Introduce an always-on event hub and broaden the device event surface
Decouple listening from consuming as the first step toward a full MeshCore client. A new always-on EventHub owns the single device subscription and fans typed MeshEvents out to any number of subscribers; passive-monitor history logging becomes just one subscriber, so listening is now unconditional while the on/off toggle controls only persistence. - core/events.py: MeshEvent envelope + EventKind (OBSERVATION/MESSAGE/ACK) - services/event_hub.py: subscribe/stream/wait_for fan-out, always-on pump - connection.py: Device.subscribe_observations -> unified subscribe_events emitting observations, inbound messages, and acks; add message_from_event / ack_from_event mappers and a simulated message stream on MockDevice - core/models.py: Message and Ack domain models - monitor_service.py: slim to a hub subscriber (recording, not listening) - context.py/menu.py: wire ctx.events into the session lifecycle - config.py: connect_on_start setting (default on) to allow lazy connect - Remove monitor --seconds / foreground capture and Device.listen; monitoring is passive/background only Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
1 parent
2a9facc56e
commit
20c32f9642
12 files changed
+873
-243
No files matched your search
+19
-1
@@ -22,6 +22,7 @@ from .persistence.logging import get_logger
|
||||
from .persistence.repository import Repository
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .services.event_hub import EventHub
|
||||
from .services.monitor_service import MonitorService
|
||||
from .ui.surface import Ui
|
||||
|
||||
@@ -59,6 +60,7 @@ class AppContext:
|
||||
selected_device: Optional[DiscoveredDevice] = None
|
||||
explicit_selection: bool = False
|
||||
_device: Optional[Device] = field(default=None, init=False, repr=False)
|
||||
_events: "Optional[EventHub]" = field(default=None, init=False, repr=False)
|
||||
_monitor: "Optional[MonitorService]" = field(default=None, init=False, repr=False)
|
||||
_ui: "Optional[Ui]" = field(default=None, init=False, repr=False)
|
||||
|
||||
@@ -86,6 +88,20 @@ class AppContext:
|
||||
"""Install a UI surface (used by the menu to switch to the full-screen TUI)."""
|
||||
self._ui = value
|
||||
|
||||
@property
|
||||
def events(self) -> "EventHub":
|
||||
"""Return the session's always-on event hub, creating it on first use.
|
||||
|
||||
The hub owns the single device event subscription and fans events out to any
|
||||
number of subscribers (the passive monitor's logging is one of them). It is
|
||||
created idle here; the interactive session starts it once a device is available.
|
||||
"""
|
||||
if self._events is None:
|
||||
from .services.event_hub import EventHub
|
||||
|
||||
self._events = EventHub(self)
|
||||
return self._events
|
||||
|
||||
@property
|
||||
def monitor(self) -> "MonitorService":
|
||||
"""Return the session's passive-monitor service, creating it on first use.
|
||||
@@ -147,9 +163,11 @@ class AppContext:
|
||||
return self._device
|
||||
|
||||
async def aclose(self) -> None:
|
||||
"""Stop monitoring, disconnect the device (if connected), and close the repo."""
|
||||
"""Stop monitoring, stop the event hub, disconnect the device, and close the repo."""
|
||||
if self._monitor is not None:
|
||||
await self._monitor.aclose()
|
||||
if self._events is not None:
|
||||
await self._events.aclose()
|
||||
if self._device is not None:
|
||||
await self._device.disconnect()
|
||||
self._device = None
|
||||
|
||||
@@ -66,6 +66,10 @@ class Settings:
|
||||
trace_cooldown_s: Minimum delay between transmit bursts (duty-cycle safety).
|
||||
tx_opt_min: Lowest TX power explored by the remote-admin optimizer (dBm).
|
||||
tx_opt_max: Highest TX power explored by the remote-admin optimizer (dBm).
|
||||
connect_on_start: Whether the interactive session opens the companion connection
|
||||
(and starts always-on background listening) immediately at launch. When
|
||||
``False`` the connection is opened lazily — only once monitoring is turned on
|
||||
or a tool first needs the radio — so launching the menu touches no serial port.
|
||||
"""
|
||||
|
||||
config_dir: Path = field(default_factory=default_config_dir)
|
||||
@@ -76,6 +80,7 @@ class Settings:
|
||||
trace_cooldown_s: float = 1.0
|
||||
tx_opt_min: int = 12
|
||||
tx_opt_max: int = 28
|
||||
connect_on_start: bool = True
|
||||
|
||||
def __post_init__(self) -> None:
|
||||
"""Derive dependent paths that were not explicitly provided."""
|
||||
@@ -136,4 +141,5 @@ class Settings:
|
||||
trace_cooldown_s=float(data.get("trace_cooldown_s", 1.0)),
|
||||
tx_opt_min=int(data.get("tx_opt_min", 12)),
|
||||
tx_opt_max=int(data.get("tx_opt_max", 28)),
|
||||
connect_on_start=bool(data.get("connect_on_start", True)),
|
||||
)
|
||||
+121
-68
@@ -16,14 +16,17 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
import random
|
||||
from abc import ABC, abstractmethod
|
||||
from datetime import datetime, timezone
|
||||
from typing import Callable, Optional
|
||||
|
||||
from .models import Contact, Hop, Observation, TraceResult
|
||||
from .events import MeshEvent
|
||||
from .models import Ack, Contact, Hop, Message, Observation, TraceResult
|
||||
|
||||
#: Callback invoked with each :class:`Observation` as passive monitoring captures it.
|
||||
ObservationCallback = Callable[[Observation], None]
|
||||
#: Callback invoked with each :class:`~meshtools.core.events.MeshEvent` the device emits
|
||||
#: (an overheard packet, an inbound message, an acknowledgement).
|
||||
EventCallback = Callable[[MeshEvent], None]
|
||||
|
||||
#: Zero-argument callable returned by :meth:`Device.subscribe_observations` that stops the
|
||||
#: Zero-argument callable returned by :meth:`Device.subscribe_events` that stops the
|
||||
#: subscription and releases its resources when invoked.
|
||||
Unsubscribe = Callable[[], None]
|
||||
|
||||
@@ -153,64 +156,34 @@ class Device(ABC):
|
||||
A :class:`TraceResult`; ``success`` is ``False`` on timeout.
|
||||
"""
|
||||
|
||||
# -- passive monitoring ------------------------------------------------------
|
||||
# -- passive event stream ----------------------------------------------------
|
||||
|
||||
@abstractmethod
|
||||
async def subscribe_observations(
|
||||
self, on_observation: "ObservationCallback"
|
||||
) -> "Unsubscribe":
|
||||
"""Begin passively capturing overheard packets, without blocking the caller.
|
||||
async def subscribe_events(self, on_event: "EventCallback") -> "Unsubscribe":
|
||||
"""Begin streaming the device's unsolicited inbound events, without blocking.
|
||||
|
||||
Subscribes to the adverts (and, where the firmware surfaces them, telemetry
|
||||
frames) the companion overhears and invokes ``on_observation`` with each
|
||||
:class:`~meshtools.core.models.Observation` as it arrives. Capture continues in
|
||||
the background until the returned callable is invoked to stop it; the radio is
|
||||
never asked to transmit, it only listens. This is the primitive behind both the
|
||||
always-on background monitor and the bounded :meth:`listen` helper.
|
||||
Subscribes to everything the companion surfaces on its own: overheard adverts and
|
||||
telemetry (as :attr:`~meshtools.core.events.EventKind.OBSERVATION` events), inbound
|
||||
direct/channel text messages (:attr:`~meshtools.core.events.EventKind.MESSAGE`),
|
||||
and delivery acknowledgements (:attr:`~meshtools.core.events.EventKind.ACK`). Each
|
||||
is delivered to ``on_event`` as a :class:`~meshtools.core.events.MeshEvent` as it
|
||||
arrives. Delivery continues in the background until the returned callable is
|
||||
invoked to stop it; the radio is never asked to transmit, it only listens. This is
|
||||
the primitive the always-on :class:`~meshtools.services.event_hub.EventHub` is
|
||||
built on.
|
||||
|
||||
Note:
|
||||
This carries only *unsolicited* events. Replies correlated to a request we
|
||||
sent (a trace's ``TRACE_DATA``, a login result) are awaited by the issuing
|
||||
command instead, so those flows work with or without a live subscription.
|
||||
|
||||
Args:
|
||||
on_observation: Callback invoked with each observation as it is heard.
|
||||
on_event: Callback invoked with each :class:`MeshEvent` as it is heard.
|
||||
|
||||
Returns:
|
||||
A zero-argument callable that stops capture and releases the subscription.
|
||||
A zero-argument callable that stops the stream and releases the subscription.
|
||||
"""
|
||||
|
||||
async def listen(
|
||||
self,
|
||||
duration_s: float,
|
||||
*,
|
||||
on_observation: Optional["ObservationCallback"] = None,
|
||||
) -> list[Observation]:
|
||||
"""Capture observations for a bounded window, then stop and return them.
|
||||
|
||||
A thin, foreground convenience wrapper over :meth:`subscribe_observations` for
|
||||
one-shot captures (e.g. the scripted ``monitor --seconds`` command): it
|
||||
subscribes, waits ``duration_s`` seconds, unsubscribes, and returns everything
|
||||
heard. For continuous, non-blocking capture, use :meth:`subscribe_observations`
|
||||
directly.
|
||||
|
||||
Args:
|
||||
duration_s: How long to listen, in seconds.
|
||||
on_observation: Optional callback invoked with each observation as it arrives
|
||||
(e.g. to advance a live progress display).
|
||||
|
||||
Returns:
|
||||
Every observation captured during the window, in arrival order.
|
||||
"""
|
||||
captured: list[Observation] = []
|
||||
|
||||
def collect(obs: Observation) -> None:
|
||||
captured.append(obs)
|
||||
if on_observation is not None:
|
||||
on_observation(obs)
|
||||
|
||||
unsubscribe = await self.subscribe_observations(collect)
|
||||
try:
|
||||
await asyncio.sleep(duration_s)
|
||||
finally:
|
||||
unsubscribe()
|
||||
return captured
|
||||
|
||||
# -- configuration: extra reads ---------------------------------------------
|
||||
|
||||
@abstractmethod
|
||||
@@ -656,8 +629,8 @@ class MeshCoreDevice(Device):
|
||||
return b"".join(hops), path_hash_flags(trace_size) or 0
|
||||
return None
|
||||
|
||||
async def subscribe_observations( # noqa: D102 - inherited docstring
|
||||
self, on_observation: ObservationCallback
|
||||
async def subscribe_events( # noqa: D102 - inherited docstring
|
||||
self, on_event: EventCallback
|
||||
) -> Unsubscribe:
|
||||
from meshcore import EventType
|
||||
|
||||
@@ -669,16 +642,24 @@ class MeshCoreDevice(Device):
|
||||
"monitoring isn't available. Upgrade the 'meshcore' library."
|
||||
)
|
||||
|
||||
def make_handler(kind: str): # type: ignore[no-untyped-def]
|
||||
def observation_handler(kind: str): # type: ignore[no-untyped-def]
|
||||
def handler(event) -> None: # noqa: ANN001
|
||||
obs = observation_from_event(event, kind)
|
||||
if obs is not None:
|
||||
on_observation(obs)
|
||||
on_event(MeshEvent.observation_event(obs))
|
||||
|
||||
return handler
|
||||
|
||||
# Subscribe to whichever advert/telemetry event types this firmware/library build
|
||||
# exposes. The event payload field names below are best-effort and, like the trace
|
||||
def message_handler(event) -> None: # noqa: ANN001
|
||||
msg = message_from_event(event)
|
||||
if msg is not None:
|
||||
on_event(MeshEvent.message_event(msg))
|
||||
|
||||
def ack_handler(event) -> None: # noqa: ANN001
|
||||
on_event(MeshEvent.ack_event(ack_from_event(event)))
|
||||
|
||||
# Subscribe to whichever event types this firmware/library build exposes. The
|
||||
# event payload field names the mappers read are best-effort and, like the trace
|
||||
# mapping, should be validated against your firmware's event schema.
|
||||
subs = []
|
||||
for attr, kind in (
|
||||
@@ -689,7 +670,14 @@ class MeshCoreDevice(Device):
|
||||
):
|
||||
etype = getattr(EventType, attr, None)
|
||||
if etype is not None:
|
||||
subs.append(subscribe(etype, make_handler(kind)))
|
||||
subs.append(subscribe(etype, observation_handler(kind)))
|
||||
for attr in ("CONTACT_MSG_RECV", "CHANNEL_MSG_RECV"):
|
||||
etype = getattr(EventType, attr, None)
|
||||
if etype is not None:
|
||||
subs.append(subscribe(etype, message_handler))
|
||||
etype = getattr(EventType, "ACK", None)
|
||||
if etype is not None:
|
||||
subs.append(subscribe(etype, ack_handler))
|
||||
|
||||
def unsubscribe() -> None:
|
||||
for sub in subs:
|
||||
@@ -881,7 +869,7 @@ class MockDevice(Device):
|
||||
self._channels: dict[int, dict] = {}
|
||||
self._device_pin = 0
|
||||
self._private_key = "11" * 32
|
||||
# Background emitter tasks spawned by ``subscribe_observations``; tracked so they
|
||||
# Background emitter tasks spawned by ``subscribe_events``; tracked so they
|
||||
# can be cancelled on disconnect and are never garbage-collected while pending.
|
||||
self._bg_tasks: set[asyncio.Task] = set()
|
||||
|
||||
@@ -1026,22 +1014,29 @@ class MockDevice(Device):
|
||||
self._custom_vars.clear()
|
||||
self._channels.clear()
|
||||
|
||||
async def subscribe_observations( # noqa: D102 - inherited docstring
|
||||
self, on_observation: ObservationCallback
|
||||
async def subscribe_events( # noqa: D102 - inherited docstring
|
||||
self, on_event: EventCallback
|
||||
) -> Unsubscribe:
|
||||
# Simulate a live packet stream. Emit a burst of synthetic adverts/telemetry from
|
||||
# Simulate a live event stream. Emit a burst of synthetic adverts/telemetry from
|
||||
# the known contacts *synchronously* here, then keep emitting at a steady cadence
|
||||
# from a background task until unsubscribed. The immediate first burst means even
|
||||
# a zero-length capture window always sees every contact (two of which carry a
|
||||
# location), keeping bounded ``listen`` runs and their tests deterministic.
|
||||
# a zero-length window always sees every contact (two of which carry a location)
|
||||
# and one inbound message, keeping capture tests deterministic.
|
||||
stop = asyncio.Event()
|
||||
seq = 0
|
||||
burst = 0
|
||||
|
||||
def emit_burst() -> None:
|
||||
nonlocal seq
|
||||
nonlocal seq, burst
|
||||
for contact in self._contacts:
|
||||
on_observation(self._synth_observation(contact, seq))
|
||||
on_event(MeshEvent.observation_event(self._synth_observation(contact, seq)))
|
||||
seq += 1
|
||||
# Periodically simulate an inbound direct message so message-driven features
|
||||
# (and their tests) have traffic to react to; the first burst always includes
|
||||
# one so a subscriber sees a message without waiting.
|
||||
if burst % 8 == 0:
|
||||
on_event(MeshEvent.message_event(self._synth_message(burst // 8)))
|
||||
burst += 1
|
||||
|
||||
emit_burst()
|
||||
|
||||
@@ -1092,6 +1087,23 @@ class MockDevice(Device):
|
||||
lon=lat_lon[1] if lat_lon else None,
|
||||
)
|
||||
|
||||
def _synth_message(self, seq: int) -> Message:
|
||||
"""Build one plausible synthetic inbound direct message (simulator only).
|
||||
|
||||
Args:
|
||||
seq: Monotonic burst counter, used to rotate the sending contact and body.
|
||||
|
||||
Returns:
|
||||
A :class:`Message` from one of the known contacts.
|
||||
"""
|
||||
contact = self._contacts[seq % len(self._contacts)]
|
||||
return Message(
|
||||
text=f"hello from {contact.name} #{seq}",
|
||||
sender=contact.key_prefix or contact.public_key[:12],
|
||||
is_channel=False,
|
||||
snr=round(self._rng.gauss(6.0, 3.0), 1),
|
||||
)
|
||||
|
||||
def _expected_snr(self, hop_index: int) -> float:
|
||||
"""Model SNR for a hop as an inverted-U in TX power plus distance falloff.
|
||||
|
||||
@@ -1236,6 +1248,47 @@ def observation_from_event(event, kind: str) -> Optional[Observation]: # noqa:
|
||||
)
|
||||
|
||||
|
||||
def message_from_event(event) -> Optional[Message]: # noqa: ANN001
|
||||
"""Map a meshcore ``CONTACT_MSG_RECV`` / ``CHANNEL_MSG_RECV`` event into a message.
|
||||
|
||||
Direct messages carry a ``pubkey_prefix`` sender; channel messages carry a
|
||||
``channel_idx`` instead (``type`` is ``"PRIV"`` or ``"CHAN"``). Field names are
|
||||
best-effort and should be validated against your firmware's event schema.
|
||||
|
||||
Args:
|
||||
event: A meshcore message event (anything exposing a ``payload`` mapping).
|
||||
|
||||
Returns:
|
||||
The parsed :class:`Message`, or ``None`` if the payload carried no text body.
|
||||
"""
|
||||
payload = dict(getattr(event, "payload", {}) or {})
|
||||
text = payload.get("text")
|
||||
if text is None:
|
||||
return None
|
||||
is_channel = payload.get("type") == "CHAN" or "channel_idx" in payload
|
||||
ts = payload.get("sender_timestamp")
|
||||
sender_ts = (
|
||||
datetime.fromtimestamp(ts, tz=timezone.utc)
|
||||
if isinstance(ts, (int, float)) and ts
|
||||
else None
|
||||
)
|
||||
return Message(
|
||||
text=str(text),
|
||||
sender=None if is_channel else payload.get("pubkey_prefix"),
|
||||
channel=payload.get("channel_idx") if is_channel else None,
|
||||
is_channel=is_channel,
|
||||
sender_timestamp=sender_ts,
|
||||
snr=_as_float(payload.get("SNR", payload.get("snr"))),
|
||||
raw=payload,
|
||||
)
|
||||
|
||||
|
||||
def ack_from_event(event) -> Ack: # noqa: ANN001
|
||||
"""Map a meshcore ``ACK`` event into an :class:`Ack` (delivery acknowledgement)."""
|
||||
payload = dict(getattr(event, "payload", {}) or {})
|
||||
return Ack(code=payload.get("code"), raw=payload)
|
||||
|
||||
|
||||
def _as_float(value: object) -> Optional[float]:
|
||||
"""Best-effort float conversion, returning ``None`` on missing/garbage values."""
|
||||
if value is None:
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"""Typed events carried by the always-on mesh event hub.
|
||||
|
||||
These are the domain-level events that flow from the connected companion device out to
|
||||
any number of interested subscribers (see :class:`~meshtools.services.event_hub.EventHub`).
|
||||
Keeping them here — plain dataclasses with no I/O dependencies, alongside the other
|
||||
domain models — lets the hub, its subscribers, and the tests all speak the same language
|
||||
without importing the device layer.
|
||||
|
||||
The hub carries the unsolicited inbound streams a client reacts to: overheard packets
|
||||
(:class:`~meshtools.core.models.Observation`), inbound text messages
|
||||
(:class:`~meshtools.core.models.Message`), and delivery acknowledgements
|
||||
(:class:`~meshtools.core.models.Ack`). Further kinds (contact updates, path changes) slot
|
||||
in by adding an :class:`EventKind` member and stamping the payload onto a
|
||||
:class:`MeshEvent`; subscribers that don't ask for the new kind are unaffected.
|
||||
|
||||
Correlated request/response replies (a trace's ``TRACE_DATA``, a login's result) are not
|
||||
carried here — those are awaited directly by the command that sent the request, so they
|
||||
work whether or not the hub is running.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime
|
||||
from enum import Enum
|
||||
from typing import Optional
|
||||
|
||||
from .models import Ack, Message, Observation, utcnow
|
||||
|
||||
|
||||
class EventKind(str, Enum):
|
||||
"""The classes of event the hub can fan out.
|
||||
|
||||
A ``str`` enum so values log and serialize legibly. New client features add their own
|
||||
members here.
|
||||
"""
|
||||
|
||||
OBSERVATION = "observation"
|
||||
MESSAGE = "message"
|
||||
ACK = "ack"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MeshEvent:
|
||||
"""One event delivered to hub subscribers.
|
||||
|
||||
A thin envelope: :attr:`kind` selects who receives it and :attr:`payload` carries the
|
||||
kind-specific data (an :class:`~meshtools.core.models.Observation` for
|
||||
:attr:`EventKind.OBSERVATION`). Kind-specific accessors like :attr:`observation` give
|
||||
callers a typed handle without matching on ``kind`` themselves.
|
||||
|
||||
Attributes:
|
||||
kind: Which class of event this is; determines the payload type and routing.
|
||||
payload: The kind-specific data object.
|
||||
received_at: When the hub emitted the event (UTC).
|
||||
"""
|
||||
|
||||
kind: EventKind
|
||||
payload: object = None
|
||||
received_at: datetime = field(default_factory=utcnow)
|
||||
|
||||
@property
|
||||
def observation(self) -> Optional[Observation]:
|
||||
"""The carried :class:`Observation`, or ``None`` if this isn't an observation."""
|
||||
return self.payload if isinstance(self.payload, Observation) else None
|
||||
|
||||
@property
|
||||
def message(self) -> Optional[Message]:
|
||||
"""The carried :class:`Message`, or ``None`` if this isn't a message."""
|
||||
return self.payload if isinstance(self.payload, Message) else None
|
||||
|
||||
@property
|
||||
def ack(self) -> Optional[Ack]:
|
||||
"""The carried :class:`Ack`, or ``None`` if this isn't an acknowledgement."""
|
||||
return self.payload if isinstance(self.payload, Ack) else None
|
||||
|
||||
@classmethod
|
||||
def observation_event(cls, obs: Observation) -> "MeshEvent":
|
||||
"""Wrap an :class:`Observation` as an :attr:`EventKind.OBSERVATION` event."""
|
||||
return cls(kind=EventKind.OBSERVATION, payload=obs)
|
||||
|
||||
@classmethod
|
||||
def message_event(cls, message: Message) -> "MeshEvent":
|
||||
"""Wrap a :class:`Message` as an :attr:`EventKind.MESSAGE` event."""
|
||||
return cls(kind=EventKind.MESSAGE, payload=message)
|
||||
|
||||
@classmethod
|
||||
def ack_event(cls, ack: Ack) -> "MeshEvent":
|
||||
"""Wrap an :class:`Ack` as an :attr:`EventKind.ACK` event."""
|
||||
return cls(kind=EventKind.ACK, payload=ack)
|
||||
@@ -73,6 +73,51 @@ class Observation:
|
||||
raw: Optional[dict] = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Message:
|
||||
"""An inbound text message the companion received (direct or on a channel).
|
||||
|
||||
Direct messages carry a :attr:`sender` key prefix; channel messages carry a
|
||||
:attr:`channel` index instead. Both are surfaced by the always-on event hub as
|
||||
:attr:`~meshtools.core.events.EventKind.MESSAGE` events, so client features (an inbox,
|
||||
notifications) can react to them without polling.
|
||||
|
||||
Attributes:
|
||||
text: The decoded message body.
|
||||
sender: Key prefix of the sending contact (direct messages), if known.
|
||||
channel: Channel index the message arrived on (channel messages), if applicable.
|
||||
is_channel: Whether this is a channel message rather than a direct one.
|
||||
sender_timestamp: The sender's own timestamp for the message, if carried.
|
||||
snr: Signal-to-noise ratio (dB) of the reception, if reported.
|
||||
received_at: When the companion delivered the message to us.
|
||||
raw: Optional raw event payload for debugging/replay.
|
||||
"""
|
||||
|
||||
text: str
|
||||
sender: Optional[str] = None
|
||||
channel: Optional[int] = None
|
||||
is_channel: bool = False
|
||||
sender_timestamp: Optional[datetime] = None
|
||||
snr: Optional[float] = None
|
||||
received_at: datetime = field(default_factory=utcnow)
|
||||
raw: Optional[dict] = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Ack:
|
||||
"""A delivery acknowledgement for a message the companion sent.
|
||||
|
||||
Attributes:
|
||||
code: The ACK correlation code (hex), matching it to the sent message, if present.
|
||||
received_at: When the acknowledgement arrived.
|
||||
raw: Optional raw event payload for debugging/replay.
|
||||
"""
|
||||
|
||||
code: Optional[str] = None
|
||||
received_at: datetime = field(default_factory=utcnow)
|
||||
raw: Optional[dict] = None
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class HeardNode:
|
||||
"""Aggregated reception statistics for one node across many observations.
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
"""The always-on mesh event hub.
|
||||
|
||||
The hub is the single seam between the raw companion-device event stream and everything
|
||||
that wants to react to it. It opens *one* subscription to the connected device, normalizes
|
||||
what arrives into typed :class:`~meshtools.core.events.MeshEvent` values, and fans each
|
||||
one out to any number of subscribers. Unlike a one-shot capture it is meant to run for the
|
||||
whole life of an interactive session — a MeshCore client must always be listening — so
|
||||
subscribers come and go while the pump keeps running underneath them.
|
||||
|
||||
This decouples *listening* from *consuming*: the passive monitor's database logging becomes
|
||||
just one subscriber (see :class:`~meshtools.services.monitor_service.MonitorService`), and
|
||||
future client features (a live node list, an incoming-message inbox) attach as additional
|
||||
subscribers without touching the device layer.
|
||||
|
||||
The hub is session-scoped state on the :class:`~meshtools.context.AppContext`
|
||||
(``ctx.events``). Fan-out runs synchronously on the event loop as packets arrive, so
|
||||
handlers should stay cheap; a handler that returns a coroutine is scheduled as a task.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Awaitable, Callable, Optional, Union
|
||||
|
||||
from ..core.connection import Unsubscribe
|
||||
from ..core.events import EventKind, MeshEvent
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..context import AppContext
|
||||
|
||||
#: A subscriber callback. Invoked with each matching :class:`MeshEvent`. Keep it cheap;
|
||||
#: it runs inline on the event loop as packets arrive. It may return a coroutine, which
|
||||
#: the hub schedules as a task rather than awaiting inline.
|
||||
EventHandler = Callable[[MeshEvent], Union[None, Awaitable[None]]]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class _Subscription:
|
||||
"""One registered subscriber: a handler plus the kinds it cares about.
|
||||
|
||||
Attributes:
|
||||
handler: The callback to invoke with matching events.
|
||||
kinds: The event kinds to deliver; an empty set means *all* kinds.
|
||||
"""
|
||||
|
||||
handler: EventHandler
|
||||
kinds: frozenset = field(default_factory=frozenset)
|
||||
|
||||
def wants(self, kind: EventKind) -> bool:
|
||||
"""Whether this subscription should receive an event of ``kind``."""
|
||||
return not self.kinds or kind in self.kinds
|
||||
|
||||
|
||||
class EventHub:
|
||||
"""Owns the device event subscription and fans events out to subscribers.
|
||||
|
||||
Interact through :meth:`subscribe` / :meth:`stream` to consume events and the async
|
||||
lifecycle methods (:meth:`start`, :meth:`stop`, :meth:`aclose`) to control the pump.
|
||||
"""
|
||||
|
||||
def __init__(self, ctx: "AppContext") -> None:
|
||||
"""Initialize an idle hub bound to an application context.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context, used to open the device connection and
|
||||
to log. No device is opened until :meth:`start` is called.
|
||||
"""
|
||||
self._ctx = ctx
|
||||
self._device_unsubscribe: Optional[Unsubscribe] = None
|
||||
self._subs: list[_Subscription] = []
|
||||
self._tasks: set[asyncio.Task] = set()
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
"""Whether the pump is running (subscribed to the device)."""
|
||||
return self._device_unsubscribe is not None
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Open the device subscription and begin pumping events. Idempotent.
|
||||
|
||||
Opens the companion connection (which may raise if no device can be selected) and
|
||||
subscribes to its observation stream. Subscribers registered before or after this
|
||||
call all receive events once the pump is running.
|
||||
|
||||
Raises:
|
||||
Exception: Propagates any device/subscription error; the hub stays inactive so
|
||||
the caller can surface the problem and retry later.
|
||||
"""
|
||||
if self.active:
|
||||
return
|
||||
device = await self._ctx.device()
|
||||
self._device_unsubscribe = await device.subscribe_events(self.publish)
|
||||
self._ctx.log.info("event hub started")
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Release the device subscription and drop any scheduled handler tasks.
|
||||
|
||||
Idempotent. Registered subscribers are left in place, so a later :meth:`start`
|
||||
resumes delivering to them.
|
||||
"""
|
||||
if self._device_unsubscribe is not None:
|
||||
try:
|
||||
self._device_unsubscribe()
|
||||
finally:
|
||||
self._device_unsubscribe = None
|
||||
for task in list(self._tasks):
|
||||
task.cancel()
|
||||
self._tasks.clear()
|
||||
self._ctx.log.info("event hub stopped")
|
||||
|
||||
def subscribe(self, handler: EventHandler, *kinds: EventKind) -> Unsubscribe:
|
||||
"""Register ``handler`` to receive events, and return a callable that removes it.
|
||||
|
||||
Args:
|
||||
handler: The callback invoked with each matching :class:`MeshEvent`.
|
||||
*kinds: The event kinds to receive. Pass none to receive *every* kind.
|
||||
|
||||
Returns:
|
||||
A zero-argument callable that unregisters the subscription.
|
||||
"""
|
||||
sub = _Subscription(handler=handler, kinds=frozenset(kinds))
|
||||
self._subs.append(sub)
|
||||
|
||||
def unsubscribe() -> None:
|
||||
try:
|
||||
self._subs.remove(sub)
|
||||
except ValueError:
|
||||
pass # already removed; unsubscribe is idempotent
|
||||
|
||||
return unsubscribe
|
||||
|
||||
def stream(self, *kinds: EventKind, maxsize: int = 0):
|
||||
"""Return an async iterator yielding matching events as they arrive.
|
||||
|
||||
An ergonomic ``async for event in hub.stream(...)`` adapter over :meth:`subscribe`,
|
||||
backed by an :class:`asyncio.Queue`. The subscription is removed automatically when
|
||||
the iterator is closed (e.g. the ``async for`` loop breaks or the consumer is
|
||||
cancelled).
|
||||
|
||||
Args:
|
||||
*kinds: The event kinds to receive. Pass none to receive every kind.
|
||||
maxsize: Optional bound on the backing queue (``0`` = unbounded).
|
||||
|
||||
Returns:
|
||||
An async generator of :class:`MeshEvent`.
|
||||
"""
|
||||
queue: asyncio.Queue = asyncio.Queue(maxsize=maxsize)
|
||||
unsubscribe = self.subscribe(queue.put_nowait, *kinds)
|
||||
|
||||
async def _iterator():
|
||||
try:
|
||||
while True:
|
||||
yield await queue.get()
|
||||
finally:
|
||||
unsubscribe()
|
||||
|
||||
return _iterator()
|
||||
|
||||
def publish(self, event: MeshEvent) -> None:
|
||||
"""Fan ``event`` out to every subscriber that wants its kind.
|
||||
|
||||
Delivery is synchronous and best-effort: a handler that raises is logged and
|
||||
skipped so one bad subscriber can never take down the pump or starve the others.
|
||||
A handler that returns a coroutine is scheduled as a background task.
|
||||
|
||||
Args:
|
||||
event: The event to deliver.
|
||||
"""
|
||||
for sub in list(self._subs):
|
||||
if not sub.wants(event.kind):
|
||||
continue
|
||||
try:
|
||||
result = sub.handler(event)
|
||||
except Exception as exc: # noqa: BLE001 - one bad subscriber must not break the pump
|
||||
self._ctx.log.debug("event hub: subscriber raised: %s", exc)
|
||||
continue
|
||||
if asyncio.iscoroutine(result):
|
||||
self._schedule(result)
|
||||
|
||||
def _schedule(self, coro: Awaitable[None]) -> None:
|
||||
"""Run an async handler's coroutine as a tracked background task."""
|
||||
task = asyncio.ensure_future(coro)
|
||||
self._tasks.add(task)
|
||||
task.add_done_callback(self._tasks.discard)
|
||||
|
||||
async def wait_for(
|
||||
self,
|
||||
*kinds: EventKind,
|
||||
predicate: Optional[Callable[[MeshEvent], bool]] = None,
|
||||
timeout: Optional[float] = None,
|
||||
) -> Optional[MeshEvent]:
|
||||
"""Await the next event matching ``kinds`` (and ``predicate``), or time out.
|
||||
|
||||
A one-shot convenience for consumers that want to block for a specific event
|
||||
rather than register a standing handler. The temporary subscription is always
|
||||
removed before returning.
|
||||
|
||||
Args:
|
||||
*kinds: The event kinds to accept. Pass none to accept every kind.
|
||||
predicate: Optional extra filter; the event must also satisfy it to match.
|
||||
timeout: Seconds to wait before giving up, or ``None`` to wait indefinitely.
|
||||
|
||||
Returns:
|
||||
The matching :class:`MeshEvent`, or ``None`` if ``timeout`` elapsed first.
|
||||
"""
|
||||
loop = asyncio.get_event_loop()
|
||||
future: asyncio.Future = loop.create_future()
|
||||
|
||||
def handler(event: MeshEvent) -> None:
|
||||
if not future.done() and (predicate is None or predicate(event)):
|
||||
future.set_result(event)
|
||||
|
||||
unsubscribe = self.subscribe(handler, *kinds)
|
||||
try:
|
||||
if timeout is None:
|
||||
return await future
|
||||
return await asyncio.wait_for(future, timeout)
|
||||
except asyncio.TimeoutError:
|
||||
return None
|
||||
finally:
|
||||
unsubscribe()
|
||||
|
||||
async def aclose(self) -> None:
|
||||
"""Stop the pump at session end (an alias for :meth:`stop`)."""
|
||||
await self.stop()
|
||||
@@ -1,15 +1,17 @@
|
||||
"""The passive-monitor background service.
|
||||
"""The passive-monitor history logger.
|
||||
|
||||
Passive monitoring records every advert/telemetry frame the companion overhears to the
|
||||
database, building the longitudinal history the coverage map and link-quality alerting
|
||||
read back. Unlike a one-shot capture, it runs as a non-blocking background subscription:
|
||||
once started it logs observations as they arrive while the user keeps using the app, and
|
||||
keeps going across menu actions until stopped or the session ends.
|
||||
read back. It is not a listener in its own right: the always-on
|
||||
:class:`~meshtools.services.event_hub.EventHub` (``ctx.events``) does the listening, and
|
||||
this service is simply one of its subscribers — the one that writes observations to the
|
||||
database. Listening is therefore unconditional; the on/off preference this service owns
|
||||
controls only whether what's heard is *persisted to history*.
|
||||
|
||||
The service is session-scoped state on the :class:`~meshtools.context.AppContext`
|
||||
(``ctx.monitor``). It owns the on/off preference (persisted via
|
||||
:class:`~meshtools.core.monitor_store.MonitorStore`), the live subscription, and the
|
||||
counters shown live in the menu.
|
||||
:class:`~meshtools.core.monitor_store.MonitorStore`), the hub subscription that records
|
||||
observations, and the counters shown live in the menu.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -17,7 +19,7 @@ from __future__ import annotations
|
||||
from typing import TYPE_CHECKING, Optional
|
||||
|
||||
from ..core.connection import Unsubscribe
|
||||
from ..core.models import Observation
|
||||
from ..core.events import EventKind, MeshEvent
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..context import AppContext
|
||||
@@ -25,7 +27,7 @@ if TYPE_CHECKING:
|
||||
|
||||
|
||||
class MonitorService:
|
||||
"""Manages the always-on, non-blocking passive-monitor subscription.
|
||||
"""Records overheard packets to history as a subscriber of the always-on event hub.
|
||||
|
||||
Attributes are private; interact through the properties and the async lifecycle
|
||||
methods (:meth:`enable`, :meth:`disable`, :meth:`toggle`, :meth:`start`, :meth:`stop`,
|
||||
@@ -42,7 +44,7 @@ class MonitorService:
|
||||
self._ctx = ctx
|
||||
self._store = store
|
||||
self._enabled = store.load_enabled()
|
||||
self._unsubscribe: Optional[Unsubscribe] = None
|
||||
self._unsubscribe: Optional[Unsubscribe] = None # hub subscription, when recording
|
||||
self._run_id: Optional[int] = None
|
||||
self._session_count = 0
|
||||
self._run_start_count = 0
|
||||
@@ -59,7 +61,7 @@ class MonitorService:
|
||||
|
||||
@property
|
||||
def active(self) -> bool:
|
||||
"""Whether a live subscription is currently capturing."""
|
||||
"""Whether observations are currently being recorded to history."""
|
||||
return self._unsubscribe is not None
|
||||
|
||||
@property
|
||||
@@ -93,20 +95,21 @@ class MonitorService:
|
||||
return "○ monitor OFF"
|
||||
|
||||
async def start(self) -> None:
|
||||
"""Open a background subscription and begin logging observations.
|
||||
"""Begin recording overheard observations to history. Idempotent.
|
||||
|
||||
Idempotent: a no-op if already active. Opens the device connection (which may
|
||||
raise if no device can be selected) and records a ``monitor`` run that the
|
||||
captured observations are linked to.
|
||||
A no-op if already recording. Ensures the always-on event hub is running (which
|
||||
opens the device connection and may raise if no device can be selected), then
|
||||
subscribes to its observation stream and opens a ``monitor`` run for the recorded
|
||||
observations to link to.
|
||||
|
||||
Raises:
|
||||
Exception: Propagates any device/subscription error after recording it; the
|
||||
on/off preference is left unchanged so the caller can surface the problem.
|
||||
Exception: Propagates any device/hub error after remembering it; the on/off
|
||||
preference is left unchanged so the caller can surface the problem.
|
||||
"""
|
||||
if self.active:
|
||||
return
|
||||
try:
|
||||
device = await self._ctx.device()
|
||||
await self._ctx.events.start()
|
||||
except Exception as exc: # noqa: BLE001 - remember why, then re-raise
|
||||
self._error = str(exc)
|
||||
raise
|
||||
@@ -115,29 +118,28 @@ class MonitorService:
|
||||
)
|
||||
self._run_start_count = self._session_count
|
||||
|
||||
def on_observation(obs: Observation) -> None:
|
||||
def on_event(event: MeshEvent) -> None:
|
||||
# Runs on the event loop as packets arrive; keep it cheap and defensive so a
|
||||
# single bad write can never take down the subscription.
|
||||
obs = event.observation
|
||||
if obs is None:
|
||||
return
|
||||
self._session_count += 1
|
||||
try:
|
||||
self._ctx.repo.record_observation(run_id, obs)
|
||||
except Exception as exc: # noqa: BLE001 - never let logging break capture
|
||||
self._ctx.log.debug("monitor: failed to record observation: %s", exc)
|
||||
|
||||
try:
|
||||
self._unsubscribe = await device.subscribe_observations(on_observation)
|
||||
except Exception as exc: # noqa: BLE001 - record, remember, and re-raise
|
||||
self._ctx.repo.finish_run(run_id, "error", {"error": str(exc)})
|
||||
self._error = str(exc)
|
||||
raise
|
||||
self._unsubscribe = self._ctx.events.subscribe(on_event, EventKind.OBSERVATION)
|
||||
self._run_id = run_id
|
||||
self._error = None
|
||||
self._ctx.log.info("passive monitor started (run %s)", run_id)
|
||||
self._ctx.log.info("passive monitor recording (run %s)", run_id)
|
||||
|
||||
async def stop(self) -> None:
|
||||
"""Stop the background subscription and close its run record.
|
||||
"""Stop recording to history and close the run record. Idempotent.
|
||||
|
||||
Idempotent: a no-op if not active.
|
||||
A no-op if not recording. The event hub keeps listening; only this service's
|
||||
recording subscription is removed.
|
||||
"""
|
||||
if not self.active:
|
||||
return
|
||||
|
||||
+7
-121
@@ -5,15 +5,12 @@ with SNR, RSSI, and any shared location — to the database, building the longit
|
||||
history that the coverage map and link-quality alerting read back. It transmits nothing;
|
||||
it only listens.
|
||||
|
||||
Capture itself runs as a non-blocking background subscription owned by
|
||||
:class:`~meshtools.services.monitor_service.MonitorService` (``ctx.monitor``), so it never
|
||||
blocks the menu. This tool is the control panel for it: toggling capture on/off (a
|
||||
preference remembered between sessions) and reviewing the heard-node history. The live
|
||||
packet counters are shown in the main-menu header, not here.
|
||||
|
||||
The CLI subcommand additionally offers a one-shot foreground capture (``--seconds``) for
|
||||
scripting, since a short-lived CLI process has no long-running menu to host a background
|
||||
subscription.
|
||||
Listening itself is always on: the session-wide
|
||||
:class:`~meshtools.services.event_hub.EventHub` overhears every packet, and
|
||||
:class:`~meshtools.services.monitor_service.MonitorService` (``ctx.monitor``) records
|
||||
them to history as one of its subscribers. This tool is the control panel for that
|
||||
recording: toggling it on/off (a preference remembered between sessions) and reviewing the
|
||||
heard-node history. The live packet counters are shown in the main-menu header, not here.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -25,16 +22,10 @@ from rich.table import Table
|
||||
from rich.text import Text
|
||||
|
||||
from ..context import AppContext
|
||||
from ..core.models import HeardNode, Observation
|
||||
from ..services import trace_runner
|
||||
from ..core.models import HeardNode
|
||||
from ..ui.tui import Choice
|
||||
from ..ui.widgets import make_progress
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
#: Cap a single foreground capture window so a scripted run can't block indefinitely;
|
||||
#: longer passive logging is done by enabling the background monitor instead.
|
||||
MAX_DURATION_S = 3600
|
||||
|
||||
|
||||
@register
|
||||
class MonitorTool(Tool):
|
||||
@@ -172,13 +163,6 @@ class MonitorTool(Tool):
|
||||
off: bool = typer.Option(
|
||||
False, "--off", help="Disable background monitoring."
|
||||
),
|
||||
seconds: Optional[int] = typer.Option(
|
||||
None,
|
||||
"--seconds",
|
||||
"-d",
|
||||
help=f"Capture in the foreground for N seconds now, then exit "
|
||||
f"(1-{MAX_DURATION_S}).",
|
||||
),
|
||||
) -> None:
|
||||
from ..cli import _state
|
||||
|
||||
@@ -196,9 +180,6 @@ class MonitorTool(Tool):
|
||||
"interactive sessions"
|
||||
)
|
||||
return
|
||||
if seconds is not None:
|
||||
_run_foreground_capture(ctx, seconds)
|
||||
return
|
||||
# No flags: report the current preference and history size.
|
||||
enabled = "[ok]on[/ok]" if store.load_enabled() else "[muted]off[/muted]"
|
||||
ctx.console.print(
|
||||
@@ -207,101 +188,6 @@ class MonitorTool(Tool):
|
||||
)
|
||||
|
||||
|
||||
def _run_foreground_capture(ctx: AppContext, seconds: int) -> None:
|
||||
"""Drive a one-shot foreground capture on its own event loop.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
seconds: Requested capture duration (clamped to ``1..MAX_DURATION_S``).
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
from ..cli import _drive
|
||||
|
||||
asyncio.run(_drive(_foreground_capture(ctx, seconds), ctx))
|
||||
|
||||
|
||||
async def _foreground_capture(ctx: AppContext, seconds: int) -> None:
|
||||
"""Capture overheard packets for a bounded window and print a heard-node table.
|
||||
|
||||
This is the scripted, blocking counterpart to the background monitor: it records to
|
||||
its own ``monitor`` run and returns when the window elapses. Used by ``monitor
|
||||
--seconds``.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
seconds: Requested capture duration (clamped to ``1..MAX_DURATION_S``).
|
||||
"""
|
||||
duration = max(1, min(MAX_DURATION_S, int(seconds)))
|
||||
run_id = ctx.repo.start_run(
|
||||
"monitor", {"mode": "foreground", "duration": duration}, ctx.profile_name
|
||||
)
|
||||
observations: list[Observation] = []
|
||||
try:
|
||||
device = await ctx.device()
|
||||
resolve = trace_runner.make_node_resolver(await device.get_contacts())
|
||||
with make_progress(ctx.console) as progress:
|
||||
task = progress.add_task(f"listening {duration}s", total=duration)
|
||||
|
||||
def on_observation(obs: Observation) -> None:
|
||||
observations.append(obs)
|
||||
ctx.repo.record_observation(run_id, obs)
|
||||
progress.update(
|
||||
task,
|
||||
description=f"heard {len(observations)} pkts · "
|
||||
f"{_distinct(observations)} nodes",
|
||||
)
|
||||
|
||||
await device.listen(duration, on_observation=on_observation)
|
||||
progress.update(task, completed=duration)
|
||||
except Exception as exc: # noqa: BLE001 - record then re-raise for the CLI handler
|
||||
ctx.repo.finish_run(run_id, "error", {"error": str(exc)})
|
||||
raise
|
||||
|
||||
heard = _aggregate(observations)
|
||||
if heard:
|
||||
ctx.console.print(_heard_table(heard, resolve))
|
||||
else:
|
||||
ctx.console.print("[muted]no packets heard during the window[/muted]")
|
||||
|
||||
located = sum(1 for n in heard if n.has_location)
|
||||
ctx.repo.finish_run(
|
||||
run_id,
|
||||
"ok",
|
||||
{
|
||||
"duration_s": duration,
|
||||
"observations": len(observations),
|
||||
"nodes_heard": len(heard),
|
||||
"nodes_with_location": located,
|
||||
},
|
||||
)
|
||||
ctx.console.print(
|
||||
f"[ok]✓[/ok] heard [brand]{len(observations)}[/brand] packets from "
|
||||
f"[brand]{len(heard)}[/brand] nodes in {duration}s"
|
||||
)
|
||||
|
||||
|
||||
def _distinct(observations: list[Observation]) -> int:
|
||||
"""Return the number of distinct nodes among observations."""
|
||||
return len({o.node for o in observations})
|
||||
|
||||
|
||||
def _aggregate(observations: list[Observation]) -> list[HeardNode]:
|
||||
"""Group observations by node into :class:`HeardNode` records, freshest first.
|
||||
|
||||
Args:
|
||||
observations: The observations captured this run.
|
||||
|
||||
Returns:
|
||||
One aggregate per node, ordered by most-recently heard.
|
||||
"""
|
||||
grouped: dict[Optional[str], list[Observation]] = {}
|
||||
for obs in observations:
|
||||
grouped.setdefault(obs.node, []).append(obs)
|
||||
nodes = [HeardNode.from_observations(node, obs) for node, obs in grouped.items()]
|
||||
return sorted(nodes, key=lambda n: n.last_seen, reverse=True)
|
||||
|
||||
|
||||
def _heard_table(heard: list[HeardNode], resolve) -> Table: # noqa: ANN001
|
||||
"""Render the heard-node summary table.
|
||||
|
||||
|
||||
+17
-5
@@ -61,8 +61,10 @@ async def run_menu(ctx: AppContext) -> None:
|
||||
await _startup(ctx)
|
||||
await _menu_loop(ctx, session)
|
||||
finally:
|
||||
# Stop background capture and close its run record even on an unexpected exit.
|
||||
# Stop history recording (closing its run record) and the always-on event
|
||||
# hub, even on an unexpected exit.
|
||||
await ctx.monitor.aclose()
|
||||
await ctx.events.aclose()
|
||||
|
||||
await session.run(main())
|
||||
ctx.console.print("[muted]bye 73![/muted]")
|
||||
@@ -111,15 +113,25 @@ async def _startup(ctx: AppContext) -> None:
|
||||
|
||||
|
||||
async def _resume_monitor(ctx: AppContext) -> None:
|
||||
"""Resume passive monitoring if it was left enabled, ignoring a benign start failure.
|
||||
"""Start always-on background listening, and resume history recording if enabled.
|
||||
|
||||
A failure to start (typically no companion device selected) is non-fatal: the
|
||||
preference stays on, so monitoring resumes automatically once a device is available.
|
||||
The header reflects the resulting state, so nothing needs to be printed here.
|
||||
A MeshCore client always listens while it runs, so by default the event hub is
|
||||
started unconditionally at launch; if the passive-monitor preference is on, history
|
||||
recording is resumed on top of it. The ``connect_on_start`` setting can defer that
|
||||
eager connect — when it is off, the hub is left idle here and opens lazily instead
|
||||
(when recording is turned on, or a tool first needs the radio). A failure to start
|
||||
(typically no companion device selected) is non-fatal: the preference stays on, so
|
||||
recording resumes automatically once a device is available. The header reflects the
|
||||
resulting state, so nothing needs to be printed here.
|
||||
|
||||
Args:
|
||||
ctx: The shared application context.
|
||||
"""
|
||||
if ctx.settings.connect_on_start:
|
||||
try:
|
||||
await ctx.events.start()
|
||||
except Exception: # noqa: BLE001 - surface via the header, don't crash the menu
|
||||
pass
|
||||
if not ctx.monitor.enabled:
|
||||
return
|
||||
try:
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Tests for application settings loading."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from meshtools.core.config import Settings
|
||||
|
||||
|
||||
def test_connect_on_start_defaults_true() -> None:
|
||||
"""Eager connect-at-launch is the default when nothing is configured."""
|
||||
assert Settings().connect_on_start is True
|
||||
|
||||
|
||||
def test_connect_on_start_loads_from_toml(tmp_path: Path) -> None:
|
||||
"""The connect_on_start preference round-trips from the config file."""
|
||||
config = tmp_path / "config.toml"
|
||||
config.write_text("connect_on_start = false\n", encoding="utf-8")
|
||||
assert Settings.load(config).connect_on_start is False
|
||||
@@ -0,0 +1,196 @@
|
||||
"""Tests for the always-on event hub: fan-out, filtering, streaming, and lifecycle.
|
||||
|
||||
All run against the :class:`MockDevice` simulator; no hardware required.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from meshtools.core.connection import (
|
||||
_MOCK_MONITOR_INTERVAL_S as _MOCK_INTERVAL,
|
||||
)
|
||||
from meshtools.core.connection import MockDevice
|
||||
from meshtools.core.events import EventKind, MeshEvent
|
||||
from meshtools.core.models import Observation
|
||||
from meshtools.services.event_hub import EventHub
|
||||
|
||||
|
||||
class _StubContext:
|
||||
"""Minimal stand-in for :class:`~meshtools.context.AppContext` for hub tests."""
|
||||
|
||||
def __init__(self, device: MockDevice) -> None:
|
||||
self._device = device
|
||||
self.log = logging.getLogger("test.event_hub")
|
||||
|
||||
async def device(self) -> MockDevice:
|
||||
await self._device.connect()
|
||||
return self._device
|
||||
|
||||
|
||||
def _obs_event(node: str) -> MeshEvent:
|
||||
"""Build an observation event for a node id (test helper)."""
|
||||
return MeshEvent.observation_event(Observation(node=node))
|
||||
|
||||
|
||||
def test_publish_fans_out_to_all_subscribers() -> None:
|
||||
"""Every subscriber receives each published event."""
|
||||
hub = EventHub(_StubContext(MockDevice()))
|
||||
a: list[MeshEvent] = []
|
||||
b: list[MeshEvent] = []
|
||||
hub.subscribe(a.append)
|
||||
hub.subscribe(b.append)
|
||||
|
||||
event = _obs_event("a1")
|
||||
hub.publish(event)
|
||||
|
||||
assert a == [event]
|
||||
assert b == [event]
|
||||
|
||||
|
||||
def test_kind_filter_only_delivers_requested_kinds() -> None:
|
||||
"""A subscriber filtered to a kind only sees that kind; an unfiltered one sees all."""
|
||||
hub = EventHub(_StubContext(MockDevice()))
|
||||
observations: list[MeshEvent] = []
|
||||
everything: list[MeshEvent] = []
|
||||
hub.subscribe(observations.append, EventKind.OBSERVATION)
|
||||
hub.subscribe(everything.append) # no kinds = all
|
||||
|
||||
obs_event = _obs_event("a1")
|
||||
other = MeshEvent(kind=EventKind.OBSERVATION, payload=None) # still an OBSERVATION kind
|
||||
hub.publish(obs_event)
|
||||
hub.publish(other)
|
||||
|
||||
assert observations == [obs_event, other] # both are OBSERVATION kind
|
||||
assert everything == [obs_event, other]
|
||||
|
||||
|
||||
def test_unsubscribe_stops_delivery() -> None:
|
||||
"""A removed subscriber receives nothing further, and unsubscribe is idempotent."""
|
||||
hub = EventHub(_StubContext(MockDevice()))
|
||||
seen: list[MeshEvent] = []
|
||||
unsubscribe = hub.subscribe(seen.append)
|
||||
|
||||
hub.publish(_obs_event("a1"))
|
||||
unsubscribe()
|
||||
hub.publish(_obs_event("b2"))
|
||||
unsubscribe() # second call is a harmless no-op
|
||||
|
||||
assert len(seen) == 1
|
||||
|
||||
|
||||
def test_failing_subscriber_does_not_break_others() -> None:
|
||||
"""A subscriber that raises is skipped; the others still receive the event."""
|
||||
hub = EventHub(_StubContext(MockDevice()))
|
||||
good: list[MeshEvent] = []
|
||||
|
||||
def boom(_event: MeshEvent) -> None:
|
||||
raise RuntimeError("subscriber blew up")
|
||||
|
||||
hub.subscribe(boom)
|
||||
hub.subscribe(good.append)
|
||||
|
||||
event = _obs_event("a1")
|
||||
hub.publish(event) # must not raise
|
||||
|
||||
assert good == [event]
|
||||
|
||||
|
||||
async def test_async_handler_is_scheduled() -> None:
|
||||
"""A handler returning a coroutine is run as a task rather than awaited inline."""
|
||||
hub = EventHub(_StubContext(MockDevice()))
|
||||
ran = asyncio.Event()
|
||||
|
||||
async def handler(_event: MeshEvent) -> None:
|
||||
ran.set()
|
||||
|
||||
hub.subscribe(handler)
|
||||
hub.publish(_obs_event("a1"))
|
||||
|
||||
assert not ran.is_set() # not awaited inline
|
||||
await asyncio.wait_for(ran.wait(), timeout=1.0) # but scheduled and runs on the loop
|
||||
|
||||
|
||||
async def test_stream_yields_matching_events_then_unsubscribes() -> None:
|
||||
"""stream() yields published events and drops its subscription when closed."""
|
||||
hub = EventHub(_StubContext(MockDevice()))
|
||||
stream = hub.stream(EventKind.OBSERVATION)
|
||||
|
||||
event = _obs_event("a1")
|
||||
hub.publish(event)
|
||||
received = await asyncio.wait_for(stream.__anext__(), timeout=1.0)
|
||||
assert received is event
|
||||
|
||||
await stream.aclose() # closing removes the underlying subscription
|
||||
assert hub._subs == []
|
||||
|
||||
|
||||
async def test_message_events_delivered_from_device() -> None:
|
||||
"""The device's inbound messages reach a MESSAGE subscriber as message events."""
|
||||
device = MockDevice()
|
||||
hub = EventHub(_StubContext(device))
|
||||
messages: list[MeshEvent] = []
|
||||
hub.subscribe(messages.append, EventKind.MESSAGE)
|
||||
|
||||
await hub.start() # the simulator's first burst carries one message synchronously
|
||||
assert messages
|
||||
assert all(e.kind is EventKind.MESSAGE and e.message is not None for e in messages)
|
||||
assert messages[0].message.text
|
||||
|
||||
await hub.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_wait_for_returns_matching_event() -> None:
|
||||
"""wait_for resolves with the next event of the requested kind."""
|
||||
device = MockDevice()
|
||||
hub = EventHub(_StubContext(device))
|
||||
await hub.start()
|
||||
|
||||
event = await hub.wait_for(EventKind.OBSERVATION, timeout=1.0)
|
||||
assert event is not None
|
||||
assert event.observation is not None
|
||||
|
||||
await hub.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_wait_for_honors_predicate_and_times_out() -> None:
|
||||
"""wait_for returns None when no event satisfies the predicate before the timeout."""
|
||||
device = MockDevice()
|
||||
hub = EventHub(_StubContext(device))
|
||||
await hub.start()
|
||||
|
||||
event = await hub.wait_for(
|
||||
EventKind.OBSERVATION, predicate=lambda _e: False, timeout=0.2
|
||||
)
|
||||
assert event is None
|
||||
|
||||
await hub.stop()
|
||||
await device.disconnect()
|
||||
|
||||
|
||||
async def test_start_pumps_device_observations_then_stops() -> None:
|
||||
"""Starting subscribes to the device; observations arrive as events until stopped."""
|
||||
device = MockDevice()
|
||||
hub = EventHub(_StubContext(device))
|
||||
events: list[MeshEvent] = []
|
||||
hub.subscribe(events.append, EventKind.OBSERVATION)
|
||||
|
||||
assert not hub.active
|
||||
await hub.start()
|
||||
assert hub.active
|
||||
|
||||
await asyncio.sleep(_MOCK_INTERVAL * 3)
|
||||
assert events # the simulator's adverts flowed through as observation events
|
||||
assert all(e.kind is EventKind.OBSERVATION for e in events)
|
||||
assert all(e.observation is not None for e in events)
|
||||
|
||||
await hub.stop()
|
||||
assert not hub.active
|
||||
frozen = len(events)
|
||||
await asyncio.sleep(_MOCK_INTERVAL * 3)
|
||||
assert len(events) == frozen # nothing more after stopping
|
||||
|
||||
await device.disconnect()
|
||||
+98
-21
@@ -18,6 +18,8 @@ from meshtools.core.connection import (
|
||||
)
|
||||
from meshtools.core.connection import (
|
||||
MockDevice,
|
||||
ack_from_event,
|
||||
message_from_event,
|
||||
observation_from_event,
|
||||
)
|
||||
from meshtools.core.models import HeardNode, Observation, utcnow
|
||||
@@ -32,6 +34,7 @@ class _StubContext:
|
||||
def __init__(self, repo: Repository, device: MockDevice) -> None:
|
||||
self.repo = repo
|
||||
self._device = device
|
||||
self._events = None
|
||||
self.profile_name = None
|
||||
self.log = logging.getLogger("test.monitor")
|
||||
|
||||
@@ -39,29 +42,44 @@ class _StubContext:
|
||||
await self._device.connect()
|
||||
return self._device
|
||||
|
||||
@property
|
||||
def events(self):
|
||||
"""Lazily build a real event hub bound to this stub context (as AppContext does)."""
|
||||
from meshtools.services.event_hub import EventHub
|
||||
|
||||
async def test_mock_listen_emits_observations_and_callbacks() -> None:
|
||||
"""Listening yields observations and fires the per-observation callback."""
|
||||
if self._events is None:
|
||||
self._events = EventHub(self)
|
||||
return self._events
|
||||
|
||||
|
||||
async def _collect_observations(device: MockDevice, duration_s: float) -> list[Observation]:
|
||||
"""Subscribe, gather observations for a window, then unsubscribe (test helper)."""
|
||||
seen: list[Observation] = []
|
||||
|
||||
def on_event(event) -> None:
|
||||
if event.observation is not None:
|
||||
seen.append(event.observation)
|
||||
|
||||
unsubscribe = await device.subscribe_events(on_event)
|
||||
try:
|
||||
await asyncio.sleep(duration_s)
|
||||
finally:
|
||||
unsubscribe()
|
||||
return seen
|
||||
|
||||
|
||||
async def test_subscribe_events_streams_observations_then_stops() -> None:
|
||||
"""The event stream emits an immediate burst, keeps streaming, and halts on unsub."""
|
||||
device = MockDevice()
|
||||
await device.connect()
|
||||
|
||||
seen: list[Observation] = []
|
||||
observations = await device.listen(0.2, on_observation=seen.append)
|
||||
|
||||
assert observations # the simulator advertises its known contacts
|
||||
assert seen == observations # every observation was reported via the callback
|
||||
assert all(o.node for o in observations)
|
||||
# At least one node advertises a location (for the coverage map).
|
||||
assert any(o.lat is not None and o.lon is not None for o in observations)
|
||||
def on_event(event) -> None:
|
||||
if event.observation is not None:
|
||||
seen.append(event.observation)
|
||||
|
||||
|
||||
async def test_subscribe_observations_streams_then_stops() -> None:
|
||||
"""The subscription emits an immediate burst, keeps streaming, and halts on unsub."""
|
||||
device = MockDevice()
|
||||
await device.connect()
|
||||
|
||||
seen: list[Observation] = []
|
||||
unsubscribe = await device.subscribe_observations(seen.append)
|
||||
unsubscribe = await device.subscribe_events(on_event)
|
||||
try:
|
||||
# The first burst is emitted synchronously, before any await.
|
||||
first_burst = len(seen)
|
||||
@@ -82,7 +100,7 @@ async def test_disconnect_stops_background_emitter() -> None:
|
||||
"""Disconnecting cancels any live subscription task rather than leaking it."""
|
||||
device = MockDevice()
|
||||
await device.connect()
|
||||
await device.subscribe_observations(lambda _obs: None)
|
||||
await device.subscribe_events(lambda _event: None)
|
||||
assert device._bg_tasks # a background emitter is running
|
||||
await device.disconnect()
|
||||
await asyncio.sleep(0) # let the cancellation settle
|
||||
@@ -154,6 +172,60 @@ def test_observation_from_event_without_node_is_skipped() -> None:
|
||||
assert observation_from_event(_Event(), "advert") is None
|
||||
|
||||
|
||||
def test_message_from_event_parses_direct_message() -> None:
|
||||
"""A CONTACT_MSG_RECV payload maps to a direct message with sender and timestamp."""
|
||||
from datetime import datetime, timezone
|
||||
|
||||
class _Event:
|
||||
payload = {
|
||||
"type": "PRIV",
|
||||
"pubkey_prefix": "aabbccddeeff",
|
||||
"text": "hello there",
|
||||
"sender_timestamp": 1_700_000_000,
|
||||
"txt_type": 0,
|
||||
}
|
||||
|
||||
msg = message_from_event(_Event())
|
||||
assert msg is not None
|
||||
assert msg.text == "hello there"
|
||||
assert msg.sender == "aabbccddeeff"
|
||||
assert msg.is_channel is False
|
||||
assert msg.channel is None
|
||||
assert msg.sender_timestamp == datetime.fromtimestamp(1_700_000_000, tz=timezone.utc)
|
||||
|
||||
|
||||
def test_message_from_event_parses_channel_message() -> None:
|
||||
"""A CHANNEL_MSG_RECV payload maps to a channel message with no per-contact sender."""
|
||||
|
||||
class _Event:
|
||||
payload = {"type": "CHAN", "channel_idx": 2, "text": "net tonight", "SNR": 5.0}
|
||||
|
||||
msg = message_from_event(_Event())
|
||||
assert msg is not None
|
||||
assert msg.is_channel is True
|
||||
assert msg.channel == 2
|
||||
assert msg.sender is None
|
||||
assert msg.snr == 5.0
|
||||
|
||||
|
||||
def test_message_from_event_without_text_is_skipped() -> None:
|
||||
"""A payload carrying no text body yields no message."""
|
||||
|
||||
class _Event:
|
||||
payload = {"pubkey_prefix": "aabb"}
|
||||
|
||||
assert message_from_event(_Event()) is None
|
||||
|
||||
|
||||
def test_ack_from_event_extracts_code() -> None:
|
||||
"""An ACK payload maps to an Ack carrying the correlation code."""
|
||||
|
||||
class _Event:
|
||||
payload = {"code": "deadbeef"}
|
||||
|
||||
assert ack_from_event(_Event()).code == "deadbeef"
|
||||
|
||||
|
||||
async def test_observations_round_trip_and_aggregate(tmp_path: Path) -> None:
|
||||
"""Observations persist and heard_nodes reaggregates them across runs."""
|
||||
repo = Repository(tmp_path / "obs.db")
|
||||
@@ -161,9 +233,9 @@ async def test_observations_round_trip_and_aggregate(tmp_path: Path) -> None:
|
||||
|
||||
device = MockDevice()
|
||||
await device.connect()
|
||||
observations = await device.listen(
|
||||
0.2, on_observation=lambda o: repo.record_observation(run_id, o)
|
||||
)
|
||||
observations = await _collect_observations(device, 0.2)
|
||||
for obs in observations:
|
||||
repo.record_observation(run_id, obs)
|
||||
assert observations
|
||||
|
||||
nodes = repo.heard_nodes()
|
||||
@@ -220,7 +292,12 @@ async def test_monitor_service_captures_in_background(tmp_path: Path) -> None:
|
||||
|
||||
frozen = service.session_count
|
||||
await asyncio.sleep(_MOCK_INTERVAL * 3)
|
||||
assert service.session_count == frozen # capture really stopped
|
||||
assert service.session_count == frozen # recording really stopped
|
||||
|
||||
# The always-on hub keeps listening after recording stops; shut it down cleanly so the
|
||||
# simulator's background emitter task doesn't outlive the test.
|
||||
await ctx.events.stop()
|
||||
await ctx._device.disconnect()
|
||||
repo.close()
|
||||
|
||||
|
||||
|
||||
Reference in new issue
Block a user