Retire Heard nodes, Link health, Link budget, Route map, and History
Five features leave the menu and CLI: the heard-nodes review, the baseline-regression checker, the offline link-budget calculator, the route-stability graph, and the run-history browser — along with their services (link_quality, link_budget, route_stability), the pyvis route renderer, and the pyvis/networkx dependencies. The data layer is untouched where it still earns its keep: passive monitoring keeps recording every overheard packet (the header counters, Nodes, and Map read it, and `meshterm monitor` still captures a bounded window from the CLI), run logging keeps writing `runs` rows, and trace history stays queryable for the trace tools. Only the route-map-only `all_traces` query goes. Also fixes a latent tie-break flake in the nodes sort: ages are now measured from one clock snapshot, so identical last-seen stamps really tie and keep their A→Z order in both directions. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ba1ff2eedf
commit
44a093c460
20 files changed
+49
-2523
No files matched your search
@@ -4,28 +4,23 @@ A modern, extensible command-line toolkit for tuning and exploring a
|
||||
[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
|
||||
turned into interactive HTML visualizations.
|
||||
MeshTerm is interactive by default (a full-screen Rich + prompt_toolkit TUI) and fully
|
||||
scriptable (every menu option is also a Typer subcommand). Every run is logged to SQLite,
|
||||
building a longitudinal history of the mesh.
|
||||
|
||||
## Features
|
||||
|
||||
| Feature | Status | What it does |
|
||||
| --- | --- | --- |
|
||||
| **Trace** | ✅ skeleton | Run repeated path traces to a target and aggregate per-hop SNR. |
|
||||
| **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. |
|
||||
| **Chat** | ✅ working | Live full-screen channel and direct messaging — a scrolling transcript with a pinned input line where sent and received messages stream together. Every message is logged to SQLite, unread counts show in the menu header, and `chat send/history/list` script the same from the CLI. Channels are picked here; edit them in `config`. |
|
||||
| **Channels** | ✅ working | Create, join, reorder, and share mesh channels — with QR codes and `meshcore://` links. |
|
||||
| **Map** | ✅ working | Mesh nodes on a pannable street map, repeaters highlighted, fed by everything the monitor has overheard. |
|
||||
| **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 *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. |
|
||||
| **Chat** | ✅ working | Live full-screen channel and direct messaging — a scrolling transcript with a pinned input line where sent and received messages stream together. Every message is logged to SQLite, unread counts show in the menu header, and `chat send/history/list` script the same from the CLI. Channels are picked here; edit them in `config`. |
|
||||
| **Passive monitor** | ✅ working | Always-on background logger that records every overheard advert/telemetry (SNR, RSSI, location) to a longitudinal history while you use the app; live packet counts show in the menu header, the heard-node summary is a menu item, and `meshterm monitor --seconds 60` captures a bounded window from the CLI. |
|
||||
| **Link health** | ✅ working | Compare a target's recent traces to its rolling baseline and flag SNR/reliability regressions, end-to-end and per hop. |
|
||||
| **Route map** | ✅ working | Aggregate trace history into an interactive route-stability graph — which links are stable, which the mesh flaps between, with churn metrics. |
|
||||
| **Path optimization** | 🚧 planned | Discover and score mesh paths from neighbors outward. |
|
||||
| **Visualizations** | 🟡 partial | Plotly TX-sweep chart (HTML) done; pyvis mesh graph + time-series planned. |
|
||||
| **Node list** | ✅ working | List this node and its known contacts — recency heat-map, overheard packet counts, full public keys with the path-hash prefix highlighted. |
|
||||
| **Trace** | ✅ working | A live trace screen: pick a target, watch each trace stream in hop by hop, with running per-hop medians and reliability. |
|
||||
| **TX-power optimization** | ✅ working | Sweep a remote node's transmit power live (coarse + refine + verify), watch each level land, then decide whether to apply the winner. |
|
||||
| **Passive monitor** | ✅ working | Always-on background logger that records every overheard advert/telemetry (SNR, RSSI, location) to a longitudinal history while you use the app; live packet counts show in the menu header, the data feeds Nodes and Map, and `meshterm monitor --seconds 60` captures a bounded window from the CLI. |
|
||||
|
||||
## Install
|
||||
|
||||
@@ -51,9 +46,8 @@ meshterm trace --target Alice --samples 10 --profile yagi
|
||||
# contact names and/or hex key prefixes, mixed freely. Blank lets the device route.
|
||||
meshterm trace --target Alice --path "3d,f2,3d"
|
||||
meshterm trace --target Alice --path "3d,Bravo-Repeater,f2"
|
||||
meshterm tx-optimize --target Alice --samples 6 --step 3 --apply
|
||||
meshterm tx-optimize --path "Bravo-Repeater,Alice" --samples 6 --step 3 --apply
|
||||
meshterm info
|
||||
meshterm history
|
||||
|
||||
# Messaging: live chat in the menu, or scripted from the CLI
|
||||
meshterm chat # interactive: pick a conversation, chat live
|
||||
@@ -81,10 +75,10 @@ cli.py Typer app; no subcommand -> interactive menu
|
||||
context.py AppContext (console, config, repository, device) dependency container
|
||||
core/ Domain: models, config + device profiles, connection abstraction (+ mock)
|
||||
tools/ Pluggable "menu options"; each self-registers and gets logging for free
|
||||
services/ Algorithms (trace aggregation, tx search, path exploration) — no UI
|
||||
services/ Algorithms (trace aggregation, tx search) — no UI
|
||||
persistence/ SQLite schema, repository, structured logging
|
||||
ui/ Rich theme/widgets + Questionary menu
|
||||
viz/ Plotly / pyvis renderers -> HTML & PNG
|
||||
ui/ Rich theme/widgets + the full-screen TUI (screens, dialogs, map, chat)
|
||||
viz/ Plotly renderers -> interactive HTML
|
||||
```
|
||||
|
||||
Adding a feature means subclassing `Tool`, decorating it with `@register`, and
|
||||
|
||||
@@ -265,22 +265,6 @@ class Repository:
|
||||
).fetchall()
|
||||
return [self._hydrate_trace(row) for row in rows]
|
||||
|
||||
def all_traces(self, *, limit: int = 500) -> list[TraceResult]:
|
||||
"""Return recent traces across every target, newest first, rehydrated with hops.
|
||||
|
||||
Used to build a whole-mesh route graph rather than a single target's history.
|
||||
|
||||
Args:
|
||||
limit: Maximum number of traces to return.
|
||||
|
||||
Returns:
|
||||
The matching :class:`TraceResult` objects, newest first.
|
||||
"""
|
||||
rows = self._conn.execute(
|
||||
"SELECT * FROM traces ORDER BY id DESC LIMIT ?", (limit,)
|
||||
).fetchall()
|
||||
return [self._hydrate_trace(row) for row in rows]
|
||||
|
||||
def _hydrate_trace(self, row: sqlite3.Row) -> TraceResult:
|
||||
"""Rebuild a :class:`TraceResult` (with hops) from a ``traces`` row.
|
||||
|
||||
|
||||
@@ -1,334 +0,0 @@
|
||||
"""Offline LoRa link-budget, time-on-air, and duty-cycle math.
|
||||
|
||||
This is the *predictive* counterpart to the empirical TX optimizer: given a radio
|
||||
configuration (frequency, bandwidth, spreading factor, coding rate) and a link's
|
||||
geometry (TX power, antenna gains, path-loss model) it computes — with no radio attached —
|
||||
|
||||
* **time-on-air** and bitrate for a packet, the basis for duty-cycle planning;
|
||||
* **receiver sensitivity** from the thermal noise floor and the SF's demodulator limit;
|
||||
* the **maximum tolerable path loss** and a rough **range estimate** from a log-distance
|
||||
model;
|
||||
* **duty-cycle / dwell-time headroom** against a regional limit.
|
||||
|
||||
Everything here is pure arithmetic over plain dataclasses, so it is fully unit-testable
|
||||
and needs no hardware. The formulas follow Semtech's LoRa modem design guide (AN1200.13);
|
||||
range and sensitivity are first-order estimates meant for *comparing* configurations, not
|
||||
for certifying a deployment.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
#: Demodulator SNR floor (dB) per spreading factor — the SNR below which a LoRa symbol
|
||||
#: can no longer be decoded. From Semtech's published figures; used to derive receiver
|
||||
#: sensitivity. SF7..SF12 are the values MeshCore radios actually use.
|
||||
SNR_LIMIT_DB: dict[int, float] = {
|
||||
6: -5.0,
|
||||
7: -7.5,
|
||||
8: -10.0,
|
||||
9: -12.5,
|
||||
10: -15.0,
|
||||
11: -17.5,
|
||||
12: -20.0,
|
||||
}
|
||||
|
||||
#: Receiver noise figure (dB) assumed for a typical SX126x front end.
|
||||
DEFAULT_NOISE_FIGURE_DB = 6.0
|
||||
|
||||
#: Path-loss exponent presets. Free space is the optimistic ceiling; the others are
|
||||
#: common log-distance values for increasingly cluttered environments.
|
||||
PATH_LOSS_EXPONENTS: dict[str, float] = {
|
||||
"free-space": 2.0,
|
||||
"rural": 2.7,
|
||||
"suburban": 3.0,
|
||||
"urban": 3.5,
|
||||
}
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RadioConfig:
|
||||
"""A LoRa physical-layer configuration.
|
||||
|
||||
Attributes:
|
||||
freq_mhz: Carrier frequency in MHz.
|
||||
bw_khz: Bandwidth in kHz (e.g. ``250``).
|
||||
sf: Spreading factor (6-12).
|
||||
cr_denom: Coding-rate denominator (5-8, i.e. 4/5 .. 4/8).
|
||||
preamble_symbols: Preamble length in symbols.
|
||||
explicit_header: Whether the explicit LoRa header is used.
|
||||
crc: Whether the payload CRC is enabled.
|
||||
low_data_rate: Low-data-rate optimization. ``None`` auto-enables it when the
|
||||
symbol time exceeds 16 ms (the conventional threshold).
|
||||
"""
|
||||
|
||||
freq_mhz: float
|
||||
bw_khz: float
|
||||
sf: int
|
||||
cr_denom: int = 5
|
||||
preamble_symbols: int = 8
|
||||
explicit_header: bool = True
|
||||
crc: bool = True
|
||||
low_data_rate: Optional[bool] = None
|
||||
|
||||
def symbol_time_ms(self) -> float:
|
||||
"""Return the LoRa symbol duration in milliseconds (``2**SF / BW``)."""
|
||||
return (2**self.sf) / (self.bw_khz * 1000.0) * 1000.0
|
||||
|
||||
def low_data_rate_enabled(self) -> bool:
|
||||
"""Return whether low-data-rate optimization applies for this config."""
|
||||
if self.low_data_rate is not None:
|
||||
return self.low_data_rate
|
||||
return self.symbol_time_ms() > 16.0
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class TimeOnAir:
|
||||
"""A packet's airtime breakdown.
|
||||
|
||||
Attributes:
|
||||
payload_bytes: Application payload size the figures were computed for.
|
||||
total_ms: Total time-on-air in milliseconds.
|
||||
preamble_ms: Preamble portion in milliseconds.
|
||||
payload_ms: Payload portion in milliseconds.
|
||||
payload_symbols: Number of symbols carrying the payload.
|
||||
bitrate_bps: Effective LoRa bitrate in bits per second.
|
||||
"""
|
||||
|
||||
payload_bytes: int
|
||||
total_ms: float
|
||||
preamble_ms: float
|
||||
payload_ms: float
|
||||
payload_symbols: int
|
||||
bitrate_bps: float
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class DutyCycle:
|
||||
"""Duty-cycle and dwell-time headroom for a configuration.
|
||||
|
||||
Attributes:
|
||||
limit_percent: The regional duty-cycle ceiling applied (e.g. ``1.0`` for 1%).
|
||||
airtime_ms: Time-on-air of one packet.
|
||||
max_packets_per_hour: Packets/hour that fit under ``limit_percent``.
|
||||
min_interval_s: Minimum spacing between packets to stay legal.
|
||||
max_dwell_ms: Regional max dwell time, if any (e.g. 400 ms for US915 FHSS).
|
||||
dwell_ok: Whether one packet fits within ``max_dwell_ms`` (``None`` if no limit).
|
||||
"""
|
||||
|
||||
limit_percent: float
|
||||
airtime_ms: float
|
||||
max_packets_per_hour: float
|
||||
min_interval_s: float
|
||||
max_dwell_ms: Optional[float]
|
||||
dwell_ok: Optional[bool]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class LinkBudget:
|
||||
"""A complete link-budget estimate for one radio config and geometry.
|
||||
|
||||
Attributes:
|
||||
config: The radio configuration evaluated.
|
||||
toa: The packet airtime breakdown.
|
||||
sensitivity_dbm: Estimated receiver sensitivity in dBm.
|
||||
tx_power_dbm: Transmit power used in the budget.
|
||||
tx_gain_dbi: Transmit antenna gain.
|
||||
rx_gain_dbi: Receive antenna gain.
|
||||
max_path_loss_db: Largest path loss the link can tolerate (EIRP-to-sensitivity).
|
||||
range_km: Estimated range from the log-distance model.
|
||||
path_loss_exponent: The exponent used for the range estimate.
|
||||
link_margin_db: Margin at ``reference_path_loss_db`` when one was supplied.
|
||||
duty: Duty-cycle headroom for the configuration.
|
||||
"""
|
||||
|
||||
config: RadioConfig
|
||||
toa: TimeOnAir
|
||||
sensitivity_dbm: float
|
||||
tx_power_dbm: float
|
||||
tx_gain_dbi: float
|
||||
rx_gain_dbi: float
|
||||
max_path_loss_db: float
|
||||
range_km: float
|
||||
path_loss_exponent: float
|
||||
link_margin_db: Optional[float]
|
||||
duty: DutyCycle
|
||||
|
||||
|
||||
def time_on_air(config: RadioConfig, payload_bytes: int) -> TimeOnAir:
|
||||
"""Compute the LoRa time-on-air for a payload.
|
||||
|
||||
Implements the airtime formula from Semtech AN1200.13: a preamble of
|
||||
``(n + 4.25)`` symbols followed by a payload whose symbol count depends on SF, the
|
||||
coding rate, header mode, CRC, and low-data-rate optimization.
|
||||
|
||||
Args:
|
||||
config: The radio configuration.
|
||||
payload_bytes: Application payload length in bytes.
|
||||
|
||||
Returns:
|
||||
A :class:`TimeOnAir` with the airtime breakdown and effective bitrate.
|
||||
"""
|
||||
sf = config.sf
|
||||
tsym_ms = config.symbol_time_ms()
|
||||
de = 1 if config.low_data_rate_enabled() else 0
|
||||
ih = 0 if config.explicit_header else 1
|
||||
crc = 1 if config.crc else 0
|
||||
|
||||
preamble_symbols = config.preamble_symbols + 4.25
|
||||
# Semtech payload-symbol formula; the numerator can go negative for tiny payloads,
|
||||
# so the ceiling is floored at zero before the fixed 8-symbol header overhead.
|
||||
numerator = 8 * payload_bytes - 4 * sf + 28 + 16 * crc - 20 * ih
|
||||
denominator = 4 * (sf - 2 * de)
|
||||
payload_symbols = 8 + max(math.ceil(numerator / denominator) * config.cr_denom, 0)
|
||||
|
||||
preamble_ms = preamble_symbols * tsym_ms
|
||||
payload_ms = payload_symbols * tsym_ms
|
||||
total_ms = preamble_ms + payload_ms
|
||||
bitrate_bps = (payload_bytes * 8) / (total_ms / 1000.0) if total_ms > 0 else 0.0
|
||||
|
||||
return TimeOnAir(
|
||||
payload_bytes=payload_bytes,
|
||||
total_ms=total_ms,
|
||||
preamble_ms=preamble_ms,
|
||||
payload_ms=payload_ms,
|
||||
payload_symbols=payload_symbols,
|
||||
bitrate_bps=bitrate_bps,
|
||||
)
|
||||
|
||||
|
||||
def receiver_sensitivity(
|
||||
config: RadioConfig, noise_figure_db: float = DEFAULT_NOISE_FIGURE_DB
|
||||
) -> float:
|
||||
"""Estimate receiver sensitivity in dBm.
|
||||
|
||||
Sensitivity is the thermal noise floor in the channel plus the receiver noise figure
|
||||
plus the spreading factor's demodulator SNR limit:
|
||||
``-174 + 10*log10(BW_Hz) + NF + SNR_limit(SF)``.
|
||||
|
||||
Args:
|
||||
config: The radio configuration.
|
||||
noise_figure_db: Receiver noise figure in dB.
|
||||
|
||||
Returns:
|
||||
The estimated sensitivity in dBm (more negative is better).
|
||||
"""
|
||||
bw_hz = config.bw_khz * 1000.0
|
||||
snr_limit = SNR_LIMIT_DB.get(config.sf, SNR_LIMIT_DB[12])
|
||||
return -174.0 + 10.0 * math.log10(bw_hz) + noise_figure_db + snr_limit
|
||||
|
||||
|
||||
def free_space_range_km(max_path_loss_db: float, freq_mhz: float, exponent: float) -> float:
|
||||
"""Invert a log-distance path-loss model to estimate range.
|
||||
|
||||
Uses free-space path loss as the 1 km reference and scales by ``exponent``:
|
||||
``PL(d) = FSPL(1km) + 10*n*log10(d_km)``. With ``n = 2`` this is pure free space;
|
||||
higher exponents model clutter. The result is an optimistic line-of-sight figure for
|
||||
*comparing* configurations, not a guaranteed coverage radius.
|
||||
|
||||
Args:
|
||||
max_path_loss_db: The largest path loss the link can tolerate.
|
||||
freq_mhz: Carrier frequency in MHz.
|
||||
exponent: Path-loss exponent (2 = free space).
|
||||
|
||||
Returns:
|
||||
The estimated range in kilometres (never negative).
|
||||
"""
|
||||
# Free-space path loss at the 1 km reference distance.
|
||||
fspl_1km = 32.45 + 20.0 * math.log10(freq_mhz) + 20.0 * math.log10(1.0)
|
||||
excess = max_path_loss_db - fspl_1km
|
||||
if excess <= 0:
|
||||
return 0.0
|
||||
return 10.0 ** (excess / (10.0 * exponent))
|
||||
|
||||
|
||||
def duty_cycle(
|
||||
airtime_ms: float,
|
||||
*,
|
||||
limit_percent: float = 1.0,
|
||||
max_dwell_ms: Optional[float] = None,
|
||||
) -> DutyCycle:
|
||||
"""Compute duty-cycle headroom for a packet airtime.
|
||||
|
||||
Args:
|
||||
airtime_ms: Time-on-air of one packet in milliseconds.
|
||||
limit_percent: Regional duty-cycle ceiling as a percent (e.g. ``1.0`` = 1%).
|
||||
max_dwell_ms: Regional maximum dwell time per transmission, if any.
|
||||
|
||||
Returns:
|
||||
A :class:`DutyCycle` summary.
|
||||
"""
|
||||
fraction = limit_percent / 100.0
|
||||
airtime_s = airtime_ms / 1000.0
|
||||
if airtime_s > 0:
|
||||
max_per_hour = (fraction * 3600.0) / airtime_s
|
||||
min_interval_s = airtime_s / fraction
|
||||
else:
|
||||
max_per_hour = math.inf
|
||||
min_interval_s = 0.0
|
||||
dwell_ok = None if max_dwell_ms is None else airtime_ms <= max_dwell_ms
|
||||
return DutyCycle(
|
||||
limit_percent=limit_percent,
|
||||
airtime_ms=airtime_ms,
|
||||
max_packets_per_hour=max_per_hour,
|
||||
min_interval_s=min_interval_s,
|
||||
max_dwell_ms=max_dwell_ms,
|
||||
dwell_ok=dwell_ok,
|
||||
)
|
||||
|
||||
|
||||
def compute_link_budget(
|
||||
config: RadioConfig,
|
||||
*,
|
||||
payload_bytes: int = 32,
|
||||
tx_power_dbm: float = 22.0,
|
||||
tx_gain_dbi: float = 2.0,
|
||||
rx_gain_dbi: float = 2.0,
|
||||
noise_figure_db: float = DEFAULT_NOISE_FIGURE_DB,
|
||||
path_loss_exponent: float = PATH_LOSS_EXPONENTS["suburban"],
|
||||
reference_path_loss_db: Optional[float] = None,
|
||||
duty_limit_percent: float = 1.0,
|
||||
max_dwell_ms: Optional[float] = None,
|
||||
) -> LinkBudget:
|
||||
"""Assemble a full link budget for a radio configuration and link geometry.
|
||||
|
||||
Args:
|
||||
config: The radio configuration.
|
||||
payload_bytes: Payload size for airtime/bitrate figures.
|
||||
tx_power_dbm: Transmit power in dBm.
|
||||
tx_gain_dbi: Transmit antenna gain in dBi.
|
||||
rx_gain_dbi: Receive antenna gain in dBi.
|
||||
noise_figure_db: Receiver noise figure in dB.
|
||||
path_loss_exponent: Exponent for the range estimate (2 = free space).
|
||||
reference_path_loss_db: A known/expected path loss to report link margin at.
|
||||
duty_limit_percent: Regional duty-cycle ceiling (percent).
|
||||
max_dwell_ms: Regional max dwell time per transmission, if any.
|
||||
|
||||
Returns:
|
||||
A populated :class:`LinkBudget`.
|
||||
"""
|
||||
toa = time_on_air(config, payload_bytes)
|
||||
sensitivity = receiver_sensitivity(config, noise_figure_db)
|
||||
# EIRP minus sensitivity is the most loss the path can absorb and still close.
|
||||
max_path_loss = tx_power_dbm + tx_gain_dbi + rx_gain_dbi - sensitivity
|
||||
range_km = free_space_range_km(max_path_loss, config.freq_mhz, path_loss_exponent)
|
||||
margin = (
|
||||
None if reference_path_loss_db is None else max_path_loss - reference_path_loss_db
|
||||
)
|
||||
return LinkBudget(
|
||||
config=config,
|
||||
toa=toa,
|
||||
sensitivity_dbm=sensitivity,
|
||||
tx_power_dbm=tx_power_dbm,
|
||||
tx_gain_dbi=tx_gain_dbi,
|
||||
rx_gain_dbi=rx_gain_dbi,
|
||||
max_path_loss_db=max_path_loss,
|
||||
range_km=range_km,
|
||||
path_loss_exponent=path_loss_exponent,
|
||||
link_margin_db=margin,
|
||||
duty=duty_cycle(
|
||||
toa.total_ms, limit_percent=duty_limit_percent, max_dwell_ms=max_dwell_ms
|
||||
),
|
||||
)
|
||||
@@ -1,297 +0,0 @@
|
||||
"""Link-quality regression detection against a rolling baseline.
|
||||
|
||||
The trace and TX tools already persist every measurement, so a link's *history* is on
|
||||
disk. This service turns that history into an answer to "is this link worse than it
|
||||
usually is?" — it splits a target's traces into a recent window and an older baseline,
|
||||
then flags end-to-end and per-hop metrics that have degraded beyond a threshold (e.g. the
|
||||
yagi→local hop sitting 6 dB below its 30-day median, or the success rate falling off).
|
||||
|
||||
It is pure logic over :class:`~meshterm.core.models.TraceResult` lists, so it runs
|
||||
identically on live data, replayed history, or the simulator.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import statistics
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable, Optional
|
||||
|
||||
from ..core.models import LOCAL_DEVICE_LABEL, TraceResult, TraceStats
|
||||
|
||||
#: Default SNR drop (dB) from baseline that counts as a regression.
|
||||
DEFAULT_SNR_DROP_DB = 3.0
|
||||
#: Default success-rate drop (fraction) from baseline that counts as a regression.
|
||||
DEFAULT_SUCCESS_DROP = 0.2
|
||||
#: Traces taken as the "recent" window (the rest form the baseline).
|
||||
DEFAULT_RECENT_COUNT = 3
|
||||
#: Minimum baseline traces required before a verdict is trustworthy.
|
||||
DEFAULT_MIN_BASELINE = 3
|
||||
|
||||
NodeResolver = Callable[[Optional[str]], Optional[str]]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class MetricChange:
|
||||
"""A single metric compared between the baseline and recent windows.
|
||||
|
||||
Attributes:
|
||||
subject: What the metric describes (the target, or a ``a → b`` link).
|
||||
metric: Human-readable metric name (e.g. ``min SNR``).
|
||||
kind: ``target`` for an end-to-end metric, ``link`` for one hop.
|
||||
baseline: The baseline-window value.
|
||||
recent: The recent-window value.
|
||||
baseline_n: Number of baseline samples behind ``baseline``.
|
||||
recent_n: Number of recent samples behind ``recent``.
|
||||
threshold: The drop magnitude that marks a regression.
|
||||
regressed: Whether ``recent`` is worse than ``baseline`` past ``threshold``.
|
||||
"""
|
||||
|
||||
subject: str
|
||||
metric: str
|
||||
kind: str
|
||||
baseline: float
|
||||
recent: float
|
||||
baseline_n: int
|
||||
recent_n: int
|
||||
threshold: float
|
||||
regressed: bool
|
||||
|
||||
@property
|
||||
def delta(self) -> float:
|
||||
"""Signed change ``recent - baseline`` (negative means degraded)."""
|
||||
return self.recent - self.baseline
|
||||
|
||||
@property
|
||||
def severity(self) -> str:
|
||||
"""``critical`` when the drop is at least twice the threshold, else ``warn``/``ok``."""
|
||||
if not self.regressed:
|
||||
return "ok"
|
||||
return "critical" if -self.delta >= 2 * self.threshold else "warn"
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class HealthReport:
|
||||
"""The link-quality verdict for one target.
|
||||
|
||||
Attributes:
|
||||
target: The trace destination analyzed.
|
||||
baseline_n: Traces in the baseline window.
|
||||
recent_n: Traces in the recent window.
|
||||
changes: Every metric evaluated (target-level and per-link).
|
||||
"""
|
||||
|
||||
target: str
|
||||
baseline_n: int
|
||||
recent_n: int
|
||||
changes: list[MetricChange] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def regressions(self) -> list[MetricChange]:
|
||||
"""The subset of ``changes`` that actually regressed, worst drop first."""
|
||||
return sorted(
|
||||
(c for c in self.changes if c.regressed), key=lambda c: c.delta
|
||||
)
|
||||
|
||||
@property
|
||||
def status(self) -> str:
|
||||
"""``insufficient-data``, ``ok``, ``degraded`` (warn), or ``critical``."""
|
||||
if not self.changes:
|
||||
return "insufficient-data"
|
||||
regs = self.regressions
|
||||
if not regs:
|
||||
return "ok"
|
||||
if any(c.severity == "critical" for c in regs):
|
||||
return "critical"
|
||||
return "degraded"
|
||||
|
||||
|
||||
def analyze_target(
|
||||
target: str,
|
||||
traces: list[TraceResult],
|
||||
*,
|
||||
recent_count: int = DEFAULT_RECENT_COUNT,
|
||||
min_baseline: int = DEFAULT_MIN_BASELINE,
|
||||
snr_drop_db: float = DEFAULT_SNR_DROP_DB,
|
||||
success_drop: float = DEFAULT_SUCCESS_DROP,
|
||||
resolve: Optional[NodeResolver] = None,
|
||||
device_label: str = LOCAL_DEVICE_LABEL,
|
||||
) -> HealthReport:
|
||||
"""Detect link-quality regressions for ``target`` from its trace history.
|
||||
|
||||
The traces are split by recency: the newest ``recent_count`` form the recent window,
|
||||
the remainder the baseline. End-to-end bottleneck SNR and success rate are compared,
|
||||
plus the median SNR of each per-hop link that appears in both windows.
|
||||
|
||||
Args:
|
||||
target: The trace destination.
|
||||
traces: Its trace history (any order; partitioned here by timestamp).
|
||||
recent_count: Number of newest traces treated as the recent window.
|
||||
min_baseline: Minimum baseline traces required for a verdict.
|
||||
snr_drop_db: SNR drop (dB) from baseline that flags a regression.
|
||||
success_drop: Success-rate drop (fraction) that flags a regression.
|
||||
resolve: Optional resolver mapping a hop hash to a friendly node name.
|
||||
device_label: Label for our own device at the path endpoints.
|
||||
|
||||
Returns:
|
||||
A :class:`HealthReport`. With too little history its ``changes`` is empty and
|
||||
``status`` is ``insufficient-data``.
|
||||
"""
|
||||
ordered = sorted(traces, key=lambda t: t.timestamp, reverse=True)
|
||||
recent = ordered[:recent_count]
|
||||
baseline = ordered[recent_count:]
|
||||
if len(recent) < 2 or len(baseline) < min_baseline:
|
||||
return HealthReport(target=target, baseline_n=len(baseline), recent_n=len(recent))
|
||||
|
||||
base_stats = TraceStats.from_traces(target, baseline)
|
||||
recent_stats = TraceStats.from_traces(target, recent)
|
||||
changes: list[MetricChange] = []
|
||||
|
||||
if base_stats.median_min_snr is not None and recent_stats.median_min_snr is not None:
|
||||
changes.append(
|
||||
_change(
|
||||
subject=target,
|
||||
metric="min SNR (dB)",
|
||||
kind="target",
|
||||
baseline=base_stats.median_min_snr,
|
||||
recent=recent_stats.median_min_snr,
|
||||
baseline_n=base_stats.successes,
|
||||
recent_n=recent_stats.successes,
|
||||
threshold=snr_drop_db,
|
||||
)
|
||||
)
|
||||
|
||||
changes.append(
|
||||
_change(
|
||||
subject=target,
|
||||
metric="success rate",
|
||||
kind="target",
|
||||
baseline=base_stats.success_rate,
|
||||
recent=recent_stats.success_rate,
|
||||
baseline_n=base_stats.samples,
|
||||
recent_n=recent_stats.samples,
|
||||
threshold=success_drop,
|
||||
)
|
||||
)
|
||||
|
||||
changes.extend(
|
||||
_link_changes(baseline, recent, snr_drop_db, resolve, device_label)
|
||||
)
|
||||
return HealthReport(
|
||||
target=target, baseline_n=len(baseline), recent_n=len(recent), changes=changes
|
||||
)
|
||||
|
||||
|
||||
def _change(
|
||||
*,
|
||||
subject: str,
|
||||
metric: str,
|
||||
kind: str,
|
||||
baseline: float,
|
||||
recent: float,
|
||||
baseline_n: int,
|
||||
recent_n: int,
|
||||
threshold: float,
|
||||
) -> MetricChange:
|
||||
"""Build a :class:`MetricChange`, flagging it regressed on a drop past ``threshold``.
|
||||
|
||||
Both metrics here are "higher is better" (SNR, success rate), so a regression is a
|
||||
decrease of at least ``threshold``.
|
||||
|
||||
Args:
|
||||
subject: What the metric describes.
|
||||
metric: Metric name.
|
||||
kind: ``target`` or ``link``.
|
||||
baseline: Baseline value.
|
||||
recent: Recent value.
|
||||
baseline_n: Baseline sample count.
|
||||
recent_n: Recent sample count.
|
||||
threshold: Drop magnitude that marks a regression.
|
||||
|
||||
Returns:
|
||||
The populated :class:`MetricChange`.
|
||||
"""
|
||||
regressed = (baseline - recent) >= threshold
|
||||
return MetricChange(
|
||||
subject=subject,
|
||||
metric=metric,
|
||||
kind=kind,
|
||||
baseline=baseline,
|
||||
recent=recent,
|
||||
baseline_n=baseline_n,
|
||||
recent_n=recent_n,
|
||||
threshold=threshold,
|
||||
regressed=regressed,
|
||||
)
|
||||
|
||||
|
||||
def _link_changes(
|
||||
baseline: list[TraceResult],
|
||||
recent: list[TraceResult],
|
||||
snr_drop_db: float,
|
||||
resolve: Optional[NodeResolver],
|
||||
device_label: str,
|
||||
) -> list[MetricChange]:
|
||||
"""Compare per-hop link SNR between the two windows.
|
||||
|
||||
Only links present in *both* windows are compared, so a transient path that appears
|
||||
in just one window doesn't masquerade as a regression.
|
||||
|
||||
Args:
|
||||
baseline: Baseline-window traces.
|
||||
recent: Recent-window traces.
|
||||
snr_drop_db: SNR drop (dB) that flags a link regression.
|
||||
resolve: Optional hop-hash → name resolver for the link label.
|
||||
device_label: Label for our own device.
|
||||
|
||||
Returns:
|
||||
One :class:`MetricChange` per shared link, worst (most negative) drop first.
|
||||
"""
|
||||
base_links = _link_snrs(baseline, resolve, device_label)
|
||||
recent_links = _link_snrs(recent, resolve, device_label)
|
||||
changes: list[MetricChange] = []
|
||||
for link in base_links.keys() & recent_links.keys():
|
||||
base_snrs = base_links[link]
|
||||
recent_snrs = recent_links[link]
|
||||
changes.append(
|
||||
_change(
|
||||
subject=link,
|
||||
metric="link SNR (dB)",
|
||||
kind="link",
|
||||
baseline=statistics.median(base_snrs),
|
||||
recent=statistics.median(recent_snrs),
|
||||
baseline_n=len(base_snrs),
|
||||
recent_n=len(recent_snrs),
|
||||
threshold=snr_drop_db,
|
||||
)
|
||||
)
|
||||
return sorted(changes, key=lambda c: c.delta)
|
||||
|
||||
|
||||
def _link_snrs(
|
||||
traces: list[TraceResult], resolve: Optional[NodeResolver], device_label: str
|
||||
) -> dict[str, list[float]]:
|
||||
"""Collect per-link SNR samples keyed by an ``origin → destination`` label.
|
||||
|
||||
Args:
|
||||
traces: The traces to read edges from.
|
||||
resolve: Optional hop-hash → name resolver.
|
||||
device_label: Label for our own device at the endpoints.
|
||||
|
||||
Returns:
|
||||
A mapping of link label to the SNR readings seen on it.
|
||||
"""
|
||||
out: dict[str, list[float]] = {}
|
||||
for trace in traces:
|
||||
if not trace.success:
|
||||
continue
|
||||
for edge in trace.edges(device_label):
|
||||
label = f"{_name(edge.origin, resolve)} → {_name(edge.destination, resolve)}"
|
||||
out.setdefault(label, []).append(edge.snr)
|
||||
return out
|
||||
|
||||
|
||||
def _name(label: str, resolve: Optional[NodeResolver]) -> str:
|
||||
"""Resolve a hop label to a friendly name when a resolver is supplied."""
|
||||
if resolve is None:
|
||||
return label
|
||||
return resolve(label) or label
|
||||
@@ -1,191 +0,0 @@
|
||||
"""Route-stability aggregation: turn trace history into a mesh graph with churn metrics.
|
||||
|
||||
The MeshCore app traces a route once. Because MeshTerm persists every trace, it can
|
||||
instead show how *stable* routing is over time — which hops are always used and which the
|
||||
mesh flaps between. This service aggregates a set of traces into:
|
||||
|
||||
* a **graph** of nodes and directed links, each link weighted by how often it was
|
||||
traversed and its median SNR; and
|
||||
* per-target **churn** metrics: how many distinct routes were seen and what share the
|
||||
single most-common route held (the higher that share, the steadier the routing).
|
||||
|
||||
It is pure logic over :class:`~meshterm.core.models.TraceResult` lists; the pyvis
|
||||
renderer in :mod:`meshterm.viz.route_graph` draws the result.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import statistics
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
|
||||
from ..core.models import LOCAL_DEVICE_LABEL, TraceResult
|
||||
|
||||
NodeResolver = Callable[[Optional[str]], Optional[str]]
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RouteLink:
|
||||
"""A directed link between two nodes, aggregated across traces.
|
||||
|
||||
Attributes:
|
||||
origin: Transmitting node label.
|
||||
destination: Receiving node label.
|
||||
count: Number of trace hops that traversed this link.
|
||||
median_snr: Median SNR (dB) measured on it.
|
||||
"""
|
||||
|
||||
origin: str
|
||||
destination: str
|
||||
count: int
|
||||
median_snr: float
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RouteNode:
|
||||
"""A node in the route graph.
|
||||
|
||||
Attributes:
|
||||
label: Display label for the node.
|
||||
is_self: Whether this is our own companion device.
|
||||
degree: Number of distinct links (in or out) touching the node.
|
||||
"""
|
||||
|
||||
label: str
|
||||
is_self: bool
|
||||
degree: int
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class RouteGraph:
|
||||
"""An aggregated route graph plus churn metrics.
|
||||
|
||||
Attributes:
|
||||
target: The single target analyzed, or ``None`` for a whole-mesh graph.
|
||||
nodes: The graph's nodes.
|
||||
links: The graph's directed links.
|
||||
total_routes: Number of successful traces aggregated.
|
||||
distinct_routes: Number of unique full-path signatures seen.
|
||||
dominant_share: Fraction of traces that took the single most-common route.
|
||||
churn_entropy: Shannon entropy (bits) of the route-choice distribution — ``0``
|
||||
when one route is always chosen, growing as traffic spreads across more
|
||||
equally-likely routes.
|
||||
"""
|
||||
|
||||
target: Optional[str]
|
||||
nodes: list[RouteNode] = field(default_factory=list)
|
||||
links: list[RouteLink] = field(default_factory=list)
|
||||
total_routes: int = 0
|
||||
distinct_routes: int = 0
|
||||
dominant_share: float = 0.0
|
||||
churn_entropy: float = 0.0
|
||||
|
||||
@property
|
||||
def stability(self) -> float:
|
||||
"""A 0-1 stability score: ``1`` when one route always wins, lower as it flaps.
|
||||
|
||||
Defined as the dominant route's share, so a single stable path scores ``1.0`` and
|
||||
an even split across many routes trends toward ``0``.
|
||||
"""
|
||||
return self.dominant_share
|
||||
|
||||
|
||||
def build_route_graph(
|
||||
traces: list[TraceResult],
|
||||
*,
|
||||
target: Optional[str] = None,
|
||||
resolve: Optional[NodeResolver] = None,
|
||||
device_label: str = LOCAL_DEVICE_LABEL,
|
||||
) -> RouteGraph:
|
||||
"""Aggregate traces into a route graph with churn metrics.
|
||||
|
||||
Args:
|
||||
traces: The traces to aggregate (only successful ones contribute edges/routes).
|
||||
target: The target these traces share, or ``None`` for a multi-target graph.
|
||||
resolve: Optional resolver mapping a hop hash to a friendly node name.
|
||||
device_label: Label for our own device at the path endpoints.
|
||||
|
||||
Returns:
|
||||
A populated :class:`RouteGraph`. With no successful traces the graph is empty and
|
||||
its metrics are zero.
|
||||
"""
|
||||
successes = [t for t in traces if t.success and t.hops]
|
||||
link_snrs: dict[tuple[str, str], list[float]] = {}
|
||||
route_counts: dict[tuple[str, ...], int] = {}
|
||||
node_links: dict[str, set[tuple[str, str]]] = {}
|
||||
|
||||
for trace in successes:
|
||||
edges = trace.edges(device_label)
|
||||
signature: list[str] = []
|
||||
for edge in edges:
|
||||
origin = _name(edge.origin, resolve)
|
||||
destination = _name(edge.destination, resolve)
|
||||
key = (origin, destination)
|
||||
link_snrs.setdefault(key, []).append(edge.snr)
|
||||
node_links.setdefault(origin, set()).add(key)
|
||||
node_links.setdefault(destination, set()).add(key)
|
||||
if not signature:
|
||||
signature.append(origin)
|
||||
signature.append(destination)
|
||||
route_counts[tuple(signature)] = route_counts.get(tuple(signature), 0) + 1
|
||||
|
||||
links = [
|
||||
RouteLink(
|
||||
origin=origin,
|
||||
destination=destination,
|
||||
count=len(snrs),
|
||||
median_snr=statistics.median(snrs),
|
||||
)
|
||||
for (origin, destination), snrs in link_snrs.items()
|
||||
]
|
||||
links.sort(key=lambda link_item: link_item.count, reverse=True)
|
||||
|
||||
self_label = _name(device_label, resolve)
|
||||
nodes = [
|
||||
RouteNode(label=label, is_self=(label == self_label), degree=len(keys))
|
||||
for label, keys in sorted(node_links.items(), key=lambda kv: len(kv[1]), reverse=True)
|
||||
]
|
||||
|
||||
total = len(successes)
|
||||
dominant_share = (max(route_counts.values()) / total) if total else 0.0
|
||||
return RouteGraph(
|
||||
target=target,
|
||||
nodes=nodes,
|
||||
links=links,
|
||||
total_routes=total,
|
||||
distinct_routes=len(route_counts),
|
||||
dominant_share=dominant_share,
|
||||
churn_entropy=_route_entropy(route_counts, total),
|
||||
)
|
||||
|
||||
|
||||
def _route_entropy(route_counts: dict[tuple[str, ...], int], total: int) -> float:
|
||||
"""Return the Shannon entropy (bits) of a route-choice distribution.
|
||||
|
||||
Args:
|
||||
route_counts: Map of route signature to how often it occurred.
|
||||
total: Total number of routes counted.
|
||||
|
||||
Returns:
|
||||
The entropy in bits (``0`` for a single route).
|
||||
"""
|
||||
if total <= 0:
|
||||
return 0.0
|
||||
entropy = 0.0
|
||||
for count in route_counts.values():
|
||||
p = count / total
|
||||
if p > 0:
|
||||
entropy -= p * math.log2(p)
|
||||
return entropy
|
||||
|
||||
|
||||
def _name(label: Optional[str], resolve: Optional[NodeResolver]) -> str:
|
||||
"""Resolve a hop label to a friendly name, leaving our own device's label intact."""
|
||||
if label is None:
|
||||
resolved = resolve(None) if resolve else None
|
||||
return resolved or LOCAL_DEVICE_LABEL
|
||||
if resolve is None:
|
||||
return label
|
||||
return resolve(label) or label
|
||||
@@ -142,7 +142,7 @@ _REGISTRY: dict[str, Tool] = {}
|
||||
#: Explicit menu ordering for tool categories. Messaging (Chat + Channels) leads because it
|
||||
#: holds the first-class, everyday features; the rest follow in a natural workflow order.
|
||||
#: Categories not listed here sort last, alphabetically, so a new category still appears.
|
||||
_CATEGORY_ORDER = ["Messaging", "Device", "Diagnostics", "Optimization", "Data"]
|
||||
_CATEGORY_ORDER = ["Messaging", "Device", "Diagnostics"]
|
||||
|
||||
|
||||
def _category_rank(category: str) -> int:
|
||||
|
||||
@@ -1,69 +0,0 @@
|
||||
"""The ``history`` tool: browse logged tool executions from the database."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import typer
|
||||
from rich.table import Table
|
||||
|
||||
from ..context import AppContext
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
_STATUS_STYLE = {"ok": "ok", "error": "err", "running": "warn"}
|
||||
|
||||
|
||||
@register
|
||||
class HistoryTool(Tool):
|
||||
"""List recent runs recorded in the database (no device needed)."""
|
||||
|
||||
name = "history"
|
||||
title = "History"
|
||||
help = "Show recent tool executions and their outcomes"
|
||||
category = "Data"
|
||||
order = 10
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Render the most recent runs as a table.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Optional ``limit`` (int) controlling row count.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` noting how many runs were shown.
|
||||
"""
|
||||
limit = int(params.get("limit", 20))
|
||||
runs = ctx.repo.list_runs(limit=limit)
|
||||
|
||||
table = Table(title=f"Recent runs (last {limit})", border_style="muted")
|
||||
table.add_column("#", justify="right", style="muted")
|
||||
table.add_column("TOOL", style="brand")
|
||||
table.add_column("PROFILE", style="muted")
|
||||
table.add_column("STATUS")
|
||||
table.add_column("STARTED")
|
||||
for r in runs:
|
||||
style = _STATUS_STYLE.get(r.status, "muted")
|
||||
table.add_row(
|
||||
str(r.id),
|
||||
r.tool,
|
||||
r.profile or "-",
|
||||
f"[{style}]{r.status}[/{style}]",
|
||||
r.started_at.replace("T", " ")[:19],
|
||||
)
|
||||
ctx.ui.show(table)
|
||||
return ToolResult(summary={"shown": len(runs)})
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``history`` subcommand.
|
||||
|
||||
Args:
|
||||
app: The Typer application.
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
|
||||
@app.command(name=self.name, help=self.help)
|
||||
def _history(
|
||||
limit: int = typer.Option(20, "--limit", "-n", help="Number of runs to show"),
|
||||
) -> None:
|
||||
run_tool_command(self, {"limit": limit})
|
||||
@@ -1,320 +0,0 @@
|
||||
"""The ``link-budget`` tool: predict airtime, range, and duty-cycle headroom offline.
|
||||
|
||||
Unlike the empirical ``tx-optimize`` sweep, this tool measures nothing on the air — it
|
||||
answers "*should* I try SF11?" or "how many packets an hour can I legally send?" from the
|
||||
LoRa math alone. Radio parameters default to the connected device's current config (so it
|
||||
reads like a what-if on your live setup), but every value can be overridden, and a fully
|
||||
specified invocation needs no radio at all.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
import typer
|
||||
from rich.panel import Panel
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
|
||||
from ..context import AppContext
|
||||
from ..services import link_budget
|
||||
from ..services.link_budget import PATH_LOSS_EXPONENTS, RadioConfig
|
||||
from ..ui.tui import Choice
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
|
||||
@register
|
||||
class LinkBudgetTool(Tool):
|
||||
"""Compute time-on-air, sensitivity, range, and duty-cycle headroom for a radio config."""
|
||||
|
||||
name = "link-budget"
|
||||
title = "Link budget"
|
||||
help = "Predict airtime, range, and duty-cycle headroom for a radio config"
|
||||
category = "Optimization"
|
||||
order = 20
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]:
|
||||
"""Interactively gather payload, geometry, and environment, prefilled from the device.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
|
||||
Returns:
|
||||
A parameter dict, or ``None`` if the user cancelled.
|
||||
"""
|
||||
defaults = await self._device_radio(ctx)
|
||||
|
||||
payload = await ctx.ui.text(
|
||||
"Payload size (bytes):", default="32", validate=_is_pos_int
|
||||
)
|
||||
if payload is None:
|
||||
return None
|
||||
tx = await ctx.ui.text(
|
||||
"TX power (dBm):",
|
||||
default=str(int(defaults.get("tx_power") or 22)),
|
||||
validate=_is_number,
|
||||
)
|
||||
if tx is None:
|
||||
return None
|
||||
tx_gain = await ctx.ui.text("TX antenna gain (dBi):", default="2", validate=_is_number)
|
||||
if tx_gain is None:
|
||||
return None
|
||||
rx_gain = await ctx.ui.text("RX antenna gain (dBi):", default="2", validate=_is_number)
|
||||
if rx_gain is None:
|
||||
return None
|
||||
env = await ctx.ui.select(
|
||||
"Environment (path-loss model):",
|
||||
[Choice(name, name) for name in PATH_LOSS_EXPONENTS],
|
||||
default="suburban",
|
||||
)
|
||||
if env is None:
|
||||
return None
|
||||
duty = await ctx.ui.text("Duty-cycle limit (%):", default="1.0", validate=_is_number)
|
||||
if duty is None:
|
||||
return None
|
||||
|
||||
params: dict[str, Any] = {
|
||||
"payload": int(payload),
|
||||
"tx": float(tx),
|
||||
"tx_gain": float(tx_gain),
|
||||
"rx_gain": float(rx_gain),
|
||||
"env": env,
|
||||
"duty": float(duty),
|
||||
}
|
||||
params.update(defaults.get("radio", {}))
|
||||
return params
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Build the radio config, compute the budget, and render it.
|
||||
|
||||
Radio parameters come from ``params`` when fully supplied (so the tool runs with
|
||||
no radio attached); any missing value is read from the connected device.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``payload``, ``tx``, ``tx_gain``, ``rx_gain``, ``env``/``exponent``,
|
||||
``duty``, optional ``dwell``/``path_loss``, and the radio parameters
|
||||
``freq``/``bw``/``sf``/``cr`` (else read from the device).
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing the budget.
|
||||
"""
|
||||
config = await self._resolve_config(ctx, params)
|
||||
exponent = float(
|
||||
params.get("exponent", PATH_LOSS_EXPONENTS.get(params.get("env", "suburban"), 3.0))
|
||||
)
|
||||
budget = link_budget.compute_link_budget(
|
||||
config,
|
||||
payload_bytes=int(params.get("payload", 32)),
|
||||
tx_power_dbm=float(params.get("tx", 22.0)),
|
||||
tx_gain_dbi=float(params.get("tx_gain", 2.0)),
|
||||
rx_gain_dbi=float(params.get("rx_gain", 2.0)),
|
||||
path_loss_exponent=exponent,
|
||||
reference_path_loss_db=params.get("path_loss"),
|
||||
duty_limit_percent=float(params.get("duty", 1.0)),
|
||||
max_dwell_ms=params.get("dwell"),
|
||||
)
|
||||
|
||||
ctx.ui.show(_radio_panel(config))
|
||||
ctx.ui.show(_budget_panel(budget))
|
||||
|
||||
return ToolResult(
|
||||
summary={
|
||||
"freq_mhz": config.freq_mhz,
|
||||
"bw_khz": config.bw_khz,
|
||||
"sf": config.sf,
|
||||
"cr_denom": config.cr_denom,
|
||||
"payload_bytes": budget.toa.payload_bytes,
|
||||
"time_on_air_ms": round(budget.toa.total_ms, 2),
|
||||
"bitrate_bps": round(budget.toa.bitrate_bps, 1),
|
||||
"sensitivity_dbm": round(budget.sensitivity_dbm, 1),
|
||||
"max_path_loss_db": round(budget.max_path_loss_db, 1),
|
||||
"range_km": round(budget.range_km, 2),
|
||||
"max_packets_per_hour": round(budget.duty.max_packets_per_hour, 1),
|
||||
"dwell_ok": budget.duty.dwell_ok,
|
||||
},
|
||||
message=(
|
||||
f"[ok]✓[/ok] SF{config.sf}/BW{config.bw_khz:g} → "
|
||||
f"[brand]{budget.toa.total_ms:.0f} ms[/brand] airtime, "
|
||||
f"~[brand]{budget.range_km:.1f} km[/brand] range "
|
||||
f"({budget.duty.max_packets_per_hour:.0f} pkts/h at "
|
||||
f"{budget.duty.limit_percent:g}% duty)"
|
||||
),
|
||||
)
|
||||
|
||||
async def _resolve_config(self, ctx: AppContext, params: dict[str, Any]) -> RadioConfig:
|
||||
"""Build a :class:`RadioConfig` from params, filling gaps from the device.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Tool params that may carry ``freq``/``bw``/``sf``/``cr``.
|
||||
|
||||
Returns:
|
||||
The resolved radio configuration.
|
||||
"""
|
||||
radio_keys = ("freq", "bw", "sf", "cr")
|
||||
if not all(params.get(k) is not None for k in radio_keys):
|
||||
info = await (await ctx.device()).get_self_info()
|
||||
params = {
|
||||
"freq": params.get("freq", info.get("radio_freq")),
|
||||
"bw": params.get("bw", info.get("radio_bw")),
|
||||
"sf": params.get("sf", info.get("radio_sf")),
|
||||
"cr": params.get("cr", info.get("radio_cr")),
|
||||
**{k: v for k, v in params.items() if k not in radio_keys},
|
||||
}
|
||||
return RadioConfig(
|
||||
freq_mhz=float(params["freq"]),
|
||||
bw_khz=float(params["bw"]),
|
||||
sf=int(params["sf"]),
|
||||
cr_denom=int(params.get("cr", 5)),
|
||||
)
|
||||
|
||||
async def _device_radio(self, ctx: AppContext) -> dict[str, Any]:
|
||||
"""Read the device's radio config for prompt prefill; tolerate no device.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
|
||||
Returns:
|
||||
A dict with a ``radio`` sub-dict (freq/bw/sf/cr) and ``tx_power`` when a
|
||||
device is reachable, otherwise empty defaults.
|
||||
"""
|
||||
try:
|
||||
info = await (await ctx.device()).get_self_info()
|
||||
except Exception: # noqa: BLE001 - offline use is fully supported; fall back
|
||||
return {}
|
||||
return {
|
||||
"radio": {
|
||||
"freq": info.get("radio_freq"),
|
||||
"bw": info.get("radio_bw"),
|
||||
"sf": info.get("radio_sf"),
|
||||
"cr": info.get("radio_cr"),
|
||||
},
|
||||
"tx_power": info.get("tx_power"),
|
||||
}
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``link-budget`` subcommand.
|
||||
|
||||
Args:
|
||||
app: The Typer application.
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
|
||||
@app.command(name=self.name, help=self.help)
|
||||
def _link_budget(
|
||||
freq: Optional[float] = typer.Option(None, "--freq", help="Frequency (MHz)"),
|
||||
bw: Optional[float] = typer.Option(None, "--bw", help="Bandwidth (kHz)"),
|
||||
sf: Optional[int] = typer.Option(None, "--sf", help="Spreading factor (6-12)"),
|
||||
cr: Optional[int] = typer.Option(None, "--cr", help="Coding-rate denom (5-8)"),
|
||||
payload: int = typer.Option(32, "--payload", help="Payload size (bytes)"),
|
||||
tx: float = typer.Option(22.0, "--tx", help="TX power (dBm)"),
|
||||
tx_gain: float = typer.Option(2.0, "--tx-gain", help="TX antenna gain (dBi)"),
|
||||
rx_gain: float = typer.Option(2.0, "--rx-gain", help="RX antenna gain (dBi)"),
|
||||
env: str = typer.Option(
|
||||
"suburban", "--env", help="Path-loss model: free-space/rural/suburban/urban"
|
||||
),
|
||||
exponent: Optional[float] = typer.Option(
|
||||
None, "--exponent", help="Override the path-loss exponent (2 = free space)"
|
||||
),
|
||||
duty: float = typer.Option(1.0, "--duty", help="Duty-cycle limit (%)"),
|
||||
dwell: Optional[float] = typer.Option(
|
||||
None, "--dwell", help="Max dwell time per TX (ms), e.g. 400 for US915"
|
||||
),
|
||||
path_loss: Optional[float] = typer.Option(
|
||||
None, "--path-loss", help="A known path loss (dB) to report link margin at"
|
||||
),
|
||||
) -> None:
|
||||
tool_params: dict[str, Any] = {
|
||||
"payload": payload, "tx": tx, "tx_gain": tx_gain, "rx_gain": rx_gain,
|
||||
"env": env, "duty": duty,
|
||||
}
|
||||
for key, value in (
|
||||
("freq", freq), ("bw", bw), ("sf", sf), ("cr", cr),
|
||||
("exponent", exponent), ("dwell", dwell), ("path_loss", path_loss),
|
||||
):
|
||||
if value is not None:
|
||||
tool_params[key] = value
|
||||
run_tool_command(self, tool_params)
|
||||
|
||||
|
||||
def _radio_panel(config: RadioConfig) -> Panel:
|
||||
"""Render the radio configuration being evaluated.
|
||||
|
||||
Args:
|
||||
config: The radio configuration.
|
||||
|
||||
Returns:
|
||||
A Rich :class:`Panel` describing the config.
|
||||
"""
|
||||
ldr = "on" if config.low_data_rate_enabled() else "off"
|
||||
body = Text.assemble(
|
||||
("frequency ", "muted"), (f"{config.freq_mhz:g} MHz\n", ""),
|
||||
("bandwidth ", "muted"), (f"{config.bw_khz:g} kHz\n", ""),
|
||||
("spreading ", "muted"), (f"SF{config.sf}\n", "brand"),
|
||||
("coding rate ", "muted"), (f"4/{config.cr_denom}\n", ""),
|
||||
("symbol time ", "muted"), (f"{config.symbol_time_ms():.2f} ms\n", ""),
|
||||
("low data rate ", "muted"), (ldr, ""),
|
||||
)
|
||||
return Panel(body, title="[accent]Radio config[/accent]", border_style="muted", expand=False)
|
||||
|
||||
|
||||
def _budget_panel(budget: link_budget.LinkBudget) -> Panel:
|
||||
"""Render the computed link budget as a labelled table.
|
||||
|
||||
Args:
|
||||
budget: The link budget to display.
|
||||
|
||||
Returns:
|
||||
A Rich :class:`Panel` with airtime, sensitivity, range, and duty figures.
|
||||
"""
|
||||
table = Table(box=None, padding=(0, 2, 0, 0), expand=False)
|
||||
table.add_column("METRIC", style="muted")
|
||||
table.add_column("VALUE", justify="right")
|
||||
|
||||
toa = budget.toa
|
||||
table.add_row("payload", f"{toa.payload_bytes} bytes")
|
||||
table.add_row("time on air", Text(f"{toa.total_ms:.1f} ms", style="brand"))
|
||||
table.add_row("bitrate", f"{toa.bitrate_bps:.0f} bps")
|
||||
table.add_section()
|
||||
table.add_row("TX EIRP", f"{budget.tx_power_dbm + budget.tx_gain_dbi:.1f} dBm")
|
||||
table.add_row("RX sensitivity", f"{budget.sensitivity_dbm:.1f} dBm")
|
||||
table.add_row("max path loss", Text(f"{budget.max_path_loss_db:.1f} dB", style="brand"))
|
||||
table.add_row(
|
||||
f"est. range (n={budget.path_loss_exponent:g})",
|
||||
Text(f"{budget.range_km:.2f} km", style="brand"),
|
||||
)
|
||||
if budget.link_margin_db is not None:
|
||||
style = "ok" if budget.link_margin_db >= 0 else "err"
|
||||
table.add_row("link margin", Text(f"{budget.link_margin_db:+.1f} dB", style=style))
|
||||
table.add_section()
|
||||
duty = budget.duty
|
||||
table.add_row(f"duty limit ({duty.limit_percent:g}%)", "")
|
||||
table.add_row(" max packets/hour", f"{duty.max_packets_per_hour:.0f}")
|
||||
table.add_row(" min spacing", f"{duty.min_interval_s:.1f} s")
|
||||
if duty.max_dwell_ms is not None:
|
||||
ok = duty.dwell_ok
|
||||
cell = Text(
|
||||
f"{'ok' if ok else 'OVER'} ({duty.max_dwell_ms:g} ms)",
|
||||
style="ok" if ok else "err",
|
||||
)
|
||||
table.add_row(" dwell-time", cell)
|
||||
|
||||
return Panel(table, title="[accent]Link budget[/accent]", border_style="accent", expand=False)
|
||||
|
||||
|
||||
def _is_pos_int(value: str) -> bool | str:
|
||||
"""Validate a positive integer for a questionary text answer."""
|
||||
try:
|
||||
return True if int(value) > 0 else "Enter a number greater than zero."
|
||||
except ValueError:
|
||||
return "Enter a whole number."
|
||||
|
||||
|
||||
def _is_number(value: str) -> bool | str:
|
||||
"""Validate a real number for a questionary text answer."""
|
||||
try:
|
||||
float(value)
|
||||
return True
|
||||
except ValueError:
|
||||
return "Enter a number."
|
||||
@@ -1,278 +0,0 @@
|
||||
"""The ``link-health`` tool: flag links that have degraded against their own baseline.
|
||||
|
||||
Every trace MeshTerm runs is persisted, so each link has a history. This tool splits a
|
||||
target's trace history into a recent window and an older baseline and reports any
|
||||
end-to-end or per-hop metric that has dropped beyond a threshold — turning the live SNR
|
||||
number the app shows into "this hop is 6 dB below its usual median". Optionally it takes a
|
||||
few fresh traces first, so it can be run standalone rather than only over stored data.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
import typer
|
||||
from rich.panel import Panel
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
|
||||
from ..context import AppContext
|
||||
from ..services import link_quality, trace_runner
|
||||
from ..services.link_quality import HealthReport, MetricChange
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
_STATUS_STYLE = {
|
||||
"ok": "ok",
|
||||
"degraded": "warn",
|
||||
"critical": "err",
|
||||
"insufficient-data": "muted",
|
||||
}
|
||||
_SEVERITY_STYLE = {"critical": "err", "warn": "warn", "ok": "ok"}
|
||||
|
||||
|
||||
@register
|
||||
class LinkHealthTool(Tool):
|
||||
"""Detect link-quality regressions for a target against its rolling baseline."""
|
||||
|
||||
name = "link-health"
|
||||
title = "Link health"
|
||||
help = "Flag links whose SNR or reliability dropped below their baseline"
|
||||
category = "Diagnostics"
|
||||
order = 30
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]:
|
||||
"""Choose a target (from history or contacts) and an optional fresh-sample count.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
|
||||
Returns:
|
||||
A parameter dict, or ``None`` if the user cancelled.
|
||||
"""
|
||||
# Offer targets we already have history for first, then known contacts.
|
||||
history = ctx.repo.traced_targets()
|
||||
try:
|
||||
contacts = [c.name for c in await (await ctx.device()).get_contacts()]
|
||||
except Exception: # noqa: BLE001 - history-only analysis needs no device
|
||||
contacts = []
|
||||
choices = list(dict.fromkeys(history + contacts))
|
||||
prompt = "Target to check:"
|
||||
if choices:
|
||||
target = await ctx.ui.autocomplete(prompt, choices)
|
||||
else:
|
||||
target = await ctx.ui.text(prompt)
|
||||
if not target:
|
||||
return None
|
||||
|
||||
samples = await ctx.ui.text(
|
||||
"Take how many fresh traces first? (0 = use stored history only)",
|
||||
default="0",
|
||||
validate=_is_nonneg_int,
|
||||
)
|
||||
if samples is None:
|
||||
return None
|
||||
return {"target": target.strip(), "samples": int(samples)}
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Optionally trace, load history, analyze regressions, and render the report.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: ``target``, optional ``samples``/``path``/``recent``/``snr_drop``/
|
||||
``success_drop``/``min_baseline``, and the injected ``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` carrying the verdict and any regressions.
|
||||
"""
|
||||
target = params["target"]
|
||||
run_id = params["_run_id"]
|
||||
samples = int(params.get("samples", 0))
|
||||
resolve = None
|
||||
|
||||
if samples > 0:
|
||||
device = await ctx.device()
|
||||
contacts = await device.get_contacts()
|
||||
resolve = trace_runner.make_node_resolver(contacts)
|
||||
path = None
|
||||
if params.get("path"):
|
||||
path = trace_runner.parse_trace_path(params["path"], contacts)
|
||||
with ctx.ui.progress("link-health") as progress:
|
||||
task = progress.add_task(f"tracing {target}", total=samples)
|
||||
await trace_runner.run_traces(
|
||||
device,
|
||||
target,
|
||||
samples=samples,
|
||||
path=path,
|
||||
cooldown_s=ctx.settings.trace_cooldown_s,
|
||||
on_result=lambda *_: progress.advance(task),
|
||||
persist=lambda t: ctx.repo.record_trace(run_id, t),
|
||||
)
|
||||
|
||||
traces = ctx.repo.recent_traces(target)
|
||||
if resolve is None:
|
||||
# No fresh run: still try to name hops, but tolerate having no device.
|
||||
try:
|
||||
contacts = await (await ctx.device()).get_contacts()
|
||||
resolve = trace_runner.make_node_resolver(contacts)
|
||||
except Exception: # noqa: BLE001 - analysis works on raw hashes too
|
||||
resolve = None
|
||||
|
||||
report = link_quality.analyze_target(
|
||||
target,
|
||||
traces,
|
||||
recent_count=int(params.get("recent", link_quality.DEFAULT_RECENT_COUNT)),
|
||||
min_baseline=int(params.get("min_baseline", link_quality.DEFAULT_MIN_BASELINE)),
|
||||
snr_drop_db=float(params.get("snr_drop", link_quality.DEFAULT_SNR_DROP_DB)),
|
||||
success_drop=float(params.get("success_drop", link_quality.DEFAULT_SUCCESS_DROP)),
|
||||
resolve=resolve,
|
||||
)
|
||||
|
||||
ctx.ui.show(_report_panel(report))
|
||||
if report.status == "insufficient-data":
|
||||
message = (
|
||||
f"[muted]not enough history for[/muted] [brand]{target}[/brand] "
|
||||
f"({report.baseline_n} baseline + {report.recent_n} recent traces); "
|
||||
"run more traces or the monitor first."
|
||||
)
|
||||
elif report.status == "ok":
|
||||
message = f"[ok]✓[/ok] [brand]{target}[/brand] is healthy vs its baseline"
|
||||
else:
|
||||
n = len(report.regressions)
|
||||
style = _STATUS_STYLE[report.status]
|
||||
message = (
|
||||
f"[{style}]![/{style}] [brand]{target}[/brand] shows "
|
||||
f"[{style}]{n} regression{'s' if n != 1 else ''}[/{style}] "
|
||||
f"({report.status})"
|
||||
)
|
||||
|
||||
return ToolResult(
|
||||
summary={
|
||||
"target": report.target,
|
||||
"status": report.status,
|
||||
"baseline_n": report.baseline_n,
|
||||
"recent_n": report.recent_n,
|
||||
"regressions": [
|
||||
{
|
||||
"subject": c.subject,
|
||||
"metric": c.metric,
|
||||
"baseline": round(c.baseline, 2),
|
||||
"recent": round(c.recent, 2),
|
||||
"delta": round(c.delta, 2),
|
||||
"severity": c.severity,
|
||||
}
|
||||
for c in report.regressions
|
||||
],
|
||||
},
|
||||
message=message,
|
||||
)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``link-health`` subcommand.
|
||||
|
||||
Args:
|
||||
app: The Typer application.
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
|
||||
@app.command(name=self.name, help=self.help)
|
||||
def _link_health(
|
||||
target: str = typer.Option(..., "--target", "-t", help="Target node name/prefix"),
|
||||
samples: int = typer.Option(
|
||||
0, "--samples", "-n", help="Fresh traces to take before analyzing"
|
||||
),
|
||||
path: Optional[str] = typer.Option(
|
||||
None, "--path", "-p", help="Force a path for the fresh traces"
|
||||
),
|
||||
recent: int = typer.Option(
|
||||
link_quality.DEFAULT_RECENT_COUNT, "--recent", help="Newest traces as 'recent'"
|
||||
),
|
||||
snr_drop: float = typer.Option(
|
||||
link_quality.DEFAULT_SNR_DROP_DB, "--snr-drop", help="SNR drop (dB) to flag"
|
||||
),
|
||||
success_drop: float = typer.Option(
|
||||
link_quality.DEFAULT_SUCCESS_DROP,
|
||||
"--success-drop",
|
||||
help="Success-rate drop (fraction) to flag",
|
||||
),
|
||||
) -> None:
|
||||
tool_params: dict[str, Any] = {
|
||||
"target": target, "samples": samples, "recent": recent,
|
||||
"snr_drop": snr_drop, "success_drop": success_drop,
|
||||
}
|
||||
if path:
|
||||
tool_params["path"] = path
|
||||
run_tool_command(self, tool_params)
|
||||
|
||||
|
||||
def _report_panel(report: HealthReport) -> Panel:
|
||||
"""Render the health report as a status header plus a table of changes.
|
||||
|
||||
Args:
|
||||
report: The analyzed report.
|
||||
|
||||
Returns:
|
||||
A Rich :class:`Panel` summarizing the verdict and metric changes.
|
||||
"""
|
||||
style = _STATUS_STYLE.get(report.status, "muted")
|
||||
header = Text.assemble(
|
||||
("target ", "muted"), (f"{report.target}\n", "brand"),
|
||||
("status ", "muted"), (report.status, style), ("\n", ""),
|
||||
("window ", "muted"),
|
||||
(f"{report.recent_n} recent vs {report.baseline_n} baseline traces", ""),
|
||||
)
|
||||
if not report.changes:
|
||||
return Panel(
|
||||
header, title="[accent]Link health[/accent]", border_style=style, expand=False
|
||||
)
|
||||
|
||||
table = Table(box=None, padding=(0, 2, 0, 0), expand=False)
|
||||
table.add_column("METRIC", style="muted")
|
||||
table.add_column("SUBJECT")
|
||||
table.add_column("BASELINE", justify="right")
|
||||
table.add_column("RECENT", justify="right")
|
||||
table.add_column("Δ", justify="right")
|
||||
# Worst regressions first, then the still-healthy metrics for context.
|
||||
for change in sorted(report.changes, key=lambda c: (not c.regressed, c.delta)):
|
||||
table.add_row(*_change_row(change))
|
||||
|
||||
from rich.console import Group
|
||||
|
||||
body = Group(header, Text(), table)
|
||||
return Panel(body, title="[accent]Link health[/accent]", border_style=style, expand=False)
|
||||
|
||||
|
||||
def _change_row(change: MetricChange) -> tuple[str, Text, str, str, Text]:
|
||||
"""Format one metric change as a styled table row.
|
||||
|
||||
Args:
|
||||
change: The metric change to render.
|
||||
|
||||
Returns:
|
||||
The five cell values for the changes table.
|
||||
"""
|
||||
sev_style = _SEVERITY_STYLE.get(change.severity, "muted")
|
||||
marker = "● " if change.regressed else " "
|
||||
delta_cell = Text(f"{marker}{change.delta:+.2f}", style=sev_style)
|
||||
subject = Text(change.subject, style="brand" if change.regressed else None)
|
||||
return (
|
||||
change.metric,
|
||||
subject,
|
||||
f"{change.baseline:.2f}",
|
||||
f"{change.recent:.2f}",
|
||||
delta_cell,
|
||||
)
|
||||
|
||||
|
||||
def _is_nonneg_int(value: str) -> bool | str:
|
||||
"""Validate a non-negative integer for a questionary text answer.
|
||||
|
||||
Args:
|
||||
value: Raw input.
|
||||
|
||||
Returns:
|
||||
``True`` if valid, otherwise an error message string.
|
||||
"""
|
||||
try:
|
||||
return True if int(value) >= 0 else "Enter zero or a positive number."
|
||||
except ValueError:
|
||||
return "Enter a whole number."
|
||||
+22
-78
@@ -1,18 +1,18 @@
|
||||
"""The ``monitor`` tool: review what the always-on passive monitor has heard.
|
||||
"""The ``monitor`` tool: a bounded foreground capture of what the mesh is saying.
|
||||
|
||||
Passive monitoring records every advert and telemetry frame the companion overhears —
|
||||
with SNR, RSSI, and any shared location — to the database, building the longitudinal
|
||||
history that the coverage map and link-quality alerting read back. It transmits nothing;
|
||||
history that the map's packet counts and the nodes list read back. It transmits nothing;
|
||||
it only listens.
|
||||
|
||||
Recording is always on: the session-wide
|
||||
:class:`~meshterm.services.event_hub.EventHub` overhears every packet, and
|
||||
:class:`~meshterm.services.monitor_service.MonitorService` (``ctx.monitor``) writes them
|
||||
to history as one of its subscribers, from the moment the radio opens. There is nothing
|
||||
to switch, so in the menu this tool is purely the read side: the all-time heard-node
|
||||
summary (the live packet counters are shown in the main-menu header, not here). On the
|
||||
CLI it is instead a bounded foreground capture — ``meshterm monitor --seconds 60`` tails
|
||||
each overheard packet to the console and summarizes the window when it ends.
|
||||
to history as one of its subscribers, from the moment the radio opens. In the menu the
|
||||
live packet counters show in the persistent header and the accumulated data surfaces
|
||||
through Nodes and Map, so there is no separate screen here — this tool is CLI-only:
|
||||
``meshterm monitor --seconds 60`` tails each overheard packet to the console and
|
||||
summarizes the window when it ends.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -32,21 +32,21 @@ from .base import Tool, ToolResult, register
|
||||
|
||||
@register
|
||||
class MonitorTool(Tool):
|
||||
"""Review the nodes the always-on passive monitor has heard."""
|
||||
"""Capture overheard packets in the foreground for a bounded window (CLI only)."""
|
||||
|
||||
name = "monitor"
|
||||
title = "Heard nodes"
|
||||
help = "Review every node the passive monitor has overheard"
|
||||
title = "Monitor"
|
||||
help = "Capture overheard packets live for a while and summarize them"
|
||||
category = "Diagnostics"
|
||||
order = 20
|
||||
menu_visible = False # recording is always on; in the menu the header/Nodes/Map show it
|
||||
|
||||
async def execute(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Run directly, without a logged ``runs`` row.
|
||||
|
||||
The heard-node review is a read of existing history, not a measurement, so it is
|
||||
deliberately not wrapped in run-logging (unlike the base :meth:`Tool.execute`).
|
||||
The CLI capture's observations are recorded under the monitor service's own
|
||||
``monitor`` run instead.
|
||||
The capture's observations are recorded under the monitor service's own
|
||||
``monitor`` run, so wrapping this invocation in a second run row (as the base
|
||||
:meth:`Tool.execute` would) would double-log the session.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
@@ -58,23 +58,7 @@ class MonitorTool(Tool):
|
||||
return await self.run(ctx, params)
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Show the heard-node review, or run the CLI's bounded capture.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: Empty for the menu's review; ``action="capture"`` plus ``seconds``
|
||||
for the CLI capture.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` describing the outcome.
|
||||
"""
|
||||
if params.get("action") == "capture":
|
||||
return await self._capture(ctx, params)
|
||||
return self._view(ctx)
|
||||
|
||||
@staticmethod
|
||||
async def _capture(ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Record overheard packets in the foreground for a bounded window (CLI only).
|
||||
"""Record overheard packets in the foreground for a bounded window.
|
||||
|
||||
Connects the device, ensures history recording and the event hub are running,
|
||||
and tails each overheard packet to the console until the window ends (or the
|
||||
@@ -131,7 +115,7 @@ class MonitorTool(Tool):
|
||||
nodes = [HeardNode.from_observations(node, group) for node, group in by_node.items()]
|
||||
if nodes:
|
||||
nodes.sort(key=lambda n: n.last_seen, reverse=True)
|
||||
ctx.ui.show(_heard_table(nodes, lambda _node: None))
|
||||
ctx.ui.show(_heard_table(nodes))
|
||||
return ToolResult(
|
||||
summary={"seconds": seconds, "packets": len(seen), "nodes": len(nodes)},
|
||||
message=(
|
||||
@@ -141,42 +125,6 @@ class MonitorTool(Tool):
|
||||
),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _view(ctx: AppContext) -> ToolResult:
|
||||
"""Render the all-time heard-node summary from stored observations.
|
||||
|
||||
Reads only the database, so it needs no device connection and works whether or
|
||||
not packets are currently arriving.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` summarizing the heard nodes.
|
||||
"""
|
||||
heard = ctx.repo.heard_nodes()
|
||||
if heard:
|
||||
# Names come from the stored observations, so no device lookup is needed.
|
||||
ctx.ui.show(_heard_table(heard, lambda _node: None))
|
||||
else:
|
||||
ctx.ui.note(
|
||||
"[muted]no packets heard yet — history accumulates while MeshTerm runs[/muted]"
|
||||
)
|
||||
|
||||
packets = sum(n.count for n in heard)
|
||||
located = sum(1 for n in heard if n.has_location)
|
||||
return ToolResult(
|
||||
summary={
|
||||
"nodes_heard": len(heard),
|
||||
"observations": packets,
|
||||
"nodes_with_location": located,
|
||||
},
|
||||
message=(
|
||||
f"[ok]✓[/ok] heard [brand]{packets}[/brand] packets from "
|
||||
f"[brand]{len(heard)}[/brand] nodes (all time)"
|
||||
),
|
||||
)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``monitor`` subcommand (the bounded foreground capture).
|
||||
|
||||
@@ -185,24 +133,20 @@ class MonitorTool(Tool):
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
|
||||
@app.command(
|
||||
name=self.name,
|
||||
help="Capture overheard packets live for a while and summarize them",
|
||||
)
|
||||
@app.command(name=self.name, help=self.help)
|
||||
def _monitor(
|
||||
seconds: int = typer.Option(
|
||||
0, "--seconds", "-s", help="How long to capture (0 = until Ctrl-C)"
|
||||
),
|
||||
) -> None:
|
||||
run_tool_command(self, {"action": "capture", "seconds": seconds})
|
||||
run_tool_command(self, {"seconds": seconds})
|
||||
|
||||
|
||||
def _heard_table(heard: list[HeardNode], resolve) -> Table: # noqa: ANN001
|
||||
"""Render the heard-node summary table.
|
||||
def _heard_table(heard: list[HeardNode]) -> Table:
|
||||
"""Render the capture window's heard-node summary table.
|
||||
|
||||
Args:
|
||||
heard: Aggregated per-node statistics.
|
||||
resolve: Maps a raw node hash to a friendly contact name when known.
|
||||
heard: Aggregated per-node statistics for the window.
|
||||
|
||||
Returns:
|
||||
A Rich :class:`Table` of node, packet count, SNR, RSSI, and location.
|
||||
@@ -217,7 +161,7 @@ def _heard_table(heard: list[HeardNode], resolve) -> Table: # noqa: ANN001
|
||||
table.add_column("RSSI", justify="right")
|
||||
table.add_column("LOC", justify="center")
|
||||
for node in heard:
|
||||
label = node.name or resolve(node.node) or node.node or "?"
|
||||
label = node.name or node.node or "?"
|
||||
median = node.median_snr
|
||||
best = node.best_snr
|
||||
median_cell = (
|
||||
|
||||
@@ -1,237 +0,0 @@
|
||||
"""The ``route-map`` tool: visualize how stable mesh routing is over time.
|
||||
|
||||
Where the app's traceroute is a single snapshot, this aggregates a target's (or the whole
|
||||
mesh's) trace history into an interactive graph and churn metrics: which links are always
|
||||
used, which the mesh flaps between, and how often the single most-common route actually
|
||||
wins. It reads stored traces and can optionally take a few fresh ones first.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Optional
|
||||
|
||||
import typer
|
||||
from rich.panel import Panel
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
|
||||
from ..context import AppContext
|
||||
from ..services import route_stability, trace_runner
|
||||
from ..services.route_stability import RouteGraph
|
||||
from ..ui.theme import snr_style
|
||||
from ..ui.tui import Choice, Separator
|
||||
from ..viz.route_graph import render_route_graph
|
||||
from .base import Tool, ToolResult, register
|
||||
|
||||
_WHOLE_MESH = "(whole mesh)"
|
||||
_BACK = "__back__"
|
||||
|
||||
|
||||
@register
|
||||
class RouteMapTool(Tool):
|
||||
"""Aggregate trace history into a route-stability graph and churn metrics."""
|
||||
|
||||
name = "route-map"
|
||||
title = "Route map"
|
||||
help = "Map how stable mesh routing is over time, as an interactive graph"
|
||||
category = "Optimization"
|
||||
order = 30
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]:
|
||||
"""Choose a target (or the whole mesh) and an optional fresh-sample count.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
|
||||
Returns:
|
||||
A parameter dict, or ``None`` if the user cancelled.
|
||||
"""
|
||||
targets = ctx.repo.traced_targets()
|
||||
choice = await ctx.ui.select(
|
||||
"Map routing for:",
|
||||
[
|
||||
Choice(_WHOLE_MESH, _WHOLE_MESH),
|
||||
*(Choice(t, t) for t in targets),
|
||||
Separator(" "),
|
||||
Choice("Back", _BACK),
|
||||
],
|
||||
)
|
||||
if choice in (None, _BACK):
|
||||
return None
|
||||
samples = await ctx.ui.text(
|
||||
"Take how many fresh traces first? (0 = use stored history only)",
|
||||
default="0",
|
||||
validate=_is_nonneg_int,
|
||||
)
|
||||
if samples is None:
|
||||
return None
|
||||
params: dict[str, Any] = {"samples": int(samples)}
|
||||
if choice != _WHOLE_MESH:
|
||||
params["target"] = choice
|
||||
return params
|
||||
|
||||
async def run(self, ctx: AppContext, params: dict[str, Any]) -> ToolResult:
|
||||
"""Optionally trace, load history, build the graph, render it, and summarize.
|
||||
|
||||
Args:
|
||||
ctx: Shared application context.
|
||||
params: optional ``target``/``samples``/``path``/``viz`` and ``_run_id``.
|
||||
|
||||
Returns:
|
||||
A :class:`ToolResult` with the churn metrics and the graph path.
|
||||
"""
|
||||
target = params.get("target")
|
||||
run_id = params["_run_id"]
|
||||
samples = int(params.get("samples", 0))
|
||||
resolve = None
|
||||
|
||||
if samples > 0:
|
||||
if not target:
|
||||
return ToolResult(
|
||||
message="[err]✗[/err] --samples requires a --target to trace.",
|
||||
)
|
||||
device = await ctx.device()
|
||||
contacts = await device.get_contacts()
|
||||
resolve = trace_runner.make_node_resolver(contacts)
|
||||
path = (
|
||||
trace_runner.parse_trace_path(params["path"], contacts)
|
||||
if params.get("path")
|
||||
else None
|
||||
)
|
||||
with ctx.ui.progress("route-map") as progress:
|
||||
task = progress.add_task(f"tracing {target}", total=samples)
|
||||
await trace_runner.run_traces(
|
||||
device, target, samples=samples, path=path,
|
||||
cooldown_s=ctx.settings.trace_cooldown_s,
|
||||
on_result=lambda *_: progress.advance(task),
|
||||
persist=lambda t: ctx.repo.record_trace(run_id, t),
|
||||
)
|
||||
|
||||
traces = ctx.repo.recent_traces(target) if target else ctx.repo.all_traces()
|
||||
if resolve is None:
|
||||
try:
|
||||
contacts = await (await ctx.device()).get_contacts()
|
||||
resolve = trace_runner.make_node_resolver(contacts)
|
||||
except Exception: # noqa: BLE001 - the graph reads fine with raw hashes
|
||||
resolve = None
|
||||
|
||||
graph = route_stability.build_route_graph(traces, target=target, resolve=resolve)
|
||||
|
||||
ctx.ui.show(_graph_panel(graph))
|
||||
|
||||
artifacts: list[str] = []
|
||||
if graph.total_routes and params.get("viz", True) and ctx.settings.output_dir:
|
||||
out = render_route_graph(graph, ctx.settings.output_dir)
|
||||
artifacts.append(str(out))
|
||||
|
||||
scope = target or "the mesh"
|
||||
if not graph.total_routes:
|
||||
message = (
|
||||
f"[muted]no successful traces stored for[/muted] [brand]{scope}[/brand] — "
|
||||
"run some traces first."
|
||||
)
|
||||
else:
|
||||
message = (
|
||||
f"[ok]✓[/ok] [brand]{scope}[/brand]: {graph.stability:.0%} of "
|
||||
f"{graph.total_routes} traces took the top route "
|
||||
f"({graph.distinct_routes} distinct)"
|
||||
)
|
||||
|
||||
return ToolResult(
|
||||
summary={
|
||||
"target": target,
|
||||
"total_routes": graph.total_routes,
|
||||
"distinct_routes": graph.distinct_routes,
|
||||
"stability": round(graph.stability, 3),
|
||||
"churn_entropy_bits": round(graph.churn_entropy, 3),
|
||||
"nodes": len(graph.nodes),
|
||||
"links": len(graph.links),
|
||||
},
|
||||
message=message,
|
||||
artifacts=artifacts,
|
||||
)
|
||||
|
||||
def register_cli(self, app: typer.Typer) -> None:
|
||||
"""Register the ``route-map`` subcommand.
|
||||
|
||||
Args:
|
||||
app: The Typer application.
|
||||
"""
|
||||
from ..cli import run_tool_command
|
||||
|
||||
@app.command(name=self.name, help=self.help)
|
||||
def _route_map(
|
||||
target: Optional[str] = typer.Option(
|
||||
None, "--target", "-t", help="Target to map (omit for the whole mesh)"
|
||||
),
|
||||
samples: int = typer.Option(
|
||||
0, "--samples", "-n", help="Fresh traces to take first (requires --target)"
|
||||
),
|
||||
path: Optional[str] = typer.Option(
|
||||
None, "--path", "-p", help="Force a path for the fresh traces"
|
||||
),
|
||||
viz: bool = typer.Option(True, "--viz/--no-viz", help="Render the HTML graph"),
|
||||
) -> None:
|
||||
tool_params: dict[str, Any] = {"samples": samples, "viz": viz}
|
||||
if target:
|
||||
tool_params["target"] = target
|
||||
if path:
|
||||
tool_params["path"] = path
|
||||
run_tool_command(self, tool_params)
|
||||
|
||||
|
||||
def _graph_panel(graph: RouteGraph) -> Panel:
|
||||
"""Render churn metrics and the busiest links as a panel.
|
||||
|
||||
Args:
|
||||
graph: The aggregated route graph.
|
||||
|
||||
Returns:
|
||||
A Rich :class:`Panel` summarizing stability and top links.
|
||||
"""
|
||||
scope = graph.target or "whole mesh"
|
||||
stab_style = "ok" if graph.stability >= 0.8 else ("warn" if graph.stability >= 0.5 else "err")
|
||||
header = Text.assemble(
|
||||
("scope ", "muted"), (f"{scope}\n", "brand"),
|
||||
("traces ", "muted"), (f"{graph.total_routes}\n", ""),
|
||||
("distinct routes ", "muted"), (f"{graph.distinct_routes}\n", ""),
|
||||
("stability ", "muted"), (f"{graph.stability:.0%}", stab_style), ("\n", ""),
|
||||
("route entropy ", "muted"), (f"{graph.churn_entropy:.2f} bits", ""),
|
||||
)
|
||||
if not graph.links:
|
||||
return Panel(
|
||||
header, title="[accent]Route stability[/accent]", border_style="muted", expand=False
|
||||
)
|
||||
|
||||
table = Table(box=None, padding=(0, 2, 0, 0), expand=False)
|
||||
table.add_column("LINK")
|
||||
table.add_column("USES", justify="right")
|
||||
table.add_column("MEDIAN SNR", justify="right")
|
||||
for link in graph.links[:10]:
|
||||
table.add_row(
|
||||
f"{link.origin} → {link.destination}",
|
||||
str(link.count),
|
||||
Text(f"{link.median_snr:+.1f} dB", style=snr_style(link.median_snr)),
|
||||
)
|
||||
|
||||
from rich.console import Group
|
||||
|
||||
body = Group(header, Text("\nBusiest links", style="accent"), table)
|
||||
return Panel(
|
||||
body, title="[accent]Route stability[/accent]", border_style="accent", expand=False
|
||||
)
|
||||
|
||||
|
||||
def _is_nonneg_int(value: str) -> bool | str:
|
||||
"""Validate a non-negative integer for a questionary text answer.
|
||||
|
||||
Args:
|
||||
value: Raw input.
|
||||
|
||||
Returns:
|
||||
``True`` if valid, otherwise an error message string.
|
||||
"""
|
||||
try:
|
||||
return True if int(value) >= 0 else "Enter zero or a positive number."
|
||||
except ValueError:
|
||||
return "Enter a whole number."
|
||||
@@ -33,8 +33,8 @@ class TxOptimizeTool(Tool):
|
||||
name = "tx-optimize"
|
||||
title = "TX optimize"
|
||||
help = "Tune a remote node's TX power for the best signal at a target"
|
||||
category = "Optimization"
|
||||
order = 10
|
||||
category = "Diagnostics"
|
||||
order = 15 # right after Trace, its measurement sibling
|
||||
|
||||
async def prompt_params(self, ctx: AppContext) -> Optional[dict[str, Any]]:
|
||||
"""Interactively gather the path, sampling, range, and apply choices.
|
||||
|
||||
@@ -577,9 +577,14 @@ def _ordered_contacts(
|
||||
end.
|
||||
"""
|
||||
if sort.column == "heard":
|
||||
# One clock snapshot for the whole sort: per-row utcnow() calls would skew two
|
||||
# identical last_seen stamps apart by microseconds and defeat the name tie-break.
|
||||
now = utcnow()
|
||||
|
||||
def metric(c: Contact) -> float:
|
||||
secs = _age_seconds(c.last_seen)
|
||||
return secs if secs is not None else float("inf")
|
||||
if c.last_seen is None or getattr(c.last_seen, "tzinfo", None) is None:
|
||||
return float("inf")
|
||||
return max(0.0, (now - c.last_seen).total_seconds())
|
||||
elif sort.column == "packets":
|
||||
def metric(c: Contact) -> float:
|
||||
return _contact_pkts(c, counts) or 0
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
"""Visualization layer: Plotly / pyvis renderers producing interactive HTML (and PNG).
|
||||
"""Visualization layer: Plotly renderers producing interactive, self-contained HTML.
|
||||
|
||||
Planned renderers (see the project plan):
|
||||
|
||||
* ``tx_plot`` — SNR-vs-TX-power curve with confidence band and chosen optimum.
|
||||
* ``path_graph`` — interactive pyvis mesh graph, edges colored by SNR.
|
||||
* ``timeseries`` — link SNR / success-rate dashboards over time.
|
||||
|
||||
This package is intentionally empty in the skeleton; renderers are added alongside the
|
||||
TX-power and path-optimization tools.
|
||||
* ``tx_plot`` — SNR-vs-TX-power curve for an optimization sweep, with the chosen
|
||||
optimum highlighted.
|
||||
"""
|
||||
@@ -1,131 +0,0 @@
|
||||
"""pyvis renderer for the route-stability graph.
|
||||
|
||||
Draws the aggregated mesh routing as a self-contained, interactive HTML graph: nodes are
|
||||
mesh devices (our companion highlighted), directed edges are links whose width grows with
|
||||
how often the link was traversed and whose colour tracks median SNR. The title carries the
|
||||
churn metrics so the picture and the numbers travel together.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
from ..services.route_stability import RouteGraph
|
||||
|
||||
_SELF_COLOR = "#4ade80"
|
||||
_NODE_COLOR = "#5eead4"
|
||||
_BG = "#0f172a"
|
||||
_FONT = "#e2e8f0"
|
||||
|
||||
|
||||
def render_route_graph(graph: RouteGraph, output_dir: Path) -> Path:
|
||||
"""Render a route graph to an interactive, self-contained HTML file.
|
||||
|
||||
Args:
|
||||
graph: The aggregated route graph to draw.
|
||||
output_dir: Directory the HTML file is written to (created if needed).
|
||||
|
||||
Returns:
|
||||
Path to the written HTML file.
|
||||
"""
|
||||
from pyvis.network import Network
|
||||
|
||||
# ``cdn_resources='in_line'`` inlines vis.js so the file works offline, matching the
|
||||
# self-contained Plotly charts elsewhere.
|
||||
net = Network(
|
||||
height="720px",
|
||||
width="100%",
|
||||
directed=True,
|
||||
bgcolor=_BG,
|
||||
font_color=_FONT,
|
||||
cdn_resources="in_line",
|
||||
)
|
||||
|
||||
for node in graph.nodes:
|
||||
color = _SELF_COLOR if node.is_self else _NODE_COLOR
|
||||
net.add_node(
|
||||
node.label,
|
||||
label=node.label,
|
||||
color=color,
|
||||
shape="star" if node.is_self else "dot",
|
||||
size=14 + 3 * node.degree,
|
||||
title=f"{node.label} · {node.degree} link(s)",
|
||||
)
|
||||
|
||||
max_count = max((link.count for link in graph.links), default=1)
|
||||
for link in graph.links:
|
||||
width = 1.0 + 6.0 * (link.count / max_count)
|
||||
net.add_edge(
|
||||
link.origin,
|
||||
link.destination,
|
||||
value=link.count,
|
||||
width=width,
|
||||
color=_snr_color(link.median_snr),
|
||||
title=f"{link.origin} → {link.destination}: "
|
||||
f"{link.count}× · median {link.median_snr:+.1f} dB",
|
||||
)
|
||||
|
||||
net.set_options(_OPTIONS)
|
||||
|
||||
scope = graph.target or "mesh"
|
||||
heading = (
|
||||
f"Route stability — {scope} · {graph.total_routes} traces, "
|
||||
f"{graph.distinct_routes} route(s), {graph.stability:.0%} on the top route"
|
||||
)
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
|
||||
path = output_dir / f"route-map_{_slug(scope)}_{stamp}.html"
|
||||
html = net.generate_html(notebook=False)
|
||||
banner = f"<h2 style='color:{_FONT};font-family:sans-serif'>{heading}</h2>"
|
||||
html = html.replace("<body>", f"<body>{banner}")
|
||||
path.write_text(html, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _snr_color(snr: float) -> str:
|
||||
"""Map a median SNR (dB) to an edge colour from red (weak) to green (strong).
|
||||
|
||||
Args:
|
||||
snr: Median SNR in dB.
|
||||
|
||||
Returns:
|
||||
A hex colour string.
|
||||
"""
|
||||
if snr >= 5:
|
||||
return "#4ade80" # strong
|
||||
if snr >= 0:
|
||||
return "#facc15" # marginal
|
||||
if snr >= -8:
|
||||
return "#fb923c" # weak
|
||||
return "#f87171" # very weak
|
||||
|
||||
|
||||
def _slug(value: str) -> str:
|
||||
"""Make a filesystem-safe slug from a label.
|
||||
|
||||
Args:
|
||||
value: Arbitrary node name or scope label.
|
||||
|
||||
Returns:
|
||||
A lowercase slug containing only alphanumerics, dashes, and underscores.
|
||||
"""
|
||||
slug = "".join(c if c.isalnum() or c in "-_" else "-" for c in value).strip("-").lower()
|
||||
return slug or "graph"
|
||||
|
||||
|
||||
#: vis.js physics/layout tuning for a readable, settled mesh graph.
|
||||
_OPTIONS = """
|
||||
{
|
||||
"physics": {
|
||||
"solver": "forceAtlas2Based",
|
||||
"forceAtlas2Based": {"gravitationalConstant": -60, "springLength": 120},
|
||||
"stabilization": {"iterations": 200}
|
||||
},
|
||||
"edges": {
|
||||
"arrows": {"to": {"enabled": true, "scaleFactor": 0.6}},
|
||||
"smooth": {"type": "curvedCW", "roundness": 0.15}
|
||||
},
|
||||
"nodes": {"font": {"color": "#e2e8f0", "size": 16}}
|
||||
}
|
||||
"""
|
||||
@@ -21,8 +21,6 @@ dependencies = [
|
||||
"prompt_toolkit>=3.0", # full-screen interactive TUI (terminal, input, resize)
|
||||
"plotly>=5.20", # interactive self-contained HTML charts
|
||||
"segno>=1.6", # pure-Python QR codes (channel share links)
|
||||
"pyvis>=0.3.2", # interactive HTML mesh graphs
|
||||
"networkx>=3.2", # graph model + path scoring
|
||||
"tomli>=2.0; python_version < '3.11'", # TOML config reader on 3.10
|
||||
"tomli-w>=1.0", # TOML writer for device-config backups
|
||||
]
|
||||
|
||||
@@ -1,101 +0,0 @@
|
||||
"""Unit tests for the offline LoRa link-budget calculator.
|
||||
|
||||
These pin the airtime/sensitivity math against textbook LoRa values and check the
|
||||
monotonic relationships the tool relies on, all without any hardware.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from meshterm.services import link_budget
|
||||
from meshterm.services.link_budget import RadioConfig
|
||||
|
||||
|
||||
def test_symbol_time_and_low_data_rate() -> None:
|
||||
"""Symbol time is 2**SF / BW; LDR auto-enables past the 16 ms threshold."""
|
||||
sf12 = RadioConfig(freq_mhz=915, bw_khz=125, sf=12)
|
||||
assert sf12.symbol_time_ms() == pytest.approx(32.768, abs=1e-3)
|
||||
assert sf12.low_data_rate_enabled() is True # 32.77 ms > 16 ms
|
||||
|
||||
sf7 = RadioConfig(freq_mhz=915, bw_khz=125, sf=7)
|
||||
assert sf7.symbol_time_ms() == pytest.approx(1.024, abs=1e-3)
|
||||
assert sf7.low_data_rate_enabled() is False
|
||||
|
||||
|
||||
def test_time_on_air_matches_semtech_reference() -> None:
|
||||
"""SF12/BW125/CR4-5/20-byte payload airtime matches the canonical ~1318.9 ms."""
|
||||
config = RadioConfig(freq_mhz=868, bw_khz=125, sf=12, cr_denom=5)
|
||||
toa = link_budget.time_on_air(config, payload_bytes=20)
|
||||
assert toa.total_ms == pytest.approx(1318.9, abs=1.0)
|
||||
assert toa.payload_symbols == 28
|
||||
assert toa.bitrate_bps > 0
|
||||
|
||||
|
||||
def test_time_on_air_grows_with_spreading_factor() -> None:
|
||||
"""Airtime increases monotonically with SF for a fixed payload."""
|
||||
durations = [
|
||||
link_budget.time_on_air(
|
||||
RadioConfig(freq_mhz=915, bw_khz=250, sf=sf), payload_bytes=32
|
||||
).total_ms
|
||||
for sf in range(7, 13)
|
||||
]
|
||||
assert durations == sorted(durations)
|
||||
assert all(b > a for a, b in zip(durations, durations[1:], strict=False))
|
||||
|
||||
|
||||
def test_receiver_sensitivity_formula() -> None:
|
||||
"""Sensitivity = -174 + 10log10(BW) + NF + SNR_limit(SF)."""
|
||||
config = RadioConfig(freq_mhz=915, bw_khz=125, sf=12)
|
||||
# -174 + 10*log10(125000) + 6 + (-20) ≈ -137.03 dBm
|
||||
assert link_budget.receiver_sensitivity(config) == pytest.approx(-137.0, abs=0.1)
|
||||
# A wider bandwidth raises (worsens) the noise floor.
|
||||
wide = RadioConfig(freq_mhz=915, bw_khz=500, sf=12)
|
||||
assert link_budget.receiver_sensitivity(wide) > link_budget.receiver_sensitivity(config)
|
||||
|
||||
|
||||
def test_duty_cycle_headroom() -> None:
|
||||
"""A 1 s packet at 1% duty allows 36 packets/hour and 100 s spacing."""
|
||||
duty = link_budget.duty_cycle(1000.0, limit_percent=1.0)
|
||||
assert duty.max_packets_per_hour == pytest.approx(36.0)
|
||||
assert duty.min_interval_s == pytest.approx(100.0)
|
||||
assert duty.dwell_ok is None # no dwell limit supplied
|
||||
|
||||
|
||||
def test_dwell_time_check() -> None:
|
||||
"""The dwell check flags packets longer than the regional max dwell time."""
|
||||
assert link_budget.duty_cycle(500.0, max_dwell_ms=400.0).dwell_ok is False
|
||||
assert link_budget.duty_cycle(300.0, max_dwell_ms=400.0).dwell_ok is True
|
||||
|
||||
|
||||
def test_range_estimate_responds_to_loss_and_exponent() -> None:
|
||||
"""Range grows with tolerable path loss and shrinks in a clutter-heavy model."""
|
||||
near = link_budget.free_space_range_km(120.0, 915.0, exponent=2.0)
|
||||
far = link_budget.free_space_range_km(140.0, 915.0, exponent=2.0)
|
||||
assert far > near
|
||||
# A higher path-loss exponent (more clutter) yields a shorter range for the same loss.
|
||||
urban = link_budget.free_space_range_km(140.0, 915.0, exponent=3.5)
|
||||
assert urban < far
|
||||
# Path loss below the 1 km free-space reference yields zero range, never negative.
|
||||
assert link_budget.free_space_range_km(10.0, 915.0, exponent=2.0) == 0.0
|
||||
|
||||
|
||||
def test_compute_link_budget_integration() -> None:
|
||||
"""A full budget ties the pieces together with a positive margin at a known loss."""
|
||||
config = RadioConfig(freq_mhz=915, bw_khz=250, sf=10, cr_denom=5)
|
||||
budget = link_budget.compute_link_budget(
|
||||
config,
|
||||
payload_bytes=32,
|
||||
tx_power_dbm=22,
|
||||
tx_gain_dbi=3,
|
||||
rx_gain_dbi=3,
|
||||
reference_path_loss_db=120.0,
|
||||
duty_limit_percent=1.0,
|
||||
max_dwell_ms=400.0,
|
||||
)
|
||||
# max path loss = EIRP(25) + rx_gain(3) - sensitivity
|
||||
expected_mpl = 22 + 3 + 3 - budget.sensitivity_dbm
|
||||
assert budget.max_path_loss_db == pytest.approx(expected_mpl)
|
||||
assert budget.link_margin_db == pytest.approx(expected_mpl - 120.0)
|
||||
assert budget.range_km > 0
|
||||
assert budget.duty.max_packets_per_hour > 0
|
||||
@@ -1,93 +0,0 @@
|
||||
"""Tests for link-quality regression detection against a rolling baseline."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timedelta
|
||||
|
||||
from meshterm.core.models import Hop, TraceResult, utcnow
|
||||
from meshterm.services import link_quality
|
||||
|
||||
_NOW = utcnow()
|
||||
|
||||
|
||||
def _trace(snr: float, age_s: int, *, success: bool = True, hop: str = "3d") -> TraceResult:
|
||||
"""Build a two-hop trace; bottleneck SNR is ``snr`` and it is ``age_s`` seconds old."""
|
||||
return TraceResult(
|
||||
target="Alice",
|
||||
success=success,
|
||||
hops=[Hop(0, hop, snr), Hop(1, None, snr + 1)] if success else [],
|
||||
timestamp=_NOW - timedelta(seconds=age_s),
|
||||
)
|
||||
|
||||
|
||||
def test_detects_snr_regression() -> None:
|
||||
"""A recent SNR drop past the threshold is flagged, with critical severity."""
|
||||
# Baseline (older) ~+8 dB, recent (newer) ~+2 dB: a 6 dB drop.
|
||||
baseline = [_trace(8.0, age_s=100 + i) for i in range(5)]
|
||||
recent = [_trace(2.0, age_s=i) for i in range(3)]
|
||||
report = link_quality.analyze_target("Alice", baseline + recent, recent_count=3)
|
||||
|
||||
assert report.status == "critical" # 6 dB drop ≥ 2× the 3 dB threshold
|
||||
snr_reg = next(c for c in report.regressions if c.metric == "min SNR (dB)")
|
||||
assert snr_reg.baseline == 8.0
|
||||
assert snr_reg.recent == 2.0
|
||||
assert snr_reg.delta == -6.0
|
||||
# The per-hop link also regressed.
|
||||
assert any(c.kind == "link" and c.regressed for c in report.regressions)
|
||||
|
||||
|
||||
def test_healthy_link_reports_ok() -> None:
|
||||
"""A steady link shows no regressions and an ok status."""
|
||||
traces = [_trace(7.5, age_s=i) for i in range(8)]
|
||||
report = link_quality.analyze_target("Alice", traces, recent_count=3)
|
||||
assert report.status == "ok"
|
||||
assert report.regressions == []
|
||||
assert report.changes # metrics were still evaluated
|
||||
|
||||
|
||||
def test_success_rate_regression() -> None:
|
||||
"""A jump in recent failures is flagged even when surviving traces look fine."""
|
||||
baseline = [_trace(7.0, age_s=100 + i) for i in range(5)]
|
||||
recent = [_trace(7.0, age_s=i, success=False) for i in range(3)]
|
||||
report = link_quality.analyze_target("Alice", baseline + recent, recent_count=3)
|
||||
|
||||
success_reg = next(c for c in report.regressions if c.metric == "success rate")
|
||||
assert success_reg.baseline == 1.0
|
||||
assert success_reg.recent == 0.0
|
||||
assert report.status == "critical"
|
||||
|
||||
|
||||
def test_insufficient_history() -> None:
|
||||
"""Too little baseline data yields an insufficient-data verdict, not a false alarm."""
|
||||
traces = [_trace(8.0, age_s=i) for i in range(3)] # only 3 total, < min baseline + recent
|
||||
report = link_quality.analyze_target("Alice", traces, recent_count=3, min_baseline=3)
|
||||
assert report.status == "insufficient-data"
|
||||
assert report.changes == []
|
||||
|
||||
|
||||
def test_links_only_compared_when_present_in_both_windows() -> None:
|
||||
"""A path that appears in only one window is not reported as a link regression."""
|
||||
# Baseline goes via hop 'aa'; recent via a different hop 'bb' — no shared link.
|
||||
baseline = [_trace(8.0, age_s=100 + i, hop="aa") for i in range(5)]
|
||||
recent = [_trace(8.0, age_s=i, hop="bb") for i in range(3)]
|
||||
report = link_quality.analyze_target("Alice", baseline + recent, recent_count=3)
|
||||
link_changes = [c for c in report.changes if c.kind == "link"]
|
||||
# Only the shared 'X → us' return links overlap; the 'us → aa'/'us → bb' legs don't.
|
||||
assert all("aa" not in c.subject or "bb" not in c.subject for c in link_changes)
|
||||
assert report.status == "ok"
|
||||
|
||||
|
||||
def test_resolver_names_link_subjects() -> None:
|
||||
"""A resolver renames hop hashes in link subjects for readable output."""
|
||||
baseline = [_trace(8.0, age_s=100 + i) for i in range(5)]
|
||||
recent = [_trace(2.0, age_s=i) for i in range(3)]
|
||||
report = link_quality.analyze_target(
|
||||
"Alice",
|
||||
baseline + recent,
|
||||
recent_count=3,
|
||||
resolve=lambda h: "Repeater" if h == "3d" else h,
|
||||
device_label="Me",
|
||||
)
|
||||
link_regs = [c for c in report.regressions if c.kind == "link"]
|
||||
assert any("Repeater" in c.subject for c in link_regs)
|
||||
assert any("Me" in c.subject for c in link_regs)
|
||||
@@ -126,47 +126,6 @@ def test_recent_traces_empty_target(repo: Repository) -> None:
|
||||
assert repo.recent_traces("NoSuchNode") == []
|
||||
|
||||
|
||||
# -- all_traces ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_all_traces_spans_targets(repo: Repository) -> None:
|
||||
"""all_traces returns traces across every target."""
|
||||
run = repo.start_run("trace", {})
|
||||
repo.record_trace(run, _make_trace("Alice", ("r", 1.0)))
|
||||
repo.record_trace(run, _make_trace("Bob", ("r", 2.0)))
|
||||
repo.record_trace(run, _make_trace("Alice", ("r", 3.0)))
|
||||
|
||||
got = repo.all_traces()
|
||||
assert len(got) == 3
|
||||
targets = {t.target for t in got}
|
||||
assert targets == {"Alice", "Bob"}
|
||||
|
||||
|
||||
def test_all_traces_newest_first(repo: Repository) -> None:
|
||||
"""all_traces returns traces in reverse insertion order."""
|
||||
run = repo.start_run("trace", {})
|
||||
repo.record_trace(run, _make_trace("A", ("h", 1.0)))
|
||||
repo.record_trace(run, _make_trace("B", ("h", 2.0)))
|
||||
repo.record_trace(run, _make_trace("A", ("h", 3.0)))
|
||||
|
||||
targets = [t.target for t in repo.all_traces()]
|
||||
assert targets == ["A", "B", "A"]
|
||||
|
||||
|
||||
def test_all_traces_respects_limit(repo: Repository) -> None:
|
||||
"""The limit parameter caps the cross-target result."""
|
||||
run = repo.start_run("trace", {})
|
||||
for _ in range(10):
|
||||
repo.record_trace(run, _make_trace("X", ("h", 1.0)))
|
||||
|
||||
assert len(repo.all_traces(limit=4)) == 4
|
||||
|
||||
|
||||
def test_all_traces_empty_db(repo: Repository) -> None:
|
||||
"""An empty database returns an empty list, not an error."""
|
||||
assert repo.all_traces() == []
|
||||
|
||||
|
||||
# -- traced_targets --------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
@@ -1,301 +0,0 @@
|
||||
"""Tests for route-stability aggregation and the pyvis renderer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
from meshterm.core.models import Hop, TraceResult
|
||||
from meshterm.services import route_stability
|
||||
from meshterm.services.route_stability import RouteGraph
|
||||
|
||||
|
||||
def _trace(*nodes: str, snr: float = 5.0) -> TraceResult:
|
||||
"""Build a successful trace whose forward path visits ``nodes`` then returns to us.
|
||||
|
||||
Each hop SNR is fixed; the final hash-less hop models the reply returning to us.
|
||||
"""
|
||||
hops = [Hop(i, node, snr) for i, node in enumerate(nodes)]
|
||||
hops.append(Hop(len(nodes), None, snr))
|
||||
return TraceResult(target=nodes[-1] if nodes else "x", success=True, hops=hops)
|
||||
|
||||
|
||||
# -- churn metrics ----------------------------------------------------------
|
||||
|
||||
|
||||
def test_stable_route_scores_one() -> None:
|
||||
"""A single route taken every time scores full stability and zero entropy."""
|
||||
traces = [_trace("3d", "f2") for _ in range(6)]
|
||||
graph = route_stability.build_route_graph(traces, target="f2")
|
||||
assert graph.total_routes == 6
|
||||
assert graph.distinct_routes == 1
|
||||
assert graph.stability == 1.0
|
||||
assert graph.churn_entropy == 0.0
|
||||
|
||||
|
||||
def test_flapping_routes_lower_stability_and_raise_entropy() -> None:
|
||||
"""An even split between two routes halves stability and gives 1 bit of entropy."""
|
||||
traces = [_trace("3d", "f2") for _ in range(3)] + [_trace("aa", "f2") for _ in range(3)]
|
||||
graph = route_stability.build_route_graph(traces, target="f2")
|
||||
assert graph.distinct_routes == 2
|
||||
assert graph.stability == 0.5
|
||||
assert graph.churn_entropy == 1.0 # two equally-likely routes
|
||||
|
||||
|
||||
def test_three_way_split_entropy() -> None:
|
||||
"""Three equally-likely routes give log2(3) ≈ 1.585 bits of entropy."""
|
||||
traces = (
|
||||
[_trace("a", "x") for _ in range(4)]
|
||||
+ [_trace("b", "x") for _ in range(4)]
|
||||
+ [_trace("c", "x") for _ in range(4)]
|
||||
)
|
||||
graph = route_stability.build_route_graph(traces, target="x")
|
||||
assert graph.distinct_routes == 3
|
||||
assert math.isclose(graph.churn_entropy, math.log2(3), rel_tol=1e-9)
|
||||
|
||||
|
||||
def test_stability_property_equals_dominant_share() -> None:
|
||||
"""The stability property is an alias for dominant_share."""
|
||||
graph = RouteGraph(target="x", dominant_share=0.75)
|
||||
assert graph.stability == 0.75
|
||||
|
||||
|
||||
# -- graph topology ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_links_aggregate_counts_and_self_node() -> None:
|
||||
"""Links carry traversal counts and our own device is marked is_self."""
|
||||
traces = [_trace("3d", "f2") for _ in range(4)]
|
||||
graph = route_stability.build_route_graph(traces, target="f2", device_label="us")
|
||||
by_pair = {(link.origin, link.destination): link for link in graph.links}
|
||||
assert by_pair[("us", "3d")].count == 4 # every trace starts us → 3d
|
||||
assert by_pair[("f2", "us")].count == 4 # and returns f2 → us
|
||||
self_nodes = [n for n in graph.nodes if n.is_self]
|
||||
assert len(self_nodes) == 1 and self_nodes[0].label == "us"
|
||||
|
||||
|
||||
def test_single_hop_direct_link() -> None:
|
||||
"""A one-hop trace (direct link, no repeaters) produces a two-edge diamond."""
|
||||
traces = [_trace("Alice") for _ in range(5)]
|
||||
graph = route_stability.build_route_graph(traces, target="Alice")
|
||||
assert graph.total_routes == 5
|
||||
assert graph.distinct_routes == 1
|
||||
by_pair = {(l.origin, l.destination): l for l in graph.links}
|
||||
assert ("us", "Alice") in by_pair
|
||||
assert ("Alice", "us") in by_pair
|
||||
|
||||
|
||||
def test_median_snr_on_links() -> None:
|
||||
"""Links carry the median SNR across all traversals."""
|
||||
traces = [
|
||||
_trace("relay", "dest", snr=v)
|
||||
for v in [2.0, 4.0, 6.0, 8.0, 10.0]
|
||||
]
|
||||
graph = route_stability.build_route_graph(traces, target="dest")
|
||||
by_pair = {(l.origin, l.destination): l for l in graph.links}
|
||||
assert by_pair[("us", "relay")].median_snr == 6.0 # median of 2,4,6,8,10
|
||||
|
||||
|
||||
def test_links_sorted_by_count_descending() -> None:
|
||||
"""Links come back sorted by traversal count, busiest first."""
|
||||
traces = [_trace("a", "x")] + [_trace("b", "x") for _ in range(5)]
|
||||
graph = route_stability.build_route_graph(traces, target="x")
|
||||
counts = [link.count for link in graph.links]
|
||||
assert counts == sorted(counts, reverse=True)
|
||||
|
||||
|
||||
def test_node_degree_reflects_link_count() -> None:
|
||||
"""Each node's degree equals the number of distinct links touching it."""
|
||||
# Two different routes: us→relay→dest→us and us→alt→dest→us
|
||||
# "relay" touches (us,relay) and (relay,dest) → degree 2
|
||||
# "dest" touches (relay,dest), (alt,dest), (dest,us) → degree 3
|
||||
traces = [_trace("relay", "dest") for _ in range(3)] + [_trace("alt", "dest")]
|
||||
graph = route_stability.build_route_graph(traces, target="dest")
|
||||
by_label = {n.label: n for n in graph.nodes}
|
||||
assert by_label["dest"].degree == 3
|
||||
assert by_label["relay"].degree == 2
|
||||
|
||||
|
||||
# -- resolver / labelling ---------------------------------------------------
|
||||
|
||||
|
||||
def test_resolver_relabels_nodes() -> None:
|
||||
"""A resolver renames hop hashes throughout the graph."""
|
||||
traces = [_trace("3d", "f2") for _ in range(3)]
|
||||
graph = route_stability.build_route_graph(
|
||||
traces, target="f2", resolve=lambda h: {"3d": "Repeater", "f2": "Alice"}.get(h, h)
|
||||
)
|
||||
labels = {n.label for n in graph.nodes}
|
||||
assert "Repeater" in labels
|
||||
assert "Alice" in labels
|
||||
|
||||
|
||||
def test_resolver_returning_none_keeps_original_label() -> None:
|
||||
"""When the resolver returns None for a hash, the original label is kept."""
|
||||
traces = [_trace("3d", "f2") for _ in range(2)]
|
||||
graph = route_stability.build_route_graph(
|
||||
traces, target="f2", resolve=lambda h: None
|
||||
)
|
||||
labels = {n.label for n in graph.nodes}
|
||||
assert "3d" in labels
|
||||
assert "f2" in labels
|
||||
|
||||
|
||||
def test_resolver_renames_self_device() -> None:
|
||||
"""When the resolver renames the device_label, the self node follows."""
|
||||
traces = [_trace("relay", "dest") for _ in range(2)]
|
||||
graph = route_stability.build_route_graph(
|
||||
traces, target="dest",
|
||||
resolve=lambda h: "MyDevice" if h == "us" else h,
|
||||
)
|
||||
self_nodes = [n for n in graph.nodes if n.is_self]
|
||||
assert len(self_nodes) == 1
|
||||
assert self_nodes[0].label == "MyDevice"
|
||||
|
||||
|
||||
# -- edge cases -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_empty_history_is_safe() -> None:
|
||||
"""Failed/empty traces yield an empty graph with zeroed metrics, no errors."""
|
||||
graph = route_stability.build_route_graph(
|
||||
[TraceResult(target="x", success=False)], target="x"
|
||||
)
|
||||
assert graph.total_routes == 0
|
||||
assert graph.stability == 0.0
|
||||
assert graph.links == []
|
||||
assert graph.nodes == []
|
||||
|
||||
|
||||
def test_completely_empty_trace_list() -> None:
|
||||
"""An empty list produces a valid zeroed graph."""
|
||||
graph = route_stability.build_route_graph([], target="x")
|
||||
assert graph.total_routes == 0
|
||||
assert graph.distinct_routes == 0
|
||||
assert graph.churn_entropy == 0.0
|
||||
|
||||
|
||||
def test_mixed_success_and_failure_traces() -> None:
|
||||
"""Failed traces are excluded from the graph; only successes contribute."""
|
||||
good = [_trace("relay", "dest") for _ in range(3)]
|
||||
bad = [TraceResult(target="dest", success=False) for _ in range(5)]
|
||||
graph = route_stability.build_route_graph(good + bad, target="dest")
|
||||
assert graph.total_routes == 3 # only the successful ones
|
||||
|
||||
|
||||
def test_multi_target_graph_without_target() -> None:
|
||||
"""A whole-mesh graph (target=None) merges traces across targets."""
|
||||
t1 = [_trace("relay", "Alice") for _ in range(3)]
|
||||
t2 = [_trace("relay", "Bob") for _ in range(2)]
|
||||
graph = route_stability.build_route_graph(t1 + t2, target=None)
|
||||
assert graph.target is None
|
||||
assert graph.total_routes == 5
|
||||
labels = {n.label for n in graph.nodes}
|
||||
assert "Alice" in labels
|
||||
assert "Bob" in labels
|
||||
|
||||
|
||||
# -- pyvis renderer ---------------------------------------------------------
|
||||
|
||||
|
||||
def test_render_route_graph_writes_html(tmp_path: Path) -> None:
|
||||
"""The pyvis renderer produces a self-contained HTML file."""
|
||||
from meshterm.viz.route_graph import render_route_graph
|
||||
|
||||
traces = [_trace("3d", "f2") for _ in range(3)] + [_trace("aa", "f2")]
|
||||
graph = route_stability.build_route_graph(traces, target="f2")
|
||||
out = render_route_graph(graph, tmp_path)
|
||||
assert out.exists()
|
||||
assert out.suffix == ".html"
|
||||
text = out.read_text(encoding="utf-8")
|
||||
assert "Route stability" in text # heading injected
|
||||
assert out.stat().st_size > 1000 # vis.js inlined
|
||||
|
||||
|
||||
def test_render_empty_graph_writes_valid_html(tmp_path: Path) -> None:
|
||||
"""An empty graph still produces a valid HTML file."""
|
||||
from meshterm.viz.route_graph import render_route_graph
|
||||
|
||||
graph = RouteGraph(target="nobody")
|
||||
out = render_route_graph(graph, tmp_path)
|
||||
assert out.exists()
|
||||
text = out.read_text(encoding="utf-8")
|
||||
assert "<body>" in text
|
||||
|
||||
|
||||
def test_render_creates_output_dir(tmp_path: Path) -> None:
|
||||
"""The renderer creates the output directory if it doesn't exist."""
|
||||
from meshterm.viz.route_graph import render_route_graph
|
||||
|
||||
nested = tmp_path / "a" / "b"
|
||||
graph = route_stability.build_route_graph([_trace("x")], target="x")
|
||||
out = render_route_graph(graph, nested)
|
||||
assert out.exists()
|
||||
|
||||
|
||||
def test_render_whole_mesh_filename(tmp_path: Path) -> None:
|
||||
"""Whole-mesh graphs use 'mesh' in the filename, not an empty slug."""
|
||||
from meshterm.viz.route_graph import render_route_graph
|
||||
|
||||
graph = route_stability.build_route_graph([_trace("x")], target=None)
|
||||
out = render_route_graph(graph, tmp_path)
|
||||
assert "mesh" in out.name
|
||||
|
||||
|
||||
# -- viz helpers -------------------------------------------------------------
|
||||
|
||||
|
||||
def test_snr_color_thresholds() -> None:
|
||||
"""SNR-to-colour mapping covers all four bands."""
|
||||
from meshterm.viz.route_graph import _snr_color
|
||||
|
||||
assert _snr_color(10.0) == "#4ade80" # strong
|
||||
assert _snr_color(5.0) == "#4ade80" # boundary: strong
|
||||
assert _snr_color(2.0) == "#facc15" # marginal
|
||||
assert _snr_color(0.0) == "#facc15" # boundary: marginal
|
||||
assert _snr_color(-4.0) == "#fb923c" # weak
|
||||
assert _snr_color(-8.0) == "#fb923c" # boundary: weak
|
||||
assert _snr_color(-15.0) == "#f87171" # very weak
|
||||
|
||||
|
||||
def test_slug_edge_cases() -> None:
|
||||
"""Slug handles special characters and pathological inputs."""
|
||||
from meshterm.viz.route_graph import _slug
|
||||
|
||||
assert _slug("Alice") == "alice"
|
||||
assert _slug("my node") == "my-node"
|
||||
assert _slug("a/b\\c") == "a-b-c"
|
||||
assert _slug("") == "graph" # empty → fallback
|
||||
assert _slug("!!!") == "graph" # all-special → fallback
|
||||
|
||||
|
||||
# -- tool panel / validator --------------------------------------------------
|
||||
|
||||
|
||||
def test_graph_panel_with_links() -> None:
|
||||
"""The Rich panel renders without error when there are links."""
|
||||
from meshterm.tools.route_map import _graph_panel
|
||||
|
||||
traces = [_trace("relay", "dest") for _ in range(3)]
|
||||
graph = route_stability.build_route_graph(traces, target="dest")
|
||||
panel = _graph_panel(graph)
|
||||
assert panel.title is not None
|
||||
|
||||
|
||||
def test_graph_panel_empty() -> None:
|
||||
"""The Rich panel renders without error on an empty graph."""
|
||||
from meshterm.tools.route_map import _graph_panel
|
||||
|
||||
graph = RouteGraph(target="nobody")
|
||||
panel = _graph_panel(graph)
|
||||
assert panel.title is not None
|
||||
|
||||
|
||||
def test_is_nonneg_int_validator() -> None:
|
||||
"""The questionary validator accepts zero/positive and rejects negative/non-int."""
|
||||
from meshterm.tools.route_map import _is_nonneg_int
|
||||
|
||||
assert _is_nonneg_int("0") is True
|
||||
assert _is_nonneg_int("5") is True
|
||||
assert isinstance(_is_nonneg_int("-1"), str)
|
||||
assert isinstance(_is_nonneg_int("abc"), str)
|
||||
Reference in new issue
Block a user