xap.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. """Interactions with compatible XAP devices
  2. """
  3. import cmd
  4. import json
  5. import random
  6. import gzip
  7. from pathlib import Path
  8. from platform import platform
  9. from milc import cli
  10. from qmk.json_schema import json_load
  11. # TODO: get from xap "uses" for the current device
  12. keycode_version = '0.0.1'
  13. spec = json_load(Path(f'data/constants/keycodes_{keycode_version}.json'))
  14. KEYCODE_MAP = {int(k, 16): v.get('aliases', [v.get('key')])[0] for k, v in spec['keycodes'].items()}
  15. def _is_xap_usage(x):
  16. return x['usage_page'] == 0xFF51 and x['usage'] == 0x0058
  17. def _is_filtered_device(x):
  18. name = "%04x:%04x" % (x['vendor_id'], x['product_id'])
  19. return name.lower().startswith(cli.args.device.lower())
  20. def _search():
  21. devices = filter(_is_xap_usage, hid.enumerate())
  22. if cli.args.device:
  23. devices = filter(_is_filtered_device, devices)
  24. return list(devices)
  25. def print_dotted_output(kb_info_json, prefix=''):
  26. """Print the info.json in a plain text format with dot-joined keys.
  27. """
  28. for key in sorted(kb_info_json):
  29. new_prefix = f'{prefix}.{key}' if prefix else key
  30. if key in ['parse_errors', 'parse_warnings']:
  31. continue
  32. elif key == 'layouts' and prefix == '':
  33. cli.echo(' {fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
  34. elif isinstance(kb_info_json[key], bytes):
  35. conv = "".join(["{:02X}".format(b) for b in kb_info_json[key]])
  36. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, conv)
  37. elif isinstance(kb_info_json[key], dict):
  38. print_dotted_output(kb_info_json[key], new_prefix)
  39. elif isinstance(kb_info_json[key], list):
  40. data = kb_info_json[key]
  41. if len(data) and isinstance(data[0], dict):
  42. for index, item in enumerate(data, start=0):
  43. cli.echo(' {fg_blue}%s.%s{fg_reset}: %s', new_prefix, index, str(item))
  44. else:
  45. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(sorted(map(str, data))))
  46. else:
  47. cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
  48. def _xap_transaction(device, sub, route, *args):
  49. # gen token
  50. tok = random.getrandbits(16)
  51. token = tok.to_bytes(2, byteorder='little')
  52. # send with padding
  53. # TODO: this code is total garbage
  54. args_data = []
  55. args_len = 2
  56. if len(args) == 1:
  57. if isinstance(args[0], (bytes, bytearray)):
  58. args_len += len(args[0])
  59. args_data = args[0]
  60. else:
  61. args_len += 2
  62. args_data = args[0].to_bytes(2, byteorder='little')
  63. padding_len = 64 - 3 - args_len
  64. padding = b"\x00" * padding_len
  65. if args_data:
  66. padding = args_data + padding
  67. buffer = token + args_len.to_bytes(1, byteorder='little') + sub.to_bytes(1, byteorder='little') + route.to_bytes(1, byteorder='little') + padding
  68. # prepend 0 on windows because reasons...
  69. if 'windows' in platform().lower():
  70. buffer = b"\x00" + buffer
  71. device.write(buffer)
  72. # get resp
  73. array_alpha = device.read(64, 100)
  74. # validate tok sent == resp
  75. if str(token) != str(array_alpha[:2]):
  76. return None
  77. if int(array_alpha[2]) != 0x01:
  78. return None
  79. payload_len = int(array_alpha[3])
  80. return array_alpha[4:4 + payload_len]
  81. def _query_device(device):
  82. ver_data = _xap_transaction(device, 0x00, 0x00)
  83. if not ver_data:
  84. return {'xap': 'UNKNOWN', 'secure': 'UNKNOWN'}
  85. # to u32 to BCD string
  86. a = (ver_data[3] << 24) + (ver_data[2] << 16) + (ver_data[1] << 8) + (ver_data[0])
  87. ver = f'{a>>24}.{a>>16 & 0xFF}.{a & 0xFFFF}'
  88. secure = int.from_bytes(_xap_transaction(device, 0x00, 0x03), 'little')
  89. secure = 'unlocked' if secure == 2 else 'LOCKED'
  90. return {'xap': ver, 'secure': secure}
  91. def _query_device_id(device):
  92. return _xap_transaction(device, 0x01, 0x08)
  93. def _query_device_info_len(device):
  94. len_data = _xap_transaction(device, 0x01, 0x05)
  95. if not len_data:
  96. return 0
  97. # to u32
  98. return (len_data[3] << 24) + (len_data[2] << 16) + (len_data[1] << 8) + (len_data[0])
  99. def _query_device_info_chunk(device, offset):
  100. return _xap_transaction(device, 0x01, 0x06, offset)
  101. def _query_device_info(device):
  102. datalen = _query_device_info_len(device)
  103. if not datalen:
  104. return {}
  105. data = []
  106. offset = 0
  107. while offset < datalen:
  108. data += _query_device_info_chunk(device, offset)
  109. offset += 32
  110. str_data = gzip.decompress(bytearray(data[:datalen]))
  111. return json.loads(str_data)
  112. def _list_devices():
  113. """Dump out available devices
  114. """
  115. cli.log.info('Available devices:')
  116. devices = _search()
  117. for dev in devices:
  118. device = hid.Device(path=dev['path'])
  119. data = _query_device(device)
  120. cli.log.info(" %04x:%04x %s %s [API:%s] %s", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], data['xap'], data['secure'])
  121. if cli.config.general.verbose:
  122. # TODO: better formatting like "lsusb -v"?
  123. data = _query_device_info(device)
  124. data["_id"] = _query_device_id(device)
  125. print_dotted_output(data)
  126. def xap_dummy(device):
  127. # get layer count
  128. layers = _xap_transaction(device, 0x04, 0x01)
  129. layers = int.from_bytes(layers, "little")
  130. print(f'layers:{layers}')
  131. # get keycode [layer:0, row:0, col:0]
  132. # keycode = _xap_transaction(device, 0x04, 0x02, b"\x00\x00\x00")
  133. # get encoder [layer:0, index:0, clockwise:0]
  134. keycode = _xap_transaction(device, 0x05, 0x02, b"\x00\x00\x00")
  135. keycode = int.from_bytes(keycode, "little")
  136. print(f'keycode:{KEYCODE_MAP.get(keycode, "unknown")}[{keycode}]')
  137. # set encoder [layer:0, index:0, clockwise:0, keycode:KC_A]
  138. _xap_transaction(device, 0x05, 0x03, b"\x00\x00\x00\x04\00")
  139. def xap_broadcast_listen(device):
  140. try:
  141. cli.log.info("Listening for XAP broadcasts...")
  142. while 1:
  143. array_alpha = device.read(64, 100)
  144. if str(b"\xFF\xFF") == str(array_alpha[:2]):
  145. if array_alpha[2] == 1:
  146. cli.log.info(" Broadcast: Secure[%02x]", array_alpha[4])
  147. else:
  148. cli.log.info(" Broadcast: type[%02x] data:[%02x]", array_alpha[2], array_alpha[4])
  149. except KeyboardInterrupt:
  150. cli.log.info("Stopping...")
  151. def xap_unlock(device):
  152. _xap_transaction(device, 0x00, 0x04)
  153. class XAPShell(cmd.Cmd):
  154. intro = 'Welcome to the XAP shell. Type help or ? to list commands.\n'
  155. prompt = 'Ψ> '
  156. def __init__(self, device):
  157. cmd.Cmd.__init__(self)
  158. self.device = device
  159. def do_about(self, arg):
  160. """Prints out the current version of QMK with a build date
  161. """
  162. data = _query_device(self.device)
  163. print(data)
  164. def do_unlock(self, arg):
  165. """Initiate secure unlock
  166. """
  167. xap_unlock(self.device)
  168. print("Done")
  169. def do_listen(self, arg):
  170. """Log out XAP broadcast messages
  171. """
  172. xap_broadcast_listen(self.device)
  173. def do_keycode(self, arg):
  174. """Prints out the keycode value of a certain layer, row, and column
  175. """
  176. data = bytes(map(int, arg.split()))
  177. if len(data) != 3:
  178. cli.log.error("Invalid args")
  179. return
  180. keycode = _xap_transaction(self.device, 0x04, 0x02, data)
  181. keycode = int.from_bytes(keycode, "little")
  182. print(f'keycode:{KEYCODE_MAP.get(keycode, "unknown")}[{keycode}]')
  183. def do_keymap(self, arg):
  184. """Prints out the keycode values of a certain layer
  185. """
  186. data = bytes(map(int, arg.split()))
  187. if len(data) != 1:
  188. cli.log.error("Invalid args")
  189. return
  190. info = _query_device_info(self.device)
  191. rows = info['matrix_size']['rows']
  192. cols = info['matrix_size']['cols']
  193. # TODO: render like qmk info?
  194. for r in range(rows):
  195. for c in range(cols):
  196. q = data + r.to_bytes(1, byteorder='little') + c.to_bytes(1, byteorder='little')
  197. keycode = _xap_transaction(self.device, 0x04, 0x02, q)
  198. keycode = int.from_bytes(keycode, "little")
  199. print(f'| {KEYCODE_MAP.get(keycode, "unknown").ljust(7)} ', end='', flush=True)
  200. print('|')
  201. def do_exit(self, line):
  202. """Quit shell
  203. """
  204. return True
  205. def do_EOF(self, line): # noqa: N802
  206. """Quit shell (ctrl+D)
  207. """
  208. return True
  209. def loop(self):
  210. """Wrapper for cmdloop that handles ctrl+C
  211. """
  212. try:
  213. self.cmdloop()
  214. print('')
  215. except KeyboardInterrupt:
  216. print('^C')
  217. return False
  218. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  219. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  220. @cli.argument('-i', '--interactive', arg_only=True, action='store_true', help='Start interactive shell.')
  221. @cli.argument('action', nargs='*', default=['listen'], arg_only=True)
  222. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  223. def xap(cli):
  224. """Acquire debugging information from XAP devices
  225. """
  226. # Lazy load to avoid issues
  227. global hid
  228. import hid
  229. if cli.args.list:
  230. return _list_devices()
  231. # Connect to first available device
  232. devices = _search()
  233. if not devices:
  234. cli.log.error("No devices found!")
  235. return False
  236. dev = devices[0]
  237. device = hid.Device(path=dev['path'])
  238. cli.log.info("Connected to:%04x:%04x %s %s", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
  239. # shell?
  240. if cli.args.interactive:
  241. XAPShell(device).loop()
  242. return True
  243. XAPShell(device).onecmd(" ".join(cli.args.action))