flashers.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. import platform
  2. import shutil
  3. import time
  4. import os
  5. import signal
  6. import usb.core
  7. from qmk.constants import BOOTLOADER_VIDS_PIDS
  8. from milc import cli
  9. _PID_TO_MCU = {
  10. '2fef': 'atmega16u2',
  11. '2ff0': 'atmega32u2',
  12. '2ff3': 'atmega16u4',
  13. '2ff4': 'atmega32u4',
  14. '2ff9': 'at90usb64',
  15. '2ffa': 'at90usb162',
  16. '2ffb': 'at90usb128',
  17. }
  18. AVRDUDE_MCU = {
  19. 'atmega32a': 'm32',
  20. 'atmega328p': 'm328p',
  21. 'atmega328': 'm328',
  22. }
  23. class DelayedKeyboardInterrupt:
  24. # Custom interrupt handler to delay the processing of Ctrl-C
  25. # https://stackoverflow.com/a/21919644
  26. def __enter__(self):
  27. self.signal_received = False
  28. self.old_handler = signal.signal(signal.SIGINT, self.handler)
  29. def handler(self, sig, frame):
  30. self.signal_received = (sig, frame)
  31. def __exit__(self, type, value, traceback):
  32. signal.signal(signal.SIGINT, self.old_handler)
  33. if self.signal_received:
  34. self.old_handler(*self.signal_received)
  35. # TODO: Make this more generic, so cli/doctor/check.py and flashers.py can share the code
  36. def _check_dfu_programmer_version():
  37. # Return True if version is higher than 0.7.0: supports '--force'
  38. check = cli.run(['dfu-programmer', '--version'], combined_output=True, timeout=5)
  39. first_line = check.stdout.split('\n')[0]
  40. version_number = first_line.split()[1]
  41. maj, min_, bug = version_number.split('.')
  42. if int(maj) >= 0 and int(min_) >= 7:
  43. return True
  44. else:
  45. return False
  46. def _find_usb_device(vid_hex, pid_hex):
  47. # WSL doesnt have access to USB - use powershell instead...?
  48. if 'microsoft' in platform.uname().release.lower():
  49. ret = cli.run(['powershell.exe', '-command', 'Get-PnpDevice -PresentOnly | Select-Object -Property InstanceId'])
  50. if f'USB\\VID_{vid_hex:04X}&PID_{pid_hex:04X}' in ret.stdout:
  51. return (vid_hex, pid_hex)
  52. else:
  53. with DelayedKeyboardInterrupt():
  54. # PyUSB does not like to be interrupted by Ctrl-C
  55. # therefore we catch the interrupt with a custom handler
  56. # and only process it once pyusb finished
  57. return usb.core.find(idVendor=vid_hex, idProduct=pid_hex)
  58. def _find_uf2_devices():
  59. """Delegate to uf2conv.py as VID:PID pairs can potentially fluctuate more than other bootloaders
  60. """
  61. return cli.run(['util/uf2conv.py', '--list']).stdout.splitlines()
  62. def _find_bootloader():
  63. # To avoid running forever in the background, only look for bootloaders for 10min
  64. start_time = time.time()
  65. while time.time() - start_time < 600:
  66. for bl in BOOTLOADER_VIDS_PIDS:
  67. for vid, pid in BOOTLOADER_VIDS_PIDS[bl]:
  68. vid_hex = int(f'0x{vid}', 0)
  69. pid_hex = int(f'0x{pid}', 0)
  70. dev = _find_usb_device(vid_hex, pid_hex)
  71. if dev:
  72. if bl == 'atmel-dfu':
  73. details = _PID_TO_MCU[pid]
  74. elif bl == 'caterina':
  75. details = (vid_hex, pid_hex)
  76. elif bl == 'hid-bootloader':
  77. if vid == '16c0' and pid == '0478':
  78. details = 'halfkay'
  79. else:
  80. details = 'qmk-hid'
  81. elif bl in {'apm32-dfu', 'at32-dfu', 'gd32v-dfu', 'kiibohd', 'stm32-dfu'}:
  82. details = (vid, pid)
  83. else:
  84. details = None
  85. return (bl, details)
  86. if _find_uf2_devices():
  87. return ('_uf2_compatible_', None)
  88. time.sleep(0.1)
  89. return (None, None)
  90. def _find_serial_port(vid, pid):
  91. if 'windows' in cli.platform.lower():
  92. from serial.tools.list_ports_windows import comports
  93. platform = 'windows'
  94. else:
  95. from serial.tools.list_ports_posix import comports
  96. platform = 'posix'
  97. start_time = time.time()
  98. # Caterina times out after 8 seconds
  99. while time.time() - start_time < 8:
  100. for port in comports():
  101. port, desc, hwid = port
  102. if f'{vid:04x}:{pid:04x}' in hwid.casefold():
  103. if platform == 'windows':
  104. time.sleep(1)
  105. return port
  106. else:
  107. start_time = time.time()
  108. # Wait until the port becomes writable before returning
  109. while time.time() - start_time < 8:
  110. if os.access(port, os.W_OK):
  111. return port
  112. else:
  113. time.sleep(0.5)
  114. return None
  115. return None
  116. def _flash_bootloadhid(file):
  117. cli.run(['bootloadHID', '-r', file], capture_output=False)
  118. def _flash_caterina(details, file):
  119. port = _find_serial_port(details[0], details[1])
  120. if port:
  121. cli.run(['avrdude', '-p', 'atmega32u4', '-c', 'avr109', '-U', f'flash:w:{file}:i', '-P', port], capture_output=False)
  122. return False
  123. else:
  124. return True
  125. def _flash_atmel_dfu(mcu, file):
  126. force = '--force' if _check_dfu_programmer_version() else ''
  127. cli.run(['dfu-programmer', mcu, 'erase', force], capture_output=False)
  128. cli.run(['dfu-programmer', mcu, 'flash', force, file], capture_output=False)
  129. cli.run(['dfu-programmer', mcu, 'reset'], capture_output=False)
  130. def _flash_hid_bootloader(mcu, details, file):
  131. cmd = None
  132. if details == 'halfkay':
  133. if shutil.which('teensy_loader_cli'):
  134. cmd = 'teensy_loader_cli'
  135. elif shutil.which('teensy-loader-cli'):
  136. cmd = 'teensy-loader-cli'
  137. # Use 'hid_bootloader_cli' for QMK HID and as a fallback for HalfKay
  138. if not cmd:
  139. if shutil.which('hid_bootloader_cli'):
  140. cmd = 'hid_bootloader_cli'
  141. else:
  142. return True
  143. cli.run([cmd, f'-mmcu={mcu}', '-w', '-v', file], capture_output=False)
  144. def _flash_dfu_util(details, file):
  145. # STM32duino
  146. if details[0] == '1eaf' and details[1] == '0003':
  147. cli.run(['dfu-util', '-a', '2', '-d', f'{details[0]}:{details[1]}', '-R', '-D', file], capture_output=False)
  148. # kiibohd
  149. elif details[0] == '1c11' and details[1] == 'b007':
  150. cli.run(['dfu-util', '-a', '0', '-d', f'{details[0]}:{details[1]}', '-D', file], capture_output=False)
  151. # STM32, APM32, AT32, or GD32V DFU
  152. else:
  153. cli.run(['dfu-util', '-a', '0', '-d', f'{details[0]}:{details[1]}', '-s', '0x08000000:leave', '-D', file], capture_output=False)
  154. def _flash_wb32_dfu_updater(file):
  155. if shutil.which('wb32-dfu-updater_cli'):
  156. cmd = 'wb32-dfu-updater_cli'
  157. else:
  158. return True
  159. cli.run([cmd, '-t', '-s', '0x08000000', '-D', file], capture_output=False)
  160. def _flash_isp(mcu, programmer, file):
  161. programmer = 'usbasp' if programmer == 'usbasploader' else 'usbtiny'
  162. # Check if the provided mcu has an avrdude-specific name, otherwise pass on what the user provided
  163. mcu = AVRDUDE_MCU.get(mcu, mcu)
  164. cli.run(['avrdude', '-p', mcu, '-c', programmer, '-U', f'flash:w:{file}:i'], capture_output=False)
  165. def _flash_mdloader(file):
  166. cli.run(['mdloader', '--first', '--download', file, '--restart'], capture_output=False)
  167. def _flash_uf2(file):
  168. output = cli.run(['util/uf2conv.py', '--info', file]).stdout
  169. if 'UF2 File' not in output:
  170. return True
  171. cli.run(['util/uf2conv.py', '--deploy', file], capture_output=False)
  172. def flasher(mcu, file):
  173. # Avoid "expected string or bytes-like object, got 'WindowsPath" issues
  174. file = file.as_posix()
  175. bl, details = _find_bootloader()
  176. # Add a small sleep to avoid race conditions
  177. time.sleep(1)
  178. if bl == 'atmel-dfu':
  179. _flash_atmel_dfu(details, file)
  180. elif bl == 'bootloadhid':
  181. _flash_bootloadhid(file)
  182. elif bl == 'caterina':
  183. if _flash_caterina(details, file):
  184. return (True, "The Caterina bootloader was found but is not writable. Check 'qmk doctor' output for advice.")
  185. elif bl == 'hid-bootloader':
  186. if mcu:
  187. if _flash_hid_bootloader(mcu, details, file):
  188. return (True, "Please make sure 'teensy_loader_cli' or 'hid_bootloader_cli' is available on your system.")
  189. else:
  190. return (True, "Specifying the MCU with '-m' is necessary for HalfKay/HID bootloaders!")
  191. elif bl in {'apm32-dfu', 'at32-dfu', 'gd32v-dfu', 'kiibohd', 'stm32-dfu'}:
  192. _flash_dfu_util(details, file)
  193. elif bl == 'wb32-dfu':
  194. if _flash_wb32_dfu_updater(file):
  195. return (True, "Please make sure 'wb32-dfu-updater_cli' is available on your system.")
  196. elif bl == 'usbasploader' or bl == 'usbtinyisp':
  197. if mcu:
  198. _flash_isp(mcu, bl, file)
  199. else:
  200. return (True, "Specifying the MCU with '-m' is necessary for ISP flashing!")
  201. elif bl == 'md-boot':
  202. _flash_mdloader(file)
  203. elif bl == '_uf2_compatible_':
  204. if _flash_uf2(file):
  205. return (True, "Flashing only supports uf2 format files.")
  206. else:
  207. return (True, "Known bootloader found but flashing not currently supported!")
  208. return (False, None)