# Copyright: (c) 2026, TeTeHacko # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt) DOCUMENTATION = r""" module: meshcore_fw_ota short_description: OTA firmware update of a meshcore-tth repeater, over RF or its BLE console author: TeTeHacko (@TeTeHacko) description: - Updates a repeater that runs an C(-ota) image of meshcore-tth (the C(fw) commands of src/helpers/FwUpdate) from the packages of a release (C(.mcfw), tools/ota_pack.py), and applies it. The node checks each package itself (Ed25519 signature, target, base image, not older) and refuses a wrong one after its first chunks. - Reads C(fw status) and picks the package that fits the image the node runs. C(changed=false) when the node already runs the image, C(no_package=true) (not a failure) when no package starts from its image or the node has no C(fw) at all -- then the caller falls back to a full DFU. - Over RF (a companion transport, as the other modules) only deltas go, the node refuses a full image there. Chunks are binary requests (128 B, no reply, missing ones found by a bitmap query), with text chunks as the fallback, paced by an airtime budget (C(duty)). A 28 kB delta over two hops took 40 min at 3 %. - Over the node's BLE console (C(transport.type=ble_console)) nothing goes on air and a full image may go too. Prefer it wherever a host with a bond hears the node. - A power cut during the ~30 s rewrite after C(apply) leaves the node in its bootloader (no half image runs; recovery = DFU on site). The node refuses to apply below its battery gate. - In check mode it reads C(fw status) and says which package would go. options: transport: description: - "Companion to talk through (see meshcore_acl), or the node's own BLE console C({type: ble_console, address}), bonded on the host the module runs on." type: dict required: true target: {description: Full 64-hex pubkey of the node (not needed for ble_console)., type: str} name: {description: Name for the contact if the companion has to create it., type: str} password: {description: Admin password (empty = blank login; not used on ble_console)., type: str, default: ""} packages: description: - A C(.mcfw) package, or a directory with the packages of one release (the full image and its deltas), on the host the module runs on. type: path required: true apply: {description: Apply after a good C(fw verify) (else the package stays staged)., type: bool, default: true} duty: description: - RF only. Airtime budget in percent per hour (token bucket). Counts what the transfer puts on the channel, request and reply times (hops + 1). 869.4-869.65 MHz allows 10 %, other sub-bands 1 %. type: float default: 3 gap: {description: RF only. Pause in seconds after every reply., type: float, default: 5} resume: description: - Continue a transfer that stopped (the node keeps what it got until the next C(fw begin) or a reboot) -- no C(fw begin), only what C(fw missing) lists. type: bool default: false apply_wait: {description: Seconds to wait after C(fw apply) before reading the new version., type: int, default: 60} requirements: [meshcore (RF), bleak (ble_console)] """ EXAMPLES = r""" - name: Update over RF through the companion next to the mast tth.meshcore.meshcore_fw_ota: transport: {type: tcp, host: 127.0.0.1, port: 5000, expect_freq: 869.432} target: "{{ mc_target }}" password: "{{ vault_meshcore_admin_password }}" packages: /tmp/ota/ # the .mcfw files of one release duty: 3 async: 7200 poll: 30 register: ota - name: The same over the node's BLE console (bonded on this host) tth.meshcore.meshcore_fw_ota: transport: {type: ble_console, address: "AA:BB:CC:DD:EE:FF"} packages: /tmp/ota/ - name: No package fits the node's image -- full DFU instead ansible.builtin.debug: msg: "{{ ota.base }}: no delta" when: ota.no_package """ RETURN = r""" state: description: current | no_package | would_update | staged | applied returned: always type: str package: description: Name of the package that went (or would go). returned: when one fits type: str kind: description: delta | full returned: when one fits type: str base: description: Size and sha256 prefix of the image the node ran. returned: when the node has fw type: str no_package: description: No package starts from the node's image, or the node has no fw. returned: always type: bool version: description: Version the package installs. returned: when one fits type: str version_after: description: The `ver` reply after the apply, when the node answered. returned: when applied type: str airtime: description: Channel airtime of the transfer in seconds (RF). returned: over RF type: float log: description: Trace of the exchange (no secrets). returned: always type: list elements: str """ import asyncio import base64 import os import random from ansible.module_utils.basic import AnsibleModule, missing_required_lib from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_console import ( HAS_BLEAK, BleConsole, ConsoleError, ) 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_ota import ( BCHUNK, CHUNK, MANIFEST, MAX_FRAME, REPLY_TEXT, REQ_FW, UNIT, Bucket, Package, hops_of, lora_airtime, parse_missing, parse_status, pick, req_frame_len, text_frame_len, text_missing, w_payload, ) try: from meshcore import EventType except ImportError: # HAS_MESHCORE says so EventType = None # what each reply looks like -- a late answer to an earlier command must not pass EXPECT = { "status": r"^(>|ERR|Err|Unknown|\?)", "begin": r"^(OK|ERR|Err)", "w": r"^(ok|ERR|Err)", "list": r"^(>|ERR|Err)", "apply": r"^(OK|ERR|Err)", "ver": r"\(Build: ", } class OtaError(Exception): pass def load_packages(path): names = sorted(f for f in os.listdir(path) if f.endswith(".mcfw")) if os.path.isdir(path) else [path] out = [] for n in names: full = os.path.join(path, n) if os.path.isdir(path) else n with open(full, "rb") as f: out.append(Package(os.path.basename(n), f.read())) if not out: raise OtaError(f"no .mcfw package in {path}") return out class Console: """`fw` commands over the BLE console: local, nothing on air.""" rf = False def __init__(self, transport): self.con = BleConsole(transport["address"]) self.log = self.con.log self.airtime = None async def open(self): await self.con.open() async def close(self): await self.con.close() async def ask(self, line, kind, timeout=5.0, tries=3, quiet=False): del kind # a console answers in order for attempt in range(tries): try: return await self.con.cmd(line, timeout=timeout, quiet=quiet) except ConsoleError: if attempt + 1 == tries: raise return "" async def after_apply(self, wait): await self.con.close() await asyncio.sleep(wait) await self.con.open() class Radio: """`fw` commands as remote admin CLI through a companion, inside an airtime budget.""" rf = True def __init__(self, module): p = module.params self.link = Link(p["transport"], p["target"], p["password"], name=p["name"]) self.log = self.link.log self.bucket = Bucket(p["duty"]) self.gap = p["gap"] self.radio = None @property def airtime(self): return round(self.bucket.used, 1) async def open(self): await self.link.open() si = self.link.mc.self_info or {} self.radio = (int(si["radio_sf"]), float(si["radio_bw"]), int(si["radio_cr"]) - 4) await self.spend(lora_airtime(48, *self.radio)) await self.login() async def login(self): await self.link.login() await self.link.mc.ensure_contacts(follow=True) # the login may have taught it a path self.link.contact = self.link._find_contact() or self.link.contact self.log.append(f"path: {hops_of(self.link.contact)} hops") async def close(self): await self.link.close() async def spend(self, secs): while True: wait = self.bucket.wait_for(secs) if wait == 0: return await asyncio.sleep(wait) def hops(self): return hops_of(self.link.contact or {}) async def ask(self, line, kind, timeout=20.0, tries=4, quiet=False): one = lora_airtime(text_frame_len(line), *self.radio) + lora_airtime( text_frame_len("x" * REPLY_TEXT), *self.radio ) reply = await self.link.cli( line, EXPECT[kind], retries=tries - 1, timeout=timeout, quiet=quiet, before_send=lambda: self.spend(one * (self.hops() + 1)), ) if self.gap: await asyncio.sleep(self.gap) return reply # ── binary chunks (REQ_TYPE_FW_OTA) ────────────────────────────────────── def req_cost(self, payload_len, reply_len=0): t = lora_airtime(req_frame_len(payload_len), *self.radio) if reply_len: t += lora_airtime(req_frame_len(reply_len), *self.radio) return t * (self.hops() + 1) async def send_req(self, payload): if 1 + 32 + len(payload) > MAX_FRAME: raise OtaError(f"binary request of {len(payload)} B exceeds the companion frame") ev = await self.link.mc.commands.send( b"\x32" + bytes.fromhex(self.link.target_pk) + payload, [EventType.MSG_SENT, EventType.ERROR] ) if ev is None or ev.type != EventType.MSG_SENT: return None tag = ev.payload.get("expected_ack") return tag.hex() if isinstance(tag, (bytes, bytearray)) else str(tag) async def write(self, sid, off, chunk): payload = w_payload(sid, off, chunk) c = self.req_cost(len(payload)) await self.spend(c) await self.send_req(payload) # no reply comes: give the packet time to go out along the whole path await asyncio.sleep(max(self.gap, c + 1.0)) async def missing(self, timeout=20.0): """(state, missing unit indices) or None when the node does not answer.""" for _attempt in range(2): await self.spend(self.req_cost(2, 160)) fut = asyncio.get_running_loop().create_future() def got(ev, fut=fut): if not fut.done(): fut.set_result(ev) sub = self.link.mc.subscribe(EventType.BINARY_RESPONSE, got) try: tag = await self.send_req(bytes([REQ_FW, ord("m")])) ev = await asyncio.wait_for(fut, timeout) except TimeoutError: ev = None finally: self.link.mc.unsubscribe(sub) if ev is None or (tag and ev.payload.get("tag") != tag): continue st = parse_missing(bytes.fromhex(ev.payload["data"])) if st is None: continue await asyncio.sleep(self.gap) return st return None async def settled(self): """The bitmap once the node is done checking (state 4 = busy). A lost query after a long round must not throw the round away.""" lost = 0 st = None for _query in range(10): st = await self.missing() if st is None and lost < 4: lost += 1 await asyncio.sleep(10) continue if st is None or st[0] != 4: return st await asyncio.sleep(3) return st async def after_apply(self, wait): await asyncio.sleep(wait) await self.login() async def binary_rounds(io, data, sid): """Binary chunks in rounds; returns the text chunks still to send ([] = all in), or None = no binary.""" if await io.missing() is None: io.log.append("node does not answer binary requests: text chunks") return None todo = list(range((len(data) + BCHUNK - 1) // BCHUNK)) last_miss = 1 << 30 manifest_checked = False for rnd in range(6): for k, i in enumerate(todo): off = i * BCHUNK await io.write(sid, off, data[off : off + BCHUNK]) if not manifest_checked and off + BCHUNK >= MANIFEST and k + 1 < len(todo): # the node checks the manifest as soon as it is in: ask before # the rest goes on air, a refused package would cost the round manifest_checked = True st = await io.settled() if st is not None and st[0] == 3: raise OtaError(f"node refused the package: {await io.ask('fw status', 'status')}") st = await io.settled() if st is None: raise OtaError("no answer to the missing-units query (the node keeps what it has: resume)") state, miss = st io.log.append(f"binary round {rnd + 1}: {len(todo)} chunks sent, {len(miss)} units missing") if state == 3: raise OtaError(f"node refused the package: {await io.ask('fw status', 'status')}") if not miss: return [] if rnd > 0 and len(miss) >= last_miss: io.log.append("binary chunks do not arrive: text chunks for the rest") return sorted({u * UNIT // CHUNK for u in miss}) last_miss = len(miss) todo = sorted({u * UNIT // BCHUNK for u in miss}) raise OtaError("binary transfer did not converge in 6 rounds") async def text_rounds(io, data, todo): """Text chunks (each answered) until `fw missing` says none.""" stuck = 0 for rnd in range(40): for i in todo: off = i * CHUNK r = await io.ask(f"fw w {off} {base64.b64encode(data[off : off + CHUNK]).decode()}", "w", quiet=True) if r != "ok": raise OtaError(f"chunk {off}: {r}") reply = await io.ask("fw missing", "list") new = text_missing(reply) io.log.append(f"text round {rnd + 1}: {len(todo)} chunks sent, missing: {reply[:60]}") if new == []: return if new is None: stuck += 1 # a reply that is no list: ask again next round if stuck > 3: raise OtaError(f"`fw missing` does not answer: {reply}") todo = [] continue new = [o // CHUNK for o in new] stuck = stuck + 1 if new == todo else 0 if stuck > 3: raise OtaError("the same chunks keep missing") todo = new raise OtaError("text transfer did not converge in 40 rounds") async def work(module, io): p = module.params pkgs = load_packages(p["packages"]) out = {"changed": False, "no_package": False} await io.open() try: status = await io.ask("fw status", "status") base = parse_status(status) if base is None: out.update(state="no_package", no_package=True, status=status) io.log.append("no base image in `fw status`: not an -ota build") return out out["base"] = f"{base[0]} {base[1]}" kind, pkg = pick(pkgs, base[1], full_ok=not io.rf) if kind == "current": out.update(state="current", version=pkg.version) return out if kind == "none": out.update(state="no_package", no_package=True) io.log.append( f"no package starts from {base[1]}" + (" (a full image does not go over RF)" if io.rf else "") ) return out out.update(package=pkg.name, kind=kind, version=pkg.version, changed=True) if module.check_mode: out["state"] = "would_update" return out data = pkg.data if p["resume"]: reply = await io.ask("fw missing", "list") todo = text_missing(reply) if todo is None: raise OtaError(f"resume: {reply}") if todo: await text_rounds(io, data, [o // CHUNK for o in todo]) else: sid = random.randint(1, 0xFFFF) # chunks of an earlier transfer are dropped r = await io.ask(f"fw begin {len(data)} {sid}", "begin") if not r.startswith("OK"): raise OtaError(f"fw begin: {r}") todo = None if io.rf: todo = await binary_rounds(io, data, sid) if todo is None: todo = list(range((len(data) + CHUNK - 1) // CHUNK)) if todo: await text_rounds(io, data, todo) r = await io.ask("fw verify", "list", timeout=40) for _poll in range(20): # the node runs it in loop(), not in the handler if "verifying" not in r: break await asyncio.sleep(3) r = await io.ask("fw status", "status") if not r.startswith(">") or "ready" not in r: raise OtaError(f"fw verify: {r}") await io.ask("fw bl", "list") if not p["apply"]: out["state"] = "staged" return out r = await io.ask("fw apply", "apply", timeout=30, tries=1) if not r.startswith("OK"): raise OtaError(f"fw apply: {r}") out["state"] = "applied" try: await io.after_apply(p["apply_wait"]) out["version_after"] = await io.ask("ver", "ver") await io.ask("fw status", "status") except (LinkError, ConsoleError) as e: # applied all the same; the caller reads the version its own way io.log.append(f"after the apply: {e}") return out finally: if io.airtime is not None: out["airtime"] = io.airtime await io.close() def main(): module = AnsibleModule( argument_spec={ "transport": {"type": "dict", "required": True}, "target": {"type": "str"}, "name": {"type": "str"}, "password": {"type": "str", "default": "", "no_log": True}, "packages": {"type": "path", "required": True}, "apply": {"type": "bool", "default": True}, "duty": {"type": "float", "default": 3}, "gap": {"type": "float", "default": 5}, "resume": {"type": "bool", "default": False}, "apply_wait": {"type": "int", "default": 60}, }, supports_check_mode=True, ) console = module.params["transport"].get("type") == "ble_console" if console and not HAS_BLEAK: module.fail_json(msg=missing_required_lib("bleak")) if not console and not HAS_MESHCORE: module.fail_json(msg=missing_required_lib("meshcore")) if not console and not module.params["target"]: module.fail_json(msg="target (the node's pubkey) is required over RF") io = None try: io = Console(module.params["transport"]) if console else Radio(module) result = run(work(module, io)) except (LinkError, ConsoleError, OtaError, ValueError, OSError) as e: module.fail_json(msg=str(e), log=io.log if io else []) module.exit_json(log=io.log, **result) if __name__ == "__main__": main()