meshcore_fw_ota: OTA firmware update of a meshcore-tth repeater, over RF or its BLE console
ci / test (push) Successful in 2m21s
ci / test (push) Successful in 2m21s
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>
This commit is contained in:
1 parent
d6f2d5cf28
commit
891be3afbe
7 files changed
+966
-5
No files matched your search
@@ -0,0 +1,92 @@
|
||||
"""The text console of a meshcore-tth repeater over BLE (Nordic UART Service).
|
||||
|
||||
A local console: no login, no RF, nothing on air -- the OTA module prefers it
|
||||
wherever a bonded host hears the node. The node echoes each command and answers
|
||||
with a line ' -> <reply>'. Bond the node once on the host the module runs on
|
||||
(the console is SECMODE_ENC_WITH_MITM); the module never takes the PIN, so it
|
||||
cannot end up in a log.
|
||||
|
||||
Learned on the masts:
|
||||
* BLE connects are flaky: a TimeoutError on a node that answers the next try is
|
||||
normal, hence the retries;
|
||||
* a connected central stops the node advertising -- stop whatever holds it
|
||||
(a bridge) and `bluetoothctl disconnect` it first;
|
||||
* a NUS write carries at most ATT_MTU - 3 bytes and BlueZ does not split it;
|
||||
* do not send a bare newline to wake it: over BLE that reply comes late and is
|
||||
taken for the answer to the next command.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import re
|
||||
import time
|
||||
|
||||
try:
|
||||
from bleak import BleakClient, BleakScanner
|
||||
|
||||
HAS_BLEAK = True
|
||||
except ImportError: # reported by the module via missing_required_lib
|
||||
HAS_BLEAK = False
|
||||
|
||||
NUS_RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e" # write (host -> node)
|
||||
NUS_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" # notify (node -> host)
|
||||
REPLY = re.compile(rb"-> ?(.*?)\r?\n")
|
||||
|
||||
|
||||
class ConsoleError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BleConsole:
|
||||
def __init__(self, address, connect_tries=5):
|
||||
self.address = address
|
||||
self.connect_tries = connect_tries
|
||||
self.client = None
|
||||
self.buf = bytearray()
|
||||
self.chunk = 20
|
||||
self.log = []
|
||||
|
||||
async def open(self):
|
||||
last = None
|
||||
for attempt in range(self.connect_tries):
|
||||
try:
|
||||
dev = await BleakScanner.find_device_by_address(self.address, timeout=20)
|
||||
if dev is None:
|
||||
raise ConsoleError("not advertising (a central still connected?)")
|
||||
client = BleakClient(dev, timeout=30)
|
||||
await client.connect()
|
||||
await client.start_notify(NUS_TX, lambda _h, data: self.buf.extend(data))
|
||||
self.client = client
|
||||
self.chunk = max(20, int(getattr(client, "mtu_size", 23)) - 3)
|
||||
self.log.append(f"BLE console {self.address} open (attempt {attempt + 1}, mtu {self.chunk + 3})")
|
||||
return
|
||||
except Exception as e: # noqa: BLE001 -- bleak/BlueZ raise many kinds, all mean "try again"
|
||||
last = e
|
||||
self.log.append(f"BLE connect {attempt + 1}/{self.connect_tries}: {type(e).__name__}: {e}")
|
||||
await asyncio.sleep(4)
|
||||
raise ConsoleError(f"cannot open the BLE console of {self.address}: {last}")
|
||||
|
||||
async def close(self):
|
||||
if self.client is not None:
|
||||
try:
|
||||
await self.client.disconnect()
|
||||
except Exception as e: # noqa: BLE001 -- after `fw apply` the node is gone already
|
||||
self.log.append(f"BLE disconnect: {type(e).__name__}")
|
||||
|
||||
async def cmd(self, line, timeout=5.0, quiet=False):
|
||||
"""One console command -> the reply after '-> '."""
|
||||
self.buf.clear()
|
||||
data = line.encode() + b"\r\n"
|
||||
for i in range(0, len(data), self.chunk):
|
||||
await self.client.write_gatt_char(NUS_RX, data[i : i + self.chunk], response=False)
|
||||
await asyncio.sleep(0.05)
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
m = REPLY.search(bytes(self.buf))
|
||||
if m:
|
||||
text = m.group(1).decode(errors="replace").strip()
|
||||
if not quiet:
|
||||
self.log.append(f"$ {line} -> {text}")
|
||||
return text
|
||||
await asyncio.sleep(0.02)
|
||||
shown = line if len(line) <= 24 else line[:24] + "..."
|
||||
raise ConsoleError(f"no reply to `{shown}` on the BLE console")
|
||||
@@ -187,29 +187,38 @@ class Link:
|
||||
pfx = (msg.get("pubkey_prefix") or "").lower()
|
||||
return bool(pfx) and self.target_pk.startswith(pfx)
|
||||
|
||||
async def cli(self, cmd, expect):
|
||||
async def cli(self, cmd, expect, retries=None, timeout=None, quiet=False, before_send=None):
|
||||
"""Send one CLI command and return the reply text that matches `expect` (regex).
|
||||
|
||||
A reply that does not match (a late answer to an earlier command, or
|
||||
another node) is drained and the command is resent, up to `retries`.
|
||||
quiet: no trace line on success (hundreds of firmware chunks).
|
||||
before_send: awaited before every attempt (the OTA airtime budget).
|
||||
"""
|
||||
retries = self.retries if retries is None else retries
|
||||
timeout = self.reply_timeout if timeout is None else timeout
|
||||
# never log a secret the command carries (the trace is returned to Ansible)
|
||||
shown = cmd
|
||||
for secret_cmd in ("password ", "ble pin "):
|
||||
if cmd.startswith(secret_cmd):
|
||||
shown = secret_cmd + "***"
|
||||
for attempt in range(1 + self.retries):
|
||||
if quiet and len(shown) > 24:
|
||||
shown = shown[:24] + "..."
|
||||
for attempt in range(1 + retries):
|
||||
self.inbox.clear()
|
||||
if before_send is not None:
|
||||
await before_send()
|
||||
if self.companion:
|
||||
await self.send_cli_command(cmd)
|
||||
else:
|
||||
await self.mc.commands.send_cmd(self.contact, cmd)
|
||||
deadline = time.monotonic() + self.reply_timeout
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
for msg in list(self.inbox):
|
||||
text = (msg.get("text") or "").strip()
|
||||
if self._from_target(msg) and re.search(expect, text):
|
||||
self.log.append(f"$ {shown} -> {self._redact(text)}")
|
||||
if not quiet:
|
||||
self.log.append(f"$ {shown} -> {self._redact(text)}")
|
||||
# The reply carries the NODE's clock: what fw_facts reports as skew.
|
||||
self.last_reply_ts = msg.get("sender_timestamp")
|
||||
self.last_reply_at = time.time()
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
"""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
|
||||
Reference in new issue
Block a user