#!/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 prefix (>= 8 hex), as in its `get public.key` a DELTA package only (ota_pack.py diff / fetch --base): a full image is refused here and by the node itself. 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. --via HEX force a direct path through these repeater hashes (2 bytes each, e.g. c327 or c327a1b2) -- also the login goes along it, so the node answers back the same way. For testing multi-hop on the bench. --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 if 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 same `fw` commands as tools/ota_push.py (USB), carried as remote admin CLI. Every `fw w` is idempotent on the node, so a lost reply is simply resent; the node checks the manifest as soon as its chunks arrive and answers ERR for a wrong board or base -- that stops the transfer. 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 base64 import configparser import functools import math import random import re 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) from meshcore import EventType, MeshCore CHUNK = 96 # FW_OTA_CHUNK (text) BCHUNK = 128 # FW_OTA_BCHUNK (binary) # The companion takes host frames of at most MAX_FRAME_SIZE 176 B, and a binary # request frame is 1 (cmd) + 32 (pubkey) + payload. 160 B chunks made 199 B # frames that the companion dropped -- every one of them (13. 11. 2026). MAX_FRAME = 176 UNIT = 32 # FW_OTA_UNIT MANIFEST = 256 # FW_OTA_MANIFEST_SIZE REQ_FW = 0xF0 # REQ_TYPE_FW_OTA INI = Path(__file__).resolve().parent.parent / "platformio.local.ini" def crc16(data: bytes, crc: int = 0xFFFF) -> int: """Nordic crc16_compute (CCITT, init 0xFFFF) -- FwUpdate.cpp crc16_update.""" for b in data: crc = ((crc >> 8) | (crc << 8)) & 0xFFFF crc ^= b crc ^= (crc & 0xFF) >> 4 crc ^= (crc << 12) & 0xFFFF crc ^= ((crc & 0xFF) << 5) & 0xFFFF return crc def w_payload(sid: int, off: int, chunk: bytes) -> bytes: """REQ_TYPE_FW_OTA 'w': [F0]['w'][sid u16][off u32][len u8][crc16][data].""" head = sid.to_bytes(2, "little") + off.to_bytes(4, "little") + bytes([len(chunk)]) # the crc binds the data to this session and offset (FwUpdate::handleBinary) return ( bytes([0xF0, ord("w")]) + head + crc16(chunk, crc16(head)).to_bytes(2, "little") + chunk ) @functools.cache # asked once: the side channel and --apply log in again 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 (the firmware role) if not pw: sys.exit(f"no admin password: [secrets] admin_pw in {INI}, a terminal, or stdin") return pw NO_PACKAGE = 3 # exit code: no package starts from the node's image def pick_package(where: str, status: str, full_ok: bool) -> bytes: """`package` may be a directory with one release's packages (the full image and its deltas, as the firmware role fetches them): take the delta that starts from the image `fw status` reports, else -- where a full image may go -- the full one. Exits NO_PACKAGE when nothing fits: the node runs an image no delta starts from, or has no `fw` at all (not an -ota build).""" p = Path(where) if not p.is_dir(): return p.read_bytes() m = re.search(r"\bbase \d+ ([0-9a-f]{8})", status) if not m: print(f"no base image in `fw status`: {status!r}") sys.exit(NO_PACKAGE) base = m.group(1) full = None for f in sorted(p.glob("*.mcfw")): data = f.read_bytes() if data[:4] != b"MCFW": continue if data[16:48].hex().startswith(base): # raw_sha256 = the image it installs print(f"the node already runs the image of {f.name}") sys.exit(0) if data[4] == 2 and data[160:192].hex().startswith(base): print(f"package: {f.name} (delta from {base})") return data if data[4] == 1: full = (f, data) if full and full_ok: print(f"package: {full[0].name} (full image, no delta from {base})") return full[1] print(f"no package in {where} starts from {base}") sys.exit(NO_PACKAGE) def lora_airtime(n: int, sf: int, bw_khz: float, cr: int, preamble: int = 16) -> float: """Seconds on air for an n-byte LoRa frame (explicit header, CRC on).""" tsym = (2**sf) / (bw_khz * 1000) de = 1 if tsym > 0.016 else 0 # Semtech AN1200.13: ceil(...) * (CR + 4), CR = 1..4 for 4/5..4/8. Until # 14. 11. 2026 this multiplied by CR alone: ~3x too little airtime at 4/5, # so --duty 3 let about 9 % through. payload = 8 + max( math.ceil((8 * n - 4 * sf + 28 + 16) / (4 * (sf - 2 * de))) * (cr + 4), 0 ) return (preamble + 4.25) * tsym + payload * tsym def frame_len(text: str) -> int: """MeshCore direct text frame: header+path_len, dest/src hash, MAC, and timestamp+flags+text padded to the AES block.""" body = 5 + len(text.encode()) return 2 + 2 + 2 + 16 * math.ceil(body / 16) class Bucket: def __init__(self, duty: float): self.rate = duty / 100.0 self.cap = self.rate * 3600 self.level = self.cap self.t = time.monotonic() self.used = 0.0 async def spend(self, secs: float) -> None: while True: now = time.monotonic() self.level = min(self.cap, self.level + (now - self.t) * self.rate) self.t = now if self.level >= secs: self.level -= secs self.used += secs return await asyncio.sleep((secs - self.level) / self.rate) REPLY_TEXT = 40 # typical reply ("ok", status lines are longer but rare) def hops_of(contact: dict) -> int: """out_path_len: low 6 bits = hops, top 2 = hash size - 1; -1 = flood.""" v = int(contact.get("out_path_len", -1)) return -1 if v < 0 else v & 0x3F class Link: def __init__( self, mc: MeshCore, contact: dict, bucket: Bucket, radio: tuple, gap: float = 0.0, ): self.mc, self.c, self.bucket, self.radio, self.gap = ( mc, contact, bucket, radio, gap, ) self.prefix = contact["public_key"][:12] self.retries = 0 # (preset, window min, monotonic deadline) while the node is on a side # channel: renewed before the node's own timer would take it back self.side: tuple[str, int, float] | None = None async def keep_side(self) -> None: if self.side is None or time.monotonic() < self.side[2] - SIDE_MARGIN: return preset, win, _ = self.side self.side = (preset, win, time.monotonic() + win * 60) # before cmd(): no recursion r = await self.cmd(f"tempradio {preset},{win}") if not r.startswith("OK"): raise RuntimeError(f"tempradio renewal: {r}") await asyncio.sleep(3) # the node re-applies the preset 2 s after its reply def cost(self, text: str) -> float: hops = max(hops_of(self.c), 0) one = lora_airtime(frame_len(text), *self.radio) + lora_airtime( frame_len("x" * REPLY_TEXT), *self.radio ) return one * (hops + 1) async def cmd(self, text: str, timeout: float = 20.0, tries: int = 4) -> str: await self.keep_side() for attempt in range(tries): await self.bucket.spend(self.cost(text)) await self.mc.commands.send_cmd(self.c, text) ev = await self.mc.wait_for_event( EventType.CONTACT_MSG_RECV, attribute_filters={"pubkey_prefix": self.prefix}, timeout=timeout, ) if ev is not None: if self.gap: await asyncio.sleep(self.gap) return str(ev.payload.get("text", "")).strip() self.retries += 1 print( f" ({text[:12]}...: no reply, try {attempt + 2}/{tries})", flush=True ) raise TimeoutError(f"no reply to {text[:30]!r}") def req_frame_len(payload_len: int) -> int: """Direct REQ: header+path_len, dest/src hash, MAC, timestamp+payload padded.""" return 2 + 2 + 2 + 16 * math.ceil((4 + payload_len) / 16) class Binary: """Firmware chunks as binary requests (REQ_TYPE_FW_OTA).""" def __init__(self, link: "Link"): self.link = link self.pub = bytes.fromhex(link.c["public_key"]) self.sid = 0 def cost(self, payload_len: int, reply_len: int = 0) -> float: hops = max(hops_of(self.link.c), 0) t = lora_airtime(req_frame_len(payload_len), *self.link.radio) if reply_len: t += lora_airtime(req_frame_len(reply_len), *self.link.radio) return t * (hops + 1) async def send(self, payload: bytes) -> str | None: if 1 + 32 + len(payload) > MAX_FRAME: raise ValueError( f"binary request of {len(payload)} B exceeds the companion frame" ) ev = await self.link.mc.commands.send( b"\x32" + self.pub + payload, [EventType.MSG_SENT, EventType.ERROR] ) if 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, off: int, chunk: bytes) -> None: await self.link.keep_side() payload = w_payload(self.sid, off, chunk) c = self.cost(len(payload)) await self.link.bucket.spend(c) await self.send(payload) # no reply comes: give the packet time to go out along the whole path await asyncio.sleep(max(self.link.gap, c + 1.0)) async def missing(self, timeout: float = 20.0) -> tuple[int, list[int]] | None: """(state, missing unit indices) or None when the node does not answer.""" for _ in range(2): await self.link.keep_side() await self.link.bucket.spend(self.cost(2, 160)) fut: asyncio.Future = 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(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 d = bytes.fromhex(ev.payload["data"]) if len(d) < 5: continue cnt = int.from_bytes(d[3:5], "little") miss = [ int.from_bytes(d[5 + 2 * i : 7 + 2 * i], "little") for i in range(cnt) ] await asyncio.sleep(self.link.gap) return d[0], miss return None SIDE_FIRST = 3 # min: the node's first side window, until the link there is proven SIDE_MARGIN = 150 # s before the window ends: renew (a text cmd retries up to 80 s) def parse_preset(s: str) -> tuple[float, float, int, int]: """freq MHz, bw kHz, sf, cr (5..8) -- the ranges tempradio takes.""" try: f, bw, sf, cr = s.split(",") p = (float(f), float(bw), int(sf), int(cr)) except ValueError: sys.exit(f"--side {s!r}: freq,bw,sf,cr (e.g. 869.525,62.5,7,5)") if not (150 <= p[0] <= 2500 and 7 <= p[1] <= 500 and 5 <= p[2] <= 12 and 5 <= p[3] <= 8): sys.exit(f"--side {s!r}: out of range (freq MHz, bw kHz, sf 5-12, cr 5-8)") return p def fmt_preset(p: tuple) -> str: return f"{p[0]:g},{p[1]:g},{p[2]},{p[3]}" def same_preset(si: dict, p: tuple) -> bool: return ( abs(float(si["radio_freq"]) - p[0]) < 0.001 and abs(float(si["radio_bw"]) - p[1]) < 0.01 and int(si["radio_sf"]) == p[2] and int(si["radio_cr"]) == p[3] ) class Side: """The node and the companion on a side channel, and the way back.""" def __init__(self, mc: MeshCore, link: "Link", preset: tuple, window: int): self.mc, self.link, self.preset, self.window = mc, link, preset, window self.node_main = "" # the node's own preset (`get radio`) self.comp_main: tuple | None = None # the companion's, set once it moved self.comp_repeat: bool | None = None c = link.c # its mesh path, put back at the end self.path = c["out_path"], int(c["out_path_len"]), int(c.get("out_path_hash_mode", 0)) self.node_on_side = False async def enter(self) -> dict: r = await self.link.cmd("get radio") m = re.fullmatch(r">\s*([\d.]+),([\d.]+),(\d+),(\d+)", r) if not m: sys.exit(f"get radio: {r!r}") self.node_main = ",".join(m.groups()) side = fmt_preset(self.preset) print(f"node preset {self.node_main}, side channel {side}") r = await self.link.cmd(f"tempradio {side},{SIDE_FIRST}") print("tempradio:", r) if not r.startswith("OK"): sys.exit(1) self.node_on_side = True self.link.side = (side, SIDE_FIRST, time.monotonic() + SIDE_FIRST * 60) await asyncio.sleep(3) # the node switches 2 s after its reply si = self.mc.self_info self.comp_main = ( float(si["radio_freq"]), float(si["radio_bw"]), int(si["radio_sf"]), int(si["radio_cr"]) ) di = await self.mc.commands.send_device_query() self.comp_repeat = di.payload.get("repeat") if di.type == EventType.DEVICE_INFO else None rep = None if self.comp_repeat is None else 0 # no client repeat on the side channel await self.mc.commands.set_radio(*self.preset, repeat=rep) ev = await self.mc.commands.send_appstart() if ev.type != EventType.SELF_INFO or not same_preset(ev.payload, self.preset): self.comp_main = None # nothing moved, and the node is out of reach sys.exit( "the companion did not retune (an openHop virtual companion acks set_radio " "and keeps the host's radio): it needs a MeshCore companion firmware. " f"The node returns to its preset within {SIDE_FIRST} min." ) print(f"companion on {side}") # Zero-hop from here: the mesh path means nothing on the side channel, # and the node answers along the path of the last login -- log in again. await self.mc.commands.reset_path(self.link.c) r = await login(self.mc, self.link.c) if r != "LOGIN_SUCCESS": sys.exit(f"login on the side channel: {r} (out of direct range?)") await self.mc.ensure_contacts(follow=True) contact = await find_contact(self.mc, self.link.prefix, 5) print(f"login on the side channel: ok, {hops_of(contact)} hops") self.link.c = contact self.link.radio = (self.preset[2], self.preset[1], self.preset[3] - 4) self.link.side = (side, self.window, 0.0) # renew to the full window now await self.link.keep_side() return contact async def leave(self) -> None: """Back: the node (unless `fw apply` rebooted it), the companion, the path.""" if self.node_on_side and self.comp_main is not None: self.link.side = None try: # tempradio with its own preset: back in 2 s, on any firmware print("node back:", await self.link.cmd(f"tempradio {self.node_main},1", tries=2)) except (TimeoutError, RuntimeError): print("node does not answer: it returns by itself when its window runs out") self.node_on_side = False self.link.side = None if self.comp_main is not None: rep = None if self.comp_repeat is None else int(self.comp_repeat) await self.mc.commands.set_radio(*self.comp_main, repeat=rep) ev = await self.mc.commands.send_appstart() ok = ev.type == EventType.SELF_INFO and same_preset(ev.payload, self.comp_main) print(f"companion back on {fmt_preset(self.comp_main)}: {'ok' if ok else 'CHECK IT'}") self.comp_main = None out_path, out_len, mode = self.path if out_len < 0: await self.mc.commands.reset_path(self.link.c) else: await self.mc.commands.update_contact(self.link.c, path=out_path, path_hash_mode=mode) async def login(mc: MeshCore, contact: dict) -> str: """Admin login; returns the event type name.""" fut: asyncio.Future = asyncio.get_running_loop().create_future() def done(ev): if not fut.done(): fut.set_result(ev.type.name) subs = [ mc.subscribe(t, done) for t in (EventType.LOGIN_SUCCESS, EventType.LOGIN_FAILED) ] try: await mc.commands.send_login(contact, admin_pw()) return await asyncio.wait_for(fut, 30) except TimeoutError: return "timeout" finally: for sub in subs: mc.unsubscribe(sub) async def find_contact(mc: MeshCore, prefix: str, wait: float) -> dict: added: list[dict] = [] async def on_new(ev): added.append(ev.payload) sub = mc.subscribe(EventType.NEW_CONTACT, on_new) t0 = time.time() try: while True: await mc.ensure_contacts(follow=True) for c in mc.contacts.values(): if c["public_key"].lower().startswith(prefix): return c for p in added: if p.get("public_key", "").lower().startswith(prefix): await mc.commands.add_contact(p) 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) def check_delta(data: bytes, name: str) -> bytes: # Only deltas go over the mesh -- the node refuses anything else too # (FwUpdate: `fw begin` over 64 kB, a format 1 manifest). A full image is # ~300 kB, hours of a shared channel: USB (ota_push.py) or the BLE console. if data[:4] != b"MCFW" or data[4] != 2: sys.exit( f"{name}: not a delta package (format {data[4] if len(data) > 4 else '?'}) -- " "over the mesh only deltas; a full image goes over USB (tools/ota_push.py) or BLE" ) return data async def run(args: argparse.Namespace) -> int: pkg = Path(args.package) data = None if pkg.is_dir() else check_delta(pkg.read_bytes(), args.package) if args.companion.startswith("tcp://"): host, port = args.companion[6:].rsplit(":", 1) mc = await MeshCore.create_tcp(host, int(port)) else: mc = await MeshCore.create_serial(args.companion) if mc is None: sys.exit("companion does not answer") side: Side | None = None try: si = mc.self_info cr = int(si["radio_cr"]) - 4 radio = (int(si["radio_sf"]), float(si["radio_bw"]), cr) print( f"companion {si['name']}: {si['radio_freq']} MHz, SF{radio[0]}, BW{radio[1]}, CR4/{si['radio_cr']}" ) await mc.start_auto_message_fetching() contact = await find_contact(mc, args.dest.lower(), args.wait) if args.via: path = bytes.fromhex(args.via) if len(path) % 2: sys.exit("--via: whole 2-byte hashes") await mc.commands.update_contact(contact, path=path.hex(), path_hash_mode=1) contact = await find_contact(mc, args.dest.lower(), 5) print( f"dest {contact['adv_name']} {contact['public_key'][:8]}, out_path_len {contact.get('out_path_len')}" ) bucket = Bucket(args.duty) await bucket.spend(lora_airtime(48, *radio)) r = await login(mc, contact) if r != "LOGIN_SUCCESS": sys.exit(f"login: {r}") print("login: ok (admin)") await mc.ensure_contacts(follow=True) # login may have taught it a path contact = await find_contact(mc, args.dest.lower(), 5) print( f"path: {hops_of(contact)} hops (out_path_len {contact.get('out_path_len')})" ) link = Link(mc, contact, bucket, radio, args.gap) t0 = time.time() status = await link.cmd("fw status") print("status:", status) if data is None: data = check_delta(pick_package(args.package, status, full_ok=False), args.package) if args.side: side = Side(mc, link, parse_preset(args.side), args.window) contact = await side.enter() if args.resume: # `fw begin` would wipe what the node has; text chunks need no session r = await link.cmd("fw missing") print("missing:", r) if not r.startswith(">"): return 1 sid = 0 else: sid = random.randint(1, 0xFFFF) # chunks of an earlier transfer are dropped r = await link.cmd(f"fw begin {len(data)} {sid}") print("begin:", r) if not r.startswith("OK"): return 1 binary = None if (args.text or args.resume) else Binary(link) if binary: binary.sid = sid text_todo: list[int] | None = None if binary: st = await binary.missing() if st is None: print("node does not answer binary requests: text chunks") binary = None if binary: nb = (len(data) + BCHUNK - 1) // BCHUNK todo = list(range(nb)) last_miss = 1 << 30 async def settled(): lost = 0 for _ in range(10): st = await binary.missing() if st is None and lost < 4: # a lost query or reply after a 40-minute round must not # throw the round away (14. 11. 2026, mast-three: it did) lost += 1 await asyncio.sleep(10) continue if st is None or st[0] != 4: # 4 = busy (manifest check) return st await asyncio.sleep(3) return st manifest_checked = False for rnd in range(6): for k, i in enumerate(todo): off = i * BCHUNK await binary.write(off, data[off : off + BCHUNK]) print( f"\r{k + 1}/{len(todo)} binary chunks (round {rnd + 1}), {time.time() - t0:.0f} s, " f"airtime {bucket.used:.1f} s", end="", flush=True, ) if not manifest_checked and off + BCHUNK >= MANIFEST and k + 1 < len(todo): # The node checks the manifest as soon as it is in (signature, # target, base, NOT OLDER): ask before the rest goes on air -- # a refused package otherwise costs the whole first round. manifest_checked = True st = await settled() if st is not None and st[0] == 3: print("\nnode:", await link.cmd("fw status")) print(f"stopped after the manifest, airtime {bucket.used:.1f} s") return 1 print() st = await settled() if st is None: print("missing: no answer (the node keeps what it has: --resume)") return 1 state, miss = st print(f"missing: state {state}, {len(miss)} units") if state == 3: print("node:", await link.cmd("fw status")) return 1 if not miss: break if rnd > 0 and len(miss) >= last_miss: # a round that adds nothing will not be fixed by more rounds print("binary chunks do not arrive: text chunks for the rest") binary = None text_todo = sorted({u * UNIT // CHUNK for u in miss}) break last_miss = len(miss) todo = sorted({u * UNIT // BCHUNK for u in miss}) if binary: todo = [] elif text_todo is not None: todo = text_todo # only what the binary rounds did not deliver elif args.resume: # `fw missing` lists ~23 offsets per reply: rounds go on while they help todo = [] if not r.endswith("none"): todo = [int(x) // CHUNK for x in r.lstrip(">").split()] else: todo = list(range((len(data) + CHUNK - 1) // CHUNK)) stuck = 0 for rnd in range(40 if todo else 0): for k, i in enumerate(todo): off = i * CHUNK r = await link.cmd( f"fw w {off} {base64.b64encode(data[off : off + CHUNK]).decode()}" ) if r != "ok": print(f"\nchunk {off}: {r}") return 1 print( f"\r{k + 1}/{len(todo)} chunks (round {rnd + 1}), {time.time() - t0:.0f} s, " f"airtime {bucket.used:.1f} s", end="", flush=True, ) print() r = await link.cmd("fw missing") print("missing:", r) if r.endswith("none"): break if not r.startswith(">"): stuck += 1 # a lost reply: ask again next round if stuck > 3: print("fw missing does not answer, giving up (--resume continues)") return 1 continue new = [int(x) // CHUNK for x in r.lstrip(">").split()] stuck = stuck + 1 if new == todo else 0 if stuck > 3: print("the same chunks keep missing, giving up") return 1 todo = new r = await link.cmd("fw verify", timeout=40) for _ 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 link.cmd("fw status") print("verify:", r) if not r.startswith(">") or "ready" not in r: return 1 print("bootloader:", await link.cmd("fw bl")) if args.apply: r = await link.cmd("fw apply", timeout=30, tries=1) print("apply:", r) if not r.startswith("OK"): return 1 if side: # the reboot takes the node back to its own preset: follow it side.node_on_side = False await side.leave() await mc.ensure_contacts(follow=True) contact = link.c = await find_contact(mc, args.dest.lower(), 5) link.radio = radio side = None print("waiting 60 s for the node to rewrite itself and boot ...") await asyncio.sleep(60) print("login after apply:", await login(mc, contact)) print("ver:", await link.cmd("ver")) print("status:", await link.cmd("fw status")) print("bootloader:", await link.cmd("fw bl")) print( f"done in {time.time() - t0:.0f} s, channel airtime {bucket.used:.1f} s, retries {link.retries}" ) return 0 finally: if side: await side.leave() await mc.disconnect() 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("--via") 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()