Device picker: list configured serial profiles (soldered platform UARTs)
A soldered SoC UART like the Luckfox Lyra's /dev/ttyS1 is never enumerated by pyserial's comports(), so a serial [profiles.*] entry pointing at one could only ever be reached via `meshterm --port` on the command line -- it never surfaced in the startup picker, which listed only scanned devices (and TCP profiles). Fold configured serial profiles into the picker too, mirroring the existing TCP-profile folding, de-duplicated by port so a port pyserial *does* enumerate keeps its richer scanned row. Also fix the liveness poll for the same ports: serial_port_present() now treats an existing /dev character device as present (platform UARTs aren't in comports() but their node persists exactly as long as the port does; a USB node vanishes on unplug, so this never masks a real disconnect). Without it the watcher would falsely report a soldered radio unplugged mid-session. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
19ac17a262
commit
f5880bfc20
5 files changed
+158
-1
No files matched your search
@@ -291,9 +291,25 @@ def serial_port_present(port: str) -> bool:
|
||||
except Exception: # noqa: BLE001 - pyserial absent (e.g. --mock env); can't tell, assume up
|
||||
return True
|
||||
try:
|
||||
return any(info.device == port for info in list_ports.comports())
|
||||
if any(info.device == port for info in list_ports.comports()):
|
||||
return True
|
||||
except Exception: # noqa: BLE001 - an enumeration failure must not fake a disconnect
|
||||
return True
|
||||
# A soldered platform-bus UART (e.g. an SoC port like ``/dev/ttyS1`` on the Luckfox Lyra)
|
||||
# is never enumerated by pyserial's Linux ``comports()`` — yet its device node persists for
|
||||
# exactly as long as the port exists. A USB serial node, by contrast, is removed from the
|
||||
# filesystem the instant the cable is pulled. So an existing ``/dev`` character device is a
|
||||
# sound presence signal that never masks a real unplug (and stays Windows-safe: COM names
|
||||
# are not filesystem paths, so this branch is skipped there).
|
||||
try:
|
||||
import os
|
||||
import stat
|
||||
|
||||
if port.startswith("/dev/") and os.path.exists(port):
|
||||
return stat.S_ISCHR(os.stat(port).st_mode)
|
||||
except Exception: # noqa: BLE001 - a stat hiccup must not fake a disconnect
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
class Device(ABC):
|
||||
|
||||
@@ -300,6 +300,29 @@ def tcp_device(host: str, port: int, *, name: str = "") -> DiscoveredDevice:
|
||||
)
|
||||
|
||||
|
||||
def serial_device(port: str, *, name: str = "") -> DiscoveredDevice:
|
||||
"""Build the :class:`DiscoveredDevice` for a serial companion at ``port``.
|
||||
|
||||
A soldered platform-bus UART (e.g. ``/dev/ttyS1`` on the Luckfox Lyra) is not enumerated by
|
||||
pyserial, so a scan never finds it; this is how a configured serial ``port`` enters the same
|
||||
selection/remember/picker pipeline the discovered transports use — mirroring
|
||||
:func:`tcp_device` for network companions. An optional ``name`` (the profile alias, or a
|
||||
mesh node name learned on a prior connect) is carried to the picker's DEVICE column.
|
||||
|
||||
Args:
|
||||
port: Serial port path (e.g. ``/dev/ttyS1`` or ``COM5``).
|
||||
name: Optional friendly name for display.
|
||||
|
||||
Returns:
|
||||
A serial :class:`DiscoveredDevice` ready to select or connect.
|
||||
"""
|
||||
return DiscoveredDevice(
|
||||
port=port,
|
||||
description=name,
|
||||
product=name or None,
|
||||
)
|
||||
|
||||
|
||||
def _sort_key(device: DiscoveredDevice) -> tuple[int, str]:
|
||||
"""Sort likely companions first, then bridges, then unknown; ties by target id."""
|
||||
return (_CONFIDENCE_RANK[device.confidence], device.target)
|
||||
|
||||
@@ -32,6 +32,7 @@ from ..core.discovery import (
|
||||
DEFAULT_TCP_PORT,
|
||||
DiscoveredDevice,
|
||||
parse_tcp_endpoint,
|
||||
serial_device,
|
||||
tcp_device,
|
||||
)
|
||||
from .logo import load_logo
|
||||
@@ -301,6 +302,10 @@ async def prompt_device(
|
||||
# richer remembered row rather than being shadowed by the profile.
|
||||
listed = scanned + _remembered_tcp_devices(scanned, registry)
|
||||
listed += _profile_tcp_devices(listed, profiles)
|
||||
# A serial profile on a soldered platform UART (e.g. /dev/ttyS1) is likewise not
|
||||
# produced by the scan, so fold those in too — after the scanned set, so a port
|
||||
# pyserial *does* enumerate keeps its richer scanned row rather than the bare profile.
|
||||
listed += _profile_serial_devices(listed, profiles)
|
||||
# Preselect the remembered "last known good" device when it is currently attached/in range.
|
||||
default = next((d for d in listed if remembered and remembered.matches(d)), None)
|
||||
|
||||
@@ -421,6 +426,44 @@ def _profile_tcp_devices(
|
||||
return rebuilt
|
||||
|
||||
|
||||
def _profile_serial_devices(
|
||||
listed: list[DiscoveredDevice],
|
||||
profiles: Optional[Mapping[str, DeviceProfile]],
|
||||
) -> list[DiscoveredDevice]:
|
||||
"""Rebuild configured serial profiles as :class:`DiscoveredDevice` rows for the picker.
|
||||
|
||||
A ``[profiles.<alias>]`` serial block names a companion on a fixed port. A soldered
|
||||
platform-bus UART (e.g. ``/dev/ttyS1`` on the Luckfox Lyra) is invisible to pyserial's scan,
|
||||
so without this it would only ever surface via ``meshterm --port``/``-p`` on the command
|
||||
line, never in the interactive splash. Each such profile becomes a device carrying its alias
|
||||
as the DEVICE-column name, listed like a scanned port and smoke-tested the same way —
|
||||
mirroring :func:`_profile_tcp_devices` for network companions. De-duplication is by **port**
|
||||
(a scanned USB device keys on its serial/VID:PID, not its port name): a profile whose port is
|
||||
already present — pyserial *does* enumerate it, or it is remembered — is skipped so the
|
||||
richer existing row wins rather than being duplicated by the bare profile.
|
||||
|
||||
Args:
|
||||
listed: The devices already gathered (scanned + remembered + TCP profiles), for
|
||||
de-duplication by port.
|
||||
profiles: The configured profiles, or ``None`` when none are loaded.
|
||||
|
||||
Returns:
|
||||
One serial :class:`DiscoveredDevice` per not-yet-listed serial profile, in profile order.
|
||||
"""
|
||||
if not profiles:
|
||||
return []
|
||||
seen_ports = {d.port for d in listed if d.port}
|
||||
rebuilt: list[DiscoveredDevice] = []
|
||||
for profile in profiles.values():
|
||||
if profile.is_tcp or profile.is_ble or not profile.port:
|
||||
continue
|
||||
if profile.port in seen_ports:
|
||||
continue
|
||||
seen_ports.add(profile.port)
|
||||
rebuilt.append(serial_device(profile.port, name=profile.name))
|
||||
return rebuilt
|
||||
|
||||
|
||||
async def _add_network_device(
|
||||
ui: "Ui",
|
||||
store: DeviceStore,
|
||||
|
||||
@@ -572,6 +572,25 @@ def test_serial_port_present_assumes_up_on_enumeration_error(monkeypatch) -> Non
|
||||
assert connection.serial_port_present("COM11")
|
||||
|
||||
|
||||
def test_serial_port_present_platform_uart_by_path(monkeypatch) -> None:
|
||||
"""A soldered platform UART (e.g. ``/dev/ttyS1`` on the Luckfox Lyra) is invisible to
|
||||
pyserial's ``comports()`` but its ``/dev`` char-device node persists — so an existing
|
||||
``/dev`` character device reads as present, while a vanished node (a real USB unplug of
|
||||
``/dev/ttyUSB*``) still reads as absent."""
|
||||
pytest.importorskip("serial")
|
||||
import os as _os
|
||||
import stat as _stat
|
||||
|
||||
from serial.tools import list_ports
|
||||
|
||||
monkeypatch.setattr(list_ports, "comports", list) # platform UARTs aren't enumerated -> []
|
||||
monkeypatch.setattr(_os.path, "exists", lambda p: p == "/dev/ttyS1")
|
||||
monkeypatch.setattr(_os, "stat", lambda p: SimpleNamespace(st_mode=_stat.S_IFCHR))
|
||||
|
||||
assert connection.serial_port_present("/dev/ttyS1") # existing char device -> present
|
||||
assert not connection.serial_port_present("/dev/ttyUSB9") # node gone -> absent (unplug)
|
||||
|
||||
|
||||
async def test_wait_for_disconnect_fires_when_port_vanishes(
|
||||
tmp_path: Path, monkeypatch
|
||||
) -> None:
|
||||
|
||||
@@ -1210,6 +1210,62 @@ def test_device_picker_lists_configured_tcp_profile(tmp_path) -> None:
|
||||
assert _TCP_ICON in top.plain # marked with the network TYPE glyph
|
||||
|
||||
|
||||
def test_device_picker_lists_configured_serial_profile(tmp_path) -> None:
|
||||
"""A ``[profiles.*]`` serial entry (a soldered ``/dev/ttyS1``) shows up in the picker under
|
||||
its alias, ready to select — even though pyserial's scan never produces that platform port."""
|
||||
from meshterm.core.config import DeviceProfile
|
||||
from meshterm.core.device_store import DeviceStore
|
||||
from meshterm.ui.device_picker import prompt_device
|
||||
|
||||
store = DeviceStore(tmp_path / "devices.json")
|
||||
profiles = {"picocalc": DeviceProfile(name="picocalc", port="/dev/ttyS1", baudrate=115200)}
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
class _Ui:
|
||||
async def select_startup(self, title, items, *, default=None, banner=None, footnote=None):
|
||||
captured["items"] = items
|
||||
return None # skip past the smoke test
|
||||
|
||||
async def _never(_device):
|
||||
raise AssertionError("verify should not run when selection is skipped")
|
||||
|
||||
# Nothing scanned or remembered — the serial profile alone puts the port in the list.
|
||||
asyncio.run(prompt_device(_Ui(), [], store, _never, profiles))
|
||||
rows = [it.title for it in captured["items"] if isinstance(it, Choice)]
|
||||
device_rows = [r for r in rows if hasattr(r, "plain") and "picocalc" in r.plain]
|
||||
assert device_rows, "the configured serial profile should be listed"
|
||||
assert "/dev/ttyS1" in device_rows[0].plain # its port sits in the address column
|
||||
|
||||
|
||||
def test_device_picker_serial_profile_yields_to_scanned_port(tmp_path) -> None:
|
||||
"""A serial profile whose port pyserial DOES enumerate is not double-listed — the scanned
|
||||
row (with real USB metadata) wins over the bare profile."""
|
||||
from meshterm.core.config import DeviceProfile
|
||||
from meshterm.core.device_store import DeviceStore
|
||||
from meshterm.core.discovery import DiscoveredDevice
|
||||
from meshterm.ui.device_picker import prompt_device
|
||||
|
||||
store = DeviceStore(tmp_path / "devices.json")
|
||||
scanned = [DiscoveredDevice(port="/dev/ttyUSB0", product="XIAO", vid=0x2886, pid=0x8044)]
|
||||
profiles = {"radio": DeviceProfile(name="radio", port="/dev/ttyUSB0")}
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
class _Ui:
|
||||
async def select_startup(self, title, items, *, default=None, banner=None, footnote=None):
|
||||
captured["items"] = items
|
||||
return None
|
||||
|
||||
async def _never(_device):
|
||||
raise AssertionError("verify should not run when selection is skipped")
|
||||
|
||||
asyncio.run(prompt_device(_Ui(), scanned, store, _never, profiles))
|
||||
rows = [it.title for it in captured["items"] if isinstance(it, Choice)]
|
||||
usb_rows = [r for r in rows if hasattr(r, "plain") and "/dev/ttyUSB0" in r.plain]
|
||||
assert len(usb_rows) == 1, "the scanned port must not be duplicated by the profile"
|
||||
|
||||
|
||||
def test_device_picker_profile_yields_to_remembered_endpoint(tmp_path) -> None:
|
||||
"""A profile at an already-remembered endpoint doesn't double-list — the richer row wins."""
|
||||
from meshterm.core.config import DeviceProfile
|
||||
|
||||
Reference in new issue
Block a user