"""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 *)(?P[^\s^]+)(?P\^)?(?:\s+(?P\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\d+)(?:, passed (?P\d+))?, deny:(?P.*)$" ) 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\d+)h(?P DRY-RUN)?, held (?P\d+) \((?P\d+)s air\), " r"cache (?P\d+)/(?P\d+), evicted (?P\d+)$" ) FAIR_DRY_REPLY = re.compile(r"^(?:OK - )?fairness dry-run (?Pon|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\d+)m(?P DRY-RUN)?(?P \(clock not set, inactive\))?), " r"dropped (?P\d+)$" ) FILTER_DRY_REPLY = re.compile(r"^(?:OK - )?filter dry-run (?Pon|off)$") def parse_filter_age(text): """`filter age [|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