Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
# Auto detect text files and perform LF normalization
* text=auto
*.bin binary
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down Expand Up @@ -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
Expand Down
122 changes: 65 additions & 57 deletions pipeline/logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -26,6 +27,8 @@
import serial
import serial.tools.list_ports

import wire

# ── CONFIG ────────────────────────────────────────────
BAUD = 921600
TIMEOUT_S = 2.0
Expand Down Expand Up @@ -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.")
Expand All @@ -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


Expand Down
Loading
Loading