Skip to content

Commit 170da39

Browse files
committed
Add support for USB connections
Adds a new subclass of PybricksHub that manages USB connections. Signed-off-by: Nate Karstens <[email protected]>
1 parent eb28049 commit 170da39

File tree

2 files changed

+138
-4
lines changed

2 files changed

+138
-4
lines changed

pybricksdev/cli/__init__.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -171,10 +171,12 @@ def add_parser(self, subparsers: argparse._SubParsersAction):
171171
)
172172

173173
async def run(self, args: argparse.Namespace):
174-
from ..ble import find_device
174+
from usb.core import find as find_usb
175+
176+
from ..ble import find_device as find_ble
175177
from ..connections.ev3dev import EV3Connection
176178
from ..connections.lego import REPLHub
177-
from ..connections.pybricks import PybricksHubBLE
179+
from ..connections.pybricks import PybricksHubBLE, PybricksHubUSB
178180

179181
# Pick the right connection
180182
if args.conntype == "ssh":
@@ -185,14 +187,28 @@ async def run(self, args: argparse.Namespace):
185187

186188
device_or_address = socket.gethostbyname(args.name)
187189
hub = EV3Connection(device_or_address)
190+
188191
elif args.conntype == "ble":
189192
# It is a Pybricks Hub with BLE. Device name or address is given.
190193
print(f"Searching for {args.name or 'any hub with Pybricks service'}...")
191-
device_or_address = await find_device(args.name)
194+
device_or_address = await find_ble(args.name)
192195
hub = PybricksHubBLE(device_or_address)
193196

194197
elif args.conntype == "usb":
195-
hub = REPLHub()
198+
199+
def is_pybricks_usb(dev):
200+
return (
201+
(dev.idVendor == 0x0694)
202+
and ((dev.idProduct == 0x0009) or (dev.idProduct == 0x0011))
203+
and dev.product.endswith("Pybricks")
204+
)
205+
206+
device_or_address = find_usb(custom_match=is_pybricks_usb)
207+
208+
if device_or_address is not None:
209+
hub = PybricksHubUSB(device_or_address)
210+
else:
211+
hub = REPLHub()
196212
else:
197213
raise ValueError(f"Unknown connection type: {args.conntype}")
198214

pybricksdev/connections/pybricks.py

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import os
88
import struct
99
from typing import Awaitable, Callable, List, Optional, TypeVar
10+
from uuid import UUID
1011

1112
import reactivex.operators as op
1213
import semver
@@ -17,6 +18,10 @@
1718
from reactivex.subject import BehaviorSubject, Subject
1819
from tqdm.auto import tqdm
1920
from tqdm.contrib.logging import logging_redirect_tqdm
21+
from usb.control import get_descriptor
22+
from usb.core import Device as USBDevice
23+
from usb.core import Endpoint, USBTimeoutError
24+
from usb.util import ENDPOINT_IN, ENDPOINT_OUT, endpoint_direction, find_descriptor
2025

2126
from ..ble.lwp3.bytecodes import HubKind
2227
from ..ble.nus import NUS_RX_UUID, NUS_TX_UUID
@@ -705,3 +710,116 @@ async def write_gatt_char(self, uuid: str, data, response: bool) -> None:
705710

706711
async def start_notify(self, uuid: str, callback: Callable) -> None:
707712
return await self._client.start_notify(uuid, callback)
713+
714+
715+
class PybricksHubUSB(PybricksHub):
716+
_device: USBDevice
717+
_ep_in: Endpoint
718+
_ep_out: Endpoint
719+
_notify_callbacks = {}
720+
_monitor_task: asyncio.Task
721+
722+
def __init__(self, device: USBDevice):
723+
super().__init__()
724+
self._device = device
725+
726+
async def _client_connect(self) -> bool:
727+
self._device.set_configuration()
728+
729+
# Save input and output endpoints
730+
cfg = self._device.get_active_configuration()
731+
intf = cfg[(0, 0)]
732+
self._ep_in = find_descriptor(
733+
intf,
734+
custom_match=lambda e: endpoint_direction(e.bEndpointAddress)
735+
== ENDPOINT_IN,
736+
)
737+
self._ep_out = find_descriptor(
738+
intf,
739+
custom_match=lambda e: endpoint_direction(e.bEndpointAddress)
740+
== ENDPOINT_OUT,
741+
)
742+
743+
# Set write size to endpoint packet size minus length of UUID
744+
self._max_write_size = self._ep_out.wMaxPacketSize - 16
745+
746+
# Get length of BOS descriptor
747+
bos_descriptor = get_descriptor(self._device, 5, 0x0F, 0)
748+
(ofst, _, bos_len, _) = struct.unpack("<BBHB", bos_descriptor)
749+
750+
# Get full BOS descriptor
751+
bos_descriptor = get_descriptor(self._device, bos_len, 0x0F, 0)
752+
753+
while ofst < bos_len:
754+
(len, desc_type, cap_type) = struct.unpack_from(
755+
"<BBB", bos_descriptor, offset=ofst
756+
)
757+
758+
if desc_type != 0x10:
759+
logger.error("Expected Device Capability descriptor")
760+
exit(1)
761+
762+
# Look for platform descriptors
763+
if cap_type == 0x05:
764+
uuid_bytes = bos_descriptor[ofst + 4 : ofst + 4 + 16]
765+
uuid_str = str(UUID(bytes_le=bytes(uuid_bytes)))
766+
767+
if uuid_str == FW_REV_UUID:
768+
fw_version = bytearray(bos_descriptor[ofst + 20 : ofst + len])
769+
self.fw_version = Version(fw_version.decode())
770+
771+
elif uuid_str == SW_REV_UUID:
772+
self._protocol_version = bytearray(
773+
bos_descriptor[ofst + 20 : ofst + len]
774+
)
775+
776+
elif uuid_str == PYBRICKS_HUB_CAPABILITIES_UUID:
777+
caps = bytearray(bos_descriptor[ofst + 20 : ofst + len])
778+
(
779+
_,
780+
self._capability_flags,
781+
self._max_user_program_size,
782+
) = unpack_hub_capabilities(caps)
783+
784+
ofst += len
785+
786+
self._monitor_task = asyncio.create_task(self._monitor_usb())
787+
788+
return True
789+
790+
async def _client_disconnect(self) -> bool:
791+
self._monitor_task.cancel()
792+
self._handle_disconnect()
793+
794+
async def read_gatt_char(self, uuid: str) -> bytearray:
795+
return None
796+
797+
async def write_gatt_char(self, uuid: str, data, response: bool) -> None:
798+
self._ep_out.write(UUID(uuid).bytes_le + data)
799+
# TODO: Handle response
800+
801+
async def start_notify(self, uuid: str, callback: Callable) -> None:
802+
self._notify_callbacks[uuid] = callback
803+
804+
async def _monitor_usb(self):
805+
loop = asyncio.get_running_loop()
806+
807+
while True:
808+
msg = await loop.run_in_executor(None, self._read_usb)
809+
810+
if msg is None:
811+
continue
812+
813+
if len(msg) > 16:
814+
uuid = str(UUID(bytes_le=bytes(msg[0:16])))
815+
if uuid in self._notify_callbacks:
816+
callback = self._notify_callbacks[uuid]
817+
if callback:
818+
callback(None, bytes(msg[16:]))
819+
820+
def _read_usb(self):
821+
try:
822+
msg = self._ep_in.read(self._ep_in.wMaxPacketSize)
823+
return msg
824+
except USBTimeoutError:
825+
return None

0 commit comments

Comments
 (0)