Files
meshcore-ansible/plugins/module_utils/meshcore_ota.py
T
tthandClaude Opus 5.5 891be3afbe
ci / test (push) Successful in 2m21s
meshcore_fw_ota: OTA firmware update of a meshcore-tth repeater, over RF or its BLE console
Picks the package of a release that fits the image `fw status` reports
(changed=false when the node runs it already, no_package when none fits or
the node has no `fw`), transfers it -- over RF as binary chunks with a
bitmap of the missing ones and text chunks as the fallback, inside an
airtime budget; over the BLE console as text, a full image too -- then
verifies and applies. Port of tools/ota_mesh_push.py / ota_push.py of
meshcore-tth; radio-free parts in module_utils/meshcore_ota.py with unit
tests (the airtime formula they caught is fixed in the tool as well).
Link.cli takes retries, timeout, quiet and a before_send hook.

Tested on two live repeaters forced onto their current image (BLE console;
RF through a companion: 'current', 0.6 s airtime) and with a package of
another base (no_package).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 20:54:29 +01:00

172 lines
6.3 KiB
Python

"""Radio-free parts of the OTA firmware update of meshcore-tth (src/helpers/FwUpdate).
Kept apart from meshcore_fw_ota so they can be unit-tested: which package fits
the node, the chunk framing, and what a transfer costs on air. The protocol
itself is the reference client's, tools/ota_mesh_push.py of meshcore-tth.
A package (`.mcfw`, tools/ota_pack.py) is a 256 B manifest and a payload:
0 magic "MCFW" | 4 format 1 (full image) or 2 (delta) | 5 layout
16 raw_sha256 = the image it installs | 160 base_sha256 (delta: the image it starts from)
192 Ed25519 signature over 0..191 -- checked by the node, not here
"""
import math
import re
import time
CHUNK = 96 # FW_OTA_CHUNK: text chunk (`fw w <off> <base64>`), answered "ok"
BCHUNK = 128 # FW_OTA_BCHUNK: binary chunk (REQ_TYPE_FW_OTA 'w'), unanswered
UNIT = 32 # FW_OTA_UNIT: what the missing-units bitmap counts
MANIFEST = 256
REQ_FW = 0xF0 # REQ_TYPE_FW_OTA
# The companion takes host frames of at most 176 B, and a binary request frame
# is 1 (cmd) + 32 (pubkey) + payload: 160 B chunks were dropped, every one.
MAX_FRAME = 176
REPLY_TEXT = 40 # typical length of a reply, for the airtime estimate
class Package:
"""One `.mcfw` file: name, bytes, and what the manifest says about it."""
def __init__(self, name, data):
if data[:4] != b"MCFW" or len(data) < MANIFEST:
raise ValueError(f"{name}: not an OTA package (no MCFW manifest)")
self.name = name
self.data = data
self.format = data[4]
self.image_sha = data[16:48].hex()
self.base_sha = data[160:192].hex() if self.format == 2 else None
self.version = data[128:156].rstrip(b"\0").decode(errors="replace")
@property
def delta(self):
return self.format == 2
def parse_status(text):
"""`fw status` -> (base image size, sha256 prefix) or None (no `fw`, not an -ota build).
Reply: '> idle, batt 4137mV (min 3800), free 352256 B, base 456492 fe748410, delta'.
"""
m = re.search(r"\bbase (\d+) ([0-9a-f]{8})", text or "")
return (int(m.group(1)), m.group(2)) if m else None
def pick(packages, base, full_ok):
"""('current', pkg) | ('delta', pkg) | ('full', pkg) | ('none', None).
current: the node already runs the image these packages install. delta: the
one that starts from the node's image. full: no delta fits and a full image
may go (a local console; the node refuses one over the mesh).
"""
full = None
for p in packages:
if p.image_sha.startswith(base):
return "current", p
for p in packages:
if p.delta and p.base_sha.startswith(base):
return "delta", p
if not p.delta:
full = p
if full is not None and full_ok:
return "full", full
return "none", None
def crc16(data, crc=0xFFFF):
"""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, off, chunk):
"""REQ_TYPE_FW_OTA 'w': [F0]['w'][sid u16][off u32][len u8][crc16][data].
The crc binds the data to this session and offset (FwUpdate::handleBinary),
so late chunks of an earlier transfer are dropped.
"""
head = sid.to_bytes(2, "little") + off.to_bytes(4, "little") + bytes([len(chunk)])
return bytes([REQ_FW, ord("w")]) + head + crc16(chunk, crc16(head)).to_bytes(2, "little") + chunk
def parse_missing(data):
"""Reply to REQ_TYPE_FW_OTA 'm' -> (state, [missing unit indices]) or None.
[state u8][2 bytes][count u16][count x unit u16]; state 3 = refused, 4 = busy.
"""
if len(data) < 5:
return None
cnt = int.from_bytes(data[3:5], "little")
return data[0], [int.from_bytes(data[5 + 2 * i : 7 + 2 * i], "little") for i in range(cnt)]
def text_missing(reply):
"""`fw missing` -> chunk offsets ([] for 'none'), or None for a reply that is no list."""
if not reply.startswith(">"):
return None
body = reply[1:].strip()
return [] if body == "none" else [int(x) for x in body.split()]
# ── airtime ─────────────────────────────────────────────────────────────────
def lora_airtime(n, sf, bw_khz, cr, preamble=16):
"""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
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 text_frame_len(text):
"""Direct text frame: header+path_len, dest/src hash, MAC, timestamp+flags+text in AES blocks."""
return 6 + 16 * math.ceil((5 + len(text.encode())) / 16)
def req_frame_len(payload_len):
"""Direct REQ: header+path_len, dest/src hash, MAC, timestamp+payload in AES blocks."""
return 6 + 16 * math.ceil((4 + payload_len) / 16)
def hops_of(contact):
"""out_path_len: low 6 bits = hops, top 2 = hash size - 1; -1 = flood (counted as 0)."""
v = int(contact.get("out_path_len", -1))
return 0 if v < 0 else v & 0x3F
class Bucket:
"""Airtime budget: a token bucket of `duty` % of an hour.
It counts what the transfer puts on the CHANNEL -- request and reply, each
times (hops + 1), since every repeater on the path sends both again.
`clock` is injectable for the tests.
"""
def __init__(self, duty, clock=time.monotonic):
if not 0 < duty <= 100:
raise ValueError(f"duty {duty} % is not in (0, 100]")
self.rate = duty / 100.0
self.cap = self.rate * 3600
self.level = self.cap
self.clock = clock
self.t = clock()
self.used = 0.0
def wait_for(self, secs):
"""Seconds to wait before `secs` of airtime may be spent (0 = now); spends it when 0."""
now = self.clock()
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 0.0
return (secs - self.level) / self.rate