From 0cec67dd1ff3026886276304287bb5c62f078e0c Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Sun, 21 Jun 2026 15:40:31 -0400 Subject: [PATCH] Add offline link-budget / airtime calculator tool Predict time-on-air, receiver sensitivity, max path loss, range, and duty-cycle/dwell headroom for a LoRa radio config with no radio attached. Radio params default to the connected device's config but every value is overridable; a fully specified invocation never opens the serial port. Co-Authored-By: Claude Opus 4.8 --- README.md | 1 + meshtools/services/link_budget.py | 334 ++++++++++++++++++++++++++++++ meshtools/tools/link_budget.py | 325 +++++++++++++++++++++++++++++ tests/test_link_budget.py | 101 +++++++++ 4 files changed, 761 insertions(+) create mode 100644 meshtools/services/link_budget.py create mode 100644 meshtools/tools/link_budget.py create mode 100644 tests/test_link_budget.py diff --git a/README.md b/README.md index fbbe263..f9719a2 100644 --- a/README.md +++ b/README.md @@ -17,6 +17,7 @@ turned into interactive HTML visualizations. | **Device discovery** | ✅ working | Enumerate serial devices, pick one interactively, and remember the last good default. | | **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. | | **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. | diff --git a/meshtools/services/link_budget.py b/meshtools/services/link_budget.py new file mode 100644 index 0000000..c32ab39 --- /dev/null +++ b/meshtools/services/link_budget.py @@ -0,0 +1,334 @@ +"""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 + ), + ) diff --git a/meshtools/tools/link_budget.py b/meshtools/tools/link_budget.py new file mode 100644 index 0000000..87ed83f --- /dev/null +++ b/meshtools/tools/link_budget.py @@ -0,0 +1,325 @@ +"""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 questionary +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 .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" + help = "Predict airtime, range, and duty-cycle headroom for a radio config (no radio needed)." + 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 questionary.text( + "Payload size (bytes):", default="32", validate=_is_pos_int + ).ask_async() + if payload is None: + return None + tx = await questionary.text( + "TX power (dBm):", + default=str(int(defaults.get("tx_power") or 22)), + validate=_is_number, + ).ask_async() + if tx is None: + return None + tx_gain = await questionary.text( + "TX antenna gain (dBi):", default="2", validate=_is_number + ).ask_async() + if tx_gain is None: + return None + rx_gain = await questionary.text( + "RX antenna gain (dBi):", default="2", validate=_is_number + ).ask_async() + if rx_gain is None: + return None + env = await questionary.select( + "Environment (path-loss model):", + choices=list(PATH_LOSS_EXPONENTS), + default="suburban", + ).ask_async() + if env is None: + return None + duty = await questionary.text( + "Duty-cycle limit (%):", default="1.0", validate=_is_number + ).ask_async() + 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.console.print(_radio_panel(config)) + ctx.console.print(_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." diff --git a/tests/test_link_budget.py b/tests/test_link_budget.py new file mode 100644 index 0000000..8c88368 --- /dev/null +++ b/tests/test_link_budget.py @@ -0,0 +1,101 @@ +"""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 meshtools.services import link_budget +from meshtools.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