YModem.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. #! /usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import os
  4. import sys
  5. import time
  6. import math
  7. import string
  8. import logging
  9. logging.basicConfig(level = logging.INFO, format = '%(asctime)s - %(levelname)s - %(message)s')
  10. from YMTask import SendTask, ReceiveTask
  11. # ymodem data header byte
  12. SOH = b'\x01'
  13. STX = b'\x02'
  14. EOT = b'\x04'
  15. ACK = b'\x06'
  16. NAK = b'\x15'
  17. CAN = b'\x18'
  18. CRC = b'C'
  19. class YModem(object):
  20. def __init__(self, getc, putc, header_pad=b'\x00', data_pad=b'\x1a'):
  21. self.getc = getc
  22. self.putc = putc
  23. self.st = SendTask()
  24. self.rt = ReceiveTask()
  25. self.header_pad = header_pad
  26. self.data_pad = data_pad
  27. self.log = logging.getLogger('YReporter')
  28. def abort(self, count=2):
  29. for _ in range(count):
  30. self.putc(CAN)
  31. def send_file(self, file_path, retry=20, callback=None):
  32. try:
  33. file_stream = open(file_path, 'rb')
  34. file_name = os.path.basename(file_path)
  35. file_size = os.path.getsize(file_path)
  36. print(file_name, file_size)
  37. file_sent = self.send(file_stream, file_name, file_size, retry, callback)
  38. except IOError as e:
  39. self.log.error(str(e))
  40. finally:
  41. file_stream.close()
  42. self.log.debug("Task Done!")
  43. self.log.debug("File: " + file_name)
  44. self.log.debug("Size: " + str(file_sent) + "Bytes")
  45. self.log.debug("Packets: " + str(self.st.get_valid_sent_packets()))
  46. return file_sent
  47. def wait_for_next(self, ch):
  48. cancel_count = 0
  49. while True:
  50. c = self.getc(1)
  51. if c:
  52. if c == ch:
  53. self.log.debug("<<< " + hex(ord(ch)))
  54. break
  55. elif c == CAN:
  56. if cancel_count == 2:
  57. return -1
  58. else:
  59. cancel_count += 1
  60. else:
  61. pass#self.log.warn("Expected " + hex(ord(ch)) + ", but got " + hex(ord(c)))
  62. return 0
  63. def send(self, data_stream, data_name, data_size, retry=20, callback=None):
  64. packet_size = 1024
  65. # [<<< CRC]
  66. self.wait_for_next(CRC)
  67. # [first packet >>>]
  68. header = self._make_edge_packet_header()
  69. if len(data_name) > 100:
  70. data_name = data_name[:100]
  71. self.st.set_task_name(data_name)
  72. data_name += bytes.decode(self.header_pad)
  73. data_size = str(data_size)
  74. if len(data_size) > 20:
  75. raise Exception("Data volume is too large!")
  76. self.st.set_task_size(int(data_size))
  77. data_size += bytes.decode(self.header_pad)
  78. data = data_name + data_size
  79. data = data.ljust(128, bytes.decode(self.header_pad))
  80. checksum = self._make_send_checksum(data)
  81. data_for_send = header + data.encode() + checksum
  82. self.putc(data_for_send)
  83. self.st.inc_sent_packets()
  84. # data_in_hexstring = "".join("%02x" % b for b in data_for_send)
  85. self.log.debug("Packet 0 >>>")
  86. # [<<< ACK]
  87. # [<<< CRC]
  88. self.wait_for_next(ACK)
  89. self.wait_for_next(CRC)
  90. # [data packet >>>]
  91. # [<<< ACK]
  92. error_count = 0
  93. sequence = 1
  94. while True:
  95. data = data_stream.read(packet_size)
  96. if not data:
  97. self.log.debug('EOF')
  98. break
  99. extracted_data_bytes = len(data)
  100. if extracted_data_bytes <= 128:
  101. packet_size = 128
  102. header = self._make_data_packet_header(packet_size, sequence)
  103. data = data.ljust(packet_size, self.data_pad)
  104. checksum = self._make_send_checksum(data)
  105. data_for_send = header + data + checksum
  106. # data_in_hexstring = "".join("%02x" % b for b in data_for_send)
  107. while True:
  108. self.putc(data_for_send)
  109. self.st.inc_sent_packets()
  110. self.log.debug("Packet " + str(sequence) + " >>>")
  111. c = self.getc(1)
  112. if c == ACK:
  113. self.log.debug("<<< ACK")
  114. self.st.inc_valid_sent_packets()
  115. self.st.add_valid_sent_bytes(extracted_data_bytes)
  116. error_count = 0
  117. break
  118. else:
  119. error_count += 1
  120. self.st.inc_missing_sent_packets()
  121. self.log.debug("RETRY " + str(error_count))
  122. if error_count > retry:
  123. self.abort()
  124. self.log.error('send error: NAK received %d , aborting', retry)
  125. return -2
  126. sequence = (sequence + 1) % 0x100
  127. # [EOT >>>]
  128. # [<<< NAK]
  129. # [EOT >>>]
  130. # [<<< ACK]
  131. self.putc(EOT)
  132. self.log.debug(">>> EOT")
  133. self.wait_for_next(NAK)
  134. self.putc(EOT)
  135. self.log.debug(">>> EOT")
  136. self.wait_for_next(ACK)
  137. # [<<< CRC]
  138. self.wait_for_next(CRC)
  139. # [Final packet >>>]
  140. header = self._make_edge_packet_header()
  141. data = "".ljust(128, bytes.decode(self.header_pad))
  142. checksum = self._make_send_checksum(data)
  143. data_for_send = header + data.encode() + checksum
  144. self.putc(data_for_send)
  145. self.st.inc_sent_packets()
  146. self.log.debug("Packet End >>>")
  147. self.wait_for_next(ACK)
  148. return self.st.get_valid_sent_bytes()
  149. def wait_for_header(self):
  150. cancel_count = 0
  151. while True:
  152. c = self.getc(1)
  153. if c:
  154. if c == SOH or c == STX:
  155. return c
  156. elif c == CAN:
  157. if cancel_count == 2:
  158. return -1
  159. else:
  160. cancel_count += 1
  161. else:
  162. self.log.warn("Expected 0x01(SOH)/0x02(STX)/0x18(CAN), but got " + hex(ord(c)))
  163. def wait_for_eot(self):
  164. eot_count = 0
  165. while True:
  166. c = self.getc(1)
  167. if c:
  168. if c == EOT:
  169. eot_count += 1
  170. if eot_count == 1:
  171. self.log.debug("EOT >>>")
  172. self.putc(NAK)
  173. self.log.debug("<<< NAK")
  174. elif eot_count == 2:
  175. self.log.debug("EOT >>>")
  176. self.putc(ACK)
  177. self.log.debug("<<< ACK")
  178. self.putc(CRC)
  179. self.log.debug("<<< CRC")
  180. break
  181. else:
  182. self.log.warn("Expected 0x04(EOT), but got " + hex(ord(c)))
  183. def recv_file(self, root_path, callback=None):
  184. while True:
  185. self.putc(CRC)
  186. self.log.debug("<<< CRC")
  187. c = self.getc(1)
  188. if c:
  189. if c == SOH:
  190. packet_size = 128
  191. break
  192. elif c == STX:
  193. packet_size = 1024
  194. break
  195. else:
  196. self.log.warn("Expected 0x01(SOH)/0x02(STX)/0x18(CAN), but got " + hex(ord(c)))
  197. IS_FIRST_PACKET = True
  198. FIRST_PACKET_RECEIVED = False
  199. WAIT_FOR_EOT = False
  200. WAIT_FOR_END_PACKET = False
  201. sequence = 0
  202. while True:
  203. if WAIT_FOR_EOT:
  204. self.wait_for_eot()
  205. WAIT_FOR_EOT = False
  206. WAIT_FOR_END_PACKET = True
  207. sequence = 0
  208. else:
  209. if IS_FIRST_PACKET:
  210. IS_FIRST_PACKET = False
  211. else:
  212. c = self.wait_for_header()
  213. if c == SOH:
  214. packet_size = 128
  215. elif c == STX:
  216. packet_size = 1024
  217. else:
  218. return c
  219. seq = self.getc(1)
  220. if seq is None:
  221. seq_oc = None
  222. else:
  223. seq = ord(seq)
  224. c = self.getc(1)
  225. if c is not None:
  226. seq_oc = 0xFF - ord(c)
  227. data = self.getc(packet_size + 2)
  228. if not (seq == seq_oc == sequence):
  229. continue
  230. else:
  231. valid, _ = self._verify_recv_checksum(data)
  232. if valid:
  233. # first packet
  234. # [<<< ACK]
  235. # [<<< CRC]
  236. if seq == 0 and not FIRST_PACKET_RECEIVED and not WAIT_FOR_END_PACKET:
  237. self.log.debug("Packet 0 >>>")
  238. self.putc(ACK)
  239. self.log.debug("<<< ACK")
  240. self.putc(CRC)
  241. self.log.debug("<<< CRC")
  242. file_name_bytes, data_size_bytes = (data[:-2]).rstrip(self.header_pad).split(self.header_pad)
  243. file_name = bytes.decode(file_name_bytes)
  244. data_size = bytes.decode(data_size_bytes)
  245. self.log.debug("TASK: " + file_name + " " + data_size + "Bytes")
  246. self.rt.set_task_name(file_name)
  247. self.rt.set_task_size(int(data_size))
  248. file_stream = open(os.path.join(root_path, file_name), 'wb+')
  249. FIRST_PACKET_RECEIVED = True
  250. sequence = (sequence + 1) % 0x100
  251. # data packet
  252. # [data packet >>>]
  253. # [<<< ACK]
  254. elif not WAIT_FOR_END_PACKET:
  255. self.rt.inc_valid_received_packets()
  256. self.log.debug("Packet " + str(sequence) + " >>>")
  257. valid_data = data[:-2]
  258. # last data packet
  259. if self.rt.get_valid_received_packets() == self.rt.get_task_packets():
  260. valid_data = valid_data[:self.rt.get_last_valid_packet_size()]
  261. WAIT_FOR_EOT = True
  262. self.rt.add_valid_received_bytes(len(valid_data))
  263. file_stream.write(valid_data)
  264. self.putc(ACK)
  265. self.log.debug("<<< ACK")
  266. sequence = (sequence + 1) % 0x100
  267. # final packet
  268. # [<<< ACK]
  269. else:
  270. self.log.debug("Packet End >>>")
  271. self.putc(ACK)
  272. self.log.debug("<<< ACK")
  273. break
  274. file_stream.close()
  275. self.log.debug("Task Done!")
  276. self.log.debug("File: " + self.rt.get_task_name())
  277. self.log.debug("Size: " + str(self.rt.get_task_size()) + "Bytes")
  278. self.log.debug("Packets: " + str(self.rt.get_valid_received_packets()))
  279. return self.rt.get_valid_received_bytes()
  280. # Header byte
  281. def _make_edge_packet_header(self):
  282. _bytes = [ord(SOH), 0, 0xff]
  283. return bytearray(_bytes)
  284. def _make_data_packet_header(self, packet_size, sequence):
  285. assert packet_size in (128, 1024), packet_size
  286. _bytes = []
  287. if packet_size == 128:
  288. _bytes.append(ord(SOH))
  289. elif packet_size == 1024:
  290. _bytes.append(ord(STX))
  291. _bytes.extend([sequence, 0xff - sequence])
  292. return bytearray(_bytes)
  293. # Make check code
  294. def _make_send_checksum(self, data):
  295. _bytes = []
  296. crc = self.calc_crc(data)
  297. _bytes.extend([crc >> 8, crc & 0xff])
  298. return bytearray(_bytes)
  299. def _verify_recv_checksum(self, data):
  300. _checksum = bytearray(data[-2:])
  301. their_sum = (_checksum[0] << 8) + _checksum[1]
  302. data = data[:-2]
  303. our_sum = self.calc_crc(data)
  304. valid = bool(their_sum == our_sum)
  305. return valid, data
  306. # For CRC algorithm
  307. crctable = [
  308. 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
  309. 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
  310. 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
  311. 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
  312. 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
  313. 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
  314. 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
  315. 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
  316. 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
  317. 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
  318. 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
  319. 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
  320. 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
  321. 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
  322. 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
  323. 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
  324. 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
  325. 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
  326. 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
  327. 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
  328. 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
  329. 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
  330. 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
  331. 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
  332. 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
  333. 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
  334. 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
  335. 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
  336. 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
  337. 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
  338. 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
  339. 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
  340. ]
  341. # CRC algorithm: CCITT-0
  342. def calc_crc(self, data, crc=0):
  343. if isinstance(data, str):
  344. ba = bytearray(data, 'utf-8')
  345. else:
  346. ba = bytearray(data)
  347. for char in ba:
  348. crctbl_idx = ((crc >> 8) ^ char) & 0xff
  349. crc = ((crc << 8) ^ self.crctable[crctbl_idx]) & 0xffff
  350. return crc & 0xffff
  351. if __name__ == '__main__':
  352. pass