qmk_firmware/lib/python/qmk/cli/xap/xap.py

284 lines
10 KiB
Python
Raw Normal View History

2022-03-28 20:06:11 +00:00
"""Interactions with compatible XAP devices
"""
2022-05-05 21:16:38 +00:00
import cmd
2022-03-28 20:06:11 +00:00
from milc import cli
2022-10-12 18:41:11 +00:00
from qmk.keycodes import load_spec
from qmk.decorators import lru_cache
2022-05-11 00:52:48 +00:00
from qmk.keyboard import render_layout
2022-05-09 22:51:43 +00:00
2022-09-28 22:47:12 +00:00
from xap_client import XAPClient, XAPEventType, XAPSecureStatus, XAPConfigRgblight, XAPConfigBacklight, XAPConfigRgbMatrix, XAPRoutes
2022-06-21 12:27:53 +00:00
2022-03-28 20:06:11 +00:00
def print_dotted_output(kb_info_json, prefix=''):
"""Print the info.json in a plain text format with dot-joined keys.
"""
for key in sorted(kb_info_json):
new_prefix = f'{prefix}.{key}' if prefix else key
if key in ['parse_errors', 'parse_warnings']:
continue
elif key == 'layouts' and prefix == '':
cli.echo(' {fg_blue}layouts{fg_reset}: %s', ', '.join(sorted(kb_info_json['layouts'].keys())))
2022-04-18 23:04:22 +00:00
elif isinstance(kb_info_json[key], bytes):
conv = "".join(["{:02X}".format(b) for b in kb_info_json[key]])
cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, conv)
2022-03-28 20:06:11 +00:00
elif isinstance(kb_info_json[key], dict):
print_dotted_output(kb_info_json[key], new_prefix)
elif isinstance(kb_info_json[key], list):
data = kb_info_json[key]
if len(data) and isinstance(data[0], dict):
for index, item in enumerate(data, start=0):
cli.echo(' {fg_blue}%s.%s{fg_reset}: %s', new_prefix, index, str(item))
else:
2022-06-21 12:27:53 +00:00
cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, ', '.join(map(str, data)))
2022-03-28 20:06:11 +00:00
else:
cli.echo(' {fg_blue}%s{fg_reset}: %s', new_prefix, kb_info_json[key])
2022-10-12 18:41:11 +00:00
@lru_cache(timeout=5)
def _load_keycodes(keycode_version):
"""Gets keycode data for the required version of the XAP definitions.
"""
spec = load_spec(keycode_version)
# Transform into something more usable - { raw_value : first alias || keycode }
2022-11-07 23:30:09 +00:00
ret = {int(k, 16): v.get('aliases', [v.get('key')])[0] for k, v in spec['keycodes'].items()}
# TODO: handle non static keycodes
for k, v in spec['ranges'].items():
lo, mask = map(lambda x: int(x, 16), k.split('/'))
hi = lo + mask
define = v.get("define")
for i in range(lo, hi):
if i not in ret:
if define == 'QK_TO':
layer = i & 0x1F
ret[i] = f'TO({layer})'
elif define == 'QK_MOMENTARY':
layer = i & 0x1F
ret[i] = f'MO({layer})'
elif define == 'QK_LAYER_TAP':
layer = (((i) >> 8) & 0xF)
keycode = ((i) & 0xFF)
ret[i] = f'LT({layer}, {ret.get(keycode, "???")})'
return ret
2022-10-12 18:41:11 +00:00
2022-03-29 17:36:08 +00:00
def _list_devices():
"""Dump out available devices
"""
cli.log.info('Available devices:')
2022-07-18 23:46:08 +00:00
for dev in XAPClient.devices():
2022-06-21 12:27:53 +00:00
device = XAPClient().connect(dev)
2022-07-18 23:46:08 +00:00
ver = device.version()
2022-03-28 20:06:11 +00:00
2022-07-18 23:46:08 +00:00
cli.log.info(' %04x:%04x %s %s [API:%s]', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], ver['xap'])
2022-03-28 20:06:11 +00:00
2022-07-18 23:46:08 +00:00
if cli.args.verbose:
data = device.info()
2022-07-06 16:10:04 +00:00
# TODO: better formatting like 'lsusb -v'?
2022-03-29 17:36:08 +00:00
print_dotted_output(data)
2022-04-05 17:54:28 +00:00
2022-05-05 21:16:38 +00:00
class XAPShell(cmd.Cmd):
intro = 'Welcome to the XAP shell. Type help or ? to list commands.\n'
prompt = 'Ψ> '
def __init__(self, device):
cmd.Cmd.__init__(self)
self.device = device
2022-05-10 01:29:30 +00:00
# cache keycodes for this device
2022-10-12 18:41:11 +00:00
self.keycodes = _load_keycodes(device.version().get('keycodes', 'latest'))
2022-05-05 21:16:38 +00:00
2023-03-08 23:42:19 +00:00
# TODO: dummy code is only to PoC kb/user keycodes
kb_keycodes = self.device.info().get('keycodes', [])
for index, item in enumerate(kb_keycodes):
self.keycodes[0x7E00 + index] = item['key']
user_keycodes = self.device.info().get('user_keycodes', [])
for index, item in enumerate(user_keycodes):
self.keycodes[0x7E40 + index] = item['key']
2022-05-05 21:16:38 +00:00
def do_about(self, arg):
2022-07-17 21:02:18 +00:00
"""Prints out the version info of QMK
2022-05-05 21:16:38 +00:00
"""
2022-07-17 21:02:18 +00:00
data = self.device.version()
print_dotted_output(data)
2022-05-05 21:16:38 +00:00
2022-07-07 00:57:41 +00:00
def do_status(self, arg):
"""Prints out the current device state
"""
status = self.device.status()
print('Secure:%s' % status.get('lock', '???'))
2022-05-05 21:16:38 +00:00
def do_unlock(self, arg):
"""Initiate secure unlock
"""
2022-06-21 12:27:53 +00:00
self.device.unlock()
2022-07-06 16:10:04 +00:00
print('Unlock Requested...')
2022-05-05 21:16:38 +00:00
2022-07-07 00:57:41 +00:00
def do_lock(self, arg):
"""Disable secure routes
"""
self.device.lock()
def do_reset(self, arg):
"""Jump to bootloader if unlocked
"""
if not self.device.reset():
print("Reboot to bootloader failed")
return True
2022-05-05 21:16:38 +00:00
def do_listen(self, arg):
"""Log out XAP broadcast messages
"""
2022-06-21 12:27:53 +00:00
try:
2022-07-06 16:10:04 +00:00
cli.log.info('Listening for XAP broadcasts...')
2022-06-21 12:27:53 +00:00
while 1:
2022-07-06 16:10:04 +00:00
(event, data) = self.device.listen()
2022-07-17 00:53:59 +00:00
if event == XAPEventType.SECURE_STATUS:
2022-07-06 16:10:04 +00:00
secure_status = XAPSecureStatus(data[0]).name
cli.log.info(' Secure[%s]', secure_status)
2022-06-21 12:27:53 +00:00
else:
2022-07-07 00:57:41 +00:00
cli.log.info(' Broadcast: type[%02x] data:[%s]', event, data.hex())
2022-07-06 16:10:04 +00:00
2022-06-21 12:27:53 +00:00
except KeyboardInterrupt:
2022-07-06 16:10:04 +00:00
cli.log.info('Stopping...')
2022-05-05 21:16:38 +00:00
def do_keycode(self, arg):
"""Prints out the keycode value of a certain layer, row, and column
"""
data = bytes(map(int, arg.split()))
if len(data) != 3:
2022-07-06 16:10:04 +00:00
cli.log.error('Invalid args')
2022-05-05 21:16:38 +00:00
return
2022-07-06 16:10:04 +00:00
keycode = self.device.transaction(b'\x04\x03', data)
keycode = int.from_bytes(keycode, 'little')
2022-05-10 01:29:30 +00:00
print(f'keycode:{self.keycodes.get(keycode, "unknown")}[{keycode}]')
2022-05-05 21:16:38 +00:00
2022-05-10 00:38:14 +00:00
def do_keymap(self, arg):
"""Prints out the keycode values of a certain layer
"""
data = bytes(map(int, arg.split()))
if len(data) != 1:
2022-07-06 16:10:04 +00:00
cli.log.error('Invalid args')
2022-05-10 00:38:14 +00:00
return
2022-06-21 12:27:53 +00:00
info = self.device.info()
2022-05-10 00:38:14 +00:00
rows = info['matrix_size']['rows']
cols = info['matrix_size']['cols']
for r in range(rows):
for c in range(cols):
q = data + r.to_bytes(1, byteorder='little') + c.to_bytes(1, byteorder='little')
2022-07-06 16:10:04 +00:00
keycode = self.device.transaction(b'\x04\x03', q)
keycode = int.from_bytes(keycode, 'little')
2022-05-10 01:29:30 +00:00
print(f'| {self.keycodes.get(keycode, "unknown").ljust(7)} ', end='', flush=True)
2022-05-10 00:38:14 +00:00
print('|')
2022-05-11 00:52:48 +00:00
def do_layer(self, arg):
"""Renders keycode values of a certain layer
"""
data = bytes(map(int, arg.split()))
if len(data) != 1:
2022-07-06 16:10:04 +00:00
cli.log.error('Invalid args')
2022-05-11 00:52:48 +00:00
return
2022-06-21 12:27:53 +00:00
info = self.device.info()
2022-05-11 00:52:48 +00:00
# Assumptions on selected layout rather than prompt
first_layout = next(iter(info['layouts']))
layout = info['layouts'][first_layout]['layout']
keycodes = []
for item in layout:
q = data + bytes(item['matrix'])
2022-07-06 16:10:04 +00:00
keycode = self.device.transaction(b'\x04\x03', q)
keycode = int.from_bytes(keycode, 'little')
keycodes.append(self.keycodes.get(keycode, '???'))
2022-05-11 00:52:48 +00:00
print(render_layout(layout, False, keycodes))
2022-05-05 21:16:38 +00:00
def do_exit(self, line):
"""Quit shell
"""
return True
def do_EOF(self, line): # noqa: N802
"""Quit shell (ctrl+D)
"""
return True
def loop(self):
"""Wrapper for cmdloop that handles ctrl+C
"""
try:
self.cmdloop()
print('')
except KeyboardInterrupt:
print('^C')
return False
2022-09-26 17:09:36 +00:00
def do_dump(self, line):
2022-09-28 22:47:12 +00:00
caps = self.device.int_transaction(XAPRoutes.LIGHTING_CAPABILITIES_QUERY)
2022-09-26 17:09:36 +00:00
2022-09-28 22:47:12 +00:00
if caps & (1 << XAPRoutes.LIGHTING_BACKLIGHT[-1]):
ret = self.device.transaction(XAPRoutes.LIGHTING_BACKLIGHT_GET_CONFIG)
ret = XAPConfigBacklight.from_bytes(ret)
print(ret)
ret = self.device.int_transaction(XAPRoutes.LIGHTING_BACKLIGHT_GET_ENABLED_EFFECTS)
print(f'XAPEffectBacklight(enabled={bin(ret)})')
if caps & (1 << XAPRoutes.LIGHTING_RGBLIGHT[-1]):
ret = self.device.transaction(XAPRoutes.LIGHTING_RGBLIGHT_GET_CONFIG)
ret = XAPConfigRgblight.from_bytes(ret)
print(ret)
ret = self.device.int_transaction(XAPRoutes.LIGHTING_RGBLIGHT_GET_ENABLED_EFFECTS)
print(f'XAPEffectRgblight(enabled={bin(ret)})')
if caps & (1 << XAPRoutes.LIGHTING_RGB_MATRIX[-1]):
ret = self.device.transaction(XAPRoutes.LIGHTING_RGB_MATRIX_GET_CONFIG)
ret = XAPConfigRgbMatrix.from_bytes(ret)
print(ret)
ret = self.device.int_transaction(XAPRoutes.LIGHTING_RGB_MATRIX_GET_ENABLED_EFFECTS)
print(f'XAPEffectRgbMatrix(enabled={bin(ret)})')
2022-09-26 17:09:36 +00:00
2022-05-05 21:16:38 +00:00
2022-07-18 23:46:08 +00:00
@cli.argument('-v', '--verbose', arg_only=True, action='store_true', help='Turns on verbose output.')
2022-03-28 20:06:11 +00:00
@cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
@cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
2022-05-05 21:16:38 +00:00
@cli.argument('-i', '--interactive', arg_only=True, action='store_true', help='Start interactive shell.')
2022-07-08 23:21:34 +00:00
@cli.argument('action', nargs='*', arg_only=True, default=['listen'], help='Shell command and any arguments to run standalone')
2022-03-28 20:06:11 +00:00
@cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
def xap(cli):
"""Acquire debugging information from XAP devices
"""
if cli.args.list:
return _list_devices()
# Connect to first available device
2022-07-18 23:46:08 +00:00
devices = XAPClient.devices()
2022-04-05 17:54:28 +00:00
if not devices:
2022-07-06 16:10:04 +00:00
cli.log.error('No devices found!')
2022-04-05 17:54:28 +00:00
return False
dev = devices[0]
2022-07-08 23:21:34 +00:00
cli.log.info('Connecting to: %04x:%04x %s %s', dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'])
2022-06-21 12:27:53 +00:00
device = XAPClient().connect(dev)
2022-05-05 21:16:38 +00:00
# shell?
if cli.args.interactive:
XAPShell(device).loop()
return True
2022-04-10 23:43:18 +00:00
2022-07-06 16:10:04 +00:00
XAPShell(device).onecmd(' '.join(cli.args.action))