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
4 changes: 4 additions & 0 deletions packages/pb-service/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ Notable changes to `pybricks-service`. The format is based on

### Fixed

- Input too big for the buffer of a hub on Pybricks 4.0 is refused at once,
saying to update the firmware, rather than after 10 s as a hub not reading
its input. 4.0 takes 20 bytes at a time, or 63 on
hubs with USB, whatever write size it reports.
- 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.
Expand Down
2 changes: 1 addition & 1 deletion packages/pb-service/src/pb_service/hub/fake.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ class FakeHub:
name: str = "Fake Hub"
address: str = "AA:BB:CC:DD:EE:FF"
profile: p.Version = (1, 5, 0)
firmware: str = "4.0.1"
firmware: str = "4.1.3"
hub_type: int = p.HubType.TECHNIC_LARGE_HUB
variant: int = 0
"""Product id and version, as the PnP ID reports them."""
Expand Down
83 changes: 77 additions & 6 deletions packages/pb-service/src/pb_service/methods/stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,11 @@
on the hub rather than here -- which is what :data:`STDIN_PATIENCE_SECONDS`
eventually says.

The one exception is firmware 4.0, whose buffer is smaller than the write size
it reports: a write bigger than the buffer is refused for good, which is a
firmware bug fixed in 4.1. That is said at once, and not worked around; see
:data:`FIRMWARE_4_0_STDIN_BYTES`.

**Nothing here adapts the write size, and that is deliberate.** It used to
halve on a refusal that lasted, on the theory that a long refusal meant the
buffer was smaller than advertised, remembering where it settled. The theory
Expand All @@ -45,7 +50,7 @@
from __future__ import annotations

import logging
from typing import Any
from typing import Any, Final

import anyio

Expand All @@ -59,7 +64,7 @@
from pb_core.protocol import HUB_STATE, HUB_STATUS, HUB_STDOUT
from pb_service.errors import hub_errors
from pb_service.hub import protocol as p
from pb_service.hub.connection import HubConnection
from pb_service.hub.connection import HubConnection, HubInfo
from pb_service.hub.events import Channel, StateEvent, StatusEvent, StdoutEvent
from pb_service.methods import method, require
from pb_service.methods.hub import hub_of, report_json, status_json
Expand Down Expand Up @@ -179,7 +184,8 @@ async def _write_stdin(connection: HubConnection, data: bytes) -> int:
over and over at that size until the hub takes it. **The size never
changes**, because a refusal carries no information about it: the firmware
tests the buffer's *free space*, which is whatever the reader on the hub has
not read yet, so a refusal says only that nothing has read lately. See the
not read yet, so a refusal says only that nothing has read lately -- except
on firmware 4.0, where a piece bigger than its buffer never fits. See the
module docstring for the version of this that tried to be clever and what it
cost.

Expand All @@ -197,22 +203,41 @@ async def _write_stdin(connection: HubConnection, data: bytes) -> int:

Raises:
JsonRpcError: If the hub is not ready, or stayed busy for longer than
its patience allows.
its patience allows. ``HUB_BUSY`` at once, with ``firmware_limit``
in its data, if the hub runs firmware 4.0 and was offered more than
its buffer holds.
"""
info = connection.info
if info is None:
raise JsonRpcError(ErrorCode.HUB_NOT_CONNECTED, "hub is not ready")

offset = 0
limit = connection.stdin_limit
too_small = _firmware_4_0_limit(info)

with anyio.move_on_after(STDIN_PATIENCE_SECONDS) as patience:
while offset < len(data):
if await _offer(connection, data[offset : offset + limit], info.profile):
offset += min(limit, len(data) - offset)
chunk = data[offset : offset + limit]

if await _offer(connection, chunk, info.profile):
offset += len(chunk)

continue

if too_small is not None and len(chunk) > too_small:
# Not a program that has not read yet: this firmware has no
# room for this much, now or ever, and the fix is to update it.
# Nothing here cuts the input smaller to get round that.
#
# The remedy first: a REPL shows this in a status line cut to
# the terminal's width.
raise JsonRpcError(
ErrorCode.HUB_BUSY,
f"update the hub's firmware: {info.firmware} takes at most "
f"{too_small} bytes of input at once",
{"written": offset, "firmware_limit": too_small},
)

# Nothing on the hub has read its input yet. There is nothing to
# conclude and nothing to adjust, so wait for the soonest moment
# the answer could be different and ask again.
Expand All @@ -228,6 +253,52 @@ async def _write_stdin(connection: HubConnection, data: bytes) -> int:
return offset


FIRMWARE_4_0_STDIN_BYTES: Final = 20
"""The most input Pybricks 4.0 takes in one write, on most hubs.

4.0 sized its input buffer to 21 bytes, less the byte a ring buffer keeps empty,
while reporting a write size of up to 512: a write bigger than the buffer could
never fit, however long it waited. 4.1 sized the buffer to the write size
(pybricks-micropython a363d48f5f, discussions/2788). The betas between are not
worth telling apart: nobody stays on a beta.
"""

FIRMWARE_4_0_STDIN_BYTES_WITH_USB: Final = 63
"""The most input Pybricks 4.0 takes in one write, on hubs with USB.

