xap.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. """Interactions with compatible XAP devices
  2. """
  3. import cmd
  4. from milc import cli
  5. from qmk.keycodes import load_spec
  6. from qmk.decorators import lru_cache
  7. from qmk.keyboard import render_layout
  8. from xap_client import XAPClient, XAPEventType, XAPSecureStatus, XAPConfigRgblight, XAPConfigBacklight, XAPConfigRgbMatrix, XAPRoutes
  9. def print_dotted_output(kb_info_json, prefix=''):
  10. """Print the info.json in a plain text format with dot-joined keys.
  11. """
  12. for key in sorted(kb_info_json):
  13. new_prefix = f'{prefix}.{key}' if prefix else key
  14. if key in ['parse_errors', 'parse_warnings']:
  15. continue
  16. elif key == 'layouts' and prefix == '':
  17. cli.echo(' {fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  18. elif isinstance(kb_info_json[key], bytes):
  19. conv = "".join(["{:02X}".format(b) for b in kb_info_json[key]])
  20. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, conv)
  21. elif isinstance(kb_info_json[key], dict):
  22. print_dotted_output(kb_info_json[key], new_prefix)
  23. elif isinstance(kb_info_json[key], list):
  24. data = kb_info_json[key]
  25. if len(data) and isinstance(data[0], dict):
  26. for index, item in enumerate(data, start=0):
  27. cli.echo(' {fg_blue}%s.%s{fg_reset}: %s', new_prefix, index, str(item))
  28. else:
  29. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(map(str, data)))
  30. else:
  31. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  32. @lru_cache(timeout=5)
  33. def _load_keycodes(keycode_version):
  34. """Gets keycode data for the required version of the XAP definitions.
  35. """
  36. spec = load_spec(keycode_version)
  37. # Transform into something more usable - { raw_value : first alias || keycode }
  38. return {int(k, 16): v.get('aliases', [v.get('key')])[0] for k, v in spec['keycodes'].items()}
  39. def _list_devices():
  40. """Dump out available devices
  41. """
  42. cli.log.info('Available devices:')
  43. for dev in XAPClient.devices():
  44. device = XAPClient().connect(dev)
  45. ver = device.version()
  46. cli.log.info(' %04x:%04x %s %s [API:%s]', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], ver['xap'])
  47. if cli.args.verbose:
  48. data = device.info()
  49. # TODO: better formatting like 'lsusb -v'?
  50. print_dotted_output(data)
  51. class XAPShell(cmd.Cmd):
  52. intro = 'Welcome to the XAP shell. Type help or ? to list commands.\n'
  53. prompt = 'Ψ> '
  54. def __init__(self, device):
  55. cmd.Cmd.__init__(self)
  56. self.device = device
  57. # cache keycodes for this device
  58. self.keycodes = _load_keycodes(device.version().get('keycodes', 'latest'))
  59. def do_about(self, arg):
  60. """Prints out the version info of QMK
  61. """
  62. data = self.device.version()
  63. print_dotted_output(data)
  64. def do_status(self, arg):
  65. """Prints out the current device state
  66. """
  67. status = self.device.status()
  68. print('Secure:%s' % status.get('lock', '???'))
  69. def do_unlock(self, arg):
  70. """Initiate secure unlock
  71. """
  72. self.device.unlock()
  73. print('Unlock Requested...')
  74. def do_lock(self, arg):
  75. """Disable secure routes
  76. """
  77. self.device.lock()
  78. def do_reset(self, arg):
  79. """Jump to bootloader if unlocked
  80. """
  81. if not self.device.reset():
  82. print("Reboot to bootloader failed")
  83. return True
  84. def do_listen(self, arg):
  85. """Log out XAP broadcast messages
  86. """
  87. try:
  88. cli.log.info('Listening for XAP broadcasts...')
  89. while 1:
  90. (event, data) = self.device.listen()
  91. if event == XAPEventType.SECURE_STATUS:
  92. secure_status = XAPSecureStatus(data[0]).name
  93. cli.log.info(' Secure[%s]', secure_status)
  94. else:
  95. cli.log.info(' Broadcast: type[%02x] data:[%s]', event, data.hex())
  96. except KeyboardInterrupt:
  97. cli.log.info('Stopping...')
  98. def do_keycode(self, arg):
  99. """Prints out the keycode value of a certain layer, row, and column
  100. """
  101. data = bytes(map(int, arg.split()))
  102. if len(data) != 3:
  103. cli.log.error('Invalid args')
  104. return
  105. keycode = self.device.transaction(b'\x04\x03', data)
  106. keycode = int.from_bytes(keycode, 'little')
  107. print(f'keycode:{self.keycodes.get(keycode, "unknown")}[{keycode}]')
  108. def do_keymap(self, arg):
  109. """Prints out the keycode values of a certain layer
  110. """
  111. data = bytes(map(int, arg.split()))
  112. if len(data) != 1:
  113. cli.log.error('Invalid args')
  114. return
  115. info = self.device.info()
  116. rows = info['matrix_size']['rows']
  117. cols = info['matrix_size']['cols']
  118. for r in range(rows):
  119. for c in range(cols):
  120. q = data + r.to_bytes(1, byteorder='little') + c.to_bytes(1, byteorder='little')
  121. keycode = self.device.transaction(b'\x04\x03', q)
  122. keycode = int.from_bytes(keycode, 'little')
  123. print(f'| {self.keycodes.get(keycode, "unknown").ljust(7)} ', end='', flush=True)
  124. print('|')
  125. def do_layer(self, arg):
  126. """Renders keycode values of a certain layer
  127. """
  128. data = bytes(map(int, arg.split()))
  129. if len(data) != 1:
  130. cli.log.error('Invalid args')
  131. return
  132. info = self.device.info()
  133. # Assumptions on selected layout rather than prompt
  134. first_layout = next(iter(info['layouts']))
  135. layout = info['layouts'][first_layout]['layout']
  136. keycodes = []
  137. for item in layout:
  138. q = data + bytes(item['matrix'])
  139. keycode = self.device.transaction(b'\x04\x03', q)
  140. keycode = int.from_bytes(keycode, 'little')
  141. keycodes.append(self.keycodes.get(keycode, '???'))
  142. print(render_layout(layout, False, keycodes))
  143. def do_exit(self, line):
  144. """Quit shell
  145. """
  146. return True
  147. def do_EOF(self, line): # noqa: N802
  148. """Quit shell (ctrl+D)
  149. """
  150. return True
  151. def loop(self):
  152. """Wrapper for cmdloop that handles ctrl+C
  153. """
  154. try:
  155. self.cmdloop()
  156. print('')
  157. except KeyboardInterrupt:
  158. print('^C')
  159. return False
  160. def do_dump(self, line):
  161. caps = self.device.int_transaction(XAPRoutes.LIGHTING_CAPABILITIES_QUERY)
  162. if caps & (1 << XAPRoutes.LIGHTING_BACKLIGHT[-1]):
  163. ret = self.device.transaction(XAPRoutes.LIGHTING_BACKLIGHT_GET_CONFIG)
  164. ret = XAPConfigBacklight.from_bytes(ret)
  165. print(ret)
  166. ret = self.device.int_transaction(XAPRoutes.LIGHTING_BACKLIGHT_GET_ENABLED_EFFECTS)
  167. print(f'XAPEffectBacklight(enabled={bin(ret)})')
  168. if caps & (1 << XAPRoutes.LIGHTING_RGBLIGHT[-1]):
  169. ret = self.device.transaction(XAPRoutes.LIGHTING_RGBLIGHT_GET_CONFIG)
  170. ret = XAPConfigRgblight.from_bytes(ret)
  171. print(ret)
  172. ret = self.device.int_transaction(XAPRoutes.LIGHTING_RGBLIGHT_GET_ENABLED_EFFECTS)
  173. print(f'XAPEffectRgblight(enabled={bin(ret)})')
  174. if caps & (1 << XAPRoutes.LIGHTING_RGB_MATRIX[-1]):
  175. ret = self.device.transaction(XAPRoutes.LIGHTING_RGB_MATRIX_GET_CONFIG)
  176. ret = XAPConfigRgbMatrix.from_bytes(ret)
  177. print(ret)
  178. ret = self.device.int_transaction(XAPRoutes.LIGHTING_RGB_MATRIX_GET_ENABLED_EFFECTS)
  179. print(f'XAPEffectRgbMatrix(enabled={bin(ret)})')
  180. @cli.argument('-v', '--verbose', arg_only=True, action='store_true', help='Turns on verbose output.')
  181. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  182. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  183. @cli.argument('-i', '--interactive', arg_only=True, action='store_true', help='Start interactive shell.')
  184. @cli.argument('action', nargs='*', arg_only=True, default=['listen'], help='Shell command and any arguments to run standalone')
  185. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  186. def xap(cli):
  187. """Acquire debugging information from XAP devices
  188. """
  189. if cli.args.list:
  190. return _list_devices()
  191. # Connect to first available device
  192. devices = XAPClient.devices()
  193. if not devices:
  194. cli.log.error('No devices found!')
  195. return False
  196. dev = devices[0]
  197. cli.log.info('Connecting to: %04x:%04x %s %s', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
  198. device = XAPClient().connect(dev)
  199. # shell?
  200. if cli.args.interactive:
  201. XAPShell(device).loop()
  202. return True
  203. XAPShell(device).onecmd(' '.join(cli.args.action))