__init__.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. """Interactions with compatible XAP devices
  2. """
  3. import json
  4. import random
  5. from milc import cli
  6. def _is_xap_usage(x):
  7. return x['usage_page'] == 0xFF51 and x['usage'] == 0x0058
  8. def _is_filtered_device(x):
  9. name = "%04x:%04x" % (x['vendor_id'], x['product_id'])
  10. return name.lower().startswith(cli.args.device.lower())
  11. def _search():
  12. devices = filter(_is_xap_usage, hid.enumerate())
  13. if cli.args.device:
  14. devices = filter(_is_filtered_device, devices)
  15. return list(devices)
  16. def _list_devices():
  17. """Dump out available devices
  18. """
  19. cli.log.info('Available devices:')
  20. devices = _search()
  21. for dev in devices:
  22. device = hid.Device(path=dev['path'])
  23. data = _query_device(device)
  24. cli.log.info(" %04x:%04x %s %s [API:%s]", dev['vendor_id'], dev['product_id'], dev['manufacturer_string'], dev['product_string'], data['ver'])
  25. if cli.config.general.verbose:
  26. # TODO: better formatting like "lsusb -v"
  27. cli.log.info(" " + json.dumps(data))
  28. def _query_device(device):
  29. # gen token
  30. tok = random.getrandbits(16)
  31. temp = tok.to_bytes(2, byteorder='big')
  32. # send with padding
  33. padding = b"\x00" * 59
  34. device.write(temp + b'\x02\x00\x00' + padding)
  35. # get resp
  36. array_alpha = device.read(8, 100)
  37. # hex_string = " ".join("%02x" % b for b in array_alpha)
  38. # validate tok sent == resp
  39. ver = "UNKNOWN"
  40. if str(temp) == str(array_alpha[:2]):
  41. # to BCD string
  42. a = (array_alpha[7] << 24) + (array_alpha[6] << 16) + (array_alpha[5] << 8) + (array_alpha[4])
  43. ver = f'{a>>24}.{a>>16 & 0xFF}.{a & 0xFFFF}'
  44. return {'ver': ver}
  45. @cli.argument('-d', '--device', help='device to select - uses format <pid>:<vid>.')
  46. @cli.argument('-i', '--index', default=0, help='device index to select.')
  47. @cli.argument('-l', '--list', arg_only=True, action='store_true', help='List available devices.')
  48. @cli.subcommand('Acquire debugging information from usb XAP devices.', hidden=False if cli.config.user.developer else True)
  49. def xap(cli):
  50. """Acquire debugging information from XAP devices
  51. """
  52. # Lazy load to avoid issues
  53. global hid
  54. import hid
  55. if cli.args.list:
  56. return _list_devices()
  57. cli.log.warn("TODO: Device specific stuff")