From 5d64aad5e9cfffbac8c8cd0f63fad27162d35f41 Mon Sep 17 00:00:00 2001 From: Shivtej Gaikwad <91597404+ShivtejG236@users.noreply.github.com> Date: Fri, 13 Nov 2026 19:34:20 +0000 Subject: [PATCH] Decode the firmware's binary wire protocol in the logger - pipeline/wire.py: COBS/CRC-16 frame decoder and a StreamDecoder that detects binary vs CSV firmware and yields the same events for both - logger writes the same raw.csv either way, records the firmware's identity in raw/firmware.json, and reports lost frames and CRC errors - refuse firmware with an unknown protocol version - tests against a golden stream generated by the firmware's encoder --- .gitattributes | 1 + CHANGELOG.md | 14 ++ README.md | 3 +- pipeline/logger.py | 122 +++++++-------- pipeline/wire.py | 236 ++++++++++++++++++++++++++++++ run_pipeline.py | 4 + tests/fixtures/wire_golden_v1.bin | Bin 0 -> 960 bytes tests/test_logger.py | 93 ++++++++++-- tests/test_wire.py | 121 +++++++++++++++ 9 files changed, 520 insertions(+), 74 deletions(-) create mode 100644 pipeline/wire.py create mode 100644 tests/fixtures/wire_golden_v1.bin create mode 100644 tests/test_wire.py diff --git a/.gitattributes b/.gitattributes index dfe0770..f8baf15 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,3 @@ # Auto detect text files and perform LF normalization * text=auto +*.bin binary diff --git a/CHANGELOG.md b/CHANGELOG.md index e5d275a..0860b3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,20 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/). ## [Unreleased] +### Added +- `pipeline/wire.py`: decoder for the firmware's binary wire protocol v1 + (COBS framing, CRC-16), tested against a golden stream produced by the + firmware's own encoder. +- The logger detects which firmware build is on the board (binary or CSV + debug) and writes the same `raw.csv` for both. +- `raw/firmware.json` records the board, firmware version and git revision + the firmware reported; `metadata.json` includes it. +- The logger reports frames lost on the wire and CRC errors. + +### Changed +- The logger refuses firmware that speaks a newer wire protocol than it knows. +- A CSV header reprinted after a reboot is no longer written as a data row. + ### Added - MIT `LICENSE` file (the README badge already pointed at one). - Test suite (`pytest`) covering the logger, trimmer, diagnostics, calibrator diff --git a/README.md b/README.md index 7f927f5..d72d555 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ The pipeline follows a deterministic multi-stage flow: | Stage | Module | Responsibility | Output | |---|---|---|---| -| **1. Log** | `logger.py` | High-speed serial → CSV | `raw/raw.csv` | +| **1. Log** | `logger.py` + `wire.py` | Binary frames (or CSV debug stream) → CSV | `raw/raw.csv`, `raw/firmware.json` | | **2. Trim** | `session_trimmer.py` | Signal/Noise segmentation | `clean/signal_v1.csv` | | **3. Diagnose** | `diagnostics.py` | Timing, jitter & alignment | `diagnostics/timing_v1.json` | | **4. Calibrate** | `calibrator.py` | Bias, scale & hard-iron | `calibrated/calibrated_v1.csv` | @@ -193,6 +193,7 @@ data-pipeline/ │ └── reports/ # Markdown session summaries ├── pipeline/ │ ├── logger.py # High-speed UART listener +│ ├── wire.py # Wire protocol v1 decoder (binary + CSV detection) │ ├── session_trimmer.py # Signal/Noise segmenter │ ├── diagnostics.py # Timing & jitter analysis │ ├── calibrator.py # Bias, scale & hard-iron calibration diff --git a/pipeline/logger.py b/pipeline/logger.py index 48dfe75..a42a03c 100644 --- a/pipeline/logger.py +++ b/pipeline/logger.py @@ -10,14 +10,15 @@ Output: logs/session_YYYYMMDD_HHMMSS.csv + logs/firmware.json — what the firmware said about itself (binary builds) - A new file is created each run. The CSV header is taken from the - firmware's first non-comment line, so column names stay in sync - automatically. + A new file is created each run. Both firmware builds are understood: + the default binary wire protocol and the CSV debug build (see wire.py). """ import argparse import csv +import json import sys import time from datetime import datetime @@ -26,6 +27,8 @@ import serial import serial.tools.list_ports +import wire + # ── CONFIG ──────────────────────────────────────────── BAUD = 921600 TIMEOUT_S = 2.0 @@ -113,72 +116,72 @@ def log_session(out_path: Path, port: str | None = None, timeout: int = 30) -> i rows_written = 0 csv_writer = None csv_file = None + decoder = wire.StreamDecoder() + last_drops = 0 t_start = time.time() try: with serial.Serial(port, BAUD, timeout=TIMEOUT_S) as ser: - print(" Opened serial port. Waiting for firmware header…") + print(" Opened serial port. Waiting for firmware…") - # Pulse DTR to reset the ESP32 so it reprints the header. - # Without this, if the ESP32 booted before we connected we miss - # the header and time out. + # Pulse DTR to reset the ESP32 so it announces itself straight away. + # (Binary firmware also repeats its hello every 2 s, CSV firmware + # only prints its header at boot.) ser.dtr = False time.sleep(0.1) ser.dtr = True time.sleep(0.5) - # Wait for header line (first non-comment line from firmware) - header_cols = None deadline = time.time() + timeout - while time.time() < deadline: - raw = ser.readline() - if not raw: - continue - line = raw.decode("utf-8", errors="replace").strip() - if line.startswith("#"): - print(f" [FW] {line[2:].strip()}") - continue - if "t_imu_us" in line: - header_cols = [c.strip() for c in line.split(",")] - print(f" Header received ({len(header_cols)} columns).") - break - - if header_cols is None: - print("ERROR: No header received within timeout. Is firmware running?") - sys.exit(1) - - csv_file = open(out_path, "w", newline="", buffering=1) - csv_writer = csv.DictWriter(csv_file, fieldnames=header_cols, - extrasaction="ignore") - csv_writer.writeheader() - - print(f" Logging… (preview every {PREVIEW_EVERY} rows)\n") - while True: - raw = ser.readline() - if not raw: + chunk = ser.read(max(1, getattr(ser, "in_waiting", 0) or 1)) + if csv_writer is None and time.time() > deadline: + print("ERROR: Firmware did not identify itself within the timeout. Is it running?") + sys.exit(1) + if not chunk: continue - line = raw.decode("utf-8", errors="replace").strip() - - # Pass firmware comments straight to terminal - if line.startswith("#"): - print(f"\n [FW] {line[2:].strip()}") - continue - if not line: - continue - - cols = line.split(",") - if len(cols) != len(header_cols): - # Malformed row (e.g. partial write at startup) — show it instead of silently dropping - print(f"\n [UNEXPECTED] {line}") - continue - - row = dict(zip(header_cols, cols)) - csv_writer.writerow(row) - rows_written += 1 - if rows_written % PREVIEW_EVERY == 0: - preview(row, rows_written, t_start) + for ev in decoder.feed(chunk): + if ev.kind == "log": + print(f"\n [FW] {ev.payload}") + + elif ev.kind == "hello": + if csv_writer is not None: + continue # periodic repeat + info = ev.payload + if info["proto"] not in (0, wire.PROTO_VERSION): + print(f"ERROR: Firmware speaks wire protocol v{info['proto']}; " + f"this logger understands v{wire.PROTO_VERSION}. Update the pipeline.") + sys.exit(1) + if decoder.mode == "binary": + print(f" Firmware : {info.get('fw', '?')} ({info.get('git', '?')}) " + f"on {info.get('board', '?')}, sensors: {info.get('sensors', '?')}") + out_path.with_name("firmware.json").write_text(json.dumps(info, indent=2)) + else: + print(" Firmware : CSV debug build") + csv_file = open(out_path, "w", newline="", buffering=1) # noqa: SIM115 + csv_writer = csv.DictWriter(csv_file, fieldnames=decoder.header, + extrasaction="ignore") + csv_writer.writeheader() + t_start = time.time() + print(f" Logging {decoder.mode} stream… (preview every {PREVIEW_EVERY} rows)\n") + + elif ev.kind == "row": + if csv_writer is None: + continue # attached mid-stream: wait for the hello + csv_writer.writerow(ev.payload) + rows_written += 1 + if rows_written % PREVIEW_EVERY == 0: + preview(ev.payload, rows_written, t_start) + + elif ev.kind == "status": + if decoder.rb_drops > last_drops: + print(f"\n [FW] rb_drops={decoder.rb_drops}") + last_drops = decoder.rb_drops + + elif ev.kind == "bad": + # Malformed CSV row (e.g. partial write at startup) — show it instead of silently dropping + print(f"\n [UNEXPECTED] {ev.payload}") except KeyboardInterrupt: print("\n\n Stopped by user.") @@ -191,9 +194,14 @@ def log_session(out_path: Path, port: str | None = None, timeout: int = 30) -> i elapsed = time.time() - t_start print(f" Rows written : {rows_written:,}") print(f" Duration : {elapsed:.1f} s") - print(f" Avg rate : {rows_written/elapsed:.1f} Hz" if elapsed > 0 else "") + if elapsed > 0: + print(f" Avg rate : {rows_written/elapsed:.1f} Hz") + if decoder.mode == "binary": + print(f" Lost frames : {decoder.lost_frames:,} (CRC errors: {decoder.crc_errors:,})") + print(f" FW rb_drops : {decoder.rb_drops:,}") print(f" File : {out_path}") - print(f" File size : {out_path.stat().st_size / 1024:.1f} KB" if rows_written > 0 else "") + if rows_written > 0: + print(f" File size : {out_path.stat().st_size / 1024:.1f} KB") return rows_written diff --git a/pipeline/wire.py b/pipeline/wire.py new file mode 100644 index 0000000..2755126 --- /dev/null +++ b/pipeline/wire.py @@ -0,0 +1,236 @@ +#!/usr/bin/env python3 +""" +wire.py — Decoder for the firmware's host stream. + +The firmware speaks one of two formats on UART0: + + binary (default) COBS( type | body | crc16 ) 0x00 — wire protocol v1 + csv (debug) "# comment" lines, a header line, then one CSV row per sample + +StreamDecoder accepts raw bytes from the serial port, works out which format +it is looking at, and turns either one into the same stream of events, so the +logger does not care which firmware build is on the board. + +The protocol is specified in the firmware repo: docs/wire-protocol.md. +""" + +import binascii +import struct +from dataclasses import dataclass, field + +PROTO_VERSION = 1 + +HELLO, SAMPLE, STATUS, LOG = 0x01, 0x02, 0x03, 0x04 + +# Column order of the CSV the pipeline works on (identical to the CSV firmware build). +CSV_COLUMNS = [ + "t_imu_us", "t_read_start_us", "t_proc_end_us", "t_gps_us", + "ax_g", "ay_g", "az_g", "gx_dps", "gy_dps", "gz_dps", + "mx_uT", "my_uT", "mz_uT", + "pressure_hPa", "bmp_temp_C", + "lat_deg", "lon_deg", "alt_gps_m", "hdop", "satellites", + "fault_flag", "jitter_us", +] + +# seq, t_imu_us, proc_us, t_gps_us, 6×imu, 3×mag, pressure, temp, lat, lon, alt, hdop, sats, fault, jitter +_SAMPLE = struct.Struct(" int: + """CRC-16/CCITT-FALSE (poly 0x1021, init 0xFFFF).""" + return binascii.crc_hqx(data, 0xFFFF) + + +def cobs_decode(data: bytes) -> bytes: + out = bytearray() + i, n = 0, len(data) + while i < n: + code = data[i] + if code == 0: + raise FrameError("zero byte inside frame") + i += 1 + end = i + code - 1 + if end > n: + raise FrameError("truncated COBS block") + out += data[i:end] + i = end + if code != 0xFF and i < n: + out.append(0) + return bytes(out) + + +def decode_frame(frame: bytes) -> tuple[int, bytes]: + """Decode one frame (without its 0x00 delimiter) into (type, body).""" + raw = cobs_decode(frame) + if len(raw) < 3: + raise FrameError("frame too short") + (crc,) = struct.unpack(" dict: + """HELLO body → {"proto": int, "board": ..., "fw": ..., ...}. Unknown keys are kept.""" + if not body: + raise FrameError("empty HELLO") + info: dict = {"proto": body[0]} + for pair in body[1:].decode("ascii", errors="replace").split(";"): + key, sep, value = pair.partition("=") + if sep: + info[key] = value + return info + + +def _f32(x: float) -> str: + return format(x, ".9g") # enough digits to round-trip a float32 + + +def parse_sample(body: bytes) -> tuple[int, dict]: + """SAMPLE body → (seq, row keyed by CSV_COLUMNS).""" + if len(body) != _SAMPLE.size: + raise FrameError(f"SAMPLE body is {len(body)} bytes, expected {_SAMPLE.size}") + (seq, t_imu, proc, t_gps, ax, ay, az, gx, gy, gz, mx, my, mz, + pressure, temp, lat, lon, alt, hdop, sats, fault, jitter) = _SAMPLE.unpack(body) + values = [ + t_imu, t_imu, t_imu + proc, t_gps, + _f32(ax), _f32(ay), _f32(az), _f32(gx), _f32(gy), _f32(gz), + _f32(mx), _f32(my), _f32(mz), + _f32(pressure), _f32(temp), + repr(lat), repr(lon), _f32(alt), _f32(hdop), sats, + fault, jitter, + ] + return seq, dict(zip(CSV_COLUMNS, (str(v) for v in values))) + + +def parse_status(body: bytes) -> dict: + if len(body) != _STATUS.size: + raise FrameError("bad STATUS body") + rb_drops, samples_sent = _STATUS.unpack(body) + return {"rb_drops": rb_drops, "samples_sent": samples_sent} + + +@dataclass +class Event: + """One decoded item from the stream. + + kind payload + ─────── ───────────────────────────────────────────── + hello dict from parse_hello (binary) / {"proto": 0} (csv header seen); + StreamDecoder.header holds the column names from here on + row dict keyed by column name + status {"rb_drops": int, "samples_sent": int} + log str — a firmware message + bad str — a malformed CSV line + """ + kind: str + payload: object = None + + +@dataclass +class StreamDecoder: + mode: str | None = None # None until detected, then "binary" or "csv" + crc_errors: int = 0 # frames dropped after sync (binary) + lost_frames: int = 0 # gaps in the sample sequence (binary) + rb_drops: int = 0 # last value reported by the firmware + header: list[str] | None = None + _frames: bytearray = field(default_factory=bytearray) + _lines: bytearray = field(default_factory=bytearray) + _next_seq: int | None = None + + def feed(self, data: bytes) -> list[Event]: + events: list[Event] = [] + if self.mode != "csv": + self._frames += data + self._drain_frames(events) + if self.mode != "binary": + self._lines += data + self._drain_lines(events) + return events + + # ── binary ──────────────────────────────────────────────────────────────── + def _drain_frames(self, events: list[Event]) -> None: + while True: + end = self._frames.find(0) + if end < 0: + if len(self._frames) > MAX_FRAME: # noise with no delimiter + del self._frames[:-MAX_FRAME] + return + frame = bytes(self._frames[:end]) + del self._frames[:end + 1] + if not frame: + continue + try: + ftype, body = decode_frame(frame) + event = self._frame_event(ftype, body) + except FrameError: + # Before sync this is boot noise or a partial first frame. + if self.mode == "binary": + self.crc_errors += 1 + continue + if self.mode is None: + self.mode = "binary" + self.header = list(CSV_COLUMNS) + self._lines.clear() + if event is not None: + events.append(event) + + def _frame_event(self, ftype: int, body: bytes) -> Event | None: + if ftype == SAMPLE: + seq, row = parse_sample(body) + if self._next_seq is not None and seq > self._next_seq: + self.lost_frames += seq - self._next_seq + self._next_seq = (seq + 1) & 0xFFFFFFFF # a lower seq means the board rebooted + return Event("row", row) + if ftype == HELLO: + return Event("hello", parse_hello(body)) + if ftype == STATUS: + status = parse_status(body) + self.rb_drops = status["rb_drops"] + return Event("status", status) + if ftype == LOG: + return Event("log", body.decode("utf-8", errors="replace")) + return None # unknown type: ignore, stay in sync + + # ── csv ─────────────────────────────────────────────────────────────────── + def _drain_lines(self, events: list[Event]) -> None: + while True: + end = self._lines.find(b"\n") + if end < 0: + return + line = self._lines[:end].decode("utf-8", errors="replace").strip() + del self._lines[:end + 1] + if not line: + continue + if line.startswith("#"): + text = line[1:].strip() + if text.startswith("rb_drops="): + try: + self.rb_drops = int(text.split("=", 1)[1]) + except ValueError: + pass + if self.mode == "csv" or text.isprintable(): + events.append(Event("log", text)) + continue + if self.header is None: + if "t_imu_us" in line: + self.mode = "csv" + self.header = [c.strip() for c in line.split(",")] + self._frames.clear() + events.append(Event("hello", {"proto": 0})) + continue + cols = line.split(",") + if cols[0].strip() == "t_imu_us": # header reprinted after a reboot + continue + if len(cols) != len(self.header): + events.append(Event("bad", line)) + continue + events.append(Event("row", dict(zip(self.header, cols)))) diff --git a/run_pipeline.py b/run_pipeline.py index ec4629a..a388b94 100644 --- a/run_pipeline.py +++ b/run_pipeline.py @@ -132,10 +132,14 @@ def write_metadata(session_dir: Path, session_type: str, steps_run: list[str], else: detected = list(sensor_map.values()) + # Identity reported by the firmware itself (binary builds only). + firmware = _load_json_safe(session_dir / "raw" / "firmware.json") + meta.update({ "created_at": datetime.now().isoformat(timespec="seconds"), "user_note": user_note, "platform": "ESP32 nav-stack v1", + "firmware": firmware, "sensors": detected, "steps_run": steps_run, "files": { diff --git a/tests/fixtures/wire_golden_v1.bin b/tests/fixtures/wire_golden_v1.bin new file mode 100644 index 0000000000000000000000000000000000000000..2412c680488006be3d41fe99ef78b0cfc1a0ba58 GIT binary patch literal 960 zcmd;Q@eK&oH8U_ZQ1JKu^ME0XkufPhu_(nhwYb38C?&PbI<4H+K+j0ez&bs%#5OT0 z+0e+?#5yy#G(Mxs*3`hjIyW&L#56axPD(7w2QiIIthjA73d8a$w}(ahWx9racEp12eY_12fnf zfnbO=k*L;if~+~JfNTwu9ncEmtzqH2yT0hPi=6Yeaz7 z6i5KAVFp^WAqiqlG!|?8l8~)AK%6yP&_H9816mU)2DF9+XiY;F#F`i^)(ABtSp$xv z1tbKT2GAPELqKa-fz|{RL9B_zV$Jo%NY*eb0FweK)))b;$zcLo!v?fQp$cM692RTl z96`3mfkbO;fYzMh09wNiwB|!2#F}_4)+9VdwkCl@Yutd=cr-IGGXs+V6EJ- bytes: df = make_session(n_rows) rows = [",".join(str(v) for v in r) for r in df.itertuples(index=False)] lines = ["# MPU-6050 OK", "# BMP280 OK", ",".join(COLUMNS)] lines += rows[:10] lines += ["# rb_drops=3", "123,456", ""] # comment, short row, blank lines += rows[10:] - return [(line + "\r\n").encode() for line in lines] + return "".join(line + "\r\n" for line in lines).encode() + + +@pytest.fixture +def fake_port(monkeypatch): + def install(data: bytes): + monkeypatch.setattr(logger.serial, "Serial", lambda *a, **k: FakeSerial(data)) + monkeypatch.setattr(logger.time, "sleep", lambda s: None) + return install @pytest.mark.parametrize("flag,expected", [ @@ -43,9 +61,8 @@ def test_decode_faults(flag, expected): assert logger.decode_faults(flag) == expected -def test_log_session_writes_only_well_formed_rows(tmp_path, monkeypatch): - monkeypatch.setattr(logger.serial, "Serial", lambda *a, **k: FakeSerial(firmware_stream())) - monkeypatch.setattr(logger.time, "sleep", lambda s: None) +def test_csv_firmware_writes_only_well_formed_rows(tmp_path, fake_port): + fake_port(csv_stream()) out = tmp_path / "raw" / "raw.csv" rows = logger.log_session(out, port="/dev/fake") @@ -55,11 +72,55 @@ def test_log_session_writes_only_well_formed_rows(tmp_path, monkeypatch): got = list(csv.DictReader(fh)) assert len(got) == 20 assert list(got[0].keys()) == COLUMNS + assert not (out.parent / "firmware.json").exists() + + +def test_binary_firmware_is_logged_to_the_same_csv_layout(tmp_path, fake_port, capsys): + fake_port(GOLDEN) + out = tmp_path / "raw" / "raw.csv" + + rows = logger.log_session(out, port="/dev/fake") + + assert rows == 8 + with open(out, newline="") as fh: + got = list(csv.DictReader(fh)) + assert list(got[0].keys()) == COLUMNS + assert got[3]["t_imu_us"] == "5006000" + assert got[3]["fault_flag"] == "6" + firmware = json.loads((out.parent / "firmware.json").read_text()) + assert firmware["board"] == "esp32dev" and firmware["fw"] == "0.2.0" + printed = capsys.readouterr().out + assert "[FW] MPU-6050 OK" in printed + assert "rb_drops=3" in printed + + +def test_binary_rows_before_the_hello_are_not_written(tmp_path, fake_port): + frames = GOLDEN.split(b"\x00")[:-1] + hello, samples = frames[1], frames[2:10] + stream = b"\x00".join(samples[:3] + [hello] + samples[3:]) + b"\x00" + fake_port(stream) + + rows = logger.log_session(tmp_path / "raw.csv", port="/dev/fake") + + assert rows == 5 + + +def test_unsupported_protocol_version_is_refused(tmp_path, fake_port): + import struct + + import wire + raw = bytes([wire.HELLO, 99]) + b"board=x" + raw += struct.pack("