Ansible collection that converges MeshCore repeaters through a companion radio (TCP, USB serial or BLE): admin ACL, CLI prefs, region tree, firmware facts, companion remote-CLI ACL, and the meshcore-tth extras (BLE on/off and own BLE PIN, channel-hash filter, message age, advert fairness). Every change is read, diffed, sent and read back; --check only reads. ansible-test sanity, unit tests and a galaxy build in CI. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
0a4cfafc78
27 files changed
+3195
No files matched your search
@@ -0,0 +1,78 @@
|
||||
"""Radio-free parsing of `ver` and of the BLE commands of meshcore-tth.
|
||||
|
||||
Kept apart from the modules so it can be unit-tested on real replies (see
|
||||
tests/unit) -- every rule here once cost time on real hardware.
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
# Stamp written by meshcore-tth's tools/build_version.py: <upstream tag>-tth<sha>[+].
|
||||
# '+' = built from a dirty tree: nobody can tell what is in it, so such a node
|
||||
# always counts as outdated.
|
||||
# meshcore-tth v1.18.0-tth0781378; Solo v2.0-tth8345a5a, or its CI release name
|
||||
# v2.0+tth.20261011195120 (two-part version, optional -rcN).
|
||||
VERSION_RE = re.compile(r"v\d+(?:\.\d+)+(?:-rc\d+)?(?:-tth-?[0-9a-f]{4,}\+?|\+tth\.\d{14})")
|
||||
# Stock MeshCore: `v1.18.0 (Build: ...)`. Only trusted right before "(Build:",
|
||||
# a bare vX.Y.Z elsewhere in a reply or an ELF is too easy to mistake.
|
||||
UPSTREAM_RE = re.compile(r"(v\d+(?:\.\d+)+(?:-rc\d+)?) \(Build: ")
|
||||
|
||||
|
||||
def parse_version(text):
|
||||
"""First firmware stamp in a `ver` reply / board_probe line / ELF, or None."""
|
||||
m = VERSION_RE.search(text or "")
|
||||
if m:
|
||||
return m.group(0)
|
||||
m = UPSTREAM_RE.search(text or "")
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def fw_state(current, wanted):
|
||||
"""'current' | 'outdated' | 'dirty' | 'unknown' (no readable version)."""
|
||||
if not wanted or wanted.endswith("+"):
|
||||
raise ValueError(f"wanted version {wanted!r} is not a clean stamp -- build from a clean tree")
|
||||
if not current:
|
||||
return "unknown"
|
||||
if current.endswith("+"):
|
||||
return "dirty"
|
||||
return "current" if current == wanted else "outdated"
|
||||
|
||||
|
||||
# ── BLE CLI replies (examples/simple_repeater/main.cpp) ─────────────────────
|
||||
|
||||
|
||||
def parse_ble(text):
|
||||
"""`ble` -> 'on' | 'off'. Reply: 'BLE: on (advertising)'."""
|
||||
m = re.match(r"^BLE: (on|off)\b", (text or "").strip())
|
||||
if not m:
|
||||
raise ValueError(f"unexpected `ble` reply: {text!r}")
|
||||
return m.group(1)
|
||||
|
||||
|
||||
def parse_ble_pin(text):
|
||||
"""`ble` -> 'own' | 'build default', or None when the firmware predates `ble pin`.
|
||||
|
||||
Reply: 'BLE: off, PIN own'. The PIN itself is never printed.
|
||||
"""
|
||||
m = re.search(r", PIN (own|build default)\s*$", (text or "").strip())
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def ble_pin_valid(pin):
|
||||
return isinstance(pin, str) and len(pin) == 6 and pin.isdigit()
|
||||
|
||||
|
||||
def parse_blepwr(text):
|
||||
"""`blepwr` -> connection tx power in dBm. Reply: 'BLE conn tx: 0 dBm, adv tx: 8 dBm'."""
|
||||
m = re.match(r"^BLE conn tx: (-?\d+) dBm", (text or "").strip())
|
||||
if not m:
|
||||
raise ValueError(f"unexpected `blepwr` reply: {text!r}")
|
||||
return int(m.group(1))
|
||||
|
||||
|
||||
BLE_CONN_TX_VALID = {-40, -20, -16, -12, -8, -4, 0, 2, 3, 4, 5, 6, 7, 8}
|
||||
|
||||
|
||||
def blepwr_set_ok(text):
|
||||
"""A `blepwr <n>` reply proves the value is applied AND saved."""
|
||||
t = (text or "").strip()
|
||||
return t.startswith("OK") and t.endswith(", saved")
|
||||
@@ -0,0 +1,256 @@
|
||||
"""RF admin link to a MeshCore repeater (or companion) through a companion radio.
|
||||
|
||||
Shared by the tth.meshcore modules. The companion is either a TCP companion
|
||||
(e.g. an openHop companion), a USB serial companion, or a BLE companion
|
||||
bonded on the host the module runs on. Everything below was
|
||||
learned the hard way:
|
||||
|
||||
* subscribe to replies BEFORE sending anything -- wait_for_event only sees
|
||||
events created after it is called, so a reply delivered meanwhile is lost;
|
||||
* set the companion's path hash width to 2 B (its own pref, default 1 B);
|
||||
* a repeater that never advertised can still be addressed: build the contact
|
||||
from its full pubkey (the login secret is derived from the contact);
|
||||
* use send_login_sync -- plain send_login + wait times out on a flood login;
|
||||
* never echo the password: the node's `password` reply contains it.
|
||||
|
||||
A COMPANION target (companion=True), fw 1.18+ / Solo 2.0+: its ACL is the
|
||||
"remote CLI" flag (ContactInfo flags 0x10) on its contacts, set on the companion
|
||||
itself -- the same mc_admins keys as on the repeaters, nobody else. A command
|
||||
comes as TXT_TYPE_CLI_COMMAND (3), encrypted to that contact's shared secret,
|
||||
so only a flagged key gets an answer; there is no password step on top. Type 1
|
||||
that send_cmd uses is a CLI *reply* there and only lands in its app.
|
||||
|
||||
Plus what the RF itself does: replies get lost and occasionally arrive late,
|
||||
so every CLI exchange checks that the reply came from the target and looks
|
||||
like the expected kind of answer, and retries otherwise.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
import time
|
||||
|
||||
try:
|
||||
from meshcore import EventType, MeshCore
|
||||
|
||||
HAS_MESHCORE = True
|
||||
except ImportError: # reported by the module via missing_required_lib
|
||||
HAS_MESHCORE = False
|
||||
|
||||
HEX64 = re.compile(r"^[0-9a-f]{64}$")
|
||||
|
||||
|
||||
class LinkError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Link:
|
||||
def __init__(
|
||||
self,
|
||||
transport,
|
||||
target,
|
||||
password="",
|
||||
path_hash_mode=1,
|
||||
reply_timeout=None,
|
||||
retries=None,
|
||||
companion=False,
|
||||
name=None,
|
||||
):
|
||||
self.transport = transport
|
||||
self.companion = companion
|
||||
self.last_reply_ts = None # node clock (sender_timestamp) of the last matched reply
|
||||
self.last_reply_at = None
|
||||
self.contact_name = (name or "target")[:31]
|
||||
self.target_pk = target.lower()
|
||||
if not HEX64.match(self.target_pk):
|
||||
raise LinkError("target must be the node's full 64-hex pubkey")
|
||||
self.password = password or ""
|
||||
self.path_hash_mode = path_hash_mode
|
||||
# A repeater with a BLE client connected lost three CLI replies in a row
|
||||
# (a BLE link mutes DIRECT traffic, and CLI replies are DIRECT), so the
|
||||
# default is generous; both can be set per host in mc_transport.
|
||||
self.reply_timeout = float(reply_timeout or transport.get("reply_timeout", 20))
|
||||
self.retries = int(retries if retries is not None else transport.get("retries", 4))
|
||||
self.mc = None
|
||||
self.contact = None
|
||||
self.inbox = []
|
||||
self.log = [] # human-readable trace, returned by the modules (no secrets)
|
||||
|
||||
# ── session ─────────────────────────────────────────────────────────────
|
||||
|
||||
async def open(self):
|
||||
t = self.transport
|
||||
if t.get("type") == "serial":
|
||||
self.mc = await MeshCore.create_serial(t["port"], int(t.get("baud", 115200)))
|
||||
elif t.get("type") == "ble":
|
||||
# No PIN here on purpose: it would end up in the task's logged
|
||||
# arguments. The companion is bonded once by hand (bluetoothctl pair)
|
||||
# on the host the module runs on, and the bond does the encryption.
|
||||
self.mc = await MeshCore.create_ble(t["address"])
|
||||
else:
|
||||
self.mc = await MeshCore.create_tcp(
|
||||
host=t.get("host", "127.0.0.1"), port=int(t["port"]), auto_reconnect=False
|
||||
)
|
||||
if self.mc is None:
|
||||
raise LinkError(f"cannot connect to companion {t}")
|
||||
# Bench guard: an inventory that says which frequency its companion must
|
||||
# be on never transmits anywhere else (a bench run must not reach the
|
||||
# live mesh because a cable went to the wrong board).
|
||||
if t.get("expect_freq") is not None:
|
||||
freq = float((self.mc.self_info or {}).get("radio_freq") or 0)
|
||||
if abs(freq - float(t["expect_freq"])) > 0.01:
|
||||
await self.mc.disconnect()
|
||||
raise LinkError(f"companion is on {freq} MHz, inventory expects {t['expect_freq']} -- nothing sent")
|
||||
self.mc.subscribe(EventType.CONTACT_MSG_RECV, lambda ev: self.inbox.append(ev.payload))
|
||||
if (await self.mc.commands.get_path_hash_mode()) != self.path_hash_mode:
|
||||
await self.mc.commands.set_path_hash_mode(self.path_hash_mode)
|
||||
await self.mc.ensure_contacts()
|
||||
self.contact = self._find_contact()
|
||||
if self.contact is None:
|
||||
await self._add_contact()
|
||||
await self.mc.start_auto_message_fetching()
|
||||
|
||||
async def close(self):
|
||||
if self.mc is not None:
|
||||
await self.mc.disconnect()
|
||||
|
||||
def self_pubkey(self):
|
||||
return (self.mc.self_info or {}).get("public_key", "").lower()
|
||||
|
||||
def _find_contact(self):
|
||||
for c in (self.mc.contacts or {}).values():
|
||||
if (c.get("public_key") or "").lower() == self.target_pk:
|
||||
return c
|
||||
return None
|
||||
|
||||
async def _add_contact(self):
|
||||
contact = {
|
||||
"public_key": self.target_pk,
|
||||
"type": 1 if self.companion else 2,
|
||||
"flags": 0,
|
||||
"out_path": "",
|
||||
"out_path_len": -1,
|
||||
# last_advert = now: with 0 it is the "oldest" contact and the next
|
||||
# eviction (table full) would pick exactly the one just created.
|
||||
"out_path_hash_mode": 0,
|
||||
"adv_name": self.contact_name,
|
||||
"last_advert": int(time.time()),
|
||||
"adv_lat": 0.0,
|
||||
"adv_lon": 0.0,
|
||||
}
|
||||
ev = await self.mc.commands.add_contact(contact)
|
||||
if ev is not None and ev.type == EventType.ERROR:
|
||||
# Table full (a busy companion with auto-add sits at 1000/1000):
|
||||
# make room the way the firmware's own auto-add does -- drop the
|
||||
# contact heard longest ago that is not a favourite.
|
||||
cands = [
|
||||
c
|
||||
for c in (self.mc.contacts or {}).values()
|
||||
if not (c.get("flags") or 0) & 1 and (c.get("public_key") or "").lower() != self.target_pk
|
||||
]
|
||||
if not cands:
|
||||
raise LinkError(f"companion refused the contact ({ev.payload}) and nothing can be evicted")
|
||||
victim = min(cands, key=lambda c: c.get("last_advert") or 0)
|
||||
await self.mc.commands.remove_contact(victim["public_key"])
|
||||
self.log.append(f"contact table full: evicted {victim.get('adv_name') or victim['public_key'][:12]}")
|
||||
await self.mc.commands.add_contact(contact)
|
||||
await asyncio.sleep(2)
|
||||
fresh = await self.mc.commands.get_contacts()
|
||||
for c in ((fresh.payload if fresh else None) or {}).values():
|
||||
if (c.get("public_key") or "").lower() == self.target_pk:
|
||||
self.contact = c
|
||||
self.log.append("contact created from pubkey")
|
||||
return
|
||||
raise LinkError("could not create a contact for the target")
|
||||
|
||||
async def login(self):
|
||||
"""Admin login; blank password works for a client already in the ACL."""
|
||||
for attempt in range(1 + self.retries):
|
||||
# a stale path from an earlier session would send the login nowhere
|
||||
await self.mc.commands.reset_path(self.contact)
|
||||
ev = await self.mc.commands.send_login_sync(self.contact, self.password, timeout=45)
|
||||
if ev is not None and ev.type == EventType.LOGIN_SUCCESS:
|
||||
# LOGIN_SUCCESS alone is not enough: a password that equals the
|
||||
# node's GUEST password (or a blank one when guest is blank) logs
|
||||
# in as guest, and the admin requests then just go unanswered.
|
||||
if not (ev.payload or {}).get("is_admin"):
|
||||
raise LinkError(
|
||||
"logged in as GUEST, not admin -- the node's admin password differs "
|
||||
"(prefs override the build) or this companion is not admin in its ACL"
|
||||
)
|
||||
self.log.append(f"login ok as admin (attempt {attempt + 1})")
|
||||
return True
|
||||
raise LinkError("login refused or no reply (wrong password, or not in the ACL)")
|
||||
|
||||
# ── CLI ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def _from_target(self, msg):
|
||||
pfx = (msg.get("pubkey_prefix") or "").lower()
|
||||
return bool(pfx) and self.target_pk.startswith(pfx)
|
||||
|
||||
async def cli(self, cmd, expect):
|
||||
"""Send one CLI command and return the reply text that matches `expect` (regex).
|
||||
|
||||
A reply that does not match (a late answer to an earlier command, or
|
||||
another node) is drained and the command is resent, up to `retries`.
|
||||
"""
|
||||
# never log a secret the command carries (the trace is returned to Ansible)
|
||||
shown = cmd
|
||||
for secret_cmd in ("password ", "ble pin "):
|
||||
if cmd.startswith(secret_cmd):
|
||||
shown = secret_cmd + "***"
|
||||
for attempt in range(1 + self.retries):
|
||||
self.inbox.clear()
|
||||
if self.companion:
|
||||
await self.send_cli_command(cmd)
|
||||
else:
|
||||
await self.mc.commands.send_cmd(self.contact, cmd)
|
||||
deadline = time.monotonic() + self.reply_timeout
|
||||
while time.monotonic() < deadline:
|
||||
for msg in list(self.inbox):
|
||||
text = (msg.get("text") or "").strip()
|
||||
if self._from_target(msg) and re.search(expect, text):
|
||||
self.log.append(f"$ {shown} -> {self._redact(text)}")
|
||||
# The reply carries the NODE's clock: what fw_facts reports as skew.
|
||||
self.last_reply_ts = msg.get("sender_timestamp")
|
||||
self.last_reply_at = time.time()
|
||||
await asyncio.sleep(0.5) # let a straggler land before the next command
|
||||
return text
|
||||
await asyncio.sleep(0.3)
|
||||
seen = [self._redact((m.get("text") or "").strip()) for m in self.inbox]
|
||||
self.log.append(f"$ {shown} -> no matching reply (attempt {attempt + 1}, got {seen})")
|
||||
raise LinkError(f"no reply matching /{expect}/ to `{shown}`")
|
||||
|
||||
async def send_cli_command(self, cmd):
|
||||
"""CMD_SEND_TXT_MSG with txt_type 3 -- what a companion's remote CLI answers."""
|
||||
data = (
|
||||
b"\x02\x03\x00" + int(time.time()).to_bytes(4, "little") + bytes.fromhex(self.target_pk[:12]) + cmd.encode()
|
||||
)
|
||||
ev = await self.mc.commands.send(data, [EventType.MSG_SENT, EventType.ERROR])
|
||||
if ev is not None and ev.type == EventType.ERROR:
|
||||
raise LinkError(f"companion refused to send `{cmd}`: {ev.payload}")
|
||||
|
||||
def name(self):
|
||||
return (self.contact or {}).get("adv_name") or ""
|
||||
|
||||
def _redact(self, text):
|
||||
return text.replace(self.password, "***") if self.password else text
|
||||
|
||||
async def get(self, key):
|
||||
"""`get <key>` -> the value string (reply is '> value')."""
|
||||
text = await self.cli(f"get {key}", r"^(>|Err|\?)")
|
||||
if not text.startswith(">"):
|
||||
raise LinkError(f"`get {key}`: {text}")
|
||||
return text[1:].strip()
|
||||
|
||||
async def acl(self):
|
||||
"""Real ACL as {prefix12: perm}, via the binary access-list request."""
|
||||
for attempt in range(1 + self.retries):
|
||||
res = await self.mc.commands.req_acl_sync(self.contact, timeout=40)
|
||||
if res is not None:
|
||||
return {e["key"].lower(): e["perm"] for e in res}
|
||||
self.log.append(f"ACL request: no reply (attempt {attempt + 1})")
|
||||
raise LinkError("ACL request: no reply")
|
||||
|
||||
|
||||
def run(coro):
|
||||
return asyncio.run(coro)
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Pure planning logic of the tth.meshcore modules -- no radio, unit-tested."""
|
||||
|
||||
import re
|
||||
|
||||
PERM_ADMIN = 3
|
||||
|
||||
# Prefs that can cut the node off (or are gated to the local console anyway).
|
||||
# The prefs module refuses them; change them on site.
|
||||
DANGEROUS_PREFS = {"freq", "radio", "bw", "sf", "cr", "prv.key", "password", "guest.password"}
|
||||
|
||||
|
||||
# ── 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
|
||||
Reference in new issue
Block a user