ota_push.py: the BLE console as a transport (MAC instead of a USB board), --force
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f7bd88c1c8
commit
96cbd7333a
1 file changed
+109
-8
+109
-8
@@ -1,13 +1,17 @@
|
||||
#!/usr/bin/env python3
|
||||
# SPDX-License-Identifier: MIT
|
||||
"""Push an OTA package (tools/ota_pack.py) to a node over its USB console.
|
||||
"""Push an OTA package (tools/ota_pack.py) to a node over its USB or BLE console.
|
||||
|
||||
tools/ota_push.py b1 Xiao_nrf52_repeater-ota.mcfw # transfer + verify
|
||||
tools/ota_push.py b1 Xiao_nrf52_repeater-ota.mcfw --apply # ... and apply
|
||||
tools/ota_push.py b1 pkg.mcfw --binary --drop 30 --prime old.mcfw
|
||||
tools/ota_push.py CE:72:14:CD:FD:02 pkg.mcfw --apply # over BLE (NUS)
|
||||
|
||||
The board: a name from the local config (tools/mctools_config.py), a USB
|
||||
serial number or a port path.
|
||||
serial number, a port path -- or a BLE MAC: the node's BLE console, bonded
|
||||
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.
|
||||
|
||||
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
|
||||
@@ -36,8 +40,10 @@ import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from board_probe import _open as open_port
|
||||
from fleet import serial_for
|
||||
|
||||
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
|
||||
@@ -139,10 +145,96 @@ def send_binary(
|
||||
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)
|
||||
|
||||
|
||||
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("/"):
|
||||
return target
|
||||
from fleet import serial_for
|
||||
|
||||
sn = serial_for(target)
|
||||
hits = [p for p in sorted(glob.glob("/dev/serial/by-id/*")) if sn in p]
|
||||
if len(hits) != 1:
|
||||
@@ -174,6 +266,12 @@ def main() -> None:
|
||||
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")
|
||||
@@ -184,10 +282,13 @@ def main() -> None:
|
||||
|
||||
with open(args.package, "rb") as f:
|
||||
data = f.read()
|
||||
s = open_port(resolve(args.board))
|
||||
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)
|
||||
try:
|
||||
s.write(b"\r\n")
|
||||
time.sleep(0.4)
|
||||
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)
|
||||
print("status:", command(s, "fw status"))
|
||||
if args.prime:
|
||||
with open(args.prime, "rb") as f:
|
||||
@@ -244,7 +345,7 @@ def main() -> None:
|
||||
sys.exit(1)
|
||||
print("bootloader:", command(s, "fw bl"))
|
||||
if args.apply:
|
||||
print("apply:", command(s, "fw apply", timeout=10))
|
||||
print("apply:", command(s, "fw apply force" if args.force else "fw apply", timeout=10))
|
||||
finally:
|
||||
s.close()
|
||||
|
||||
|
||||
Reference in new issue
Block a user