ota_mesh_push.py, ota_push.py: run the tth.meshcore OTA engine instead of their own copies
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f6e792f1bb
commit
a69e97583e
5 files changed
+310
-947
No files matched your search
+144
-289
@@ -18,10 +18,18 @@ beforehand (tools/ble_pair.py), from the host that holds the bond. Prefer it
|
||||
to tools/ota_mesh_push.py wherever BLE reaches: no airtime on the mesh, and the
|
||||
console is local, so a full image goes too. Needs bleak; --binary is USB only.
|
||||
|
||||
The transfer is the tth.meshcore Ansible collection's OTA engine
|
||||
(module_utils/meshcore_ota_engine.py), the same code as ota_mesh_push.py and
|
||||
the meshcore_fw_ota module; tools/ota_collection.py says where it is found.
|
||||
|
||||
--force apply below the battery gate (`fw apply force`, local
|
||||
console only): a bench board without a cell reads its
|
||||
floating battery pin
|
||||
|
||||
Bench tests of the MESH protocol without a radio (--binary): the chunks go
|
||||
through `fw bin`, which feeds the very handler a binary request over the mesh
|
||||
reaches, padded to the AES block as the node sees it after decryption. Then
|
||||
the missing-units bitmap ('m') decides what to resend, as ota_mesh_push.py does.
|
||||
the missing-units bitmap ('m') decides what to resend, as over the mesh.
|
||||
--drop P lose P % of the chunks of the first round on purpose
|
||||
--prime FILE first send the manifest of ANOTHER package and abort, so it
|
||||
stays in the stage flash
|
||||
@@ -36,242 +44,33 @@ that failed `fw verify`.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import base64
|
||||
import glob
|
||||
import os
|
||||
import importlib
|
||||
import random
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
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")
|
||||
console = importlib.import_module(f"{PKG}.meshcore_console")
|
||||
|
||||
MAC_RE = re.compile(r"^[0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}$")
|
||||
NUS_RX = "6e400002-b5a3-f393-e0a9-e50e24dcca9e" # write (host -> node)
|
||||
NUS_TX = "6e400003-b5a3-f393-e0a9-e50e24dcca9e" # notify (node -> host)
|
||||
|
||||
CHUNK = 96 # FW_OTA_CHUNK
|
||||
BCHUNK = 96 # binary over USB: base64 of 7 + 96 B fits the 160 B console line
|
||||
UNIT = 32 # FW_OTA_UNIT
|
||||
|
||||
|
||||
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
|
||||
)
|
||||
|
||||
|
||||
def fw_bin(s, payload: bytes) -> bytes | None:
|
||||
r = command(s, "fw bin " + base64.b64encode(payload).decode())
|
||||
if r.startswith("ERR"):
|
||||
sys.exit(f"fw bin: {r}")
|
||||
r = r.lstrip("> ").strip()
|
||||
return None if r == "-" else bytes.fromhex(r)
|
||||
|
||||
|
||||
def bin_missing(s) -> tuple[int, list[int]]:
|
||||
d = fw_bin(s, bytes([0xF0, ord("m")]))
|
||||
if not d or len(d) < 5:
|
||||
sys.exit(f"'m' reply: {d!r}")
|
||||
cnt = int.from_bytes(d[3:5], "little")
|
||||
have = (len(d) - 5) // 2 # the console prints a shortened list
|
||||
return d[0], [
|
||||
int.from_bytes(d[5 + 2 * i : 7 + 2 * i], "little")
|
||||
for i in range(min(cnt, have))
|
||||
]
|
||||
|
||||
|
||||
def send_binary(
|
||||
s, data: bytes, drop: float, sid: int, stale: bytes | None = None
|
||||
) -> None:
|
||||
if stale:
|
||||
# chunks of ANOTHER session (as if a late packet of an earlier transfer):
|
||||
# the node must drop them, or the manifest check sees the wrong package
|
||||
for off in (0, BCHUNK, 2 * BCHUNK):
|
||||
c = stale[off : off + BCHUNK]
|
||||
fw_bin(
|
||||
s,
|
||||
w_payload((sid ^ 0x5A5A), off, c),
|
||||
)
|
||||
print("sent 3 stale chunks of another session")
|
||||
todo = list(range((len(data) + BCHUNK - 1) // BCHUNK))
|
||||
for rnd in range(10):
|
||||
lost = 0
|
||||
for i in todo:
|
||||
if rnd == 0 and random.random() < drop / 100:
|
||||
lost += 1
|
||||
continue
|
||||
off = i * BCHUNK
|
||||
chunk = data[off : off + BCHUNK]
|
||||
if fw_bin(
|
||||
s,
|
||||
w_payload(sid, off, chunk),
|
||||
):
|
||||
sys.exit("a 'w' got a reply, it must not")
|
||||
if stale and rnd == 0:
|
||||
# and again AFTER the real manifest chunks: the order seen on the bench
|
||||
for off in (0, BCHUNK, 2 * BCHUNK):
|
||||
c = stale[off : off + BCHUNK]
|
||||
fw_bin(
|
||||
s,
|
||||
w_payload((sid ^ 0x5A5A), off, c),
|
||||
)
|
||||
state, miss = bin_missing(s)
|
||||
for _ in range(20):
|
||||
if state != 4:
|
||||
break
|
||||
time.sleep(0.3)
|
||||
state, miss = bin_missing(s)
|
||||
print(
|
||||
f"round {rnd + 1}: sent {len(todo) - lost}, dropped {lost}, state {state}, missing {len(miss)}+"
|
||||
)
|
||||
if state == 3:
|
||||
sys.exit(f"node: {command(s, 'fw status')}")
|
||||
if not miss:
|
||||
return
|
||||
todo = sorted({u * UNIT // BCHUNK for u in miss})
|
||||
sys.exit("binary transfer did not converge")
|
||||
|
||||
|
||||
class BleConsole:
|
||||
"""The node's BLE console (NUS) behind the few serial calls this tool makes:
|
||||
write, read, reset_input_buffer, close. bleak runs in its own thread."""
|
||||
|
||||
def __init__(self, mac: str):
|
||||
import asyncio
|
||||
import threading
|
||||
|
||||
from bleak import BleakClient, BleakScanner
|
||||
|
||||
self._asyncio = asyncio
|
||||
self._buf = bytearray()
|
||||
self._lock = threading.Lock()
|
||||
self._loop = asyncio.new_event_loop()
|
||||
threading.Thread(target=self._loop.run_forever, daemon=True).start()
|
||||
|
||||
async def connect():
|
||||
last = None
|
||||
for attempt in range(5): # BLE connects are flaky, as in ble_cli.py
|
||||
try:
|
||||
dev = await BleakScanner.find_device_by_address(mac, timeout=20)
|
||||
if dev is None:
|
||||
raise RuntimeError("not advertising (already connected?)")
|
||||
c = BleakClient(dev, timeout=30)
|
||||
await c.connect()
|
||||
await c.start_notify(NUS_TX, self._rx)
|
||||
return c
|
||||
except Exception as e: # noqa: BLE001
|
||||
last = e
|
||||
print(f" [connect {attempt + 1}/5] {type(e).__name__}: {e}", flush=True)
|
||||
await asyncio.sleep(4)
|
||||
raise RuntimeError(f"cannot connect to {mac}: {last}")
|
||||
|
||||
try:
|
||||
self._c = self._run(connect())
|
||||
except RuntimeError as e:
|
||||
sys.exit(str(e))
|
||||
# A NUS write carries at most ATT_MTU-3 bytes and BlueZ does not split it
|
||||
# (ble_cli.py); at the default MTU 23 a chunk line goes out in 8 writes.
|
||||
self._chunk = max(20, int(getattr(self._c, "mtu_size", 23)) - 3)
|
||||
|
||||
def _run(self, coro):
|
||||
return self._asyncio.run_coroutine_threadsafe(coro, self._loop).result()
|
||||
|
||||
def _rx(self, _handle, data: bytearray) -> None:
|
||||
with self._lock:
|
||||
self._buf.extend(data)
|
||||
|
||||
def reset_input_buffer(self) -> None:
|
||||
with self._lock:
|
||||
self._buf.clear()
|
||||
|
||||
def write(self, data: bytes) -> None:
|
||||
async def w():
|
||||
for i in range(0, len(data), self._chunk):
|
||||
await self._c.write_gatt_char(NUS_RX, data[i : i + self._chunk], response=False)
|
||||
await self._asyncio.sleep(0.05)
|
||||
|
||||
self._run(w())
|
||||
|
||||
def read(self, n: int) -> bytes:
|
||||
time.sleep(0.01)
|
||||
with self._lock:
|
||||
d = bytes(self._buf[:n])
|
||||
del self._buf[:n]
|
||||
return d
|
||||
|
||||
def close(self) -> None:
|
||||
try:
|
||||
self._run(self._c.disconnect())
|
||||
except Exception as e: # noqa: BLE001 -- after `fw apply` the node is gone already
|
||||
print(f"(disconnect: {type(e).__name__})")
|
||||
finally:
|
||||
self._loop.call_soon_threadsafe(self._loop.stop)
|
||||
|
||||
|
||||
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 open_console(target: str):
|
||||
if MAC_RE.match(target):
|
||||
return BleConsole(target)
|
||||
from board_probe import _open as open_port
|
||||
|
||||
return open_port(resolve(target))
|
||||
|
||||
|
||||
def resolve(target: str) -> str:
|
||||
"""Same rules as serial_cli.py: fleet name, bare serial number, or a path."""
|
||||
if target.startswith("/"):
|
||||
@@ -285,6 +84,28 @@ def resolve(target: str) -> str:
|
||||
return hits[0]
|
||||
|
||||
|
||||
class EchoLog(list):
|
||||
def append(self, line):
|
||||
print(line, flush=True)
|
||||
super().append(line)
|
||||
|
||||
|
||||
async def push(args: argparse.Namespace) -> int:
|
||||
"""The ordinary transfer: the engine over the node's console."""
|
||||
con = console.BleConsole(args.board) if MAC_RE.match(args.board) else console.SerialConsole(resolve(args.board))
|
||||
io = engine.Console(con, log=EchoLog())
|
||||
try:
|
||||
out = await engine.update(io, args.package, apply=args.apply, force=args.force)
|
||||
except (engine.OtaError, console.ConsoleError, ValueError, OSError) as e:
|
||||
print(f"FAILED: {e}")
|
||||
return 1
|
||||
print(f"{out['state']}: {out.get('package', '-')} {out.get('version_after') or out.get('version') or ''}")
|
||||
return NO_PACKAGE if out["no_package"] else 0
|
||||
|
||||
|
||||
# ── bench harness: the mesh protocol through `fw bin` (USB only) ─────────────
|
||||
|
||||
|
||||
def command(s, line: str, timeout: float = 5.0) -> str:
|
||||
"""One console command, returns the reply after '-> '."""
|
||||
s.reset_input_buffer()
|
||||
@@ -294,7 +115,7 @@ def command(s, line: str, timeout: float = 5.0) -> str:
|
||||
d = s.read(4096)
|
||||
if d:
|
||||
buf += d
|
||||
m = re.search(rb"-> ?(.*?)\r?\n", buf)
|
||||
m = console.REPLY.search(buf)
|
||||
if m:
|
||||
return m.group(1).decode(errors="replace").strip()
|
||||
else:
|
||||
@@ -302,81 +123,95 @@ def command(s, line: str, timeout: float = 5.0) -> str:
|
||||
raise TimeoutError(f"no reply to {line[:40]!r}: {buf[-200:]!r}")
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(
|
||||
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
|
||||
)
|
||||
ap.add_argument("board", help="board name (local config), USB serial number, or port path")
|
||||
ap.add_argument("package")
|
||||
ap.add_argument("--apply", action="store_true")
|
||||
ap.add_argument(
|
||||
"--force",
|
||||
action="store_true",
|
||||
help="apply below the battery gate (`fw apply force`, local console only): "
|
||||
"a bench board without a cell reads its floating battery pin",
|
||||
)
|
||||
ap.add_argument("--binary", action="store_true")
|
||||
ap.add_argument("--drop", type=float, default=0.0)
|
||||
ap.add_argument("--prime")
|
||||
ap.add_argument(
|
||||
"--stale", help="package whose chunks are injected with a wrong session id"
|
||||
)
|
||||
args = ap.parse_args()
|
||||
def fw_bin(s, payload: bytes) -> bytes | None:
|
||||
r = command(s, "fw bin " + base64.b64encode(payload).decode())
|
||||
if r.startswith("ERR"):
|
||||
sys.exit(f"fw bin: {r}")
|
||||
r = r.lstrip("> ").strip()
|
||||
return None if r == "-" else bytes.fromhex(r)
|
||||
|
||||
if args.binary and MAC_RE.match(args.board):
|
||||
sys.exit("--binary is a bench test of the mesh path: USB only")
|
||||
s = open_console(args.board)
|
||||
|
||||
def bin_missing(s) -> tuple[int, list[int]]:
|
||||
d = fw_bin(s, bytes([ota.REQ_FW, ord("m")]))
|
||||
st = ota.parse_missing(d or b"")
|
||||
if st is None:
|
||||
sys.exit(f"'m' reply: {d!r}")
|
||||
have = (len(d or b"") - 5) // 2 # the console prints a shortened list
|
||||
return st[0], st[1][:have]
|
||||
|
||||
|
||||
def send_binary(s, data: bytes, drop: float, sid: int, stale: bytes | None = None) -> None:
|
||||
def inject():
|
||||
# chunks of ANOTHER session (as if a late packet of an earlier transfer):
|
||||
# the node must drop them, or the manifest check sees the wrong package
|
||||
for off in (0, BCHUNK, 2 * BCHUNK):
|
||||
fw_bin(s, ota.w_payload(sid ^ 0x5A5A, off, stale[off : off + BCHUNK]))
|
||||
|
||||
if stale:
|
||||
inject()
|
||||
print("sent 3 stale chunks of another session")
|
||||
todo = list(range((len(data) + BCHUNK - 1) // BCHUNK))
|
||||
for rnd in range(10):
|
||||
lost = 0
|
||||
for i in todo:
|
||||
if rnd == 0 and random.random() < drop / 100:
|
||||
lost += 1
|
||||
continue
|
||||
off = i * BCHUNK
|
||||
if fw_bin(s, ota.w_payload(sid, off, data[off : off + BCHUNK])):
|
||||
sys.exit("a 'w' got a reply, it must not")
|
||||
if stale and rnd == 0:
|
||||
inject() # and again AFTER the real manifest chunks: the order seen on the bench
|
||||
state, miss = bin_missing(s)
|
||||
for _ in range(20):
|
||||
if state != 4:
|
||||
break
|
||||
time.sleep(0.3)
|
||||
state, miss = bin_missing(s)
|
||||
print(f"round {rnd + 1}: sent {len(todo) - lost}, dropped {lost}, state {state}, missing {len(miss)}+")
|
||||
if state == 3:
|
||||
sys.exit(f"node: {command(s, 'fw status')}")
|
||||
if not miss:
|
||||
return
|
||||
todo = sorted({u * ota.UNIT // BCHUNK for u in miss})
|
||||
sys.exit("binary transfer did not converge")
|
||||
|
||||
|
||||
def bench(args: argparse.Namespace) -> int:
|
||||
from board_probe import _open as open_port
|
||||
|
||||
s = open_port(resolve(args.board))
|
||||
try:
|
||||
if not isinstance(s, BleConsole): # over BLE its reply comes late, as the next one's
|
||||
s.write(b"\r\n")
|
||||
time.sleep(0.4)
|
||||
s.write(b"\r\n")
|
||||
time.sleep(0.4)
|
||||
st = command(s, "fw status")
|
||||
print("status:", st)
|
||||
data = pick_package(args.package, st, full_ok=True)
|
||||
base = ota.parse_status(st)
|
||||
if base is None:
|
||||
print("no base image in `fw status`: not an -ota build")
|
||||
return NO_PACKAGE
|
||||
kind, pkg = ota.pick(engine.load_packages(args.package), base[1], full_ok=True)
|
||||
if kind == "current":
|
||||
print(f"the node already runs the image of {pkg.name}")
|
||||
return 0
|
||||
if kind == "none":
|
||||
print(f"no package in {args.package} starts from {base[1]}")
|
||||
return NO_PACKAGE
|
||||
print(f"package: {pkg.name} ({kind})")
|
||||
data = pkg.data
|
||||
if args.prime:
|
||||
with open(args.prime, "rb") as f:
|
||||
other = f.read()
|
||||
other = Path(args.prime).read_bytes()
|
||||
command(s, f"fw begin {len(other)}")
|
||||
for off in range(0, 256, CHUNK):
|
||||
command(
|
||||
s,
|
||||
f"fw w {off} {base64.b64encode(other[off : off + CHUNK]).decode()}",
|
||||
)
|
||||
for off in range(0, ota.MANIFEST, ota.CHUNK):
|
||||
command(s, f"fw w {off} {base64.b64encode(other[off : off + ota.CHUNK]).decode()}")
|
||||
time.sleep(1) # let loop() check and flush it
|
||||
print(
|
||||
"primed with",
|
||||
args.prime,
|
||||
"->",
|
||||
command(s, "fw status"),
|
||||
"/",
|
||||
command(s, "fw abort"),
|
||||
)
|
||||
print("primed with", args.prime, "->", command(s, "fw status"), "/", command(s, "fw abort"))
|
||||
sid = random.randint(1, 0xFFFF)
|
||||
r = command(s, f"fw begin {len(data)} {sid}")
|
||||
print("begin:", r)
|
||||
if not r.startswith("OK"):
|
||||
sys.exit(1)
|
||||
t0 = time.time()
|
||||
n = 0 if args.binary else (len(data) + CHUNK - 1) // CHUNK
|
||||
if args.binary:
|
||||
stale = None
|
||||
if args.stale:
|
||||
with open(args.stale, "rb") as f:
|
||||
stale = f.read()
|
||||
send_binary(s, data, args.drop, sid, stale)
|
||||
for i in range(n):
|
||||
off = i * CHUNK
|
||||
b64 = base64.b64encode(data[off : off + CHUNK]).decode()
|
||||
r = command(s, f"fw w {off} {b64}")
|
||||
if r != "ok":
|
||||
sys.exit(f"chunk {off}: {r}")
|
||||
if i % 200 == 0 or i == n - 1:
|
||||
print(
|
||||
f"\r{i + 1}/{n} chunks, {time.time() - t0:.0f} s",
|
||||
end="",
|
||||
flush=True,
|
||||
)
|
||||
print()
|
||||
return 1
|
||||
send_binary(s, data, args.drop, sid, Path(args.stale).read_bytes() if args.stale else None)
|
||||
print("missing:", command(s, "fw missing"))
|
||||
r = command(s, "fw verify", timeout=30)
|
||||
t1 = time.time()
|
||||
@@ -385,13 +220,33 @@ def main() -> None:
|
||||
r = command(s, "fw status")
|
||||
print("verify:", r)
|
||||
if "ready" not in r:
|
||||
sys.exit(1)
|
||||
return 1
|
||||
print("bootloader:", command(s, "fw bl"))
|
||||
if args.apply:
|
||||
print("apply:", command(s, "fw apply force" if args.force else "fw apply", timeout=10))
|
||||
return 0
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("board", help="board name (local config), USB serial number, port path, or BLE MAC")
|
||||
ap.add_argument("package")
|
||||
ap.add_argument("--apply", action="store_true")
|
||||
ap.add_argument("--force", action="store_true")
|
||||
ap.add_argument("--binary", action="store_true")
|
||||
ap.add_argument("--drop", type=float, default=0.0)
|
||||
ap.add_argument("--prime")
|
||||
ap.add_argument("--stale", help="package whose chunks are injected with a wrong session id")
|
||||
args = ap.parse_args()
|
||||
harness = args.binary or args.drop or args.prime or args.stale
|
||||
if harness and MAC_RE.match(args.board):
|
||||
sys.exit("--binary/--drop/--prime/--stale are a bench test of the mesh path: USB only")
|
||||
if harness and not args.binary:
|
||||
sys.exit("--drop/--prime/--stale go with --binary")
|
||||
sys.exit(bench(args) if harness else asyncio.run(push(args)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user