Their buffer was 64 bytes, to match the USB endpoint. Measured on a Prime hub
on 4.0.1: 63 bytes are taken at the prompt, and 64 are refused for good.
"""

_HUBS_WITH_USB: Final = frozenset(
{p.HubType.TECHNIC_LARGE_HUB, p.HubType.TECHNIC_SMALL_HUB, p.HubType.NXT}
)


def _firmware_4_0_limit(info: HubInfo) -> int | None:
"""How much input a hub takes at once, if its firmware has too small a buffer.

Args:
info: The hub.

Returns:
The most it takes in one write, or ``None`` for firmware without the
bug, including firmware whose version cannot be read.
"""
try:
version = p.parse_version(info.firmware)
except ValueError:
return None

if version[:2] != (4, 0):
return None

if info.pnp is not None and info.pnp.product_id in _HUBS_WITH_USB:
return FIRMWARE_4_0_STDIN_BYTES_WITH_USB

return FIRMWARE_4_0_STDIN_BYTES


@method(
"hub.attach",
"Stream a hub's output, status and connection state until cancelled. "
Expand Down
61 changes: 61 additions & 0 deletions packages/pb-service/tests/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,3 +166,64 @@ async def test_the_write_size_is_what_the_hub_said_and_nothing_else(
await _write_stdin(connection, b"x" * 100)

assert connection.stdin_limit == was


# ------------------------------------------------------------ firmware 4.0


@pytest.mark.parametrize(
("hub_type", "buffer", "most"),
[
(p.HubType.TECHNIC_LARGE_HUB, 64, 63),
(p.HubType.CITY_HUB, 21, 20),
],
)
async def test_firmware_4_0_says_its_buffer_is_too_small_at_once(
hub_type: p.HubType, buffer: int, most: int
) -> None:
# 4.0 reported a write size it had no room for, so a paste waited out
# the whole of its patience and was then blamed on nothing reading. It is
# a firmware bug with a fix, which is what the user needs to hear, and
# straight away: no amount of waiting makes room that is not there.
hub = FakeHub(firmware="4.0.1", hub_type=hub_type, stdin_capacity=buffer - 1)
transport = FakeHubTransport(hub)

async with anyio.create_task_group() as tg:
connection = await _start(tg, transport, hub)

try:
assert await _write_stdin(connection, b"x" * most) == most
hub.stdin.clear()

with anyio.fail_after(1), pytest.raises(JsonRpcError) as caught:
await _write_stdin(connection, b"x" * 100)

assert caught.value.code == ErrorCode.HUB_BUSY
assert caught.value.message.startswith("update the hub's firmware")
assert f"at most {most} bytes" in caught.value.message
assert caught.value.data["firmware_limit"] == most

finally:
connection.close("test finished")


async def test_firmware_4_0_not_reading_small_input_is_still_not_reading(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# Input that would fit says nothing about the firmware when it is refused.
monkeypatch.setattr(stdio, "STDIN_PATIENCE_SECONDS", 0.3)
hub = FakeHub(firmware="4.0.1", hub_type=p.HubType.CITY_HUB, stdin_capacity=20)
hub.stdin += b"y" * 15
transport = FakeHubTransport(hub)

async with anyio.create_task_group() as tg:
connection = await _start(tg, transport, hub)

try:
with pytest.raises(JsonRpcError) as caught:
await _write_stdin(connection, b"x" * 10)

assert "not reading its input" in caught.value.message

finally:
connection.close("test finished")
10 changes: 10 additions & 0 deletions tests/hardware/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import pytest

import pb_client
from pb_core.jsonrpc import ErrorCode

SCAN_SECONDS = 15.0
"""How long to look for a hub before deciding there is none to test against."""
Expand Down Expand Up @@ -173,6 +174,15 @@ async def _connected(service: pb_client.Service) -> str:

except _UNAVAILABLE as exc:
_no_hub = f"no hub switched on and in range: {exc}"

# Several hubs on and none chosen is refused rather than guessed at,
# and the remedy is not to switch one on.
if (
isinstance(exc, pb_client.JsonRpcError)
and exc.code == ErrorCode.HUB_AMBIGUOUS
):
_no_hub = f"{exc}; switch the others off, or choose one with pb use"

pytest.skip(_no_hub)

return info.name
Expand Down
8 changes: 8 additions & 0 deletions tests/hardware/test_hub.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import pytest

import pb_client
from pb_service.hub.protocol import parse_version

pytestmark = [pytest.mark.hardware, pytest.mark.anyio]

Expand Down Expand Up @@ -189,6 +190,13 @@ async def test_a_program_that_ignores_input_does_not_slow_the_hub_afterwards(
# the buffer was smaller than advertised, halved the write size, and
# remembered that for the life of the connection. The connection outlives
# every command, so pasting stayed slow for the rest of the day.
firmware = (await service.hub_info(hub)).firmware

if parse_version(firmware)[:2] == (4, 0):
# Its input buffer is smaller than a paste, so nothing pasted fits,
# and the service says so rather than waiting. Fixed in 4.1.
pytest.skip(f"Pybricks {firmware} cannot take a paste this size")

await service.start_repl(hub_id=hub)
await anyio.sleep(1.0)
before = await _paste_ms(service, hub)
Expand Down
Loading