#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Push an OTA package (tools/ota_pack.py) to a node OVER THE MESH, as admin. tools/ota_mesh_push.py [--apply] [--duty 1] how to reach the companion that talks for us: tcp://127.0.0.1:7003 (serial_tcp_proxy.py + ssh -L) or a serial port path the target node's public key, or a prefix (>= 8 hex) of a contact the companion knows, as in its `get public.key` a DELTA package (ota_pack.py diff / fetch --base): a full image does not go over the mesh, the node refuses it too. Or a directory with one release's packages: the delta from the image `fw status` reports is taken; exit 3 = none fits --apply after a good `fw verify`, `fw apply` and wait for the node to come back with the new image (ver + fw status over the mesh) --duty P airtime budget in percent per hour (default 1: the 865-868 MHz bench band). Token bucket of P% x 3600 s. It counts what the transfer puts on the CHANNEL, not just our radio: request and the expected reply, each times (hops + 1), because every repeater on the path sends both again. --gap S pause after every reply before the next command (default 5). Without it a small delta goes out as fast as the round trip (~2 s per chunk at SF8) and holds the channel for that time. --text send chunks as text CLI (`fw w `, 96 B, each answered) instead of the default binary requests (128 B, unanswered, missing ones found by a bitmap query). Falls back to text by itself when the node does not answer the binary query (older firmware, or the sensor build). --resume continue a transfer that stopped (the node keeps what it got until the next `fw begin` or a reboot): no begin, only the chunks `fw missing` lists, as text, then verify (and --apply) --wait S how long to wait for the dest's advert when only a prefix is given and the companion does not know it yet (default 120 s); send `advert.zerohop` on the dest meanwhile --side F,BW,SF,CR carry the transfer on a SIDE CHANNEL, off the shared mesh: login, `fw status` and `get radio` go over the mesh, then the node gets `tempradio F,BW,SF,CR,` and the companion is retuned to the same preset; the chunks go there, ZERO-HOP -- the companion must be in direct range of the node. E.g. 869.525,62.5,7,5: inside 869.4-869.65 (10 % duty), between the CZ mesh (869.432/62.5) and EU Narrow (869.618/62.5). The node returns to its own preset by itself when the window runs out (first 3 min, then --window, renewed while the transfer runs), at `fw apply` (reboot), or when we are done. The companion must be one that retunes its radio: a MeshCore companion firmware, not an openHop virtual companion (that acks set_radio and stays put -- checked, and refused). Its own preset is put back at the end; killed hard (-9), it stays on the side channel: put it back with set_radio. --duty and --gap still apply: on a side channel of its own the transfer can take e.g. --duty 10 --gap 1. --window M side channel window in minutes (default 15), renewed while the transfer runs The transfer itself is the tth.meshcore Ansible collection's OTA engine (module_utils/meshcore_ota_engine.py) -- the meshcore_fw_ota module runs the very same code. tools/ota_collection.py says where it is looked for. The admin password comes from platformio.local.ini ([secrets] admin_pw), is asked for on the terminal, or read from stdin when that is no terminal; it is never printed. CHECK `get radio` on both ends first: this transmits. """ import argparse import asyncio import configparser import importlib import sys import time from pathlib import Path if __name__ == "__main__" and (any(a in ("-h", "--help") for a in sys.argv[1:]) or len(sys.argv) == 1): print(__doc__) sys.exit(0) sys.path.insert(0, str(Path(__file__).resolve().parent)) from ota_collection import PKG, locate locate() engine = importlib.import_module(f"{PKG}.meshcore_ota_engine") ota = importlib.import_module(f"{PKG}.meshcore_ota") link = importlib.import_module(f"{PKG}.meshcore_link") INI = Path(__file__).resolve().parent.parent / "platformio.local.ini" NO_PACKAGE = 3 # exit code: no package starts from the node's image class EchoLog(list): """The engine's trace, printed as it grows.""" def __init__(self): super().__init__() self.t0 = time.time() def append(self, line): print(f"[{time.time() - self.t0:5.0f} s] {line}", flush=True) super().append(line) def admin_pw() -> str: """[secrets] admin_pw of platformio.local.ini, else asked on the terminal (never an argument: it would show in the process list and the history).""" cp = configparser.ConfigParser(interpolation=None, strict=False) cp.read(INI) pw = cp.get("secrets", "admin_pw", fallback="").strip() if not pw and sys.stdin.isatty(): import getpass pw = getpass.getpass("admin password of the node: ").strip() elif not pw: pw = sys.stdin.readline().strip() # piped in if not pw: sys.exit(f"no admin password: [secrets] admin_pw in {INI}, a terminal, or stdin") return pw def transport_of(companion: str) -> dict: if companion.startswith("tcp://"): host, port = companion[6:].rsplit(":", 1) return {"type": "tcp", "host": host, "port": int(port)} return {"type": "serial", "port": companion} async def full_key(transport: dict, prefix: str, wait: float) -> str: """The node's full pubkey from a prefix, among the companion's contacts (waiting for its advert). The engine addresses the node by the full key.""" from meshcore import EventType, MeshCore if transport["type"] == "tcp": mc = await MeshCore.create_tcp(transport["host"], transport["port"], auto_reconnect=False) else: mc = await MeshCore.create_serial(transport["port"]) if mc is None: sys.exit("companion does not answer") added: list[dict] = [] sub = mc.subscribe(EventType.NEW_CONTACT, lambda ev: added.append(ev.payload)) t0 = time.time() try: while True: await mc.ensure_contacts(follow=True) for c in list(mc.contacts.values()) + added: if c.get("public_key", "").lower().startswith(prefix): if c in added: await mc.commands.add_contact(c) return c["public_key"].lower() if time.time() - t0 > wait: sys.exit(f"{prefix}: not among the companion's contacts after {wait:.0f} s (advert.zerohop on the node?)") await asyncio.sleep(3) finally: mc.unsubscribe(sub) await mc.disconnect() async def run(args: argparse.Namespace) -> int: transport = transport_of(args.companion) target = args.dest.lower() if len(target) != 64: target = await full_key(transport, target, args.wait) side = ota.parse_preset(args.side) if args.side else None log = EchoLog() io = engine.Radio( transport, target, admin_pw(), duty=args.duty, gap=args.gap, side=side, window=args.window, log=log ) try: out = await engine.update(io, args.package, apply=args.apply, resume=args.resume, text=args.text) except (engine.OtaError, link.LinkError, ValueError, OSError) as e: print(f"FAILED: {e} (airtime {io.airtime} s)") return 1 print( f"{out['state']}: {out.get('package', '-')} {out.get('version_after') or out.get('version') or ''}" f" -- {time.time() - log.t0:.0f} s, channel airtime {out.get('airtime', 0)} s" ) return NO_PACKAGE if out["no_package"] else 0 def main() -> None: ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) ap.add_argument("companion") ap.add_argument("dest") ap.add_argument("package") ap.add_argument("--apply", action="store_true") ap.add_argument("--duty", type=float, default=1.0) ap.add_argument("--wait", type=float, default=120.0) ap.add_argument("--gap", type=float, default=5.0) ap.add_argument("--text", action="store_true") ap.add_argument("--resume", action="store_true") ap.add_argument("--side") ap.add_argument("--window", type=int, default=15) sys.exit(asyncio.run(run(ap.parse_args()))) if __name__ == "__main__": main()