Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
7 changes: 6 additions & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
17 changes: 17 additions & 0 deletions packages/pb-cli/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
144 changes: 128 additions & 16 deletions packages/pb-cli/src/pb_cli/commands/hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand All @@ -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.
Expand All @@ -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
Expand All @@ -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


Expand Down
61 changes: 61 additions & 0 deletions packages/pb-cli/src/pb_cli/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."
Expand Down Expand Up @@ -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.

Expand Down Expand Up @@ -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)

Expand Down
10 changes: 10 additions & 0 deletions packages/pb-client/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions packages/pb-client/src/pb_client/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__``.
Expand Down Expand Up @@ -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,
)
Loading
Loading