xap.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  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. ret = {int(k, 16): v.get('aliases', [v.get('key')])[0] for k, v in spec['keycodes'].items()}
  39. # TODO: handle non static keycodes
  40. for k, v in spec['ranges'].items():
  41. lo, mask = map(lambda x: int(x, 16), k.split('/'))
  42. hi = lo + mask
  43. define = v.get("define")
  44. for i in range(lo, hi):
  45. if i not in ret:
  46. if define == 'QK_TO':
  47. layer = i & 0x1F
  48. ret[i] = f'TO({layer})'
  49. elif define == 'QK_MOMENTARY':
  50. layer = i & 0x1F
  51. ret[i] = f'MO({layer})'
  52. elif define == 'QK_LAYER_TAP':
  53. layer = (((i) >> 8) & 0xF)
  54. keycode = ((i) & 0xFF)
  55. ret[i] = f'LT({layer}, {ret.get(keycode, "???")})'
  56. return ret
  57. def _list_devices():
  58. """Dump out available devices
  59. """
  60. cli.log.info('Available devices:')
  61. for dev in XAPClient.devices():
  62. device = XAPClient().connect(dev)
  63. ver = device.version()
  64. cli.log.info(' %04x:%04x %s %s [API:%s]', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], ver['xap'])
  65. if cli.args.verbose:
  66. data = device.info()
  67. # TODO: better formatting like 'lsusb -v'?
  68. print_dotted_output(data)
  69. class XAPShell(cmd.Cmd):
  70. intro = 'Welcome to the XAP shell. Type help or ? to list commands.\n'
  71. prompt = 'Ψ> '
  72. def __init__(self, device):
  73. cmd.Cmd.__init__(self)
  74. self.device = device
  75. # cache keycodes for this device
  76. self.keycodes = _load_keycodes(device.version().get('keycodes', 'latest'))
  77. # TODO: dummy code is only to PoC kb/user keycodes
  78. kb_keycodes = self.device.info().get('keycodes', [])
  79. for index, item in enumerate(kb_keycodes):
  80. self.keycodes[0x7E00 + index] = item['key']
  81. user_keycodes = self.device.info().get('user_keycodes', [])
  82. for index, item in enumerate(user_keycodes):
  83. self.keycodes[0x7E40 + index] = item['key']
  84. def do_about(self, arg):
  85. """Prints out the version info of QMK
  86. """
  87. data = self.device.version()
  88. print_dotted_output(data)
  89. def do_status(self, arg):
  90. """Prints out the current device state
  91. """
  92. status = self.device.status()
  93. print('Secure:%s' % status.get('lock', '???'))
  94. def do_unlock(self, arg):
  95. """Initiate secure unlock
  96. """
  97. self.device.unlock()
  98. print('Unlock Requested...')
  99. def do_lock(self, arg):
  100. """Disable secure routes
  101. """
  102. self.device.lock()
  103. def do_reset(self, arg):
  104. """Jump to bootloader if unlocked
  105. """
  106. if not self.device.reset():
  107. print("Reboot to bootloader failed")
  108. return True
  109. def do_listen(self, arg):
  110. """Log out XAP broadcast messages
  111. """
  112. try:
  113. cli.log.info('Listening for XAP broadcasts...')
  114. while 1:
  115. (event, data) = self.device.listen()
  116. if event == XAPEventType.SECURE_STATUS:
  117. secure_status = XAPSecureStatus(data[0]).name
  118. cli.log.info(' Secure[%s]', secure_status)
  119. else:
  120. cli.log.info(' Broadcast: type[%02x] data:[%s]', event, data.hex())
  121. except KeyboardInterrupt:
  122. cli.log.info('Stopping...')
  123. def do_keycode(self, arg):
  124. """Prints out the keycode value of a certain layer, row, and column
  125. """
  126. data = bytes(map(int, arg.split()))
  127. if len(data) != 3:
  128. cli.log.error('Invalid args')
  129. return
  130. keycode = self.device.transaction(b'\x04\x03', data)
  131. keycode = int.from_bytes(keycode, 'little')
  132. print(f'keycode:{self.keycodes.get(keycode, "unknown")}[{keycode}]')
  133. def do_keymap(self, arg):
  134. """Prints out the keycode values of a certain layer
  135. """
  136. data = bytes(map(int, arg.split()))
  137. if len(data) != 1:
  138. cli.log.error('Invalid args')
  139. return
  140. info = self.device.info()
  141. rows = info['matrix_size']['rows']
  142. cols = info['matrix_size']['cols']
  143. for r in range(rows):
  144. for c in range(cols):
  145. q = data + r.to_bytes(1, byteorder='little') + c.to_bytes(1, byteorder='little')
  146. keycode = self.device.transaction(b'\x04\x03', q)
  147. keycode = int.from_bytes(keycode, 'little')
  148. print(f'| {self.keycodes.get(keycode, "unknown").ljust(7)} ', end='', flush=True)
  149. print('|')
  150. def do_layer(self, arg):
  151. """Renders keycode values of a certain layer
  152. """
  153. data = bytes(map(int, arg.split()))
  154. if len(data) != 1:
  155. cli.log.error('Invalid args')
  156. return
  157. info = self.device.info()
  158. # Assumptions on selected layout rather than prompt
  159. first_layout = next(iter(info['layouts']))
  160. layout = info['layouts'][first_layout]['layout']
  161. keycodes = []
  162. for item in layout:
  163. q = data + bytes(item['matrix'])
  164. keycode = self.device.transaction(b'\x04\x03', q)
  165. keycode = int.from_bytes(keycode, 'little')
  166. keycodes.append(self.keycodes.get(keycode, '???'))
  167. print(render_layout(layout, False, keycodes))
  168. def do_exit(self, line):
  169. """Quit shell
  170. """
  171. return True
  172. def do_EOF(self, line): # noqa: N802
  173. """Quit shell (ctrl+D)
  174. """
  175. return True
  176. def loop(self):
  177. """Wrapper for cmdloop that handles ctrl+C
  178. """
  179. try:
  180. self.cmdloop()
  181. print('')
  182. except KeyboardInterrupt:
  183. print('^C')
  184. return False
  185. def do_dump(self, line):
  186. caps = self.device.int_transaction(XAPRoutes.LIGHTING_CAPABILITIES_QUERY)
  187. if caps & (1 << XAPRoutes.LIGHTING_BACKLIGHT[-1]):
  188. ret = self.device.transaction(XAPRoutes.LIGHTING_BACKLIGHT_GET_CONFIG)
  189. ret = XAPConfigBacklight.from_bytes(ret)
  190. print(ret)
  191. ret = self.device.int_transaction(XAPRoutes.LIGHTING_BACKLIGHT_GET_ENABLED_EFFECTS)
  192. print(f'XAPEffectBacklight(enabled={bin(ret)})')
  193. if caps & (1 << XAPRoutes.LIGHTING_RGBLIGHT[-1]):
  194. ret = self.device.transaction(XAPRoutes.LIGHTING_RGBLIGHT_GET_CONFIG)
  195. ret = XAPConfigRgblight.from_bytes(ret)
  196. print(ret)
  197. ret = self.device.int_transaction(XAPRoutes.LIGHTING_RGBLIGHT_GET_ENABLED_EFFECTS)
  198. print(f'XAPEffectRgblight(enabled={bin(ret)})')
  199. if caps & (1 << XAPRoutes.LIGHTING_RGB_MATRIX[-1]):
  200. ret = self.device.transaction(XAPRoutes.LIGHTING_RGB_MATRIX_GET_CONFIG)
  201. ret = XAPConfigRgbMatrix.from_bytes(ret)
  202. print(ret)
  203. ret = self.device.int_transaction(XAPRoutes.LIGHTING_RGB_MATRIX_GET_ENABLED_EFFECTS)
  204. print(f'XAPEffectRgbMatrix(enabled={bin(ret)})')
  205. @cli.argument('-v', '--verbose', arg_only=True, action='store_true', help='Turns on verbose output.')
  206. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  207. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  208. @cli.argument('-i', '--interactive', arg_only=True, action='store_true', help='Start interactive shell.')
  209. @cli.argument('action', nargs='*', arg_only=True, default=['listen'], help='Shell command and any arguments to run standalone')
  210. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  211. def xap(cli):
  212. """Acquire debugging information from XAP devices
  213. """
  214. if cli.args.list:
  215. return _list_devices()
  216. # Connect to first available device
  217. devices = XAPClient.devices()
  218. if not devices:
  219. cli.log.error('No devices found!')
  220. return False
  221. dev = devices[0]
  222. cli.log.info('Connecting to: %04x:%04x %s %s', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
  223. device = XAPClient().connect(dev)
  224. # shell?
  225. if cli.args.interactive:
  226. XAPShell(device).loop()
  227. return True
  228. XAPShell(device).onecmd(' '.join(cli.args.action))