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
|
||||
@@ -0,0 +1,130 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_acl
|
||||
short_description: Admin ACL of a MeshCore repeater, over RF through a companion
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- Reads the repeater's real ACL with the binary access-list request (the only
|
||||
way to see it remotely; `get acl` prints to the node's USB serial), then sends
|
||||
`setperm <pubkey> 3` for missing admins and, with I(exclusive), `setperm <prefix> 0`
|
||||
for everything else. Reads the ACL back afterwards and fails on a mismatch.
|
||||
- The companion this runs through must stay admin, otherwise the next run could
|
||||
not log in. It is kept even when not listed in I(admins).
|
||||
options:
|
||||
transport:
|
||||
description:
|
||||
- "Companion to talk through: C({type: tcp, host, port}), C({type: serial, port, baud})
|
||||
or C({type: ble, address})."
|
||||
- A BLE companion must already be bonded on the host the module runs on
|
||||
(C(bluetoothctl pair)); there is no PIN option, so it never lands in a log.
|
||||
While the module holds the link, the companion is not reachable from a phone.
|
||||
- C(expect_freq) (MHz) refuses to send anything when the companion is on another
|
||||
frequency; C(retries) and C(reply_timeout) tune the RF exchange.
|
||||
type: dict
|
||||
required: true
|
||||
target:
|
||||
description: Full 64-hex pubkey of the repeater.
|
||||
type: str
|
||||
required: true
|
||||
password:
|
||||
description: Admin password. Empty = blank login, works for a companion already in the ACL.
|
||||
type: str
|
||||
default: ""
|
||||
admins:
|
||||
description: Full 64-hex pubkeys that must be admin.
|
||||
type: list
|
||||
elements: str
|
||||
required: true
|
||||
exclusive:
|
||||
description: Remove every ACL entry that is not in I(admins).
|
||||
type: bool
|
||||
default: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Exactly these admins
|
||||
tth.meshcore.meshcore_acl:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
admins:
|
||||
- "{{ managing_companion_pubkey }}"
|
||||
- "{{ my_phone_pubkey }}"
|
||||
"""
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import (
|
||||
HAS_MESHCORE,
|
||||
HEX64,
|
||||
Link,
|
||||
LinkError,
|
||||
run,
|
||||
)
|
||||
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_plan import PERM_ADMIN, plan_acl
|
||||
|
||||
|
||||
async def work(module, link):
|
||||
p = module.params
|
||||
await link.open()
|
||||
try:
|
||||
await link.login()
|
||||
before = await link.acl()
|
||||
me = link.self_pubkey()
|
||||
add, remove = plan_acl(before, p["admins"], p["exclusive"], keep=[me])
|
||||
add_pfx = {a[:12] for a in add}
|
||||
expected = (set(before) - set(remove)) | add_pfx
|
||||
result = {
|
||||
"changed": bool(add or remove),
|
||||
"add": add,
|
||||
"remove": remove,
|
||||
"diff": {
|
||||
"before": "".join(f"{k} {before[k]}\n" for k in sorted(before)),
|
||||
"after": "".join(f"{k} {PERM_ADMIN if k in add_pfx else before[k]}\n" for k in sorted(expected)),
|
||||
},
|
||||
}
|
||||
if module.check_mode or not result["changed"]:
|
||||
return result
|
||||
for pk in add:
|
||||
await link.cli(f"setperm {pk} {PERM_ADMIN}", r"^(OK|Err)")
|
||||
for pfx in remove:
|
||||
# a prefix that is gone already answers "Err - invalid params": fine
|
||||
await link.cli(f"setperm {pfx} 0", r"^(OK|Err)")
|
||||
after = await link.acl()
|
||||
left_add, left_remove = plan_acl(after, p["admins"], p["exclusive"], keep=[me])
|
||||
if left_add or left_remove:
|
||||
raise LinkError(f"ACL after apply still differs: missing {left_add}, extra {left_remove}")
|
||||
result["acl"] = after
|
||||
return result
|
||||
finally:
|
||||
await link.close()
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"transport": {"type": "dict", "required": True},
|
||||
"target": {"type": "str", "required": True},
|
||||
"password": {"type": "str", "default": "", "no_log": True},
|
||||
"admins": {"type": "list", "elements": "str", "required": True},
|
||||
"exclusive": {"type": "bool", "default": True},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
if not HAS_MESHCORE:
|
||||
module.fail_json(msg=missing_required_lib("meshcore"))
|
||||
admins = [a.lower() for a in module.params["admins"]]
|
||||
bad = [a for a in admins if not HEX64.match(a)]
|
||||
if bad:
|
||||
module.fail_json(msg=f"admins must be full 64-hex pubkeys: {bad}")
|
||||
module.params["admins"] = admins
|
||||
link = Link(module.params["transport"], module.params["target"], module.params["password"])
|
||||
try:
|
||||
result = run(work(module, link))
|
||||
except LinkError as e:
|
||||
module.fail_json(msg=str(e), log=link.log)
|
||||
module.exit_json(log=link.log, **result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,172 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_ble
|
||||
short_description: BLE on/off, own BLE PIN and connection tx power of a MeshCore repeater, over RF
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- Commands of the meshcore-tth firmware (examples/simple_repeater/main.cpp), which have no
|
||||
`get`/`set` form, so meshcore_prefs cannot manage them. Both are persistent on
|
||||
the node (marker files in InternalFS) and survive a reboot AND a reflash.
|
||||
- C(state) reads `ble` and sends `ble on|off` when it differs. The switch is
|
||||
applied 1.5 s after the reply, so the RF reply still goes out.
|
||||
- C(conn_tx_power) reads `blepwr` and sends `blepwr <dBm>`; the reply must say
|
||||
`saved`. It sets the CONNECTION power only -- advertising is fixed at 8 dBm.
|
||||
A node already on the wanted value is left alone even when that value is only
|
||||
the build default (not pinned); `blepwr` cannot tell the two apart.
|
||||
- C(pin) sets the node's own BLE PIN with `ble pin`. The BLE console has no
|
||||
login of its own, only this PIN, and a public build ships the placeholder
|
||||
123456 (it refuses `ble on` until another PIN is set). The firmware never
|
||||
prints the PIN, only whether it is C(own) or C(build default), so the module
|
||||
sends it only when the node reports C(build default) -- or with C(pin_force).
|
||||
Every `ble pin` clears the node's bonds, so every paired device has to pair
|
||||
again; that is why it is not sent on every run.
|
||||
- The PIN goes over RF encrypted to the node like any admin command and is
|
||||
masked in the returned log.
|
||||
- Never turns BLE off as a side effect; with no option it only reports.
|
||||
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}
|
||||
password: {description: Admin password (empty = blank login)., type: str, default: ""}
|
||||
state: {description: Wanted BLE state., type: str, choices: ["on", "off"]}
|
||||
conn_tx_power:
|
||||
description: Wanted connection tx power in dBm (-40,-20,-16,-12,-8,-4,0,2..8).
|
||||
type: int
|
||||
pin:
|
||||
description:
|
||||
- Own BLE PIN, six digits. Sent when the node still has the build's PIN,
|
||||
or always with I(pin_force). Keep it in ansible-vault.
|
||||
- Needs meshcore-tth with `ble pin` (releases after tth-654d53f3).
|
||||
type: str
|
||||
pin_force:
|
||||
description:
|
||||
- Send I(pin) even when the node already has an own PIN (to change it).
|
||||
Clears the node's bonds every time, so it is not idempotent -- use it
|
||||
for one run, not in a playbook that runs regularly.
|
||||
type: bool
|
||||
default: false
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: BLE console off, connection power 8 dBm
|
||||
tth.meshcore.meshcore_ble:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
state: "off"
|
||||
conn_tx_power: 8
|
||||
|
||||
- name: Own BLE PIN first, then the console on
|
||||
tth.meshcore.meshcore_ble:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
pin: "{{ vault_meshcore_ble_pin }}"
|
||||
state: "on"
|
||||
"""
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_fw import (
|
||||
BLE_CONN_TX_VALID,
|
||||
ble_pin_valid,
|
||||
blepwr_set_ok,
|
||||
parse_ble,
|
||||
parse_ble_pin,
|
||||
parse_blepwr,
|
||||
)
|
||||
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run
|
||||
|
||||
|
||||
async def read(link):
|
||||
ble = await link.cli("ble", r"^BLE: ")
|
||||
return {
|
||||
"state": parse_ble(ble),
|
||||
"pin": parse_ble_pin(ble),
|
||||
"conn_tx_power": parse_blepwr(await link.cli("blepwr", r"^BLE conn tx: ")),
|
||||
}
|
||||
|
||||
|
||||
async def work(module, link):
|
||||
want = {k: module.params[k] for k in ("state", "conn_tx_power") if module.params[k] is not None}
|
||||
await link.open()
|
||||
try:
|
||||
await link.login()
|
||||
before = await read(link)
|
||||
changes = {k: v for k, v in want.items() if before[k] != v}
|
||||
if module.params["pin"] is not None:
|
||||
if before["pin"] is None:
|
||||
raise LinkError("the firmware has no `ble pin` (meshcore-tth after tth-654d53f3 needed)")
|
||||
if before["pin"] != "own" or module.params["pin_force"]:
|
||||
# the value itself never goes into the result, only the status
|
||||
changes["pin"] = "own"
|
||||
result = {
|
||||
"changed": bool(changes),
|
||||
"before": before,
|
||||
"set": changes,
|
||||
"diff": {
|
||||
"before": "".join(f"{k}: {before[k]}\n" for k in sorted(changes)),
|
||||
"after": "".join(f"{k}: {changes[k]}\n" for k in sorted(changes)),
|
||||
},
|
||||
}
|
||||
if module.check_mode or not changes:
|
||||
return result
|
||||
if "pin" in changes:
|
||||
# first, so a following `ble on` is not refused for the default PIN
|
||||
reply = await link.cli(f"ble pin {module.params['pin']}", r"^(OK|ERR)")
|
||||
if not reply.startswith("OK"):
|
||||
raise LinkError(f"`ble pin ***`: {reply}")
|
||||
if "conn_tx_power" in changes:
|
||||
reply = await link.cli(f"blepwr {changes['conn_tx_power']}", r"^(OK|ERR)")
|
||||
if not blepwr_set_ok(reply):
|
||||
raise LinkError(f"`blepwr {changes['conn_tx_power']}`: {reply}")
|
||||
if "state" in changes:
|
||||
reply = await link.cli(f"ble {changes['state']}", r"^(OK|ERR|Err|\?)")
|
||||
if reply.startswith("ERR - set your own PIN"):
|
||||
raise LinkError("`ble on` refused: the node still has the build's placeholder PIN -- give it `pin`")
|
||||
if not reply.startswith("OK"):
|
||||
raise LinkError(f"`ble {changes['state']}`: {reply}")
|
||||
after = await read(link)
|
||||
bad = {k: after[k] for k in changes if after[k] != changes[k]}
|
||||
if bad.get("pin") == "build default":
|
||||
raise LinkError("`ble pin` answered OK but the node reports the build default: `pin` is the build's PIN")
|
||||
if bad:
|
||||
raise LinkError(f"answered OK but reads back {bad}")
|
||||
result["after"] = after
|
||||
return result
|
||||
finally:
|
||||
await link.close()
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"transport": {"type": "dict", "required": True},
|
||||
"target": {"type": "str", "required": True},
|
||||
"password": {"type": "str", "default": "", "no_log": True},
|
||||
"state": {"type": "str", "choices": ["on", "off"]},
|
||||
"conn_tx_power": {"type": "int"},
|
||||
"pin": {"type": "str", "no_log": True},
|
||||
"pin_force": {"type": "bool", "default": False},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
if not HAS_MESHCORE:
|
||||
module.fail_json(msg=missing_required_lib("meshcore"))
|
||||
pin = module.params["pin"]
|
||||
if pin is not None and not ble_pin_valid(pin):
|
||||
module.fail_json(msg="pin must be exactly six digits")
|
||||
if module.params["pin_force"] and pin is None:
|
||||
module.fail_json(msg="pin_force needs pin")
|
||||
p = module.params["conn_tx_power"]
|
||||
if p is not None and p not in BLE_CONN_TX_VALID:
|
||||
module.fail_json(msg=f"conn_tx_power {p}: the nRF52840 takes {sorted(BLE_CONN_TX_VALID)}")
|
||||
link = Link(module.params["transport"], module.params["target"], module.params["password"])
|
||||
try:
|
||||
result = run(work(module, link))
|
||||
except (LinkError, ValueError) as e:
|
||||
module.fail_json(msg=str(e), log=link.log)
|
||||
module.exit_json(log=link.log, **result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,217 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_companion_acl
|
||||
short_description: Remote-CLI ACL of a MeshCore companion (contact flag 0x10), over its BLE link
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- A companion (fw 1.18+, Solo 2.0+) runs a CLI command that arrives as
|
||||
TXT_TYPE_CLI_COMMAND only from a contact flagged "remote CLI"
|
||||
(ContactInfo flags bit 0x10). That flag IS its ACL, and the remote CLI can
|
||||
do everything (radio, name, PIN, reboot), so the set is converged exactly
|
||||
like a repeater's ACL - the listed keys get it, every other contact loses it.
|
||||
- Flags live on the companion and can only be changed over its own link, so
|
||||
this runs on a host with BLE in range (bleak, NUS, one write = one frame) and
|
||||
needs a bond with the node. A listed key the companion does not know is
|
||||
added as a chat contact; when its table is full, the contact heard longest
|
||||
ago that is neither a favourite nor in the list is removed to make room
|
||||
(what the firmware's own auto-add does) and reported in C(evicted).
|
||||
- Each contact is read, only its flags byte changed, and written back
|
||||
(CMD_ADD_UPDATE_CONTACT takes the CONTACT frame layout), so path, name and
|
||||
the other flag bits (favourite, telemetry, Solo's kept route) are kept.
|
||||
options:
|
||||
mac: {description: BLE MAC of the companion., type: str, required: true}
|
||||
admins: {description: Pubkeys (64 hex) that get remote CLI., type: list, elements: str, required: true}
|
||||
names: {description: pubkey -> name for contacts that have to be added., type: dict, default: {}}
|
||||
timeout: {description: Seconds for the whole BLE session., type: int, default: 120}
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Remote CLI only for these keys
|
||||
tth.meshcore.meshcore_companion_acl:
|
||||
mac: "AA:BB:CC:DD:EE:FF"
|
||||
admins:
|
||||
- "{{ my_phone_pubkey }}"
|
||||
names:
|
||||
"{{ my_phone_pubkey }}": my-phone
|
||||
"""
|
||||
import asyncio
|
||||
import re
|
||||
import struct
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule
|
||||
|
||||
try:
|
||||
from bleak import BleakClient
|
||||
|
||||
HAS_BLEAK = True
|
||||
except ImportError:
|
||||
HAS_BLEAK = False
|
||||
|
||||
RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e"
|
||||
TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e"
|
||||
CMD_APP_START = 1
|
||||
CMD_GET_CONTACTS = 4
|
||||
CMD_ADD_UPDATE_CONTACT = 9
|
||||
CMD_REMOVE_CONTACT = 15
|
||||
ERR_TABLE_FULL = 3
|
||||
FLAG_FAV = 0x01
|
||||
RESP_OK = 0
|
||||
RESP_ERR = 1
|
||||
RESP_CONTACTS_START = 2
|
||||
RESP_CONTACT = 3
|
||||
RESP_END = 4
|
||||
RESP_SELF_INFO = 5
|
||||
FLAG_REMOTE_CLI = 0x10
|
||||
HEX64 = re.compile(r"^[0-9a-f]{64}$")
|
||||
# CONTACT frame: code pub[32] type flags out_path_len out_path[64] name[32]
|
||||
# last_advert[4] lat[4] lon[4] lastmod[4]
|
||||
OFF_FLAGS = 1 + 32 + 1
|
||||
OFF_NAME = 1 + 32 + 3 + 64
|
||||
OFF_LAST_ADVERT = OFF_NAME + 32
|
||||
CONTACT_LEN = 1 + 32 + 3 + 64 + 32 + 16
|
||||
|
||||
|
||||
class Ble:
|
||||
def __init__(self, client):
|
||||
self.c = client
|
||||
self.q = asyncio.Queue()
|
||||
|
||||
async def start(self):
|
||||
await self.c.start_notify(TX, lambda _, d: self.q.put_nowait(bytes(d)))
|
||||
|
||||
async def send(self, frame, want, timeout=10):
|
||||
await self.c.write_gatt_char(RX, frame, response=True)
|
||||
while True:
|
||||
f = await asyncio.wait_for(self.q.get(), timeout)
|
||||
if f and f[0] in want:
|
||||
return f
|
||||
|
||||
|
||||
def new_contact_frame(pubkey, name, flags):
|
||||
nm = name.encode()[:31].ljust(32, b"\0")
|
||||
return (
|
||||
bytes([CMD_ADD_UPDATE_CONTACT])
|
||||
+ bytes.fromhex(pubkey)
|
||||
+ bytes([1, flags, 0xFF])
|
||||
+ bytes(64)
|
||||
+ nm
|
||||
+ struct.pack("<I", 0)
|
||||
)
|
||||
|
||||
|
||||
async def work(module, mac, admins, names):
|
||||
want = {pk.lower(): names.get(pk) or ("acl-" + pk[:8]) for pk in admins}
|
||||
async with BleakClient(mac, timeout=30) as client:
|
||||
ble = Ble(client)
|
||||
await ble.start()
|
||||
si = await ble.send(bytes([CMD_APP_START, 3]) + bytes(6) + b"ansible", {RESP_SELF_INFO})
|
||||
self_pub = si[4:36].hex()
|
||||
await ble.send(bytes([CMD_GET_CONTACTS]), {RESP_CONTACTS_START})
|
||||
contacts = {}
|
||||
while True:
|
||||
f = await asyncio.wait_for(ble.q.get(), 15)
|
||||
if f[0] == RESP_END:
|
||||
break
|
||||
if f[0] == RESP_CONTACT and len(f) >= CONTACT_LEN - 4:
|
||||
contacts[f[1:33].hex()] = f
|
||||
plan = [] # (pubkey, name, old_flags or None, new_flags)
|
||||
for pk, f in contacts.items():
|
||||
has = bool(f[OFF_FLAGS] & FLAG_REMOTE_CLI)
|
||||
if has != (pk in want):
|
||||
plan.append(
|
||||
(
|
||||
pk,
|
||||
f[OFF_NAME : OFF_NAME + 32].split(b"\0")[0].decode(errors="replace") or pk[:8],
|
||||
f[OFF_FLAGS],
|
||||
f[OFF_FLAGS] ^ FLAG_REMOTE_CLI,
|
||||
)
|
||||
)
|
||||
for pk, name in want.items():
|
||||
if pk not in contacts and pk != self_pub:
|
||||
plan.append((pk, name, None, FLAG_REMOTE_CLI))
|
||||
evicted = []
|
||||
|
||||
def victim():
|
||||
cands = [
|
||||
(struct.unpack_from("<I", f, OFF_LAST_ADVERT)[0], pk)
|
||||
for pk, f in contacts.items()
|
||||
if pk not in want and not f[OFF_FLAGS] & (FLAG_FAV | FLAG_REMOTE_CLI)
|
||||
]
|
||||
return min(cands)[1] if cands else None
|
||||
|
||||
if not module.check_mode:
|
||||
for pk, name, old, new in plan:
|
||||
if old is None:
|
||||
frame = new_contact_frame(pk, name, new)
|
||||
else:
|
||||
f = bytearray(contacts[pk])
|
||||
f[0] = CMD_ADD_UPDATE_CONTACT
|
||||
f[OFF_FLAGS] = new
|
||||
frame = bytes(f[: CONTACT_LEN - 4]) # without lastmod: the node stamps it
|
||||
r = await ble.send(frame, {RESP_OK, RESP_ERR})
|
||||
if r[0] == RESP_ERR and r[1:2] == bytes([ERR_TABLE_FULL]) and old is None:
|
||||
v = victim()
|
||||
if v is None:
|
||||
raise RuntimeError("contact table full and nothing safe to remove")
|
||||
vf = contacts.pop(v)
|
||||
rr = await ble.send(bytes([CMD_REMOVE_CONTACT]) + bytes.fromhex(v), {RESP_OK, RESP_ERR})
|
||||
if rr[0] != RESP_OK:
|
||||
raise RuntimeError(f"could not remove {v[:12]} to make room")
|
||||
evicted.append(
|
||||
{"pubkey": v, "name": vf[OFF_NAME : OFF_NAME + 32].split(b"\0")[0].decode(errors="replace")}
|
||||
)
|
||||
r = await ble.send(frame, {RESP_OK, RESP_ERR})
|
||||
if r[0] != RESP_OK:
|
||||
raise RuntimeError(f"companion refused {name} ({pk[:12]}): error {r[1:2].hex()}")
|
||||
return self_pub, len(contacts), plan, evicted
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"mac": {"type": "str", "required": True},
|
||||
"admins": {"type": "list", "elements": "str", "required": True},
|
||||
"names": {"type": "dict", "default": {}},
|
||||
"timeout": {"type": "int", "default": 120},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
if not HAS_BLEAK:
|
||||
module.fail_json(msg="bleak is required on the BLE host")
|
||||
for pk in module.params["admins"]:
|
||||
if not HEX64.match(pk.lower()):
|
||||
module.fail_json(msg=f"admin pubkey must be 64 hex: {pk}")
|
||||
mac = module.params["mac"]
|
||||
_rc, info, _err = module.run_command(["bluetoothctl", "info", mac])
|
||||
if "Connected: yes" in info:
|
||||
module.fail_json(msg=f"{mac} is held by another client on this host (a phone or desktop app?) -- nothing sent")
|
||||
if "Bonded: yes" not in info:
|
||||
module.fail_json(msg=f"{mac} has no bond on this host -- pair it first (bluetoothctl pair)")
|
||||
try:
|
||||
self_pub, n, plan, evicted = asyncio.run(
|
||||
asyncio.wait_for(
|
||||
work(module, mac, module.params["admins"], module.params["names"]), module.params["timeout"]
|
||||
)
|
||||
)
|
||||
except Exception as e: # noqa: BLE001 -- BLE/GATT errors come in many types
|
||||
module.fail_json(msg=f"{type(e).__name__}: {e}")
|
||||
lines_before = sorted(
|
||||
f"{pk[:12]} {name}" for pk, name, old, new in plan if old is not None and old & FLAG_REMOTE_CLI
|
||||
)
|
||||
lines_after = sorted(f"{pk[:12]} {name}" for pk, name, old, new in plan if new & FLAG_REMOTE_CLI)
|
||||
module.exit_json(
|
||||
changed=bool(plan),
|
||||
self_pubkey=self_pub,
|
||||
contacts=n,
|
||||
evicted=evicted,
|
||||
plan=[
|
||||
{"pubkey": pk, "name": name, "add_contact": old is None, "remote_cli": bool(new & FLAG_REMOTE_CLI)}
|
||||
for pk, name, old, new in plan
|
||||
],
|
||||
diff={"before": "\n".join(lines_before) + "\n", "after": "\n".join(lines_after) + "\n"},
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,125 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_fairness
|
||||
short_description: Per-origin advert window and fairness dry-run of a MeshCore repeater, over RF
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- Reads `fairness advert` and `fairness dryrun`, sends only what differs and
|
||||
reads both again to prove it took (meshcore-tth firmware).
|
||||
- The advert window forwards each origin's flood advert at most once per
|
||||
C(advert_hours) (0 = off). Dry-run counts every verdict of the window and
|
||||
of the FairnessLimiter buckets but forwards anyway -- for sizing a setting
|
||||
on a live mast against CoreScope before it bites.
|
||||
- The counters (held, airtime, cache use, evictions) are returned as
|
||||
C(stats); they live in RAM and restart from zero on every reboot.
|
||||
- A node whose firmware does not know the commands is reported as skipped
|
||||
(flash it first) instead of failing the run.
|
||||
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}
|
||||
password: {description: Admin password (empty = blank login)., type: str, default: ""}
|
||||
advert_hours:
|
||||
description: Advert window in hours, 0-720; 0 = off. Omit to leave it alone.
|
||||
type: int
|
||||
dry_run:
|
||||
description: Count but do not shed. Omit to leave it alone.
|
||||
type: bool
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: One flood advert per origin and 12 h, counted only
|
||||
tth.meshcore.meshcore_fairness:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
advert_hours: 12
|
||||
dry_run: true
|
||||
"""
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
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 (
|
||||
parse_fairness_advert,
|
||||
parse_fairness_dry,
|
||||
)
|
||||
|
||||
EXPECT = r"^(advert window|OK - fairness dry-run|fairness dry-run|Err|Unknown|\?)"
|
||||
|
||||
|
||||
async def read(link):
|
||||
adv_reply = await link.cli("fairness advert", EXPECT)
|
||||
adv = parse_fairness_advert(adv_reply)
|
||||
dry = parse_fairness_dry(await link.cli("fairness dryrun", EXPECT)) if adv is not None else None
|
||||
return adv, dry, adv_reply
|
||||
|
||||
|
||||
async def work(module, link):
|
||||
want_h, want_dry = module.params["advert_hours"], module.params["dry_run"]
|
||||
await link.open()
|
||||
try:
|
||||
await link.login()
|
||||
adv, dry, reply = await read(link)
|
||||
if adv is None or dry is None:
|
||||
return {
|
||||
"changed": False,
|
||||
"skipped": True,
|
||||
"msg": f"firmware has no advert window ({reply!r}) -- flash it first",
|
||||
}
|
||||
cmds = []
|
||||
if want_h is not None and adv["hours"] != want_h:
|
||||
cmds.append(f"fairness advert {want_h}")
|
||||
if want_dry is not None and dry != want_dry:
|
||||
cmds.append(f"fairness dryrun {'on' if want_dry else 'off'}")
|
||||
before = {"advert_hours": adv["hours"], "dry_run": dry}
|
||||
after = {
|
||||
"advert_hours": adv["hours"] if want_h is None else want_h,
|
||||
"dry_run": dry if want_dry is None else want_dry,
|
||||
}
|
||||
result = {
|
||||
"changed": bool(cmds),
|
||||
"commands": cmds,
|
||||
"stats": adv,
|
||||
"diff": {"before": f"{before}\n", "after": f"{after}\n"},
|
||||
}
|
||||
if module.check_mode or not cmds:
|
||||
return result
|
||||
for cmd in cmds:
|
||||
r = await link.cli(cmd, EXPECT)
|
||||
if r.startswith(("Err", "Unknown", "?")):
|
||||
raise LinkError(f"`{cmd}`: {r}")
|
||||
adv, dry, reply = await read(link)
|
||||
if adv is None or {"advert_hours": adv["hours"], "dry_run": dry} != after:
|
||||
raise LinkError(f"fairness reads {reply!r} / dry-run {dry}, expected {after}")
|
||||
result["stats"] = adv
|
||||
return result
|
||||
finally:
|
||||
await link.close()
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"transport": {"type": "dict", "required": True},
|
||||
"target": {"type": "str", "required": True},
|
||||
"password": {"type": "str", "default": "", "no_log": True},
|
||||
"advert_hours": {"type": "int"},
|
||||
"dry_run": {"type": "bool"},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
if not HAS_MESHCORE:
|
||||
module.fail_json(msg=missing_required_lib("meshcore"))
|
||||
h = module.params["advert_hours"]
|
||||
if h is not None and not 0 <= h <= 720:
|
||||
module.fail_json(msg="advert_hours must be 0-720")
|
||||
link = Link(module.params["transport"], module.params["target"], module.params["password"])
|
||||
try:
|
||||
result = run(work(module, link))
|
||||
except LinkError as e:
|
||||
module.fail_json(msg=str(e), log=link.log)
|
||||
module.exit_json(log=link.log, **result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,124 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_filter
|
||||
short_description: Message age limit and filter dry-run of a MeshCore repeater, over RF
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- Reads `filter age` and `filter dryrun`, sends only what differs and reads
|
||||
both again to prove it took (meshcore-tth firmware).
|
||||
- The age limit refuses to forward group texts on the channels the repeater
|
||||
can decrypt whose sender timestamp is older than C(age_minutes) (0 = off).
|
||||
It judges the SENDER's clock, so companions without a time sync are
|
||||
dropped too -- keep it in days. It is inactive while the repeater's own
|
||||
clock is unset; a clock running ahead is not detected.
|
||||
- Dry-run counts every verdict of `filter` (channel hash, age, sender names)
|
||||
but forwards anyway.
|
||||
- The drop counter is returned as C(stats); it restarts from zero on reboot.
|
||||
- A node whose firmware does not know the commands is reported as skipped
|
||||
(flash it first) instead of failing the run.
|
||||
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}
|
||||
password: {description: Admin password (empty = blank login)., type: str, default: ""}
|
||||
age_minutes:
|
||||
description: Age limit in minutes, 0-10080; 0 = off. Omit to leave it alone.
|
||||
type: int
|
||||
dry_run:
|
||||
description: Count but do not drop. Omit to leave it alone.
|
||||
type: bool
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Drop group texts older than a day
|
||||
tth.meshcore.meshcore_filter:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
age_minutes: 1440
|
||||
dry_run: false
|
||||
"""
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
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 parse_filter_age, parse_filter_dry
|
||||
|
||||
EXPECT = r"^(filter age|OK - filter|filter dry-run|Err|Unknown|\?)"
|
||||
|
||||
|
||||
async def read(link):
|
||||
age_reply = await link.cli("filter age", EXPECT)
|
||||
age = parse_filter_age(age_reply)
|
||||
dry = parse_filter_dry(await link.cli("filter dryrun", EXPECT)) if age is not None else None
|
||||
return age, dry, age_reply
|
||||
|
||||
|
||||
async def work(module, link):
|
||||
want_min, want_dry = module.params["age_minutes"], module.params["dry_run"]
|
||||
await link.open()
|
||||
try:
|
||||
await link.login()
|
||||
age, dry, reply = await read(link)
|
||||
if age is None or dry is None:
|
||||
return {
|
||||
"changed": False,
|
||||
"skipped": True,
|
||||
"msg": f"firmware has no message age limit ({reply!r}) -- flash it first",
|
||||
}
|
||||
cmds = []
|
||||
if want_min is not None and age["minutes"] != want_min:
|
||||
cmds.append(f"filter age {want_min}" if want_min else "filter age off")
|
||||
if want_dry is not None and dry != want_dry:
|
||||
cmds.append(f"filter dryrun {'on' if want_dry else 'off'}")
|
||||
before = {"age_minutes": age["minutes"], "dry_run": dry}
|
||||
after = {
|
||||
"age_minutes": age["minutes"] if want_min is None else want_min,
|
||||
"dry_run": dry if want_dry is None else want_dry,
|
||||
}
|
||||
result = {
|
||||
"changed": bool(cmds),
|
||||
"commands": cmds,
|
||||
"stats": age,
|
||||
"diff": {"before": f"{before}\n", "after": f"{after}\n"},
|
||||
}
|
||||
if module.check_mode or not cmds:
|
||||
return result
|
||||
for cmd in cmds:
|
||||
r = await link.cli(cmd, EXPECT)
|
||||
if r.startswith(("Err", "Unknown", "?")):
|
||||
raise LinkError(f"`{cmd}`: {r}")
|
||||
age, dry, reply = await read(link)
|
||||
if age is None or {"age_minutes": age["minutes"], "dry_run": dry} != after:
|
||||
raise LinkError(f"filter reads {reply!r} / dry-run {dry}, expected {after}")
|
||||
result["stats"] = age
|
||||
return result
|
||||
finally:
|
||||
await link.close()
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"transport": {"type": "dict", "required": True},
|
||||
"target": {"type": "str", "required": True},
|
||||
"password": {"type": "str", "default": "", "no_log": True},
|
||||
"age_minutes": {"type": "int"},
|
||||
"dry_run": {"type": "bool"},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
if not HAS_MESHCORE:
|
||||
module.fail_json(msg=missing_required_lib("meshcore"))
|
||||
m = module.params["age_minutes"]
|
||||
if m is not None and not 0 <= m <= 10080:
|
||||
module.fail_json(msg="age_minutes must be 0-10080")
|
||||
link = Link(module.params["transport"], module.params["target"], module.params["password"])
|
||||
try:
|
||||
result = run(work(module, link))
|
||||
except LinkError as e:
|
||||
module.fail_json(msg=str(e), log=link.log)
|
||||
module.exit_json(log=link.log, **result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,126 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_filter_hash
|
||||
short_description: Channel-hash deny-forward list (`filter hash`) of a MeshCore repeater, over RF
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- Reads `filter hash`, sends only the difference (`filter hash add|del <hex>`)
|
||||
and reads the list again to prove it took. The repeater then refuses to
|
||||
FORWARD GRP_TXT/GRP_DATA whose channel byte is listed; reception and
|
||||
rxlog/pktfeed are untouched (meshcore-tth firmware).
|
||||
- The hash is one byte, so an entry hits every channel whose key hashes to it.
|
||||
- A node whose firmware does not know the command is reported as skipped
|
||||
(flash it first) instead of failing the run.
|
||||
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}
|
||||
password: {description: Admin password (empty = blank login)., type: str, default: ""}
|
||||
hashes:
|
||||
description:
|
||||
- Channel hash bytes to deny, e.g. C(["43"]). Up to 8 (firmware limit).
|
||||
- C(43/60) throttles instead of blocking -- one packet of that byte per
|
||||
60 s is forwarded (meshcore-tth firmware, `filter hash add 43 60`).
|
||||
type: list
|
||||
elements: raw
|
||||
required: true
|
||||
exclusive:
|
||||
description: Remove listed hashes that are not in C(hashes).
|
||||
type: bool
|
||||
default: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Block channel 0x43, throttle 0x09 to one packet a minute
|
||||
tth.meshcore.meshcore_filter_hash:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
hashes: ["43", "09/60"]
|
||||
"""
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
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 (
|
||||
entry_hash,
|
||||
filter_hash_cmd,
|
||||
norm_entry,
|
||||
parse_filter_hash,
|
||||
plan_filter_hash,
|
||||
)
|
||||
|
||||
EXPECT = r"^(filter hash:|Err|Unknown|\?)"
|
||||
|
||||
|
||||
async def read(link):
|
||||
reply = await link.cli("filter hash", EXPECT)
|
||||
return parse_filter_hash(reply), reply
|
||||
|
||||
|
||||
async def work(module, link):
|
||||
await link.open()
|
||||
try:
|
||||
await link.login()
|
||||
parsed, reply = await read(link)
|
||||
if parsed is None:
|
||||
return {
|
||||
"changed": False,
|
||||
"skipped": True,
|
||||
"msg": f"firmware does not know `filter hash` ({reply!r}) -- flash it first",
|
||||
}
|
||||
current, dropped = parsed
|
||||
add, remove = plan_filter_hash(current, module.params["hashes"], module.params["exclusive"])
|
||||
added = {entry_hash(e) for e in add}
|
||||
after = [h for h in current if h not in remove and entry_hash(h) not in added] + add
|
||||
result = {
|
||||
"changed": bool(add or remove),
|
||||
"add": add,
|
||||
"remove": remove,
|
||||
"dropped": dropped,
|
||||
"diff": {"before": " ".join(current) + "\n", "after": " ".join(after) + "\n"},
|
||||
}
|
||||
if module.check_mode or not (add or remove):
|
||||
return result
|
||||
for cmd in [filter_hash_cmd(h, delete=True) for h in remove] + [filter_hash_cmd(h) for h in add]:
|
||||
r = await link.cli(cmd, EXPECT)
|
||||
if not r.startswith("filter hash:"):
|
||||
raise LinkError(f"`{cmd}`: {r}")
|
||||
parsed, reply = await read(link)
|
||||
if parsed is None or sorted(parsed[0]) != sorted(after):
|
||||
raise LinkError(f"deny list reads {reply!r}, expected {after}")
|
||||
return result
|
||||
finally:
|
||||
await link.close()
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"transport": {"type": "dict", "required": True},
|
||||
"target": {"type": "str", "required": True},
|
||||
"password": {"type": "str", "default": "", "no_log": True},
|
||||
"hashes": {"type": "list", "elements": "raw", "required": True},
|
||||
"exclusive": {"type": "bool", "default": True},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
if not HAS_MESHCORE:
|
||||
module.fail_json(msg=missing_required_lib("meshcore"))
|
||||
try:
|
||||
hashes = [norm_entry(h) for h in module.params["hashes"]]
|
||||
except ValueError as e:
|
||||
module.fail_json(msg=str(e))
|
||||
if len({entry_hash(h) for h in hashes}) != len(set(hashes)):
|
||||
module.fail_json(msg="one channel hash listed with two different intervals")
|
||||
if len(set(hashes)) > 8:
|
||||
module.fail_json(msg="firmware holds at most 8 channel hashes")
|
||||
link = Link(module.params["transport"], module.params["target"], module.params["password"])
|
||||
try:
|
||||
result = run(work(module, link))
|
||||
except LinkError as e:
|
||||
module.fail_json(msg=str(e), log=link.log)
|
||||
module.exit_json(log=link.log, **result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,106 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_fw_facts
|
||||
short_description: Firmware version of a MeshCore repeater or companion, over RF
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- Logs in as admin and reads `ver`. A companion (C(companion), fw 1.18+ /
|
||||
Solo 2.0+) answers `ver` as remote CLI only to a contact in its ACL (the
|
||||
"remote CLI" flag 0x10, see meshcore_companion_acl); anyone else gets silence. With C(wanted), also says whether the
|
||||
node is current, outdated, dirty (built from a dirty tree, '+') or unknown.
|
||||
- Returns C(clock_skew), node clock minus ours in seconds, from the
|
||||
timestamp on the node's `ver` reply.
|
||||
- Read-only; runs in check mode too.
|
||||
options:
|
||||
transport: {description: Companion to talk through (see meshcore_acl)., type: dict, required: true}
|
||||
target: {description: Full 64-hex pubkey of the node., type: str, required: true}
|
||||
name: {description: Name for the contact if the companion has to create it., type: str}
|
||||
companion: {description: "The target is a companion (remote CLI, ACL = flagged contacts).", type: bool, default: false}
|
||||
password: {description: Admin password (empty = blank login)., type: str, default: ""}
|
||||
wanted: {description: The version stamp the node should run (from the built ELF)., type: str}
|
||||
clock_sync:
|
||||
description:
|
||||
- Send `clock sync` first (sets the node clock from our timestamp when it is
|
||||
behind). A freshly flashed node boots in May 2024, and clients drop
|
||||
replies stamped that far back. Fire-and-forget, its own reply may be the
|
||||
one that gets dropped.
|
||||
type: bool
|
||||
default: false
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Which firmware runs there
|
||||
tth.meshcore.meshcore_fw_facts:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
clock_sync: true
|
||||
register: fw
|
||||
|
||||
- name: Show it
|
||||
ansible.builtin.debug:
|
||||
msg: "{{ fw.version }}, clock off by {{ fw.clock_skew | default('?') }} s"
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_fw import fw_state, parse_version
|
||||
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, Link, LinkError, run
|
||||
|
||||
|
||||
async def work(module, link):
|
||||
await link.open()
|
||||
try:
|
||||
if not module.params["companion"]:
|
||||
await link.login()
|
||||
if module.params["clock_sync"] and not module.check_mode:
|
||||
await link.mc.commands.send_cmd(link.contact, "clock sync")
|
||||
link.log.append("$ clock sync (not waiting for the reply)")
|
||||
await asyncio.sleep(3)
|
||||
reply = await link.cli("ver", r"\(Build: ")
|
||||
finally:
|
||||
await link.close()
|
||||
version = parse_version(reply)
|
||||
out = {"changed": False, "ver": reply, "version": version, "name": link.name()}
|
||||
# Node clock minus ours, from the timestamp the node put on its `ver` reply:
|
||||
# costs no extra packet and works for companions too (they have no `clock`
|
||||
# CLI). Positive = node ahead. Accurate to the reply latency (seconds).
|
||||
if link.last_reply_ts:
|
||||
out["clock_skew"] = int(link.last_reply_ts - link.last_reply_at)
|
||||
if module.params["wanted"]:
|
||||
out["state"] = fw_state(version, module.params["wanted"])
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"transport": {"type": "dict", "required": True},
|
||||
"target": {"type": "str", "required": True},
|
||||
"password": {"type": "str", "default": "", "no_log": True},
|
||||
"wanted": {"type": "str"},
|
||||
"clock_sync": {"type": "bool", "default": False},
|
||||
"companion": {"type": "bool", "default": False},
|
||||
"name": {"type": "str"},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
if not HAS_MESHCORE:
|
||||
module.fail_json(msg=missing_required_lib("meshcore"))
|
||||
link = Link(
|
||||
module.params["transport"],
|
||||
module.params["target"],
|
||||
module.params["password"],
|
||||
companion=module.params["companion"],
|
||||
name=module.params["name"],
|
||||
)
|
||||
try:
|
||||
result = run(work(module, link))
|
||||
except (LinkError, ValueError) as e:
|
||||
module.fail_json(msg=str(e), log=link.log)
|
||||
module.exit_json(log=link.log, **result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,105 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_prefs
|
||||
short_description: CLI prefs (`get`/`set`) of a MeshCore repeater, over RF
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- For every key, `get <key>`; when it differs from the wanted value,
|
||||
`set <key> <value>` 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.
|
||||
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}
|
||||
password: {description: Admin password (empty = blank login)., type: str, default: ""}
|
||||
prefs:
|
||||
description: "Map of pref key -> wanted value, e.g. C({repeat: on, advert.interval: 120})."
|
||||
type: dict
|
||||
required: true
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Two-byte path hash, no zero-hop adverts, flood advert every 47 h
|
||||
tth.meshcore.meshcore_prefs:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
prefs:
|
||||
path.hash.mode: 1
|
||||
advert.interval: 0
|
||||
flood.advert.interval: 47
|
||||
"""
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
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 work(module, link):
|
||||
prefs = module.params["prefs"]
|
||||
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)
|
||||
result = {
|
||||
"changed": bool(changes),
|
||||
"set": changes,
|
||||
"diff": {
|
||||
"before": "".join(f"{k}: {before[k]}\n" for k in sorted(changes)),
|
||||
"after": "".join(f"{k}: {changes[k]}\n" for k in sorted(changes)),
|
||||
},
|
||||
}
|
||||
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}")
|
||||
return result
|
||||
finally:
|
||||
await link.close()
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"transport": {"type": "dict", "required": True},
|
||||
"target": {"type": "str", "required": True},
|
||||
"password": {"type": "str", "default": "", "no_log": True},
|
||||
"prefs": {"type": "dict", "required": True},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
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}")
|
||||
link = Link(module.params["transport"], module.params["target"], module.params["password"])
|
||||
try:
|
||||
result = run(work(module, link))
|
||||
except LinkError as e:
|
||||
module.fail_json(msg=str(e), log=link.log)
|
||||
module.exit_json(log=link.log, **result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,139 @@
|
||||
# Copyright: (c) 2026, TeTeHacko <tth@rfa.cz>
|
||||
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
|
||||
DOCUMENTATION = r"""
|
||||
module: meshcore_region
|
||||
short_description: Region tree, home region and default scope of a MeshCore repeater, over RF
|
||||
author: TeTeHacko (@TeTeHacko)
|
||||
description:
|
||||
- Reads the tree with `region`, puts/removes/re-parents regions and switches
|
||||
flood allow/deny so the tree matches I(regions) exactly (the wildcard root
|
||||
`*` always stays), sets the home region and the default scope, then
|
||||
`region save` -- without it the changes are RAM-only and a reboot drops them.
|
||||
Reads the tree back and fails on a mismatch.
|
||||
- The CLI reply is cut at ~160 bytes. A tree whose listing does not fit cannot
|
||||
be read reliably, so the module refuses to manage it.
|
||||
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}
|
||||
password: {description: Admin password (empty = blank login)., type: str, default: ""}
|
||||
regions:
|
||||
description: Wanted regions, C({name, parent (default "*"), flood (default true)}), names without "#".
|
||||
type: list
|
||||
elements: dict
|
||||
required: true
|
||||
home: {description: Home region name (omit to leave it)., type: str}
|
||||
default_scope: {description: "Default flood scope region name, or C(<null>); omit to leave it.", type: str}
|
||||
"""
|
||||
|
||||
EXAMPLES = r"""
|
||||
- name: Region tree with a home region
|
||||
tth.meshcore.meshcore_region:
|
||||
transport: {type: tcp, host: 127.0.0.1, port: 5000}
|
||||
target: "{{ mc_target }}"
|
||||
password: "{{ vault_meshcore_admin_password }}"
|
||||
regions:
|
||||
- {name: cz}
|
||||
- {name: cz-ulk, parent: cz}
|
||||
home: cz-ulk
|
||||
"""
|
||||
|
||||
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
|
||||
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 (
|
||||
expected_tree,
|
||||
parse_regions,
|
||||
plan_regions,
|
||||
region_reply_truncated,
|
||||
render_regions,
|
||||
)
|
||||
|
||||
EXPECT = {
|
||||
"put": r"^(OK|Err)",
|
||||
"remove": r"^(OK|Err)",
|
||||
"allowf": r"^(OK|Err)",
|
||||
"denyf": r"^(OK|Err)",
|
||||
"home": r"(home is now|^Err)",
|
||||
"default": r"(default scope is now|^Err)",
|
||||
"save": r"^(OK|Err)",
|
||||
}
|
||||
|
||||
|
||||
async def read_tree(link):
|
||||
text = await link.cli("region", r"^\*")
|
||||
if region_reply_truncated(text):
|
||||
raise LinkError(f"region list is cut at the CLI reply limit ({len(text)} B) -- cannot manage it")
|
||||
return text, parse_regions(text)
|
||||
|
||||
|
||||
def default_wanted(name):
|
||||
return None if name is None else name.lstrip("#")
|
||||
|
||||
|
||||
async def work(module, link):
|
||||
p = module.params
|
||||
regions = [
|
||||
{**r, "name": r["name"].lstrip("#"), "parent": (r.get("parent") or "*").lstrip("#")} for r in p["regions"]
|
||||
]
|
||||
await link.open()
|
||||
try:
|
||||
await link.login()
|
||||
_text, tree = await read_tree(link)
|
||||
cmds = plan_regions(tree, regions, p["home"])
|
||||
dflt = None
|
||||
if p["default_scope"] is not None:
|
||||
reply = await link.cli("region default", r"default scope is")
|
||||
dflt = reply.split("default scope is", 1)[1].strip().lstrip("#")
|
||||
if dflt != default_wanted(p["default_scope"]):
|
||||
cmds.append(f"region default {p['default_scope']}")
|
||||
want_dflt = default_wanted(p["default_scope"])
|
||||
result = {
|
||||
"changed": bool(cmds),
|
||||
"commands": cmds,
|
||||
"diff": {
|
||||
"before": render_regions(tree) + (f"default scope {dflt}\n" if dflt is not None else ""),
|
||||
"after": render_regions(expected_tree(tree, regions, p["home"]))
|
||||
+ (f"default scope {want_dflt}\n" if want_dflt is not None else ""),
|
||||
},
|
||||
}
|
||||
if module.check_mode or not cmds:
|
||||
return result
|
||||
for c in cmds:
|
||||
reply = await link.cli(c, EXPECT[c.split()[1]])
|
||||
if reply.startswith("Err"):
|
||||
raise LinkError(f"`{c}`: {reply}")
|
||||
reply = await link.cli("region save", EXPECT["save"])
|
||||
if not reply.startswith("OK"):
|
||||
raise LinkError(f"`region save`: {reply}")
|
||||
_text, after = await read_tree(link)
|
||||
left = plan_regions(after, regions, p["home"])
|
||||
if left:
|
||||
raise LinkError(f"region tree after apply still differs: {left}")
|
||||
return result
|
||||
finally:
|
||||
await link.close()
|
||||
|
||||
|
||||
def main():
|
||||
module = AnsibleModule(
|
||||
argument_spec={
|
||||
"transport": {"type": "dict", "required": True},
|
||||
"target": {"type": "str", "required": True},
|
||||
"password": {"type": "str", "default": "", "no_log": True},
|
||||
"regions": {"type": "list", "elements": "dict", "required": True},
|
||||
"home": {"type": "str"},
|
||||
"default_scope": {"type": "str"},
|
||||
},
|
||||
supports_check_mode=True,
|
||||
)
|
||||
if not HAS_MESHCORE:
|
||||
module.fail_json(msg=missing_required_lib("meshcore"))
|
||||
link = Link(module.params["transport"], module.params["target"], module.params["password"])
|
||||
try:
|
||||
result = run(work(module, link))
|
||||
except LinkError as e:
|
||||
module.fail_json(msg=str(e), log=link.log)
|
||||
module.exit_json(log=link.log, **result)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user