"""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 ' -> '. 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")