diff --git a/arduino/README.md b/arduino/README.md index 7a6e1ce..64146e3 100644 --- a/arduino/README.md +++ b/arduino/README.md @@ -2,6 +2,12 @@ This submodule contains the firmware for an ESP8266 that reads two light barriers and measures the speed of passing vehicles. It sends the measurement data to the companion app using serial communication. It also controls a relay to trigger the flash when the companion app requests it when it takes a picture. +## Module Architecture + +The firmware follows a monolithic companion architecture with dormant feature modules (e.g. `LapTimer`). All modules compile into a single firmware binary and are activated on-demand via serial commands from the companion daemon (`headless-rust`). + +For implementation details and instructions on adding new modules, see the [Module Architecture Guide](src/modules/README.md). + ## Setup 1. Install the Platformio IDE extension in Visual Studio Code. diff --git a/arduino/src/json_output.cpp b/arduino/src/json_output.cpp index 214cf9b..f02e8a5 100644 --- a/arduino/src/json_output.cpp +++ b/arduino/src/json_output.cpp @@ -3,6 +3,9 @@ #include "config.h" #include "state.h" +#include "modules/laptimer.h" +#include "modules/alignment.h" + // ─── Serial Output Helpers ──────────────────────────────────────────────────── // Serial.flush() is intentionally omitted for most messages: the TX FIFO // buffers them at 115200 baud while the loop continues polling sensors. @@ -58,10 +61,8 @@ void sendJsonPong() { cfg["maxSpeed"] = maxSpeedKmH; cfg["sensorDistance"] = sensorDistance; cfg["debugEnabled"] = debugEnabled; - cfg["lapMode"] = (lapMode == LapMode::MULTI) ? "multi" : "single"; - cfg["lapActive"] = (lapSessionState != LapSessionState::IDLE); - cfg["lapDirFilter"] = (lapDirectionFilter == LapDirectionFilter::FORWARD_ONLY) ? "forward" - : (lapDirectionFilter == LapDirectionFilter::REVERSE_ONLY) ? "reverse" : "both"; + LapTimer::populatePongConfig(cfg); + Alignment::populatePongConfig(cfg); String out; serializeJson(doc, out); out += '\n'; @@ -69,24 +70,13 @@ void sendJsonPong() { Serial.flush(); // Ensure full pong reply is sent before next command is processed } -void sendLapStart(int lapNum, float speedAtStart) { - JsonDocument doc; - doc["status"] = "lapStart"; - doc["lapNumber"] = lapNum; - doc["speedAtStart"] = round(speedAtStart * 10.0f) / 10.0f; - String out; - serializeJson(doc, out); - out += '\n'; - Serial.write(out.c_str(), out.length()); -} - -void sendLapEnd(int lapNum, float durationMs, float speedAtStart, float speedAtEnd) { +void sendJsonCapabilities() { JsonDocument doc; - doc["status"] = "lapEnd"; - doc["lapNumber"] = lapNum; - doc["durationMs"] = durationMs; // full float precision (~0.001 ms) - doc["speedAtStart"] = round(speedAtStart * 10.0f) / 10.0f; - doc["speedAtEnd"] = round(speedAtEnd * 10.0f) / 10.0f; + doc["status"] = "capabilities"; + JsonArray features = doc["features"].to(); + features.add("speed"); + features.add("laptimer"); + features.add("alignment"); String out; serializeJson(doc, out); out += '\n'; diff --git a/arduino/src/json_output.h b/arduino/src/json_output.h index c3eeb27..e60d6d5 100644 --- a/arduino/src/json_output.h +++ b/arduino/src/json_output.h @@ -9,12 +9,9 @@ void sendJsonStatus(const char *status, float value, float tolerance, const char void sendJsonConfig(const char *key, float value); void sendJsonConfigError(const char *message); -// ─── Ping / Pong ───────────────────────────────────────────────────────────── +// ─── Ping / Capabilities ───────────────────────────────────────────────────── void sendJsonPong(); - -// ─── Lap Timer ─────────────────────────────────────────────────────────────── -void sendLapStart(int lapNum, float speedAtStart); -void sendLapEnd(int lapNum, float durationMs, float speedAtStart, float speedAtEnd); +void sendJsonCapabilities(); // ─── Debug ─────────────────────────────────────────────────────────────────── void sendDebug(const String &message); diff --git a/arduino/src/main.cpp b/arduino/src/main.cpp index ea6e857..fd92066 100644 --- a/arduino/src/main.cpp +++ b/arduino/src/main.cpp @@ -3,6 +3,8 @@ #include "state.h" #include "json_output.h" #include "serial_io.h" +#include "modules/laptimer.h" +#include "modules/alignment.h" // ─── State Reset ───────────────────────────────────────────────────────────── void resetMeasurement() { @@ -17,11 +19,16 @@ void setup() { Serial.begin(115200); pinMode(sensor1, INPUT_PULLUP); pinMode(sensor2, INPUT_PULLUP); + LapTimer::init(); + Alignment::init(); sendJsonStatus("ready"); } // ─── Main Loop ─────────────────────────────────────────────────────────────── void loop() { + LapTimer::update(); + Alignment::update(); + // Process incoming serial commands every iteration handleSerial(); if (stringComplete) { @@ -102,68 +109,18 @@ void loop() { resetMeasurement(); if (speedInKmH > 0.0f && speedInKmH < (float)maxSpeedHardCap) { + MeasurementEvent event = { speedInKmH, speedTolerance, direction, boundaryUs }; - // ================================================================ - // SPEED CAMERA MODE (no active lap session) - // Behavior unchanged: host-controlled flash, violation tracking. - // ================================================================ - if (lapSessionState == LapSessionState::IDLE) { - if (speedInKmH > maxSpeedKmH) { - sendJsonStatus("speeding", speedInKmH, speedTolerance, direction); - } else { - sendJsonStatus("legal", speedInKmH, speedTolerance, direction); - } - - // ================================================================ - // LAP TIMER MODE (active lap session) - // Lap boundaries are firstTriggerUs (µs-precise first beam break), - // captured before any serial output or state change. - // ================================================================ + // Base speed status (speeding or legal) + if (speedInKmH > maxSpeedKmH) { + sendJsonStatus("speeding", speedInKmH, speedTolerance, direction); } else { - // Emit speed event for UI display only — no blocking call follows - if (speedInKmH > maxSpeedKmH) { - sendJsonStatus("speeding", speedInKmH, speedTolerance, direction); - } else { - sendJsonStatus("legal", speedInKmH, speedTolerance, direction); - } - - // Direction filter — configured per session - bool passValid = (lapDirectionFilter == LapDirectionFilter::BOTH) - || (lapDirectionFilter == LapDirectionFilter::FORWARD_ONLY && strcmp(direction, "forward") == 0) - || (lapDirectionFilter == LapDirectionFilter::REVERSE_ONLY && strcmp(direction, "reverse") == 0); - - if (passValid) { - if (lapSessionState == LapSessionState::WAITING) { - // ── WAITING → TIMING: open lap N ──────────────────────────────── - lapStartUs = boundaryUs; // µs-precise first beam break - lapStartSpeedKmH = speedInKmH; - lapSessionState = LapSessionState::TIMING; - sendLapStart(lapNumber, speedInKmH); - - } else if (lapSessionState == LapSessionState::TIMING) { - // ── TIMING: close lap N ────────────────────────────────────────── - float lapDurationMs = (float)(boundaryUs - lapStartUs) * 0.001f; - sendLapEnd(lapNumber, lapDurationMs, lapStartSpeedKmH, speedInKmH); - - if (lapMode == LapMode::SINGLE) { - lapSessionState = LapSessionState::WAITING; - lapNumber = 1; - lapStartUs = 0; - lapStartSpeedKmH = 0.0f; - - } else { - // MULTI: this same boundary crossing closes lap N and opens lap N+1. - // Reuse boundaryUs so there is zero gap between consecutive laps. - lapStartUs = boundaryUs; - lapStartSpeedKmH = speedInKmH; - lapNumber++; - // lapSessionState stays TIMING - sendLapStart(lapNumber, speedInKmH); // resets host live timer immediately - } - } - } + sendJsonStatus("legal", speedInKmH, speedTolerance, direction); } + // ponytail: notify active modules with zero heap allocation or dynamic dispatch + LapTimer::onMeasurement(event); + } else { sendJsonStatus("timeout"); // Speed out of valid range — discard } @@ -174,21 +131,24 @@ void loop() { // ─── Protocol Reference ─────────────────────────────────────────────────────── // -// SPEED CAMERA MODE (lapSessionState == IDLE) +// SYSTEM / CORE // Out: speeding {value, tolerance, direction} | legal {value, tolerance, direction} // timeout | measuring | ready | pong | config | configError | jsonError +// capabilities {features: [...]} // In: setMaxSpeed {value:1–250} — set speed limit // setDebug {value:0|1} // ping +// getCapabilities // -// LAP TIMER MODE (lapSessionState != IDLE) +// MODULE: LAP TIMER (dormant until startLapSession received) // Out: lapWaiting — session opened, awaiting first pass // lapStopped — session closed by host // lapStart {lapNumber, speedAtStart} — first beam break // lapEnd {lapNumber, durationMs, speedAtStart, speedAtEnd} — lap closed // speeding / legal still emitted (UI speed display) // In: startLapSession {mode, dirFilter?} — open session -// stopLapSession — close session +// stopLapSession — close session // // startLapSession optional fields: // dirFilter: "both" | "forward" | "reverse" (default "both") + diff --git a/arduino/src/modules/README.md b/arduino/src/modules/README.md new file mode 100644 index 0000000..53905ea --- /dev/null +++ b/arduino/src/modules/README.md @@ -0,0 +1,237 @@ +# ESP Firmware Module Architecture Guide (`arduino/src/modules`) + +This guide explains how AI software development agents and embedded developers structure and implement feature modules for the ESP8266/ESP32 firmware companion. + +For backend and frontend plugins on the host side, see: +- Backend: [`headless-rust/src/plugins/README.md`](../../../headless-rust/src/plugins/README.md) +- Frontend: [`headless-rust/frontend/src/plugins/README.md`](../../../headless-rust/frontend/src/plugins/README.md) + +--- + +## 1. Architectural Principles + +1. **Monolithic Companion Firmware:** + - Single firmware binary flashed once at factory/setup. + - All modules compiled into firmware. Zero reflashing required when host adds, removes, or toggles features. +2. **Dormant by Default:** + - Modules remain completely inactive until host sends activation command (e.g. `startLapSession`). + - While dormant: consume 0 CPU cycles and 0 serial bandwidth. +3. **Zero Dynamic Allocation (Ponytail / YAGNI):** + - **NO `malloc`, `new`, `std::vector`, or `std::function`.** + - Avoid dynamic heap fragmentation on ESP8266/ESP32 microcontrollers. + - No virtual function tables or polymorphic base class overhead. + - Use static C++ namespaces or static classes. +4. **Deterministic Timing Integrity:** + - Core beam-break polling loop in `main.cpp` runs at sub-10µs precision. + - Modules must never perform blocking operations, busy loops, or long `delay()` calls during `onMeasurement()`. + +--- + +## 2. Directory Layout + +Feature modules reside inside `arduino/src/modules/`: + +``` +arduino/src/ +├── config.h # Pins & hardware timing constants +├── types.h # MeasurementEvent struct & core enums +├── state.h / state.cpp # Core hardware state ONLY (no module state) +├── json_output.h / .cpp # Core JSON serialization & capabilities +├── serial_io.h / .cpp # Serial buffer reading & command routing +├── main.cpp # Hardware polling loop (<10µs) & event dispatch +└── modules/ + ├── README.md # This guide + ├── laptimer.h # LapTimer module header + ├── laptimer.cpp # LapTimer state machine & serial output + ├── example.h # Future module header + └── example.cpp # Future module implementation +``` + +--- + +## 3. The Module Contract + +A module is implemented as a C++ namespace (or static class) exposing the standard interface: + +```cpp +// arduino/src/modules/example.h +#pragma once +#include +#include +#include "../types.h" + +namespace ExampleModule { + +void init(); +void reset(); +bool isActive(); + +// Optional: populate fields in the ping/pong response for backward compat +void populatePongConfig(JsonObject &cfg); + +// Command handler: returns true if command is handled by this module +bool handleCommand(const char *command, const JsonDocument &doc); + +// Event hook: called when a passing vehicle triggers both sensors +void onMeasurement(const MeasurementEvent &event); + +} // namespace ExampleModule +``` + +### The `MeasurementEvent` Struct + +Defined in [`arduino/src/types.h`](../types.h): + +```cpp +struct MeasurementEvent { + float speedKmH; // Calculated speed in km/h + float toleranceKmH; // Resolution uncertainty in km/h + const char *direction; // "forward" | "reverse" + unsigned long boundaryUs; // µs timestamp of the first beam break +}; +``` + +--- + +## 4. Step-by-Step Implementation Guide + +### Step 1: Define Header (`modules/.h`) + +Declare module enums, state machine types, and the module interface: + +```cpp +// arduino/src/modules/calibration.h +#pragma once +#include +#include +#include "../types.h" + +namespace Calibration { + +enum class CalibrationState : uint8_t { IDLE, RUNNING }; + +void init(); +void reset(); +bool isActive(); +void populatePongConfig(JsonObject &cfg); +bool handleCommand(const char *command, const JsonDocument &doc); +void onMeasurement(const MeasurementEvent &event); + +} // namespace Calibration +``` + +### Step 2: Implement Logic & Local State (`modules/.cpp`) + +Keep state private to the compilation unit using `static`: + +```cpp +// arduino/src/modules/calibration.cpp +#include "calibration.h" +#include "../json_output.h" + +namespace Calibration { + +static CalibrationState state = CalibrationState::IDLE; + +void init() { + reset(); +} + +void reset() { + state = CalibrationState::IDLE; +} + +bool isActive() { + return state != CalibrationState::IDLE; +} + +void populatePongConfig(JsonObject &cfg) { + cfg["calibrationActive"] = isActive(); +} + +bool handleCommand(const char *command, const JsonDocument &doc) { + if (strcmp(command, "startCalibration") == 0) { + state = CalibrationState::RUNNING; + sendJsonStatus("calibrationReady"); + return true; + } else if (strcmp(command, "stopCalibration") == 0) { + reset(); + sendJsonStatus("calibrationStopped"); + return true; + } + return false; +} + +void onMeasurement(const MeasurementEvent &event) { + if (!isActive()) return; + + // Process measurement for calibration... + JsonDocument outDoc; + outDoc["status"] = "calibrationPass"; + outDoc["speed"] = event.speedKmH; + serializeJson(outDoc, Serial); + Serial.println(); +} + +} // namespace Calibration +``` + +### Step 3: Register in Command Dispatcher (`serial_io.cpp`) + +Delegate unrecognized serial commands to your module: + +```cpp +// In handleCommand() in arduino/src/serial_io.cpp: +#include "modules/calibration.h" + +// ... +} else if (LapTimer::handleCommand(command, doc)) { + return; +} else if (Calibration::handleCommand(command, doc)) { + return; +} else { + sendJsonStatus("jsonError"); +} +``` + +### Step 4: Register in Event Dispatch & Lifecycle (`main.cpp`) + +1. Call `init()` in `setup()`: + ```cpp + Calibration::init(); + ``` + +2. Forward `MeasurementEvent` in `loop()`: + ```cpp + LapTimer::onMeasurement(event); + Calibration::onMeasurement(event); + ``` + +### Step 5: Update Capability List (`json_output.cpp`) + +Add feature identifier to `sendJsonCapabilities()`: + +```cpp +void sendJsonCapabilities() { + JsonDocument doc; + doc["status"] = "capabilities"; + JsonArray features = doc["features"].to(); + features.add("speed"); + features.add("laptimer"); + features.add("calibration"); // <-- Add new feature + // ... +} +``` + +--- + +## 5. Verification Checklist for AI Agents + +Before completing any firmware module refactoring or addition: + +- [ ] Zero global variables added to `state.h` or `state.cpp`. Module state is `static` inside `modules/.cpp`. +- [ ] No heap allocations (`malloc`, `new`, `new[]`) used. +- [ ] `handleCommand` returns `true` only for handled commands, `false` otherwise. +- [ ] `getCapabilities` output updated to include feature name. +- [ ] `onMeasurement` exits immediately if module is inactive (`isActive() == false`). +- [ ] JSON strings formatted with line ending `\n` to match companion framing. diff --git a/arduino/src/modules/alignment.cpp b/arduino/src/modules/alignment.cpp new file mode 100644 index 0000000..b975e76 --- /dev/null +++ b/arduino/src/modules/alignment.cpp @@ -0,0 +1,76 @@ +#include "alignment.h" +#include "../config.h" +#include "../json_output.h" + +namespace Alignment { + +// ponytail: private module state isolated in compilation unit +static bool active = false; +static bool reportedSensor1 = false; +static bool reportedSensor2 = false; +static unsigned long lastSendMs = 0; + +static void sendBarrierStatus(bool s1, bool s2) { + JsonDocument doc; + doc["status"] = "barrierStatus"; + doc["s1"] = s1; + doc["s2"] = s2; + serializeJson(doc, Serial); + Serial.println(); +} + +void init() { + reset(); +} + +void reset() { + active = false; + reportedSensor1 = false; + reportedSensor2 = false; + lastSendMs = 0; +} + +bool isActive() { + return active; +} + +void update() { + // ponytail: 0 CPU cycles when dormant + if (!active) { + return; + } + + unsigned long now = millis(); + bool s1 = (digitalRead(sensor1) == HIGH); + bool s2 = (digitalRead(sensor2) == HIGH); + bool dirty = (s1 != reportedSensor1 || s2 != reportedSensor2); + + // Send immediately on change (throttled to 25ms), or periodic 200ms heartbeat + if ((dirty && (now - lastSendMs >= 25)) || (now - lastSendMs >= 200)) { + reportedSensor1 = s1; + reportedSensor2 = s2; + lastSendMs = now; + sendBarrierStatus(s1, s2); + } +} + +void populatePongConfig(JsonObject &cfg) { + cfg["alignmentActive"] = active; +} + +bool handleCommand(const char *command, const JsonDocument &doc) { + (void)doc; + if (strcmp(command, "startAlignment") == 0) { + active = true; + lastSendMs = 0; // Trigger immediate status on next update + sendJsonStatus("alignmentReady"); + return true; + } else if (strcmp(command, "stopAlignment") == 0) { + reset(); + sendJsonStatus("alignmentStopped"); + return true; + } + return false; +} + +} // namespace Alignment diff --git a/arduino/src/modules/alignment.h b/arduino/src/modules/alignment.h new file mode 100644 index 0000000..a16ff47 --- /dev/null +++ b/arduino/src/modules/alignment.h @@ -0,0 +1,17 @@ +#pragma once +#include +#include +#include "../types.h" + +// ponytail: static modular Alignment. Zero heap, zero vtables, 0 CPU when dormant. +namespace Alignment { + +void init(); +void reset(); +bool isActive(); +void update(); + +void populatePongConfig(JsonObject &cfg); +bool handleCommand(const char *command, const JsonDocument &doc); + +} // namespace Alignment diff --git a/arduino/src/modules/laptimer.cpp b/arduino/src/modules/laptimer.cpp new file mode 100644 index 0000000..44db9ce --- /dev/null +++ b/arduino/src/modules/laptimer.cpp @@ -0,0 +1,169 @@ +#include "laptimer.h" +#include "../json_output.h" + +namespace LapTimer { + +// ponytail: 64-bit continuous microsecond tracking for rollover-safe timing (>71.58 mins) +static uint32_t lastMicros = 0; +static uint32_t microsHigh = 0; + +static uint64_t getNowMicros64() { + unsigned long m = micros(); + if (m < lastMicros) { + microsHigh++; + } + lastMicros = m; + return ((uint64_t)microsHigh << 32) | (uint64_t)m; +} + +static uint64_t toMicros64(unsigned long boundaryUs) { + unsigned long m = micros(); + if (m < lastMicros) { + microsHigh++; + lastMicros = m; + } + uint32_t high = microsHigh; + if (m < boundaryUs) { + high--; + } + return ((uint64_t)high << 32) | (uint64_t)boundaryUs; +} + +// ponytail: private module state isolated from global namespace +static LapSessionState sessionState = LapSessionState::IDLE; +static LapMode lapMode = LapMode::SINGLE; +static LapDirectionFilter directionFilter = LapDirectionFilter::BOTH; +static uint64_t lapStartUs64 = 0; +static float lapStartSpeedKmH = 0.0f; +static int lapNumber = 1; + +// ─── Internal Serial Output ────────────────────────────────────────────────── +static void sendLapStart(int lapNum, float speedAtStart) { + JsonDocument doc; + doc["status"] = "lapStart"; + doc["lapNumber"] = lapNum; + doc["speedAtStart"] = serialized(String(speedAtStart, 1)); + serializeJson(doc, Serial); + Serial.println(); +} + +static void sendLapEnd(int lapNum, double durationMs, uint64_t durationUs, float speedAtStart, float speedAtEnd) { + JsonDocument doc; + doc["status"] = "lapEnd"; + doc["lapNumber"] = lapNum; + // 3 decimal places in ms = 1 µs resolution (realistic light barrier ceiling) + doc["durationMs"] = serialized(String(durationMs, 3)); + doc["durationUs"] = durationUs; + doc["speedAtStart"] = serialized(String(speedAtStart, 1)); + doc["speedAtEnd"] = serialized(String(speedAtEnd, 1)); + serializeJson(doc, Serial); + Serial.println(); +} + +// ─── Public API ────────────────────────────────────────────────────────────── +void init() { + lastMicros = micros(); + microsHigh = 0; + reset(); +} + +void reset() { + sessionState = LapSessionState::IDLE; + lapMode = LapMode::SINGLE; + directionFilter = LapDirectionFilter::BOTH; + lapStartUs64 = 0; + lapStartSpeedKmH = 0.0f; + lapNumber = 1; +} + +bool isActive() { + return sessionState != LapSessionState::IDLE; +} + +void update() { + getNowMicros64(); +} + +void populatePongConfig(JsonObject &cfg) { + cfg["lapMode"] = (lapMode == LapMode::MULTI) ? "multi" : "single"; + cfg["lapActive"] = (sessionState != LapSessionState::IDLE); + cfg["lapDirFilter"] = (directionFilter == LapDirectionFilter::FORWARD_ONLY) ? "forward" + : (directionFilter == LapDirectionFilter::REVERSE_ONLY) ? "reverse" : "both"; +} + +bool handleCommand(const char *command, const JsonDocument &doc) { + if (strcmp(command, "startLapSession") == 0) { + const char *modeStr = doc["mode"] | "single"; + lapMode = (strcmp(modeStr, "multi") == 0) ? LapMode::MULTI : LapMode::SINGLE; + + const char *dirStr = doc["dirFilter"] | "both"; + if (strcmp(dirStr, "forward") == 0) directionFilter = LapDirectionFilter::FORWARD_ONLY; + else if (strcmp(dirStr, "reverse") == 0) directionFilter = LapDirectionFilter::REVERSE_ONLY; + else directionFilter = LapDirectionFilter::BOTH; + + sessionState = LapSessionState::WAITING; + lapNumber = 1; + lapStartUs64 = 0; + lapStartSpeedKmH = 0.0f; + sendJsonStatus("lapWaiting"); + return true; + + } else if (strcmp(command, "stopLapSession") == 0) { + sessionState = LapSessionState::IDLE; + lapNumber = 1; + lapStartUs64 = 0; + lapStartSpeedKmH = 0.0f; + sendJsonStatus("lapStopped"); + return true; + } + + return false; +} + +void onMeasurement(const MeasurementEvent &event) { + if (sessionState == LapSessionState::IDLE) { + return; + } + + // Direction filter check + bool passValid = (directionFilter == LapDirectionFilter::BOTH) + || (directionFilter == LapDirectionFilter::FORWARD_ONLY && strcmp(event.direction, "forward") == 0) + || (directionFilter == LapDirectionFilter::REVERSE_ONLY && strcmp(event.direction, "reverse") == 0); + + if (!passValid) { + return; + } + + uint64_t boundaryUs64 = toMicros64(event.boundaryUs); + + if (sessionState == LapSessionState::WAITING) { + // ── WAITING → TIMING: open lap N ────────────────────────────────────────── + lapStartUs64 = boundaryUs64; // µs-precise first beam break expanded to 64-bit + lapStartSpeedKmH = event.speedKmH; + sessionState = LapSessionState::TIMING; + sendLapStart(lapNumber, event.speedKmH); + + } else if (sessionState == LapSessionState::TIMING) { + // ── TIMING: close lap N ──────────────────────────────────────────────────── + uint64_t durationUs = boundaryUs64 - lapStartUs64; + double durationMs = (double)durationUs / 1000.0; + sendLapEnd(lapNumber, durationMs, durationUs, lapStartSpeedKmH, event.speedKmH); + + if (lapMode == LapMode::SINGLE) { + sessionState = LapSessionState::WAITING; + lapNumber = 1; + lapStartUs64 = 0; + lapStartSpeedKmH = 0.0f; + + } else { + // MULTI: this crossing closes lap N and opens lap N+1 without time gap + lapStartUs64 = boundaryUs64; + lapStartSpeedKmH = event.speedKmH; + lapNumber++; + // sessionState stays TIMING + sendLapStart(lapNumber, event.speedKmH); + } + } +} + +} // namespace LapTimer diff --git a/arduino/src/modules/laptimer.h b/arduino/src/modules/laptimer.h new file mode 100644 index 0000000..a19f11b --- /dev/null +++ b/arduino/src/modules/laptimer.h @@ -0,0 +1,27 @@ +#pragma once +#include +#include +#include "../types.h" + +// ponytail: static modular LapTimer. Zero dynamic memory allocation, zero vtables. +namespace LapTimer { + +enum class LapMode : uint8_t { SINGLE, MULTI }; +enum class LapSessionState : uint8_t { IDLE, WAITING, TIMING }; +enum class LapDirectionFilter : uint8_t { BOTH, FORWARD_ONLY, REVERSE_ONLY }; + +void init(); +void reset(); +bool isActive(); +void update(); + +// Query helpers for pong response +void populatePongConfig(JsonObject &cfg); + +// Command handler — returns true if command recognized & consumed +bool handleCommand(const char *command, const JsonDocument &doc); + +// Hardware event hook — called when a valid speed measurement occurs +void onMeasurement(const MeasurementEvent &event); + +} // namespace LapTimer diff --git a/arduino/src/serial_io.cpp b/arduino/src/serial_io.cpp index 50e33a2..a6a6c0f 100644 --- a/arduino/src/serial_io.cpp +++ b/arduino/src/serial_io.cpp @@ -1,6 +1,8 @@ #include "serial_io.h" #include "state.h" #include "json_output.h" +#include "modules/laptimer.h" +#include "modules/alignment.h" // ─── Serial Input ───────────────────────────────────────────────────────────── void handleSerial() { @@ -65,32 +67,19 @@ void handleCommand(JsonDocument &doc) { debugEnabled = (val == 1); sendJsonConfig("debug", debugEnabled ? 1.0f : 0.0f); - } else if (strcmp(command, "startLapSession") == 0) { - const char *modeStr = doc["mode"] | "single"; - lapMode = (strcmp(modeStr, "multi") == 0) ? LapMode::MULTI : LapMode::SINGLE; - - // dirFilter: which crossing directions advance the lap state machine - const char *dirStr = doc["dirFilter"] | "both"; - if (strcmp(dirStr, "forward") == 0) lapDirectionFilter = LapDirectionFilter::FORWARD_ONLY; - else if (strcmp(dirStr, "reverse") == 0) lapDirectionFilter = LapDirectionFilter::REVERSE_ONLY; - else lapDirectionFilter = LapDirectionFilter::BOTH; - - lapSessionState = LapSessionState::WAITING; - lapNumber = 1; - lapStartUs = 0; - lapStartSpeedKmH = 0.0f; - sendJsonStatus("lapWaiting"); - - } else if (strcmp(command, "stopLapSession") == 0) { - lapSessionState = LapSessionState::IDLE; - lapNumber = 1; - lapStartUs = 0; - lapStartSpeedKmH = 0.0f; - sendJsonStatus("lapStopped"); - } else if (strcmp(command, "ping") == 0) { sendJsonPong(); + } else if (strcmp(command, "getCapabilities") == 0) { + sendJsonCapabilities(); + + // ponytail: route module-specific commands without bloated registry abstractions + } else if (LapTimer::handleCommand(command, doc)) { + return; + + } else if (Alignment::handleCommand(command, doc)) { + return; + } else { sendJsonStatus("jsonError"); } diff --git a/arduino/src/state.cpp b/arduino/src/state.cpp index 092f805..0b75504 100644 --- a/arduino/src/state.cpp +++ b/arduino/src/state.cpp @@ -15,15 +15,6 @@ unsigned long firstTriggerUs = 0; unsigned long measurementStartMs = 0; unsigned long lastMeasurementEndMs = 0; -// ─── Lap Timer State ────────────────────────────────────────────────────────── -LapMode lapMode = LapMode::SINGLE; -LapSessionState lapSessionState = LapSessionState::IDLE; -LapDirectionFilter lapDirectionFilter = LapDirectionFilter::BOTH; -unsigned long lapStartUs = 0; -float lapStartSpeedKmH = 0.0f; -int lapNumber = 1; - - // ─── Speed Measurement Results ──────────────────────────────────────────────── float speedInKmH = 0.0f; float speedTolerance = 0.0f; diff --git a/arduino/src/state.h b/arduino/src/state.h index 6c2303c..ec8cfb0 100644 --- a/arduino/src/state.h +++ b/arduino/src/state.h @@ -18,15 +18,6 @@ extern unsigned long firstTriggerUs; extern unsigned long measurementStartMs; extern unsigned long lastMeasurementEndMs; -// ─── Lap Timer State ────────────────────────────────────────────────────────── -extern LapMode lapMode; -extern LapSessionState lapSessionState; -extern LapDirectionFilter lapDirectionFilter; -extern unsigned long lapStartUs; // µs timestamp of lap start (= firstTriggerUs) -extern float lapStartSpeedKmH; -extern int lapNumber; - - // ─── Speed Measurement Results ──────────────────────────────────────────────── extern float speedInKmH; extern float speedTolerance; diff --git a/arduino/src/types.h b/arduino/src/types.h index af413c6..fad1dd8 100644 --- a/arduino/src/types.h +++ b/arduino/src/types.h @@ -7,11 +7,11 @@ enum class MeasurementState : uint8_t { IDLE, WAITING_FOR_SECOND }; enum class FirstSensor : uint8_t { NONE, SENSOR_ONE, SENSOR_TWO }; -// ─── Lap Timer State Machine ────────────────────────────────────────────────── -// The host starts/stops a lap session via serial commands. Once a session is -// active the firmware drives the state machine: the first car pass opens a -// lap (WAITING → TIMING) and the second car pass closes it (TIMING → WAITING -// for SINGLE mode, or TIMING → TIMING with an incremented counter for MULTI). -enum class LapMode : uint8_t { SINGLE, MULTI }; -enum class LapSessionState : uint8_t { IDLE, WAITING, TIMING }; -enum class LapDirectionFilter : uint8_t { BOTH, FORWARD_ONLY, REVERSE_ONLY }; +// ─── Measurement Event ──────────────────────────────────────────────────────── +// Emitted when a passing vehicle triggers both sensors within valid window. +struct MeasurementEvent { + float speedKmH; + float toleranceKmH; + const char *direction; // "forward" | "reverse" + unsigned long boundaryUs; // µs timestamp of first beam break +}; diff --git a/headless-rust/frontend/src/App.tsx b/headless-rust/frontend/src/App.tsx index ffaa34b..4f60073 100644 --- a/headless-rust/frontend/src/App.tsx +++ b/headless-rust/frontend/src/App.tsx @@ -6,9 +6,9 @@ import { IndexRoute } from "@/routes/index"; import { ViolationsRoute } from "@/routes/violations"; import { SettingsRoute } from "@/routes/settings"; import { AboutRoute } from "@/routes/about"; -import { LapsRoute } from "@/routes/laps"; import { TeableRoute } from "@/routes/teable"; import { SetupRoute } from "@/routes/setup"; +import { pluginRegistry } from "@/plugins"; // ─── Router ───────────────────────────────────────────────────────────────────── @@ -17,9 +17,9 @@ const routeTree = RootRoute.addChildren([ ViolationsRoute, SettingsRoute, AboutRoute, - LapsRoute, TeableRoute, SetupRoute, + ...pluginRegistry.getRoutes(RootRoute), ]); const history = createMemoryHistory({ initialEntries: ["/"] }); diff --git a/headless-rust/frontend/src/components/NavigationMenu.tsx b/headless-rust/frontend/src/components/NavigationMenu.tsx index 48f56b1..f4caa64 100644 --- a/headless-rust/frontend/src/components/NavigationMenu.tsx +++ b/headless-rust/frontend/src/components/NavigationMenu.tsx @@ -1,14 +1,11 @@ import { Link } from "@tanstack/react-router"; -import { HugeiconsIcon } from "@hugeicons/react"; -import { Timer01Icon, DashboardCircleIcon } from "@hugeicons/core-free-icons"; import { cn } from "@/lib/utils"; -import { useAppStore } from "@/stores/useAppStore"; +import { pluginRegistry } from "@/plugins"; import { ConnectionIndicator } from "./ConnectionIndicator"; -const NAV_ITEMS = [ +const CORE_NAV_ITEMS = [ { label: "Home", to: "/" }, { label: "Violations", to: "/violations" }, - { label: "Laps", to: "/laps" }, { label: "Settings", to: "/settings" }, { label: "Setup", to: "/setup" }, { label: "Teable", to: "/teable" }, @@ -20,12 +17,18 @@ interface NavigationMenuProps { } export function NavigationMenu({ className }: NavigationMenuProps) { - const appMode = useAppStore((s) => s.appMode); - const setAppMode = useAppStore((s) => s.setAppMode); + const pluginNavItems = pluginRegistry.getNavItems(); + + const allNavItems = [ + CORE_NAV_ITEMS[0], // Home + CORE_NAV_ITEMS[1], // Violations + ...pluginNavItems, // Dynamic plugin routes (e.g. Laps) + ...CORE_NAV_ITEMS.slice(2), // Settings, Setup, Teable, About + ]; return (