My Marlin configs for Fabrikator Mini and CTC i3 Pro B
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

upload.py 12KB

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