xap.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. """Interactions with compatible XAP devices
  2. """
  3. import cmd
  4. from milc import cli
  5. from qmk.keyboard import render_layout
  6. from qmk.xap.common import get_xap_keycodes
  7. from xap_client import XAPClient, XAPEventType, XAPSecureStatus
  8. KEYCODE_MAP = get_xap_keycodes('latest')
  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. def _list_devices():
  33. """Dump out available devices
  34. """
  35. cli.log.info('Available devices:')
  36. devices = XAPClient.list()
  37. for dev in devices:
  38. device = XAPClient().connect(dev)
  39. data = device.info()
  40. cli.log.info(' %04x:%04x %s %s [API:%s]', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], data['_version']['xap'])
  41. if cli.config.general.verbose:
  42. # TODO: better formatting like 'lsusb -v'?
  43. print_dotted_output(data)
  44. class XAPShell(cmd.Cmd):
  45. intro = 'Welcome to the XAP shell. Type help or ? to list commands.\n'
  46. prompt = 'Ψ> '
  47. def __init__(self, device):
  48. cmd.Cmd.__init__(self)
  49. self.device = device
  50. # cache keycodes for this device
  51. self.keycodes = get_xap_keycodes(device.version()['xap'])
  52. def do_about(self, arg):
  53. """Prints out the version info of QMK
  54. """
  55. data = self.device.version()
  56. print_dotted_output(data)
  57. def do_status(self, arg):
  58. """Prints out the current device state
  59. """
  60. status = self.device.status()
  61. print('Secure:%s' % status.get('lock', '???'))
  62. def do_unlock(self, arg):
  63. """Initiate secure unlock
  64. """
  65. self.device.unlock()
  66. print('Unlock Requested...')
  67. def do_lock(self, arg):
  68. """Disable secure routes
  69. """
  70. self.device.lock()
  71. def do_reset(self, arg):
  72. """Jump to bootloader if unlocked
  73. """
  74. if not self.device.reset():
  75. print("Reboot to bootloader failed")
  76. return True
  77. def do_listen(self, arg):
  78. """Log out XAP broadcast messages
  79. """
  80. try:
  81. cli.log.info('Listening for XAP broadcasts...')
  82. while 1:
  83. (event, data) = self.device.listen()
  84. if event == XAPEventType.SECURE_STATUS:
  85. secure_status = XAPSecureStatus(data[0]).name
  86. cli.log.info(' Secure[%s]', secure_status)
  87. else:
  88. cli.log.info(' Broadcast: type[%02x] data:[%s]', event, data.hex())
  89. except KeyboardInterrupt:
  90. cli.log.info('Stopping...')
  91. def do_keycode(self, arg):
  92. """Prints out the keycode value of a certain layer, row, and column
  93. """
  94. data = bytes(map(int, arg.split()))
  95. if len(data) != 3:
  96. cli.log.error('Invalid args')
  97. return
  98. keycode = self.device.transaction(b'\x04\x03', data)
  99. keycode = int.from_bytes(keycode, 'little')
  100. print(f'keycode:{self.keycodes.get(keycode, "unknown")}[{keycode}]')
  101. def do_keymap(self, arg):
  102. """Prints out the keycode values of a certain layer
  103. """
  104. data = bytes(map(int, arg.split()))
  105. if len(data) != 1:
  106. cli.log.error('Invalid args')
  107. return
  108. info = self.device.info()
  109. rows = info['matrix_size']['rows']
  110. cols = info['matrix_size']['cols']
  111. for r in range(rows):
  112. for c in range(cols):
  113. q = data + r.to_bytes(1, byteorder='little') + c.to_bytes(1, byteorder='little')
  114. keycode = self.device.transaction(b'\x04\x03', q)
  115. keycode = int.from_bytes(keycode, 'little')
  116. print(f'| {self.keycodes.get(keycode, "unknown").ljust(7)} ', end='', flush=True)
  117. print('|')
  118. def do_layer(self, arg):
  119. """Renders keycode values of a certain layer
  120. """
  121. data = bytes(map(int, arg.split()))
  122. if len(data) != 1:
  123. cli.log.error('Invalid args')
  124. return
  125. info = self.device.info()
  126. # Assumptions on selected layout rather than prompt
  127. first_layout = next(iter(info['layouts']))
  128. layout = info['layouts'][first_layout]['layout']
  129. keycodes = []
  130. for item in layout:
  131. q = data + bytes(item['matrix'])
  132. keycode = self.device.transaction(b'\x04\x03', q)
  133. keycode = int.from_bytes(keycode, 'little')
  134. keycodes.append(self.keycodes.get(keycode, '???'))
  135. print(render_layout(layout, False, keycodes))
  136. def do_exit(self, line):
  137. """Quit shell
  138. """
  139. return True
  140. def do_EOF(self, line): # noqa: N802
  141. """Quit shell (ctrl+D)
  142. """
  143. return True
  144. def loop(self):
  145. """Wrapper for cmdloop that handles ctrl+C
  146. """
  147. try:
  148. self.cmdloop()
  149. print('')
  150. except KeyboardInterrupt:
  151. print('^C')
  152. return False
  153. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  154. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  155. @cli.argument('-i', '--interactive', arg_only=True, action='store_true', help='Start interactive shell.')
  156. @cli.argument('action', nargs='*', arg_only=True, default=['listen'], help='Shell command and any arguments to run standalone')
  157. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  158. def xap(cli):
  159. """Acquire debugging information from XAP devices
  160. """
  161. if cli.args.list:
  162. return _list_devices()
  163. # Connect to first available device
  164. devices = XAPClient.list()
  165. if not devices:
  166. cli.log.error('No devices found!')
  167. return False
  168. dev = devices[0]
  169. cli.log.info('Connecting to: %04x:%04x %s %s', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
  170. device = XAPClient().connect(dev)
  171. # shell?
  172. if cli.args.interactive:
  173. XAPShell(device).loop()
  174. return True
  175. XAPShell(device).onecmd(' '.join(cli.args.action))