From 8306d91b487cb9458cbfcc3d522d9185d74f1051 Mon Sep 17 00:00:00 2001 From: TeTeHacko Date: Sun, 15 Nov 2026 14:03:11 +0100 Subject: [PATCH] meshcore_prefs: a spec per known key -- range and step checked before sending, the value read out of replies that are not bare; gps and powersaving The prefs were a free dict compared as text with the `get` reply, so lint and sanity could not see that several keys never converge: - `get radio.silence` -> '30 min (now x1), quiet ...', `get batt.icon` -> 'on (level 3/5, ...)', `get dutycycle` -> '50.0%': a change on every run, then a failure after the `set`; - `advert.interval` is stored halved (25 reads back as 24, and the node takes only 0 or 60-240), `agc.reset.interval` in steps of 4; - `set repeat ` means ON, so `repeat: 0` turned it on; - lat/lon compared to 1e-3 (~100 m), so a smaller move never went out; - errors like 'ERR - ...', 'unknown config: ...', 'Invalid ...' did not match the expected reply and ended as a timeout after five resends. module_utils/meshcore_prefspec.py now holds kind, range, step, tolerance and a reply parser for every pref of the meshcore-tth CLI (CommonCLI.cpp, CommonRadioPrefs.cpp, NodeMaintenance.cpp, CommonGpsPrefs.cpp); the module refuses a value the node would refuse or alter before it sends anything, in check mode too. Unknown keys still go, compared as before, with a warning. radio.txstall (RAM only) and radio.rxps (compound) are refused with a reason. New keys that are plain commands in the firmware: gps (off/on/duty), gps.period, gps.firstfix and powersaving; gps.period goes first and conflicts with gps off/duty. Tests: replies as the firmware prints them and as a bench board and three repeaters answered; with MESHCORE_TTH_SRC set, a drift check that every key is still in the CLI sources. --- README.md | 18 +- plugins/module_utils/meshcore_plan.py | 4 - plugins/module_utils/meshcore_prefspec.py | 253 ++++++++++++++++++ plugins/modules/meshcore_prefs.py | 91 ++++--- .../module_utils/test_meshcore_prefspec.py | 183 +++++++++++++ 5 files changed, 511 insertions(+), 38 deletions(-) create mode 100644 plugins/module_utils/meshcore_prefspec.py create mode 100644 tests/unit/plugins/module_utils/test_meshcore_prefspec.py diff --git a/README.md b/README.md index c9960b8..07235d2 100644 --- a/README.md +++ b/README.md @@ -43,7 +43,7 @@ z AUR, jinde venv a `ansible_python_interpreter` na něj. | modul | co spravuje | firmware | |---|---|---| | `meshcore_acl` | admini repeateru (`setperm`), čte skutečné ACL binárním dotazem | MeshCore | -| `meshcore_prefs` | `get`/`set` klíčů; `freq`, `radio`, hesla a klíč odmítne | MeshCore | +| `meshcore_prefs` | `get`/`set` klíčů, typ, rozsah a krok známých klíčů ověří před odesláním; navíc `gps` (off/on/duty), `gps.period`, `gps.firstfix`, `powersaving`. `freq`, `radio`, hesla, klíč a ne-trvalé klíče odmítne | MeshCore (`gps duty`, `radio.silence`: meshcore-tth) | | `meshcore_region` | strom regionů, domovský region, default scope, `region save` | MeshCore 1.10+ | | `meshcore_fw_facts` | jen čte: verze z `ver` a odchylka hodin uzlu | MeshCore | | `meshcore_companion_acl` | "remote CLI" příznak kontaktů na companionu, přes jeho BLE | MeshCore 1.18+ | @@ -118,9 +118,19 @@ Admin heslo patří do ansible-vault (`vault_meshcore_admin_password`). - **Uložené prefs přebíjejí výchozí hodnoty buildu.** Jiný uzel z téže várky může mít jiné admin heslo; login pak projde jen jako host. -- **Jednotky advert intervalů:** `advert.interval` je v **minutách**, - `flood.advert.interval` v **hodinách** (3–168). Hodnotu mimo rozsah uzel - odmítne a modul selže — nikdy po něm nezůstane tiché `OK`. +- **Jednotky advert intervalů:** `advert.interval` je v **minutách** (0 nebo + 60–240, sudé — uzel ukládá polovinu, 25 by přečetl jako 24), + `flood.advert.interval` v **hodinách** (0 nebo 3–168). `meshcore_prefs` + takovou hodnotu odmítne dřív, než cokoli pošle. +- **Odpověď na `get` není vždycky holá hodnota:** `radio.silence` → + `30 min (now x1), quiet …`, `batt.icon` → `on (level 3/5, …)`, `dutycycle` → + `50.0%`. Známé klíče (`plugins/module_utils/meshcore_prefspec.py`, ze zdrojáků + CLI meshcore-tth) z ní hodnotu vyčtou; neznámý klíč modul porovná jako text + a varuje. `set repeat ` znamená na uzlu ON — modul proto + bere jen on/off/true/false. +- **`lat`/`lon` porovnává modul na ~1 m** (na uzlu jsou `float32`). Dřív to + bylo 0,001° (~100 m) a menší posun se nikdy nepropsal; zaokrouhlená hodnota + v inventáři teď uzel jednou přesune na ni. - **Heslo nikdy přes heredoc s rourou** (`echo heslo | python - < '> 30 min (now x1), quiet 0 min, stage 0', `get batt.icon` +-> '> on (level 3/5, 4100 mV, scale 3300..4200)', `get dutycycle` -> '> 50.0%'. +Compared as text they never equal the wanted value, so the module reported a +change on every run and failed after the `set`. And some values the node does +not keep as sent: `advert.interval` is stored halved (25 reads back as 24), +`agc.reset.interval` in steps of 4; `set repeat ` means ON. + +So every known key has a spec here: its kind, range and step -- checked BEFORE +anything is sent -- and how to read the value out of the reply. The sources are +src/helpers/CommonCLI.cpp, CommonRadioPrefs.cpp, NodeMaintenance.cpp and +CommonGpsPrefs.cpp of meshcore-tth; the tests feed the replies those print. + +A few keys are not `get`/`set` prefs in the firmware but plain commands +(`gps`, `gps period`, `gps firstfix`, `powersaving`); they carry their own +commands. A key not listed here is still sent, compared the generic way +(meshcore_plan.same_value), with a warning. +""" + +import re + +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import same_value + +# Prefs that can cut the node off, or are local-console only anyway: refused. +REFUSED = { + "freq": "can cut the node off -- change it on site", + "radio": "can cut the node off -- change it on site", + "bw": "can cut the node off -- change it on site", + "sf": "can cut the node off -- change it on site", + "cr": "can cut the node off -- change it on site", + "prv.key": "local console only", + "password": "rotate it with the password command, not as a pref", + "guest.password": "a secret; `get` would put it into the log", + "radio.txstall": "RAM only: RADIO_TXSTALL_MIN again after every boot, nothing to converge", + "radio.rxps": "several parameters in one reply; not supported declaratively", +} + +ON = ("on", "true", "yes", "1") +OFF = ("off", "false", "no", "0") + +# kind: bool | int | float | enum | text +# lo/hi: range; zero: 0 is allowed outside it ("off"); step: the node keeps +# multiples only; tol: float tolerance; off_is_zero: a reply "off" reads as 0 +# get/set: own commands ({v} = value) for keys that are not `get`/`set` prefs; +# order: lower goes first (`gps period` switches GPS on, so before `gps`) +SPECS = { + "allow.read.only": {"kind": "bool"}, + "repeat": {"kind": "bool"}, + "cad": {"kind": "bool"}, + "radio.rxgain": {"kind": "bool"}, + "batt.icon": {"kind": "bool"}, # reply 'on (level 3/5, ...)' + "bridge.enabled": {"kind": "bool"}, + "advert.interval": {"kind": "int", "lo": 60, "hi": 240, "zero": True, "step": 2, "unit": "minutes"}, + "flood.advert.interval": {"kind": "int", "lo": 3, "hi": 168, "zero": True, "unit": "hours"}, + "flood.max": {"kind": "int", "lo": 0, "hi": 64}, + "flood.max.unscoped": {"kind": "int", "lo": 0, "hi": 64}, + "flood.max.advert": {"kind": "int", "lo": 0, "hi": 64}, + "path.hash.mode": {"kind": "int", "lo": 0, "hi": 2}, + "agc.reset.interval": {"kind": "int", "lo": 0, "hi": 1020, "step": 4, "unit": "seconds"}, + "multi.acks": {"kind": "int", "lo": 0, "hi": 255}, + "int.thresh": {"kind": "int", "lo": 0, "hi": 255}, + "tx": {"kind": "int", "lo": -9, "hi": 30, "unit": "dBm"}, + "batt.icon.lo": {"kind": "int", "lo": 0, "hi": 10000, "unit": "mV"}, + "batt.icon.hi": {"kind": "int", "lo": 0, "hi": 10000, "unit": "mV"}, + "bridge.delay": {"kind": "int", "lo": 0, "hi": 10000, "unit": "ms"}, + "bridge.baud": {"kind": "int", "lo": 9600, "hi": 115200}, + "bridge.channel": {"kind": "int", "lo": 1, "hi": 14}, + # reply '> 30 min (now x1), quiet 0 min, stage 0' or '> off' + "radio.silence": {"kind": "int", "lo": 0, "hi": 1440, "off_is_zero": True, "unit": "minutes"}, + "af": {"kind": "float", "lo": 0, "hi": 9}, + "dutycycle": {"kind": "float", "lo": 1, "hi": 100, "tol": 0.06}, # reply '> 50.0%' + "rxdelay": {"kind": "float", "lo": 0, "hi": 20}, + "txdelay": {"kind": "float", "lo": 0, "hi": 2}, + "direct.txdelay": {"kind": "float", "lo": 0, "hi": 2}, + "adc.multiplier": {"kind": "float", "lo": 0, "hi": 100}, + # float32 on the node: ~4e-6 degree at 50 N, so 1e-5 (about a metre) + "lat": {"kind": "float", "lo": -90, "hi": 90, "tol": 1e-5}, + "lon": {"kind": "float", "lo": -180, "hi": 180, "tol": 1e-5}, + "advert.loc": {"kind": "enum", "choices": ("none", "prefs", "share")}, + "loop.detect": {"kind": "enum", "choices": ("off", "minimal", "moderate", "strict")}, + "bridge.source": {"kind": "enum", "choices": ("logTx", "logRx")}, + "name": {"kind": "text", "max": 31}, + "owner.info": {"kind": "text", "max": 119}, # '|' = newline on the node + # ── plain commands, not get/set prefs ────────────────────────────────── + # `gps` reply: '> duty, asleep, fix, 6 sats', '> on, active, ...', '> off, ...'; + # firmware before 12. 11. 2026 prints duty without the '> ' + "gps": {"kind": "enum", "choices": ("off", "on", "duty"), "get": "gps", "set": "gps {v}", "order": 1}, + # setting a period turns GPS on (CommonGpsPrefs), `gps duty` resets it to 0 + "gps.period": { + "kind": "int", + "lo": 0, + "hi": 604800, + "unit": "seconds", + "get": "gps period", + "set": "gps period {v}", + "order": 0, + }, + "gps.firstfix": { + "kind": "int", + "lo": 0, + "hi": 86400, + "unit": "seconds", + "get": "gps firstfix", + "set": "gps firstfix {v}", + "order": 0, + }, + # reply 'on' / 'off' without '> '; set -> 'on - Immediate effect' / 'off' + "powersaving": {"kind": "bool", "get": "powersaving", "set": "powersaving {v}"}, +} + +# A `get` reply: the value, '> value', or an error the firmware prints. +GET_REPLY = r"^(>|on\b|off\b|duty\b|Err|ERR|\?\?|unknown|Invalid)" +# A `set` reply. Not just OK: the node also answers 'ERR - minutes 0..1440', +# 'Error, max 64', 'unknown config: x', 'Invalid extra SF config', 'on - ...'. +SET_REPLY = r"^(OK|on\b|off\b|Err|ERR|\?|unknown|Invalid|Board|Bridge)" + +NUMBER = re.compile(r"-?\d+(?:\.\d+)?") + + +class PrefError(ValueError): + pass + + +def spec(key): + return SPECS.get(key) + + +def order(keys): + """Keys in the order to set them (`gps period` before `gps`).""" + return sorted(keys, key=lambda k: ((SPECS.get(k) or {}).get("order", 5), k)) + + +def _as_bool(key, want): + w = str(want).strip().lower() if not isinstance(want, bool) else ("on" if want else "off") + if w in ON: + return "on" + if w in OFF: + return "off" + raise PrefError(f"{key}: {want!r} is not on/off") + + +def wanted(key, want): + """The value as the CLI takes it, or PrefError when the node would refuse or alter it.""" + if key in REFUSED: + raise PrefError(f"{key}: refused -- {REFUSED[key]}") + s = SPECS.get(key) + if s is None: + if isinstance(want, bool): + return "on" if want else "off" + return str(want) + kind = s["kind"] + if kind == "bool": + return _as_bool(key, want) + if kind == "enum": + w = str(want).strip() + if w not in s["choices"]: + raise PrefError(f"{key}: {want!r} is not one of {', '.join(s['choices'])}") + return w + if kind == "text": + w = str(want) + if len(w.encode()) > s["max"]: + raise PrefError(f"{key}: longer than {s['max']} B, the node would cut it") + return w + if isinstance(want, bool): + raise PrefError(f"{key}: {want!r} is not a number") + if kind == "int" and s.get("off_is_zero") and str(want).strip().lower() == "off": + want = 0 + try: + num = float(want) + except (TypeError, ValueError): + raise PrefError(f"{key}: {want!r} is not a number") from None + unit = f" {s['unit']}" if "unit" in s else "" + if kind == "int": + if num != int(num): + raise PrefError(f"{key}: {want!r} is not a whole number") + num = int(num) + if not (s.get("zero") and num == 0) and not s["lo"] <= num <= s["hi"]: + zero = "0 or " if s.get("zero") else "" + raise PrefError(f"{key}: {want}{unit} is out of range ({zero}{s['lo']}..{s['hi']}{unit})") + if s.get("step") and num % s["step"]: + raise PrefError(f"{key}: {want}{unit} -- the node keeps multiples of {s['step']} only") + return str(num) + + +ERROR_REPLY = re.compile(r"^(Err|ERR|\?\?|unknown|Invalid)") + + +def is_error(reply): + """'??: radio.silence' (a firmware without the key), 'Error: unsupported', ...""" + return bool(ERROR_REPLY.match(reply.strip())) + + +def reading(key, reply): + """The value out of a `get` reply (without the '> '), as `wanted` would spell it; None if unreadable.""" + text = reply.strip() + if text.startswith(">"): + text = text[1:].strip() + s = SPECS.get(key) + if s is None: + return text + kind = s["kind"] + word = re.split(r"[\s,(]", text, maxsplit=1)[0] if text else "" + if kind == "bool": + return word.lower() if word.lower() in ("on", "off") else None + if kind == "enum": + return word if word in s["choices"] else None + if kind == "text": + return text + if s.get("off_is_zero") and word.lower() == "off": + return "0" + m = NUMBER.match(text) + if not m: + return None + return str(int(float(m.group(0)))) if kind == "int" else m.group(0) + + +def same(key, current, want): + """current: reading() of the reply; want: wanted().""" + s = SPECS.get(key) + if current is None: + return False + if s is None: + return same_value(current, want) + if s["kind"] == "float": + return abs(float(current) - float(want)) <= s.get("tol", 1e-3) + return current == want + + +def get_cmd(key): + return (SPECS.get(key) or {}).get("get", f"get {key}") + + +def set_cmd(key, value): + s = SPECS.get(key) or {} + return s["set"].format(v=value) if "set" in s else f"set {key} {value}" + + +def set_ok(key, value, reply): + """Did the node take it? OK, or for `powersaving` the new state ('on - ...', 'off').""" + if reply.startswith("OK"): + return True + return key == "powersaving" and reply.split()[:1] == [value] + + +def check_combination(prefs): + """Conflicts between keys the node would resolve on its own, silently.""" + gps = prefs.get("gps") + if gps in ("off", "duty") and "gps.period" in prefs and prefs["gps.period"] != "0": + raise PrefError( + f"gps.period {prefs['gps.period']}: it switches GPS on -- with gps {gps} leave it out (duty = 0)" + ) diff --git a/plugins/modules/meshcore_prefs.py b/plugins/modules/meshcore_prefs.py index be3fd45..cbd8b71 100644 --- a/plugins/modules/meshcore_prefs.py +++ b/plugins/modules/meshcore_prefs.py @@ -5,14 +5,23 @@ module: meshcore_prefs short_description: CLI prefs (`get`/`set`) of a MeshCore repeater, over RF author: TeTeHacko (@TeTeHacko) description: - - For every key, `get `; when it differs from the wanted value, - `set ` and `get` again to prove it took. Numbers compare - numerically, on/off/true/false/1/0 as booleans. - - Refuses keys that can cut the node off or are local-console only - (freq, radio, bw/sf/cr, prv.key, password, guest.password). - - Units are the firmware's, `advert.interval` is MINUTES, `flood.advert.interval` - HOURS (3-168). A value out of range is rejected by the node and the module - fails -- it never leaves a silent `OK` behind. + - For every key, read the value; when it differs from the wanted value, set it + and read it again to prove it took. + - Known keys (module_utils/meshcore_prefspec.py, from the meshcore-tth CLI) are + checked BEFORE anything is sent -- kind, range, step -- so a value the node + would refuse or keep altered (C(advert.interval) is stored halved, C(agc.reset.interval) + in steps of 4) fails the task instead of leaving a change behind on every run. + The value is read out of the reply, which is not always bare + ('30 min (now x1), quiet ...', 'on (level 3/5, ...)', '50.0%'). + - "Besides the get/set prefs: C(gps) (off/on/duty), C(gps.period), C(gps.firstfix) + (seconds) and C(powersaving) (on/off), which the firmware has as plain commands." + - A key not known there is sent anyway and compared as text, numbers numerically, + on/off/true/false/1/0 as booleans -- with a warning. + - Refuses keys that can cut the node off, are local-console only, secret, or + not persistent (freq, radio, bw/sf/cr, prv.key, password, guest.password, + radio.txstall, radio.rxps). + - Units are the firmware's, C(advert.interval) is MINUTES (0 or 60-240, even), + C(flood.advert.interval) HOURS (0 or 3-168), C(radio.silence) minutes (0 = off). options: transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true} target: {description: Full 64-hex pubkey of the repeater., type: str, required: true} @@ -33,29 +42,43 @@ EXAMPLES = r""" path.hash.mode: 1 advert.interval: 0 flood.advert.interval: 47 + +- name: GPS only around clock syncs, MCU sleep, reboot a receiver deaf for 30 min + tth.meshcore.meshcore_prefs: + transport: {type: tcp, host: 127.0.0.1, port: 5000} + target: "{{ mc_target }}" + password: "{{ vault_meshcore_admin_password }}" + prefs: + gps: duty + powersaving: true + radio.silence: 30 """ from ansible.module_utils.basic import AnsibleModule, missing_required_lib +from ansible_collections.tth.meshcore.plugins.module_utils import meshcore_prefspec as spec from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run -from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import DANGEROUS_PREFS, same_value -def as_cli(value): - if isinstance(value, bool): - return "on" if value else "off" - return str(value) +async def read(link, key): + """The value as meshcore_prefspec.reading spells it; LinkError when the node cannot say.""" + reply = await link.cli(spec.get_cmd(key), spec.GET_REPLY) + if spec.is_error(reply): + raise LinkError(f"`{spec.get_cmd(key)}`: {reply} -- does this firmware have it?") + value = spec.reading(key, reply) + if value is None: + raise LinkError(f"`{spec.get_cmd(key)}`: cannot read a {spec.spec(key)['kind']} out of {reply!r}") + return value -async def work(module, link): - prefs = module.params["prefs"] +async def work(module, link, want): await link.open() try: await link.login() before, changes = {}, {} - for key, want in prefs.items(): - before[key] = await link.get(key) - if not same_value(before[key], as_cli(want)): - changes[key] = as_cli(want) + for key in spec.order(want): + before[key] = await read(link, key) + if not spec.same(key, before[key], want[key]): + changes[key] = want[key] result = { "changed": bool(changes), "set": changes, @@ -66,13 +89,15 @@ async def work(module, link): } if module.check_mode or not changes: return result - for key, value in changes.items(): - reply = await link.cli(f"set {key} {value}", r"^(OK|Err|\?)") - if not reply.startswith("OK"): - raise LinkError(f"`set {key} {value}`: {reply}") - now = await link.get(key) - if not same_value(now, value): - raise LinkError(f"`set {key} {value}` answered OK but `get` reads {now!r}") + for key in spec.order(changes): + value = changes[key] + cmd = spec.set_cmd(key, value) + reply = await link.cli(cmd, spec.SET_REPLY) + if not spec.set_ok(key, value, reply): + raise LinkError(f"`{cmd}`: {reply}") + now = await read(link, key) + if not spec.same(key, now, value): + raise LinkError(f"`{cmd}` answered {reply!r} but it reads {now!r}") return result finally: await link.close() @@ -90,12 +115,18 @@ def main(): ) if not HAS_MESHCORE: module.fail_json(msg=missing_required_lib("meshcore")) - bad = sorted(set(module.params["prefs"]) & DANGEROUS_PREFS) - if bad: - module.fail_json(msg=f"refusing prefs that can cut the node off (change them on site): {bad}") + # checked before anything is sent, in check mode too + try: + want = {k: spec.wanted(k, v) for k, v in module.params["prefs"].items()} + spec.check_combination(want) + except spec.PrefError as e: + module.fail_json(msg=str(e)) + unknown = sorted(k for k in want if spec.spec(k) is None) + if unknown: + module.warn(f"prefs not known to this collection, compared as text: {unknown}") link = Link(module.params["transport"], module.params["target"], module.params["password"]) try: - result = run(work(module, link)) + result = run(work(module, link, want)) except LinkError as e: module.fail_json(msg=str(e), log=link.log) module.exit_json(log=link.log, **result) diff --git a/tests/unit/plugins/module_utils/test_meshcore_prefspec.py b/tests/unit/plugins/module_utils/test_meshcore_prefspec.py new file mode 100644 index 0000000..56c69e5 --- /dev/null +++ b/tests/unit/plugins/module_utils/test_meshcore_prefspec.py @@ -0,0 +1,183 @@ +"""Unit tests for the pref specs. Replies as the firmware prints them (meshcore-tth +CommonCLI.cpp, CommonRadioPrefs.cpp, NodeMaintenance.cpp, CommonGpsPrefs.cpp), the +`gps` lines as three masts answered on 15. 11. 2026.""" + +import pytest +from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_prefspec import ( + PrefError, + check_combination, + is_error, + order, + reading, + same, + set_cmd, + set_ok, + wanted, +) + + +@pytest.mark.parametrize( + "key, reply, value", + [ + ("radio.silence", "> 30 min (now x1), quiet 0 min, stage 0", "30"), + ("radio.silence", "> off", "0"), + ("radio.silence", "> 25 min (now x1), quiet 1367 min, stage 0", "25"), # bench XIAO 15. 11. + ("batt.icon", "> on (level 3/5, 4100 mV, scale 3300..4200)", "on"), + ("batt.icon", "> on (omitted, name too long)", "on"), + ("batt.icon", "> off", "off"), + ("dutycycle", "> 50.0%", "50.0"), + ("repeat", "> on", "on"), + ("advert.interval", "> 120", "120"), + ("agc.reset.interval", "> 60", "60"), + ("af", "> 1.0", "1.0"), + ("lat", "> 50.548099", "50.548099"), + ("loop.detect", "> moderate", "moderate"), + ("owner.info", "> tth|rfa.cz", "tth|rfa.cz"), + ("gps", "> duty, asleep, fix, 6 sats", "duty"), + ("gps", "duty, asleep, no fix, 0 sats", "duty"), # firmware before 12. 11. 2026 + ("gps", "> on, active, 7 sats 12s ago, continuous", "on"), + ("gps", "> off, periodic (3600s)", "off"), + ("gps.period", "> 0 (continuous)", "0"), + ("gps.firstfix", "> 3600", "3600"), + ("gps.firstfix", "> 0 (no limit)", "0"), + ("powersaving", "on", "on"), + ("unknown.key", "> whatever 1", "whatever 1"), + ], +) +def test_reading(key, reply, value): + assert reading(key, reply) == value + + +def test_reading_unreadable(): + # an older firmware answers `gps period` with the `gps` line + assert reading("gps.period", "duty, asleep, no fix, 0 sats") is None + + +@pytest.mark.parametrize( + "reply", + [ + "??: radio.silence", + "Error: unsupported", + "ERROR: Power management not supported", + "Error, gps provider not found", # a board without GPS + "unknown config: nonsense 1", + ], +) +def test_error_replies(reply): + assert is_error(reply) + + +@pytest.mark.parametrize( + "key, want, cli", + [ + ("repeat", True, "on"), + ("repeat", "off", "off"), + ("repeat", 0, "off"), # `set repeat 0` would mean ON on the node + ("powersaving", "yes", "on"), + ("advert.interval", 0, "0"), + ("advert.interval", 120, "120"), + ("flood.advert.interval", 47, "47"), + ("agc.reset.interval", 60, "60"), + ("radio.silence", "off", "0"), + ("radio.silence", 30, "30"), + ("lat", 50.5481, "50.5481"), + ("gps", "duty", "duty"), + ("unknown.key", True, "on"), + ], +) +def test_wanted(key, want, cli): + assert wanted(key, want) == cli + + +@pytest.mark.parametrize( + "key, want, why", + [ + ("advert.interval", 25, "range"), # 0 or 60..240 + ("advert.interval", 121, "multiples of 2"), # stored halved + ("agc.reset.interval", 10, "multiples of 4"), + ("flood.advert.interval", 2, "range"), + ("flood.advert.interval", 200, "range"), + ("path.hash.mode", 3, "range"), + ("radio.silence", 2000, "range"), + ("repeat", "maybe", "on/off"), + ("gps", "auto", "one of"), + ("tx", "loud", "not a number"), + ("tx", True, "not a number"), + ("flood.max", 1.5, "whole number"), + ("freq", 869.432, "refused"), + ("radio.txstall", 15, "RAM only"), + ("guest.password", "x", "refused"), + ("name", "x" * 40, "longer"), + ], +) +def test_wanted_refuses(key, want, why): + with pytest.raises(PrefError, match=why): + wanted(key, want) + + +@pytest.mark.parametrize( + "key, current, want, result", + [ + ("radio.silence", "30", "30", True), + ("radio.silence", "0", "30", False), + ("dutycycle", "33.3", "33.33", True), + ("lat", "50.548099", "50.5481", True), + ("lat", "50.5482", "50.5481", False), # ~11 m: the old 1e-3 hid it + ("batt.icon", "on", "on", True), + ("unknown.key", "869.4320068", "869.432", True), + ("repeat", None, "on", False), + ], +) +def test_same(key, current, want, result): + assert same(key, current, want) is result + + +def test_commands_and_order(): + assert set_cmd("gps", "duty") == "gps duty" + assert set_cmd("gps.period", "0") == "gps period 0" + assert set_cmd("radio.silence", "30") == "set radio.silence 30" + assert order(["repeat", "gps", "gps.period"]) == ["gps.period", "gps", "repeat"] + + +@pytest.mark.parametrize( + "key, value, reply, ok", + [ + ("repeat", "on", "OK - repeat is now ON", True), + ("radio.silence", "30", "ERR - minutes 0..1440 (0/off = disabled)", False), + ("powersaving", "on", "on - After 2 minutes", True), + ("powersaving", "off", "off", True), + ("powersaving", "on", "Board not supported", False), + ("flood.max", "70", "Error, max 64", False), + ], +) +def test_set_ok(key, value, reply, ok): + assert set_ok(key, value, reply) is ok + + +def test_gps_period_conflicts_with_duty(): + with pytest.raises(PrefError, match="switches GPS on"): + check_combination({"gps": "duty", "gps.period": "3600"}) + check_combination({"gps": "on", "gps.period": "3600"}) + check_combination({"gps": "duty", "gps.period": "0"}) + + +def test_every_spec_is_in_the_firmware(): + """Drift check against a meshcore-tth checkout (MESHCORE_TTH_SRC=): every + known key's get and set must appear in the CLI sources. Skipped without one.""" + import os + import pathlib + + from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_prefspec import SPECS, get_cmd + + root = os.environ.get("MESHCORE_TTH_SRC") + if not root: + pytest.skip("MESHCORE_TTH_SRC not set") + helpers = pathlib.Path(root, "src", "helpers") + src = "".join(p.read_text(errors="replace") for p in helpers.glob("*.cpp")) + missing = [] + for key, s in SPECS.items(): + if "get" in s: # plain commands: both of them + missing += [w for w in (get_cmd(key), s["set"].split(" {v}")[0]) if f'"{w}' not in src] + elif f'"{key}' not in src and f'"get {key}' not in src: # handleGetCmd matches the bare key + missing.append(key) + assert not missing, f"not in {helpers}: {missing}"