ci / test (push) Failing after 1m29s
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.
276 lines
9.9 KiB
Python
276 lines
9.9 KiB
Python
"""Pure planning logic of the tth.meshcore modules -- no radio, unit-tested."""
|
|
|
|
import re
|
|
|
|
PERM_ADMIN = 3
|
|
|
|
|
|
# ── ACL ──────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def plan_acl(current, desired, exclusive=True, keep=()):
|
|
"""current: {prefix12: perm} as the repeater reports it (6-byte prefixes).
|
|
desired: [64-hex pubkey]. keep: pubkeys that must never be removed.
|
|
|
|
-> (add, remove): add = full pubkeys to setperm 3 (missing or not admin),
|
|
remove = 12-hex prefixes to setperm 0 (only when exclusive).
|
|
"""
|
|
want = {pk.lower()[:12]: pk.lower() for pk in desired}
|
|
add = [full for pfx, full in want.items() if current.get(pfx) != PERM_ADMIN]
|
|
keep_pfx = {pk.lower()[:12] for pk in keep}
|
|
remove = [pfx for pfx in current if exclusive and pfx not in want and pfx not in keep_pfx]
|
|
return sorted(add), sorted(remove)
|
|
|
|
|
|
# ── regions ──────────────────────────────────────────────────────────────────
|
|
|
|
REGION_LINE = re.compile(r"^(?P<indent> *)(?P<name>[^\s^]+)(?P<home>\^)?(?:\s+(?P<flags>\S+))?\s*$")
|
|
# CommonCLI exports the region list into a 160-byte reply: a tree that does not
|
|
# fit is cut mid-name and cannot be managed from it.
|
|
REGION_REPLY_LIMIT = 159
|
|
|
|
|
|
def parse_regions(text):
|
|
"""`region` reply -> {name: {"parent": name|None, "flood": bool, "home": bool}}.
|
|
|
|
* F
|
|
cz F
|
|
cz-ulk^ F
|
|
cs F
|
|
|
|
One space of indent per level under the wildcard root '*'. 'F' = flood
|
|
allowed; '^' after the name = home region.
|
|
"""
|
|
regions, stack = {}, []
|
|
for raw in text.replace("\r", "").split("\n"):
|
|
if not raw.strip():
|
|
continue
|
|
m = REGION_LINE.match(raw)
|
|
if not m:
|
|
raise ValueError(f"unparsable region line: {raw!r}")
|
|
depth = len(m.group("indent"))
|
|
stack = stack[:depth]
|
|
name = m.group("name")
|
|
regions[name] = {
|
|
"parent": stack[-1] if stack else None,
|
|
"flood": "F" in (m.group("flags") or ""),
|
|
"home": bool(m.group("home")),
|
|
}
|
|
stack.append(name)
|
|
return regions
|
|
|
|
|
|
def region_reply_truncated(text):
|
|
return len(text) >= REGION_REPLY_LIMIT - 4
|
|
|
|
|
|
def plan_regions(current, desired, home=None):
|
|
"""desired: [{"name", "parent" (default "*"), "flood" (default True)}].
|
|
|
|
-> list of CLI commands, in an order the firmware accepts (parents first
|
|
on put, children first on remove), without `region save`.
|
|
"""
|
|
cmds = []
|
|
want = {r["name"]: {"parent": r.get("parent") or "*", "flood": r.get("flood", True)} for r in desired}
|
|
# remove what is not wanted, deepest first
|
|
|
|
def depth(name, tree):
|
|
d = 0
|
|
while tree.get(name, {}).get("parent"):
|
|
name = tree[name]["parent"]
|
|
d += 1
|
|
return d
|
|
|
|
for name in sorted((n for n in current if n != "*" and n not in want), key=lambda n: -depth(n, current)):
|
|
cmds.append(f"region remove {name}")
|
|
# put new or re-parented ones, shallowest first
|
|
for name in sorted(
|
|
want, key=lambda n: depth(n, {**{k: {"parent": v["parent"]} for k, v in want.items()}, "*": {"parent": None}})
|
|
):
|
|
cur = current.get(name)
|
|
if cur is None or (cur["parent"] or "*") != want[name]["parent"]:
|
|
parent = want[name]["parent"]
|
|
cmds.append(f"region put {name}" + ("" if parent == "*" else f" {parent}"))
|
|
cur = None
|
|
if (cur is None and not want[name]["flood"]) or (cur is not None and cur["flood"] != want[name]["flood"]):
|
|
cmds.append(f"region {'allowf' if want[name]['flood'] else 'denyf'} {name}")
|
|
if home is not None:
|
|
cur_home = next((n for n, r in current.items() if r["home"]), None)
|
|
if cur_home != home:
|
|
cmds.append(f"region home {home}")
|
|
return cmds
|
|
|
|
|
|
def render_regions(tree):
|
|
"""Inverse of parse_regions, in the firmware's order (children after their
|
|
parent, siblings in tree order) -- used to show the expected tree in --diff."""
|
|
lines = []
|
|
|
|
def walk(name, depth):
|
|
r = tree[name]
|
|
lines.append(" " * depth + name + ("^" if r.get("home") else "") + (" F" if r.get("flood", True) else ""))
|
|
for child in [n for n, c in tree.items() if c.get("parent") == name]:
|
|
walk(child, depth + 1)
|
|
|
|
walk("*", 0)
|
|
return "\n".join(lines) + "\n"
|
|
|
|
|
|
def expected_tree(current, desired, home=None):
|
|
"""The tree plan_regions() is going to produce from `current`."""
|
|
tree = {
|
|
"*": {
|
|
"parent": None,
|
|
"flood": current.get("*", {}).get("flood", True),
|
|
"home": current.get("*", {}).get("home", False),
|
|
}
|
|
}
|
|
for r in desired:
|
|
cur = current.get(r["name"], {})
|
|
tree[r["name"]] = {
|
|
"parent": r.get("parent") or "*",
|
|
"flood": r.get("flood", True),
|
|
"home": cur.get("home", False),
|
|
}
|
|
if home is not None:
|
|
for n, node in tree.items():
|
|
node["home"] = n == home
|
|
return tree
|
|
|
|
|
|
# ── prefs ────────────────────────────────────────────────────────────────────
|
|
|
|
|
|
def same_value(current, desired):
|
|
"""Compare a `get` reply with the desired value: numbers numerically
|
|
(869.4320068 == 869.432), on/off/true/false/1/0 as booleans, rest as text."""
|
|
c, d = str(current).strip(), str(desired).strip()
|
|
bools = {"on": True, "true": True, "1": True, "off": False, "false": False, "0": False}
|
|
if c.lower() in bools and d.lower() in bools:
|
|
return bools[c.lower()] == bools[d.lower()]
|
|
try:
|
|
return abs(float(c) - float(d)) < 1e-3
|
|
except ValueError:
|
|
return c == d
|
|
|
|
|
|
# ── channel-hash deny list (`filter hash`, MeshCore 22fa0659+) ───────────────
|
|
|
|
FILTER_HASH_REPLY = re.compile(
|
|
r"^filter hash: dropped (?P<dropped>\d+)(?:, passed (?P<passed>\d+))?, deny:(?P<list>.*)$"
|
|
)
|
|
|
|
|
|
def parse_filter_hash(text):
|
|
"""`filter hash` reply -> (entries, dropped counter). An entry is `43`
|
|
(blocked) or `43/60` (throttled to one packet per 60 s, meshcore-tth firmware).
|
|
None = the firmware does not know the command (older build)."""
|
|
m = FILTER_HASH_REPLY.match(text.strip())
|
|
if not m:
|
|
return None
|
|
items = [] if "(nic)" in m["list"] else m["list"].split()
|
|
return [norm_entry(h) for h in items], int(m["dropped"])
|
|
|
|
|
|
FAIR_ADVERT_REPLY = re.compile(
|
|
r"^advert window (?P<hours>\d+)h(?P<dry> DRY-RUN)?, held (?P<held>\d+) \((?P<air>\d+)s air\), "
|
|
r"cache (?P<count>\d+)/(?P<cap>\d+), evicted (?P<evicted>\d+)$"
|
|
)
|
|
FAIR_DRY_REPLY = re.compile(r"^(?:OK - )?fairness dry-run (?P<state>on|off)$")
|
|
|
|
|
|
def parse_fairness_advert(text):
|
|
"""`fairness advert` reply -> dict (hours, dry_run, held, air_s, cache, evicted).
|
|
None = the firmware has no advert window (before MeshCore 39031b18)."""
|
|
m = FAIR_ADVERT_REPLY.match(text.strip())
|
|
if not m:
|
|
return None
|
|
return {
|
|
"hours": int(m["hours"]),
|
|
"dry_run": bool(m["dry"]),
|
|
"held": int(m["held"]),
|
|
"air_s": int(m["air"]),
|
|
"cache": int(m["count"]),
|
|
"evicted": int(m["evicted"]),
|
|
}
|
|
|
|
|
|
def parse_fairness_dry(text):
|
|
"""`fairness dryrun [on|off]` reply -> bool, None = command unknown."""
|
|
m = FAIR_DRY_REPLY.match(text.strip())
|
|
return None if not m else m["state"] == "on"
|
|
|
|
|
|
FILTER_AGE_REPLY = re.compile(
|
|
r"^(?:OK - )?filter age (?:off|(?P<min>\d+)m(?P<dry> DRY-RUN)?(?P<unset> \(clock not set, inactive\))?), "
|
|
r"dropped (?P<dropped>\d+)$"
|
|
)
|
|
FILTER_DRY_REPLY = re.compile(r"^(?:OK - )?filter dry-run (?P<state>on|off)$")
|
|
|
|
|
|
def parse_filter_age(text):
|
|
"""`filter age [<min>|off]` reply -> dict (minutes 0 = off, dry_run, clock_unset,
|
|
dropped). None = the firmware has no age limit (before MeshCore a7336790)."""
|
|
m = FILTER_AGE_REPLY.match(text.strip())
|
|
if not m:
|
|
return None
|
|
return {
|
|
"minutes": int(m["min"] or 0),
|
|
"dry_run": bool(m["dry"]),
|
|
"clock_unset": bool(m["unset"]),
|
|
"dropped": int(m["dropped"]),
|
|
}
|
|
|
|
|
|
def parse_filter_dry(text):
|
|
"""`filter dryrun [on|off]` reply -> bool, None = command unknown."""
|
|
m = FILTER_DRY_REPLY.match(text.strip())
|
|
return None if not m else m["state"] == "on"
|
|
|
|
|
|
def norm_hash(value):
|
|
"""`43`, `0x43`, 67 -> `43`."""
|
|
if isinstance(value, int):
|
|
n = value
|
|
else:
|
|
s = str(value).strip().lower()
|
|
n = int(s.removeprefix("0x"), 16)
|
|
if not 0 <= n <= 0xFF:
|
|
raise ValueError(f"channel hash out of range: {value!r}")
|
|
return f"{n:02X}"
|
|
|
|
|
|
def norm_entry(value):
|
|
"""`43`, `0x43`, 67 -> `43` (block); `43/60`, `0x43/60` -> `43/60` (throttle);
|
|
`43/0` is a block, so `43`."""
|
|
if isinstance(value, int):
|
|
return norm_hash(value)
|
|
h, _sep, secs = str(value).strip().partition("/")
|
|
if not secs:
|
|
return norm_hash(h)
|
|
n = int(secs)
|
|
if not 0 <= n <= 65535:
|
|
raise ValueError(f"throttle interval out of range: {value!r}")
|
|
return norm_hash(h) if n == 0 else f"{norm_hash(h)}/{n}"
|
|
|
|
|
|
def entry_hash(entry):
|
|
return entry.partition("/")[0]
|
|
|
|
|
|
def filter_hash_cmd(entry, delete=False):
|
|
h, _sep, secs = entry.partition("/")
|
|
if delete:
|
|
return f"filter hash del {h}"
|
|
return f"filter hash add {h} {secs}" if secs else f"filter hash add {h}"
|
|
|
|
|
|
def plan_filter_hash(current, desired, exclusive=True):
|
|
"""-> (add, remove) of entries. A listed byte whose interval changes is
|
|
re-added (firmware updates it in place), never deleted first."""
|
|
want = list(dict.fromkeys(norm_entry(h) for h in desired))
|
|
want_hashes = {entry_hash(e) for e in want}
|
|
add = [e for e in want if e not in current]
|
|
remove = [e for e in current if exclusive and entry_hash(e) not in want_hashes]
|
|
return add, remove
|