Files
tthandClaude Opus 5.5 185470de08
ci / test (push) Failing after 15s
meshcore_fw_ota: the transfer as an Ansible-free engine shared with meshcore-tth's tools, plus a side channel via tempradio
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>
2026-11-16 23:17:41 +01:00

156 lines
5.9 KiB
Python

"""The text console of a meshcore-tth repeater over BLE (Nordic UART Service),
or over USB serial (SerialConsole, the same calls).
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
try:
import serial
HAS_SERIAL = True
except ImportError:
HAS_SERIAL = 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")
class SerialConsole:
"""The same console on USB (CDC): a port path, preferably /dev/serial/by-id/."""
def __init__(self, port):
self.port = port
self.s = None
self.log = []
async def open(self):
try:
self.s = serial.Serial(self.port, 115200, timeout=0)
except (OSError, serial.SerialException) as e:
raise ConsoleError(f"cannot open {self.port}: {e}") from None
self.s.dtr = True
self.s.rts = True
await asyncio.sleep(0.9)
# wake the console; over USB the bare line's reply is drained right here
self.s.write(b"\r\n")
await asyncio.sleep(0.4)
self.s.reset_input_buffer()
self.log.append(f"USB console {self.port} open")
async def close(self):
if self.s is not None:
try:
self.s.close()
except (OSError, serial.SerialException) as e: # after `fw apply` the port is gone already
self.log.append(f"USB close: {type(e).__name__}")
self.s = None
async def cmd(self, line, timeout=5.0, quiet=False):
"""One console command -> the reply after '-> '."""
self.s.reset_input_buffer()
self.s.write(line.encode() + b"\r\n")
buf = b""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
d = self.s.read(4096)
except (OSError, serial.SerialException) as e:
raise ConsoleError(f"USB console: {e}") from None
if d:
buf += d
m = REPLY.search(buf)
if m:
text = m.group(1).decode(errors="replace").strip()
if not quiet:
self.log.append(f"$ {line} -> {text}")
return text
else:
await asyncio.sleep(0.005)
shown = line if len(line) <= 24 else line[:24] + "..."
raise ConsoleError(f"no reply to `{shown}` on the USB console")