meshcore_fw_ota: the transfer as an Ansible-free engine shared with meshcore-tth's tools, plus a side channel via tempradio
ci / test (push) Failing after 15s

module_utils/meshcore_ota_engine.py now holds the whole transfer (Console,
Radio, binary and text rounds, update()); the module only maps its
parameters. tools/ota_mesh_push.py and tools/ota_push.py of meshcore-tth
import the same code, so the protocol lives in one place.

New:
- side/window: the node goes to another preset by `tempradio`, the
  companion is retuned (checked -- an openHop virtual companion acks
  set_radio as a no-op and is refused), a fresh login goes zero-hop and
  the delta follows; the window is renewed, and the node and companion
  come back at the end (or the node by its own timer).
- SerialConsole: the node's USB console, the same calls as BleConsole.
- `fw base` when `fw status` shows no base (failed/ready/rx): a node left
  after a refused package was taken for "not an -ota build", i.e. a full
  DFU, and `resume` could never pick its package.
- asyncio.TimeoutError caught too: on Python 3.10 (dopey) a lost bitmap
  reply ended the whole transfer.
- text: text chunks only; update(force=...) for `fw apply force`.

Bench 16. 11. 2026 (x3 companion -> x1 -ota repeater, 866.5 -> side 866.0/SF7):
the module from dopey (py3.10), the firmware role's ota.yml with
mc_fw_ota_side, ota_mesh_push.py and ota_push.py over USB -- each applied
a 2.7 kB delta, ~20 s airtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Opus 5.5 committed 2026-11-16 23:17:41 +01:00
1 parent 8306d91b48
commit 185470de08
7 files changed
+922 -375

No files matched your search

+68 -372
View File
@@ -60,6 +60,23 @@ options:
type: bool
default: false
apply_wait: {description: Seconds to wait after C(fw apply) before reading the new version., type: int, default: 60}
text: {description: RF only. Text chunks only (each answered) instead of binary requests., type: bool, default: false}
side:
description:
- "RF only. Carry the transfer on a side channel, off the shared mesh:
C(freq,bw,sf,cr), e.g. C(869.525,62.5,7,5). Login, C(fw status) and
C(get radio) go over the mesh, then the node gets C(tempradio) and the
companion is retuned to the same preset; the chunks go there zero-hop,
so the companion must be in direct range of the node."
- The companion must retune its own radio (a MeshCore companion firmware).
An openHop virtual companion acks the change and stays put -- checked,
and the task fails; the node returns within 3 minutes.
- The node comes back on C(fw apply) (the reboot), by C(tempradio) with its
own preset at the end, or by its own timer. The companion gets its
preset back at the end -- unless the task is killed (async timeout),
then set its radio back by hand.
type: str
window: {description: "Side channel window in minutes, renewed while the transfer runs.", type: int, default: 15}
requirements: [meshcore (RF), bleak (ble_console)]
"""
@@ -80,6 +97,16 @@ EXAMPLES = r"""
transport: {type: ble_console, address: "AA:BB:CC:DD:EE:FF"}
packages: /tmp/ota/
- name: Off the shared channel, through a MeshCore companion in direct range
tth.meshcore.meshcore_fw_ota:
transport: {type: serial, port: /dev/serial/by-id/usb-Seeed_Studio_XIAO_nRF52840_0123-if00, expect_freq: 869.432}
target: "{{ mc_target }}"
password: "{{ vault_meshcore_admin_password }}"
packages: /tmp/ota/
side: 869.525,62.5,7,5
duty: 10
gap: 1
- name: No package fits the node's image -- full DFU instead
ansible.builtin.debug:
msg: "{{ ota.base }}: no delta"
@@ -125,376 +152,16 @@ log:
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_console import HAS_BLEAK, ConsoleError
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_link import HAS_MESHCORE, LinkError, run
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_ota import parse_preset
from ansible_collections.tth.meshcore.plugins.module_utils.meshcore_ota_engine import (
Console,
OtaError,
Radio,
update,
)
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():
@@ -510,20 +177,49 @@ def main():
"gap": {"type": "float", "default": 5},
"resume": {"type": "bool", "default": False},
"apply_wait": {"type": "int", "default": 60},
"text": {"type": "bool", "default": False},
"side": {"type": "str"},
"window": {"type": "int", "default": 15},
},
supports_check_mode=True,
)
console = module.params["transport"].get("type") == "ble_console"
p = module.params
console = p["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"]:
if not console and not p["target"]:
module.fail_json(msg="target (the node's pubkey) is required over RF")
if console and p["side"]:
module.fail_json(msg="side is RF only: the BLE console puts nothing on air")
io = None
try:
io = Console(module.params["transport"]) if console else Radio(module)
result = run(work(module, io))
side = parse_preset(p["side"]) if p["side"] else None
if console:
io = Console(p["transport"]["address"])
else:
io = Radio(
p["transport"],
p["target"],
p["password"],
name=p["name"],
duty=p["duty"],
gap=p["gap"],
side=side,
window=p["window"],
)
result = run(
update(
io,
p["packages"],
apply=p["apply"],
resume=p["resume"],
check=module.check_mode,
apply_wait=p["apply_wait"],
text=p["text"],
)
)
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)