diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37e50c2..0465d88 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -50,10 +50,14 @@ jobs: python scripts/check_firmware_image.py .pio/build/sender/firmware.bin sender python scripts/check_firmware_image.py .pio/build/display/firmware.bin display + - name: Archive exact debug images + run: python scripts/archive_build.py --out output --version "$(cat VERSION.txt)" sender display sender_dev display_dev + - uses: actions/upload-artifact@v4 with: name: firmware-unsigned-${{ github.sha }} path: | .pio/build/sender/firmware.bin .pio/build/display/firmware.bin - retention-days: 14 + output/debug-*.zip + retention-days: 90 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b5f2f25..658adc8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -10,6 +10,11 @@ on: description: "SemVer version, e.g. 2.1.0 or 2.1.0-beta.1" required: true type: string + initialize_index: + description: "Nur beim ersten Release: fehlenden Update-Index neu anlegen" + required: false + default: false + type: boolean channel: description: "Update channel shown to devices" required: true @@ -91,15 +96,24 @@ jobs: - name: Update manifest env: BASE_URL: https://github.com/${{ github.repository }}/releases/download/${{ steps.meta.outputs.tag }} + INITIALIZE_INDEX: ${{ inputs.initialize_index }} INDEX_URL: https://github.com/${{ github.repository }}/releases/download/firmware-index/update_manifest.json run: | set -euo pipefail - curl -fsSL "$INDEX_URL" -o previous_manifest.json || echo '{}' > previous_manifest.json + args=() + if [[ "$INITIALIZE_INDEX" == "true" ]]; then args+=(--initialize); fi + python scripts/fetch_previous_manifest.py "$INDEX_URL" --out previous_manifest.json "${args[@]}" + cp previous_manifest.json output/previous_manifest.json python scripts/release_manifest.py --previous previous_manifest.json \ --out output/update_manifest.json --version "${{ steps.meta.outputs.version }}" \ --channel "${{ inputs.channel }}" --protocol "${{ steps.meta.outputs.protocol }}" \ --base-url "$BASE_URL" --sender output/sender.bin --display output/display.bin - (cd output && sha256sum sender.bin display.bin > SHA256SUMS.txt) + + + - name: Archive exact debug images + run: | + python scripts/archive_build.py --out output --version "V${{ steps.meta.outputs.version }}" sender display + (cd output && sha256sum sender.bin display.bin debug-*.zip previous_manifest.json > SHA256SUMS.txt) - name: Publish release uses: softprops/action-gh-release@v2 @@ -118,6 +132,9 @@ jobs: output/sender.bin output/display.bin output/SHA256SUMS.txt + output/debug-sender.zip + output/debug-display.zip + output/previous_manifest.json - name: Publish update index uses: softprops/action-gh-release@v2 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ab792ad --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,29 @@ +# Änderungen + +## V2.1.1-beta.4 + +- Updates bei unbekanntem/veraltetem Fahrzeugstatus und während Booting sperren. + Authentifizierter Wartungsmodus für das vom Fahrzeug getrennte Gerät, maximal + zehn Minuten, bei aktivem Fahrzeugzustand automatisch aufgehoben. +- Neue Firmware erst nach 30 Sekunden erfolgreicher lokaler Initialisierung + bestätigen; bei anhaltendem Initialisierungsfehler Rollback nach 60 Sekunden. + Fehlende externe CAN-/Funkantworten lösen keinen Boot-Rollback aus. +- Messwerte nach 60 Sekunden ohne Messung im Snapshot ungültig machen, auch wenn + weiterhin Funkpakete eintreffen. Protokollformat bleibt v3. +- PID-Gültigkeit bis zur Verarbeitung erhalten; ungültige Antworten zählen und + nicht als frische Werte oder als Aktivitätsdaten übernehmen. +- Durchschnittsverbrauch aus zeitintegrierter Kraftstoffmenge und Strecke bilden; + Nullverbrauch und Kraftstoff im Stand berücksichtigen, Messlücken auslassen. +- Frischegrenzen für Kühlmitteltemperatur und ECU-Spannung an langsame Abfrage + anpassen. JSON-Escaping für WLAN, Management und Updates vereinheitlichen. +- Sender-/Display-Webseiten von den Routen trennen; Browser-Helfer teilen. + Display-Rendering von Hardwareinitialisierung und Tastersteuerung trennen. +- Release-Index bei Downloadfehlern erhalten; begrenzte Retries und ausdrückliche + Erstinitialisierung. Vorherigen Index als Release-Anhang sichern. +- Exakte ELF-/MAP-/BIN-Dateien mit Build-Metadaten und Prüfsummen archivieren; + Debug-Archive dauerhaft an Releases anhängen, CI-Aufbewahrung 90 Tage. +- Secret-Scanner meldet Fundort und Regel ohne Geheimwerte. Veraltete espota- + Anleitung entfernt; Regressionstests und Betriebsdokumentation ergänzt. + +Hardwareprüfungen für OTA, Rollback, CAN und Display sind vor dem produktiven +Einsatz erforderlich. Einträge beschreiben den Quellstand, keine Geräteinstallation. diff --git a/README.md b/README.md index 9f3d9c2..16099d0 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ per ESP-NOW an ein LilyGO T-Display S3 im Auto. - **Display** (`env:display`): flackerfreie Anzeige mit 4 Fahrseiten und 4 Diagnoseseiten, Weboberfläche. -Stand: `V2.1.0-beta.3`, Telemetrie-Protokoll 3. +Stand: `V2.1.1-beta.4`, Telemetrie-Protokoll 3. ## Schnellstart @@ -54,3 +54,5 @@ Danach mit dem WLAN `CANOBD2_Sender` bzw. `CANOBD2_Display` verbinden und Siehe [LICENSE](LICENSE). Enthält Monocypher 4.0.2 (BSD-2-Clause/CC0, `lib/monocypher`). Ursprünglich basierend auf dem [MrDIY CAN-Bus Gateway](https://gitlab.com/MrDIYca/canabus). + +Änderungen dieser Version: [CHANGELOG.md](CHANGELOG.md). diff --git a/VERSION.txt b/VERSION.txt index d5eca96..6ed3edc 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -V2.1.0-beta.3 +V2.1.1-beta.4 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index a36f454..9e8b0e8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -35,7 +35,7 @@ Gemeinsamer Code liegt in `lib/` und wird nativ getestet (`env:native`). 4. Das Display übernimmt den Snapshot in `DisplayLogic::LiveValueView`. Jeder Wert ist *frisch*, *veraltet* (grau, letzter Wert bleibt sichtbar), *nicht unterstützt* oder *fehlend*. -5. `DisplayUi` zeichnet alle 50 ms ein komplettes Bild in einen Sprite und +5. `DisplayRenderer` zeichnet alle 50 ms ein komplettes Bild in einen Sprite und überträgt es in einem Stück. Dadurch flackert nichts. Statusinformationen (CAN/OBD-Zustand, DTC, VIN, UDS, Power-Zustand, @@ -55,7 +55,7 @@ Heartbeat) sind selten und bleiben Textpakete. | `lib/firmware_signing/`, `lib/monocypher/` | Ed25519-Prüfung der Firmware | | `lib/security/` | Gerätezugangsdaten im NVS | | `lib/diagnostics/` | Neustartgrund, Absturzbericht (Coredump), Loop-Watchdog | -| `lib/web/` | Gemeinsamer Management-Webserver, Authentifizierung, HTML-Assets | +| `lib/web/` | Gemeinsamer Management-Webserver, Authentifizierung, HTML-Assets (`DevicePages`, `WebAssets`) | | `lib/simulation/`, `lib/capabilities/`, `lib/can_router/` | Entwicklerwerkzeuge (nur `*_dev`-Builds aktiv) | | `include/config/` | Konfiguration je Bereich (keine Zugangsdaten) | | `scripts/` | Signieren, Upload, Release-Manifest, Secret-Check, Build-Hooks | @@ -67,3 +67,11 @@ Heartbeat) sind selten und bleiben Textpakete. Simulation, OBD/UDS-Capability-Scanner, CAN-Signal-Finder, RAW-CAN-Telemetrie und die CAN-Sniffer-Seite. In Release-Builds sind Endpunkte und Bedienelemente nicht vorhanden; die Simulation kann dort nicht eingeschaltet werden. + +Display-Hardware, Framebuffer und Taster liegen in `DisplayUi`; Seiten und Widgets +in `DisplayRenderer`. Web-Routen verwenden die separat abgelegten Seiten aus +`lib/web/DevicePages.cpp`. JSON-Escaping teilen sie mit dem Update- und WLAN-Code +über `lib/utils/JsonEscape.h`; Browser-HTML-Escaping kommt aus `WebAssets::commonScript`. +`ConsumptionAccumulator` integriert Kraftstoffmenge und Strecke unabhängig von +PID-Abfragefrequenz und Display-Rendering. `UpdateSafety` trennt unbekannten, +geparkten und aktiven Fahrzeugzustand vom ausdrücklich bestätigten Wartungsmodus. diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 65bea79..722032c 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -29,7 +29,7 @@ getestet werden. ## Version -`VERSION.txt` enthält die SemVer-Version für lokale Builds (`V2.1.0-beta.1`). +`VERSION.txt` enthält die SemVer-Version für lokale Builds (`V2.1.1-beta.4`). Release-Builds setzen sie über `CANOBD2_FIRMWARE_VERSION` (`scripts/apply_firmware_version.py`). @@ -60,8 +60,8 @@ können die Fahrgestellnummer enthalten, also nicht ins Repository übernehmen. Jeder Start schreibt den Grund ins Diagnose-Log (`[BOOT] … reset=PANIC|TASK_WDT|…`). Nach einem Absturz liegt ein Absturzbericht (Coredump, ELF) im Flash. Man lädt ihn in der Weboberfläche oder per `GET /api/coredump` herunter und wertet ihn -mit der `firmware.elf` **genau dieses Builds** aus (CI-Artefakt bzw. lokaler -Build mit gleichem Commit): +mit der `firmware.elf` **genau dieses Builds** aus (Release-Anhang `debug-sender.zip` bzw. `debug-display.zip` oder +CI-Artefakt **desselben Builds**; ein Neubau desselben Commits ist kein Ersatz): ```bash pip install esp-coredump @@ -83,3 +83,18 @@ Update-Manifest und veröffentlicht beides. Voraussetzung ist das Secret * Neue Livewerte nur hinten in `LiveData::Metric` anfügen. * Gemeinsame Logik nach `lib/` mit nativem Test, Geräte-Code nach `src/`. * Keine Zugangsdaten in Code, Tests oder Doku. + +## Release-Artefakte und Indexschutz (ab V2.1.1-beta.4) + +CI archiviert BIN, ELF, MAP, Konfiguration, Paketversionen und SHA-256-Prüfsummen +für alle vier Environments für 90 Tage. Releases behalten `debug-sender.zip` +und `debug-display.zip` als Anhänge. `build.json` enthält Commit, Version, +Environment und die konkret installierten PlatformIO-Paketversionen. +Für Absturzanalysen immer das Archiv der tatsächlich installierten Firmware nutzen. + +Der Release-Workflow lädt und validiert den vorhandenen Index mit drei begrenzten +Versuchen. Netzwerkfehler, beschädigtes JSON und unerwartete HTTP-Antworten brechen +ab. Nur bei HTTP 404 und explizitem `initialize_index=true` wird erstmals ein Index +angelegt. `previous_manifest.json` bleibt als Release-Anhang erhalten; nach einer +Fehlveröffentlichung kann dieser geprüfte Stand nach Freigabe wieder als Index +hochgeladen werden. Alte Firmware-Dateien werden dabei nicht gelöscht. diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index 679fded..84bc615 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -28,7 +28,7 @@ uint8 flags bit0 = simulierte Werte uint32 validMask bit n: Metrik n hat einen Wert uint32 unsupportedMask bit n: ECU unterstützt Metrik n nicht float values[19] IEEE-754, little endian -uint8 ageTenths[19] Alter in 0,1 s; 255 = nie gemessen +uint8 ageTenths[19] Alter in 0,1 s; 254 = gesättigt, 255 = fehlend/abgelaufen ``` Metriken (Reihenfolge = Bitnummer): RPM, Speed, CoolantTemp, BatteryVoltage, @@ -51,3 +51,16 @@ Displays verwerfen den Snapshot statt falsch zuzuordnen. | `DTC` (Typ DTC) | aktive Fehlercodes, Status `WARN` bei Fehlern | | `VIN`, `UDS_DID_F190`, `UDS`, `UDS_DTC`, `UDS_NEGATIVE`, `ECU_COUNT` | Diagnose | | `RAW`, `HINT`, `CAN_*` (Typ CAN) | nur Entwickler-Builds | + +## Messwertgültigkeit ab V2.1.1-beta.4 + +Das Paketformat bleibt v3. Ab 60 Sekunden ohne neue Messung löscht der Sender +beim nächsten Snapshot das jeweilige `validMask`-Bit. Ein weiterlaufender +Funkkontakt verlängert diese Frist nicht. Das kompakte Altersfeld ist bis dahin +auf 25,4 Sekunden begrenzt. Kühlmitteltemperatur und ECU-Spannung haben wie andere +langsame PIDs eine Frischegrenze von 7 Sekunden; schnelle Werte 1,5 Sekunden. + +Der Durchschnittsverbrauch umfasst die seit Start (oder Simulationswechsel) +aufgelaufene Kraftstoffmenge und Strecke. Beide Eingaben müssen frisch sein; +Lücken werden nicht integriert. Nullverbrauch zählt mit, Kraftstoff im Stillstand +zur Menge, nicht zur Strecke. Die Anzeige beginnt ab einem gefahrenen Meter. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 9daa3dd..dedfad0 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -39,10 +39,28 @@ Zugriff auf die Platine das NVS auslesen. * Wege: Web-Upload (`/github-update` → „Datei hochladen“ oder `scripts/ota_upload.py`) und GitHub-Update. Ein Update per USB-Kabel ist immer möglich (physischer Zugriff). -* Während das Fahrzeug läuft, werden Updates abgelehnt. +* Vor Beginn eines Updates muss ein höchstens 3 s alter Zustand `Parked` oder + `DisplaySleep` vorliegen. `Booting`, unbekannte Zustände und ein veralteter + Senderstatus sperren Updates ebenfalls. Die Freigabe wird vor dem Flashen geprüft; + während eines laufenden synchronen Uploads/Downloads wird keine neue + Fahrzeugzustandsmessung garantiert. Das Fahrzeug muss bis zum Neustart stehen bleiben. +* Für Wartung ohne Fahrzeug: Gerät vom Fahrzeug trennen, auf der Update-Seite den + Wartungsmodus ausdrücklich bestätigen. Er gilt höchstens 10 Minuten, wird nicht + gespeichert und bei einem neuen aktiven Fahrzeugzustand sofort aufgehoben. + API: authentifiziertes `POST /api/update/maintenance` mit + `confirm=vehicle-disconnected` und Header `X-Maintenance-Confirm: vehicle-disconnected`; + `enable=0` mit demselben Header beendet ihn. Der zusätzliche Header verhindert + die Aktivierung über fremde HTML-Formulare mit gespeicherter Browser-Anmeldung. Signatur und Anmeldung + bleiben auch im Wartungsmodus erforderlich. * **Automatischer Rollback:** Neue Firmware gilt erst nach 30 s stabilem Lauf - als bestätigt (`lib/update/BootValidation`). Stürzt sie vorher ab, startet - der Bootloader wieder die vorherige Version. + mit erfolgreicher lokaler Initialisierung als bestätigt (`lib/update/BootValidation`). + Geprüft werden Logspeicher, CAN-Treiber bzw. Display-Framebuffer sowie bei + provisionierten Geräten Webserver und ESP-NOW-Initialisierung. Fehlende externe + ECU-/Senderantworten sind kein Fehler dieser Boot-Prüfung. Bleibt die lokale + Initialisierung 60 s lang unzureichend, wird die vorherige gültige Firmware + angefordert. Ohne gültigen Rückweg wird der Fehler protokolliert; soweit erfolgreich + initialisiert, bleibt die Diagnose-/Wartungsoberfläche erreichbar. + Ein Absturz vor der Bestätigung führt ebenfalls zum Bootloader-Rollback. * **Watchdog:** Hängt `loop()` länger als 30 s, startet das Gerät neu. Passiert das mit einer frisch installierten Firmware innerhalb der ersten 30 s, greift diff --git a/include/OBDHandler.h b/include/OBDHandler.h index e7a4200..4a7d554 100644 --- a/include/OBDHandler.h +++ b/include/OBDHandler.h @@ -29,9 +29,6 @@ class OBD2Handler { /// Requests a PID, decodes it and stores it in the live snapshot table. static bool requestAndSendPID(uint8_t pid); - /// Calculates and sends consumption from speed and fuel rate. - static void calcConsumption(uint8_t pid, float value); - /// Updates MAP/BARO state and sends the centrally calculated boost pressure. static void updateBoostPressure(uint8_t pid, float value); diff --git a/include/PID_Converter.h b/include/PID_Converter.h index 19bb2e4..c08678b 100644 --- a/include/PID_Converter.h +++ b/include/PID_Converter.h @@ -1,18 +1,16 @@ #ifndef PID_CONVERTER_H #define PID_CONVERTER_H -#include +#include +#include "PidDecoder.h" // Struktur für umgerechnete Werte -struct PIDResult { - float value; - const char* unit; -}; +using PIDResult = Obd::PidValue; // Hauptfunktion zur Umrechnung von Rohdaten -PIDResult convertPID(byte pid, const byte* data, byte length); +PIDResult convertPID(uint8_t pid, const uint8_t* data, uint8_t length); // Gibt lesbaren Namen zu einem PID zurück -const char* getPIDName(byte pid); +const char* getPIDName(uint8_t pid); #endif diff --git a/include/config/UpdateConfig.h b/include/config/UpdateConfig.h index de2a471..5c1c382 100644 --- a/include/config/UpdateConfig.h +++ b/include/config/UpdateConfig.h @@ -22,7 +22,6 @@ constexpr FirmwareUpdate::UpdateChannel DefaultChannel = FirmwareUpdate::UpdateC // Installing an older version is allowed only after explicit confirmation. constexpr bool AllowRollback = true; -constexpr bool BlockInstallWhileVehicleRunning = true; constexpr bool RejectWhenSketchSpaceUnknown = true; constexpr uint32_t ManifestTimeoutMs = 15000; diff --git a/lib/common/PID_Converter.cpp b/lib/common/PID_Converter.cpp index 7733614..675593c 100644 --- a/lib/common/PID_Converter.cpp +++ b/lib/common/PID_Converter.cpp @@ -1,12 +1,10 @@ #include "PID_Converter.h" #include "PidDecoder.h" -PIDResult convertPID(byte pid, const byte* data, byte length) { - const Obd::PidValue decoded = Obd::decodePid(pid, data, length); - if (!decoded.valid) return {-1.0f, "INVALID"}; - return {decoded.value, decoded.unit}; +PIDResult convertPID(uint8_t pid, const uint8_t* data, uint8_t length) { + return Obd::decodePid(pid, data, length); } -const char* getPIDName(byte pid) { +const char* getPIDName(uint8_t pid) { return Obd::pidName(pid); } diff --git a/lib/display/LiveValueView.cpp b/lib/display/LiveValueView.cpp index 40109f4..25c3599 100644 --- a/lib/display/LiveValueView.cpp +++ b/lib/display/LiveValueView.cpp @@ -1,4 +1,5 @@ #include "LiveValueView.h" +#include "config/SenderConfig.h" namespace DisplayLogic { @@ -47,13 +48,14 @@ uint32_t LiveValueView::freshLimitMs(Metric metric) { case Metric::Rpm: case Metric::Speed: case Metric::EngineLoad: - case Metric::CoolantTemp: - case Metric::EcuVoltage: - return 1500; // polled every ~200 ms + case Metric::Maf: + case Metric::FuelRate: + case Metric::InstantConsumption: + return SenderConfig::FastPidIntervalMs * 3 + 900; case Metric::BatteryVoltage: - return 8000; // measured every 3 s + return SenderConfig::BatterySendIntervalMs * 2 + 2000; default: - return 7000; // slow PIDs (~2 s) and values derived from them + return SenderConfig::SlowPidIntervalMs * 3 + 1000; } } diff --git a/lib/display/LiveValueView.h b/lib/display/LiveValueView.h index d301aae..8a8c640 100644 --- a/lib/display/LiveValueView.h +++ b/lib/display/LiveValueView.h @@ -30,7 +30,7 @@ struct ValueView { class LiveValueView { public: - static constexpr uint32_t MaxStaleMs = 60000; + static constexpr uint32_t MaxStaleMs = LiveData::MaxValueAgeMs; void reset(); void apply(const LiveData::Snapshot& snapshot, uint32_t receivedAtMs); diff --git a/lib/obd/ConsumptionAccumulator.h b/lib/obd/ConsumptionAccumulator.h new file mode 100644 index 0000000..7014f7f --- /dev/null +++ b/lib/obd/ConsumptionAccumulator.h @@ -0,0 +1,65 @@ +#pragma once + +#include +#include +#include "config/SenderConfig.h" + +namespace Obd { +// Integrates last-known speed and fuel rate only while BOTH inputs are fresh. +// Input events integrate the preceding interval before replacing a value. +class ConsumptionAccumulator { +public: + static constexpr uint32_t MaxInputAgeMs = SenderConfig::FastPidIntervalMs * 3 + 900; + void reset() { *this = ConsumptionAccumulator{}; } + void updateSpeed(float speedKph, uint32_t nowMs) { + advance(nowMs); + speed_ = speedKph; + speedAt_ = nowMs; + speedValid_ = std::isfinite(speedKph) && speedKph >= 0; + } + void updateFuelRate(float litresPerHour, uint32_t nowMs) { + advance(nowMs); + fuel_ = litresPerHour; + fuelAt_ = nowMs; + fuelValid_ = std::isfinite(litresPerHour) && litresPerHour >= 0; + } + void advance(uint32_t nowMs) { + if (started_ && speedValid_ && fuelValid_) { + const uint32_t speedAge = lastAt_ - speedAt_; + const uint32_t fuelAge = lastAt_ - fuelAt_; + if (speedAge < MaxInputAgeMs && fuelAge < MaxInputAgeMs) { + uint32_t dt = nowMs - lastAt_; + if (dt > MaxInputAgeMs - speedAge) dt = MaxInputAgeMs - speedAge; + if (dt > MaxInputAgeMs - fuelAge) dt = MaxInputAgeMs - fuelAge; + const double hours = static_cast(dt) / 3600000.0; + litres_ += static_cast(fuel_) * hours; + kilometres_ += static_cast(speed_) * hours; + } + } + started_ = true; + lastAt_ = nowMs; + } + bool fresh(uint32_t nowMs) const { + return speedValid_ && fuelValid_ && nowMs - speedAt_ <= MaxInputAgeMs && + nowMs - fuelAt_ <= MaxInputAgeMs; + } + bool hasAverage() const { return kilometres_ >= 0.001; } + float average() const { return hasAverage() ? static_cast(100.0 * litres_ / kilometres_) : 0.0f; } + bool hasInstant(uint32_t nowMs) const { return fresh(nowMs) && speed_ >= 5.0f; } + float instant() const { return speed_ >= 5.0f ? fuel_ * 100.0f / speed_ : 0.0f; } + double litres() const { return litres_; } + double kilometres() const { return kilometres_; } + +private: + double litres_ = 0; + double kilometres_ = 0; + float speed_ = 0; + float fuel_ = 0; + uint32_t speedAt_ = 0; + uint32_t fuelAt_ = 0; + uint32_t lastAt_ = 0; + bool started_ = false; + bool speedValid_ = false; + bool fuelValid_ = false; +}; +} // namespace Obd diff --git a/lib/obd/ObdDiagnostics.h b/lib/obd/ObdDiagnostics.h index 09d40d9..1cc0941 100644 --- a/lib/obd/ObdDiagnostics.h +++ b/lib/obd/ObdDiagnostics.h @@ -18,6 +18,7 @@ namespace Obd { class Diagnostics { public: static void reset() { + invalidResponseCount_ = 0; requestCount_ = 0; sendFailureCount_ = 0; timeoutCount_ = 0; @@ -63,6 +64,13 @@ class Diagnostics { copyText(lastEcuResponse_, sizeof(lastEcuResponse_), "SEND_FAIL"); } + static void recordInvalidResponse() { + ++invalidResponseCount_; + copyText(lastEcuResponse_, sizeof(lastEcuResponse_), "INVALID_PID_DATA"); + } + + static uint32_t invalidResponseCount() { return invalidResponseCount_; } + static void recordTimeout() { ++timeoutCount_; ++timeoutStreak_; @@ -169,6 +177,7 @@ class Diagnostics { std::snprintf(target, targetSize, "%s", source); } + static inline uint32_t invalidResponseCount_ = 0; static inline uint32_t requestCount_ = 0; static inline uint32_t sendFailureCount_ = 0; static inline uint32_t timeoutCount_ = 0; diff --git a/lib/runtime/SenderRuntimeState.h b/lib/runtime/SenderRuntimeState.h index 32422af..6789de7 100644 --- a/lib/runtime/SenderRuntimeState.h +++ b/lib/runtime/SenderRuntimeState.h @@ -26,36 +26,11 @@ class SenderRuntimeState { lastFuelRateLh_ = litersPerHour; } - static bool hasConsumptionInput() { - return lastSpeedKph_ >= 1.0f && lastFuelRateLh_ >= 0.1f; - } - - static float currentConsumptionL100Km() { - if (!hasConsumptionInput()) return 0.0f; - return (lastFuelRateLh_ / lastSpeedKph_) * 100.0f; - } - - static bool addConsumptionSample(float& averageL100Km) { - const float consumption = currentConsumptionL100Km(); - if (consumption <= 0.0f) return false; - - consumptionSum_ += consumption; - ++consumptionCount_; - - if (consumptionCount_ < SamplesPerAverage) return false; - - averageL100Km = consumptionSum_ / static_cast(consumptionCount_); - consumptionSum_ = 0.0f; - consumptionCount_ = 0; - return true; - } - static float lastSpeedKph() { return lastSpeedKph_; } static float lastRpm() { return lastRpm_; } static float lastEngineLoadPercent() { return lastEngineLoadPercent_; } static float lastThrottlePercent() { return lastThrottlePercent_; } static float lastFuelRateLh() { return lastFuelRateLh_; } - static uint32_t consumptionSampleCount() { return consumptionCount_; } static void reset() { lastSpeedKph_ = 0.0f; @@ -63,19 +38,14 @@ class SenderRuntimeState { lastEngineLoadPercent_ = 0.0f; lastThrottlePercent_ = 0.0f; lastFuelRateLh_ = 0.0f; - consumptionSum_ = 0.0f; - consumptionCount_ = 0; } private: - static constexpr uint32_t SamplesPerAverage = 10; static inline float lastSpeedKph_ = 0.0f; static inline float lastRpm_ = 0.0f; static inline float lastEngineLoadPercent_ = 0.0f; static inline float lastThrottlePercent_ = 0.0f; static inline float lastFuelRateLh_ = 0.0f; - static inline float consumptionSum_ = 0.0f; - static inline uint32_t consumptionCount_ = 0; }; } diff --git a/lib/telemetry/LiveData.cpp b/lib/telemetry/LiveData.cpp index eac035b..89f3a59 100644 --- a/lib/telemetry/LiveData.cpp +++ b/lib/telemetry/LiveData.cpp @@ -1,6 +1,7 @@ #include "LiveData.h" #include +#include namespace LiveData { namespace { @@ -116,7 +117,7 @@ void LiveValueTable::reset() { void LiveValueTable::update(Metric metric, float value, uint32_t nowMs) { const uint8_t index = static_cast(metric); - if (index >= MetricCount) return; + if (index >= MetricCount || !std::isfinite(value)) return; values_[index] = value; updatedAt_[index] = nowMs; validMask_ |= 1u << index; @@ -151,7 +152,8 @@ Snapshot LiveValueTable::snapshot(uint32_t nowMs) const { snap.unsupportedMask = unsupportedMask_; for (std::size_t index = 0; index < MetricCount; ++index) { snap.values[index] = values_[index]; - if (!((validMask_ >> index) & 1U)) { + if (!((validMask_ >> index) & 1U) || nowMs - updatedAt_[index] > MaxValueAgeMs) { + snap.validMask &= ~(1u << index); snap.ageTenths[index] = AgeUnknown; continue; } diff --git a/lib/telemetry/LiveData.h b/lib/telemetry/LiveData.h index 320427f..8c2438a 100644 --- a/lib/telemetry/LiveData.h +++ b/lib/telemetry/LiveData.h @@ -15,7 +15,7 @@ // uint32 validMask bit n: metric n has a value // uint32 unsupportedMask bit n: ECU does not support metric n // float values[MetricCount] -// uint8 ageTenths[MetricCount] age of each value in 0.1 s, 255 = >= 25.5 s +// uint8 ageTenths[MetricCount] age of each value in 0.1 s, 254 = saturated age, 255 = missing/expired // // Status/diagnostic information (DTC, VIN, UDS, CAN hints, power state) stays // in the text packets, it is rare and not time critical. @@ -66,6 +66,7 @@ bool metricForPid(uint8_t pid, Metric& out); bool metricForName(const char* name, Metric& out); constexpr uint8_t AgeUnknown = 255; +constexpr uint32_t MaxValueAgeMs = 60000; constexpr uint8_t FlagSimulated = 0x01; struct Snapshot { diff --git a/lib/update/BootValidation.cpp b/lib/update/BootValidation.cpp index 4432c6c..69f8351 100644 --- a/lib/update/BootValidation.cpp +++ b/lib/update/BootValidation.cpp @@ -14,6 +14,7 @@ extern "C" bool verifyRollbackLater() { namespace BootValidation { namespace { bool done = false; +HealthGate health; } // namespace bool pendingVerify() { @@ -27,15 +28,27 @@ bool pendingVerify() { #endif } -void tick(uint32_t nowMs) { - if (done || nowMs < StableAfterMs) return; - done = true; +void tick(uint32_t nowMs, bool localHealthy) { + if (done) return; + const Decision decision = health.evaluate(nowMs, localHealthy); + if (decision == Decision::Wait) return; #if defined(ARDUINO) if (pendingVerify()) { + if (decision == Decision::Rollback) { + DiagnosticLog::appendf("[OTA] Lokale Initialisierung fehlgeschlagen, Rollback"); + // If no previous valid slot exists, remain in the recovery UI. + const esp_err_t result = esp_ota_mark_app_invalid_rollback_and_reboot(); + DiagnosticLog::appendf("[OTA] Rollback nicht moeglich: %d", static_cast(result)); + done = true; + return; + } const bool ok = esp_ota_mark_app_valid_cancel_rollback() == ESP_OK; DiagnosticLog::appendf(ok ? "[OTA] Neue Firmware stabil, bestaetigt" : "[OTA] Bestaetigung fehlgeschlagen"); + // A failed confirmation must not be silently considered successful. + if (!ok) return; } #endif + done = true; } } // namespace BootValidation diff --git a/lib/update/BootValidation.h b/lib/update/BootValidation.h index bca113b..47dcc3c 100644 --- a/lib/update/BootValidation.h +++ b/lib/update/BootValidation.h @@ -4,7 +4,7 @@ // // After an OTA update the bootloader starts the new image in "pending verify" // state. This module keeps it pending until the firmware ran StableAfterMs -// without reset and only then confirms it. If the new image crashes or hangs +// with successful local initialization and only then confirms it. If the new image crashes or hangs // (watchdog reset) before that, the bootloader boots the previous firmware. #include @@ -12,9 +12,29 @@ namespace BootValidation { constexpr uint32_t StableAfterMs = 30000; +constexpr uint32_t HealthDeadlineMs = 60000; + +enum class Decision { Wait, Confirm, Rollback }; + +class HealthGate { +public: + Decision evaluate(uint32_t nowMs, bool localHealthy) { + if (!started_) { started_ = true; startedAt_ = nowMs; } + if (!localHealthy) healthy_ = false; + else if (!healthy_) { healthy_ = true; healthyAt_ = nowMs; } + if (healthy_ && nowMs - healthyAt_ >= StableAfterMs) return Decision::Confirm; + if (nowMs - startedAt_ >= HealthDeadlineMs) return Decision::Rollback; + return Decision::Wait; + } +private: + uint32_t startedAt_ = 0; + uint32_t healthyAt_ = 0; + bool started_ = false; + bool healthy_ = false; +}; // Call regularly from loop(); cheap after confirmation. -void tick(uint32_t nowMs); +void tick(uint32_t nowMs, bool localHealthy); // True if this boot is a freshly installed image waiting for confirmation. bool pendingVerify(); diff --git a/lib/update/FirmwareUpdateManager.cpp b/lib/update/FirmwareUpdateManager.cpp index d6bae8d..88e2bca 100644 --- a/lib/update/FirmwareUpdateManager.cpp +++ b/lib/update/FirmwareUpdateManager.cpp @@ -1,3 +1,5 @@ +#include "JsonEscape.h" +#include "UpdateSafety.h" #include "FirmwareUpdateManager.h" #include "FirmwareVersion.h" @@ -52,19 +54,7 @@ uint32_t nowMs() { } std::string jsonEscape(const std::string& value) { - std::string out; - out.reserve(value.size() + 8); - for (char c : value) { - switch (c) { - case '"': out += "\\\""; break; - case '\\': out += "\\\\"; break; - case '\n': out += "\\n"; break; - case '\r': out += "\\r"; break; - default: - if (static_cast(c) >= 0x20) out.push_back(c); - } - } - return out; + return Json::escape(value); } void refreshAvailability() { @@ -83,8 +73,8 @@ bool fail(const std::string& message) { // Downloads, verifies and activates one manifest entry. Never returns on // success because the device restarts into the new firmware. bool installEntry(const FirmwareVersionEntry& entry) { - if (UpdateConfig::BlockInstallWhileVehicleRunning && state.installBlocker != nullptr && state.installBlocker()) { - return fail("Fahrzeug aktiv - Update erst im Stand bei Motor aus"); + if (state.installBlocker == nullptr || state.installBlocker()) { + return fail("Update gesperrt: Fahrzeug aktiv oder Status unbekannt"); } OtaSession session; @@ -203,6 +193,10 @@ String FirmwareUpdateManager::statusJson() { json += ",\"allowRollback\":"; json += UpdateConfig::AllowRollback ? "true" : "false"; json += ",\"signedUpdatesOnly\":true"; + json += ",\"installBlocked\":"; + json += (state.installBlocker == nullptr || state.installBlocker()) ? "true" : "false"; + json += ",\"maintenance\":"; + json += updateSafety.maintenance(nowMs()) ? "true" : "false"; json += ",\"channel\":\"" + std::string(channelName(state.channel)) + "\""; json += ",\"installed\":\"" + jsonEscape(state.installed) + "\""; json += ",\"target\":\"" + jsonEscape(state.target) + "\""; diff --git a/lib/update/UpdateManifest.cpp b/lib/update/UpdateManifest.cpp index fcb3e9e..8a10f4d 100644 --- a/lib/update/UpdateManifest.cpp +++ b/lib/update/UpdateManifest.cpp @@ -1,3 +1,4 @@ +#include "JsonEscape.h" #include "UpdateManifest.h" #include "FirmwareVersion.h" @@ -25,23 +26,8 @@ bool equalsIgnoreCase(const char* a, const char* b) { } std::string jsonEscape(const std::string& value) { - std::string out; - out.reserve(value.size() + 8); - for (char c : value) { - if (c == '"' || c == '\\') { - out.push_back('\\'); - out.push_back(c); - } else if (c == '\n') { - out += "\\n"; - } else if (c == '\r') { - out += "\\r"; - } else { - out.push_back(c); - } - } - return out; + return Json::escape(value); } - std::string extractString(const std::string& object, const char* key) { const std::string pattern = std::string("\"") + key + "\""; size_t pos = object.find(pattern); diff --git a/lib/update/UpdateSafety.h b/lib/update/UpdateSafety.h new file mode 100644 index 0000000..afdf4bc --- /dev/null +++ b/lib/update/UpdateSafety.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include + +namespace FirmwareUpdate { +enum class VehicleCondition { Unknown, Parked, Active }; + +inline VehicleCondition vehicleCondition(const char* state) { + if (!state) return VehicleCondition::Unknown; + if (std::strcmp(state, "Parked") == 0 || std::strcmp(state, "DisplaySleep") == 0) + return VehicleCondition::Parked; + if (std::strcmp(state, "Running") == 0 || std::strcmp(state, "Idle") == 0 || + std::strcmp(state, "StartStop") == 0) return VehicleCondition::Active; + return VehicleCondition::Unknown; +} + +// Unknown is not parked. A bench update requires an explicit, authenticated +// confirmation that the device is disconnected from the vehicle. Never saved. +class UpdateSafety { +public: + static constexpr uint32_t StatusFreshMs = 3000; + static constexpr uint32_t MaintenanceDurationMs = 10 * 60 * 1000; + + void observe(VehicleCondition condition, uint32_t nowMs) { + condition_ = condition; + observedAt_ = nowMs; + observed_ = true; + if (condition == VehicleCondition::Active) maintenance_ = false; + } + bool maintenance(uint32_t nowMs) const { + return maintenance_ && nowMs - maintenanceAt_ < MaintenanceDurationMs; + } + bool enableMaintenance(uint32_t nowMs, bool disconnectedConfirmed) { + if (!disconnectedConfirmed || active(nowMs)) return false; + maintenance_ = true; + maintenanceAt_ = nowMs; + return true; + } + void disableMaintenance() { maintenance_ = false; } + bool blocked(uint32_t nowMs) const { + if (active(nowMs)) return true; + if (maintenance(nowMs)) return false; + return !fresh(nowMs) || condition_ != VehicleCondition::Parked; + } + +private: + bool fresh(uint32_t nowMs) const { return observed_ && nowMs - observedAt_ <= StatusFreshMs; } + bool active(uint32_t nowMs) const { return fresh(nowMs) && condition_ == VehicleCondition::Active; } + VehicleCondition condition_ = VehicleCondition::Unknown; + uint32_t observedAt_ = 0; + uint32_t maintenanceAt_ = 0; + bool observed_ = false; + bool maintenance_ = false; +}; + +inline UpdateSafety updateSafety; +} // namespace FirmwareUpdate diff --git a/lib/utils/JsonEscape.h b/lib/utils/JsonEscape.h new file mode 100644 index 0000000..e0b4fe9 --- /dev/null +++ b/lib/utils/JsonEscape.h @@ -0,0 +1,31 @@ +#pragma once + +#include +#include + +namespace Json { +// Escapes JSON string contents, including embedded NUL/control bytes. +inline std::string escape(std::string_view value) { + constexpr char hex[] = "0123456789abcdef"; + std::string out; + out.reserve(value.size() + 8); + for (unsigned char c : value) { + switch (c) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (c < 0x20) { + out += "\\u00"; + out += hex[c >> 4]; + out += hex[c & 15]; + } else { + out += static_cast(c); + } + } + } + return out; +} +} // namespace Json diff --git a/lib/web/AuthHelpers.cpp b/lib/web/AuthHelpers.cpp index b1b9039..340f290 100644 --- a/lib/web/AuthHelpers.cpp +++ b/lib/web/AuthHelpers.cpp @@ -31,8 +31,8 @@ bool isConfiguredToken(const char* token) { #if defined(ARDUINO) void collectAuthHeaders(WebServer& server) { - static const char* headers[] = {"X-API-Token", "Authorization"}; - server.collectHeaders(headers, 2); + static const char* headers[] = {"X-API-Token", "Authorization", "X-Maintenance-Confirm"}; + server.collectHeaders(headers, 3); } bool requireAuthentication(WebServer& server, bool protectEndpoint) { diff --git a/lib/web/DevicePages.cpp b/lib/web/DevicePages.cpp new file mode 100644 index 0000000..bbb0d9a --- /dev/null +++ b/lib/web/DevicePages.cpp @@ -0,0 +1,171 @@ +#include "WebAssets.h" + +namespace WebAssets { +const char* senderPage() { + return R"rawliteral( + + + + + +CAN OBD2 Sender + + + +
+
CAN OBD2 Sender
WebConsole
Warte
+ +
+
Firmware
Version: --
Target: --
Protocol: --
Build: --
+
CAN
--
+
OBD2
--
+
ESP-NOW
--
+
LED
--
Test: --
VehicleOff: --
Wechsel: --
+
Power Manager
--
Score: -- · Command: --
StartStop: -- · Parked: --
Sleep Timer: --
+
Heartbeat
--
+
Batterie
--
+
Telemetrie
--
+
Letztes Paket
--
+
+
+
PID Support
--
+
Letzter CAN
--
+
Simulation
--
Szenario: --
+
Simulationsszenario
+
DTC / Fehlercodes
--
+
VIN
--
+
OBD Diagnose
+Requests: -- · OK: -- · Timeouts: --
+Negative: -- · SendFail: -- · Timeout-Streak: --
+Request-ID: -- · Fallback: -- +
+
Letzte OBD Anfrage
--
+
Letzte ECU Antwort
--
+
Letzte Negative Response
--
+
Supported PID Masks
01-20: --
21-40: --
41-60: --
+
UDS Diagnose
+Verfuegbar: -- · Requests: -- · OK: --
+Timeouts: -- · Negative: -- · SendFail: -- +
+
Letzte UDS Anfrage
--
+
Letzte UDS Antwort
--
+
UDS DID / DTC
DID: --
DTC: --
NRC: --
+
Diagnose-Snapshot
JSON herunterladen
Noch kein Snapshot geladen.
+
Fehlerstatus
--
+
+
+
Capabilities
--
--
Export JSON
+
OBD PID Ergebnis
Unterstuetzte PIDs werden testweise abgefragt. Nicht unterstuetzte PIDs bleiben grau, Timeouts orange/rot.
PIDNameSupportAntwortWertEinheitmsStatus
+
UDS ECUs
ECUAntwortErreichbarUDSName
+
UDS DID / ECU Infos
ECUDIDNameWertStatus
+
CAN Signal-Finder Kandidaten
Passiv ueber CanRouter: erst Baseline aufnehmen, dann Aktion starten, Ereignis im Fahrzeug ausloesen und danach analysieren.
IDByteVorherNachherMaskeWechsel%
+
Rohdaten
Noch kein Scan geladen.
+
+
+
Diagnose-Log
Persistent: --
Letzter Neustart: --
Log herunterladen
+
Live-Log
Live-Log wird nicht automatisch geladen. Button drücken, damit das Diagnose-WLAN nicht unnötig belastet wird.
+
+
Firmware über Web hochladen
Es wird nur vom Projekt signierte Sender-Firmware akzeptiert. Unsignierte, veraenderte oder Display-Dateien werden abgelehnt, bevor umgeschaltet wird.
+
OTA Status
--
Frei: -- · Sketch: -- · Flash: --
+ +
+
+
GitHub Updates / Rollback
Firmware per WLAN oder Handy-Hotspot aus dem GitHub-Manifest laden. Sender installiert nur Sender-Firmware. Rollback ist manuell und benötigt eine Browser-Bestätigung.
+
+
+ + +)rawliteral"; +} + +const char* displayPage() { + return R"HTML( +CANOBD2 Display +

CANOBD2 Display

+
Verbindung zum Sender
--
+ +
Display-Seiten
--
+
+
Neustart / Absturzbericht
--
+
+
Diagnose-Log
Log herunterladen
+ +)HTML"; +} +} // namespace WebAssets diff --git a/lib/web/ManagementServer.cpp b/lib/web/ManagementServer.cpp index 7c3d599..fb0c286 100644 --- a/lib/web/ManagementServer.cpp +++ b/lib/web/ManagementServer.cpp @@ -1,3 +1,5 @@ +#include "JsonEscape.h" +#include "UpdateSafety.h" #if defined(ARDUINO) #include "ManagementServer.h" @@ -79,8 +81,8 @@ void handleUploadChunk() { case UPLOAD_FILE_START: uploadSucceeded = false; uploadInProgress = true; - if (config.installBlocker != nullptr && config.installBlocker()) { - uploadStatus = "Abgelehnt: Fahrzeug aktiv"; + if (config.installBlocker == nullptr || config.installBlocker()) { + uploadStatus = "Abgelehnt: Fahrzeug aktiv oder Status unbekannt; Wartungsmodus nur bei getrenntem Fahrzeug"; uploadInProgress = false; break; } @@ -141,6 +143,25 @@ void handleUpdateStatus() { sendJson(200, FirmwareUpdate::FirmwareUpdateManager::statusJson()); } +void handleMaintenance() { + if (!authorized(SecurityConfig::RequireOtaAuthentication)) return; + // A custom header prevents cross-origin HTML forms using cached Basic Auth + // from enabling maintenance. This server does not grant CORS preflights. + if (webServer.header("X-Maintenance-Confirm") != "vehicle-disconnected") { + sendJson(403, "{\"error\":\"Wartungsbestaetigung im Header fehlt\"}"); + return; + } + if (webServer.arg("enable") == "0") { + FirmwareUpdate::updateSafety.disableMaintenance(); + } else if (!FirmwareUpdate::updateSafety.enableMaintenance( + millis(), webServer.arg("confirm") == "vehicle-disconnected")) { + sendJson(409, "{\"error\":\"Fahrzeug aktiv oder Bestaetigung fehlt\"}"); + return; + } + log("[OTA] Wartungsmodus geaendert"); + handleUpdateStatus(); +} + void handleUpdateVersions() { if (!authorized()) return; sendJson(200, FirmwareUpdate::FirmwareUpdateManager::versionsJson()); @@ -315,6 +336,7 @@ void handleSimulationScenario() { void registerRoutes() { webServer.on("/update", HTTP_POST, handleUploadFinished, handleUploadChunk); webServer.on("/github-update", HTTP_GET, handleGithubPage); + webServer.on("/api/update/maintenance", HTTP_POST, handleMaintenance); webServer.on("/api/update/status", HTTP_GET, handleUpdateStatus); webServer.on("/api/update/versions", HTTP_GET, handleUpdateVersions); webServer.on("/api/update/check", HTTP_POST, handleUpdateCheck); @@ -354,7 +376,7 @@ bool begin(const Config& value) { return false; } - startAccessPoint("boot"); + if (!startAccessPoint("boot")) return false; WifiNet::WifiStationManager::begin(); FirmwareUpdate::FirmwareUpdateManager::begin(ProjectConfig::TargetName, ProjectConfig::FirmwareVersion, ProjectConfig::ProtocolVersion); @@ -382,21 +404,7 @@ bool otaInProgress() { return uploadInProgress; } const String& otaStatus() { return uploadStatus; } String jsonEscape(const String& value) { - String out; - out.reserve(value.length() + 8); - for (unsigned int index = 0; index < value.length(); ++index) { - const char c = value[index]; - switch (c) { - case '"': out += "\\\""; break; - case '\\': out += "\\\\"; break; - case '\n': out += "\\n"; break; - case '\r': out += "\\r"; break; - case '\t': out += "\\t"; break; - default: - if (static_cast(c) >= 0x20) out += c; - } - } - return out; + return String(Json::escape(std::string_view(value.c_str(), value.length())).c_str()); } void appendCommonStatusJson(String& json) { diff --git a/lib/web/ManagementServer.h b/lib/web/ManagementServer.h index 605f29d..e94ca61 100644 --- a/lib/web/ManagementServer.h +++ b/lib/web/ManagementServer.h @@ -5,7 +5,7 @@ // Common endpoints (all authenticated): // POST /update signed firmware upload (multipart, field "firmware") // GET /github-update GitHub update page -// GET /api/update/status|versions, POST /api/update/check|install|channel +// GET /api/update/status|versions, POST /api/update/check|install|channel|maintenance // GET /api/wifi/status, POST /api/wifi/configure|connect|forget // GET /log/file|/log/download, POST /api/log/clear // GET /api/simulation, POST /api/simulation/on|off|toggle|scenario @@ -35,7 +35,7 @@ struct Config { const char* apPassword; LogFunction log; // required ReportFunction diagnosticReport; // full text report for /log/file - FirmwareUpdate::FirmwareUpdateManager::InstallBlocker installBlocker; // may be nullptr + FirmwareUpdate::FirmwareUpdateManager::InstallBlocker installBlocker; // nullptr blocks all installations }; // Starts AP, station manager, update manager and the common routes. diff --git a/lib/web/WebAssets.cpp b/lib/web/WebAssets.cpp index d92b35b..72ef416 100644 --- a/lib/web/WebAssets.cpp +++ b/lib/web/WebAssets.cpp @@ -32,6 +32,7 @@ table{width:100%;border-collapse:collapse;font-size:.9rem}th,td{border-bottom:1p

Firmware-Updates – %%DEVICE%%

Es werden nur vom Projekt signierte Firmware-Dateien akzeptiert (Ed25519). Unsignierte oder veraenderte Dateien werden vor dem Umschalten verworfen. Zurueck

+

Update-Freigabe

--

Ohne aktuellen Fahrzeugstatus sind Updates gesperrt. Fuer Wartung am Tisch das Geraet vom Fahrzeug trennen.

Datei hochladen

--

WLAN / Hotspot fuer GitHub

--

GitHub

@@ -39,6 +40,9 @@ table{width:100%;border-collapse:collapse;font-size:.9rem}th,td{border-bottom:1p )HTML"; void handleRoot() { if (!WebSecurity::requireAuthentication(Management::server())) return; - String page(RootPage); + String page(WebAssets::displayPage()); page.replace("%%COMMON_JS%%", WebAssets::commonScript()); Management::server().send(200, "text/html; charset=utf-8", page); } @@ -104,8 +74,7 @@ void handleDiagnosticPagesToggle() { // Updates must not interrupt the driver: block while the sender reports a // running vehicle. bool vehicleActive() { - const String& state = DisplayData::runtime().vehicleState; - return DisplayData::isEspNowConnected() && (state == "Running" || state == "StartStop" || state == "Idle"); + return FirmwareUpdate::updateSafety.blocked(millis()); } } // namespace diff --git a/src/sender/OBDHandler.cpp b/src/sender/OBDHandler.cpp index e07360a..f5c1bcc 100644 --- a/src/sender/OBDHandler.cpp +++ b/src/sender/OBDHandler.cpp @@ -108,29 +108,6 @@ bool OBD2Handler::requestPayload(uint8_t mode, return receivePayload(mode, expectedPid, outPayload); } -void OBD2Handler::calcConsumption(uint8_t pid, float value) { - if (pid == VEHICLE_SPEED) Runtime::SenderRuntimeState::updateSpeed(value); - if (pid == ENGINE_FUEL_RATE) Runtime::SenderRuntimeState::updateFuelRate(value); - - // Instantaneous consumption only makes sense while moving; standing it - // is cleared instead of keeping the last (now wrong) value. - if (SenderLiveData::has(LiveData::Metric::FuelRate) && SenderLiveData::has(LiveData::Metric::Speed)) { - const float speed = SenderLiveData::value(LiveData::Metric::Speed); - if (speed >= 5.0f) { - SenderLiveData::update(LiveData::Metric::InstantConsumption, - SenderLiveData::value(LiveData::Metric::FuelRate) * 100.0f / speed); - } else { - SenderLiveData::clear(LiveData::Metric::InstantConsumption); - } - } - - if (!Runtime::SenderRuntimeState::hasConsumptionInput()) return; - float avg = 0.0f; - if (Runtime::SenderRuntimeState::addConsumptionSample(avg)) { - SenderLiveData::update(LiveData::Metric::AverageConsumption, avg); - } -} - namespace { void updateActivityMetrics(uint8_t pid, float value) { if (pid == ENGINE_RPM) Runtime::SenderRuntimeState::updateRpm(value); @@ -176,6 +153,11 @@ bool OBD2Handler::requestAndSendPID(uint8_t pid) { Logger::obdFrame(pid, responseData, responseLen); const PIDResult result = convertPID(pid, responseData, responseLen); + if (!result.valid) { + Obd::Diagnostics::recordInvalidResponse(); + Logger::warn("[OBD] Ungueltige PID-Nutzdaten verworfen"); + return false; + } updateActivityMetrics(pid, result.value); LiveData::Metric metric; @@ -189,10 +171,8 @@ bool OBD2Handler::requestAndSendPID(uint8_t pid) { : result.value * 3600.0f / (ObdConfig::StoichiometricAfr * ObdConfig::FuelDensityGramPerLitre); SenderLiveData::update(LiveData::Metric::FuelRate, litresPerHour); - calcConsumption(ENGINE_FUEL_RATE, litresPerHour); } - if (pid == VEHICLE_SPEED || (pid == ENGINE_FUEL_RATE && !fuelFromMaf)) calcConsumption(pid, result.value); if (pid == INTAKE_MANIFOLD_ABS_PRESSURE || pid == ABS_BAROMETRIC_PRESSURE) updateBoostPressure(pid, result.value); Logger::obdValue(getPIDName(pid), result.value, result.unit); diff --git a/src/sender/SenderApp.cpp b/src/sender/SenderApp.cpp index 84e7ed1..ae386d3 100644 --- a/src/sender/SenderApp.cpp +++ b/src/sender/SenderApp.cpp @@ -6,6 +6,7 @@ #include #include #include "SenderApp.h" +#include "UpdateSafety.h" #include #include "common_config.h" #include "config/ProjectConfig.h" @@ -23,6 +24,7 @@ #include "SenderPower.h" #include "WebConsoleHandler.h" #include "DiagnosticLog.h" +#include "ManagementServer.h" #include "ObdDiagnostics.h" #include "UdsDiagnostics.h" #include "SenderEspNow.h" @@ -205,7 +207,7 @@ void SenderApp::begin() { CanRouting::setFramePump(CANHandler::processIncoming); coordinator.resetForBoot(millis(), kCanIdleTimeoutMs, espNowReady, canDriverReady); - WebConsoleHandler::setInstallBlocker(SenderPower::isCarRunning); + WebConsoleHandler::setInstallBlocker([]() { return FirmwareUpdate::updateSafety.blocked(millis()); }); WebConsoleHandler::begin(); if (!espNowReady) { @@ -245,8 +247,10 @@ void SenderApp::begin() { void SenderApp::tick() { const uint32_t now = millis(); coordinator.tick(now); - SenderLiveData::tick(now); - BootValidation::tick(now); + SenderLiveData::tick(millis()); + BootValidation::tick(now, coordinator.state().canDriverReady && + (!Security::provisioned() || (coordinator.state().espNowReady && Management::running())) && + DiagnosticLog::mounted()); #if CANOBD2_DEV_TOOLS SenderCapabilityScanner::tick(now); #endif diff --git a/src/sender/SenderLiveData.cpp b/src/sender/SenderLiveData.cpp index 4ed526f..1081da5 100644 --- a/src/sender/SenderLiveData.cpp +++ b/src/sender/SenderLiveData.cpp @@ -1,4 +1,5 @@ #include "SenderLiveData.h" +#include "ConsumptionAccumulator.h" #include @@ -8,6 +9,7 @@ namespace { LiveData::LiveValueTable table; +Obd::ConsumptionAccumulator consumption; uint32_t lastSnapshotAt = 0; bool simulationWasActive = false; } // namespace @@ -16,12 +18,16 @@ namespace SenderLiveData { void reset() { table.reset(); + consumption.reset(); lastSnapshotAt = 0; simulationWasActive = false; } void update(LiveData::Metric metric, float value) { - table.update(metric, value, millis()); + const uint32_t now = millis(); + table.update(metric, value, now); + if (metric == LiveData::Metric::Speed) consumption.updateSpeed(value, now); + if (metric == LiveData::Metric::FuelRate) consumption.updateFuelRate(value, now); } void markUnsupported(LiveData::Metric metric) { @@ -47,9 +53,20 @@ float value(LiveData::Metric metric) { void tick(uint32_t nowMs) { // Leaving the simulation must not leave simulated values on the display. const bool simulationActive = Simulation::RuntimeSimulation::enabled(); - if (simulationWasActive && !simulationActive) table.reset(); + if (simulationWasActive != simulationActive) { + table.reset(); + consumption.reset(); + } simulationWasActive = simulationActive; + if (!simulationActive) { + consumption.advance(nowMs); + if (consumption.hasInstant(nowMs)) table.update(LiveData::Metric::InstantConsumption, consumption.instant(), nowMs); + else table.clear(LiveData::Metric::InstantConsumption); + if (consumption.fresh(nowMs) && consumption.hasAverage()) + table.update(LiveData::Metric::AverageConsumption, consumption.average(), nowMs); + } + if (nowMs - lastSnapshotAt < SenderConfig::LiveSnapshotIntervalMs) return; lastSnapshotAt = nowMs; diff --git a/src/sender/SenderPower.cpp b/src/sender/SenderPower.cpp index 9e9b61e..6f358f2 100644 --- a/src/sender/SenderPower.cpp +++ b/src/sender/SenderPower.cpp @@ -1,4 +1,5 @@ #include "SenderPower.h" +#include "UpdateSafety.h" #include @@ -81,6 +82,10 @@ namespace SenderPower { const Power::VehicleState previousState = lastSnapshot.state; lastSnapshot = activityMonitor.update(input); logStateChange(previousState, lastSnapshot.state); + FirmwareUpdate::updateSafety.observe( + Simulation::RuntimeSimulation::enabled() ? FirmwareUpdate::VehicleCondition::Unknown + : FirmwareUpdate::vehicleCondition(Power::ActivityMonitor::vehicleStateName(lastSnapshot.state)), + state.currentMillis); if (lastSnapshot.command != Power::PowerCommand::None) { WebConsoleHandler::log(String("[POWER] command=") + diff --git a/src/sender/WebConsoleHandler.cpp b/src/sender/WebConsoleHandler.cpp index acb35fd..052adda 100644 --- a/src/sender/WebConsoleHandler.cpp +++ b/src/sender/WebConsoleHandler.cpp @@ -9,6 +9,7 @@ #include "DeviceSecrets.h" #include "DiagnosticLog.h" #include "Logger.h" +#include "ObdDiagnostics.h" #include "ManagementServer.h" #include "RuntimeSimulation.h" #include "SenderCapabilityScanner.h" @@ -120,140 +121,8 @@ void WebConsoleHandler::appendLiveWebBuffer(String& report) { void WebConsoleHandler::handleRoot() { if (!WebSecurity::requireAuthentication(Management::server())) return; - static const char html[] PROGMEM = R"rawliteral( - - - - - -CAN OBD2 Sender - - - -
-
CAN OBD2 Sender
WebConsole
Warte
- -
-
Firmware
Version: --
Target: --
Protocol: --
Build: --
-
CAN
--
-
OBD2
--
-
ESP-NOW
--
-
LED
--
Test: --
VehicleOff: --
Wechsel: --
-
Power Manager
--
Score: -- · Command: --
StartStop: -- · Parked: --
Sleep Timer: --
-
Heartbeat
--
-
Batterie
--
-
Telemetrie
--
-
Letztes Paket
--
-
-
-
PID Support
--
-
Letzter CAN
--
-
Simulation
--
Szenario: --
-
Simulationsszenario
-
DTC / Fehlercodes
--
-
VIN
--
-
OBD Diagnose
-Requests: -- · OK: -- · Timeouts: --
-Negative: -- · SendFail: -- · Timeout-Streak: --
-Request-ID: -- · Fallback: -- -
-
Letzte OBD Anfrage
--
-
Letzte ECU Antwort
--
-
Letzte Negative Response
--
-
Supported PID Masks
01-20: --
21-40: --
41-60: --
-
UDS Diagnose
-Verfuegbar: -- · Requests: -- · OK: --
-Timeouts: -- · Negative: -- · SendFail: -- -
-
Letzte UDS Anfrage
--
-
Letzte UDS Antwort
--
-
UDS DID / DTC
DID: --
DTC: --
NRC: --
-
Diagnose-Snapshot
JSON herunterladen
Noch kein Snapshot geladen.
-
Fehlerstatus
--
-
-
-
Capabilities
--
--
Export JSON
-
OBD PID Ergebnis
Unterstuetzte PIDs werden testweise abgefragt. Nicht unterstuetzte PIDs bleiben grau, Timeouts orange/rot.
PIDNameSupportAntwortWertEinheitmsStatus
-
UDS ECUs
ECUAntwortErreichbarUDSName
-
UDS DID / ECU Infos
ECUDIDNameWertStatus
-
CAN Signal-Finder Kandidaten
Passiv ueber CanRouter: erst Baseline aufnehmen, dann Aktion starten, Ereignis im Fahrzeug ausloesen und danach analysieren.
IDByteVorherNachherMaskeWechsel%
-
Rohdaten
Noch kein Scan geladen.
-
-
-
Diagnose-Log
Persistent: --
Letzter Neustart: --
Log herunterladen
-
Live-Log
Live-Log wird nicht automatisch geladen. Button drücken, damit das Diagnose-WLAN nicht unnötig belastet wird.
-
-
Firmware über Web hochladen
Es wird nur vom Projekt signierte Sender-Firmware akzeptiert. Unsignierte, veraenderte oder Display-Dateien werden abgelehnt, bevor umgeschaltet wird.
-
OTA Status
--
Frei: -- · Sketch: -- · Flash: --
- -
-
-
GitHub Updates / Rollback
Firmware per WLAN oder Handy-Hotspot aus dem GitHub-Manifest laden. Sender installiert nur Sender-Firmware. Rollback ist manuell und benötigt eine Browser-Bestätigung.
-
-
- - -)rawliteral"; - String page(html); + String page(WebAssets::senderPage()); + page.replace("%%COMMON_JS%%", WebAssets::commonScript()); page.replace("%%SIMULATION_SCENARIOS%%", WebAssets::simulationScenariosJsonArray()); #if !CANOBD2_DEV_TOOLS // Release build: hide developer tabs and controls (endpoints do not exist). @@ -273,6 +142,7 @@ void WebConsoleHandler::handleStatus() { json.reserve(1600); json += "{"; Management::appendCommonStatusJson(json); + json += "\"obdInvalidResponses\":" + String(Obd::Diagnostics::invalidResponseCount()) + ","; json += "\"started\":" + String(isStarted() ? "true" : "false") + ","; json += "\"canActive\":" + String(s.canActive ? "true" : "false") + ","; json += "\"obdActive\":" + String(s.obdActive ? "true" : "false") + ","; diff --git a/test/python/test_archive_build.py b/test/python/test_archive_build.py new file mode 100644 index 0000000..16f3ad8 --- /dev/null +++ b/test/python/test_archive_build.py @@ -0,0 +1,37 @@ +import hashlib +import json +import sys +import zipfile +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts")) +import archive_build + + +def test_debug_archive_contains_exact_files_and_matching_hashes(tmp_path, monkeypatch): + build = tmp_path / ".pio/build/sender" + build.mkdir(parents=True) + for name in ("firmware.bin", "firmware.elf", "firmware.map"): + (build / name).write_bytes(name.encode()) + for name in ("platformio.ini", "requirements-dev.txt"): + (tmp_path / name).write_text(name) + monkeypatch.setenv("PLATFORMIO_CORE_DIR", str(tmp_path / "core")) + monkeypatch.setattr(archive_build.subprocess, "check_output", + lambda cmd, **kwargs: "a" * 40 if "rev-parse" in cmd else b"") + archive_build.archive_build(tmp_path, tmp_path / "out", ["sender"], "V2.1.1-beta.4") + with zipfile.ZipFile(tmp_path / "out/debug-sender.zip") as bundle: + metadata = json.loads(bundle.read("build.json")) + assert metadata["version"] == "V2.1.1-beta.4" + assert metadata["trackedChanges"] is False + for name, digest in metadata["sha256"].items(): + assert hashlib.sha256(bundle.read(name)).hexdigest() == digest + assert bundle.read("firmware.elf") == b"firmware.elf" + + +def test_missing_elf_stops_archiving(tmp_path, monkeypatch): + monkeypatch.setenv("PLATFORMIO_CORE_DIR", str(tmp_path / "core")) + monkeypatch.setattr(archive_build.subprocess, "check_output", lambda *a, **k: "abc") + with pytest.raises(FileNotFoundError): + archive_build.archive_build(tmp_path, tmp_path / "out", ["sender"], "V2.1.1-beta.4") diff --git a/test/python/test_release_safety.py b/test/python/test_release_safety.py new file mode 100644 index 0000000..7165a5e --- /dev/null +++ b/test/python/test_release_safety.py @@ -0,0 +1,81 @@ +import io +import json +import sys +import urllib.error +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts")) +import fetch_previous_manifest as download +import release_manifest as manifest +import check_secrets + +URL = "https://example.org/index.json" + + +def test_download_retries_then_preserves_exact_valid_index(): + body = b'{"manifestVersion":1,"sender":[],"display":[]}' + attempts = [] + + def opener(url, timeout): + attempts.append(url) + if len(attempts) < 3: + raise urllib.error.HTTPError(url, 503, "unavailable", {}, None) + return io.BytesIO(body) + + assert download.fetch(URL, opener=opener, sleep=lambda _: None) == body + assert len(attempts) == 3 + + +@pytest.mark.parametrize("initialize", [False, True]) +def test_network_failure_never_initializes_index(initialize): + attempts = [] + + def opener(url, timeout): + attempts.append(url) + raise urllib.error.URLError("offline") + + with pytest.raises(manifest.ManifestError): + download.fetch(URL, initialize, opener=opener, sleep=lambda _: None) + assert len(attempts) == 3 + + +def test_missing_index_requires_explicit_initialization(): + def missing(url, timeout): + raise urllib.error.HTTPError(url, 404, "missing", {}, None) + + with pytest.raises(manifest.ManifestError): + download.fetch(URL, opener=missing) + assert json.loads(download.fetch(URL, True, opener=missing)) == {} + + +@pytest.mark.parametrize("body", [b"broken", b"[]", b"{}", b'{"manifestVersion":1,"sender":{}}']) +def test_invalid_download_is_not_replaced_by_empty_index(body): + with pytest.raises((manifest.ManifestError, ValueError)): + download.fetch(URL, True, opener=lambda *a, **k: io.BytesIO(body)) + + +def test_unreadable_previous_manifest_stops_release(tmp_path): + path = tmp_path / "previous.json" + with pytest.raises(manifest.ManifestError): + manifest.load_previous(path) + path.write_text("{") + with pytest.raises(manifest.ManifestError): + manifest.load_previous(path) + + +def test_secret_checker_reports_location_without_value(tmp_path, monkeypatch, capsys): + # Deliberately fabricated token assembled at runtime; no actual credential. + fake = "ghp_" + "z" * 36 + (tmp_path / "leak.txt").write_text("line one\n" + fake) + monkeypatch.setattr(check_secrets, "ROOT", tmp_path) + monkeypatch.setattr(check_secrets, "git_files", lambda: ["leak.txt"]) + class Result: + returncode = 1 + monkeypatch.setattr(check_secrets.subprocess, "run", lambda *a, **k: Result()) + assert check_secrets.main() == 1 + output = capsys.readouterr().out + assert "leak.txt:2:" in output + assert "redacted" in output + assert fake not in output diff --git a/test/python/test_wifi_json.py b/test/python/test_wifi_json.py new file mode 100644 index 0000000..594ae7d --- /dev/null +++ b/test/python/test_wifi_json.py @@ -0,0 +1,36 @@ +"""Parse the real native WLAN status serializer, with persistence replaced only.""" +import json +import shutil +import subprocess +from pathlib import Path + +import pytest + + +def test_ssid_survives_real_status_json(tmp_path): + compiler = shutil.which("g++") + if not compiler: + pytest.skip("native C++ compiler unavailable") + root = Path(__file__).resolve().parents[2] + source = tmp_path / "wifi.cpp" + source.write_text(r''' +#include +#include "WifiStationManager.h" +#include "WifiCredentialStore.h" +namespace WifiNet { +WifiCredentials WifiCredentialStore::load() { return {"Test\"Net\\\n\t", "", true}; } +bool WifiCredentialStore::save(const String&, const String&) { return true; } +bool WifiCredentialStore::clear() { return true; } +} +int main() { + WifiNet::WifiStationManager::begin(); + std::cout << WifiNet::WifiStationManager::statusJson(); +} +''') + executable = tmp_path / "wifi" + subprocess.run([compiler, "-std=c++17", "-Iinclude", "-Ilib/utils", "-Ilib/wifi_station", + str(source), "lib/wifi_station/WifiStationManager.cpp", "-o", str(executable)], + cwd=root, check=True, capture_output=True) + status = json.loads(subprocess.check_output([str(executable)], text=True)) + assert status["ssid"] == 'Test"Net\\\n\t' + assert status["connected"] is False diff --git a/test/test_live_data/test_live_data.cpp b/test/test_live_data/test_live_data.cpp index 62364c4..1cf7660 100644 --- a/test/test_live_data/test_live_data.cpp +++ b/test/test_live_data/test_live_data.cpp @@ -38,11 +38,12 @@ void test_snapshot_roundtrip_keeps_values_masks_and_ages() { TEST_ASSERT_EQUAL_UINT8(LiveData::FlagSimulated, decoded.flags); } -void test_very_old_values_never_report_unknown_age() { +void test_very_old_values_expire_in_snapshot() { LiveData::LiveValueTable table; table.update(Metric::FuelLevel, 50.0f, 0); const LiveData::Snapshot snap = table.snapshot(600000); - TEST_ASSERT_EQUAL_UINT8(LiveData::AgeUnknown - 1, snap.ageTenths[static_cast(Metric::FuelLevel)]); + TEST_ASSERT_FALSE(snap.valid(Metric::FuelLevel)); + TEST_ASSERT_EQUAL_UINT8(LiveData::AgeUnknown, snap.ageTenths[static_cast(Metric::FuelLevel)]); } void test_new_value_clears_unsupported_flag() { @@ -95,7 +96,7 @@ int main(int, char**) { UNITY_BEGIN(); RUN_TEST(test_snapshot_fits_into_one_espnow_packet); RUN_TEST(test_snapshot_roundtrip_keeps_values_masks_and_ages); - RUN_TEST(test_very_old_values_never_report_unknown_age); + RUN_TEST(test_very_old_values_expire_in_snapshot); RUN_TEST(test_new_value_clears_unsupported_flag); RUN_TEST(test_decode_rejects_wrong_size_or_table_version); RUN_TEST(test_pid_and_name_lookup); diff --git a/test/test_review_regressions/test_review_regressions.cpp b/test/test_review_regressions/test_review_regressions.cpp new file mode 100644 index 0000000..bfc926f --- /dev/null +++ b/test/test_review_regressions/test_review_regressions.cpp @@ -0,0 +1,167 @@ +#include +#include +#include "BootValidation.h" +#include "ConsumptionAccumulator.h" +#include "JsonEscape.h" +#include "LiveData.h" +#include "LiveValueView.h" +#include "UpdateSafety.h" +// common is excluded from native library discovery; exercise its real adapter. +#include "../../lib/common/PID_Converter.cpp" + +void setUp() {} +void tearDown() {} + +void test_expiry_survives_repeated_wire_snapshots_and_timer_wrap() { + for (uint32_t start : {1000u, UINT32_MAX - 30000u}) { + LiveData::LiveValueTable table; + DisplayLogic::LiveValueView view; + table.update(LiveData::Metric::Rpm, 1800, start); + for (uint32_t elapsed = 0; elapsed <= 120000; elapsed += 100) { + uint8_t bytes[LiveData::EncodedSnapshotSize]; + LiveData::Snapshot received; + LiveData::encodeSnapshot(table.snapshot(start + elapsed), bytes, sizeof(bytes)); + TEST_ASSERT_TRUE(LiveData::decodeSnapshot(bytes, sizeof(bytes), received)); + view.apply(received, start + elapsed); + if (elapsed > LiveData::MaxValueAgeMs) { + TEST_ASSERT_FALSE(view.get(LiveData::Metric::Rpm, start + elapsed).hasValue()); + } + } + table.update(LiveData::Metric::Rpm, 1900, start + 120100); + view.apply(table.snapshot(start + 120100), start + 120100); + TEST_ASSERT_EQUAL_FLOAT(1900, view.get(LiveData::Metric::Rpm, start + 120100).value); + } +} + +void test_invalid_pid_keeps_validity_and_negative_temperatures_remain_valid() { + const uint8_t data[] = {39}; + TEST_ASSERT_FALSE(convertPID(0x0c, data, 1).valid); + const auto temperature = convertPID(0x05, data, 1); + TEST_ASSERT_TRUE(temperature.valid); + TEST_ASSERT_EQUAL_FLOAT(-1, temperature.value); + LiveData::LiveValueTable table; + table.update(LiveData::Metric::Rpm, std::numeric_limits::quiet_NaN(), 0); + TEST_ASSERT_FALSE(table.snapshot(0).valid(LiveData::Metric::Rpm)); +} + +void test_slow_pid_remains_fresh_until_next_poll_with_margin() { + LiveData::LiveValueTable table; + for (auto metric : {LiveData::Metric::CoolantTemp, LiveData::Metric::EcuVoltage}) { + table.update(metric, 12, 1000); + DisplayLogic::LiveValueView view; + view.apply(table.snapshot(1000), 1000); + TEST_ASSERT_EQUAL(static_cast(DisplayLogic::ValueState::Fresh), + static_cast(view.get(metric, 1000 + SenderConfig::SlowPidIntervalMs + 500).state)); + } +} + +void test_json_preserves_quotes_backslashes_and_control_characters() { + std::string input = "Test\"Net\\\n\r\t"; + input.push_back(0); + input.push_back(1); + const auto escaped = Json::escape(input); + TEST_ASSERT_EQUAL_STRING("Test\\\"Net\\\\\\n\\r\\t\\u0000\\u0001", escaped.c_str()); + TEST_ASSERT_EQUAL_STRING("Grüße", Json::escape("Grüße").c_str()); +} + +void test_update_requires_fresh_parked_state_or_explicit_maintenance() { + using namespace FirmwareUpdate; + UpdateSafety gate; + TEST_ASSERT_TRUE(gate.blocked(0)); + TEST_ASSERT_FALSE(gate.enableMaintenance(0, false)); + gate.observe(VehicleCondition::Parked, 100); + TEST_ASSERT_FALSE(gate.blocked(100)); + TEST_ASSERT_TRUE(gate.blocked(100 + UpdateSafety::StatusFreshMs + 1)); + gate.observe(VehicleCondition::Active, 4000); + TEST_ASSERT_TRUE(gate.blocked(4000)); + TEST_ASSERT_FALSE(gate.enableMaintenance(4000, true)); + TEST_ASSERT_TRUE(gate.blocked(8000)); + TEST_ASSERT_TRUE(gate.enableMaintenance(8000, true)); + TEST_ASSERT_FALSE(gate.blocked(8000)); + TEST_ASSERT_TRUE(gate.blocked(8000 + UpdateSafety::MaintenanceDurationMs)); + TEST_ASSERT_TRUE(gate.enableMaintenance(UINT32_MAX - 100, true)); + TEST_ASSERT_FALSE(gate.blocked(100)); + gate.observe(VehicleCondition::Active, 101); + TEST_ASSERT_TRUE(gate.blocked(101)); + TEST_ASSERT_FALSE(gate.maintenance(101)); + TEST_ASSERT_EQUAL(static_cast(VehicleCondition::Unknown), static_cast(vehicleCondition("Booting"))); +} + +void test_boot_health_requires_continuous_local_success() { + using namespace BootValidation; + HealthGate gate; + TEST_ASSERT_EQUAL(static_cast(Decision::Wait), static_cast(gate.evaluate(90000, true))); + TEST_ASSERT_EQUAL(static_cast(Decision::Wait), static_cast(gate.evaluate(119999, true))); + TEST_ASSERT_EQUAL(static_cast(Decision::Confirm), static_cast(gate.evaluate(120000, true))); + HealthGate failed; + failed.evaluate(0, true); + failed.evaluate(29000, false); + TEST_ASSERT_EQUAL(static_cast(Decision::Wait), static_cast(failed.evaluate(30000, true))); + failed.evaluate(59999, false); + TEST_ASSERT_EQUAL(static_cast(Decision::Rollback), static_cast(failed.evaluate(60000, true))); + HealthGate wrap; + wrap.evaluate(UINT32_MAX - 100, true); + TEST_ASSERT_EQUAL(static_cast(Decision::Confirm), static_cast(wrap.evaluate(30000, true))); +} + +void test_consumption_weights_distance_and_accepts_zero_fuel_and_standstill() { + Obd::ConsumptionAccumulator c; + for (uint32_t t = 0; t <= 10000; t += 1000) { + c.updateSpeed(t < 5000 ? 10 : 100, t); + c.updateFuelRate(1, t); + } + TEST_ASSERT_FLOAT_WITHIN(0.0001, 100.0 / 55.0, c.average()); + c.updateFuelRate(0, 10000); + const float before = c.average(); + c.updateSpeed(100, 11000); + c.updateFuelRate(0, 11000); + TEST_ASSERT_TRUE(c.average() < before); + TEST_ASSERT_EQUAL_FLOAT(0, c.instant()); + c.updateSpeed(0, 11000); + c.updateFuelRate(1, 11000); + const double litres = c.litres(); + const double distance = c.kilometres(); + c.advance(12000); + TEST_ASSERT_TRUE(c.litres() > litres); + TEST_ASSERT_FLOAT_WITHIN(0.000001, distance, c.kilometres()); + TEST_ASSERT_FALSE(c.hasInstant(12000)); +} + +void test_consumption_stale_gap_does_not_count_and_frequency_does_not_change_average() { + Obd::ConsumptionAccumulator fast, slow; + for (uint32_t t = 0; t <= 10000; t += 100) { + fast.updateSpeed(100, t); + fast.updateFuelRate(5, t); + if (t % 1000 == 0) { + slow.updateSpeed(100, t); + slow.updateFuelRate(5, t); + } + } + TEST_ASSERT_FLOAT_WITHIN(0.00001, fast.average(), slow.average()); + slow.advance(20000); + const double distance = slow.kilometres(); + slow.advance(60000); + TEST_ASSERT_FLOAT_WITHIN(0.000001, distance, slow.kilometres()); + TEST_ASSERT_FALSE(slow.fresh(60000)); + slow.updateSpeed(100, 60000); + slow.updateFuelRate(5, 60000); + TEST_ASSERT_FLOAT_WITHIN(0.000001, distance, slow.kilometres()); + slow.advance(61000); + TEST_ASSERT_TRUE(slow.kilometres() > distance); + slow.reset(); + TEST_ASSERT_FALSE(slow.hasAverage()); + TEST_ASSERT_FALSE(slow.fresh(61000)); +} + +int main(int, char**) { + UNITY_BEGIN(); + RUN_TEST(test_expiry_survives_repeated_wire_snapshots_and_timer_wrap); + RUN_TEST(test_invalid_pid_keeps_validity_and_negative_temperatures_remain_valid); + RUN_TEST(test_slow_pid_remains_fresh_until_next_poll_with_margin); + RUN_TEST(test_json_preserves_quotes_backslashes_and_control_characters); + RUN_TEST(test_update_requires_fresh_parked_state_or_explicit_maintenance); + RUN_TEST(test_boot_health_requires_continuous_local_success); + RUN_TEST(test_consumption_weights_distance_and_accepts_zero_fuel_and_standstill); + RUN_TEST(test_consumption_stale_gap_does_not_count_and_frequency_does_not_change_average); + return UNITY_END(); +} diff --git a/test/test_runtime/test_sender_runtime.cpp b/test/test_runtime/test_sender_runtime.cpp index bb0671c..2821e06 100644 --- a/test/test_runtime/test_sender_runtime.cpp +++ b/test/test_runtime/test_sender_runtime.cpp @@ -92,28 +92,6 @@ void setUp() { void tearDown() {} -void test_consumption_requires_speed_and_fuel_rate() { - TEST_ASSERT_FALSE(Runtime::SenderRuntimeState::hasConsumptionInput()); - Runtime::SenderRuntimeState::updateSpeed(50.0f); - TEST_ASSERT_FALSE(Runtime::SenderRuntimeState::hasConsumptionInput()); - Runtime::SenderRuntimeState::updateFuelRate(5.0f); - TEST_ASSERT_TRUE(Runtime::SenderRuntimeState::hasConsumptionInput()); -} - -void test_consumption_average_after_ten_samples() { - Runtime::SenderRuntimeState::updateSpeed(100.0f); - Runtime::SenderRuntimeState::updateFuelRate(7.5f); - - float average = 0.0f; - for (int i = 0; i < 9; ++i) { - TEST_ASSERT_FALSE(Runtime::SenderRuntimeState::addConsumptionSample(average)); - } - - TEST_ASSERT_TRUE(Runtime::SenderRuntimeState::addConsumptionSample(average)); - TEST_ASSERT_FLOAT_WITHIN(0.001f, 7.5f, average); - TEST_ASSERT_EQUAL_UINT32(0, Runtime::SenderRuntimeState::consumptionSampleCount()); -} - void test_sender_loop_state_tracks_can_activity() { Runtime::SenderLoopState state; state.resetForBoot(1000, 250); @@ -201,8 +179,6 @@ void test_runtime_coordinator_respects_start_and_driver_guards() { int main(int, char**) { UNITY_BEGIN(); - RUN_TEST(test_consumption_requires_speed_and_fuel_rate); - RUN_TEST(test_consumption_average_after_ten_samples); RUN_TEST(test_sender_loop_state_tracks_can_activity); RUN_TEST(test_sender_loop_state_resets_timestamps); RUN_TEST(test_runtime_coordinator_runs_simulation_path_before_schedulers);