The SPI radio listens for the preamble the mesh actually sends

MeshCore transmits a 32-symbol preamble up to SF8 (16 above), but the
node and the bridge configured the SX1262 for the library's fixed 12.
The chip waits for the sync word only about as long as the preamble it
expects, so it locked onto each packet, gave up, and locked on again
further along the same preamble - decoding a packet only when it
happened to catch the tail. On the uConsole that meant 0 of 5 detected
packets decoded after a send; with 32 symbols, 4 of 4.

The node now derives the preamble from the spreading factor as MeshCore
does, and re-sends it to the listening chip when Device config changes
the SF. preamble_length leaves the SPI wiring table (it was protocol,
never wiring) and is retired; the bridge defaults to the same rule.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Jean-Pierre MartineauandClaude Opus 5.5 committed 2026-09-24 03:12:52 -04:00
1 parent 9538bfedce
commit dee4674942
8 files changed
+149 -10

No files matched your search

+13 -3
View File
@@ -20,7 +20,7 @@ import os
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any
from typing import Any, ClassVar
if sys.version_info >= (3, 11):
import tomllib
@@ -93,7 +93,6 @@ class SpiWiring:
use_dio2_rf: Whether DIO2 drives the RF switch.
use_dio3_tcxo: Whether DIO3 powers a TCXO.
is_waveshare: The Waveshare HAT's wiring quirks, which the radio library knows.
preamble_length: LoRa preamble symbols.
python: An interpreter to run the node under, when the one MeshTerm would find
is not the one you want. Empty to let MeshTerm look.
"""
@@ -112,9 +111,14 @@ class SpiWiring:
use_dio2_rf: bool = True
use_dio3_tcxo: bool = True
is_waveshare: bool = False
preamble_length: int = 12
python: str = ""
#: Keys this table once took and must never take again under another meaning (see
#: :data:`meshterm.core.preferences.RETIRED`). ``preamble_length`` was never wiring: it is
#: protocol, and a fixed 12 against a mesh sending 32 is what left the node deaf to
#: most traffic; the node now derives it from the spreading factor as MeshCore does.
RETIRED: ClassVar[frozenset[str]] = frozenset({"preamble_length"})
@classmethod
def from_toml(cls, table: dict[str, Any]) -> SpiWiring:
"""Build the wiring from a ``[profiles.<name>.spi]`` table, defaults for the rest.
@@ -127,6 +131,12 @@ class SpiWiring:
ValueError: On an unknown key or a value of the wrong type.
"""
known = {f.name: f for f in cls.__dataclass_fields__.values()}
retired = sorted(set(table) & cls.RETIRED)
if retired:
raise ValueError(
f"{', '.join(retired)} is no longer a wiring key — the node sets the "
"preamble from the spreading factor, as MeshCore does; delete the line"
)
unknown = sorted(set(table) - set(known))
if unknown:
raise ValueError(f"unknown SPI wiring key(s): {', '.join(unknown)}")
+48
View File
@@ -223,6 +223,20 @@ def saved_channels(saved: Any) -> list[tuple[int, str, bytes]]:
# --- the node ------------------------------------------------------------------------------
def preamble_for_sf(spreading_factor: int) -> int:
"""The LoRa preamble, in symbols, MeshCore uses at a spreading factor: 32 up to SF8, else 16.
This is MeshCore's own rule (``RadioLibWrapper::preambleLengthForSF``), and the receiver
has to follow it, not only the transmitter. The SX1262 waits for the sync word only about
as long as the preamble it was told to expect, so a node listening for 12 symbols against
a mesh sending 32 locks on, gives up, and locks on again further along the same preamble
— and decodes a packet only when it happens to lock on near the end. That was the whole
of "the uConsole misses replies other radios hear": the preamble was a fixed 12, the
library's default, and at SF7 the mesh sends 32.
"""
return 32 if spreading_factor <= 8 else 16
def radio_kwargs(signature_params, wiring: dict, prefs: Any) -> dict: # noqa: ANN001
"""The ``SX1262Radio`` constructor arguments: the board's wiring plus the saved radio.
@@ -231,6 +245,7 @@ def radio_kwargs(signature_params, wiring: dict, prefs: Any) -> dict: # noqa: A
"""
wanted = dict(wiring)
wanted.update(
preamble_length=preamble_for_sf(prefs.spreading_factor),
frequency=prefs.frequency_hz,
bandwidth=prefs.bandwidth_hz,
spreading_factor=prefs.spreading_factor,
@@ -415,6 +430,28 @@ async def run_node(config: dict, report) -> int: # noqa: ANN001 - (dict) -> Non
return 0
def apply_preamble(radio: Any, symbols: int) -> None:
"""Give a running radio a new preamble length, for both what it sends and what it hears.
The driver reads ``preamble_length`` afresh for every transmission, but reception keeps
the packet parameters it was last given, so those are re-sent from standby and the chip
put back to listening.
"""
if getattr(radio, "preamble_length", symbols) == symbols:
return
radio.preamble_length = symbols
lora = getattr(radio, "lora", None)
if lora is None:
return
try:
lora.setStandby(lora.STANDBY_RC)
lora.setPacketParamsLoRa(symbols, lora.HEADER_EXPLICIT, 64, lora.CRC_ON, lora.IQ_STANDARD)
lora.request(lora.RX_CONTINUOUS)
log.info("preamble set to %d symbols", symbols)
except Exception as exc: # noqa: BLE001 - the next transmission sets it regardless
log.warning("could not apply the new preamble while listening: %s", exc)
def _persistent_companion(base: type, state: Path) -> type:
"""``CompanionRadio`` with its preferences written to ``prefs.json`` on every change.
@@ -423,6 +460,17 @@ def _persistent_companion(base: type, state: Path) -> type:
"""
class PersistentCompanion(base): # type: ignore[misc, valid-type]
def set_radio_params(self, freq_hz: int, bw_hz: int, sf: int, cr: int) -> bool:
"""Retune, and bring the preamble along when the spreading factor moves it.
The library retunes the modulation but leaves the packet parameters alone, and
the preamble is one of them (see :func:`preamble_for_sf`).
"""
ok = super().set_radio_params(freq_hz, bw_hz, sf, cr)
if ok:
apply_preamble(self._radio, preamble_for_sf(sf))
return ok
def _save_prefs(self) -> None:
try:
_write_json(state / "prefs.json", prefs_to_json(self.prefs))
-1
View File
@@ -474,7 +474,6 @@ async def start_node(wiring: SpiWiring, state: Path, *, node_name: str) -> NodeP
"use_dio2_rf": wiring.use_dio2_rf,
"use_dio3_tcxo": wiring.use_dio3_tcxo,
"is_waveshare": wiring.is_waveshare,
"preamble_length": wiring.preamble_length,
},
"seed": {"node_name": node_name, **DEFAULT_SEED},
}