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,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