"""Station-link client for the bench tests (obu-firmware/docs/station-link.tex, revision 3), over the native USB Serial/JTAG port. Standard library plus pyserial. Written from the spec and main/link_protocol.*, not from the phone app, so it is a second implementation of the host side. Opening the port resets the board (USB Serial/JTAG): a reopen is how the tests get a clean, unconfigured station. """ import collections import os import random import re import struct import threading import time import zlib import serial LINK, LOG = 0x10, 0x7F # opcodes, host -> station STATION_CONFIGURE, POTI_UPDATE, BTP_DATA_REQUEST, CREDENTIALS_PROVISION, CREDENTIALS_ERASE = 0x01, 0x02, 0x03, 0x04, 0x05 SF_IDCHANGE_SUBSCRIBE, SF_IDCHANGE_UNSUBSCRIBE, SF_IDCHANGE_EVENT_RESPONSE, SF_IDCHANGE_TRIGGER = 0x06, 0x07, 0x08, 0x09 SF_ID_LOCK, SF_ID_UNLOCK, STATUS_REQUEST, RAW_CAPTURE, PKI_STATUS = 0x0A, 0x0B, 0x0C, 0x0D, 0x15 # station -> host CONFIRM, BTP_DATA_INDICATION, SF_IDCHANGE_EVENT, RAW_FRAME, PKI_REQUEST_DATA, V2X_RX = 0x80, 0x81, 0x82, 0x85, 0x87, 0x90 CODES = {0: "accepted", 1: "invalid_argument", 2: "unsupported", 3: "wrong_entry_point", 4: "security_unavailable", 5: "resource_limit", 6: "rejected", 7: "time_regression", 8: "identity_change_pending", 0x10: "unknown_opcode", 0x11: "malformed", 0x12: "not_configured", 0x13: "busy", 0x14: "no_credentials"} ACCEPTED, INVALID_ARGUMENT, UNSUPPORTED, RESOURCE_LIMIT, REJECTED, TIME_REGRESSION = 0, 1, 2, 5, 6, 7 UNKNOWN_OPCODE, MALFORMED, NOT_CONFIGURED, NO_CREDENTIALS = 0x10, 0x11, 0x12, 0x14 ITS_EPOCH_UNIX_MS = 1072915200000 # 2004-01-01T00:00:00Z LEAP_SECONDS_MS = 5000 # TimestampIts counts TAI: 5 leap seconds ahead of UTC MAX_FRAME_PAYLOAD = 1536 # serial_link.hpp maximum_payload MAX_MESSAGE = 512 # link message, header included REQUEST_MAX = 1536 # complete host-to-station body PANIC_PATTERNS = re.compile(r"Guru Meditation|abort\(\)|assert failed|Task watchdog|stack overflow|panic|Backtrace:|" r"CORRUPT HEAP|heap_caps_|LoadProhibited|StoreProhibited|Illegal instruction|rst:0x(?!15)|" r"Rebooting|Brownout|brownout", re.I) STATUS_FIELDS = ( # name, offset, struct format; the 131-octet snapshot (link_protocol.cpp encode(Status)) ("uptime_ms", 0, " dict, or None.""" if len(detail) not in (111, 127, 129, 131): return None out = {} for name, off, fmt in STATUS_FIELDS: if off + struct.calcsize(fmt) <= len(detail): out[name] = struct.unpack_from(fmt, detail, off)[0] out["raw_len"] = len(detail) return out # ---------------------------------------------------------------- message bodies -------------------------- def configure_body(secured=False, power=5, channel=180, station_type=2, beaconing=0, mac=None, radio=2): """STATION_CONFIGURE: the 6-octet form, or with `mac` the 16-octet form that names the MAC.""" if mac is None and radio == 2: return struct.pack("I", TEST_STATION_ID) + struct.pack("I", TEST_STATION_ID): return None run_id, seq, size = struct.unpack_from(" [Event, Reply|None, sent_at] self._seq = random.randrange(1000, 30000) self.reader = None self.stop = threading.Event() self.v2x_rx = collections.deque(maxlen=20000) # (t, body) complete V2X_RX messages self.raw_frames = collections.deque(maxlen=20000) # (t, flags, rssi, 802.11 frame) self.counts = collections.Counter() # frames_ok, frames_bad_crc, opcodes, fragments, ... self.frag = {} # (opcode, seq) -> [total, bytearray, t] self.log_lines = collections.deque(maxlen=5000) self.noise = bytearray() # bytes outside frames: ROM boot text, panic output self.boots = 0 # "ESP-ROM:" banners seen on the port since open self.panics = [] # (t, line) of every line matching PANIC_PATTERNS self.opened_at = 0.0 os.makedirs(outdir, exist_ok=True) self.app_version = self.app_compile_time = self.app_project = None # from the boot log (esp app_init lines) self.logfile = open(os.path.join(outdir, "device.log"), "a", encoding="utf-8", buffering=1) self.bootfile = open(os.path.join(outdir, "boot.log"), "a", encoding="utf-8", errors="replace", buffering=1) self.statuslog = open(os.path.join(outdir, "status.csv"), "a", encoding="utf-8", buffering=1) if self.statuslog.tell() == 0: self.statuslog.write("time,phase," + ",".join(n for n, _, _ in STATUS_FIELDS) + "\n") # -- open / close def open(self, boot_wait=4.0, retries=40): last = None for _ in range(retries): try: self.ser = serial.Serial(self.port, self.baud, timeout=0.05, write_timeout=3) break except (serial.SerialException, OSError) as e: # the port briefly disappears when the board resets last = e time.sleep(0.5) else: raise RuntimeError("cannot open %s: %s" % (self.port, last)) self.ser.dtr = False self.ser.rts = False self.stop.clear() self.opened_at = time.time() self.boots = 0 self.noise.clear() self.reader = threading.Thread(target=self._read_loop, daemon=True) self.reader.start() time.sleep(boot_wait) def close(self): self.stop.set() if self.reader: self.reader.join(2) if self.ser: try: self.ser.close() except Exception: pass self.ser = None def reboot(self, boot_wait=4.0): """Close and reopen the port: the board resets. Clears the receive queues.""" self.close() time.sleep(0.7) self.open(boot_wait) self.v2x_rx.clear() self.raw_frames.clear() self.frag.clear() with self.lock: self.pending.clear() # -- reader thread def _read_loop(self): buf = bytearray() while not self.stop.is_set(): try: data = self.ser.read(4096) except (serial.SerialException, OSError, AttributeError, TypeError): time.sleep(0.2) continue if not data: continue buf += data while True: i = buf.find(b"\xAA\x55") if i < 0: if len(buf) > 8192: self._noise(bytes(buf[:-2])) del buf[:-2] break if i > 0: self._noise(bytes(buf[:i])) del buf[:i] if len(buf) < 7: break ftype, n = buf[2], struct.unpack(" MAX_FRAME_PAYLOAD: del buf[:2] self.counts["frames_bad_length"] += 1 continue if len(buf) < 5 + n + 2: break payload = bytes(buf[5:5 + n]) got = struct.unpack("= 2: p[1] = Reply(body[0], body[2:2 + body[1]], now - p[2]) p[0].set() else: self.counts["confirm_unmatched"] += 1 elif op == V2X_RX: self.v2x_rx.append((now, body)) elif op == RAW_FRAME: if len(body) >= 20 and body[6:10] == b"ITS5": n = struct.unpack(" 2.0]: del self.frag[k] self.counts["frag_timeouts"] += 1 if len(body) < 4: self.counts["frag_errors"] += 1 return None total, offset = struct.unpack("= total: self.counts["frag_errors"] += 1 del self.frag[key] return None # -- sending def next_seq(self): self._seq = (self._seq + 1) & 0xFFFF or 1 return self._seq def write(self, data): with self.lock: ser = self.ser if ser is None: raise RuntimeError("port closed") ser.write(data) def send(self, opcode, body=b"", seq=None, flags=0): seq = self.next_seq() if seq is None else seq self.write(frame(LINK, link_message(opcode, seq, body, flags))) return seq def request(self, opcode, body=b"", timeout=2.0, seq=None): """Send one request and wait for its CONFIRM; Reply or None on timeout. A body that does not fit one 512-octet link message is sent in fragments, as the spec requires (the station silently ignores an unfragmented message over 512 octets). """ seq = self.next_seq() if seq is None else seq ev = [threading.Event(), None, time.time()] with self.lock: self.pending[seq] = ev try: if len(body) > MAX_MESSAGE - 4: self.send_fragmented(opcode, body, seq=seq, cap=MAX_MESSAGE - 8) else: self.write(frame(LINK, link_message(opcode, seq, body))) ev[0].wait(timeout) return ev[1] finally: with self.lock: self.pending.pop(seq, None) def send_fragmented(self, opcode, body, seq=None, cap=240, total_override=None): """The request fragments of the spec: flags 1/2/3, then u16 total, u16 offset, data. Returns the sequence.""" seq = self.next_seq() if seq is None else seq total = len(body) if total_override is None else total_override for off in range(0, len(body), cap): chunk = body[off:off + cap] flags = 1 if off == 0 else (3 if off + len(chunk) == len(body) else 2) self.write(frame(LINK, link_message(opcode, seq, struct.pack("= since]