flashers.py 7.7 KB

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