diff --git a/conftest.py b/conftest.py index 6fa769c..5d85023 100644 --- a/conftest.py +++ b/conftest.py @@ -64,10 +64,13 @@ def _leave_logging_as_it_was() -> Iterator[None]: # pyright: ignore[reportUnuse def _short_grace(monkeypatch: pytest.MonkeyPatch) -> None: # pyright: ignore[reportUnusedFunction] """Stop a connect waiting for hubs that have all been heard already. - A connect that finds a hub waits a moment for a better route to it, since - real hubs advertise only every so often. Simulated hubs are all heard at + A connect that finds a hub waits a moment for a better route to it, and, + short of an id, for another hub that would match as well, since real hubs + advertise only every so often. Simulated hubs are all heard at once, so under test the wait is only ever waited out, by every connect that is not by id -- which was more than a third of the time the whole suite took. A test about the wait itself sets it back. """ monkeypatch.setattr(pb_service.methods.hub, "PREFERENCE_SECONDS", GRACE_SECONDS) + monkeypatch.setattr(pb_service.methods.hub, "AMBIGUITY_SECONDS", GRACE_SECONDS) + monkeypatch.setattr(pb_service.methods.hub, "PAIRED_SECONDS", GRACE_SECONDS) diff --git a/docs/index.md b/docs/index.md index c9d0ed4..585c8eb 100644 --- a/docs/index.md +++ b/docs/index.md @@ -104,9 +104,14 @@ pb use --hub "Rover" # or name it What is remembered is the hub's name, so the choice survives switching the hub off and on, and outlives the background service; every shell sees the same one. The hub does not have to be connected, or even switched on, so the hub a -project belongs to can be chosen before any of it is plugged in. +project belongs to can be chosen before any of it is plugged in: the next +`pb connect` goes looking for that hub, and for no other. `pb use --clear` forgets it again. +With nothing chosen and more than one hub switched on, `pb connect` asks which +one you mean rather than taking whichever it heard first — in a room full of +robots, that is usually somebody else's. + Every command takes `-v` for more detail, and `-vv` or `-vvv` when something is going wrong and you want to see why. diff --git a/packages/pb-cli/CHANGELOG.md b/packages/pb-cli/CHANGELOG.md index 055f146..cb0a2ea 100644 --- a/packages/pb-cli/CHANGELOG.md +++ b/packages/pb-cli/CHANGELOG.md @@ -5,6 +5,23 @@ Notable changes to `pybricks-cli`, the `pb` command. The format is based on ## [Unreleased] +### Changed + +- `pb connect` with no `--hub` connects to the hub chosen with `pb use` + ([support#2866](https://github.com/pybricks/support/issues/2866)). +- `pb connect` asks which hub when several are switched on and none is chosen, + instead of taking the first one heard. The same goes for several hubs + sharing the name asked for or chosen, as unnamed hubs all do. A hub only + paired over RFCOMM is not offered unless the service counted it. +- `pb connect` says "Already connected" when the hub already was, rather than + claiming to have connected it. +- When the hub chosen with `pb use` is not found, `pb connect` says how to + choose another. + +### Fixed + +- `pb connect` printed a hub name with square brackets in it as rich markup. + ## [1.0.0b1] - 2026-10-18 ### Added diff --git a/packages/pb-cli/src/pb_cli/commands/hub.py b/packages/pb-cli/src/pb_cli/commands/hub.py index 88a2241..18073e2 100644 --- a/packages/pb-cli/src/pb_cli/commands/hub.py +++ b/packages/pb-cli/src/pb_cli/commands/hub.py @@ -16,12 +16,13 @@ import logging import sys from collections.abc import AsyncGenerator, AsyncIterator, Callable, Mapping -from contextlib import AbstractAsyncContextManager, asynccontextmanager -from typing import Annotated, Final +from contextlib import AbstractAsyncContextManager, aclosing, asynccontextmanager +from typing import Annotated, Final, cast import anyio import cyclopts from rich.console import Console, RenderableType +from rich.markup import escape import pb_client from pb_cli import errors, keys, picker, ui @@ -272,8 +273,9 @@ async def connect_cmd( than reconnecting. Args: - hub: The hub's name, as shown by pb scan. Defaults to the first - hub found. + hub: The hub's name, as shown by pb scan. Defaults to the hub + chosen with pb use, and otherwise to the only hub switched on; + when there are several, you are asked which. scan: Watch for hubs and choose one from the list. There is no time limit, so the hub can be switched on whenever you like, and Ctrl-C gives up without connecting to anything. @@ -305,6 +307,65 @@ async def connect_cmd( ) +def _shared_name(exc: pb_client.JsonRpcError) -> str | None: + """The name several hubs answered to, if that is what made them ambiguous. + + Args: + exc: A ``HUB_AMBIGUOUS`` refusal. + + Returns: + The name, or ``None`` if no name was asked for or the service did not + say. + """ + data: object = exc.data + if not isinstance(data, Mapping): + return None + + name = cast("Mapping[str, object]", data).get("name") + return name if isinstance(name, str) and name else None + + +def _offered_transports(exc: pb_client.JsonRpcError) -> frozenset[str] | None: + """The transports the hubs in an ambiguity were found on. + + Args: + exc: A ``HUB_AMBIGUOUS`` refusal. + + Returns: + Their transports, or ``None`` if the service did not list them. + """ + data: object = exc.data + if not isinstance(data, Mapping): + return None + + devices = cast("Mapping[str, object]", data).get("devices") + if not isinstance(devices, list): + return None + + return frozenset( + str(cast("Mapping[str, object]", device).get("transport", "")) + for device in cast("list[object]", devices) + if isinstance(device, Mapping) + ) + + +async def _offering( + devices: AsyncIterator[pb_client.DeviceInfo], heard_only: bool +) -> AsyncGenerator[pb_client.DeviceInfo, None]: + """Pass on the hubs found, less those only paired over RFCOMM if asked. + + Args: + devices: Hubs as they are found. + heard_only: Leave out hubs only listed as paired. + + Yields: + The hubs to offer. + """ + async for device in devices: + if not heard_only or device.transport != "rfcomm": + yield device + + async def _connect(hub: str | None, scan: bool, transport: str | None) -> int: err = ui.console(err=True) @@ -315,14 +376,69 @@ def tell(asked: bool) -> None: err.print(_asked()) async with pb_client.connect() as service: - if scan: + info: pb_client.HubInfo | None = None + # The name several hubs share, when that is why one could not be + # picked: the choice is then between those hubs and no others. + shared: str | None = None + # Whether the hubs to choose between were only those heard, the service + # having left out hubs that are merely paired: offering a paired EV3 + # in a drawer as one of them would be offering a hub that is not there. + heard_only = False + + if not scan: + # Which hub is meant, when none was named, is the service's to + # decide -- the chosen one, as for every other command -- but it is + # worth saying, so that a hub left switched off is not a mystery. + chosen = None if hub else (await service.chosen_hub()).name + # Escaped, as every hub name printed with markup is: a name is the + # user's to write, square brackets and all. + doing = f"Connecting to {escape(chosen)}..." if chosen else "Connecting..." + + with ui.spinner(err, doing): + async with _telling_when_asked(service, tell): + try: + info = await service.connect_hub( + hub_id=hub if hub and _looks_like_id(hub) else None, + name=hub if hub and not _looks_like_id(hub) else None, + transport=transport, + ) + except pb_client.JsonRpcError as exc: + # Several hubs and nothing to say which is a question, + # not a failure, wherever there is someone to ask. With + # no terminal it is reported like any other refusal. + if ( + exc.code != ErrorCode.HUB_AMBIGUOUS + or not keys.keys_available() + ): + raise + + shared = _shared_name(exc) + offered = _offered_transports(exc) + heard_only = offered is not None and "rfcomm" not in offered + + if info is None: + if shared: + err.print( + f"More than one hub called {shared} was found. Which one?", + markup=False, + highlight=False, + ) + else: + err.print("More than one hub was found. Which one?") + + if info is None: # No time limit: the hub may still be in the next room. The scan # ends when the block does, whether the user chose or gave up. + # aclosing, because the picker stops listening as soon as a hub is + # chosen, which leaves the filter suspended at its yield. async with ( _telling_when_asked(service, tell), - service.scanning(seconds=None, transport=transport) as devices, + service.scanning( + seconds=None, name=shared, transport=transport + ) as devices, + aclosing(_offering(devices, heard_only)) as offered, ): - device = await picker.choose_hub(err, devices, ui.chooser_table) + device = await picker.choose_hub(err, offered, ui.chooser_table) if device is None: # Deciding not to connect is what was asked for, not a failure. @@ -333,14 +449,6 @@ def tell(asked: bool) -> None: info = await service.connect_hub(hub_id=device.id) # No transport here: choosing a row from the list has already # chosen the route, since each row is one. - else: - with ui.spinner(err, "Connecting..."): - async with _telling_when_asked(service, tell): - info = await service.connect_hub( - hub_id=hub if hub and _looks_like_id(hub) else None, - name=hub if hub and not _looks_like_id(hub) else None, - transport=transport, - ) # The protocol version belongs to pb status: it explains why a command was # refused, but on a successful connection it is one more number to read @@ -350,7 +458,11 @@ def tell(asked: bool) -> None: if info.hub_type: described = f"{info.hub_type}, {described}" - err.print(f"Connected to [bold]{info.name}[/] ({described}).") + # Said, because connecting to a hub that already is succeeds without doing + # anything, and a user who meant another hub of the same name needs to see + # that none was looked for. + done = "Already connected" if info.already_connected else "Connected" + err.print(f"{done} to [bold]{escape(info.name)}[/] ({escape(described)}).") return EXIT_OK diff --git a/packages/pb-cli/src/pb_cli/errors.py b/packages/pb-cli/src/pb_cli/errors.py index e2d6701..345b5a2 100644 --- a/packages/pb-cli/src/pb_cli/errors.py +++ b/packages/pb-cli/src/pb_cli/errors.py @@ -240,6 +240,12 @@ def bluetooth_advice(availability: str | None, platform: str = sys.platform) -> ErrorCode.HUB_BUSY: _Rule( "Wait a moment, or stop what it is doing with [bold]pb stop[/]." ), + # Only seen where nobody can be asked which: with a terminal, pb connect + # turns it into a choice instead. + ErrorCode.HUB_AMBIGUOUS: _Rule( + "Say which with [bold]--hub[/], or choose one for every command with " + "[bold]pb use[/]." + ), ErrorCode.HUB_INVALID_COMMAND: _Rule( "If the hub's firmware is old, installing the latest version from " "code.pybricks.com may help." @@ -436,6 +442,55 @@ def _slot_hint(exc: JsonRpcError, default: str | None) -> str | None: return _ONE_SLOT if data.get("slots") == 1 else default +_SAME_NAME = ( + "Hubs with the same name cannot be told apart by it. Give one another " + "name when installing the firmware with Pybricks Code, or connect it in " + "a terminal with [bold]pb connect --scan[/]." +) + + +def _ambiguous_hint(exc: JsonRpcError, default: str | None) -> str | None: + """Suggest how to say which hub, which a shared name rules out. + + Args: + exc: The error the service sent. + default: The suggestion for hubs that a name would tell apart. + + Returns: + The suggestion to print. + """ + payload: object = exc.data + if not isinstance(payload, Mapping): + return default + + data = cast("Mapping[str, object]", exc.data) + return _SAME_NAME if data.get("name") else default + + +def _chosen_hint(exc: JsonRpcError, hint: str | None) -> str | None: + """Add how to choose again, when the hub not found was the chosen one. + + Args: + exc: The error the service sent. + hint: The suggestion so far. + + Returns: + The suggestion to print. Switching the hub on is still the first one, + but a choice outlives the hub it named, and without this the only way + out of an old one is to know about pb use. + """ + payload: object = exc.data + if not isinstance(payload, Mapping): + return hint + + data = cast("Mapping[str, object]", payload) + if not data.get("chosen"): + return hint + + again = "To use another hub, choose it with [bold]pb use[/]." + return f"{hint} {again}" if hint else again + + def _bluetooth_hint(exc: JsonRpcError) -> str: """Suggest what to do about Bluetooth, by the reason the service gave. @@ -475,6 +530,12 @@ def _describe_rpc(exc: JsonRpcError, hints: Mapping[int, str] | None) -> Problem if exc.code == ErrorCode.BLUETOOTH_UNAVAILABLE: hint = _bluetooth_hint(exc) + if exc.code == ErrorCode.HUB_AMBIGUOUS: + hint = _ambiguous_hint(exc, hint) + + if exc.code == ErrorCode.HUB_NOT_FOUND: + hint = _chosen_hint(exc, hint) + if exc.code == ErrorCode.UNSUPPORTED_PROTOCOL_VERSION: message, hint = _version_mismatch(exc, message, hint) diff --git a/packages/pb-client/CHANGELOG.md b/packages/pb-client/CHANGELOG.md index 026494b..88c2eb5 100644 --- a/packages/pb-client/CHANGELOG.md +++ b/packages/pb-client/CHANGELOG.md @@ -5,6 +5,16 @@ Notable changes to `pybricks-client`. The format is based on ## [Unreleased] +### Changed + +- `Service.connect_hub()` with no hub named connects to the chosen hub, and + raises `HUB_AMBIGUOUS` when several are switched on and none is chosen. + +### Added + +- `HubInfo.already_connected`, set when `Service.connect_hub()` handed back a + hub that was connected before. + ## [1.0.0b1] - 2026-10-18 ### Added diff --git a/packages/pb-client/src/pb_client/models.py b/packages/pb-client/src/pb_client/models.py index 0245922..6849d82 100644 --- a/packages/pb-client/src/pb_client/models.py +++ b/packages/pb-client/src/pb_client/models.py @@ -255,6 +255,14 @@ class HubInfo: can join from a program somebody else started. """ + already_connected: bool = False + """Whether the hub was connected before, as told by ``hub.connect`` only. + + Asking to connect a hub that already is hands that hub back rather than + failing, so this is how to tell that nothing was done. Always false from + anything but ``hub.connect``, and from a service too old to say. + """ + @property def legacy_main_module(self) -> bool: """Whether this hub needs the program's entry module called ``__main__``. @@ -307,4 +315,5 @@ def from_wire(cls, payload: dict[str, Any]) -> HubInfo: else None ), status_names=tuple(str(name) for name in listed), + already_connected=payload.get("already_connected") is True, ) diff --git a/packages/pb-client/src/pb_client/service.py b/packages/pb-client/src/pb_client/service.py index 4c01008..84d5037 100644 --- a/packages/pb-client/src/pb_client/service.py +++ b/packages/pb-client/src/pb_client/service.py @@ -372,15 +372,29 @@ async def connect_hub( The connection outlives this client: that is the point of the service. + With neither ``hub_id`` nor ``name``, the hub is the one chosen with + [use_hub][pb_client.service.Service.use_hub] if there is one; + otherwise one already connected; otherwise the only hub switched on. + Several hubs switched on and nothing to say which is refused rather + than guessed at. + Args: hub_id: The hub's id, from [scan][pb_client.service.Service.scan]. - name: Connect to the first hub with this name instead. + name: Connect to the hub with this name instead. One already + connected is handed back; several switched on are refused. transport: Reach the hub this way, such as ``"usb"`` or ``"ble"``. Left out, the service uses whichever it can, preferring USB where a hub is reachable both ways. Returns: - The connected hub. + The connected hub. If it was connected already, it is handed back + as it is, with ``already_connected`` set. + + Raises: + JsonRpcError: With ``ErrorCode.HUB_AMBIGUOUS`` when several hubs + were found and none was named or chosen, or several have the + name asked for or chosen. Its ``data`` lists them, in the + shape ``hub.scan`` reports, and names that shared ``name``. """ params: dict[str, Any] = {} diff --git a/packages/pb-core/CHANGELOG.md b/packages/pb-core/CHANGELOG.md index 87d59a5..1cd89af 100644 --- a/packages/pb-core/CHANGELOG.md +++ b/packages/pb-core/CHANGELOG.md @@ -5,6 +5,16 @@ Notable changes to `pybricks-core`. The format is based on ## [Unreleased] +### Added + +- `ErrorCode.HUB_AMBIGUOUS`, for a hub that could be any of several. + +### Changed + +- `PROTOCOL_VERSION` and `MIN_PROTOCOL_VERSION` are 4, for the changes to + `hub.connect`. A client and a service of different versions refuse each + other, and `pb service stop` replaces a service left over from before. + ## [1.0.0b1] - 2026-10-18 ### Added diff --git a/packages/pb-core/src/pb_core/jsonrpc/errors.py b/packages/pb-core/src/pb_core/jsonrpc/errors.py index 1cc421b..33a69bf 100644 --- a/packages/pb-core/src/pb_core/jsonrpc/errors.py +++ b/packages/pb-core/src/pb_core/jsonrpc/errors.py @@ -43,6 +43,16 @@ class ErrorCode(IntEnum): HUB_BUSY = -32014 HUB_INVALID_COMMAND = -32015 HUB_UNSUPPORTED = -32016 + HUB_AMBIGUOUS = -32024 + """More than one hub was found, and nothing said which one was meant. + + Raised by ``hub.connect`` when no hub is named, none is chosen and none is + connected, rather than taking whichever advertised first: in a classroom + that is somebody else's robot. Raised too when several hubs have the name + asked for or chosen, and then the data also carries that ``name``. The data + carries what was found, as ``hub.scan`` reports it, so that a client can + offer them as a choice. + """ # Programs. PROGRAM_TOO_LARGE = -32017 diff --git a/packages/pb-core/src/pb_core/protocol.py b/packages/pb-core/src/pb_core/protocol.py index 51b1899..8ab392d 100644 --- a/packages/pb-core/src/pb_core/protocol.py +++ b/packages/pb-core/src/pb_core/protocol.py @@ -42,14 +42,16 @@ "STDIO_CAPABILITY", ] -PROTOCOL_VERSION: Final = 3 +PROTOCOL_VERSION: Final = 4 """The version this build speaks. 2 since the chosen hub became something the service remembers, which changed -what ``hub.use`` and ``hub.list`` say. +what ``hub.use`` and ``hub.list`` say. 4 since ``hub.connect`` goes to the chosen +hub and refuses several with ``HUB_AMBIGUOUS``, which a client of 3 does not +know, and says whether the hub was ``already_connected``. """ -MIN_PROTOCOL_VERSION: Final = 3 +MIN_PROTOCOL_VERSION: Final = 4 """The oldest client version this build still accepts. Equal to :data:`PROTOCOL_VERSION`, and moved with it, so that a mismatch is diff --git a/packages/pb-service/CHANGELOG.md b/packages/pb-service/CHANGELOG.md index b6f54d7..2119e7b 100644 --- a/packages/pb-service/CHANGELOG.md +++ b/packages/pb-service/CHANGELOG.md @@ -5,6 +5,36 @@ Notable changes to `pybricks-service`. The format is based on ## [Unreleased] +### Changed + +- `hub.connect` with no hub named connects to the chosen hub, even when + another hub is already connected. +- `hub.connect` refuses with `HUB_AMBIGUOUS` when several hubs are found and + none is named or chosen, rather than connecting to the first, and when + several share the name asked for. It listens for 1 s after the first hub + heard, so that a second hub that advertises less often is still heard, and + for a second hub on USB too. Hubs with different names count as several even + when heard on different transports. A hub only paired over RFCOMM counts, and + is chosen, only when no other transport heard one, and it waits up to 3 s for + one to be heard rather than starting the 1 s wait itself. +- `hub.connect` with a name hands back a connected hub with that name rather + than scanning past it and connecting another hub with the same name. That + hub, or with nothing named the connected one, is not handed back when + `transport` asks for another route, and `exclusive` refuses it. + +### Added + +- `already_connected` in the `hub.connect` result, saying whether the hub was + connected before the call. +- `chosen` in the data of `hub.connect`'s `HUB_NOT_FOUND`, naming the hub when + it was the one chosen with `hub.use` that was not found. + +### Fixed + +- A Bluetooth hub was sometimes first reported without its hub type, before + its scan response arrived. Hubs are now reported only once it has, and one + that never sends it is logged as a firmware bug rather than listed. + ## [1.0.0b2] - 2026-10-24 ### Fixed diff --git a/packages/pb-service/src/pb_service/hub/ble.py b/packages/pb-service/src/pb_service/hub/ble.py index c1e0bd1..8c45006 100644 --- a/packages/pb-service/src/pb_service/hub/ble.py +++ b/packages/pb-service/src/pb_service/hub/ble.py @@ -21,6 +21,7 @@ from contextlib import AbstractAsyncContextManager, aclosing, asynccontextmanager from typing import Any, final +import anyio from bleak import BleakClient, BleakScanner from bleak.backends.device import BLEDevice from bleak.backends.scanner import AdvertisementData @@ -42,6 +43,15 @@ SCHEME = "ble" +SCAN_RESPONSE_SECONDS = 1.0 +"""How long a hub may go without a scan response before that is logged. + +The kind of hub is in the scan response, which arrives after the advertisement, +so a hub is not reported until it has been heard. Every Pybricks firmware sends +one, so a hub that still has not after this long has a firmware bug, and is +logged as such rather than listed without its type. +""" + def device_id_for(address: str) -> str: """Return the service-facing id for a Bluetooth address. @@ -71,8 +81,8 @@ def _advertised_pnp_id(advertisement: AdvertisementData) -> p.PnpId | None: Returns: The decoded identifier, or ``None`` if this hub did not advertise one - or advertised something malformed. Either way the hub is still listed: - not knowing what kind it is is no reason to hide it. + or advertised something malformed, which is not yet, or a firmware + bug if it never comes. """ data = advertisement.service_data.get(p.PNP_ID_UUID) if data is None: @@ -185,7 +195,9 @@ async def discover( Yields: Hubs as they are seen. A hub may be reported more than once as its - advertisement repeats; callers deduplicate by id. + advertisement repeats; callers deduplicate by id. A hub is only + reported once its scan response, which says what kind of hub it + is, has arrived. One that never sends it is logged, not reported. """ # aclosing on bleak's generator, because this one is nearly always @@ -198,8 +210,25 @@ async def discover( BleakScanner(service_uuids=[p.PYBRICKS_SERVICE_UUID]) as scanner, aclosing(scanner.advertisement_data()) as seen, ): + first_seen: dict[str, float] = {} + logged: set[str] = set() async for device, advertisement in seen: - info = self._to_device_info(device, advertisement) + pnp = _advertised_pnp_id(advertisement) + if pnp is None: + now = anyio.current_time() + since = now - first_seen.setdefault(device.address, now) + if since >= SCAN_RESPONSE_SECONDS and device.address not in logged: + logged.add(device.address) + logger.warning( + "ignoring %s (%s): no PnP ID in its scan response after" + " %.1f s, which is a firmware bug", + device.address, + advertisement.local_name or device.name, + since, + ) + continue + + info = self._to_device_info(device, advertisement, pnp) if info is None: continue @@ -213,10 +242,13 @@ async def discover( yield info def _to_device_info( - self, device: BLEDevice, advertisement: AdvertisementData + self, + device: BLEDevice, + advertisement: AdvertisementData, + pnp: p.PnpId, ) -> DeviceInfo | None: - # The name arrives in the scan response, which may lag the advertisement, - # so a hub without one yet is skipped rather than shown as unnamed. + # A hub may be heard before its name is, so one without a name yet is + # skipped rather than shown as unnamed. name = advertisement.local_name or device.name if not name: return None @@ -227,7 +259,7 @@ def _to_device_info( address=device.address, rssi=advertisement.rssi, transport=SCHEME, - hub_type=p.hub_type_name(_advertised_pnp_id(advertisement)), + hub_type=p.hub_type_name(pnp), ) def open(self, device_id: str) -> AbstractAsyncContextManager[HubLink]: diff --git a/packages/pb-service/src/pb_service/hub/fake.py b/packages/pb-service/src/pb_service/hub/fake.py index f279a63..d7088e1 100644 --- a/packages/pb-service/src/pb_service/hub/fake.py +++ b/packages/pb-service/src/pb_service/hub/fake.py @@ -65,6 +65,14 @@ class FakeHub: variant: int = 0 """Product id and version, as the PnP ID reports them.""" + heard_after: float = 0.0 + """Seconds into a scan before this hub is first heard. + + A real hub advertises only every so often, so one switched on alongside + another may be heard a second after it. Simulated hubs are otherwise all + heard at once, which hides anything that decides too soon. + """ + max_write_size: int = 512 max_program_size: int = 16384 num_slots: int = 5 @@ -445,7 +453,13 @@ async def discover( if self.scan_delay: await anyio.sleep(self.scan_delay) - for hub in self.hubs: + heard_until = 0.0 + + for hub in sorted(self.hubs, key=lambda hub: hub.heard_after): + if hub.heard_after > heard_until: + await anyio.sleep(hub.heard_after - heard_until) + heard_until = hub.heard_after + if scan_filter.name is not None and hub.name != scan_filter.name: continue diff --git a/packages/pb-service/src/pb_service/methods/hub.py b/packages/pb-service/src/pb_service/methods/hub.py index 3f28a57..3b7bdb1 100644 --- a/packages/pb-service/src/pb_service/methods/hub.py +++ b/packages/pb-service/src/pb_service/methods/hub.py @@ -6,7 +6,7 @@ from __future__ import annotations import logging -from collections.abc import Callable +from collections.abc import Callable, Iterable from contextlib import aclosing from typing import Any @@ -53,7 +53,7 @@ """How long disconnecting waits for a built-in program to stop first.""" -def _found_nothing(manager: HubManager) -> JsonRpcError: +def _found_nothing(manager: HubManager, chosen: str | None = None) -> JsonRpcError: """Say as precisely as the transports allow why nothing turned up. A hub that is plugged in but whose port will not open is the opposite @@ -64,6 +64,10 @@ def _found_nothing(manager: HubManager) -> JsonRpcError: Args: manager: Whose transports did the looking. + chosen: The chosen hub, if that is what was looked for. Named in the + message because the user did not name it this time, and "no hub + found" while another hub sits switched on beside them would read + as the tool being broken. Returns: The error to raise. Factual either way: what to suggest depends on the @@ -94,6 +98,27 @@ def _found_nothing(manager: HubManager) -> JsonRpcError: {"availability": known[0]} if known else None, ) + return _not_found(chosen) + + +def _not_found(chosen: str | None) -> JsonRpcError: + """Say that no hub was found, naming the chosen one if that was looked for. + + Args: + chosen: The chosen hub, if that is what was looked for. + + Returns: + The error to raise. + """ + if chosen is not None: + # Marked as chosen in the data too, because the remedy may be to choose + # again: a hub chosen last week can be one nobody is using any more. + return JsonRpcError( + ErrorCode.HUB_NOT_FOUND, + f"the chosen hub {chosen!r} was not found", + {"chosen": chosen}, + ) + return JsonRpcError(ErrorCode.HUB_NOT_FOUND, "no hub found") @@ -198,15 +223,82 @@ def _device_json(device: DeviceInfo) -> dict[str, Any]: } +def _present(devices: Iterable[DeviceInfo]) -> list[DeviceInfo]: + """Leave out hubs that are only known of, if any were actually heard. + + RFCOMM lists the paired hubs, switched on or not, so a hub on it is no + evidence of anything when another transport heard one: an EV3 paired last + term and left in a drawer is neither a second hub to ask about nor a better + choice than the hub advertising on the desk. Heard on its own, though, it is + all there is to go on. + + Args: + devices: What a search found. + + Returns: + The hubs to choose between. + """ + devices = list(devices) + heard = [device for device in devices if device.transport != "rfcomm"] + return heard or devices + + +def _several(devices: Iterable[DeviceInfo]) -> bool: + """Whether these are certainly more than one hub. + + Two ids on the same transport are. Across transports the same hub turns up + under a different id each way, and taking a hub on a cable and over + Bluetooth for two hubs would ask the user to choose between one -- but it + has the same name both ways, so two names are two hubs wherever they were + heard. + + Args: + devices: What a search found, at most one entry per id. + + Returns: + True if some transport reported two different hubs, or two names were + heard. + """ + devices = list(devices) + transports = [device.transport for device in devices] + + if len(transports) != len(set(transports)): + return True + + return len({device.name for device in devices}) > 1 + + PREFERENCE_SECONDS = 0.5 """How long a hub found on one transport waits for a better route to appear. A hub can be reachable more than one way, and which way it is reached decides how quick everything afterwards will be -- so taking whichever route answered -first would make that a race rather than a decision. It is a short wait and it -is only ever paid when the route that answered is not already the preferred one, -which in practice means only when Bluetooth answered before USB: enumerating -serial ports is quick enough that USB usually wins outright. +first would make that a race rather than a decision. It is a short wait, paid +only when a hub is asked for by id and the route that answered is not already +the preferred one. Without an id the longer AMBIGUITY_SECONDS is waited instead, +USB or not, since then the question is also whether there is another hub. +""" + +AMBIGUITY_SECONDS = 1.0 +"""How long a hub found without an id waits for another that would match too. + +Longer than the wait for a better route, because a second hub has to be heard +before it can be refused, and hubs advertise only so often: measured on +Windows, gaps between a hub's advertisements of up to 0.8 s with current +firmware, and of a second with some City hub firmware. A hub quieter +than this is still missed, and connected to without asking, as before. +""" + +PAIRED_SECONDS = 3.0 +"""How long a paired hub found without an id waits for a hub actually heard. + +RFCOMM lists the paired hubs at once, switched on or not, so one of them is no +sign that anything is there. Starting AMBIGUITY_SECONDS from it would end the +search before Bluetooth had heard the hubs that are -- Windows takes a moment +to start watching, and a hub is heard only once its scan response is in. This +is the wait for that instead, and the first hub heard on another transport +starts AMBIGUITY_SECONDS afresh. It is what connecting an EV3 costs when no +other hub is about. """ @@ -311,6 +403,55 @@ def status_json(connection: HubConnection) -> dict[str, Any]: return {} if report is None else report_json(report) +def _hand_back( + connection: HubConnection, params: dict[str, Any], *, by_id: bool = False +) -> dict[str, Any] | None: + """Hand back a hub already connected, if it is what ``hub.connect`` asked for. + + Args: + connection: The connected hub that would do. + params: The request. + by_id: Whether it was asked for by id. An id names the route as well + as the hub, so another transport asked for alongside it is not a + route to search: no hub on it can have that id. + + Returns: + The hub, as ``hub.connect`` describes it; or ``None`` if the request + asked for another route to it, which makes it a hub to look for that + way -- which route is in use decides how quick everything after it is. + + Raises: + JsonRpcError: With ``HUB_ALREADY_CONNECTED`` if the request was + ``exclusive``, which is a request for a hub nothing else holds. + """ + wanted = _transport(params) + using = connection.info.transport if connection.info is not None else None + + if wanted is not None and wanted != using and not by_id: + return None + + if params.get("exclusive"): + # Named as the user knows it: ids are not shown to anyone. + name = connection.info.name if connection.info is not None else "the hub" + raise as_wire_error(HubAlreadyConnectedError(f"{name} is already connected")) + + return _connected_json(connection, already=True) + + +def _connected_json(connection: HubConnection, *, already: bool) -> dict[str, Any]: + """Describe the hub ``hub.connect`` hands back. + + Args: + connection: The hub. + already: Whether it was connected before this call, so that a client + can say so rather than claim to have just connected it. + + Returns: + The hub, as ``hub.info`` describes it, and whether it already was. + """ + return _hub_json(connection) | {"already_connected": already} + + def _hub_json(connection: HubConnection) -> dict[str, Any]: info = connection.info payload: dict[str, Any] = { @@ -428,18 +569,28 @@ async def hub_scan(session: Session, params: dict[str, Any]) -> dict[str, Any]: @method( "hub.connect", - "Connect to a hub and keep it connected. While looking for it, an " - "unusable Bluetooth adapter is reported as hub.adapters, as by hub.scan.", + "Connect to a hub and keep it connected. With no id or name, the hub " + "chosen with hub.use if there is one; otherwise one already connected; " + "otherwise the only hub found, or an ambiguity error listing them if there " + "are several. Several hubs with the name asked for, or chosen, are an " + "ambiguity error too. While looking for it, an unusable Bluetooth adapter is " + "reported as hub.adapters, as by hub.scan.", params={ "id": "The hub's id, from hub.scan.", - "name": "Connect to the first hub with this name instead.", + "name": ( + "Connect to the hub with this name instead. One already connected " + "is handed back; several found are an ambiguity error." + ), "exclusive": "Fail if the hub is already connected.", "transport": ( "Reach the hub this way, such as usb or ble. Omit to use whichever " "is available, preferring USB where a hub is reachable both ways." ), }, - returns="The connected hub's details.", + returns=( + "The connected hub's details, as hub.info gives them, with " + "already_connected saying whether it was connected before this call." + ), ) async def hub_connect(session: Session, params: dict[str, Any]) -> dict[str, Any]: """Connect to a hub, scanning for it first if needed.""" @@ -448,17 +599,77 @@ async def hub_connect(session: Session, params: dict[str, Any]) -> dict[str, Any wanted_id = params.get("id") wanted_name = params.get("name") - - if wanted_id and wanted_id in manager: - return _hub_json(manager.get(str(wanted_id))) - - if not wanted_id and not wanted_name and manager.connected: + chosen: str | None = None + + if ( + wanted_id + and wanted_id in manager + and (handed := _hand_back(manager.get(str(wanted_id)), params, by_id=True)) + ): + return handed + + # Nothing named means the same here as for every other command: the chosen + # hub, then whatever is connected. Connecting is not the exception it once + # was. A hub can be chosen before it is switched on precisely so that the + # next connect finds it, and connecting to some other hub instead leaves + # the user with one hub chosen and a different one connected. + unnamed = not wanted_id and not wanted_name + + if unnamed: + chosen = manager.selection.name + wanted_name = chosen + + # A name, typed or chosen, is a hub already connected before it is anything + # to scan for: a connected hub has stopped advertising, so the scan would + # pass it by and connect another hub of the same name instead. + if wanted_name and not wanted_id: + try: + connection = manager.resolve(str(wanted_name)) + except HubNotFoundError: + connection = None + + if connection is not None and (handed := _hand_back(connection, params)): + return handed + elif unnamed and manager.connected: # Connecting is what a user types to be sure they have a hub, so being # asked when there already is one is not an error and not a reason to # go looking for a second. It would look like one, too: a connected hub # has stopped advertising, so the scan would find nothing and the user # would be told to check that their hub is switched on. - return _hub_json(manager.get(None)) + # + # The one a command would act on, unless another route was asked for + # and some other connected hub is on it. + wanted_transport = _transport(params) + connection = manager.get(None) + + def on(candidate: HubConnection) -> bool: + return ( + candidate.info is not None + and candidate.info.transport == wanted_transport + ) + + if wanted_transport is not None and not on(connection): + connection = next(filter(on, manager.connected), connection) + + if handed := _hand_back(connection, params): + return handed + + # Anything short of an id has to come down to one hub, or it is a guess. + # With nothing named that is plainly so; with a name it is too, because + # every hub flashed without one is called Pybricks Hub, so in a classroom + # a name -- typed, or remembered by pb use -- can match half the room. + # Hubs are told apart within a transport only, because one hub on a cable + # and over Bluetooth has two ids and nothing here can tell that it is the + # same hub. + refuse_several = not wanted_id + found: dict[str, DeviceInfo] = {} + # Whether a hub has been heard on a transport that hears them, rather than + # only listed as paired. + heard = False + # When the search would have ended had a paired hub not capped it. Kept + # rather than read at the start, because waiting on a permission dialog + # moves the end later until something is found. + uncapped: float | None = None scan_filter = ScanFilter( name=str(wanted_name) if wanted_name else None, @@ -494,20 +705,46 @@ async def hub_connect(session: Session, params: dict[str, Any]) -> dict[str, Any if wanted_id and candidate.id != wanted_id: continue + found[candidate.id] = candidate + if device is None or preference_rank( candidate.transport ) < preference_rank(device.transport): device = candidate - if preference_rank(device.transport) == 0: + if preference_rank(device.transport) == 0 and not refuse_several: # Nothing can beat it, so do not wait out the grace. + # Short of an id, though, another hub may be on the + # next port, and only waiting can tell. break # Something matched, so stop waiting for a hub and start - # waiting for a better route to the one already found. - looking.deadline = min( - looking.deadline, anyio.current_time() + PREFERENCE_SECONDS - ) + # waiting for a better route to the one already found, and, + # short of an id, for any other hub that matches as well. + now = anyio.current_time() + + if not refuse_several: + looking.deadline = min( + looking.deadline, now + PREFERENCE_SECONDS + ) + elif candidate.transport == "rfcomm": + # Paired, which is not the same as there: give the + # transports that hear hubs time to hear one. + if not heard: + if uncapped is None: + uncapped = looking.deadline + + looking.deadline = min( + looking.deadline, now + PAIRED_SECONDS + ) + elif not heard: + # The first hub actually heard starts the wait afresh, + # whatever a paired one had set it to. + heard = True + looking.deadline = min( + looking.deadline if uncapped is None else uncapped, + now + AMBIGUITY_SECONDS, + ) tg.cancel_scope.cancel() @@ -515,9 +752,40 @@ async def hub_connect(session: Session, params: dict[str, Any]) -> dict[str, Any # As for a scan: what the transports say is another search's unless # this one got the radio. if not started.is_set(): - raise JsonRpcError(ErrorCode.HUB_NOT_FOUND, "no hub found") + raise _not_found(chosen) + + raise _found_nothing(manager, chosen) + + present = _present(found.values()) + + if refuse_several and _several(present): + # Bounded by AMBIGUITY_SECONDS after the first hub heard on a transport + # that hears them, which is what a lone hub costs extra to connect to, + # or by PAIRED_SECONDS when only paired hubs were found. A second hub + # that has not advertised within it is missed, which is no worse than + # before this check, and so is a second USB hub whose port takes longer + # than that to answer the first time it is opened. + devices = [_device_json(d) for d in present] + + if wanted_name: + # Named in the data as well, because the remedy is different: no + # choosing by name can tell these apart, only renaming one can. + raise JsonRpcError( + ErrorCode.HUB_AMBIGUOUS, + f"more than one hub named {wanted_name!r} found", + {"devices": devices, "name": str(wanted_name)}, + ) - raise _found_nothing(manager) + names = ", ".join(sorted({d.name for d in present})) + raise JsonRpcError( + ErrorCode.HUB_AMBIGUOUS, + f"more than one hub found: {names}", + {"devices": devices}, + ) + + # The best route among the hubs heard, which is the hub found when there was + # only the one, reached the quickest way. + device = min(present, key=lambda found: preference_rank(found.transport)) try: with anyio.fail_after(CONNECT_SECONDS): @@ -538,7 +806,7 @@ async def hub_connect(session: Session, params: dict[str, Any]) -> dict[str, Any except (HubNotFoundError, HubAlreadyConnectedError, HubDisconnectedError) as exc: raise as_wire_error(exc) from exc - return _hub_json(manager.get(device.id)) + return _connected_json(manager.get(device.id), already=False) async def _stop_builtin_program(connection: HubConnection) -> None: diff --git a/packages/pb-service/tests/test_ble_scan.py b/packages/pb-service/tests/test_ble_scan.py new file mode 100644 index 0000000..2983a6e --- /dev/null +++ b/packages/pb-service/tests/test_ble_scan.py @@ -0,0 +1,133 @@ +# SPDX-License-Identifier: MIT +# Copyright (c) 2026 The Pybricks Authors + +"""What a Bluetooth scan reports, from what the radio hears. + +bleak is replaced by a scanner that replays advertisements, so these run +without a radio and say exactly which packet arrived when. +""" + +from __future__ import annotations + +from collections.abc import AsyncGenerator, Sequence +from types import TracebackType +from typing import Any + +import anyio +import pytest +from bleak.backends.device import BLEDevice +from bleak.backends.scanner import AdvertisementData + +from pb_service.hub import ble +from pb_service.hub import protocol as p +from pb_service.hub.transport import DeviceInfo, ScanFilter + +pytestmark = pytest.mark.anyio + +CITY_HUB_PNP_ID = bytes([1, 0x97, 0x03, 0x41, 0x00, 0x00, 0x00]) +ADDRESS = "ED:2F:CF:0F:14:39" +NAME = "Pybricks Hub" + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +def _heard(*, scan_response: bool) -> tuple[BLEDevice, AdvertisementData]: + """One sighting of a City hub, with or without its scan response merged in.""" + service_data = {p.PNP_ID_UUID: CITY_HUB_PNP_ID} if scan_response else {} + advertisement = AdvertisementData( + local_name=NAME, + manufacturer_data={}, + service_data=service_data, + service_uuids=[p.PYBRICKS_SERVICE_UUID], + tx_power=None, + rssi=-50, + platform_data=(), + ) + return BLEDevice(ADDRESS, NAME, None), advertisement + + +class _ReplayingScanner: + """Stands in for bleak's scanner, hearing what it is given, in order. + + Each entry is how long to wait before hearing it, then what is heard. + """ + + script: Sequence[tuple[float, tuple[BLEDevice, AdvertisementData]]] = () + + def __init__(self, **_kwargs: Any) -> None: + pass + + async def __aenter__(self) -> _ReplayingScanner: + return self + + async def __aexit__( + self, + _type: type[BaseException] | None, + _value: BaseException | None, + _traceback: TracebackType | None, + ) -> None: + pass + + async def advertisement_data( + self, + ) -> AsyncGenerator[tuple[BLEDevice, AdvertisementData], None]: + for delay, heard in self.script: + await anyio.sleep(delay) + yield heard + await anyio.sleep_forever() + + +async def _first_report( + monkeypatch: pytest.MonkeyPatch, + script: Sequence[tuple[float, tuple[BLEDevice, AdvertisementData]]], +) -> DeviceInfo: + monkeypatch.setattr(_ReplayingScanner, "script", script) + monkeypatch.setattr(ble, "BleakScanner", _ReplayingScanner) + with anyio.fail_after(5): + async for info in ble.BleHubTransport().discover(ScanFilter()): + return info + raise AssertionError("the scan ended without reporting anything") + + +async def test_a_hub_is_first_reported_with_its_type( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The advertisement comes first and the scan response, which says what + # kind of hub this is, a moment later. Only the whole of it is reported. + info = await _first_report( + monkeypatch, + [ + (0, _heard(scan_response=False)), + (0.05, _heard(scan_response=True)), + ], + ) + + assert info.hub_type == "City hub" + + +async def test_a_hub_that_never_says_its_type_is_logged_not_reported( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + # Every Pybricks firmware sends its PnP ID, so one that does not has a bug + # worth hearing about, once, rather than a hub to list without its type. + monkeypatch.setattr(ble, "SCAN_RESPONSE_SECONDS", 0.2) + monkeypatch.setattr( + _ReplayingScanner, + "script", + [(0, _heard(scan_response=False))] + [(0.05, _heard(scan_response=False))] * 10, + ) + monkeypatch.setattr(ble, "BleakScanner", _ReplayingScanner) + + reported: list[DeviceInfo] = [] + with anyio.move_on_after(1): + async for info in ble.BleHubTransport().discover(ScanFilter()): + reported.append(info) + + assert reported == [] + warnings = [r for r in caplog.records if r.levelname == "WARNING"] + assert len(warnings) == 1 + assert ADDRESS in warnings[0].getMessage() + assert "firmware bug" in warnings[0].getMessage() diff --git a/tests/e2e/test_commands.py b/tests/e2e/test_commands.py index 5b70a9a..6dc820b 100644 --- a/tests/e2e/test_commands.py +++ b/tests/e2e/test_commands.py @@ -18,26 +18,28 @@ import sys import uuid -from collections.abc import AsyncGenerator +from collections.abc import AsyncGenerator, AsyncIterator from pathlib import Path import aio_rfcomm import anyio import pytest +import pb_client import pb_service.methods.hub import pb_service.methods.program # pyright: ignore[reportUnusedImport] # Imported to register the RPC methods. import pb_service.methods.service # pyright: ignore[reportUnusedImport] import pb_service.methods.stdio # pyright: ignore[reportUnusedImport] -from pb_cli import errors +from pb_cli import errors, keys, picker from pb_cli.commands import hub as hub_commands from pb_cli.commands import program as program_commands from pb_cli.commands import service as service_commands from pb_core.ipc import Endpoint from pb_service import service as service_module from pb_service.hub import protocol as p +from pb_service.hub.combined import CombinedTransport from pb_service.hub.fake import FakeHub, FakeHubTransport from pb_service.hub.rfcomm.fake import FakePairedHub, radio, switch from pb_service.hub.rfcomm.transport import RfcommHubTransport @@ -239,6 +241,230 @@ async def test_a_chosen_hub_is_what_a_command_acts_on( assert listed.startswith("*") +SPARE_NAME = "Spare Hub" + + +@pytest.fixture +async def two_hubs(private: Endpoint) -> AsyncGenerator[None, None]: + """A service with two hubs switched on, as in a classroom.""" + transport = FakeHubTransport( + FakeHub(name=HUB_NAME, address="00:11:22:33:44:55"), + FakeHub(name=SPARE_NAME, address="66:77:88:99:AA:BB"), + ) + + async with service_module.run_service(private, idle_timeout=0, transport=transport): + yield + + +async def test_connect_goes_to_the_hub_chosen_with_use( + two_hubs: None, capsys: pytest.CaptureFixture[str] +) -> None: + # pybricks/support#2866. + await hub_commands.use_cmd(hub=SPARE_NAME) + capsys.readouterr() + + assert await hub_commands.connect_cmd() == errors.EXIT_OK + assert f"Connected to {SPARE_NAME}" in capsys.readouterr().err + + +async def test_connect_says_when_the_hub_already_was( + two_hubs: None, capsys: pytest.CaptureFixture[str] +) -> None: + # Succeeding is right, so that connect can be run to be sure of a hub, but + # claiming to have connected would hide that no other hub was looked for. + await hub_commands.use_cmd(hub=SPARE_NAME) + await hub_commands.connect_cmd() + capsys.readouterr() + + assert await hub_commands.connect_cmd() == errors.EXIT_OK + assert f"Already connected to {SPARE_NAME}" in capsys.readouterr().err + + +async def test_connect_asks_which_when_several_hubs_are_on( + two_hubs: None, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + offered: list[str] = [] + + async def choose( + err: object, devices: AsyncIterator[pb_client.DeviceInfo], *_: object + ) -> pb_client.DeviceInfo: + async for device in devices: + offered.append(device.name) + if device.name == SPARE_NAME: + return device + + raise AssertionError("the spare hub was never offered") + + monkeypatch.setattr(keys, "keys_available", lambda: True) + monkeypatch.setattr(picker, "choose_hub", choose) + + assert await hub_commands.connect_cmd() == errors.EXIT_OK + captured = capsys.readouterr() + assert "More than one hub" in captured.err + assert f"Connected to {SPARE_NAME}" in captured.err + assert SPARE_NAME in offered + assert captured.out == "" + + +async def test_the_picker_leaves_out_a_paired_hub_the_service_did( + private: Endpoint, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The service did not count the EV3 in the drawer, so offering it would be + # offering a hub that is not there. + transport = CombinedTransport( + RfcommHubTransport( + radio(FakePairedHub(name="Ostrich (MINDSTORMS EV3)", reachable=False)) + ), + FakeHubTransport( + FakeHub(name=HUB_NAME, address="00:11:22:33:44:55"), + FakeHub(name=SPARE_NAME, address="66:77:88:99:AA:BB"), + ), + ) + offered: set[str] = set() + + async def choose( + err: object, devices: AsyncIterator[pb_client.DeviceInfo], *_: object + ) -> pb_client.DeviceInfo | None: + with anyio.move_on_after(0.5): + async for device in devices: + offered.add(device.name) + + return None + + monkeypatch.setattr(keys, "keys_available", lambda: True) + monkeypatch.setattr(picker, "choose_hub", choose) + + async with service_module.run_service(private, idle_timeout=0, transport=transport): + assert await hub_commands.connect_cmd() == errors.EXIT_OK + + assert "More than one hub was found" in capsys.readouterr().err + assert offered == {HUB_NAME, SPARE_NAME} + + +async def test_connect_without_a_terminal_refuses_to_guess( + two_hubs: None, capsys: pytest.CaptureFixture[str] +) -> None: + assert await hub_commands.connect_cmd() != errors.EXIT_OK + captured = capsys.readouterr() + assert "More than one hub found" in captured.err + assert "pb use" in captured.err + assert captured.out == "" + + +async def test_a_chosen_hub_not_found_says_how_to_choose_another( + two_hubs: None, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + # A choice outlives the hub it named, so the way out of an old one is said. + monkeypatch.setattr(pb_service.methods.hub, "DEFAULT_SCAN_SECONDS", 0.3) + await hub_commands.use_cmd(hub="Retired Hub") + capsys.readouterr() + + assert await hub_commands.connect_cmd() != errors.EXIT_OK + said = " ".join(capsys.readouterr().err.split()) + assert "The chosen hub 'Retired Hub' was not found" in said + assert "Switch the hub on" in said + assert "choose it with pb use" in said + + +async def test_a_typed_hub_not_found_does_not_mention_choosing( + two_hubs: None, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Nothing was chosen, so there is no choice to undo. + monkeypatch.setattr(pb_service.methods.hub, "DEFAULT_SCAN_SECONDS", 0.3) + + assert await hub_commands.connect_cmd(hub="Retired Hub") != errors.EXIT_OK + said = " ".join(capsys.readouterr().err.split()) + assert "Switch the hub on" in said + assert "pb use" not in said + + +async def test_a_hub_name_is_printed_as_it_was_written( + private: Endpoint, capsys: pytest.CaptureFixture[str] +) -> None: + # A name is the user's to write, and rich reads square brackets as markup. + name = "Robot [red] [/b]" + transport = FakeHubTransport(FakeHub(name=name, address="00:11:22:33:44:55")) + + async with service_module.run_service(private, idle_timeout=0, transport=transport): + await hub_commands.use_cmd(hub=name) + capsys.readouterr() + + assert await hub_commands.connect_cmd() == errors.EXIT_OK + + assert f"Connected to {name}" in capsys.readouterr().err + + +@pytest.fixture +async def twins_and_spare(private: Endpoint) -> AsyncGenerator[None, None]: + """Two hubs flashed without a name, and one that was given its own.""" + transport = FakeHubTransport( + FakeHub(name=HUB_NAME, address="00:11:22:33:44:55"), + FakeHub(name=HUB_NAME, address="66:77:88:99:AA:BB"), + FakeHub(name=SPARE_NAME, address="12:34:56:78:9A:BC"), + ) + + async with service_module.run_service(private, idle_timeout=0, transport=transport): + yield + + +async def test_connect_asks_which_of_the_hubs_with_the_chosen_name( + twins_and_spare: None, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + offered: dict[str, str] = {} + + async def choose( + err: object, devices: AsyncIterator[pb_client.DeviceInfo], *_: object + ) -> pb_client.DeviceInfo: + # Long enough to hear every hub there is, since what matters is the + # one that is not offered. + with anyio.move_on_after(0.5): + async for device in devices: + offered[device.id] = device.name + + return pb_client.DeviceInfo( + id=sorted(offered)[1], + name=HUB_NAME, + address="", + rssi=None, + transport="fake", + ) + + monkeypatch.setattr(keys, "keys_available", lambda: True) + monkeypatch.setattr(picker, "choose_hub", choose) + + await hub_commands.use_cmd(hub=HUB_NAME) + capsys.readouterr() + + assert await hub_commands.connect_cmd() == errors.EXIT_OK + captured = capsys.readouterr() + assert f"More than one hub called {HUB_NAME}" in captured.err + assert f"Connected to {HUB_NAME}" in captured.err + # Only the hubs answering to the name: the spare is not what was asked for. + assert sorted(offered.values()) == [HUB_NAME, HUB_NAME] + + +async def test_a_shared_name_without_a_terminal_says_to_rename_one( + twins_and_spare: None, capsys: pytest.CaptureFixture[str] +) -> None: + assert await hub_commands.connect_cmd(hub=HUB_NAME) != errors.EXIT_OK + captured = capsys.readouterr() + assert f"More than one hub named '{HUB_NAME}' found" in captured.err + # Not "say which with --hub": that is what was just done. + assert "same name" in captured.err + assert "--hub" not in captured.err + assert captured.out == "" + + async def test_scan_lists_what_it_hears( service: FakeHub, capsys: pytest.CaptureFixture[str] ) -> None: diff --git a/tests/e2e/test_hub_lifecycle.py b/tests/e2e/test_hub_lifecycle.py index 0a4b6e3..f6242cc 100644 --- a/tests/e2e/test_hub_lifecycle.py +++ b/tests/e2e/test_hub_lifecycle.py @@ -12,7 +12,8 @@ import sys import uuid -from collections.abc import AsyncGenerator, Iterator +from collections.abc import AsyncGenerator, Callable, Iterator +from contextlib import AbstractAsyncContextManager from pathlib import Path import aio_rfcomm @@ -34,7 +35,12 @@ from pb_service.hub.fake import FakeHub, FakeHubTransport from pb_service.hub.rfcomm.fake import FakePairedHub, radio, switch from pb_service.hub.rfcomm.transport import RfcommHubTransport -from pb_service.hub.transport import UnavailableDevice +from pb_service.hub.transport import ( + DeviceInfo, + HubLink, + ScanFilter, + UnavailableDevice, +) pytestmark = pytest.mark.anyio @@ -572,6 +578,498 @@ async def test_a_hub_can_be_chosen_before_it_is_connected( assert (await service.hub_info()).name == FIRST +async def test_connecting_with_no_hub_named_connects_the_chosen_one( + service_at: Endpoint, +) -> None: + # pybricks/support#2866: choosing a hub and then connecting reached + # whichever hub advertised first, which need not be the one chosen. + async with pb_client.connect(service_at, autostart=False) as service: + await service.use_hub(SECOND) + info = await service.connect_hub() + + assert info.name == SECOND + + +async def test_the_chosen_hub_is_connected_even_with_another_connected( + service_at: Endpoint, +) -> None: + # Handing back the hub already connected instead would leave one hub + # chosen and another connected, and commands going to the wrong one. + async with pb_client.connect(service_at, autostart=False) as service: + await service.connect_hub(name=FIRST) + await service.use_hub(SECOND) + info = await service.connect_hub() + hubs, _ = await service.list_hubs() + + assert info.name == SECOND + assert {hub.name for hub in hubs} == {FIRST, SECOND} + + +async def test_a_chosen_hub_already_connected_is_handed_back( + service_at: Endpoint, +) -> None: + # It has stopped advertising, so looking for it would report it missing. + async with pb_client.connect(service_at, autostart=False) as service: + first = await service.connect_hub(name=SECOND) + await service.use_hub(SECOND) + again = await service.connect_hub() + + assert again.id == first.id + assert not first.already_connected + assert again.already_connected + + +async def test_a_chosen_hub_that_is_switched_off_is_named_as_missing( + service_at: Endpoint, monkeypatch: pytest.MonkeyPatch +) -> None: + # Two other hubs are switched on, and neither is taken instead: the user + # chose, and connecting to a hub they did not choose is the bug. + monkeypatch.setattr(pb_service.methods.hub, "DEFAULT_SCAN_SECONDS", 0.3) + + async with pb_client.connect(service_at, autostart=False) as service: + await service.use_hub("Some Other Hub") + + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub() + + hubs, _ = await service.list_hubs() + + assert caught.value.code == ErrorCode.HUB_NOT_FOUND + assert "Some Other Hub" in str(caught.value) + assert hubs == [] + + +async def test_several_hubs_and_nothing_chosen_is_refused( + service_at: Endpoint, +) -> None: + # In a classroom the first hub to advertise is usually somebody else's. + async with pb_client.connect(service_at, autostart=False) as service: + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub() + + hubs, _ = await service.list_hubs() + + assert caught.value.code == ErrorCode.HUB_AMBIGUOUS + offered = {device["name"] for device in caught.value.data["devices"]} + assert offered == {FIRST, SECOND} + assert hubs == [] + + +@pytest.fixture +async def twins_at(endpoint: Endpoint) -> AsyncGenerator[Endpoint, None]: + """Two hubs flashed without a name, so both answer to the default one.""" + transport = FakeHubTransport( + FakeHub(name=FIRST, address="00:11:22:33:44:55"), + FakeHub(name=FIRST, address="66:77:88:99:AA:BB"), + ) + + async with service_module.run_service( + endpoint, idle_timeout=0, transport=transport + ): + yield endpoint + + +async def test_a_chosen_name_two_hubs_share_is_refused(twins_at: Endpoint) -> None: + # Choosing by name is no choice at all when every hub has the same one. + async with pb_client.connect(twins_at, autostart=False) as service: + await service.use_hub(FIRST) + + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub() + + hubs, _ = await service.list_hubs() + + assert caught.value.code == ErrorCode.HUB_AMBIGUOUS + assert caught.value.data["name"] == FIRST + assert len(caught.value.data["devices"]) == 2 + assert hubs == [] + + +async def test_a_name_given_that_two_hubs_share_is_refused(twins_at: Endpoint) -> None: + async with pb_client.connect(twins_at, autostart=False) as service: + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub(name=FIRST) + + assert caught.value.code == ErrorCode.HUB_AMBIGUOUS + assert caught.value.data["name"] == FIRST + + +async def test_an_id_tells_hubs_with_one_name_apart(twins_at: Endpoint) -> None: + async with pb_client.connect(twins_at, autostart=False) as service: + devices = await service.scan(seconds=0.3) + info = await service.connect_hub(hub_id=devices[1].id) + + assert info.id == devices[1].id + + +async def test_a_name_given_for_a_connected_hub_hands_it_back( + twins_at: Endpoint, +) -> None: + # The connected twin has stopped advertising, so a scan for the name would + # find only the other one and connect it too, as if it were the one meant. + async with pb_client.connect(twins_at, autostart=False) as service: + devices = await service.scan(seconds=0.3) + first = await service.connect_hub(hub_id=devices[0].id) + again = await service.connect_hub(name=FIRST) + hubs, _ = await service.list_hubs() + + assert again.id == first.id + assert again.already_connected + assert [hub.id for hub in hubs] == [first.id] + + +async def test_a_twin_heard_late_is_still_noticed( + endpoint: Endpoint, monkeypatch: pytest.MonkeyPatch +) -> None: + # Measured on real hubs: one advertising every 0.8 s or so is first heard + # that long after the other, and deciding at the first one heard connected + # to whichever that was without asking. The wait is the point here, so it + # is the real one rather than the root conftest's. + monkeypatch.setattr(pb_service.methods.hub, "AMBIGUITY_SECONDS", 1.0) + transport = FakeHubTransport( + FakeHub(name=FIRST, address="00:11:22:33:44:55"), + FakeHub(name=FIRST, address="66:77:88:99:AA:BB", heard_after=0.8), + ) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub(name=FIRST) + + assert caught.value.code == ErrorCode.HUB_AMBIGUOUS + assert len(caught.value.data["devices"]) == 2 + + +class _PluggedIn: + """Hubs on cables, one per port, heard a moment into a search. + + Only as much of a transport as a search needs: these hubs are refused + before anything opens them. + """ + + scheme = "usb" + unavailable: tuple[UnavailableDevice, ...] = () + + def __init__(self, *names: str, heard_after: float = 0.0) -> None: + self.on_disconnect: Callable[[str], None] | None = None + self._names = names + self._heard_after = heard_after + + async def discover( + self, scan_filter: ScanFilter + ) -> AsyncGenerator[DeviceInfo, None]: + await anyio.sleep(self._heard_after) + + for number, name in enumerate(self._names): + port = f"/dev/ttyACM{number}" + + if scan_filter.name in (None, name): + yield DeviceInfo( + id=f"usb:{port}", + name=name, + address=port, + transport=self.scheme, + ) + + # A port takes a moment to answer the first time it is opened. + await anyio.sleep(0.01) + + await anyio.sleep_forever() + + def open(self, device_id: str) -> AbstractAsyncContextManager[HubLink]: + raise ConnectionError(f"not expected to open {device_id}") + + +async def test_a_cable_does_not_hide_another_hub_heard_first( + endpoint: Endpoint, +) -> None: + # A hub on a cable used to end the search at once, and only two hubs on one + # transport counted as two. So with one hub heard over the air and another + # plugged in, the one on the cable was connected without asking. + transport = CombinedTransport( + _PluggedIn(FIRST, heard_after=0.02), + FakeHubTransport(FakeHub(name=SECOND, address="66:77:88:99:AA:BB")), + ) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub() + + assert caught.value.code == ErrorCode.HUB_AMBIGUOUS + assert {d["name"] for d in caught.value.data["devices"]} == {FIRST, SECOND} + + +async def test_two_hubs_on_cables_are_two_hubs(endpoint: Endpoint) -> None: + # USB is the best route there is, so finding a hub on it used to end the + # search before the next port was read. + transport = CombinedTransport(_PluggedIn(FIRST, FIRST)) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub() + + assert caught.value.code == ErrorCode.HUB_AMBIGUOUS + assert len(caught.value.data["devices"]) == 2 + + +async def test_a_paired_hub_switched_off_is_not_another_hub( + endpoint: Endpoint, +) -> None: + # RFCOMM lists what the computer is paired with, switched on or not, so an + # EV3 in a drawer must not make the hub on the desk ambiguous. + bluetooth = radio(FakePairedHub(address=EV3, reachable=False)) + transport = CombinedTransport( + RfcommHubTransport(bluetooth), + FakeHubTransport(FakeHub(name=SECOND, address="66:77:88:99:AA:BB")), + ) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + info = await service.connect_hub() + + assert info.name == SECOND + + +async def test_a_connected_hub_asked_for_exclusively_is_refused( + service_at: Endpoint, +) -> None: + async with pb_client.connect(service_at, autostart=False) as service: + await service.connect_hub(name=FIRST) + + with pytest.raises(JsonRpcError) as caught: + await service._peer.call( # pyright: ignore[reportPrivateUsage] + "hub.connect", {"name": FIRST, "exclusive": True} + ) + + assert caught.value.code == ErrorCode.HUB_ALREADY_CONNECTED + + +async def test_a_connected_hub_asked_for_by_another_route_is_looked_for( + endpoint: Endpoint, monkeypatch: pytest.MonkeyPatch +) -> None: + # Which route is in use decides how quick everything after it is, so a hub + # connected one way and asked for another is not the hub asked for. + monkeypatch.setattr(pb_service.methods.hub, "DEFAULT_SCAN_SECONDS", 0.3) + # Combined, because that is what keeps a search to the transport asked for. + transport = CombinedTransport( + FakeHubTransport(FakeHub(name=FIRST, address="00:11:22:33:44:55")) + ) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + await service.connect_hub(name=FIRST) + + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub(name=FIRST, transport="usb") + + assert caught.value.code == ErrorCode.HUB_NOT_FOUND + + +@pytest.fixture +def drawer_and_desk(monkeypatch: pytest.MonkeyPatch) -> CombinedTransport: + """A paired EV3 switched off, and two hubs heard a little apart. + + The waits are scaled down from the real ones but keep their proportions: + the first hub heard comes after the paired one is listed, and the second + after AMBIGUITY_SECONDS has passed since the paired one was listed, though + not since the first hub was heard. + """ + monkeypatch.setattr(pb_service.methods.hub, "AMBIGUITY_SECONDS", 0.6) + monkeypatch.setattr(pb_service.methods.hub, "PAIRED_SECONDS", 2.0) + + # 0.1 s either side of the wait that a paired hub would have started, and + # 0.2 s inside the one the first hub heard starts. + return CombinedTransport( + RfcommHubTransport(radio(FakePairedHub(address=EV3, reachable=False))), + FakeHubTransport( + FakeHub(name=FIRST, address="00:11:22:33:44:55", heard_after=0.3), + FakeHub(name=SECOND, address="66:77:88:99:AA:BB", heard_after=0.7), + ), + ) + + +async def test_a_paired_hub_does_not_cut_short_the_wait_for_another( + endpoint: Endpoint, drawer_and_desk: CombinedTransport +) -> None: + # The paired EV3 is listed at once. Had that started the wait, it would + # have ended before the second hub was heard, and the first been taken. + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=drawer_and_desk), + pb_client.connect(endpoint, autostart=False) as service, + ): + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub() + + assert caught.value.code == ErrorCode.HUB_AMBIGUOUS + assert {d["name"] for d in caught.value.data["devices"]} == {FIRST, SECOND} + + +async def test_a_hub_heard_after_the_wait_a_paired_one_would_start_is_found( + endpoint: Endpoint, monkeypatch: pytest.MonkeyPatch +) -> None: + # Had the paired EV3 started the wait, it would have ended holding only + # the EV3, and tried to connect to a hub in a drawer. + monkeypatch.setattr(pb_service.methods.hub, "AMBIGUITY_SECONDS", 0.6) + monkeypatch.setattr(pb_service.methods.hub, "PAIRED_SECONDS", 2.0) + transport = CombinedTransport( + RfcommHubTransport(radio(FakePairedHub(address=EV3, reachable=False))), + FakeHubTransport( + FakeHub(name=SECOND, address="66:77:88:99:AA:BB", heard_after=0.9) + ), + ) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + info = await service.connect_hub() + + assert info.name == SECOND + + +async def test_a_permission_dialog_does_not_cut_short_the_wait_for_another( + endpoint: Endpoint, monkeypatch: pytest.MonkeyPatch +) -> None: + # Waiting on the dialog moves the end of the search later. Had the wait for + # a second hub been bounded by the end as it was at the start, the first + # hub heard after that would have ended the search at once. + monkeypatch.setattr(pb_service.methods.hub, "DEFAULT_SCAN_SECONDS", 0.3) + monkeypatch.setattr(pb_service.methods.hub, "AMBIGUITY_SECONDS", 0.5) + monkeypatch.setattr(pb_service.methods.hub, "PERMISSION_SECONDS", 3.0) + asking = radio( + unavailable="macOS is asking whether this program may use Bluetooth", + reason=aio_rfcomm.Availability.AWAITING_PERMISSION, + ) + transport = CombinedTransport( + RfcommHubTransport(asking), + FakeHubTransport( + FakeHub(name=FIRST, address="00:11:22:33:44:55", heard_after=0.8), + FakeHub(name=SECOND, address="66:77:88:99:AA:BB", heard_after=0.9), + ), + ) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub() + + assert caught.value.code == ErrorCode.HUB_AMBIGUOUS + + +async def test_nothing_named_finds_the_connected_hub_on_the_route_asked_for( + endpoint: Endpoint, +) -> None: + # The hub a command would act on is the one connected last, but asked for + # another route, a connected hub on it is the one meant. + bluetooth = radio(FakePairedHub(address=EV3)) + transport = CombinedTransport( + RfcommHubTransport(bluetooth), + FakeHubTransport(FakeHub(name=SECOND, address="66:77:88:99:AA:BB")), + ) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + ev3 = await service.connect_hub(transport="rfcomm") + await service.connect_hub(name=SECOND) + again = await service.connect_hub(transport="rfcomm") + + assert again.id == ev3.id + assert again.already_connected + + +async def test_nothing_named_and_a_route_asked_for_keeps_the_hub_commands_use( + service_at: Endpoint, +) -> None: + # Two hubs connected the same way: asking for that way is no reason to + # hand back a different one from the hub the next command will act on. + async with pb_client.connect(service_at, autostart=False) as service: + await service.connect_hub(name=FIRST) + second = await service.connect_hub(name=SECOND) + again = await service.connect_hub(transport="fake") + + assert again.id == second.id + + +async def test_a_connected_id_with_another_route_asked_for_is_handed_back( + service_at: Endpoint, +) -> None: + # An id names its route too, so no hub on another one could have it, and + # searching there would only end in "no hub found" with the hub connected. + async with pb_client.connect(service_at, autostart=False) as service: + first = await service.connect_hub(name=FIRST) + + with anyio.fail_after(1): + again = await service.connect_hub(hub_id=first.id, transport="rfcomm") + + assert again.id == first.id + assert again.already_connected + + +async def test_nothing_named_and_another_route_asked_for_is_looked_for( + endpoint: Endpoint, monkeypatch: pytest.MonkeyPatch +) -> None: + # As for a name: a hub connected one way is not one asked for another. + monkeypatch.setattr(pb_service.methods.hub, "DEFAULT_SCAN_SECONDS", 0.3) + transport = CombinedTransport( + FakeHubTransport(FakeHub(name=FIRST, address="00:11:22:33:44:55")) + ) + + async with ( + service_module.run_service(endpoint, idle_timeout=0, transport=transport), + pb_client.connect(endpoint, autostart=False) as service, + ): + await service.connect_hub() + + with pytest.raises(JsonRpcError) as caught: + await service.connect_hub(transport="usb") + + assert caught.value.code == ErrorCode.HUB_NOT_FOUND + + +async def test_nothing_named_and_exclusive_refuses_a_connected_hub( + service_at: Endpoint, +) -> None: + async with pb_client.connect(service_at, autostart=False) as service: + await service.connect_hub(name=FIRST) + + with pytest.raises(JsonRpcError) as caught: + await service._peer.call( # pyright: ignore[reportPrivateUsage] + "hub.connect", {"exclusive": True} + ) + + assert caught.value.code == ErrorCode.HUB_ALREADY_CONNECTED + + +async def test_the_only_hub_switched_on_needs_no_name(endpoint: Endpoint) -> None: + hub = FakeHub(name=FIRST, address="00:11:22:33:44:55") + + async with ( + service_module.run_service( + endpoint, idle_timeout=0, transport=FakeHubTransport(hub) + ), + pb_client.connect(endpoint, autostart=False) as service, + ): + info = await service.connect_hub() + + assert info.name == FIRST + + async def test_an_id_for_a_hub_that_is_not_connected_is_refused( service_at: Endpoint, ) -> None: