upload.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. import argparse
  2. import sys
  3. import os
  4. import time
  5. import random
  6. import serial
  7. Import("env")
  8. import MarlinBinaryProtocol
  9. #-----------------#
  10. # Upload Callback #
  11. #-----------------#
  12. def Upload(source, target, env):
  13. #-------#
  14. # Debug #
  15. #-------#
  16. Debug = False # Set to True to enable script debug
  17. def debugPrint(data):
  18. if Debug: print(f"[Debug]: {data}")
  19. #------------------#
  20. # Marlin functions #
  21. #------------------#
  22. def _GetMarlinEnv(marlinEnv, feature):
  23. if not marlinEnv: return None
  24. return marlinEnv[feature] if feature in marlinEnv else None
  25. #----------------#
  26. # Port functions #
  27. #----------------#
  28. def _GetUploadPort(env):
  29. debugPrint('Autodetecting upload port...')
  30. env.AutodetectUploadPort(env)
  31. portName = env.subst('$UPLOAD_PORT')
  32. if not portName:
  33. raise Exception('Error detecting the upload port.')
  34. debugPrint('OK')
  35. return portName
  36. #-------------------------#
  37. # Simple serial functions #
  38. #-------------------------#
  39. def _OpenPort():
  40. # Open serial port
  41. if port.is_open: return
  42. debugPrint('Opening upload port...')
  43. port.open()
  44. port.reset_input_buffer()
  45. debugPrint('OK')
  46. def _ClosePort():
  47. # Open serial port
  48. if port is None: return
  49. if not port.is_open: return
  50. debugPrint('Closing upload port...')
  51. port.close()
  52. debugPrint('OK')
  53. def _Send(data):
  54. debugPrint(f'>> {data}')
  55. strdata = bytearray(data, 'utf8') + b'\n'
  56. port.write(strdata)
  57. time.sleep(0.010)
  58. def _Recv():
  59. clean_responses = []
  60. responses = port.readlines()
  61. for Resp in responses:
  62. # Suppress invalid chars (coming from debug info)
  63. try:
  64. clean_response = Resp.decode('utf8').rstrip().lstrip()
  65. clean_responses.append(clean_response)
  66. debugPrint(f'<< {clean_response}')
  67. except:
  68. pass
  69. return clean_responses
  70. #------------------#
  71. # SDCard functions #
  72. #------------------#
  73. def _CheckSDCard():
  74. debugPrint('Checking SD card...')
  75. _Send('M21')
  76. Responses = _Recv()
  77. if len(Responses) < 1 or not any('SD card ok' in r for r in Responses):
  78. raise Exception('Error accessing SD card')
  79. debugPrint('SD Card OK')
  80. return True
  81. #----------------#
  82. # File functions #
  83. #----------------#
  84. def _GetFirmwareFiles(UseLongFilenames):
  85. debugPrint('Get firmware files...')
  86. _Send(f"M20 F{'L' if UseLongFilenames else ''}")
  87. Responses = _Recv()
  88. if len(Responses) < 3 or not any('file list' in r for r in Responses):
  89. raise Exception('Error getting firmware files')
  90. debugPrint('OK')
  91. return Responses
  92. def _FilterFirmwareFiles(FirmwareList, UseLongFilenames):
  93. Firmwares = []
  94. for FWFile in FirmwareList:
  95. # For long filenames take the 3rd column of the firmwares list
  96. if UseLongFilenames:
  97. Space = 0
  98. Space = FWFile.find(' ')
  99. if Space >= 0: Space = FWFile.find(' ', Space + 1)
  100. if Space >= 0: FWFile = FWFile[Space + 1:]
  101. if not '/' in FWFile and '.BIN' in FWFile.upper():
  102. Firmwares.append(FWFile[:FWFile.upper().index('.BIN') + 4])
  103. return Firmwares
  104. def _RemoveFirmwareFile(FirmwareFile):
  105. _Send(f'M30 /{FirmwareFile}')
  106. Responses = _Recv()
  107. Removed = len(Responses) >= 1 and any('File deleted' in r for r in Responses)
  108. if not Removed:
  109. raise Exception(f"Firmware file '{FirmwareFile}' not removed")
  110. return Removed
  111. def _RollbackUpload(FirmwareFile):
  112. if not rollback: return
  113. print(f"Rollback: trying to delete firmware '{FirmwareFile}'...")
  114. _OpenPort()
  115. # Wait for SD card release
  116. time.sleep(1)
  117. # Remount SD card
  118. _CheckSDCard()
  119. print(' OK' if _RemoveFirmwareFile(FirmwareFile) else ' Error!')
  120. _ClosePort()
  121. #---------------------#
  122. # Callback Entrypoint #
  123. #---------------------#
  124. port = None
  125. protocol = None
  126. filetransfer = None
  127. rollback = False
  128. # Get Marlin evironment vars
  129. MarlinEnv = env['MARLIN_FEATURES']
  130. marlin_pioenv = _GetMarlinEnv(MarlinEnv, 'PIOENV')
  131. marlin_motherboard = _GetMarlinEnv(MarlinEnv, 'MOTHERBOARD')
  132. marlin_board_info_name = _GetMarlinEnv(MarlinEnv, 'BOARD_INFO_NAME')
  133. marlin_board_custom_build_flags = _GetMarlinEnv(MarlinEnv, 'BOARD_CUSTOM_BUILD_FLAGS')
  134. marlin_firmware_bin = _GetMarlinEnv(MarlinEnv, 'FIRMWARE_BIN')
  135. marlin_long_filename_host_support = _GetMarlinEnv(MarlinEnv, 'LONG_FILENAME_HOST_SUPPORT') is not None
  136. marlin_longname_write = _GetMarlinEnv(MarlinEnv, 'LONG_FILENAME_WRITE_SUPPORT') is not None
  137. marlin_custom_firmware_upload = _GetMarlinEnv(MarlinEnv, 'CUSTOM_FIRMWARE_UPLOAD') is not None
  138. marlin_short_build_version = _GetMarlinEnv(MarlinEnv, 'SHORT_BUILD_VERSION')
  139. marlin_string_config_h_author = _GetMarlinEnv(MarlinEnv, 'STRING_CONFIG_H_AUTHOR')
  140. # Get firmware upload params
  141. upload_firmware_source_name = str(source[0]) # Source firmware filename
  142. upload_speed = env['UPLOAD_SPEED'] if 'UPLOAD_SPEED' in env else 115200
  143. # baud rate of serial connection
  144. upload_port = _GetUploadPort(env) # Serial port to use
  145. # Set local upload params
  146. upload_firmware_target_name = os.path.basename(upload_firmware_source_name)
  147. # Target firmware filename
  148. upload_timeout = 1000 # Communication timout, lossy/slow connections need higher values
  149. upload_blocksize = 512 # Transfer block size. 512 = Autodetect
  150. upload_compression = True # Enable compression
  151. upload_error_ratio = 0 # Simulated corruption ratio
  152. upload_test = False # Benchmark the serial link without storing the file
  153. upload_reset = True # Trigger a soft reset for firmware update after the upload
  154. # Set local upload params based on board type to change script behavior
  155. # "upload_delete_old_bins": delete all *.bin files in the root of SD Card
  156. upload_delete_old_bins = marlin_motherboard in ['BOARD_CREALITY_V4', 'BOARD_CREALITY_V4210', 'BOARD_CREALITY_V422', 'BOARD_CREALITY_V423',
  157. 'BOARD_CREALITY_V427', 'BOARD_CREALITY_V431', 'BOARD_CREALITY_V452', 'BOARD_CREALITY_V453',
  158. 'BOARD_CREALITY_V24S1']
  159. # "upload_random_name": generate a random 8.3 firmware filename to upload
  160. upload_random_filename = upload_delete_old_bins and not marlin_long_filename_host_support
  161. # Heatshrink module is needed (only) for compression
  162. if upload_compression:
  163. if sys.version_info[0] > 2:
  164. try:
  165. import heatshrink2
  166. except ImportError:
  167. print("Installing 'heatshrink2' python module...")
  168. env.Execute(env.subst("$PYTHONEXE -m pip install heatshrink2"))
  169. else:
  170. try:
  171. import heatshrink
  172. except ImportError:
  173. print("Installing 'heatshrink' python module...")
  174. env.Execute(env.subst("$PYTHONEXE -m pip install heatshrink"))
  175. try:
  176. # Start upload job
  177. print(f"Uploading firmware '{os.path.basename(upload_firmware_target_name)}' to '{marlin_motherboard}' via '{upload_port}'")
  178. # Dump some debug info
  179. if Debug:
  180. print('Upload using:')
  181. print('---- Marlin -----------------------------------')
  182. print(f' PIOENV : {marlin_pioenv}')
  183. print(f' SHORT_BUILD_VERSION : {marlin_short_build_version}')
  184. print(f' STRING_CONFIG_H_AUTHOR : {marlin_string_config_h_author}')
  185. print(f' MOTHERBOARD : {marlin_motherboard}')
  186. print(f' BOARD_INFO_NAME : {marlin_board_info_name}')
  187. print(f' CUSTOM_BUILD_FLAGS : {marlin_board_custom_build_flags}')
  188. print(f' FIRMWARE_BIN : {marlin_firmware_bin}')
  189. print(f' LONG_FILENAME_HOST_SUPPORT : {marlin_long_filename_host_support}')
  190. print(f' LONG_FILENAME_WRITE_SUPPORT : {marlin_longname_write}')
  191. print(f' CUSTOM_FIRMWARE_UPLOAD : {marlin_custom_firmware_upload}')
  192. print('---- Upload parameters ------------------------')
  193. print(f' Source : {upload_firmware_source_name}')
  194. print(f' Target : {upload_firmware_target_name}')
  195. print(f' Port : {upload_port} @ {upload_speed} baudrate')
  196. print(f' Timeout : {upload_timeout}')
  197. print(f' Block size : {upload_blocksize}')
  198. print(f' Compression : {upload_compression}')
  199. print(f' Error ratio : {upload_error_ratio}')
  200. print(f' Test : {upload_test}')
  201. print(f' Reset : {upload_reset}')
  202. print('-----------------------------------------------')
  203. # Custom implementations based on board parameters
  204. # Generate a new 8.3 random filename
  205. if upload_random_filename:
  206. upload_firmware_target_name = f"fw-{''.join(random.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=5))}.BIN"
  207. print(f"Board {marlin_motherboard}: Overriding firmware filename to '{upload_firmware_target_name}'")
  208. # Delete all *.bin files on the root of SD Card (if flagged)
  209. if upload_delete_old_bins:
  210. # CUSTOM_FIRMWARE_UPLOAD is needed for this feature
  211. if not marlin_custom_firmware_upload:
  212. raise Exception(f"CUSTOM_FIRMWARE_UPLOAD must be enabled in 'Configuration_adv.h' for '{marlin_motherboard}'")
  213. # Init & Open serial port
  214. port = serial.Serial(upload_port, baudrate = upload_speed, write_timeout = 0, timeout = 0.1)
  215. _OpenPort()
  216. # Check SD card status
  217. _CheckSDCard()
  218. # Get firmware files
  219. FirmwareFiles = _GetFirmwareFiles(marlin_long_filename_host_support)
  220. if Debug:
  221. for FirmwareFile in FirmwareFiles:
  222. print(f'Found: {FirmwareFile}')
  223. # Get all 1st level firmware files (to remove)
  224. OldFirmwareFiles = _FilterFirmwareFiles(FirmwareFiles[1:len(FirmwareFiles)-2], marlin_long_filename_host_support) # Skip header and footers of list
  225. if len(OldFirmwareFiles) == 0:
  226. print('No old firmware files to delete')
  227. else:
  228. print(f"Remove {len(OldFirmwareFiles)} old firmware file{'s' if len(OldFirmwareFiles) != 1 else ''}:")
  229. for OldFirmwareFile in OldFirmwareFiles:
  230. print(f" -Removing- '{OldFirmwareFile}'...")
  231. print(' OK' if _RemoveFirmwareFile(OldFirmwareFile) else ' Error!')
  232. # Close serial
  233. _ClosePort()
  234. # Cleanup completed
  235. debugPrint('Cleanup completed')
  236. # WARNING! The serial port must be closed here because the serial transfer that follow needs it!
  237. # Upload firmware file
  238. debugPrint(f"Copy '{upload_firmware_source_name}' --> '{upload_firmware_target_name}'")
  239. protocol = MarlinBinaryProtocol.Protocol(upload_port, upload_speed, upload_blocksize, float(upload_error_ratio), int(upload_timeout))
  240. #echologger = MarlinBinaryProtocol.EchoProtocol(protocol)
  241. protocol.connect()
  242. # Mark the rollback (delete broken transfer) from this point on
  243. rollback = True
  244. filetransfer = MarlinBinaryProtocol.FileTransferProtocol(protocol)
  245. transferOK = filetransfer.copy(upload_firmware_source_name, upload_firmware_target_name, upload_compression, upload_test)
  246. protocol.disconnect()
  247. # Notify upload completed
  248. protocol.send_ascii('M117 Firmware uploaded' if transferOK else 'M117 Firmware upload failed')
  249. # Remount SD card
  250. print('Wait for SD card release...')
  251. time.sleep(1)
  252. print('Remount SD card')
  253. protocol.send_ascii('M21')
  254. # Transfer failed?
  255. if not transferOK:
  256. protocol.shutdown()
  257. _RollbackUpload(upload_firmware_target_name)
  258. else:
  259. # Trigger firmware update
  260. if upload_reset:
  261. print('Trigger firmware update...')
  262. protocol.send_ascii('M997', True)
  263. protocol.shutdown()
  264. print('Firmware update completed' if transferOK else 'Firmware update failed')
  265. return 0 if transferOK else -1
  266. except KeyboardInterrupt:
  267. print('Aborted by user')
  268. if filetransfer: filetransfer.abort()
  269. if protocol:
  270. protocol.disconnect()
  271. protocol.shutdown()
  272. _RollbackUpload(upload_firmware_target_name)
  273. _ClosePort()
  274. raise
  275. except serial.SerialException as se:
  276. # This exception is raised only for send_ascii data (not for binary transfer)
  277. print(f'Serial excepion: {se}, transfer aborted')
  278. if protocol:
  279. protocol.disconnect()
  280. protocol.shutdown()
  281. _RollbackUpload(upload_firmware_target_name)
  282. _ClosePort()
  283. raise Exception(se)
  284. except MarlinBinaryProtocol.FatalError:
  285. print('Too many retries, transfer aborted')
  286. if protocol:
  287. protocol.disconnect()
  288. protocol.shutdown()
  289. _RollbackUpload(upload_firmware_target_name)
  290. _ClosePort()
  291. raise
  292. except Exception as ex:
  293. print(f"\nException: {ex}, transfer aborted")
  294. if protocol:
  295. protocol.disconnect()
  296. protocol.shutdown()
  297. _RollbackUpload(upload_firmware_target_name)
  298. _ClosePort()
  299. print('Firmware not updated')
  300. raise
  301. # Attach custom upload callback
  302. env.Replace(UPLOADCMD=Upload)