diff --git a/README.md b/README.md index e70a996..b2c1d52 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,8 @@ # MeshTerm A modern, extensible command-line toolkit for tuning and exploring a -[MeshCore](https://meshcore.co.uk/) mesh through a serial-connected companion device. +[MeshCore](https://meshcore.co.uk/) mesh through a serial- or Bluetooth-connected companion +device. MeshTerm is interactive by default (a Rich + Questionary menu) and fully scriptable (every menu option is also a Typer subcommand). Every run is logged to SQLite and can be @@ -15,7 +16,7 @@ turned into interactive HTML visualizations. | **Device info** | ✅ skeleton | Show the connected companion device's identity and radio config. | | **Node list** | ✅ working | List this node and its known contacts — full public keys with the path-hash prefix highlighted. | | **Device config** | ✅ working | View and change every setting (name, radio, behavior, experimental), with TOML backup/restore, channels, and gated destructive ops. | -| **Device discovery** | ✅ working | Enumerate serial devices, pick one interactively, and remember the last good default. | +| **Device discovery** | ✅ working | Enumerate serial *and* Bluetooth LE companions, pick one interactively, and remember the last good default. A dropped link (unplug, power-off, or BLE out-of-range) is detected live and offers to reconnect. | | **History / DB** | ✅ skeleton | Every tool execution and measurement is persisted and queryable. | | **TX-power optimization** | ✅ working | Sweep transmit power (coarse + refine), converge on the best signal, optionally apply, render an interactive chart. | | **Link budget** | ✅ working | Predict time-on-air, receiver sensitivity, range, and duty-cycle/dwell headroom for a radio config — offline, no radio needed. | @@ -40,6 +41,9 @@ Python 3.10+ is required (matching the `meshcore` library). # Interactive menu (default) meshterm +# Connect over Bluetooth instead of USB (address from `meshterm devices`) +meshterm --ble AA:BB:CC:DD:EE:FF info + # Scripted: every menu option is also a subcommand meshterm trace --target Alice --samples 10 --profile yagi diff --git a/config.example.toml b/config.example.toml index 5bb6068..6602b6f 100644 --- a/config.example.toml +++ b/config.example.toml @@ -1,10 +1,11 @@ # MeshTerm configuration. # Copy to ~/.meshterm/config.toml (or pass --db / --port on the CLI). # -# Profiles are optional. With no profile and no --port, MeshTerm discovers attached -# serial devices, lets you pick one (interactively) or uses the single one present, and -# remembers the last device that connected as the default for next time. Define profiles -# below only to give your hardware stable aliases (e.g. --profile yagi). +# Profiles are optional. With no profile, no --port, and no --ble, MeshTerm discovers +# attached serial devices and nearby Bluetooth companions, lets you pick one (interactively) +# or uses the single one present, and remembers the last device that connected as the default +# for next time. Define profiles below only to give your hardware stable aliases +# (e.g. --profile yagi, or --profile handheld for a Bluetooth device). default_profile = "s3" trace_cooldown_s = 1.0 @@ -29,3 +30,11 @@ description = "Local-range repeater" [profiles.observer] port = "COM8" description = "XIAO observer running a bot" + +# A Bluetooth LE companion: give it an `address` (from `meshterm devices`) instead of a port. +# The `transport = "ble"` line is optional — a bare `address` already implies Bluetooth. +[profiles.handheld] +address = "AA:BB:CC:DD:EE:FF" +# transport = "ble" +# ble_pin = "123456" # only if your device requires a pairing PIN +description = "Pocket handheld over Bluetooth" diff --git a/meshterm/cli.py b/meshterm/cli.py index 8444eaa..99f2d89 100644 --- a/meshterm/cli.py +++ b/meshterm/cli.py @@ -44,6 +44,12 @@ def main_callback( ctx: typer.Context, profile: Optional[str] = typer.Option(None, "--profile", "-p", help="Device profile."), port: Optional[str] = typer.Option(None, "--port", help="Serial port override."), + ble: Optional[str] = typer.Option( + None, "--ble", help="Bluetooth address of a companion device (selects the BLE transport)." + ), + ble_pin: Optional[str] = typer.Option( + None, "--ble-pin", help="BLE pairing PIN, if the Bluetooth companion requires one." + ), mock: bool = typer.Option(False, "--mock", help="Use the built-in simulator."), db_path: Optional[Path] = typer.Option(None, "--db", help="SQLite database path."), json_output: bool = typer.Option(False, "--json", help="Machine-readable output."), @@ -55,6 +61,8 @@ def main_callback( ctx: The Click/Typer context. profile: Named device profile to use. port: Explicit serial port, overriding the profile. + ble: Explicit Bluetooth address, selecting the BLE transport. + ble_pin: Optional BLE pairing PIN for the Bluetooth companion. mock: Whether to use the simulator instead of real hardware. db_path: Override the database location. json_output: Request machine-readable output from tools. @@ -80,8 +88,10 @@ def main_callback( profile=settings.resolve_profile(profile), mock=mock, port_override=port, + ble_override=ble, + ble_pin=ble_pin, json_output=json_output, - explicit_selection=profile is not None or port is not None, + explicit_selection=profile is not None or port is not None or ble is not None, ) _state = app_ctx ctx.call_on_close(app_ctx.repo.close) diff --git a/meshterm/context.py b/meshterm/context.py index 5a18237..4848585 100644 --- a/meshterm/context.py +++ b/meshterm/context.py @@ -42,11 +42,14 @@ class AppContext: mock: Whether the simulator device is in use. port_override: Explicit serial port (from ``--port`` or the interactive picker), overriding the profile. + ble_override: Explicit Bluetooth address (from ``--ble`` or the interactive picker), + selecting the BLE transport. Takes precedence over ``port_override``. + ble_pin: Optional BLE pairing PIN for the chosen Bluetooth device. json_output: Whether tools should emit machine-readable output. selected_device: The discovered device chosen for this session, when known, so it can be remembered after a successful connection. - explicit_selection: Whether ``--port``/``--profile`` was passed explicitly (which - suppresses the interactive picker and auto-discovery). + explicit_selection: Whether ``--port``/``--ble``/``--profile`` was passed explicitly + (which suppresses the interactive picker and auto-discovery). """ console: Console @@ -57,11 +60,15 @@ class AppContext: profile: Optional[DeviceProfile] = None mock: bool = False port_override: Optional[str] = None + ble_override: Optional[str] = None + ble_pin: Optional[str] = None json_output: bool = False selected_device: Optional[DiscoveredDevice] = None explicit_selection: bool = False _device: Optional[Device] = field(default=None, init=False, repr=False) _active_port: Optional[str] = field(default=None, init=False, repr=False) + _active_transport: Optional[str] = field(default=None, init=False, repr=False) + _active_address: Optional[str] = field(default=None, init=False, repr=False) _resume_intent: Optional[tuple[bool, bool, bool]] = field( default=None, init=False, repr=False ) @@ -82,15 +89,47 @@ class AppContext: @property def active_port(self) -> Optional[str]: - """The serial port the current connection is open on, if any (``None`` for --mock). + """The serial port the current connection is open on, if any (``None`` for --mock/BLE). - Set when a real connection is opened so the liveness watcher knows which OS port to - poll for a mid-session unplug. Falls back to an explicit ``--port`` override when a - connection hasn't recorded one yet. + Set when a real *serial* connection is opened so the reconnect flow knows which OS + port to wait on. ``None`` for the simulator and for BLE connections (which have no + serial port). Falls back to an explicit ``--port`` override when a connection hasn't + recorded one yet. + """ + if self.mock or self.active_transport == "ble": + return None + return self._active_port or self.port_override + + @property + def active_transport(self) -> Optional[str]: + """The transport of the current/selected connection: ``"serial"``, ``"ble"``, or ``None``. + + ``None`` for the simulator. For a real device it reflects the open connection when + one exists, otherwise the transport implied by the pending selection (an explicit + ``--ble`` selects BLE), defaulting to serial. """ if self.mock: return None - return self._active_port or self.port_override + if self._active_transport is not None: + return self._active_transport + return "ble" if self.ble_override else "serial" + + async def link_alive(self) -> bool: + """Whether the current device's transport link is still up (best-effort, non-invasive). + + Delegates to the connected device's :meth:`~meshterm.core.connection.Device.link_present` + — OS port enumeration for serial, the BLE client's connection flag for Bluetooth — so + the session's liveness watcher is transport-agnostic. Returns ``False`` when nothing is + connected (there is no live link), and ``True`` on any check hiccup so a transient + lookup failure never fakes a disconnect. + """ + device = self._device + if device is None: + return False + try: + return await device.link_present() + except Exception: # noqa: BLE001 - a liveness-check failure must not fake a disconnect + return True @property def ui(self) -> "Ui": @@ -174,9 +213,12 @@ class AppContext: device: A connected :class:`Device` to serve as this session's radio. """ self._device = device - # Record the port so the liveness watcher knows which OS port to poll (the picker - # opened it directly, bypassing the resolution in ``device()`` that normally sets it). + # Record the transport and endpoint the picker opened directly, bypassing the + # resolution in ``device()`` that normally sets them — so the liveness watcher knows + # what to poll and ``reconnect`` can rebuild the same connection. + self._active_transport = getattr(device, "transport", "serial") self._active_port = getattr(device, "_port", None) + self._active_address = getattr(device, "_address", None) async def device(self) -> Device: """Return a connected :class:`Device`, opening the connection on first use. @@ -197,8 +239,25 @@ class AppContext: if self.mock: self._device = make_device(mock=True, port=None) + self._active_transport = None + self._active_port = None + self._active_address = None + await self._device.connect() + return self._device + + # A Bluetooth endpoint (an explicit ``--ble``, a BLE profile, a device picked at + # startup, or the remembered BLE default) is opened directly by address — no serial + # resolution, and no re-scan needed to reconnect to a known address. + ble_address, ble_pin = self._resolve_ble_endpoint() + if ble_address: + self._device = make_device( + mock=False, port=None, transport="ble", address=ble_address, pin=ble_pin + ) + self._active_transport = "ble" + self._active_address = ble_address self._active_port = None await self._device.connect() + await self._remember_connected() return self._device resolution = resolve_device( @@ -211,15 +270,50 @@ class AppContext: self.selected_device = resolution.device baudrate = self.profile.baudrate if self.profile else 115200 self._device = make_device(mock=False, port=resolution.port, baudrate=baudrate) + self._active_transport = "serial" self._active_port = resolution.port + self._active_address = None await self._device.connect() - # Connection succeeded: this is now the last known good device. Learn its mesh node - # name (best-effort — a probe failure must not block a good connection). + await self._remember_connected() + return self._device + + def _resolve_ble_endpoint(self) -> tuple[Optional[str], Optional[str]]: + """Return the ``(address, pin)`` to open over Bluetooth, or ``(None, None)`` for serial. + + Resolves a BLE endpoint in priority order — an explicit ``--ble``, a BLE + :class:`~meshterm.core.config.DeviceProfile`, then the remembered BLE default — so a + Bluetooth companion is honored wherever a serial one would be. Returns ``(None, None)`` + when the session should fall through to serial resolution. + """ + if self.ble_override: + return self.ble_override, self.ble_pin + # An explicit serial selection (``--port`` or a serial profile with a port) wins over a + # remembered BLE default, mirroring the serial resolution priority. + explicit_serial = bool(self.port_override) or ( + self.profile is not None and not self.profile.is_ble and bool(self.profile.port) + ) + if self.profile is not None and self.profile.is_ble and self.profile.address: + return self.profile.address, self.ble_pin or self.profile.ble_pin + if explicit_serial: + return None, None + remembered = self.device_store.load() + if remembered is not None and remembered.is_ble and remembered.target: + self.selected_device = None # remembered, not freshly discovered this session + return remembered.target, self.ble_pin + return None, None + + async def _remember_connected(self) -> None: + """Record the just-connected device as the last known good default (best-effort). + + Learns the device's mesh node name (a probe failure must not block a good + connection). Only devices discovered this session carry a + :class:`~meshterm.core.discovery.DiscoveredDevice` to remember; a bare ``--port`` or + remembered-by-address reconnect has nothing new to upsert. + """ if self.selected_device is not None: self.device_store.remember( self.selected_device, node_name=await self._node_name() ) - return self._device async def reconnect(self) -> None: """Drop a lost device connection and rebuild it, restoring live services. diff --git a/meshterm/core/config.py b/meshterm/core/config.py index a0caf97..d8f3149 100644 --- a/meshterm/core/config.py +++ b/meshterm/core/config.py @@ -35,12 +35,19 @@ def default_config_dir() -> Path: class DeviceProfile: """Connection defaults for one physical companion device. + A profile addresses either a serial companion (via ``port``) or a Bluetooth one (via + ``transport = "ble"`` and ``address``). ``transport`` defaults to serial, so existing + port-only profiles are unchanged. + Attributes: name: The profile alias (e.g. ``"yagi"``). - port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``). + port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``); serial profiles. baudrate: Serial baud rate. default_tx_power: TX power to assume/restore for this device, if known. description: Free-text note about the hardware. + transport: ``"serial"`` (default) or ``"ble"``. + address: Bluetooth address (e.g. ``AA:BB:CC:DD:EE:FF``); BLE profiles. + ble_pin: Optional BLE pairing PIN, if the Bluetooth companion requires one. """ name: str @@ -48,6 +55,14 @@ class DeviceProfile: baudrate: int = 115200 default_tx_power: Optional[int] = None description: str = "" + transport: str = "serial" + address: Optional[str] = None + ble_pin: Optional[str] = None + + @property + def is_ble(self) -> bool: + """Whether this profile addresses a Bluetooth LE companion.""" + return self.transport == "ble" @dataclass(slots=True) @@ -121,12 +136,19 @@ class Settings: profiles: dict[str, DeviceProfile] = {} for pname, pdata in (data.get("profiles") or {}).items(): + # A profile with an ``address`` (or ``transport = "ble"``) is a Bluetooth device; + # otherwise it's serial. Defaulting the transport this way keeps port-only + # profiles working untouched while a bare ``address`` is enough to declare a BLE one. + transport = pdata.get("transport") or ("ble" if pdata.get("address") else "serial") profiles[pname] = DeviceProfile( name=pname, port=pdata.get("port"), baudrate=pdata.get("baudrate", 115200), default_tx_power=pdata.get("default_tx_power"), description=pdata.get("description", ""), + transport=transport, + address=pdata.get("address"), + ble_pin=pdata.get("ble_pin"), ) return cls( diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index 8c4fcee..c5fab0d 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -18,7 +18,7 @@ import logging import random from abc import ABC, abstractmethod from datetime import datetime, timezone -from typing import Callable, Optional +from typing import TYPE_CHECKING, Callable, Optional from .channels import CHANNEL_SLOT_PROBE_CAP from .events import MeshEvent @@ -33,6 +33,9 @@ from .models import ( TraceResult, ) +if TYPE_CHECKING: + from .discovery import DiscoveredDevice + #: Module logger; enable DEBUG on ``meshterm.core.connection`` to trace the message pump. _log = logging.getLogger(__name__) @@ -75,13 +78,14 @@ class DeviceCommandError(RuntimeError): """ -#: Exception class names that signal the serial link to the companion has dropped — the -#: device was unplugged, powered off, or its port otherwise vanished — as opposed to an -#: ordinary command-level failure. Matched by name in :func:`is_connection_lost` so the -#: optional ``pyserial`` dependency need not be imported here (it isn't installed on the -#: ``--mock`` path). ``SerialException`` covers pyserial's read/write failures (including the -#: Windows ``ClearCommError``/``WriteFile`` variants); the ``OSError`` subclasses cover a -#: link torn down at the OS layer. +#: Exception class names that signal the link to the companion has dropped — the device was +#: unplugged, powered off, moved out of range, or its port/transport otherwise vanished — as +#: opposed to an ordinary command-level failure. Matched by name in :func:`is_connection_lost` +#: so the optional ``pyserial``/``bleak`` dependencies need not be imported here (neither is +#: installed on the ``--mock`` path). ``SerialException`` covers pyserial's read/write failures +#: (including the Windows ``ClearCommError``/``WriteFile`` variants); the ``Bleak*`` names cover +#: a Bluetooth link that dropped or a peripheral that went out of range; the ``OSError`` +#: subclasses cover a link torn down at the OS layer. _CONNECTION_LOST_TYPES = frozenset( { "SerialException", @@ -89,6 +93,11 @@ _CONNECTION_LOST_TYPES = frozenset( "ConnectionResetError", "ConnectionAbortedError", "BrokenPipeError", + "BleakError", + "BleakDeviceNotFoundError", + "BleakDBusError", + "BleakGATTError", + "BleakCharacteristicNotFoundError", } ) @@ -106,6 +115,12 @@ _CONNECTION_LOST_HINTS = ( "port is closed", "no such device", "input/output error", + # BLE link-loss phrasings (bleak errors / meshcore BLE transport callback reasons). + "ble_transport_lost", + "ble_write_failed", + "ble_disconnect", + "not connected to a ble device", + "device is no longer connected", ) @@ -182,6 +197,22 @@ class Device(ABC): async def disconnect(self) -> None: """Close the connection and release resources. Idempotent.""" + async def link_present(self) -> bool: + """Return whether the underlying transport link is still up (best-effort). + + A cheap, *non-invasive* liveness probe — it never transmits and never opens a new + handle — so the interactive session can poll it while the device is in use to notice + a mid-session drop (a serial cable pulled, a companion powered off, a BLE peripheral + out of range). Each transport implements it against the signal that actually reflects + its link state (OS port enumeration for serial, the BLE client's connection flag for + Bluetooth). It returns ``True`` whenever presence can't be determined, so a lookup + hiccup never fakes a disconnect. + + Returns: + ``True`` if the link appears up (or can't be checked), ``False`` if it is gone. + """ + return True + @abstractmethod async def get_self_info(self) -> dict: """Return identity and radio configuration of the connected device. @@ -482,7 +513,12 @@ class Device(ABC): class MeshCoreDevice(Device): - """A :class:`Device` backed by the ``meshcore`` serial companion client. + """A :class:`Device` backed by the ``meshcore`` companion client (serial or BLE). + + The same wrapper serves both transports: which one it opens is chosen by ``transport`` + (``"serial"`` opens ``port``; ``"ble"`` opens ``address``). Everything above the + connection — commands, event mapping, trace parsing — is transport-agnostic, so only + :meth:`connect` and :meth:`link_present` differ between the two. Note: The trace mapping here follows the documented companion protocol (trace replies @@ -491,22 +527,35 @@ class MeshCoreDevice(Device): """ def __init__( - self, port: str, baudrate: int = 115200, connect_timeout: Optional[float] = None + self, + port: Optional[str] = None, + baudrate: int = 115200, + connect_timeout: Optional[float] = None, + *, + transport: str = "serial", + address: Optional[str] = None, + pin: Optional[str] = None, ) -> None: """Initialize the device wrapper. Args: - port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``). + port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``); serial transport only. baudrate: Serial baud rate. connect_timeout: Handshake timeout (seconds) for the initial connection, passed to the client as its default command timeout. ``None`` uses the ``meshcore`` library default (~15s). The startup smoke test sets a short value so a non-responsive port is rejected quickly instead of blocking on the full default handshake window. + transport: ``"serial"`` (default) or ``"ble"``. + address: Bluetooth address (e.g. ``AA:BB:CC:DD:EE:FF``); BLE transport only. + pin: Optional BLE pairing PIN, when the peripheral requires one (BLE only). """ self._port = port self._baudrate = baudrate self._connect_timeout = connect_timeout + self._transport = transport + self._address = address + self._pin = pin self._mc = None # type: ignore[var-annotated] # meshcore.MeshCore # Serializes channel reads. The meshcore library's get_channel waits for "the next # CHANNEL_INFO event" with no correlation to the index it asked for, and the dispatcher @@ -515,6 +564,16 @@ class MeshCoreDevice(Device): # keeps at most one channel read outstanding, so the response is unambiguously ours. self._channel_read_lock = asyncio.Lock() + @property + def transport(self) -> str: + """Which transport this device connects over (``"serial"`` or ``"ble"``).""" + return self._transport + + @property + def endpoint(self) -> Optional[str]: + """The connection endpoint: the BLE address for BLE, else the serial port.""" + return self._address if self._transport == "ble" else self._port + async def connect(self) -> None: # noqa: D102 - inherited docstring if self._mc is not None: return @@ -527,20 +586,20 @@ class MeshCoreDevice(Device): "--mock for the simulator." ) from exc - self._mc = await MeshCore.create_serial( - self._port, self._baudrate, default_timeout=self._connect_timeout - ) - # ``create_serial`` returns ``None`` (after cleaning up its own connection) when the - # node never answers the identity handshake — i.e. the port isn't a MeshCore serial - # companion. Surface that as a clean, recoverable error rather than leaving a - # half-open device whose next command fails with a confusing "not connected". - if self._mc is None: - raise DeviceCommandError( - f"no response from a MeshCore companion on {self._port}; it may not be a " - "MeshCore device, or it may be powered off or in use by another program." + if self._transport == "ble": + self._mc = await self._create_ble(MeshCore) + else: + self._mc = await MeshCore.create_serial( + self._port, self._baudrate, default_timeout=self._connect_timeout ) + # ``create_*`` returns ``None`` (after cleaning up its own connection) when the node + # never answers the identity handshake — i.e. the endpoint isn't a MeshCore companion. + # Surface that as a clean, recoverable error rather than leaving a half-open device + # whose next command fails with a confusing "not connected". + if self._mc is None: + raise DeviceCommandError(self._no_response_message()) # A short ``connect_timeout`` is only meant to bound the initial identity handshake - # (so a dead port is rejected quickly). Now that we're connected, restore the + # (so a dead endpoint is rejected quickly). Now that we're connected, restore the # library's normal per-command timeout so the rest of the session isn't rushed. if self._connect_timeout is not None: commands = getattr(self._mc, "commands", None) @@ -548,6 +607,62 @@ class MeshCoreDevice(Device): if commands is not None and default is not None: commands.default_timeout = default + async def _create_ble(self, mesh_core): # type: ignore[no-untyped-def] + """Open the BLE companion connection, translating a missing-bleak import cleanly. + + ``auto_reconnect`` is deliberately left off: MeshTerm drives reconnection itself (the + same reconnect dialog the serial path uses), so the meshcore client should surface a + dropped link promptly via ``is_connected`` rather than silently retrying underneath us. + + Args: + mesh_core: The imported ``meshcore.MeshCore`` class. + + Returns: + The connected ``MeshCore`` client, or ``None`` if the peripheral never answered. + """ + try: + return await mesh_core.create_ble( + address=self._address, + pin=self._pin, + default_timeout=self._connect_timeout, + auto_reconnect=False, + ) + except ImportError as exc: + raise DeviceCommandError( + "Bluetooth support requires the 'bleak' package, which isn't installed. " + "Run `pip install -e .` (or `pip install bleak`), use a USB device, or " + "run with --mock." + ) from exc + + def _no_response_message(self) -> str: + """A clean, recoverable error for an endpoint that didn't answer as a companion.""" + if self._transport == "ble": + where = self._address or "the selected Bluetooth device" + return ( + f"no response from a MeshCore companion over Bluetooth ({where}); it may be " + "out of range, powered off, already connected to another device, or not a " + "MeshCore device." + ) + return ( + f"no response from a MeshCore companion on {self._port}; it may not be a " + "MeshCore device, or it may be powered off or in use by another program." + ) + + async def link_present(self) -> bool: # noqa: D102 - inherited docstring + if self._mc is None: + return True # not connected yet / already torn down — nothing to declare lost + if self._transport == "ble": + # The meshcore client flips ``is_connected`` to False the moment bleak reports the + # peripheral dropped (via its disconnect callback), so this is the BLE analogue of + # the serial port-enumeration check — a cheap, non-transmitting liveness read. + try: + return bool(self._mc.is_connected) + except Exception: # noqa: BLE001 - a status hiccup must not fake a disconnect + return True + if not self._port: + return True # no port recorded (shouldn't happen once connected) — can't tell + return serial_port_present(self._port) + async def disconnect(self) -> None: # noqa: D102 - inherited docstring if self._mc is None: return @@ -1747,23 +1862,37 @@ def make_device( port: Optional[str], baudrate: int = 115200, mock_optimal_tx: int = 14, + transport: str = "serial", + address: Optional[str] = None, + pin: Optional[str] = None, ) -> Device: """Construct the appropriate :class:`Device` for the current invocation. Args: mock: When ``True`` return a :class:`MockDevice` simulator. - port: Serial port for a real device. Required unless ``mock`` is set. - baudrate: Serial baud rate for a real device. + port: Serial port for a real serial device. Required for the serial transport + unless ``mock`` is set. + baudrate: Serial baud rate for a real serial device. mock_optimal_tx: Peak TX power for the simulator. + transport: ``"serial"`` (default) or ``"ble"``. + address: Bluetooth address for the BLE transport. Required when ``transport="ble"``. + pin: Optional BLE pairing PIN (BLE only). Returns: A connected-on-enter :class:`Device` instance. Raises: - ValueError: If a real device is requested without a serial port. + ValueError: If a real device is requested without a usable endpoint for its transport. """ if mock: return MockDevice(optimal_tx=mock_optimal_tx) + if transport == "ble": + if not address: + raise ValueError( + "No Bluetooth address configured. Pass --ble, pick a device at startup, " + "or use --mock." + ) + return MeshCoreDevice(transport="ble", address=address, pin=pin) if not port: raise ValueError( "No serial port configured. Pass --port, set a profile, or use --mock." @@ -1771,20 +1900,61 @@ def make_device( return MeshCoreDevice(port=port, baudrate=baudrate) -async def probe_meshcore( - port: str, baudrate: int = 115200, *, timeout: float = 6.0 -) -> Optional[tuple["MeshCoreDevice", dict]]: - """Open ``port``, confirm a MeshCore companion answers, and return the live connection. +#: Handshake window (seconds) for probing a serial companion. A genuine board answers in well +#: under a second; a non-MeshCore port is rejected within this bound. +_PROBE_TIMEOUT_SERIAL_S = 6.0 - Opens a real serial connection and issues an identity query (the APPSTART that backs - :meth:`MeshCoreDevice.get_self_info`). A genuine companion replies with a self-info - payload; anything else — a non-MeshCore serial gadget, the wrong baud rate, an - unresponsive port — never answers and is rejected within ``timeout``. +#: Handshake window (seconds) for probing a BLE companion. Longer than serial: a BLE connect +#: involves a link-layer connection and GATT service discovery before the identity reply. +_PROBE_TIMEOUT_BLE_S = 20.0 + + +async def probe_device( + device: "DiscoveredDevice", *, baudrate: int = 115200, pin: Optional[str] = None +) -> Optional[tuple["MeshCoreDevice", dict]]: + """Open a discovered device, confirm a MeshCore companion answers, and keep it connected. + + Transport-agnostic front door for the startup smoke test: it opens the right connection + for ``device`` (serial port or BLE address) and issues an identity query (the APPSTART + that backs :meth:`MeshCoreDevice.get_self_info`). A genuine companion replies with a + self-info payload; anything else — a non-MeshCore gadget, an unresponsive port, a BLE + device out of range — never answers and is rejected within the transport's timeout. On success the connection is **left open** and returned to the caller, which reuses it as - the session device. This is deliberate: many companion boards reset on each serial open, - so a probe-then-reopen cycle is slow and flaky — opening the radio exactly once is both - faster and far more reliable. On any failure the probe connection is closed. + the session device. This is deliberate: many companion boards reset on each serial open + (and a BLE reconnect re-runs service discovery), so a probe-then-reopen cycle is slow and + flaky — opening the radio exactly once is both faster and far more reliable. On any + failure the probe connection is closed. + + Args: + device: The discovered device to probe (serial or BLE). + baudrate: Serial baud rate (serial transport only). + pin: Optional BLE pairing PIN (BLE transport only). + + Returns: + ``(device, self_info)`` with a connected :class:`MeshCoreDevice` on success (the + caller owns and must eventually close it), or ``None`` if it is not a reachable + MeshCore companion. + """ + if device.is_ble: + timeout = _PROBE_TIMEOUT_BLE_S + probe = MeshCoreDevice( + transport="ble", address=device.address, pin=pin, connect_timeout=timeout + ) + else: + timeout = _PROBE_TIMEOUT_SERIAL_S + probe = MeshCoreDevice( + port=device.port, baudrate=baudrate, connect_timeout=timeout + ) + return await _probe(probe, timeout) + + +async def probe_meshcore( + port: str, baudrate: int = 115200, *, timeout: float = _PROBE_TIMEOUT_SERIAL_S +) -> Optional[tuple["MeshCoreDevice", dict]]: + """Probe a serial ``port`` for a MeshCore companion (see :func:`probe_device`). + + Thin serial-only convenience wrapper retained for callers that hold a bare port string. Args: port: Serial port to probe (e.g. ``COM5`` or ``/dev/ttyUSB0``). @@ -1792,16 +1962,31 @@ async def probe_meshcore( timeout: Seconds to bound the connection handshake and the identity reply. Returns: - ``(device, self_info)`` with a connected :class:`MeshCoreDevice` on success (the - caller owns and must eventually close it), or ``None`` if the port is not a reachable + ``(device, self_info)`` on success, or ``None`` if the port is not a reachable MeshCore companion. """ - # ``timeout`` is the handshake window handed to the client, so a non-MeshCore port is + return await _probe( + MeshCoreDevice(port=port, baudrate=baudrate, connect_timeout=timeout), timeout + ) + + +async def _probe( + device: "MeshCoreDevice", timeout: float +) -> Optional[tuple["MeshCoreDevice", dict]]: + """Connect ``device`` and read its identity, returning it live or closing it on failure. + + Args: + device: An unconnected :class:`MeshCoreDevice` configured for its transport. + timeout: Handshake window bounding both the connect and the identity read. + + Returns: + ``(device, self_info)`` with the connection left open, or ``None`` on any failure. + """ + # ``timeout`` is the handshake window handed to the client, so a non-MeshCore endpoint is # rejected in ~``timeout`` seconds and the client cleans up its own connection. The outer # ``wait_for`` is only a safety net a few seconds beyond that, so we never cancel the - # client mid-handshake (which would leak the open port). A real companion answers in well - # under a second, so this never delays a good device. - device = MeshCoreDevice(port=port, baudrate=baudrate, connect_timeout=timeout) + # client mid-handshake (which would leak the open connection). A real companion answers in + # well under a second (serial) or a few seconds (BLE), so this never delays a good device. try: await asyncio.wait_for(device.connect(), timeout + 4.0) info = await asyncio.wait_for(device.get_self_info(), timeout) diff --git a/meshterm/core/device_store.py b/meshterm/core/device_store.py index ab21c0e..2ad5099 100644 --- a/meshterm/core/device_store.py +++ b/meshterm/core/device_store.py @@ -20,7 +20,7 @@ from dataclasses import dataclass from pathlib import Path from typing import Optional -from .discovery import DiscoveredDevice +from .discovery import TRANSPORT_BLE, TRANSPORT_SERIAL, DiscoveredDevice from .models import utcnow @@ -30,10 +30,14 @@ class RememberedDevice: Attributes: stable_id: The device's :attr:`DiscoveredDevice.stable_id` at connect time. - port: The serial port it was last seen on (informational; may have changed). + port: The serial port it was last seen on (informational; may have changed). Blank + for a BLE device. label: A friendly label for display in prompts and tables. - node_name: The device's own mesh node name, learned at connect time (may be empty). last_connected: ISO-8601 timestamp of the last successful connection. + node_name: The device's own mesh node name, learned at connect time (may be empty). + transport: ``"serial"`` or ``"ble"`` — how this device was last reached. + address: The Bluetooth address, for a BLE device (blank otherwise), so it can be + reconnected directly without re-scanning. """ stable_id: str @@ -41,6 +45,18 @@ class RememberedDevice: label: str last_connected: str node_name: str = "" + transport: str = TRANSPORT_SERIAL + address: str = "" + + @property + def is_ble(self) -> bool: + """Whether this remembered device was reached over Bluetooth LE.""" + return self.transport == TRANSPORT_BLE + + @property + def target(self) -> str: + """The connection target: the BLE address for a BLE device, else the serial port.""" + return self.address or self.port if self.is_ble else self.port def matches(self, device: DiscoveredDevice) -> bool: """Return whether ``device`` is the same hardware as this record.""" @@ -98,10 +114,12 @@ class DeviceStore: try: return RememberedDevice( stable_id=entry["stable_id"], - port=entry["port"], - label=entry.get("label", entry["port"]), + port=entry.get("port", ""), + label=entry.get("label", entry.get("port", "")), last_connected=entry.get("last_connected", ""), node_name=entry.get("node_name", ""), + transport=entry.get("transport", TRANSPORT_SERIAL), + address=entry.get("address", ""), ) except (KeyError, TypeError): return None @@ -150,6 +168,8 @@ class DeviceStore: label=device.label, last_connected=utcnow().isoformat(), node_name=node_name, + transport=device.transport, + address=device.address or "", ) self._write(registry, device.stable_id) @@ -164,6 +184,8 @@ class DeviceStore: "label": record.label, "last_connected": record.last_connected, "node_name": record.node_name, + "transport": record.transport, + "address": record.address, } for stable_id, record in registry.items() }, diff --git a/meshterm/core/discovery.py b/meshterm/core/discovery.py index 53a50aa..67cb470 100644 --- a/meshterm/core/discovery.py +++ b/meshterm/core/discovery.py @@ -1,20 +1,40 @@ -"""Serial-port enumeration for companion-device discovery. +"""Companion-device discovery across transports (serial + Bluetooth LE). -Discovery is protocol-agnostic: it lists USB serial ports via ``pyserial`` and flags the -ones whose USB vendor ID matches hardware commonly used for LoRa companion devices -(ESP32/nRF boards and their USB-UART bridges). Nothing is hidden — unrecognized adapters -still appear, just sorted after the likely candidates. +Discovery enumerates two kinds of companion: -This module has no UI and no persistent state; it only reads what is currently plugged in. -The companion connection itself still goes through -:class:`~meshterm.core.connection.MeshCoreDevice`. +* **Serial**: USB serial ports via ``pyserial``, flagging the ones whose USB vendor ID + matches hardware commonly used for LoRa companion devices (ESP32/nRF boards and their + USB-UART bridges). Nothing is hidden — unrecognized adapters still appear, just sorted + after the likely candidates. +* **Bluetooth LE**: nearby devices advertising a ``MeshCore*`` name, scanned via ``bleak``. + Unlike a bare serial adapter, a BLE advert that names itself MeshCore is a strong signal, + so scanned devices are always treated as likely companions. + +This module has no UI and no persistent state; it only reads what is currently attached or +in range. The companion connection itself still goes through +:class:`~meshterm.core.connection.MeshCoreDevice`, which the ``transport`` field selects. """ from __future__ import annotations +import logging from dataclasses import dataclass from typing import Optional +_log = logging.getLogger(__name__) + +#: Transport discriminators for a :class:`DiscoveredDevice` (also stored/remembered as-is). +TRANSPORT_SERIAL = "serial" +TRANSPORT_BLE = "ble" + +#: BLE advertisements from a MeshCore companion begin with this name prefix; the scan filters +#: to it so unrelated Bluetooth gadgets (headphones, watches, beacons) never clutter the list. +BLE_NAME_PREFIX = "MeshCore" + +#: Default seconds to scan for BLE companions. Long enough to hear a nearby device's periodic +#: advertisement, short enough not to stall the startup splash noticeably. +BLE_SCAN_TIMEOUT_S = 5.0 + # USB vendor IDs frequently seen on MeshCore/Meshtastic companion hardware and the # USB-UART bridges they ship with. Used only to name, flag, and sort likely devices. KNOWN_LORA_VIDS: dict[int, str] = { @@ -41,20 +61,28 @@ _CONFIDENCE_RANK: dict[str, int] = {"board": 0, "bridge": 1, "unknown": 2} @dataclass(slots=True) class DiscoveredDevice: - """A serial port found on the system, with USB metadata when available. + """A companion device found on the system, with transport metadata. + + A serial device carries its USB metadata; a Bluetooth LE device carries its BLE + ``address`` and advertised ``name`` instead (its ``port`` is left blank). The + ``transport`` field says which, and :attr:`target` returns the identifier used to + open a connection regardless of kind. Attributes: - port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``). - description: Human-readable description reported by the OS/driver. - hwid: Raw hardware id string from ``pyserial`` (VID/PID/serial blob). + port: Serial port path (e.g. ``COM5`` or ``/dev/ttyUSB0``); ``""`` for BLE. + description: Human-readable description reported by the OS/driver/advert. + hwid: Raw hardware id string from ``pyserial`` (VID/PID/serial blob); serial only. vid: USB vendor ID, if the port is a USB device. pid: USB product ID, if the port is a USB device. serial_number: USB serial number, if exposed by the device. manufacturer: USB manufacturer string, if available. product: USB product string, if available. + transport: ``"serial"`` or ``"ble"`` — which connection layer opens this device. + address: Bluetooth address for a BLE device (e.g. ``AA:BB:CC:DD:EE:FF``). + name: Advertised BLE local name (e.g. ``"MeshCore-Basestation"``); BLE only. """ - port: str + port: str = "" description: str = "" hwid: str = "" vid: Optional[int] = None @@ -62,17 +90,33 @@ class DiscoveredDevice: serial_number: Optional[str] = None manufacturer: Optional[str] = None product: Optional[str] = None + transport: str = TRANSPORT_SERIAL + address: Optional[str] = None + name: Optional[str] = None + + @property + def is_ble(self) -> bool: + """Whether this device is reached over Bluetooth LE rather than a serial port.""" + return self.transport == TRANSPORT_BLE + + @property + def target(self) -> str: + """The identifier a connection opens on: the BLE address, else the serial port.""" + return self.address or self.port if self.is_ble else self.port @property def stable_id(self) -> str: """Return an identifier stable across replug/reboot. - Prefers the USB serial number (survives a changed COM number), then the - ``vid:pid`` pair, and finally the port name as a last resort. + For BLE, the Bluetooth address (stable per adapter pairing). For serial, the USB + serial number (survives a changed COM number), then the ``vid:pid`` pair, and + finally the port name as a last resort. Returns: A non-empty identifier string used to recognize this device later. """ + if self.is_ble: + return f"ble:{(self.address or self.name or '').lower()}" if self.serial_number: return f"sn:{self.serial_number}" if self.vid is not None and self.pid is not None: @@ -81,13 +125,15 @@ class DiscoveredDevice: @property def confidence(self) -> str: - """How likely this port is a LoRa companion, by USB vendor ID. + """How likely this device is a LoRa companion. Returns: - ``"board"`` for a LoRa dev board's native USB (a strong signal), ``"bridge"`` - for a generic USB-UART chip (a weak hint — could be anything), or ``"unknown"`` - for an unrecognized adapter. + ``"board"`` for a BLE device that named itself MeshCore or a LoRa dev board's + native USB (both strong signals), ``"bridge"`` for a generic USB-UART chip (a + weak hint — could be anything), or ``"unknown"`` for an unrecognized adapter. """ + if self.is_ble: + return "board" # a MeshCore-named BLE advert is a confident companion signal if self.vid in NATIVE_LORA_VIDS: return "board" if self.vid in UART_BRIDGE_VIDS: @@ -96,23 +142,32 @@ class DiscoveredDevice: @property def is_likely_lora(self) -> bool: - """Whether the VID belongs to a LoRa board or a serial bridge one commonly uses.""" + """Whether this looks like a companion: a MeshCore BLE advert or a known-VID board.""" return self.confidence != "unknown" @property def vendor_label(self) -> str: - """A friendly vendor name from the known-VID table, or the manufacturer string.""" + """A friendly vendor/transport name for display. + + ``"Bluetooth"`` for a BLE device, else a known-VID vendor name or the USB + manufacturer string. + """ + if self.is_ble: + return "Bluetooth" if self.vid in KNOWN_LORA_VIDS: return KNOWN_LORA_VIDS[self.vid] return self.manufacturer or "" @property def label(self) -> str: - """A concise human-friendly label, e.g. ``"Wio SX1262 (COM5)"``. + """A concise human-friendly label, e.g. ``"Wio SX1262 (COM5)"`` or ``"…(BLE)"``. The OS description often already ends with the port (Windows reports - ``"USB Serial Device (COM11)"``), so the port is not appended a second time. + ``"USB Serial Device (COM11)"``), so the identifier is not appended a second time. """ + if self.is_ble: + name = self.name or self.product or self.description or "Bluetooth device" + return f"{name} (BLE)" name = self.product or self.description or self.vendor_label or "Serial device" suffix = f"({self.port})" if name.endswith(suffix): # avoid "… (COM11) (COM11)" @@ -121,8 +176,8 @@ class DiscoveredDevice: def _sort_key(device: DiscoveredDevice) -> tuple[int, str]: - """Sort LoRa boards first, then serial bridges, then unknown adapters; ties by port.""" - return (_CONFIDENCE_RANK[device.confidence], device.port) + """Sort likely companions first, then bridges, then unknown; ties by target id.""" + return (_CONFIDENCE_RANK[device.confidence], device.target) def discover_devices() -> list[DiscoveredDevice]: @@ -133,7 +188,7 @@ def discover_devices() -> list[DiscoveredDevice]: so callers can fall back to ``--port``/``--mock`` with a friendly message. Returns: - Discovered devices, likely candidates first, then sorted by port name. + Discovered serial devices, likely candidates first, then sorted by port name. """ try: from serial.tools import list_ports @@ -155,3 +210,72 @@ def discover_devices() -> list[DiscoveredDevice]: ] devices.sort(key=_sort_key) return devices + + +async def discover_ble_devices(timeout: float = BLE_SCAN_TIMEOUT_S) -> list[DiscoveredDevice]: + """Scan for nearby Bluetooth LE companions advertising a ``MeshCore*`` name. + + Uses ``bleak`` to listen for advertisements for ``timeout`` seconds and keeps only the + ones whose advertised name marks them as a MeshCore companion. If ``bleak`` is + unavailable, or the platform has no usable Bluetooth adapter, this returns an empty list + rather than raising — BLE is an optional transport, and its absence must never block + serial discovery or the simulator. + + Args: + timeout: Seconds to scan for advertising devices. + + Returns: + Discovered BLE companions (deduplicated by address), sorted by name. + """ + try: + from bleak import BleakScanner + except ImportError: # bleak not installed → BLE simply unavailable + return [] + + try: + found = await BleakScanner.discover(timeout=timeout, return_adv=True) + except Exception as exc: # noqa: BLE001 - no adapter / OS Bluetooth off / driver hiccup + _log.debug("BLE scan unavailable: %s", exc) + return [] + + devices: list[DiscoveredDevice] = [] + for dev, adv in found.values(): + name = (getattr(adv, "local_name", None) or getattr(dev, "name", None) or "").strip() + if not name.startswith(BLE_NAME_PREFIX): + continue + devices.append( + DiscoveredDevice( + transport=TRANSPORT_BLE, + address=dev.address, + name=name, + description=name, + product=name, + ) + ) + devices.sort(key=lambda d: (d.name or "").casefold()) + return devices + + +async def discover_all( + *, ble: bool = True, ble_timeout: float = BLE_SCAN_TIMEOUT_S +) -> list[DiscoveredDevice]: + """Enumerate every attached or in-range companion across all transports. + + Serial enumeration is instant; the BLE scan is what takes ``ble_timeout`` seconds. Serial + devices are listed first (they're already attached and connect fastest), then BLE + companions. + + Args: + ble: Whether to include a Bluetooth LE scan (skip it to avoid the scan delay). + ble_timeout: Seconds to spend scanning for BLE companions. + + Returns: + All discovered devices: serial (likely-LoRa first), then BLE companions. + """ + serial = discover_devices() + if not ble: + return serial + # A device paired over both USB and BLE is vanishingly unlikely to collide by stable_id + # (USB serial number vs BLE address), so no cross-transport dedup is needed here. + ble_devices = await discover_ble_devices(ble_timeout) + return serial + ble_devices diff --git a/meshterm/core/selection.py b/meshterm/core/selection.py index a765dd5..aabafc1 100644 --- a/meshterm/core/selection.py +++ b/meshterm/core/selection.py @@ -13,7 +13,7 @@ from typing import Optional from .config import DeviceProfile from .device_store import RememberedDevice -from .discovery import DiscoveredDevice +from .discovery import TRANSPORT_BLE, TRANSPORT_SERIAL, DiscoveredDevice class DeviceSelectionError(ValueError): @@ -29,22 +29,33 @@ class Resolution: """The outcome of resolving which device to use. Attributes: - port: The chosen serial port. + port: The chosen connection target — the serial port for a serial device, or the + Bluetooth address for a BLE device. (Named ``port`` for historical reasons; use + :attr:`target`.) device: The matching discovered device, when enumeration knows it (so the caller can remember it on a successful connection). ``None`` for an explicit - ``--port``/profile port that is not currently enumerable. - source: Where the choice came from (``"port"``, ``"profile"``, ``"remembered"``, - or ``"only"``), for logging and messaging. + target that is not currently enumerable. + source: Where the choice came from (``"port"``, ``"ble"``, ``"profile"``, + ``"remembered"``, or ``"only"``), for logging and messaging. + transport: ``"serial"`` or ``"ble"`` — which connection layer opens the device. """ port: str device: Optional[DiscoveredDevice] source: str + transport: str = TRANSPORT_SERIAL + + @property + def target(self) -> str: + """The connection target (serial port or BLE address); alias for :attr:`port`.""" + return self.port -def _find_by_port(devices: list[DiscoveredDevice], port: str) -> Optional[DiscoveredDevice]: - """Return the discovered device on ``port``, if enumeration found one.""" - return next((d for d in devices if d.port == port), None) +def _find_by_target( + devices: list[DiscoveredDevice], target: str +) -> Optional[DiscoveredDevice]: + """Return the discovered device whose port or BLE address equals ``target``.""" + return next((d for d in devices if d.target == target or d.port == target), None) def _format_device_list(devices: list[DiscoveredDevice]) -> str: @@ -54,7 +65,10 @@ def _format_device_list(devices: list[DiscoveredDevice]) -> str: lines = [] for d in devices: flag = " [likely LoRa]" if d.is_likely_lora else "" - lines.append(f" • {d.port} — {d.product or d.description or 'serial device'}{flag}") + kind = "BLE" if d.is_ble else "serial" + lines.append( + f" • {d.target} ({kind}) — {d.product or d.description or 'device'}{flag}" + ) return "\n".join(lines) @@ -63,54 +77,64 @@ def resolve_device( remembered: Optional[RememberedDevice], *, explicit_port: Optional[str] = None, + explicit_ble: Optional[str] = None, profile: Optional[DeviceProfile] = None, ) -> Resolution: - """Decide which serial port to use without prompting. + """Decide which companion to connect to without prompting. Resolution priority: - 1. ``explicit_port`` (an explicit ``--port``). - 2. ``profile.port`` (an explicitly chosen profile with a port). - 3. The remembered "last known good" device, if it is currently attached. - 4. The single attached device, if exactly one is present. + 1. ``explicit_ble`` (an explicit ``--ble`` Bluetooth address). + 2. ``explicit_port`` (an explicit ``--port``). + 3. ``profile.port`` (an explicitly chosen profile with a port). + 4. The remembered "last known good" device, if it is currently attached/in range. + 5. The single attached device, if exactly one is present. Otherwise a :class:`DeviceSelectionError` is raised listing the candidates. Args: - devices: Currently discovered devices (see ``discover_devices``). + devices: Currently discovered devices (serial and/or BLE). remembered: The remembered default, if any. explicit_port: A serial port supplied on the command line. + explicit_ble: A Bluetooth address supplied on the command line. profile: A device profile supplied on the command line. Returns: - A :class:`Resolution` naming the chosen port. + A :class:`Resolution` naming the chosen target and transport. Raises: - DeviceSelectionError: If no port can be chosen unambiguously. + DeviceSelectionError: If no device can be chosen unambiguously. """ + if explicit_ble: + return Resolution( + explicit_ble, _find_by_target(devices, explicit_ble), "ble", TRANSPORT_BLE + ) + if explicit_port: - return Resolution(explicit_port, _find_by_port(devices, explicit_port), "port") + match = _find_by_target(devices, explicit_port) + return Resolution(explicit_port, match, "port", TRANSPORT_SERIAL) if profile is not None and profile.port: - return Resolution(profile.port, _find_by_port(devices, profile.port), "profile") + match = _find_by_target(devices, profile.port) + return Resolution(profile.port, match, "profile", TRANSPORT_SERIAL) if remembered is not None: match = next((d for d in devices if remembered.matches(d)), None) if match is not None: - return Resolution(match.port, match, "remembered") + return Resolution(match.target, match, "remembered", match.transport) if len(devices) == 1: - return Resolution(devices[0].port, devices[0], "only") + return Resolution(devices[0].target, devices[0], "only", devices[0].transport) if not devices: raise DeviceSelectionError( - "No serial devices detected. Connect a companion device, or pass --port " - "explicitly, or use --mock for the simulator." + "No companion devices detected. Connect a companion device (USB or Bluetooth), " + "or pass --port / --ble explicitly, or use --mock for the simulator." ) raise DeviceSelectionError( - "Multiple serial devices detected and no default to fall back on.\n" + "Multiple companion devices detected and no default to fall back on.\n" f"{_format_device_list(devices)}\n" - "Choose one with --port (or run 'meshterm devices' to inspect them). " - "The chosen device is remembered as the default after it connects." + "Choose one with --port or --ble
(or run 'meshterm devices' to " + "inspect them). The chosen device is remembered as the default after it connects." ) diff --git a/meshterm/tools/devices.py b/meshterm/tools/devices.py index 5f68930..73b7cee 100644 --- a/meshterm/tools/devices.py +++ b/meshterm/tools/devices.py @@ -1,12 +1,12 @@ -"""The ``devices`` tool: enumerate attached serial companion devices. +"""The ``devices`` tool: enumerate attached serial and in-range Bluetooth companions. -Discovery never opens the radio — it only lists what is attached. This is a CLI-only, -read-only inventory (``menu_visible = False``): by the time the interactive menu is up a -device is already selected, so the listing has no job there — it belongs on the command line -as a startup-time "which port is my radio?" diagnostic. It marks devices already confirmed as -MeshCore companions (and the active one). Selecting a companion is a startup-only concern: -pass ``--port`` on the CLI (remembered after it connects), or pick from the prompt shown when -the menu launches (which smoke-tests the choice before confirming it). +Discovery never opens the radio — it only lists what is attached or advertising. This is a +CLI-only, read-only inventory (``menu_visible = False``): by the time the interactive menu is +up a device is already selected, so the listing has no job there — it belongs on the command +line as a startup-time "which port/address is my radio?" diagnostic. It marks devices already +confirmed as MeshCore companions (and the active one). Selecting a companion is a startup-only +concern: pass ``--port`` or ``--ble`` on the CLI (remembered after it connects), or pick from +the prompt shown when the menu launches (which smoke-tests the choice before confirming it). """ from __future__ import annotations @@ -17,7 +17,7 @@ import typer from rich.table import Table from ..context import AppContext -from ..core.discovery import discover_devices +from ..core.discovery import discover_all, discover_devices from .base import Tool, ToolResult, register #: "MeshCore?" table cell per discovery confidence tier, for devices we have *not* yet @@ -36,10 +36,10 @@ _CONFIRMED_CELL = "[ok]yes[/ok]" @register class DevicesTool(Tool): - """List attached serial devices, flag likely LoRa hardware, mark the default.""" + """List attached serial + in-range Bluetooth companions, flag likely LoRa, mark the default.""" name = "devices" - help = "List attached serial devices and flag likely LoRa hardware." + help = "List attached serial and Bluetooth companion devices and flag likely LoRa hardware." category = "Device" order = 5 menu_visible = False # CLI-only: a startup diagnostic with no place in a connected session @@ -54,18 +54,24 @@ class DevicesTool(Tool): Returns: A :class:`ToolResult` summarizing how many devices were found. """ - devices = discover_devices() + scan_ble = params.get("ble", True) + devices = await discover_all(ble=scan_ble) if scan_ble else discover_devices() known = ctx.device_store.load_all() remembered = ctx.device_store.load() active = ctx.selected_device - active_port = ctx.port_override or (active.port if active else None) + active_target = ctx.ble_override or ctx.port_override or ( + active.target if active else None + ) if ctx.json_output: import json payload = [ { + "transport": d.transport, "port": d.port, + "address": d.address, + "target": d.target, "label": d.label, "vendor": d.vendor_label, "likely_lora": d.is_likely_lora, @@ -74,7 +80,7 @@ class DevicesTool(Tool): "serial_number": d.serial_number, "stable_id": d.stable_id, "remembered": remembered is not None and remembered.matches(d), - "active": d.port == active_port, + "active": d.target == active_target, } for d in devices ] @@ -83,28 +89,29 @@ class DevicesTool(Tool): if not devices: ctx.ui.note( - "[warn]No serial devices detected.[/warn] " - "Connect a companion device, or use [accent]--mock[/accent] for the simulator." + "[warn]No companion devices detected.[/warn] " + "Connect one over USB or power on a Bluetooth companion nearby, or use " + "[accent]--mock[/accent] for the simulator." ) return ToolResult(summary={"count": 0}) - table = Table(title="Serial devices", border_style="muted", expand=False) + table = Table(title="Companion devices", border_style="muted", expand=False) table.add_column("", style="ok", no_wrap=True) # active/confirmed markers - table.add_column("Port", style="brand") + table.add_column("Port / Address", style="brand") table.add_column("Device") table.add_column("Vendor", style="muted") table.add_column("MeshCore?", justify="center") table.add_column("Serial", style="muted") for d in devices: confirmed = known.get(d.stable_id) # the remembered record, if ever confirmed - is_active = d.port == active_port + is_active = d.target == active_target marker = ("●" if is_active else "") + ("★" if confirmed else "") - device_name = d.product or d.description or "[muted]?[/muted]" + device_name = d.name or d.product or d.description or "[muted]?[/muted]" if confirmed and confirmed.node_name: # the mesh name learned on connect device_name = f"{confirmed.node_name} [muted]({device_name})[/muted]" table.add_row( marker, - d.port, + d.target, device_name, d.vendor_label or "[muted]?[/muted]", _CONFIRMED_CELL if confirmed else _MAYBE_CELL[d.confidence], @@ -113,7 +120,7 @@ class DevicesTool(Tool): ctx.ui.show(table) ctx.ui.note( "[muted]● active ★ confirmed MeshCore device. " - "Pass --port to select on the CLI.[/muted]" + "Pass --port or --ble
to select on the CLI.[/muted]" ) return ToolResult(summary={"count": len(devices)}) @@ -126,5 +133,9 @@ class DevicesTool(Tool): from ..cli import run_tool_command @app.command(name=self.name, help=self.help) - def _devices() -> None: - run_tool_command(self, {}) + def _devices( + ble: bool = typer.Option( + True, "--ble/--no-ble", help="Include a Bluetooth LE scan (adds a few seconds)." + ), + ) -> None: + run_tool_command(self, {"ble": ble}) diff --git a/meshterm/ui/device_picker.py b/meshterm/ui/device_picker.py index 3021fe2..ef8d100 100644 --- a/meshterm/ui/device_picker.py +++ b/meshterm/ui/device_picker.py @@ -49,6 +49,8 @@ def _pad(text: str, width: int) -> str: def _hardware_name(device: DiscoveredDevice) -> str: """The device's product name without its trailing ``(port)`` (that is its own column).""" + if device.is_ble: + return device.name or device.product or device.description or "Bluetooth device" name = device.product or device.description or device.vendor_label or "Serial device" suffix = f"({device.port})" if name.endswith(suffix): @@ -56,6 +58,11 @@ def _hardware_name(device: DiscoveredDevice) -> str: return name +def _where(device: DiscoveredDevice) -> str: + """The connection target shown in the middle column: serial port or BLE address.""" + return device.target + + def _node_name_from(info: dict) -> str: """Return a device's own mesh node name from its self-info payload, or ``""``.""" return str(info.get("adv_name") or info.get("name") or "") @@ -89,8 +96,10 @@ async def prompt_device( if not devices: await ui.notify_startup( Text.from_markup( - "[warn]No serial devices detected.[/warn]\n" - "Plug one in, pass [accent]--port[/accent], or run with [accent]--mock[/accent]." + "[warn]No companion devices detected.[/warn]\n" + "Plug one in over USB or power on a Bluetooth companion nearby, pass " + "[accent]--port[/accent]/[accent]--ble[/accent], or run with " + "[accent]--mock[/accent]." ), title="Select a companion device", banner=load_logo(), @@ -126,10 +135,13 @@ async def prompt_device( name = remembered.node_name if ( remembered and remembered.matches(chosen) and remembered.node_name ) else _hardware_name(chosen) + # "over Bluetooth" reads better than an address; a serial device names its port. + where = "over Bluetooth" if chosen.is_ble else f"on {chosen.port}" # Smoke-test the choice in place: the splash keeps its wordmark and box, only the box - # contents swap for an animated spinner while we talk to the device. + # contents swap for an animated spinner while we talk to the device. BLE connect and + # service discovery take a few seconds, so the spinner matters most here. info = await ui.busy_startup( - f"Talking to {name} on {chosen.port}…", + f"Talking to {name} {where}…", verify(chosen), title="Checking companion", banner=load_logo(), @@ -137,10 +149,15 @@ async def prompt_device( ) if info is None: + reason = ( + "It may be out of range, powered off, already connected elsewhere, or busy." + if chosen.is_ble + else "It may be a different kind of serial device, powered off, or busy." + ) await ui.notify_startup( Text.from_markup( - f"[warn]{name} on {chosen.port} didn't answer as a MeshCore device.[/warn]\n" - "It may be a different kind of serial device, powered off, or busy.\n" + f"[warn]{name} {where} didn't answer as a MeshCore device.[/warn]\n" + f"{reason}\n" "Choose another device." ), title="Not a MeshCore device", @@ -174,8 +191,13 @@ def _build_items( name_w = max(cell_len(_name(d)) for d in devices) name_w = max(name_w, len("DEVICE")) - port_w = max(cell_len(d.port) for d in devices) - port_w = max(port_w, len("PORT")) + # The middle column holds a serial port or a BLE address; label it for whichever kinds + # are present so a Bluetooth address never sits under a bare "PORT" heading. + port_label = "PORT" + if any(d.is_ble for d in devices): + port_label = "ADDRESS" if all(d.is_ble for d in devices) else "PORT / ADDRESS" + port_w = max(cell_len(_where(d)) for d in devices) + port_w = max(port_w, len(port_label)) vendor_w = max(cell_len(d.vendor_label) for d in devices) vendor_w = max(vendor_w, len("VENDOR")) @@ -184,7 +206,7 @@ def _build_items( header = Separator( " " + _pad("DEVICE", name_w) - + " " + _pad("PORT", port_w) + + " " + _pad(port_label, port_w) + " " + "VENDOR" ) @@ -196,14 +218,18 @@ def _build_items( row.append(" ") row.append(_pad(_name(device), name_w)) row.append(" ") - row.append(_pad(device.port, port_w), style="muted") + row.append(_pad(_where(device), port_w), style="muted") row.append(" ") row.append(_pad(device.vendor_label, vendor_w), style="muted") - # Only devices we've actually confirmed are billed as MeshCore companions; the USB - # vendor ID is a sort hint, not a claim. A bare serial bridge earns an honest label. + # Only devices we've actually confirmed are billed as MeshCore companions; a USB + # vendor ID (or a BLE advert) is a sort hint, not a claim. A bare serial bridge earns + # an honest label; a MeshCore-named BLE advert is flagged as a likely companion. if device.stable_id in known: row.append(" ") row.append("· MeshCore device", style="ok") + elif device.is_ble: + row.append(" ") + row.append("· Bluetooth companion", style="muted") elif device.confidence == "bridge": row.append(" ") row.append("· serial adapter", style="muted") diff --git a/meshterm/ui/menu.py b/meshterm/ui/menu.py index a130adb..0117c08 100644 --- a/meshterm/ui/menu.py +++ b/meshterm/ui/menu.py @@ -262,22 +262,34 @@ async def _startup(ctx: AppContext) -> bool: splash (pressed Esc or picked Quit) — in which case the caller skips the menu loop. """ if not (ctx.mock or ctx.explicit_selection): - from ..core.connection import probe_meshcore - from ..core.discovery import DiscoveredDevice, discover_devices + from ..core.connection import probe_device + from ..core.discovery import DiscoveredDevice, discover_all from .device_picker import prompt_device + from .logo import load_logo - devices = discover_devices() baudrate = ctx.profile.baudrate if ctx.profile else 115200 + # Enumerate serial ports (instant) and scan for BLE companions (a few seconds), behind + # the splash spinner so the wait reads as intentional rather than a hang. + from datetime import datetime + + footnote = f"© {datetime.now().year} Johnputer" + devices = await ctx.ui.busy_startup( + "Scanning for companion devices…", + discover_all(ble=True), + title="Select a companion device", + banner=load_logo(), + footnote=footnote, + ) # The smoke test opens the radio; on success we keep that live connection and reuse - # it for the session rather than reopening (boards often reset on each serial open). + # it for the session rather than reopening (boards often reset on each open). probed: dict = {} async def verify(device: DiscoveredDevice): - result = await probe_meshcore(device.port, baudrate) + result = await probe_device(device, baudrate=baudrate, pin=ctx.ble_pin) if result is None: return None connection, info = result - probed["port"] = device.port + probed["device_id"] = device.stable_id probed["device"] = connection return info @@ -285,8 +297,13 @@ async def _startup(ctx: AppContext) -> bool: if chosen is None: return False # the user quit at the splash — exit without opening the menu ctx.selected_device = chosen - ctx.port_override = chosen.port - if probed.get("port") == chosen.port: + if chosen.is_ble: + ctx.ble_override = chosen.address + ctx.port_override = None + else: + ctx.port_override = chosen.port + ctx.ble_override = None + if probed.get("device_id") == chosen.stable_id: ctx.adopt_device(probed["device"]) await _resume_monitor(ctx) return True @@ -420,31 +437,30 @@ async def _cancel_and_wait(task: "asyncio.Future") -> None: async def _wait_for_disconnect(ctx: AppContext) -> None: - """Resolve once the connected companion's serial port disappears from the OS. + """Resolve once the connected companion's transport link drops. - Polls the OS serial-port enumeration rather than watching for a failed command: the - ``meshcore`` client keeps serving cached data after an unplug and never raises (confirmed - on hardware), so an *active* liveness check is the only thing that reliably notices a - pulled cable. Never resolves for the simulator (it can't be unplugged) or before a real - device has actually been opened. + Polls a cheap, non-invasive liveness check (:meth:`AppContext.link_alive`) rather than + watching for a failed command: the ``meshcore`` client keeps serving cached data after a + serial unplug and never raises (confirmed on hardware), so an *active* liveness check is + the only thing that reliably notices a pulled cable. The same check covers Bluetooth, + where it reads the BLE client's connection flag (which flips the moment the peripheral + drops or goes out of range). Never resolves for the simulator (it can't be unplugged) or + before a real device has actually been opened. Args: - ctx: The shared application context (read for the active port and connection state). + ctx: The shared application context (read for the connection state and liveness). """ - from ..core.connection import serial_port_present - if ctx.mock: await asyncio.Event().wait() # the simulator is never "unplugged"; wait forever return while True: await asyncio.sleep(_LIVENESS_POLL_S) - port = ctx.active_port - if port is None or not ctx.is_connected: + if not ctx.is_connected: continue # nothing connected to watch yet (deferred connect / no device) - if serial_port_present(port): + if await ctx.link_alive(): continue - await asyncio.sleep(_LIVENESS_CONFIRM_S) # debounce a transient enumeration gap - if not serial_port_present(port): + await asyncio.sleep(_LIVENESS_CONFIRM_S) # debounce a transient enumeration/link gap + if not await ctx.link_alive(): return @@ -498,11 +514,14 @@ async def _animate_dialog(session: TuiSession, dialog: ReconnectDialog) -> None: async def _auto_reconnect(ctx: AppContext, dialog: ReconnectDialog) -> None: """Poll for the device to return, reconnect when it does, then dismiss ``dialog``. - Waits for the OS to re-enumerate the port the connection was opened on before each - attempt, so a reconnect is only tried once there's a device to reach; a failed attempt - (the port is back but the board isn't ready yet, or it dropped again) simply loops and - retries. On the first success the dialog's future is resolved with ``"reconnected"``, - which dismisses the popup. Runs until it succeeds or the task is cancelled (the user quit). + For serial, waits for the OS to re-enumerate the port the connection was opened on before + each attempt, so a reconnect is only tried once there's a device to reach. For Bluetooth + there is no cheap "is it back yet" probe short of a full scan, so it simply attempts a + reconnect each interval — ``create_ble`` connects directly by address and fails fast when + the peripheral isn't in range. Either way a failed attempt (the endpoint is back but the + board isn't ready yet, or it dropped again) just loops and retries. On the first success + the dialog's future is resolved with ``"reconnected"``, dismissing the popup. Runs until + it succeeds or the task is cancelled (the user quit). Args: ctx: The shared application context. @@ -511,12 +530,13 @@ async def _auto_reconnect(ctx: AppContext, dialog: ReconnectDialog) -> None: from ..core.connection import serial_port_present while True: - port = ctx.active_port - # Wait for the port to re-appear before touching the radio (skip the wait when there's - # no port to poll — e.g. an unknown/deferred port — and just retry on the interval). - if port is not None and not serial_port_present(port): - await asyncio.sleep(_LIVENESS_POLL_S) - continue + # Serial: wait for the port to re-appear before touching the radio. BLE (and an + # unknown/deferred serial port): skip the wait and just retry the reconnect itself. + if ctx.active_transport == "serial": + port = ctx.active_port + if port is not None and not serial_port_present(port): + await asyncio.sleep(_LIVENESS_POLL_S) + continue try: await ctx.reconnect() except Exception: # noqa: BLE001 - not reachable yet; keep the popup up and retry diff --git a/pyproject.toml b/pyproject.toml index 181b29c..6830f1b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,6 +15,7 @@ keywords = ["meshcore", "lora", "mesh", "radio", "cli"] dependencies = [ "meshcore>=2.3", # companion-device protocol (serial/BLE/TCP) "pyserial>=3.5", # serial-port enumeration for device discovery + "bleak>=0.22", # Bluetooth LE scanning + companion connection "typer>=0.12", # scripted CLI; subcommands mirror the menu "rich>=13.7", # modern console rendering (progress, tables, panels) "prompt_toolkit>=3.0", # full-screen interactive TUI (terminal, input, resize) diff --git a/tests/test_disconnect.py b/tests/test_disconnect.py index 2be3f20..ba5c71f 100644 --- a/tests/test_disconnect.py +++ b/tests/test_disconnect.py @@ -30,6 +30,23 @@ class _SerialException(Exception): """A stand-in for ``serial.SerialException`` (matched by type name, not import).""" +class _FakeSerialDevice: + """A minimal stand-in for a connected serial :class:`Device` in liveness tests. + + Its :meth:`link_present` mirrors the real serial device: it reports whether the port is + still enumerated by the OS, reading through the (monkeypatched) module function so tests + can flip presence on and off. + """ + + transport = "serial" + + def __init__(self, port: str = "COM_TEST") -> None: + self._port = port + + async def link_present(self) -> bool: + return connection.serial_port_present(self._port) + + def test_is_connection_lost_matches_serial_exception() -> None: """A pyserial-style read/write failure is classified as a dropped link.""" assert is_connection_lost(_SerialException("ClearCommError failed (Access is denied.)")) @@ -58,6 +75,24 @@ def test_is_connection_lost_ignores_ordinary_failures() -> None: assert not is_connection_lost(ValueError("bad value")) +# These stand-ins are named to match bleak's real classes, since the classifier matches by +# type name (not import) — see ``_CONNECTION_LOST_TYPES``. +class BleakError(Exception): # noqa: N818 - mirrors bleak's own (non-Error-suffixed) name + """A stand-in for ``bleak.exc.BleakError`` (matched by type name, not import).""" + + +class BleakDeviceNotFoundError(Exception): + """A stand-in for ``bleak.exc.BleakDeviceNotFoundError``.""" + + +def test_is_connection_lost_matches_ble_errors() -> None: + """A dropped Bluetooth link is classified as a lost connection, like a serial unplug.""" + assert is_connection_lost(BleakError("gatt operation failed")) # matched by type name + assert is_connection_lost(BleakDeviceNotFoundError("AA:BB:CC not found")) + # The meshcore BLE transport reports link loss via a callback reason string. + assert is_connection_lost(RuntimeError("ble_transport_lost")) + + def _make_ctx(tmp_path: Path) -> AppContext: """Build a real, mock-backed application context for reconnect tests.""" settings = Settings(config_dir=tmp_path, db_path=tmp_path / "disc.db") @@ -94,6 +129,56 @@ async def test_reconnect_rebuilds_device_and_restores_services(tmp_path: Path) - await ctx.aclose() +async def test_ble_profile_opens_bluetooth_transport(tmp_path: Path, monkeypatch) -> None: + """A BLE profile makes ``device()`` build a Bluetooth connection by address.""" + from meshterm.core import connection as conn + from meshterm.core.config import DeviceProfile + + settings = Settings(config_dir=tmp_path, db_path=tmp_path / "ble.db") + ctx = AppContext( + console=Console(file=io.StringIO()), + settings=settings, + repo=Repository(settings.db_path), + device_store=DeviceStore(tmp_path / "devices.json"), + admin_store=AdminStore(tmp_path / "admin.json"), + profile=DeviceProfile(name="handheld", transport="ble", address="AA:BB:CC:DD:EE:FF"), + ) + + built: dict = {} + + class _FakeBle: + transport = "ble" + + def __init__(self, **kw): + built.update(kw) + self._port = None + self._address = kw.get("address") + + async def connect(self): + pass + + async def get_self_info(self): + return {"name": "Handheld"} + + def fake_make_device(**kw): + assert kw["transport"] == "ble" + return _FakeBle(**kw) + + monkeypatch.setattr(conn, "make_device", fake_make_device) + # context imported make_device by name, so patch the reference it actually calls. + import meshterm.context as context_mod + + monkeypatch.setattr(context_mod, "make_device", fake_make_device) + try: + device = await ctx.device() + assert device.transport == "ble" + assert built["address"] == "AA:BB:CC:DD:EE:FF" + assert ctx.active_transport == "ble" + assert ctx.active_port is None # BLE has no serial port to watch + finally: + ctx.repo.close() + + async def test_reconnect_leaves_idle_services_idle(tmp_path: Path) -> None: """Reconnect only restores what was live: idle services stay idle afterward.""" ctx = _make_ctx(tmp_path) @@ -187,7 +272,8 @@ async def test_wait_for_disconnect_fires_when_port_vanishes( ctx = _make_ctx(tmp_path) # Pose as a live real-hardware session on COM_TEST (the mock can't be unplugged). ctx.mock = False - ctx._device = object() # stand-in for a connected device; is_connected -> True + ctx._device = _FakeSerialDevice("COM_TEST") # connected device; is_connected -> True + ctx._active_transport = "serial" ctx._active_port = "COM_TEST" checks = {"n": 0} @@ -215,6 +301,45 @@ async def test_wait_for_disconnect_ignores_the_simulator(tmp_path: Path) -> None ctx.repo.close() +class _FakeBleDevice: + """A minimal stand-in for a connected BLE :class:`Device` in liveness tests. + + Its :meth:`link_present` reads an ``is_connected`` flag, mirroring how the real BLE + device reads the meshcore client's connection state. + """ + + transport = "ble" + + def __init__(self) -> None: + self.is_connected = True + + async def link_present(self) -> bool: + return self.is_connected + + +async def test_wait_for_disconnect_fires_when_ble_link_drops( + tmp_path: Path, monkeypatch +) -> None: + """The same watcher fires for BLE once the peripheral's connection flag flips false.""" + ctx = _make_ctx(tmp_path) + ctx.mock = False + device = _FakeBleDevice() + ctx._device = device + ctx._active_transport = "ble" + ctx._active_address = "AA:BB:CC:DD:EE:FF" + + async def drop_soon() -> None: + device.is_connected = False # the peripheral goes out of range + + monkeypatch.setattr(menu, "_LIVENESS_POLL_S", 0.0) + monkeypatch.setattr(menu, "_LIVENESS_CONFIRM_S", 0.0) + try: + await drop_soon() + await asyncio.wait_for(menu._wait_for_disconnect(ctx), timeout=2.0) + finally: + ctx.repo.close() + + class _FakeSession: """A minimal stand-in for :class:`TuiSession` recording pushes/pops for dialog tests.""" diff --git a/tests/test_discovery.py b/tests/test_discovery.py index 82e07ac..8f15bd8 100644 --- a/tests/test_discovery.py +++ b/tests/test_discovery.py @@ -119,6 +119,78 @@ def test_stable_id_precedence() -> None: assert DiscoveredDevice("COM5").stable_id == "port:COM5" +# -- BLE transport ------------------------------------------------------------- + + +def _ble(address: str = "AA:BB:CC:DD:EE:FF", name: str = "MeshCore-Base") -> DiscoveredDevice: + """Build a BLE DiscoveredDevice as the scanner would.""" + return DiscoveredDevice( + transport="ble", address=address, name=name, description=name, product=name + ) + + +def test_ble_device_identity_and_labels() -> None: + """A BLE device reports its address as the target, a stable ble: id, and a BLE label.""" + dev = _ble() + assert dev.is_ble + assert dev.target == "AA:BB:CC:DD:EE:FF" # the connection identifier is the address + assert dev.stable_id == "ble:aa:bb:cc:dd:ee:ff" # stable across sessions, case-folded + assert dev.confidence == "board" and dev.is_likely_lora # a MeshCore advert is confident + assert dev.vendor_label == "Bluetooth" + assert dev.label == "MeshCore-Base (BLE)" + + +def test_ble_and_serial_stable_ids_never_collide() -> None: + """A BLE address and a serial number/port can't map to the same remembered device.""" + assert _ble().stable_id != DiscoveredDevice("COM5", serial_number="SN1").stable_id + + +async def test_discover_ble_filters_to_meshcore(monkeypatch: pytest.MonkeyPatch) -> None: + """The BLE scan keeps only MeshCore-named adverts and maps them to devices.""" + from types import SimpleNamespace + + import meshterm.core.discovery as discovery + + class _FakeScanner: + @staticmethod + async def discover(timeout: float, return_adv: bool): + return { + "AA:BB:CC:DD:EE:FF": ( + SimpleNamespace(address="AA:BB:CC:DD:EE:FF", name="MeshCore-Base"), + SimpleNamespace(local_name="MeshCore-Base", rssi=-60), + ), + "11:22:33:44:55:66": ( # a random unrelated Bluetooth gadget — filtered out + SimpleNamespace(address="11:22:33:44:55:66", name="AirPods"), + SimpleNamespace(local_name="AirPods", rssi=-70), + ), + } + + monkeypatch.setattr(discovery, "BleakScanner", _FakeScanner, raising=False) + # ``discover_ble_devices`` imports BleakScanner from bleak inside the function; patch there. + import bleak + + monkeypatch.setattr(bleak, "BleakScanner", _FakeScanner, raising=False) + + devices = await discovery.discover_ble_devices(timeout=0.0) + assert [d.name for d in devices] == ["MeshCore-Base"] + assert devices[0].is_ble and devices[0].address == "AA:BB:CC:DD:EE:FF" + + +async def test_discover_ble_survives_no_adapter(monkeypatch: pytest.MonkeyPatch) -> None: + """A scan failure (no adapter / Bluetooth off) yields an empty list, never raises.""" + import bleak + + import meshterm.core.discovery as discovery + + class _BoomScanner: + @staticmethod + async def discover(timeout: float, return_adv: bool): + raise OSError("no Bluetooth adapter") + + monkeypatch.setattr(bleak, "BleakScanner", _BoomScanner, raising=False) + assert await discovery.discover_ble_devices(timeout=0.0) == [] + + # -- device store -------------------------------------------------------------- @@ -228,19 +300,60 @@ def test_resolve_single_device_auto() -> None: assert res.port == "COM3" and res.source == "only" +def test_resolve_prefers_explicit_ble() -> None: + """An explicit --ble selects the BLE transport and wins over everything else.""" + res = resolve_device([], None, explicit_ble="AA:BB:CC:DD:EE:FF") + assert res.target == "AA:BB:CC:DD:EE:FF" + assert res.transport == "ble" and res.source == "ble" + + +def test_resolve_single_ble_device_auto() -> None: + """A lone in-range BLE companion is chosen automatically, transport and all.""" + dev = _ble() + res = resolve_device([dev], None) + assert res.target == dev.address and res.transport == "ble" and res.source == "only" + + +def test_resolve_uses_remembered_ble_device() -> None: + """A remembered BLE default reconnects by address when it's back in range.""" + from meshterm.core.device_store import RememberedDevice + + dev = _ble() + remembered = RememberedDevice( + stable_id=dev.stable_id, port="", label=dev.label, last_connected="", + transport="ble", address=dev.address, + ) + res = resolve_device([dev], remembered) + assert res.transport == "ble" and res.target == dev.address and res.source == "remembered" + + +def test_ble_device_store_round_trip(tmp_path: Path) -> None: + """A remembered BLE device persists its transport and address, matched by stable_id.""" + store = DeviceStore(tmp_path / "devices.json") + dev = _ble(name="MeshCore-Roamer") + store.remember(dev, node_name="Roamer") + + loaded = store.load() + assert loaded is not None + assert loaded.is_ble and loaded.transport == "ble" + assert loaded.address == dev.address and loaded.target == dev.address + assert loaded.node_name == "Roamer" + assert loaded.matches(dev) + + def test_resolve_ambiguous_raises(tmp_path: Path) -> None: """Multiple devices with no usable default raise a guidance error.""" devices = [ DiscoveredDevice("COM3", serial_number="SN1"), DiscoveredDevice("COM4", serial_number="SN2"), ] - with pytest.raises(DeviceSelectionError, match="Multiple serial devices"): + with pytest.raises(DeviceSelectionError, match="Multiple companion devices"): resolve_device(devices, None) def test_resolve_no_devices_raises() -> None: """No devices at all raises a clear error mentioning --mock.""" - with pytest.raises(DeviceSelectionError, match="No serial devices"): + with pytest.raises(DeviceSelectionError, match="No companion devices"): resolve_device([], None)