Files
tth 8306d91b48
ci / test (push) Failing after 1m29s
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 <anything but off>` 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.
2026-11-15 14:03:11 +01:00

254 lines
10 KiB
Python

"""What meshcore_prefs knows about each CLI pref of a meshcore-tth repeater -- no radio, unit-tested.
The firmware's `get` replies are free text, and several are not the bare value:
`get radio.silence` -> '> 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 <anything but off>` 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)"
)