xap.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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['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 current version of QMK with a build date
  54. """
  55. # TODO: request stuff?
  56. print(self.device.info()['xap'])
  57. def do_unlock(self, arg):
  58. """Initiate secure unlock
  59. """
  60. self.device.unlock()
  61. print('Unlock Requested...')
  62. def do_listen(self, arg):
  63. """Log out XAP broadcast messages
  64. """
  65. try:
  66. cli.log.info('Listening for XAP broadcasts...')
  67. while 1:
  68. (event, data) = self.device.listen()
  69. if event == XAPEventType.SECURE:
  70. secure_status = XAPSecureStatus(data[0]).name
  71. cli.log.info(' Secure[%s]', secure_status)
  72. else:
  73. data_str = ' '.join(['{:02X}'.format(b) for b in data])
  74. cli.log.info(' Broadcast: type[%02x] data:[%s]', event, data_str)
  75. except KeyboardInterrupt:
  76. cli.log.info('Stopping...')
  77. def do_keycode(self, arg):
  78. """Prints out the keycode value of a certain layer, row, and column
  79. """
  80. data = bytes(map(int, arg.split()))
  81. if len(data) != 3:
  82. cli.log.error('Invalid args')
  83. return
  84. keycode = self.device.transaction(b'\x04\x03', data)
  85. keycode = int.from_bytes(keycode, 'little')
  86. print(f'keycode:{self.keycodes.get(keycode, "unknown")}[{keycode}]')
  87. def do_keymap(self, arg):
  88. """Prints out the keycode values of a certain layer
  89. """
  90. data = bytes(map(int, arg.split()))
  91. if len(data) != 1:
  92. cli.log.error('Invalid args')
  93. return
  94. info = self.device.info()
  95. rows = info['matrix_size']['rows']
  96. cols = info['matrix_size']['cols']
  97. for r in range(rows):
  98. for c in range(cols):
  99. q = data + r.to_bytes(1, byteorder='little') + c.to_bytes(1, byteorder='little')
  100. keycode = self.device.transaction(b'\x04\x03', q)
  101. keycode = int.from_bytes(keycode, 'little')
  102. print(f'| {self.keycodes.get(keycode, "unknown").ljust(7)} ', end='', flush=True)
  103. print('|')
  104. def do_layer(self, arg):
  105. """Renders keycode values of a certain layer
  106. """
  107. data = bytes(map(int, arg.split()))
  108. if len(data) != 1:
  109. cli.log.error('Invalid args')
  110. return
  111. info = self.device.info()
  112. # Assumptions on selected layout rather than prompt
  113. first_layout = next(iter(info['layouts']))
  114. layout = info['layouts'][first_layout]['layout']
  115. keycodes = []
  116. for item in layout:
  117. q = data + bytes(item['matrix'])
  118. keycode = self.device.transaction(b'\x04\x03', q)
  119. keycode = int.from_bytes(keycode, 'little')
  120. keycodes.append(self.keycodes.get(keycode, '???'))
  121. print(render_layout(layout, False, keycodes))
  122. def do_exit(self, line):
  123. """Quit shell
  124. """
  125. return True
  126. def do_EOF(self, line): # noqa: N802
  127. """Quit shell (ctrl+D)
  128. """
  129. return True
  130. def loop(self):
  131. """Wrapper for cmdloop that handles ctrl+C
  132. """
  133. try:
  134. self.cmdloop()
  135. print('')
  136. except KeyboardInterrupt:
  137. print('^C')
  138. return False
  139. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  140. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  141. @cli.argument('-i', '--interactive', arg_only=True, action='store_true', help='Start interactive shell.')
  142. @cli.argument('action', nargs='*', default=['listen'], arg_only=True)
  143. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  144. def xap(cli):
  145. """Acquire debugging information from XAP devices
  146. """
  147. if cli.args.list:
  148. return _list_devices()
  149. # Connect to first available device
  150. devices = XAPClient.list()
  151. if not devices:
  152. cli.log.error('No devices found!')
  153. return False
  154. dev = devices[0]
  155. cli.log.info('Connecting to:%04x:%04x %s %s', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
  156. device = XAPClient().connect(dev)
  157. # shell?
  158. if cli.args.interactive:
  159. XAPShell(device).loop()
  160. return True
  161. XAPShell(device).onecmd(' '.join(cli.args.action))