From 6924ff7f45e3dc023c83b0c903780d3ea1fbabda Mon Sep 17 00:00:00 2001 From: Jean-Pierre Martineau Date: Fri, 4 Sep 2026 19:17:57 -0400 Subject: [PATCH] The presets are MeshCore's, not ours MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Every one of the region presets named a modulation no mesh runs any more, and two of them named a frequency nobody was ever on. MeshTerm's list was three regions on 250 kHz / SF11 — the shape MeshCore shipped with — plus two trade-off rows built on the EU frequency. Through 2025 most regions left that modulation for a narrow 62.5 kHz one, so the EU row is what MeshCore now calls "EU/UK (Deprecated)", the US row had the right frequency with the wrong modem (910.525 is SF7/BW62.5/CR5), and "AU / NZ 915" at 915.525 was not a preset at all: Australia is 915.800 wide, 916.575 narrow, 923.125 in SA/WA and QLD, and New Zealand is 917.375. Four parameters have to match for two nodes to hear each other, so a stale table is a radio staged onto an empty channel. The list is now MeshCore's own suggested settings, mirrored verbatim — names, order and values — from what its apps, the web flasher and config.meshcore.dev all read at api.meshcore.nz/api/v1/config. Twenty-three regions, including the two MeshCore still lists under its own "(Deprecated)" names, because nodes that never re-tuned are on them and picking one is how you go and listen. The names are spelled as MeshCore spells them so the row can be read against the phone app. Four regions also name a path-hash size, which the preset now stages alongside the radio fields as the firmware's mode (size - 1), exactly as MeshCore's own config GUI converts it. The rows moved to the two-lane menu shape — name, then the parameters in MeshCore's print order — which fits 53 columns where the old one-line title ran to 85, and the list opens on the preset the radio is already tuned to, staged values included, so picking a neighbour is a comparison rather than a guess. The trade-off pair is gone with them. They were ours rather than MeshCore's, they pinned a deprecated EU frequency onto whoever picked them, and the wide / mid / narrow choice they were reaching for is one the region list now makes properly per region. The simulator boots on the firmware's build defaults too (869.618, BW 62.5, SF8, CR5 per MeshCore's platformio.ini), rather than on the settings the EU mesh left behind. Co-Authored-By: Claude Opus 5 (1M context) --- meshterm/core/connection.py | 10 ++-- meshterm/core/device_config.py | 89 +++++++++++++++++++++++++++++----- meshterm/ui/config_editor.py | 32 ++++++------ tests/test_device_config.py | 56 +++++++++++++++++++-- tests/test_settings_store.py | 10 ++-- 5 files changed, 158 insertions(+), 39 deletions(-) diff --git a/meshterm/core/connection.py b/meshterm/core/connection.py index cdcef9e..a80f270 100644 --- a/meshterm/core/connection.py +++ b/meshterm/core/connection.py @@ -2755,9 +2755,13 @@ class MockDevice(Device): "telemetry_mode_loc": 0, "telemetry_mode_env": 0, "manual_add_contacts": False, - "radio_freq": 869.525, - "radio_bw": 250.0, - "radio_sf": 11, + # The firmware's own build defaults (MeshCore's platformio.ini: LORA_FREQ + # 869.618, BW 62.5, SF8; CR falls back to 5), so the simulator boots on the + # settings a freshly flashed companion does rather than on the 250 kHz / + # SF11 modulation the EU mesh left behind. + "radio_freq": 869.618, + "radio_bw": 62.5, + "radio_sf": 8, "radio_cr": 5, "simulated": True, } diff --git a/meshterm/core/device_config.py b/meshterm/core/device_config.py index b016e21..1d86e8b 100644 --- a/meshterm/core/device_config.py +++ b/meshterm/core/device_config.py @@ -345,42 +345,107 @@ class RadioPreset: """A named, standard set of radio parameters applied as one unit. Attributes: - name: Human-friendly preset name (region or trade-off). - help: One-line description of when to use it. + name: The preset's name, spelled exactly as MeshCore's own list spells it, so + this list can be read against the phone app or the web flasher. freq: Carrier frequency in MHz. bw: Channel bandwidth in kHz. sf: LoRa spreading factor. cr: LoRa coding-rate denominator (5-8 = 4/5-4/8). + path_hash_size: Per-hop path-hash size in bytes where the preset names one (a + few regions run 2-byte hashes); ``None`` leaves that setting where it is. """ name: str - help: str freq: float bw: float sf: int cr: int + path_hash_size: Optional[int] = None + + @property + def summary(self) -> str: + """The four parameters on one line, in the order MeshCore's own list prints.""" + return f"{self.freq:.3f} SF{self.sf} BW{self.bw:g} CR{self.cr}" def as_settings(self) -> dict[str, Any]: """Return this preset as a ``{setting_key: value}`` mapping for staging.""" - return { + values: dict[str, Any] = { "radio_freq": self.freq, "radio_bw": self.bw, "radio_sf": self.sf, "radio_cr": self.cr, } + if self.path_hash_size is not None: + # The firmware stores the *mode*, one less than the size it carries per hop + # (see _PATH_HASH_CHOICES); MeshCore's own config GUI converts it the same way. + values["path_hash_mode"] = self.path_hash_size - 1 + return values -# Standard MeshCore presets. The default modulation (250 kHz / SF11 / CR5) is shared -# across regions; the region presets differ only in the default channel frequency. The -# trade-off presets keep the EU frequency but trade airtime for range or speed. +# MeshCore's suggested radio settings, mirrored verbatim — names, order and values — from +# the list its apps, the web flasher and config.meshcore.dev all read at +# ``https://api.meshcore.nz/api/v1/config`` (``config.suggested_radio_settings.entries``), +# fetched 2026-09-04. The presets are community-maintained and they move: through 2025 +# most regions left the original 250 kHz / SF11 modulation for a "narrow" 62.5 kHz one, +# which is why MeshCore still lists the settings it superseded under its own +# "(Deprecated)" names — nodes that never re-tuned are still out there on them. +# +# Every node on a mesh must match all four parameters, so the only useful preset is the +# one the local mesh actually runs. A handful of regions also name a path-hash size, +# which the preset stages alongside the radio fields exactly as MeshCore's GUI does. RADIO_PRESETS: list[RadioPreset] = [ - RadioPreset("EU / UK 868", "MeshCore default for the 868 MHz band", 869.525, 250.0, 11, 5), - RadioPreset("US 915", "MeshCore default for the US 915 MHz band", 910.525, 250.0, 11, 5), - RadioPreset("AU / NZ 915", "MeshCore default for the AU/NZ 915 MHz band", 915.525, 250.0, 11, 5), - RadioPreset("Long range (slow)", "Narrow bandwidth + high SF: max range, low data rate", 869.525, 125.0, 12, 8), - RadioPreset("Fast (short range)", "Wide bandwidth + low SF: short range, low airtime", 869.525, 500.0, 7, 5), + RadioPreset("Australia", 915.800, 250.0, 10, 5), + RadioPreset("Australia (Narrow)", 916.575, 62.5, 7, 8), + RadioPreset("Australia (Mid)", 915.075, 125.0, 9, 5), + RadioPreset("Australia: SA, WA", 923.125, 62.5, 8, 8), + RadioPreset("Australia: QLD", 923.125, 62.5, 8, 5), + RadioPreset("Brazil", 923.125, 62.5, 8, 8), + RadioPreset("Costa Rica", 910.525, 125.0, 11, 5), + RadioPreset("EU/UK (Narrow)", 869.618, 62.5, 8, 8), + RadioPreset("EU/UK (Deprecated)", 869.525, 250.0, 11, 5), + RadioPreset("Czech Republic (Narrow)", 869.432, 62.5, 7, 5), + RadioPreset("EU 433MHz (Long Range)", 433.650, 250.0, 11, 5), + RadioPreset("EU 433MHz (Narrow)", 433.650, 62.5, 8, 8), + RadioPreset("Hungary", 869.618, 62.5, 7, 5, 2), + RadioPreset("Netherlands", 869.618, 62.5, 7, 5), + RadioPreset("New Zealand (Narrow)", 917.375, 62.5, 7, 5, 2), + RadioPreset("New Zealand (Gisborne)", 917.375, 250.0, 11, 5, 1), + RadioPreset("Portugal 433", 433.375, 62.5, 9, 6), + RadioPreset("Portugal 868", 869.618, 62.5, 7, 6), + RadioPreset("Slovakia", 869.618, 62.5, 7, 5, 2), + RadioPreset("Switzerland", 869.618, 62.5, 8, 8), + RadioPreset("USA/Canada (Recommended)", 910.525, 62.5, 7, 5), + RadioPreset("Vietnam (Narrow)", 920.250, 62.5, 8, 5), + RadioPreset("Vietnam (Deprecated)", 920.250, 250.0, 11, 5), ] +#: Frequencies are set in kHz steps, so a snapshot matches a preset within half of one. +_FREQ_TOLERANCE_MHZ = 0.0005 + + +def current_preset(snapshot: dict[str, Any]) -> Optional[RadioPreset]: + """Return the preset the radio is tuned to, or ``None`` where it matches none. + + Matched on the four radio parameters alone — the ones every node on the mesh has to + agree on — never on the path-hash size a few presets also carry, which is how + MeshCore's own config GUI reads "which of these am I on?". + + Args: + snapshot: A device snapshot (or one with staged values merged over it). + """ + for preset in RADIO_PRESETS: + freq, bw = snapshot.get("radio_freq"), snapshot.get("radio_bw") + if ( + isinstance(freq, (int, float)) + and isinstance(bw, (int, float)) + and abs(float(freq) - preset.freq) < _FREQ_TOLERANCE_MHZ + and float(bw) == preset.bw + and snapshot.get("radio_sf") == preset.sf + and snapshot.get("radio_cr") == preset.cr + ): + return preset + return None + # --- the registry ------------------------------------------------------------ diff --git a/meshterm/ui/config_editor.py b/meshterm/ui/config_editor.py index feb008b..226fdf0 100644 --- a/meshterm/ui/config_editor.py +++ b/meshterm/ui/config_editor.py @@ -185,7 +185,7 @@ async def edit_config(ctx: "AppContext") -> Optional[list[tuple]]: elif choice == _LOCATION: await _stage_location(ctx, snapshot, pending) elif choice == _PRESETS: - await _stage_preset(ctx, pending) + await _stage_preset(ctx, snapshot, pending) elif choice == _CUSTOM: await _stage_custom_var(ctx, custom, extra_ops) else: # a setting key @@ -327,7 +327,7 @@ def _menu_items( if category == "Radio": rows.append(( "Radio presets…", Text(), - "Apply a standard regional or trade-off config", _PRESETS, + "Stage MeshCore's settings for a region", _PRESETS, )) elif category == "Experimental": rows.append(( @@ -600,26 +600,30 @@ def _valid_coords(text: str) -> bool | str: return str(exc) -async def _stage_preset(ctx: "AppContext", pending: dict[str, Any]) -> None: - """Pick a standard radio preset and stage all of its fields for review/apply.""" - from ..core.device_config import RADIO_PRESETS +async def _stage_preset(ctx: "AppContext", snapshot: dict, pending: dict[str, Any]) -> None: + """Pick a MeshCore radio preset and stage every field it names for review/apply. - items: list = [ - Choice( - title=f"{p.name}: {p.freq} MHz, BW {p.bw}, SF{p.sf}, CR{p.cr} — {p.help}", - value=i, - ) - for i, p in enumerate(RADIO_PRESETS) - ] + The rows are MeshCore's own suggested settings (see + :data:`~meshterm.core.device_config.RADIO_PRESETS`), name in one lane and parameters + in the other, and the list opens on the preset the radio is already tuned to where + one matches — the "which of these am I on?" reading the phone app gives, so picking a + neighbour is a comparison rather than a guess. Staged values count: a preset picked + after a hand-edited frequency is read against what would be applied, not against what + the radio still holds. + """ + from ..core.device_config import RADIO_PRESETS, current_preset + + items = menu_rows([(p.name, p.summary, i) for i, p in enumerate(RADIO_PRESETS)]) + active = current_preset({**snapshot, **pending}) idx = await ctx.ui.select( "Radio presets", items, prompt="Stage a standard set of radio parameters:", + default=RADIO_PRESETS.index(active) if active is not None else None, ) if idx is None: return - preset = RADIO_PRESETS[idx] - pending.update(preset.as_settings()) + pending.update(RADIO_PRESETS[idx].as_settings()) async def _stage_custom_var( diff --git a/tests/test_device_config.py b/tests/test_device_config.py index 528de01..81b7325 100644 --- a/tests/test_device_config.py +++ b/tests/test_device_config.py @@ -16,6 +16,7 @@ from meshterm.core.device_config import ( RADIO_PRESETS, DeviceConfigError, build_snapshot, + current_preset, effective_maximum, format_value, get_spec, @@ -1033,12 +1034,57 @@ def test_radio_presets_map_to_radio_settings() -> None: assert RADIO_PRESETS, "expected at least one standard radio preset" for preset in RADIO_PRESETS: settings = preset.as_settings() - assert set(settings) == {"radio_freq", "radio_bw", "radio_sf", "radio_cr"} + assert {"radio_freq", "radio_bw", "radio_sf", "radio_cr"} <= set(settings) # Each value parses cleanly through its setting spec. for key, value in settings.items(): assert parse_value(get_spec(key), value) == value +def test_radio_presets_match_meshcore_list() -> None: + """Spot-check the presets against MeshCore's own suggested settings. + + The values are MeshCore's, not ours: a mesh only hears a node whose four radio + parameters match, so a drifted table is a radio that talks to nobody. These are the + ones a MeshTerm user is most likely to pick, including the two regions MeshCore now + marks deprecated (still listed, because nodes that never re-tuned are on them). + """ + by_name = {p.name: p for p in RADIO_PRESETS} + expected = { + "EU/UK (Narrow)": (869.618, 62.5, 8, 8), + "EU/UK (Deprecated)": (869.525, 250.0, 11, 5), + "USA/Canada (Recommended)": (910.525, 62.5, 7, 5), + "Australia": (915.800, 250.0, 10, 5), + "New Zealand (Narrow)": (917.375, 62.5, 7, 5), + } + for name, values in expected.items(): + preset = by_name[name] + assert (preset.freq, preset.bw, preset.sf, preset.cr) == values + # A region that names a path-hash size stages it as the firmware's mode (size - 1). + assert by_name["New Zealand (Narrow)"].as_settings()["path_hash_mode"] == 1 + assert "path_hash_mode" not in by_name["EU/UK (Narrow)"].as_settings() + + +def test_radio_preset_summary_reads_as_meshcore_prints_it() -> None: + """The row's parameter lane is MeshCore's own order, at MeshCore's precision.""" + by_name = {p.name: p for p in RADIO_PRESETS} + assert by_name["USA/Canada (Recommended)"].summary == "910.525 SF7 BW62.5 CR5" + assert by_name["Australia"].summary == "915.800 SF10 BW250 CR5" + + +async def test_current_preset_identifies_the_mock_radio() -> None: + """The mock boots on the firmware defaults, which are EU/UK (Narrow) but for CR.""" + snapshot = await build_snapshot(await _connected_mock()) + assert current_preset(snapshot) is None # CR5, where the EU preset asks CR8 + assert current_preset({**snapshot, "radio_cr": 8}).name == "EU/UK (Narrow)" + + +def test_current_preset_none_for_unmatched_radio() -> None: + """A hand-tuned radio matches no preset, and a missing field never crashes it.""" + assert current_preset({"radio_freq": 868.0, "radio_bw": 250.0, "radio_sf": 11, + "radio_cr": 5}) is None + assert current_preset({}) is None + + def test_get_spec_unknown_raises() -> None: """An unknown key produces a helpful error listing valid keys.""" with pytest.raises(DeviceConfigError, match="unknown setting"): @@ -1063,8 +1109,8 @@ async def test_apply_coupled_radio_field_preserves_others() -> None: await spec.apply(device, 9, await build_snapshot(device)) info = await device.get_self_info() assert info["radio_sf"] == 9 - assert info["radio_freq"] == 869.525 # unchanged - assert info["radio_bw"] == 250.0 + assert info["radio_freq"] == 869.618 # unchanged + assert info["radio_bw"] == 62.5 assert info["radio_cr"] == 5 @@ -1099,7 +1145,7 @@ async def test_backup_and_read_round_trip(tmp_path: Path) -> None: backup = read_backup(path) assert backup.settings["name"] == "Foo" - assert backup.settings["radio_sf"] == 11 + assert backup.settings["radio_sf"] == 8 assert backup.custom["exp"] == "1" assert backup.channels[0]["name"] == "Public" assert backup.channels[0]["secret"] == ("01" * 16) @@ -1119,7 +1165,7 @@ async def test_plan_restore_emits_only_differences(tmp_path: Path) -> None: assert ("set", "name", "Foo") in ops assert ("set_custom", "exp", "1") in ops - # Unchanged values (e.g. radio_sf 11 == 11) are not re-applied. + # Unchanged values (e.g. radio_sf 8 == 8) are not re-applied. assert "radio_sf" not in [op[1] for op in ops if op[0] == "set"] diff --git a/tests/test_settings_store.py b/tests/test_settings_store.py index a895cc9..f0d8a75 100644 --- a/tests/test_settings_store.py +++ b/tests/test_settings_store.py @@ -138,13 +138,13 @@ async def test_drift_reports_only_changed_settings(tmp_path: Path) -> None: """Drift lists remembered settings that differ from the device, in registry order.""" device, pubkey = await _mock_device() store = SettingsStore(tmp_path / "settings.json") - store.remember(pubkey, "radio_freq", 915.0) # device default is 869.525 — drifts + store.remember(pubkey, "radio_freq", 915.0) # device default is 869.618 — drifts store.remember(pubkey, "name", "MockCompanion") # equals the device default — no drift snapshot = await build_snapshot(device) drifted = settings_drift(store, pubkey, snapshot) assert [d.key for d in drifted] == ["radio_freq"] - assert drifted[0].remembered == 915.0 and drifted[0].current == 869.525 + assert drifted[0].remembered == 915.0 and drifted[0].current == 869.618 async def test_drift_empty_when_nothing_remembered(tmp_path: Path) -> None: @@ -184,7 +184,7 @@ async def test_restore_writes_remembered_values_including_coupled(tmp_path: Path assert after["name"] == "Ops-Node" assert after["radio_freq"] == 915.0 assert after["radio_sf"] == 12 - assert after["radio_bw"] == 250.0 # untouched radio field preserved by the coupled rebuild + assert after["radio_bw"] == 62.5 # untouched radio field preserved by the coupled rebuild # Idempotent: with the device now matching, there is nothing left to restore. assert settings_drift(store, pubkey, after) == [] @@ -193,13 +193,13 @@ async def test_adopt_updates_store_to_device_values(tmp_path: Path) -> None: """Adopt takes the device's current values as the new saved truth, clearing the drift.""" device, pubkey = await _mock_device() store = SettingsStore(tmp_path / "settings.json") - store.remember(pubkey, "radio_freq", 915.0) # differs from the device's 869.525 + store.remember(pubkey, "radio_freq", 915.0) # differs from the device's 869.618 snapshot = await build_snapshot(device) drifted = settings_drift(store, pubkey, snapshot) adopt(store, pubkey, snapshot, [d.key for d in drifted]) - assert store.settings(pubkey)["radio_freq"] == 869.525 # now matches the device + assert store.settings(pubkey)["radio_freq"] == 869.618 # now matches the device assert settings_drift(store, pubkey, snapshot) == []