From a0380eadcb0345529f61cf73596e90f05049799c Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sun, 1 Nov 2026 13:34:14 +0100 Subject: [PATCH 1/4] Coredump partitions, 16 MB display layout, loop watchdog - partitions/sender_4mb.csv: app slots and NVS unchanged, 64 KB coredump, 256 KB log. partitions/display_16mb.csv: 2 x 4 MB app, 128 KB coredump, 1 MB log, rest reserved. NVS stays at 0x9000 in both -> credentials survive. - lib/diagnostics/SystemHealth: reset reason + core dump summary at boot, GET /api/coredump, POST /api/coredump/clear, shown in both web UIs. - Loop task watchdog (30 s, panic -> core dump -> reboot; with boot validation a hanging new firmware is rolled back). Fed during downloads and web uploads. - flash.sh layout: new partition table + firmware without erasing NVS. - Version V2.1.0-beta.3. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- VERSION.txt | 2 +- docs/ARCHITECTURE.md | 1 + docs/DEVELOPMENT.md | 15 ++++ docs/HARDWARE.md | 6 +- docs/PROVISIONING.md | 16 ++++ docs/SECURITY.md | 4 + lib/diagnostics/SystemHealth.cpp | 122 +++++++++++++++++++++++++++ lib/diagnostics/SystemHealth.h | 44 ++++++++++ lib/update/GitHubUpdateClient.cpp | 2 + lib/web/ManagementServer.cpp | 37 ++++++++ lib/web/ManagementServer.h | 1 + partitions/display_16mb.csv | 10 +++ partitions/ota_4mb.csv | 6 -- partitions/sender_4mb.csv | 9 ++ platformio.ini | 6 +- scripts/make_provisioning_package.py | 42 ++++++--- src/display/DisplayApp.cpp | 3 + src/display/DisplayWeb.cpp | 5 ++ src/sender/SenderApp.cpp | 3 + src/sender/WebConsoleHandler.cpp | 4 +- 21 files changed, 316 insertions(+), 24 deletions(-) create mode 100644 lib/diagnostics/SystemHealth.cpp create mode 100644 lib/diagnostics/SystemHealth.h create mode 100644 partitions/display_16mb.csv delete mode 100644 partitions/ota_4mb.csv create mode 100644 partitions/sender_4mb.csv diff --git a/README.md b/README.md index 3c6ec42..9f3d9c2 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.2`, Telemetrie-Protokoll 3. +Stand: `V2.1.0-beta.3`, Telemetrie-Protokoll 3. ## Schnellstart diff --git a/VERSION.txt b/VERSION.txt index de75e04..d5eca96 100644 --- a/VERSION.txt +++ b/VERSION.txt @@ -1 +1 @@ -V2.1.0-beta.2 +V2.1.0-beta.3 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index f1e4b27..6a107e0 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -51,6 +51,7 @@ Heartbeat) sind selten und bleiben Textpakete. | `lib/update/` | GitHub-Manifest, SemVer, `OtaSession` (signierte Installation), Boot-Validierung | | `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/simulation/`, `lib/capabilities/`, `lib/can_router/` | Entwicklerwerkzeuge (nur `*_dev`-Builds aktiv) | | `include/config/` | Konfiguration je Bereich (keine Zugangsdaten) | diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index a374ca1..99794cb 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -41,6 +41,21 @@ python scripts/ota_upload.py --host 192.168.4.1 output/sender.bin python scripts/ota_upload.py --sign-key ~/canobd2-signing.pem .pio/build/sender/firmware.bin ``` +## Abstürze analysieren + +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): + +```bash +pip install esp-coredump +esp-coredump info_corefile -t raw -c CANOBD2_sender_…_coredump.bin .pio/build/sender/firmware.elf +``` + +Danach den Bericht in der Weboberfläche löschen (`POST /api/coredump/clear`). + ## Release GitHub → Actions → **Release** → Version (z. B. `2.1.0-beta.1`) und Kanal diff --git a/docs/HARDWARE.md b/docs/HARDWARE.md index e0e00de..b9821e8 100644 --- a/docs/HARDWARE.md +++ b/docs/HARDWARE.md @@ -9,6 +9,9 @@ | Taster (LED-Test) | 25 | | Spannungsteiler Bordnetz | 32 (Faktor 4,81) | +Partitionslayout `partitions/sender_4mb.csv`: 2 × 1,81 MB Firmware, 64 KB +Absturzbericht, 256 KB Log. + CAN: 500 kbit/s, OBD-Anfragen funktional an `0x7DF`, nach wiederholten Timeouts physisch an `0x7E0`. Nach Bus-Off startet der Treiber automatisch neu. CAN-Fehler (z. B. am Tisch ohne Fahrzeug: „error passive“, „Bus error“) werden @@ -30,7 +33,8 @@ sendet der Sender nur noch ein Paket pro Sekunde, bis es wieder quittiert. ## Display – LilyGO T-Display S3 ST7789 170×320 an 8-Bit-Parallelbus (Pins in `platformio.ini`), Hintergrundbeleuchtung GPIO 38, -Displayversorgung GPIO 15, Tasten GPIO 0 (BOOT) und GPIO 14. +Partitionslayout `partitions/display_16mb.csv`: 2 × 4 MB Firmware, 128 KB +Absturzbericht, 1 MB Log, Rest frei. Displayversorgung GPIO 15, Tasten GPIO 0 (BOOT) und GPIO 14. Tasten: BOOT (GPIO 0) kurz = nächste Seite, zweite Taste (GPIO 14) kurz = vorherige Seite, eine der beiden lang (1,2 s) = Hauptseite, BOOT sehr lang (3 s) = Diagnoseseiten ein/aus. diff --git a/docs/PROVISIONING.md b/docs/PROVISIONING.md index 7202296..e7338de 100644 --- a/docs/PROVISIONING.md +++ b/docs/PROVISIONING.md @@ -71,6 +71,22 @@ Paket kopieren (z. B. `scp -r`), Board per USB anschließen, dann: 5. Optional: unter „Firmware-Update“ eine unsignierte Datei hochladen – sie muss abgelehnt werden. +## Partitionslayout ändern (Zugangsdaten bleiben) + +Eine neue Partitionstabelle lässt sich nicht per WLAN einspielen. Für diesen +Fall gibt es den Befehl `layout`: Er schreibt Bootloader, Partitionstabelle, +Startauswahl und Firmware, **ohne** den Flash zu löschen. Der NVS-Bereich mit +den Zugangsdaten liegt in allen Layouts bei `0x9000` und bleibt erhalten. Nur +das Diagnose-Log wird beim ersten Start neu angelegt. + +```bash +./flash.sh pruefen sender && ./flash.sh layout sender +./flash.sh pruefen display && ./flash.sh layout display +``` + +Aktuelle Layouts: `partitions/sender_4mb.csv` (ESP32, 4 MB) und +`partitions/display_16mb.csv` (ESP32-S3, 16 MB), jeweils mit Coredump-Bereich. + ## Spätere Updates Unter **Firmware-Update** (`/github-update`): WLAN/Hotspot eintragen, Kanal diff --git a/docs/SECURITY.md b/docs/SECURITY.md index afefc16..9daa3dd 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -44,6 +44,10 @@ Zugriff auf die Platine das NVS auslesen. als bestätigt (`lib/update/BootValidation`). Stürzt sie vorher ab, startet der Bootloader wieder die vorherige Version. +* **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 + ebenfalls der Rollback. + ### Schlüsselverwaltung * Öffentliche Schlüssel: `include/config/FirmwareSigningKeys.h` (im Repo). diff --git a/lib/diagnostics/SystemHealth.cpp b/lib/diagnostics/SystemHealth.cpp new file mode 100644 index 0000000..ef63368 --- /dev/null +++ b/lib/diagnostics/SystemHealth.cpp @@ -0,0 +1,122 @@ +#include "SystemHealth.h" + +#if defined(ARDUINO) + #include + #include + #include + #include + #include + #include "DiagnosticLog.h" +#endif + +#include +#include + +namespace SystemHealth { + +const char* resetReasonText() { +#if defined(ARDUINO) + switch (esp_reset_reason()) { + case ESP_RST_POWERON: return "POWERON"; + case ESP_RST_EXT: return "EXTERNAL"; + case ESP_RST_SW: return "SOFTWARE"; + case ESP_RST_PANIC: return "PANIC"; + case ESP_RST_INT_WDT: return "INT_WDT"; + case ESP_RST_TASK_WDT: return "TASK_WDT"; + case ESP_RST_WDT: return "WDT"; + case ESP_RST_DEEPSLEEP: return "DEEPSLEEP"; + case ESP_RST_BROWNOUT: return "BROWNOUT"; + case ESP_RST_SDIO: return "SDIO"; + case ESP_RST_USB: return "USB"; + default: return "UNKNOWN"; + } +#else + return "NATIVE"; +#endif +} + +bool crashReset() { +#if defined(ARDUINO) + const esp_reset_reason_t reason = esp_reset_reason(); + return reason == ESP_RST_PANIC || reason == ESP_RST_INT_WDT || reason == ESP_RST_TASK_WDT || + reason == ESP_RST_WDT || reason == ESP_RST_BROWNOUT; +#else + return false; +#endif +} + +CoreDumpInfo coreDump() { + CoreDumpInfo info; +#if defined(ARDUINO) + if (esp_core_dump_image_check() != ESP_OK) return info; + if (esp_core_dump_image_get(&info.address, &info.size) != ESP_OK) return info; + info.present = true; + esp_core_dump_summary_t* summary = + static_cast(malloc(sizeof(esp_core_dump_summary_t))); + if (summary != nullptr) { + if (esp_core_dump_get_summary(summary) == ESP_OK) { + std::snprintf(info.task, sizeof(info.task), "%s", summary->exc_task); + info.pc = summary->exc_pc; + } + free(summary); + } +#endif + return info; +} + +bool eraseCoreDump() { +#if defined(ARDUINO) + return esp_core_dump_image_erase() == ESP_OK; +#else + return false; +#endif +} + +bool readCoreDump(std::size_t offset, uint8_t* buffer, std::size_t length) { +#if defined(ARDUINO) + const CoreDumpInfo info = coreDump(); + if (!info.present || offset + length > info.size) return false; + return esp_flash_read(nullptr, buffer, info.address + offset, length) == ESP_OK; +#else + (void)offset; + (void)buffer; + (void)length; + return false; +#endif +} + +void logBootSummary(const char* device) { +#if defined(ARDUINO) + const CoreDumpInfo dump = coreDump(); + if (dump.present) { + DiagnosticLog::appendf("[BOOT] %s reset=%s, Absturzbericht vorhanden: task=%s pc=0x%08lx (%u Bytes, /api/coredump)", + device, resetReasonText(), dump.task, static_cast(dump.pc), + static_cast(dump.size)); + } else { + DiagnosticLog::appendf("[BOOT] %s reset=%s", device, resetReasonText()); + } +#else + (void)device; +#endif +} + +void startWatchdog() { +#if defined(ARDUINO) + // The task watchdog is initialised by the core with 5 s; give loop() more + // room for TLS handshakes and UDS "response pending" sequences. + esp_task_wdt_config_t config = {}; + config.timeout_ms = WatchdogTimeoutMs; + config.idle_core_mask = 0; // only watch the loop task, not the idle tasks + config.trigger_panic = true; // panic -> core dump -> reboot + esp_task_wdt_reconfigure(&config); + enableLoopWDT(); +#endif +} + +void feed() { +#if defined(ARDUINO) + feedLoopWDT(); +#endif +} + +} // namespace SystemHealth diff --git a/lib/diagnostics/SystemHealth.h b/lib/diagnostics/SystemHealth.h new file mode 100644 index 0000000..e920647 --- /dev/null +++ b/lib/diagnostics/SystemHealth.h @@ -0,0 +1,44 @@ +#pragma once + +// Crash diagnostics and loop watchdog (sender and display). +// +// * Reset reason and a stored core dump are reported once at boot +// ("[BOOT] reset=... coredump: task=... pc=0x..."). +// * Core dumps (ELF, partition "coredump") can be downloaded via +// GET /api/coredump and analysed with +// esp-coredump info_corefile -t raw -c coredump.bin firmware.elf +// * The loop task watchdog resets the device if loop() hangs for +// WatchdogTimeoutMs; together with BootValidation a hanging new firmware +// is rolled back. Long blocking operations call SystemHealth::feed(). + +#include +#include + +namespace SystemHealth { + +constexpr uint32_t WatchdogTimeoutMs = 30000; + +// Reset reason as short text, e.g. "POWERON", "PANIC", "TASK_WDT". +const char* resetReasonText(); +bool crashReset(); + +struct CoreDumpInfo { + bool present = false; + std::size_t address = 0; + std::size_t size = 0; + char task[16] = {}; + uint32_t pc = 0; +}; + +CoreDumpInfo coreDump(); +bool eraseCoreDump(); +// Reads `length` bytes of the stored core dump starting at `offset`. +bool readCoreDump(std::size_t offset, uint8_t* buffer, std::size_t length); + +// Writes the boot summary to the diagnostic log (call after DiagnosticLog::begin). +void logBootSummary(const char* device); + +void startWatchdog(); +void feed(); + +} // namespace SystemHealth diff --git a/lib/update/GitHubUpdateClient.cpp b/lib/update/GitHubUpdateClient.cpp index 2ef3056..da4610b 100644 --- a/lib/update/GitHubUpdateClient.cpp +++ b/lib/update/GitHubUpdateClient.cpp @@ -1,6 +1,7 @@ #include "GitHubUpdateClient.h" #include "OtaSession.h" +#include "SystemHealth.h" #include "config/UpdateConfig.h" #if defined(ARDUINO) @@ -85,6 +86,7 @@ bool GitHubUpdateClient::downloadInto(const char* url, OtaSession& session, std: std::size_t received = 0; uint32_t lastDataMs = millis(); while (http.connected() && (contentLength < 0 || received < static_cast(contentLength))) { + SystemHealth::feed(); // a download takes longer than the loop watchdog allows const std::size_t available = stream->available(); if (available == 0) { if (millis() - lastDataMs > UpdateConfig::DownloadTimeoutMs) { diff --git a/lib/web/ManagementServer.cpp b/lib/web/ManagementServer.cpp index 48e9453..7c3d599 100644 --- a/lib/web/ManagementServer.cpp +++ b/lib/web/ManagementServer.cpp @@ -10,6 +10,7 @@ #include "DiagnosticLog.h" #include "FirmwareMetadata.h" #include "OtaSession.h" +#include "SystemHealth.h" #include "RuntimeSimulation.h" #include "SimulationTypes.h" #include "WebAssets.h" @@ -73,6 +74,7 @@ void keepAccessPointAlive() { void handleUploadChunk() { if (!authorized(SecurityConfig::RequireOtaAuthentication)) return; HTTPUpload& part = webServer.upload(); + SystemHealth::feed(); // the whole upload runs inside one loop() iteration switch (part.status) { case UPLOAD_FILE_START: uploadSucceeded = false; @@ -217,6 +219,35 @@ void handleLogClear() { sendJson(ok ? 200 : 500, ok ? "{\"cleared\":true}" : "{\"cleared\":false}"); } +// ---- Crash reports ----------------------------------------------------------- + +void handleCoreDumpDownload() { + if (!authorized()) return; + const SystemHealth::CoreDumpInfo dump = SystemHealth::coreDump(); + if (!dump.present) { + webServer.send(404, "text/plain; charset=utf-8", "Kein Absturzbericht vorhanden"); + return; + } + const String filename = String("CANOBD2_") + ProjectConfig::TargetName + "_" + ProjectConfig::FirmwareVersion + + "_coredump.bin"; + webServer.sendHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); + webServer.setContentLength(dump.size); + webServer.send(200, "application/octet-stream", ""); + uint8_t buffer[1024]; + for (std::size_t offset = 0; offset < dump.size; offset += sizeof(buffer)) { + const std::size_t length = dump.size - offset < sizeof(buffer) ? dump.size - offset : sizeof(buffer); + if (!SystemHealth::readCoreDump(offset, buffer, length)) break; + webServer.sendContent(reinterpret_cast(buffer), length); + } +} + +void handleCoreDumpClear() { + if (!authorized()) return; + const bool ok = SystemHealth::eraseCoreDump(); + log(ok ? "[WEB] Absturzbericht geloescht" : "[WEB] Absturzbericht konnte nicht geloescht werden"); + sendJson(ok ? 200 : 500, ok ? "{\"cleared\":true}" : "{\"cleared\":false}"); +} + void handleRestart() { if (!authorized(SecurityConfig::RequireRestartAuthentication)) return; log("[WEB] Neustart angefordert"); @@ -297,6 +328,8 @@ void registerRoutes() { webServer.on("/log/download", HTTP_GET, handleLogDownload); webServer.on("/api/log/clear", HTTP_POST, handleLogClear); webServer.on("/api/restart", HTTP_POST, handleRestart); + webServer.on("/api/coredump", HTTP_GET, handleCoreDumpDownload); + webServer.on("/api/coredump/clear", HTTP_POST, handleCoreDumpClear); // Simulation status is always readable; switching needs a dev build. webServer.on("/api/simulation", HTTP_GET, handleSimulationStatus); #if CANOBD2_DEV_TOOLS @@ -412,6 +445,10 @@ void appendCommonStatusJson(String& json) { field("ip", WiFi.softAPIP().toString()); number("apClients", WiFi.softAPgetStationNum()); number("apRestarts", apRestarts); + const SystemHealth::CoreDumpInfo dump = SystemHealth::coreDump(); + field("resetReason", SystemHealth::resetReasonText()); + flag("coreDumpPresent", dump.present); + number("coreDumpSize", dump.size); flag("devTools", CANOBD2_DEV_TOOLS); number("uptime", millis()); } diff --git a/lib/web/ManagementServer.h b/lib/web/ManagementServer.h index 8269174..605f29d 100644 --- a/lib/web/ManagementServer.h +++ b/lib/web/ManagementServer.h @@ -9,6 +9,7 @@ // 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 +// GET /api/coredump (crash report download), POST /api/coredump/clear // POST /api/restart // Device specific pages (/, /status, ...) are registered by the target via // server() after begin(). diff --git a/partitions/display_16mb.csv b/partitions/display_16mb.csv new file mode 100644 index 0000000..d37c50c --- /dev/null +++ b/partitions/display_16mb.csv @@ -0,0 +1,10 @@ +# Display, LilyGO T-Display S3 16 MB. NVS (credentials) stays at 0x9000. +# 4 MB per app slot; 1 MB log file system (larger SPIFFS mounts slowly); +# 0x930000-0xFFFFFF is left free as reserve. +# Name, Type, SubType, Offset, Size +nvs, data, nvs, 0x9000, 0x5000 +otadata, data, ota, 0xe000, 0x2000 +app0, app, ota_0, 0x10000, 0x400000 +app1, app, ota_1, 0x410000, 0x400000 +coredump, data, coredump, 0x810000, 0x20000 +spiffs, data, spiffs, 0x830000, 0x100000 diff --git a/partitions/ota_4mb.csv b/partitions/ota_4mb.csv deleted file mode 100644 index a884c8c..0000000 --- a/partitions/ota_4mb.csv +++ /dev/null @@ -1,6 +0,0 @@ -# Name, Type, SubType, Offset, Size, Flags -nvs, data, nvs, 0x9000, 0x5000, -otadata, data, ota, 0xe000, 0x2000, -app0, app, ota_0, 0x10000, 0x1D0000, -app1, app, ota_1, 0x1E0000, 0x1D0000, -spiffs, data, spiffs, 0x3B0000, 0x50000, diff --git a/partitions/sender_4mb.csv b/partitions/sender_4mb.csv new file mode 100644 index 0000000..eb9f737 --- /dev/null +++ b/partitions/sender_4mb.csv @@ -0,0 +1,9 @@ +# Sender, ESP32 4 MB. NVS (credentials) and app slots unchanged from the +# former ota_4mb.csv, so a layout change via USB keeps the provisioning. +# Name, Type, SubType, Offset, Size +nvs, data, nvs, 0x9000, 0x5000 +otadata, data, ota, 0xe000, 0x2000 +app0, app, ota_0, 0x10000, 0x1D0000 +app1, app, ota_1, 0x1E0000, 0x1D0000 +coredump, data, coredump, 0x3B0000, 0x10000 +spiffs, data, spiffs, 0x3C0000, 0x40000 diff --git a/platformio.ini b/platformio.ini index e62d3c1..15767e3 100644 --- a/platformio.ini +++ b/platformio.ini @@ -10,7 +10,6 @@ upload_speed = 921600 ; "chain" (not chain+): the "+" modes evaluate #if SOC_WIFI_SUPPORTED without ; knowing it and then miss the core library "Networking" (Arduino-ESP32 3.x). lib_ldf_mode = chain -board_build.partitions = partitions/ota_4mb.csv extra_scripts = pre:scripts/apply_firmware_version.py pre:scripts/auto_upload_port.py @@ -43,6 +42,7 @@ build_flags = -Ilib/monocypher -Ilib/firmware_signing -Ilib/security + -Ilib/diagnostics -DCORE_DEBUG_LEVEL=0 build_src_flags = -Wshadow @@ -57,6 +57,7 @@ build_src_flags = [env:sender] board = esp32dev +board_build.partitions = partitions/sender_4mb.csv custom_upload_vid = 0x1A86 custom_upload_pid = 0x7523 build_src_filter = @@ -72,6 +73,7 @@ lib_deps = [env:display] board = lilygo-t-display-s3 +board_build.partitions = partitions/display_16mb.csv ; ESP32-S3 USB-Serial ist mit 921600 je nach Kabel/Host oft instabil. upload_speed = 460800 custom_upload_vid = 0x303A @@ -167,6 +169,7 @@ build_flags = -Ilib/monocypher -Ilib/firmware_signing -Ilib/security + -Ilib/diagnostics build_src_filter = +<../lib/utils/> +<../lib/telemetry/> @@ -188,4 +191,5 @@ build_src_filter = +<../lib/monocypher/> +<../lib/firmware_signing/> +<../lib/security/> + +<../lib/diagnostics/> -<*> diff --git a/scripts/make_provisioning_package.py b/scripts/make_provisioning_package.py index 211b8c8..a211c39 100644 --- a/scripts/make_provisioning_package.py +++ b/scripts/make_provisioning_package.py @@ -29,8 +29,10 @@ # chip, bootloader offset, USB VID:PID, baud TARGETS = { - "sender": {"chip": "esp32", "bootloader": 0x1000, "usb": "1a86:7523", "baud": 460800, "mac": "SenderAllowedMac"}, - "display": {"chip": "esp32s3", "bootloader": 0x0, "usb": "303a:1001", "baud": 460800, "mac": "DisplayPeerMac"}, + "sender": {"chip": "esp32", "bootloader": 0x1000, "usb": "1a86:7523", "baud": 460800, "mac": "SenderAllowedMac", + "partitions": "sender_4mb.csv"}, + "display": {"chip": "esp32s3", "bootloader": 0x0, "usb": "303a:1001", "baud": 460800, "mac": "DisplayPeerMac", + "partitions": "display_16mb.csv"}, } PARTITIONS_OFFSET = 0x8000 @@ -54,9 +56,9 @@ def read_secrets() -> dict[str, str]: return values -def otadata_and_app_offsets() -> tuple[int, int]: +def otadata_and_app_offsets(csv_name: str) -> tuple[int, int]: otadata = app = None - for line in (ROOT / "partitions" / "ota_4mb.csv").read_text().splitlines(): + for line in (ROOT / "partitions" / csv_name).read_text().splitlines(): fields = [f.strip() for f in line.split(",")] if len(fields) >= 4 and not fields[0].startswith("#"): if fields[2] == "ota": @@ -64,7 +66,7 @@ def otadata_and_app_offsets() -> tuple[int, int]: if fields[2] == "ota_0": app = int(fields[3], 16) if otadata is None or app is None: - raise SystemExit("error: partitions/ota_4mb.csv without otadata/ota_0") + raise SystemExit(f"error: partitions/{csv_name} without otadata/ota_0") return otadata, app @@ -80,7 +82,8 @@ def find_boot_app0() -> Path: # CANOBD2Reader – Provisionierung per USB (erzeugt von make_provisioning_package.py) # # ./flash.sh pruefen sender|display Board finden und MAC prüfen (ändert nichts) -# ./flash.sh sender|display Flash komplett löschen und neu beschreiben +# ./flash.sh sender|display Flash komplett löschen und neu beschreiben (Provisionierung) +# ./flash.sh layout sender|display Partitionstabelle + Firmware schreiben, Zugangsdaten (NVS) bleiben # ./flash.sh aufraeumen Paket (enthält Zugangsdaten) löschen # # Ausgabe zusätzlich in /tmp/canobd2-flash.log @@ -100,7 +103,13 @@ def find_boot_app0() -> Path: echo "esptool: $ESPTOOL" declare -A CHIP=(%(chip)s) USB=(%(usb)s) MAC=(%(mac)s) BAUD=(%(baud)s) BOOT=(%(boot)s) -OTADATA=%(otadata)s; APP=%(app)s; PART=%(part)s +declare -A OTADATA=(%(otadata)s) APP=(%(app)s); PART=%(part)s + +write_images() { # $1 = target: bootloader, partition table, boot selection, firmware + "$ESPTOOL" --chip "${CHIP[$1]}" --port "$PORT" --baud "${BAUD[$1]}" write_flash -z \ + "${BOOT[$1]}" "$1/bootloader.bin" "$PART" "$1/partitions.bin" "${OTADATA[$1]}" boot_app0.bin \ + "${APP[$1]}" "$1/firmware.bin" +} find_port() { # $1 = target; erstes serielles Gerät mit passender VID:PID local dev vid pid @@ -135,13 +144,20 @@ def find_boot_app0() -> Path: echo "==> $T: Flash löschen (alte Firmware, Einstellungen, Logs)" "$ESPTOOL" --chip "${CHIP[$T]}" --port "$PORT" --baud "${BAUD[$T]}" erase_flash echo "==> $T: schreiben" - "$ESPTOOL" --chip "${CHIP[$T]}" --port "$PORT" --baud "${BAUD[$T]}" write_flash -z \ - "${BOOT[$T]}" "$T/bootloader.bin" "$PART" "$T/partitions.bin" "$OTADATA" boot_app0.bin "$APP" "$T/firmware.bin" + write_images "$T" echo "==> $T fertig. Das Gerät startet neu und übernimmt die Zugangsdaten ins NVS." ;; + layout) + # NVS (0x9000) is not touched: credentials stay. The log file system is + # re-created at the new position on first boot (old log is lost). + T=${2:-x}; [[ -n "${CHIP[$T]:-}" ]] || { echo "Aufruf: $0 layout sender|display"; exit 1; } + check_board "$T" + echo "==> $T: neue Partitionstabelle + Firmware schreiben (ohne Löschen, Zugangsdaten bleiben)" + write_images "$T" + echo "==> $T fertig. Erster Start legt das Log-Dateisystem neu an (dauert einige Sekunden)." ;; aufraeumen) read -r -p "Paket $(pwd) mit Zugangsdaten löschen? [j/N] " a; [[ "$a" =~ ^[jJ]$ ]] || exit 0 d=$(pwd); cd / && rm -r -- "${d:?}" && echo "gelöscht: $d" ;; - *) sed -n '2,8p' "$0"; exit 1 ;; + *) sed -n '2,9p' "$0"; exit 1 ;; esac ''' @@ -154,7 +170,7 @@ def main(argv: list[str] | None = None) -> int: args = parser.parse_args(argv) secrets = read_secrets() - otadata, app = otadata_and_app_offsets() + offsets = {t: otadata_and_app_offsets(c["partitions"]) for t, c in TARGETS.items()} if not args.skip_build: subprocess.run([args.pio, "run", "-e", "sender", "-e", "display"], cwd=ROOT, check=True) @@ -179,7 +195,9 @@ def assoc(key): "mac": assoc(lambda t, c: secrets[c["mac"]]), "baud": assoc(lambda t, c: c["baud"]), "boot": assoc(lambda t, c: hex(c["bootloader"])), - "otadata": hex(otadata), "app": hex(app), "part": hex(PARTITIONS_OFFSET), + "otadata": assoc(lambda t, c: hex(offsets[t][0])), + "app": assoc(lambda t, c: hex(offsets[t][1])), + "part": hex(PARTITIONS_OFFSET), } (out / "flash.sh").write_text(script, encoding="utf-8") (out / "flash.sh").chmod(0o700) diff --git a/src/display/DisplayApp.cpp b/src/display/DisplayApp.cpp index 74b24b2..977b632 100644 --- a/src/display/DisplayApp.cpp +++ b/src/display/DisplayApp.cpp @@ -6,6 +6,7 @@ #include #include "BootValidation.h" +#include "SystemHealth.h" #include "DeviceSecrets.h" #include "DiagnosticLog.h" #include "DisplayReceiver.h" @@ -23,12 +24,14 @@ void begin() { DisplayUi::begin(); DiagnosticLog::begin(); Security::begin(false); + SystemHealth::logBootSummary("display"); DiagnosticLog::appendf("[BOOT] Display firmware=%s protocol=%u mac=%s secrets=%s %s", ProjectConfig::FirmwareVersion, ProjectConfig::ProtocolVersion, WiFi.macAddress().c_str(), Security::sourceName(Security::source()), Security::problemText()); // Web first: it sets up the AP on the ESP-NOW channel, then ESP-NOW joins. DisplayWeb::begin(); DisplayReceiver::begin(); + SystemHealth::startWatchdog(); } void tick() { diff --git a/src/display/DisplayWeb.cpp b/src/display/DisplayWeb.cpp index 40ade9e..3dd3701 100644 --- a/src/display/DisplayWeb.cpp +++ b/src/display/DisplayWeb.cpp @@ -45,6 +45,8 @@ body{margin:0 auto;max-width:460px;padding:12px;background:#070b12;color:#f8fafc Firmware-Update (signiert)
Display-Seiten
--
+
Neustart / Absturzbericht
--
+
Diagnose-Log
Log herunterladen
)HTML"; diff --git a/src/sender/SenderApp.cpp b/src/sender/SenderApp.cpp index 77f3f6c..20ad3c8 100644 --- a/src/sender/SenderApp.cpp +++ b/src/sender/SenderApp.cpp @@ -16,6 +16,7 @@ #include "CANHandler.h" #include "CanRouterHub.h" #include "BootValidation.h" +#include "SystemHealth.h" #include "DeviceSecrets.h" #include "SenderLiveData.h" #include "SenderPower.h" @@ -168,6 +169,7 @@ void SenderApp::begin() { Serial.begin(ProjectConfig::Baudrate); DiagnosticLog::begin(); Security::begin(true); + SystemHealth::logBootSummary("sender"); DiagnosticLog::appendf("[BOOT] mac=%s secrets=%s %s", WiFi.macAddress().c_str(), Security::sourceName(Security::source()), Security::problemText()); DiagnosticLog::appendf("[BOOT] Sender firmware=%s protocol=%u target=%s", @@ -222,6 +224,7 @@ void SenderApp::begin() { WebConsoleHandler::log(canDriverReady ? "Sender bereit" : "Sender im Fehler-/OTA-Modus"); SenderLedButton::pulseError(millis()); + SystemHealth::startWatchdog(); } // End region ================================== Setup ================================== diff --git a/src/sender/WebConsoleHandler.cpp b/src/sender/WebConsoleHandler.cpp index 61a1184..acb35fd 100644 --- a/src/sender/WebConsoleHandler.cpp +++ b/src/sender/WebConsoleHandler.cpp @@ -199,7 +199,7 @@ Timeouts: -- · Negative: --
Rohdaten
Noch kein Scan geladen.
-
Diagnose-Log
Persistent: --
Log herunterladen
+
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.
@@ -219,7 +219,7 @@ function yn(v){return v?'aktiv':'aus'}function cls(el,state){el.className='value async function apiGet(url){let r=await fetch(url,{cache:'no-store',credentials:'same-origin'});if(!r.ok)throw new Error(url+' HTTP '+r.status);return r} async function apiPost(url){let r=await fetch(url,{method:'POST',credentials:'same-origin'});if(!r.ok)throw new Error(url+' HTTP '+r.status);return r} function bind(id,fn){let el=$(id);if(el)el.onclick=fn} -async function refresh(){try{let s=await fetch('/status',{cache:'no-store'}).then(r=>r.json());$('ip').textContent=s.ip+' · '+Math.floor(s.uptime/1000)+'s';$('fw').textContent=s.firmware;$('target').textContent=s.target;$('proto').textContent=s.protocol;$('build').textContent=s.buildTime;$('otastatus').textContent=s.otaStatus;$('freeota').textContent=bytes(s.freeSketchSpace);$('sketch').textContent=bytes(s.sketchSize);$('flash').textContent=bytes(s.flashSize);$('diaglog').textContent=(s.diagnosticLogMounted?'bereit':'nicht gemountet')+' · '+bytes(s.diagnosticLogSize)+' / '+bytes(s.diagnosticLogMaxSize);$('run').textContent=s.started?'läuft':'gestoppt';$('run').className='pill '+(s.started?(s.securityReady?'ok':'warn'):'warn');$('can').textContent=s.canState;cls($('can'),s.canActive);$('obd').textContent=s.obdState||yn(s.obdActive);cls($('obd'),s.obdActive);$('espnow').textContent=s.espNowState;cls($('espnow'),s.espNowState==='READY');$('ledstate').textContent=s.ledState||'--';$('ledstate').className='value '+((s.ledState==='CanError'||s.ledState==='EspNowError')?'errText':(s.ledState==='VehicleOff'||s.ledState==='ObdTimeout'?'warnText':'okText'));$('ledtest').textContent=s.ledTestActive?'aktiv':'inaktiv';$('vehicleoff').textContent=s.vehicleOff?'ja':'nein';$('ledchange').textContent=s.ledLastStateChangeAt?((Math.max(0,s.uptime-s.ledLastStateChangeAt)/1000).toFixed(1)+'s'):'--';$('vehiclestate').textContent=s.vehicleState||'--';$('vehiclestate').className='value '+((s.vehicleState==='Parked'||s.vehicleState==='DisplaySleep')?'warnText':(s.vehicleState==='StartStop'?'warnText':'okText'));$('activityscore').textContent=s.activityScore;$('powercmd').textContent=s.powerCommand||'None';$('startstop').textContent=s.startStopDetected?'ja':'nein';$('parked').textContent=s.parkedDetected?'ja':'nein';$('sleeptimer').textContent=s.displaySleepDueAtMs?((Math.max(0,s.displaySleepDueAtMs-s.uptime)/1000).toFixed(0)+'s'):'--';$('heartbeat').textContent=s.heartbeats;$('bat').textContent=s.battery.toFixed(2)+' V';$('seq').textContent=s.seq;$('tel').textContent=s.lastTelemetry;$('pid').textContent=s.pidSupport?'bereit':'unbekannt';cls($('pid'),s.pidSupport);$('canage').textContent=(s.lastCanAge/1000).toFixed(1)+'s';$('dtc').textContent=s.lastDtc||'--';$('vin').textContent=s.lastVin||'--';$('obdReq').textContent=s.obdRequestCount;$('obdOk').textContent=s.obdValidResponseCount;$('obdTimeouts').textContent=s.obdTimeoutCount;$('obdNeg').textContent=s.obdNegativeResponseCount;$('obdSendFail').textContent=s.obdSendFailureCount;$('obdStreak').textContent=s.obdTimeoutStreak;$('obdReqId').textContent=s.obdRequestCanId;$('obdFallback').textContent=s.obdPhysicalFallbackActive?'0x7E0 aktiv':'0x7DF';$('lastObdReq').textContent=s.lastObdRequest||'--';$('lastEcuResp').textContent=s.lastEcuResponse||'--';$('lastNrc').textContent=s.lastNegativeResponse||'--';$('pidMask1').textContent=s.supportedPidMask01_20;$('pidMask2').textContent=s.supportedPidMask21_40;$('pidMask3').textContent=s.supportedPidMask41_60;$('udsAvail').textContent=s.udsAvailable?'ja':'nein';$('udsReq').textContent=s.udsRequestCount;$('udsOk').textContent=s.udsPositiveResponseCount;$('udsTimeouts').textContent=s.udsTimeoutCount;$('udsNeg').textContent=s.udsNegativeResponseCount;$('udsSendFail').textContent=s.udsSendFailureCount;$('lastUdsReq').textContent=s.lastUdsRequest||'--';$('lastUdsResp').textContent=s.lastUdsResponse||'--';$('udsDid').textContent=s.lastUdsDid||'--';$('udsDtc').textContent=s.lastUdsDtc||'--';$('udsNrc').textContent=s.lastUdsNegativeResponse||'--';$('err').textContent=s.securityWarning||s.lastSendError||s.lastError||'OK';}catch(e){$('run').textContent='offline';$('run').className='pill err'}} +async function refresh(){try{let s=await fetch('/status',{cache:'no-store'}).then(r=>r.json());$('ip').textContent=s.ip+' · '+Math.floor(s.uptime/1000)+'s';$('fw').textContent=s.firmware;$('target').textContent=s.target;$('proto').textContent=s.protocol;$('build').textContent=s.buildTime;$('otastatus').textContent=s.otaStatus;$('freeota').textContent=bytes(s.freeSketchSpace);$('sketch').textContent=bytes(s.sketchSize);$('flash').textContent=bytes(s.flashSize);$('resetReason').textContent=s.resetReason+(s.coreDumpPresent?' - Absturzbericht vorhanden':'');$('crashDl').style.display=s.coreDumpPresent?'block':'none';$('diaglog').textContent=(s.diagnosticLogMounted?'bereit':'nicht gemountet')+' · '+bytes(s.diagnosticLogSize)+' / '+bytes(s.diagnosticLogMaxSize);$('run').textContent=s.started?'läuft':'gestoppt';$('run').className='pill '+(s.started?(s.securityReady?'ok':'warn'):'warn');$('can').textContent=s.canState;cls($('can'),s.canActive);$('obd').textContent=s.obdState||yn(s.obdActive);cls($('obd'),s.obdActive);$('espnow').textContent=s.espNowState;cls($('espnow'),s.espNowState==='READY');$('ledstate').textContent=s.ledState||'--';$('ledstate').className='value '+((s.ledState==='CanError'||s.ledState==='EspNowError')?'errText':(s.ledState==='VehicleOff'||s.ledState==='ObdTimeout'?'warnText':'okText'));$('ledtest').textContent=s.ledTestActive?'aktiv':'inaktiv';$('vehicleoff').textContent=s.vehicleOff?'ja':'nein';$('ledchange').textContent=s.ledLastStateChangeAt?((Math.max(0,s.uptime-s.ledLastStateChangeAt)/1000).toFixed(1)+'s'):'--';$('vehiclestate').textContent=s.vehicleState||'--';$('vehiclestate').className='value '+((s.vehicleState==='Parked'||s.vehicleState==='DisplaySleep')?'warnText':(s.vehicleState==='StartStop'?'warnText':'okText'));$('activityscore').textContent=s.activityScore;$('powercmd').textContent=s.powerCommand||'None';$('startstop').textContent=s.startStopDetected?'ja':'nein';$('parked').textContent=s.parkedDetected?'ja':'nein';$('sleeptimer').textContent=s.displaySleepDueAtMs?((Math.max(0,s.displaySleepDueAtMs-s.uptime)/1000).toFixed(0)+'s'):'--';$('heartbeat').textContent=s.heartbeats;$('bat').textContent=s.battery.toFixed(2)+' V';$('seq').textContent=s.seq;$('tel').textContent=s.lastTelemetry;$('pid').textContent=s.pidSupport?'bereit':'unbekannt';cls($('pid'),s.pidSupport);$('canage').textContent=(s.lastCanAge/1000).toFixed(1)+'s';$('dtc').textContent=s.lastDtc||'--';$('vin').textContent=s.lastVin||'--';$('obdReq').textContent=s.obdRequestCount;$('obdOk').textContent=s.obdValidResponseCount;$('obdTimeouts').textContent=s.obdTimeoutCount;$('obdNeg').textContent=s.obdNegativeResponseCount;$('obdSendFail').textContent=s.obdSendFailureCount;$('obdStreak').textContent=s.obdTimeoutStreak;$('obdReqId').textContent=s.obdRequestCanId;$('obdFallback').textContent=s.obdPhysicalFallbackActive?'0x7E0 aktiv':'0x7DF';$('lastObdReq').textContent=s.lastObdRequest||'--';$('lastEcuResp').textContent=s.lastEcuResponse||'--';$('lastNrc').textContent=s.lastNegativeResponse||'--';$('pidMask1').textContent=s.supportedPidMask01_20;$('pidMask2').textContent=s.supportedPidMask21_40;$('pidMask3').textContent=s.supportedPidMask41_60;$('udsAvail').textContent=s.udsAvailable?'ja':'nein';$('udsReq').textContent=s.udsRequestCount;$('udsOk').textContent=s.udsPositiveResponseCount;$('udsTimeouts').textContent=s.udsTimeoutCount;$('udsNeg').textContent=s.udsNegativeResponseCount;$('udsSendFail').textContent=s.udsSendFailureCount;$('lastUdsReq').textContent=s.lastUdsRequest||'--';$('lastUdsResp').textContent=s.lastUdsResponse||'--';$('udsDid').textContent=s.lastUdsDid||'--';$('udsDtc').textContent=s.lastUdsDtc||'--';$('udsNrc').textContent=s.lastUdsNegativeResponse||'--';$('err').textContent=s.securityWarning||s.lastSendError||s.lastError||'OK';}catch(e){$('run').textContent='offline';$('run').className='pill err'}} async function refreshLog(){try{$('logs').textContent=await fetch('/log',{cache:'no-store'}).then(r=>r.text())}catch(e){}} async function loadPersistentLog(){try{$('logs').textContent=await fetch('/log/file',{cache:'no-store'}).then(r=>r.text())}catch(e){}} async function refreshSimulation(){try{let s=await fetch('/api/simulation',{cache:'no-store'}).then(r=>r.json());$('sim').textContent=s.simulation?'aktiv':'inaktiv';$('sim').className='value '+(s.simulation?'okText':'warnText');$('scenario').textContent=s.scenario||'--';$('scenarioSelect').value=s.scenario||'NormalSingleFrame'}catch(e){}} From a3f7a9b2c9079a8154ae8c9bc3aad235439ae955 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:39:17 +0100 Subject: [PATCH 2/4] OBD: accept Mode 01/09 answers from the engine ECU only; display and log fixes Findings from the first vehicle test (VW Tiguan): - Functional OBD requests are answered by several ECUs; the first answer won. Supported-PID masks therefore flipped every refresh (oil, intake, throttle shown, then 'n.v.') and values could come from the wrong ECU. Mode 01/09 now only accept the engine ECU (0x7E8). - Low cards: 8 px header 'Label unit' so it no longer overlaps the value. - 'Warte auf Sender' hint cleared on the first packet. - Voltage limits for VW energy management (warn 15.5 V, critical 16 V). - scripts/read_device_logs.py: read log file system and crash report over USB (local or via SSH), unpack with mkspiffs. Co-Authored-By: Claude Opus 5.5 --- docs/DEVELOPMENT.md | 14 ++++ include/config/DisplayConfig.h | 5 +- lib/isotp/IsoTpHandler.cpp | 1 + lib/isotp/IsoTpHandler.h | 5 ++ lib/isotp/IsoTpTypes.h | 2 + scripts/read_device_logs.py | 117 ++++++++++++++++++++++++++++++++ src/display/DisplayReceiver.cpp | 1 + src/display/DisplayUi.cpp | 21 ++++-- src/sender/OBDHandler.cpp | 9 +++ 9 files changed, 169 insertions(+), 6 deletions(-) create mode 100644 scripts/read_device_logs.py diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 99794cb..65bea79 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -41,6 +41,20 @@ python scripts/ota_upload.py --host 192.168.4.1 output/sender.bin python scripts/ota_upload.py --sign-key ~/canobd2-signing.pem .pio/build/sender/firmware.bin ``` +## Logs per USB auslesen + +Ohne WLAN, direkt über USB (nur lesend). Das Board kann am selben Rechner oder +an einem per SSH erreichbaren Linux-Rechner hängen: + +```bash +python scripts/read_device_logs.py sender --remote kalipi --out ~/canobd2-logs +python scripts/read_device_logs.py display --remote kalipi --out ~/canobd2-logs +``` + +Geräte mit dem alten Layout (bis V2.1.0-beta.2): zusätzlich `--layout legacy`. +**Vor** einem Layout-Wechsel auslesen, sonst ist das alte Log weg. Die Logs +können die Fahrgestellnummer enthalten, also nicht ins Repository übernehmen. + ## Abstürze analysieren Jeder Start schreibt den Grund ins Diagnose-Log (`[BOOT] … reset=PANIC|TASK_WDT|…`). diff --git a/include/config/DisplayConfig.h b/include/config/DisplayConfig.h index fc12a79..04d31f7 100644 --- a/include/config/DisplayConfig.h +++ b/include/config/DisplayConfig.h @@ -40,8 +40,9 @@ constexpr float OilWarnC = 115.0f; constexpr float OilCriticalC = 125.0f; constexpr float VoltageWarnLow = 11.8f; constexpr float VoltageCriticalLow = 11.2f; -constexpr float VoltageWarnHigh = 14.8f; -constexpr float VoltageCriticalHigh = 15.2f; +// VW energy management charges up to ~15 V when cold; above that is suspicious. +constexpr float VoltageWarnHigh = 15.5f; +constexpr float VoltageCriticalHigh = 16.0f; constexpr uint16_t RpmWarn = 4200; constexpr uint16_t RpmCritical = 5000; constexpr uint16_t RpmMax = 6000; diff --git a/lib/isotp/IsoTpHandler.cpp b/lib/isotp/IsoTpHandler.cpp index 47f7b8c..a31184c 100644 --- a/lib/isotp/IsoTpHandler.cpp +++ b/lib/isotp/IsoTpHandler.cpp @@ -153,6 +153,7 @@ bool IsoTpHandler::receiveResponse(uint8_t expectedMode, uint8_t expectedPid, Pa void IsoTpHandler::onCanFrame(const CanRouting::CanFrame& frame) { if (frame.id < FirstResponseId || frame.id > LastResponseId) return; + if (responseFilter_ != 0 && frame.id != responseFilter_) return; if (frame.length == 0 || frame.length > 8) return; if (routedCount_ >= RoutedFrameQueueSize) { lastStatus_ = Status::BufferOverflow; diff --git a/lib/isotp/IsoTpHandler.h b/lib/isotp/IsoTpHandler.h index 4cf310d..a88b7c4 100644 --- a/lib/isotp/IsoTpHandler.h +++ b/lib/isotp/IsoTpHandler.h @@ -18,6 +18,10 @@ class IsoTpHandler : public CanRouting::CanFrameListener { bool receiveResponse(uint8_t expectedMode, uint8_t expectedPid, Payload& out, uint32_t timeoutMs); void setRequestId(uint32_t requestId) { requestId_ = requestId; } uint32_t requestId() const { return requestId_; } + // Accept only frames from this response id (0 = any ECU). Functional + // requests (0x7DF) are answered by several ECUs; without a filter the + // first answer wins, which mixed up e.g. gearbox and engine data. + void setResponseFilter(uint32_t responseId) { responseFilter_ = responseId; } bool lastResponseWasNegative() const { return lastResponseWasNegative_; } uint8_t lastNegativeService() const { return lastNegativeService_; } uint8_t lastNegativeCode() const { return lastNegativeCode_; } @@ -41,6 +45,7 @@ class IsoTpHandler : public CanRouting::CanFrameListener { std::size_t routedWriteIndex_ = 0; std::size_t routedCount_ = 0; uint32_t requestId_ = FunctionalRequestId; + uint32_t responseFilter_ = 0; uint32_t lastResponseId_ = 0; Status lastStatus_ = Status::Idle; uint8_t lastNegativeService_ = 0; diff --git a/lib/isotp/IsoTpTypes.h b/lib/isotp/IsoTpTypes.h index bc7ddd1..1ca01dd 100644 --- a/lib/isotp/IsoTpTypes.h +++ b/lib/isotp/IsoTpTypes.h @@ -10,6 +10,8 @@ namespace IsoTp { constexpr std::size_t MaxPayload = ProjectConfig::MaxIsoTpPayload; constexpr uint32_t FunctionalRequestId = 0x7DF; constexpr uint32_t PhysicalRequestId = 0x7E0; +// ISO 15765-4: 0x7E8 is the engine control module (ECU #1). +constexpr uint32_t EngineResponseId = 0x7E8; constexpr uint32_t FirstResponseId = 0x7E8; constexpr uint32_t LastResponseId = 0x7EF; diff --git a/scripts/read_device_logs.py b/scripts/read_device_logs.py new file mode 100644 index 0000000..670592b --- /dev/null +++ b/scripts/read_device_logs.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Read diagnostic logs (and crash reports) from a device over USB. + +The diagnostic log lives in the SPIFFS partition, the crash report in the +"coredump" partition. Both are read with esptool (read only, nothing on the +device changes) and the log files are unpacked with mkspiffs. + +Usage (board connected to this machine): + python scripts/read_device_logs.py sender --out logs/ +Board connected to another Linux host reachable by SSH (e.g. the kalipi): + python scripts/read_device_logs.py sender --remote kalipi --out logs/ +Devices still on the old layout (before V2.1.0-beta.3): + python scripts/read_device_logs.py display --layout legacy --remote kalipi --out logs/ + +Logs may contain the VIN - keep them out of the repository. +""" + +from __future__ import annotations + +import argparse +import os +import shlex +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +TARGETS = { + "sender": {"chip": "esp32", "usb": "1a86:7523", "csv": "sender_4mb.csv"}, + "display": {"chip": "esp32s3", "usb": "303a:1001", "csv": "display_16mb.csv"}, +} +# Layout of V2.0 - V2.1.0-beta.2 (partitions/ota_4mb.csv, both devices). +LEGACY = {"spiffs": (0x3B0000, 0x50000)} + +REMOTE_SCRIPT = r''' +set -euo pipefail +E=""; for c in "$HOME/.venv-esptool/bin/esptool.py" "$(command -v esptool.py || true)" "$(command -v esptool || true)"; do + [[ -n "$c" && -x "$c" ]] && { E=$c; break; }; done +[[ -n "$E" ]] || { echo "esptool fehlt" >&2; exit 1; } +P=""; for d in /dev/ttyUSB* /dev/ttyACM*; do [[ -e "$d" ]] || continue + v=$(udevadm info -q property -n "$d" | sed -n 's/^ID_VENDOR_ID=//p'); p=$(udevadm info -q property -n "$d" | sed -n 's/^ID_MODEL_ID=//p') + [[ "${v,,}:${p,,}" == "$USBID" ]] && { P=$d; break; }; done +[[ -n "$P" ]] || { echo "Board $USBID nicht gefunden" >&2; exit 1; } +"$E" --chip "$CHIP" --port "$P" --baud 460800 read_flash "$OFFSET" "$SIZE" "$OUT" >&2 +''' + + +def partition(csv_name: str, subtype: str) -> tuple[int, int]: + for line in (ROOT / "partitions" / csv_name).read_text().splitlines(): + fields = [f.strip() for f in line.split(",")] + if len(fields) >= 5 and not fields[0].startswith("#") and fields[2] == subtype: + return int(fields[3], 16), int(fields[4], 16) + raise SystemExit(f"error: no '{subtype}' partition in partitions/{csv_name}") + + +def read_region(target: str, offset: int, size: int, dest: Path, remote: str | None) -> None: + env = {"USBID": TARGETS[target]["usb"], "CHIP": TARGETS[target]["chip"], + "OFFSET": hex(offset), "SIZE": hex(size)} + if remote: + remote_file = f"/tmp/canobd2-read-{os.getpid()}.bin" + assignments = " ".join(f"{k}={shlex.quote(v)}" for k, v in {**env, "OUT": remote_file}.items()) + subprocess.run(["ssh", remote, f"{assignments} bash -s"], input=REMOTE_SCRIPT, text=True, check=True) + try: + subprocess.run(["scp", "-q", f"{remote}:{remote_file}", str(dest)], check=True) + finally: + subprocess.run(["ssh", remote, f"rm -f {shlex.quote(remote_file)}"], check=False) + else: + subprocess.run(["bash", "-s"], input=REMOTE_SCRIPT, text=True, check=True, + env={**os.environ, **env, "OUT": str(dest)}) + + +def find_mkspiffs() -> Path: + core = Path(os.environ.get("PLATFORMIO_CORE_DIR", Path.home() / ".platformio")) + tool = core / "packages" / "tool-mkspiffs" / "mkspiffs_espressif32_arduino" + if not tool.exists(): + raise SystemExit(f"error: {tool} missing - pio pkg install -g -t platformio/tool-mkspiffs") + return tool + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("target", choices=TARGETS) + parser.add_argument("--out", type=Path, required=True) + parser.add_argument("--remote", help="SSH host the board is connected to") + parser.add_argument("--layout", choices=["current", "legacy"], default="current") + args = parser.parse_args(argv) + + out = args.out.resolve() + out.mkdir(parents=True, exist_ok=True, mode=0o700) + if args.layout == "legacy": + spiffs = LEGACY["spiffs"] + coredump = None + else: + spiffs = partition(TARGETS[args.target]["csv"], "spiffs") + coredump = partition(TARGETS[args.target]["csv"], "coredump") + + image = out / f"{args.target}_spiffs.bin" + read_region(args.target, *spiffs, image, args.remote) + files = out / f"{args.target}_log" + files.mkdir(exist_ok=True) + subprocess.run([str(find_mkspiffs()), "-u", str(files), "-b", "4096", "-p", "256", "-s", str(spiffs[1]), + str(image)], check=True, stdout=subprocess.DEVNULL) + print(f"Logdateien: {files}") + for path in sorted(files.iterdir()): + print(f" {path.name}: {path.stat().st_size} Bytes") + + if coredump: + dump = out / f"{args.target}_coredump_partition.bin" + read_region(args.target, *coredump, dump, args.remote) + data = dump.read_bytes() + empty = all(b == 0xFF for b in data[:64]) + print(f"Coredump-Bereich: {'leer' if empty else 'enthält einen Absturzbericht'} ({dump})") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/src/display/DisplayReceiver.cpp b/src/display/DisplayReceiver.cpp index 690682e..8bc0883 100644 --- a/src/display/DisplayReceiver.cpp +++ b/src/display/DisplayReceiver.cpp @@ -101,6 +101,7 @@ void processPacket(const QueuedPacket& queued) { runtime().lastSequence = packet.sequence; runtime().receivedPackets++; runtime().lastReceivedAt = millis(); + if (runtime().lastError == "Warte auf Sender") runtime().lastError = ""; if (packet.type == static_cast(Telemetry::PacketType::LiveSnapshot)) { LiveData::Snapshot snapshot; diff --git a/src/display/DisplayUi.cpp b/src/display/DisplayUi.cpp index e6f6cd6..84749e5 100644 --- a/src/display/DisplayUi.cpp +++ b/src/display/DisplayUi.cpp @@ -178,6 +178,23 @@ void metricCard(int x, int y, int w, int h, Metric metric, bool big, const Value const LiveData::MetricInfo& info = LiveData::info(metric); panel(x, y, w, h, view.state == ValueState::Fresh ? color : DisplayConfig::Panel); + const String text = formatValue(metric, view); + // Font 7 (7-segment, 48 px) only has digits, '.', '-' and ':'. + const bool segmentFont = big && view.state != ValueState::Unsupported; + const uint8_t font = segmentFont ? 7 : 4; + + if (h < 46) { + // Low card (bottom rows): one small header line "Label unit" in font 1 + // (8 px) and the value below - a 16 px label would overlap the value. + String head = info.label; + if (info.unit[0] != '\0') head += String(" ") + info.unit; + label(x + 6, y + 4, fitText(head, w - 12, 1).c_str(), 1); + frame.setTextDatum(BR_DATUM); + frame.setTextColor(color); + frame.drawString(fitText(text, w - 12, font), x + w - 6, y + h - 5, font); + return; + } + const bool narrow = w < 120; label(x + 8, y + 4, fitText(info.label, w - 16, 2).c_str()); frame.setTextColor(DisplayConfig::Muted); @@ -190,10 +207,6 @@ void metricCard(int x, int y, int w, int h, Metric metric, bool big, const Value frame.drawString(info.unit, x + w - 8, y + 4, 2); } - const String text = formatValue(metric, view); - // Font 7 (7-segment, 48 px) only has digits, '.', '-' and ':'. - const bool segmentFont = big && view.state != ValueState::Unsupported; - const uint8_t font = segmentFont ? 7 : 4; frame.setTextDatum(BR_DATUM); frame.setTextColor(color); const int unitSpace = narrow ? frame.textWidth(info.unit, 2) + 4 : 0; diff --git a/src/sender/OBDHandler.cpp b/src/sender/OBDHandler.cpp index 1069efe..bb63222 100644 --- a/src/sender/OBDHandler.cpp +++ b/src/sender/OBDHandler.cpp @@ -38,7 +38,15 @@ void updateBoostPressureIfReady() { } } +// Live data (01) and vehicle info (09) must come from the engine ECU only; +// other ECUs answer functional requests too (different PID support, own +// temperatures). DTCs (03) are accepted from any ECU. +static void selectResponseFilter(uint8_t mode) { + isoTp.setResponseFilter(mode == read_LiveData || mode == read_VehicleInfo ? IsoTp::EngineResponseId : 0); +} + bool OBD2Handler::sendRequest(uint8_t mode, uint8_t pid) { + selectResponseFilter(mode); Obd::Diagnostics::recordRequest(mode, pid, isoTp.requestId()); const bool ok = isoTp.sendRequest(mode, pid); if (!ok) { @@ -48,6 +56,7 @@ bool OBD2Handler::sendRequest(uint8_t mode, uint8_t pid) { } bool OBD2Handler::sendRequestPayload(uint8_t mode, const uint8_t* payload, size_t payloadLength) { + selectResponseFilter(mode); Obd::Diagnostics::recordRequest(mode, payload, payloadLength, isoTp.requestId()); const bool ok = isoTp.sendRequest(mode, payload, payloadLength); if (!ok) { From a6e03a13ad918dd56f583fa28a974f46bfdcadc9 Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sun, 1 Nov 2026 14:43:27 +0100 Subject: [PATCH 3/4] Test: voltage limits for VW energy management Co-Authored-By: Claude Opus 5.5 --- test/test_display_severity/test_display_severity.cpp | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/test/test_display_severity/test_display_severity.cpp b/test/test_display_severity/test_display_severity.cpp index 05a2b11..a73817f 100644 --- a/test/test_display_severity/test_display_severity.cpp +++ b/test/test_display_severity/test_display_severity.cpp @@ -31,10 +31,13 @@ void test_voltage_severity() { static_cast(DisplayLogic::severityForMetric("BatteryVoltage", 11.7f, true))); TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Critical), static_cast(DisplayLogic::severityForMetric("BatteryVoltage", 11.0f, true))); + // VW energy management charges up to ~15 V when cold: still OK. + TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Ok), + static_cast(DisplayLogic::severityForMetric("BatteryVoltage", 15.3f, true))); TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Warning), - static_cast(DisplayLogic::severityForMetric("BatteryVoltage", 15.0f, true))); + static_cast(DisplayLogic::severityForMetric("BatteryVoltage", 15.6f, true))); TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Critical), - static_cast(DisplayLogic::severityForMetric("BatteryVoltage", 15.3f, true))); + static_cast(DisplayLogic::severityForMetric("BatteryVoltage", 16.2f, true))); } void test_rpm_severity() { From 2f82ea20624b471346ee13049582cc1fecf6837b Mon Sep 17 00:00:00 2001 From: SpecterAoD <77644070+SpecterAoD@users.noreply.github.com> Date: Sun, 1 Nov 2026 17:14:59 +0100 Subject: [PATCH 4/4] Fixes from the second vehicle test (log analysis) - Polling was ~5 requests/s (fast values every ~1.2 s, slow ~9 s): every ISO-TP/OBD trace line was written to the flash log. Trace now goes to the flash log only with PersistTraceToDiagnosticLog; serial debug off. - Display never slept: the Sleep command existed for one 10 ms update and was practically never sent; and the last RPM before ignition-off kept the car 'running'. Command is sent immediately, the display follows the DisplaySleep state, RPM/speed/load only count while OBD answers are fresh (regression test). - No CAN requests while the engine ECU is silent unless the board voltage shows a running alternator (>= 13 V): requests wake the VW gateway. - Fuel rate from MAF (PID 0x5E reported ~30 % of the real value); instant consumption cleared below 5 km/h; MAF polled fast, coolant/ECU voltage slow. - Thresholds for VW: coolant warn 110 / critical 118 C, oil 130 / 140 C. - Voltage divider calibrated against PID 0x42 (4.81 -> 4.62). - Boot log MAC read from eFuse; read_device_logs.py: 115200 baud for CH340. Co-Authored-By: Claude Opus 5.5 --- docs/ARCHITECTURE.md | 7 ++++-- docs/HARDWARE.md | 11 +++++++-- include/Logger.h | 24 ++++++++++++------- include/config/DisplayConfig.h | 9 +++---- include/config/LoggingConfig.h | 5 +++- include/config/ObdConfig.h | 22 ++++++++++------- include/config/PowerConfig.h | 3 +++ include/config/SenderConfig.h | 3 ++- lib/diagnostics/SystemHealth.cpp | 13 ++++++++++ lib/diagnostics/SystemHealth.h | 3 +++ lib/isotp/IsoTpHandler.cpp | 2 +- lib/power/ActivityMonitor.cpp | 12 ++++++---- lib/simulation/ObdSimulation.cpp | 8 +++---- lib/telemetry/LiveData.cpp | 6 +++++ lib/telemetry/LiveData.h | 2 ++ scripts/read_device_logs.py | 9 +++---- src/display/DisplayApp.cpp | 2 +- src/display/DisplayReceiver.cpp | 4 ++++ src/sender/OBDHandler.cpp | 21 +++++++++++++--- src/sender/SenderApp.cpp | 17 ++++++++++--- src/sender/SenderLiveData.cpp | 4 ++++ src/sender/SenderLiveData.h | 1 + src/sender/SenderPower.cpp | 3 +++ .../test_activity_monitor.cpp | 24 +++++++++++++++++++ .../test_display_severity.cpp | 12 +++++----- 25 files changed, 175 insertions(+), 52 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6a107e0..a36f454 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -22,8 +22,11 @@ Gemeinsamer Code liegt in `lib/` und wird nativ getestet (`env:native`). ## Datenfluss Livewerte 1. `Obd::PidPollPlanner` wählt pro Durchlauf den PID, der relativ zu seinem - Sollintervall am stärksten überfällig ist (schnelle Werte 200 ms, langsame - 2 s). Nicht unterstützte PIDs (laut ECU-Maske) werden übersprungen. + Sollintervall am stärksten überfällig ist (schnell 200 ms: Drehzahl, Tempo, + Last, Luftmasse; langsam 2 s: Temperaturen, Spannung, Tank …). Nicht + unterstützte PIDs (laut Maske des Motorsteuergeräts 0x7E8) werden übersprungen. + Antworten anderer Steuergeräte (z. B. Getriebe 0x7E9) werden für Mode 01/09 verworfen. + Der Verbrauch wird aus der Luftmasse berechnet (PID 0x5E ist bei VW unzuverlässig). 2. `OBD2Handler` dekodiert die Antwort und schreibt sie in die `LiveData::LiveValueTable` (`SenderLiveData`). Abgeleitete Werte (Ladedruck, Verbrauch) und die Bordspannung landen in derselben Tabelle. diff --git a/docs/HARDWARE.md b/docs/HARDWARE.md index b9821e8..0e4bb90 100644 --- a/docs/HARDWARE.md +++ b/docs/HARDWARE.md @@ -7,7 +7,7 @@ | CAN TX / RX (TWAI) | 5 / 4 | | LED grün / Fehler | 26 / 27 | | Taster (LED-Test) | 25 | -| Spannungsteiler Bordnetz | 32 (Faktor 4,81) | +| Spannungsteiler Bordnetz | 32 (Faktor 4,62, abgeglichen mit PID 0x42) | Partitionslayout `partitions/sender_4mb.csv`: 2 × 1,81 MB Firmware, 64 KB Absturzbericht, 256 KB Log. @@ -56,7 +56,14 @@ VW-MQB-Evo-Fahrzeuge halten Steuergeräte nach Zündung-aus minutenlang wach und nutzen Start-Stopp intensiv. Der Power-Manager (`lib/power/ActivityMonitor`) bewertet deshalb Drehzahl, Tempo, Last, Drosselklappe, Spannung und Busaktivität. Ohne CAN-/OBD-Aktivität gilt das Fahrzeug nach 5 min als geparkt; 10 min danach schickt er dem Display -`Sleep`, beim Aufwachen `Wakeup`. +`Sleep`, beim Aufwachen `Wakeup`. Das Display folgt dem jede Sekunde gesendeten +Zustand (`DisplaySleep`), ein verlorenes Paket hält es also nicht wach. + +**Fahrzeug schlafen lassen:** Antwortet das Motorsteuergerät nicht (Zündung aus), +sendet der Sender nichts mehr auf den Diagnose-CAN. Anfragen würden das +VW-Gateway wecken und das Bordnetz wach halten. Die Abfrage startet erst wieder, +wenn die Bordspannung ≥ 13,0 V zeigt (Lichtmaschine lädt, Motor läuft). Mit +Zündung an, aber Motor aus, bleiben die Werte deshalb leer. ## Inbetriebnahme-Check diff --git a/include/Logger.h b/include/Logger.h index 39744f4..b873ba1 100644 --- a/include/Logger.h +++ b/include/Logger.h @@ -16,6 +16,14 @@ namespace Logger { if (sink) sink(msg); } + // Per-frame/per-request trace (debug, ISO-TP, OBD values). Writing every + // line to the flash log slowed polling down to ~5 requests/s in the + // vehicle; it only goes to the sink (web console + flash log) when + // explicitly enabled for a debugging session. + inline void emitTrace(const char* msg) { + if (LoggingConfig::PersistTraceToDiagnosticLog && sink) sink(msg); + } + // ======== Initialisierung ======== inline void initDebug() { if (LoggingConfig::SerialEnabled) { @@ -37,7 +45,7 @@ namespace Logger { // ======== Allgemeines Debug ======== inline void debug(const char* msg) { - emit(msg); + emitTrace(msg); if (LoggingConfig::GeneralDebugEnabled && LoggingConfig::SerialEnabled) { Serial.print("[DEBUG] "); Serial.println(msg); @@ -55,7 +63,7 @@ namespace Logger { Serial.print("[DEBUG] "); Serial.println(buf); - emit(buf); + emitTrace(buf); } template @@ -72,7 +80,7 @@ namespace Logger { Serial.println(); char buf[128]; snprintf(buf, sizeof(buf), "%s: %s%s", label, String(value).c_str(), unit && unit[0] ? unit : ""); - emit(buf); + emitTrace(buf); } } @@ -110,7 +118,7 @@ namespace Logger { } inline void can(const char* msg) { - emit(msg); + emitTrace(msg); if (LoggingConfig::CanDebugEnabled && LoggingConfig::SerialEnabled) { Serial.print("[CAN] "); Serial.println(msg); @@ -125,7 +133,7 @@ namespace Logger { for (int i = 0; i < message.data_length_code && used > 0 && used < static_cast(sizeof(buf)); i++) { used += snprintf(buf + used, sizeof(buf) - used, " %02X", message.data[i]); } - emit(buf); + emitTrace(buf); if (LoggingConfig::CanDebugEnabled && LoggingConfig::SerialEnabled) { Serial.print("[CAN] ID=0x"); @@ -144,7 +152,7 @@ namespace Logger { // ======== OBD2 Debug ======== inline void obd(const char* msg) { - emit(msg); + emitTrace(msg); if (LoggingConfig::Obd2DebugEnabled && LoggingConfig::SerialEnabled) { Serial.print("[OBD2] "); Serial.println(msg); @@ -157,7 +165,7 @@ namespace Logger { for (uint8_t i = 0; i < len && used > 0 && used < static_cast(sizeof(buf)); i++) { used += snprintf(buf + used, sizeof(buf) - used, " %02X", data[i]); } - emit(buf); + emitTrace(buf); if (LoggingConfig::Obd2DebugEnabled && LoggingConfig::SerialEnabled) { Serial.print("[OBD2] PID 0x"); @@ -180,7 +188,7 @@ namespace Logger { String(value).c_str(), unit && unit[0] ? " " : "", unit && unit[0] ? unit : ""); - emit(buf); + emitTrace(buf); if (LoggingConfig::Obd2DebugEnabled && LoggingConfig::SerialEnabled) { Serial.print("[OBD2] "); diff --git a/include/config/DisplayConfig.h b/include/config/DisplayConfig.h index 04d31f7..5693a97 100644 --- a/include/config/DisplayConfig.h +++ b/include/config/DisplayConfig.h @@ -34,10 +34,11 @@ constexpr uint32_t ButtonDebounceMs = 30; constexpr std::size_t TelemetryQueueLength = 16; constexpr std::size_t TelemetryValueCapacity = 64; -constexpr float CoolantWarnC = 95.0f; -constexpr float CoolantCriticalC = 105.0f; -constexpr float OilWarnC = 115.0f; -constexpr float OilCriticalC = 125.0f; +// VW engines run 90-105 C coolant (eco mode up to ~110) and oil up to ~120 C. +constexpr float CoolantWarnC = 110.0f; +constexpr float CoolantCriticalC = 118.0f; +constexpr float OilWarnC = 130.0f; +constexpr float OilCriticalC = 140.0f; constexpr float VoltageWarnLow = 11.8f; constexpr float VoltageCriticalLow = 11.2f; // VW energy management charges up to ~15 V when cold; above that is suspicious. diff --git a/include/config/LoggingConfig.h b/include/config/LoggingConfig.h index 456034a..fd2e2a8 100644 --- a/include/config/LoggingConfig.h +++ b/include/config/LoggingConfig.h @@ -6,7 +6,8 @@ namespace LoggingConfig { constexpr bool SerialEnabled = true; -constexpr bool GeneralDebugEnabled = true; +// Serial debug output per CAN frame / OBD request costs loop time; enable only for bench debugging. +constexpr bool GeneralDebugEnabled = false; constexpr bool TwaiDebugEnabled = false; constexpr bool PowerDebugEnabled = false; constexpr bool CanDebugEnabled = false; @@ -16,6 +17,8 @@ constexpr uint32_t TraceSummaryIntervalMs = 1000; constexpr bool EnablePersistentDiagnosticLog = true; constexpr bool PersistTelemetryPayloadsToDiagnosticLog = false; +// Write per-request OBD/ISO-TP trace lines to the flash log (debug only). +constexpr bool PersistTraceToDiagnosticLog = false; constexpr std::size_t DiagnosticLogMaxBytes = 64U * 1024U; constexpr const char* SenderDiagnosticLogPath = "/sender_diagnostic.log"; diff --git a/include/config/ObdConfig.h b/include/config/ObdConfig.h index 9a9e0e5..690e7df 100644 --- a/include/config/ObdConfig.h +++ b/include/config/ObdConfig.h @@ -22,8 +22,7 @@ inline constexpr uint8_t RequestedPids[] = { RUN_TIME_SINCE_ENGINE_START, CONTROL_MODULE_VOLTAGE, AMBIENT_AIR_TEMP, - ENGINE_OIL_TEMP, - ENGINE_FUEL_RATE + ENGINE_OIL_TEMP }; inline constexpr std::size_t ObdPidCount = sizeof(RequestedPids) / sizeof(RequestedPids[0]); @@ -34,28 +33,35 @@ inline constexpr std::size_t ObdPidCount = sizeof(RequestedPids) / sizeof(Reques inline constexpr uint8_t FastLivePids[] = { ENGINE_RPM, VEHICLE_SPEED, - CONTROL_MODULE_VOLTAGE, - ENGINE_COOLANT_TEMP, - ENGINE_LOAD + ENGINE_LOAD, + MAF_FLOW_RATE // fuel consumption is derived from it }; inline constexpr std::size_t FastLivePidCount = sizeof(FastLivePids) / sizeof(FastLivePids[0]); // Slow live values still update regularly, but they are less important while // driving and are often unsupported on some vehicles. inline constexpr uint8_t SlowLivePids[] = { + ENGINE_COOLANT_TEMP, + CONTROL_MODULE_VOLTAGE, INTAKE_MANIFOLD_ABS_PRESSURE, INTAKE_AIR_TEMP, ABS_BAROMETRIC_PRESSURE, - MAF_FLOW_RATE, THROTTLE_POSITION, FUEL_TANK_LEVEL_INPUT, RUN_TIME_SINCE_ENGINE_START, AMBIENT_AIR_TEMP, - ENGINE_OIL_TEMP, - ENGINE_FUEL_RATE + ENGINE_OIL_TEMP }; inline constexpr std::size_t SlowLivePidCount = sizeof(SlowLivePids) / sizeof(SlowLivePids[0]); +// PID 0x5E (engine fuel rate) is unreliable on VW TSI engines (first vehicle +// test: 2.2 L/h reported vs. ~7.7 L/h from the air mass). For petrol engines +// the rate is derived from MAF: fuel = air / AFR, zero in overrun (load ~0). +constexpr bool FuelRateFromMaf = true; +constexpr float StoichiometricAfr = 14.7f; // petrol +constexpr float FuelDensityGramPerLitre = 745.0f; // petrol E5/E10 +constexpr float OverrunLoadPercent = 2.0f; + constexpr float DefaultBarometricPressureKpa = SenderConfig::DefaultBarometricPressureKpa; constexpr uint32_t DtcQueryIntervalMs = SenderConfig::DtcQueryIntervalMs; constexpr uint32_t VinQueryIntervalMs = SenderConfig::VinQueryIntervalMs; diff --git a/include/config/PowerConfig.h b/include/config/PowerConfig.h index 6de6b57..52831d2 100644 --- a/include/config/PowerConfig.h +++ b/include/config/PowerConfig.h @@ -19,5 +19,8 @@ constexpr float MovingSpeedKph = 1.0f; constexpr float ActiveEngineLoadPercent = 5.0f; constexpr float ActiveThrottlePercent = 2.0f; constexpr float BoardVoltageAwakeMin = 12.0f; +// With the ECU silent, OBD polling (re)starts only above this board voltage +// (alternator charging = engine running). See SenderApp vehicleBusMayBeUsed(). +constexpr float ResumePollingVoltage = 13.0f; } // namespace PowerConfig diff --git a/include/config/SenderConfig.h b/include/config/SenderConfig.h index 2d2151b..416ce41 100644 --- a/include/config/SenderConfig.h +++ b/include/config/SenderConfig.h @@ -57,7 +57,8 @@ constexpr const char* DiagnosticLogArchivePath = LoggingConfig::SenderDiagnostic constexpr uint32_t TwaiStatusLogIntervalMs = LoggingConfig::TwaiStatusLogIntervalMs; constexpr std::size_t MaxCanFramesPerTick = 16; -constexpr float VoltageCalcFactor = 4.81f; +// Calibrated 01.11.2026 against the engine ECU (PID 0x42: 14.62 V, ADC read ~15.3 V). +constexpr float VoltageCalcFactor = 4.62f; constexpr float DefaultBarometricPressureKpa = 101.3f; constexpr std::size_t CanRxQueueLength = 32; diff --git a/lib/diagnostics/SystemHealth.cpp b/lib/diagnostics/SystemHealth.cpp index ef63368..a2c8834 100644 --- a/lib/diagnostics/SystemHealth.cpp +++ b/lib/diagnostics/SystemHealth.cpp @@ -4,6 +4,7 @@ #include #include #include + #include #include #include #include "DiagnosticLog.h" @@ -100,6 +101,18 @@ void logBootSummary(const char* device) { #endif } +const char* macAddress() { + static char text[18] = "00:00:00:00:00:00"; +#if defined(ARDUINO) + uint8_t mac[6] = {}; + if (esp_read_mac(mac, ESP_MAC_WIFI_STA) == ESP_OK) { + std::snprintf(text, sizeof(text), "%02x:%02x:%02x:%02x:%02x:%02x", mac[0], mac[1], mac[2], mac[3], mac[4], + mac[5]); + } +#endif + return text; +} + void startWatchdog() { #if defined(ARDUINO) // The task watchdog is initialised by the core with 5 s; give loop() more diff --git a/lib/diagnostics/SystemHealth.h b/lib/diagnostics/SystemHealth.h index e920647..8402368 100644 --- a/lib/diagnostics/SystemHealth.h +++ b/lib/diagnostics/SystemHealth.h @@ -38,6 +38,9 @@ bool readCoreDump(std::size_t offset, uint8_t* buffer, std::size_t length); // Writes the boot summary to the diagnostic log (call after DiagnosticLog::begin). void logBootSummary(const char* device); +// Station MAC from eFuse (valid before WiFi is started), "aa:bb:cc:dd:ee:ff". +const char* macAddress(); + void startWatchdog(); void feed(); diff --git a/lib/isotp/IsoTpHandler.cpp b/lib/isotp/IsoTpHandler.cpp index a31184c..bd604e6 100644 --- a/lib/isotp/IsoTpHandler.cpp +++ b/lib/isotp/IsoTpHandler.cpp @@ -140,7 +140,7 @@ bool IsoTpHandler::receiveResponse(uint8_t expectedMode, uint8_t expectedPid, Pa } CanRouting::unregisterListener(*this); lastStatus_ = Status::Timeout; - Logger::warn("[ISOTP] Timeout waiting for response"); + Logger::obd("[ISOTP] Timeout waiting for response"); // reported once by the OBD/UDS layer return false; #else (void)expectedMode; diff --git a/lib/power/ActivityMonitor.cpp b/lib/power/ActivityMonitor.cpp index 18251db..b129354 100644 --- a/lib/power/ActivityMonitor.cpp +++ b/lib/power/ActivityMonitor.cpp @@ -77,8 +77,12 @@ const char* ActivityMonitor::powerCommandName(PowerCommand command) { uint8_t ActivityMonitor::calculateActivityScore(ActivitySnapshot& flags, const ActivityInput& input) const { flags.canActive = recently(input.nowMs, input.lastCanMessageAtMs, DisplayConfig::CanTimeoutMs); flags.obdActive = recently(input.nowMs, input.lastObdResponseAtMs, DisplayConfig::ObdTimeoutMs); - flags.engineRunning = input.rpm >= PowerConfig::EngineRunningRpm; - flags.moving = input.speedKph >= PowerConfig::MovingSpeedKph; + // RPM/speed/load/throttle are the last values the ECU reported. After + // ignition off they never change again, so they only count while OBD + // answers are recent - otherwise an engine switched off at idle looked + // like "running" forever and the car was never detected as parked. + flags.engineRunning = flags.obdActive && input.rpm >= PowerConfig::EngineRunningRpm; + flags.moving = flags.obdActive && input.speedKph >= PowerConfig::MovingSpeedKph; flags.boardAwake = input.batteryVoltage >= PowerConfig::BoardVoltageAwakeMin; flags.userActive = recently(input.nowMs, input.lastUserActivityAtMs, PowerConfig::UserActivityWindowMs); @@ -87,8 +91,8 @@ uint8_t ActivityMonitor::calculateActivityScore(ActivitySnapshot& flags, const A if (flags.obdActive) score += 5; if (flags.engineRunning) score += 3; if (flags.moving) score += 3; - if (input.engineLoadPercent >= PowerConfig::ActiveEngineLoadPercent) score += 2; - if (input.throttlePercent >= PowerConfig::ActiveThrottlePercent) score += 2; + if (flags.obdActive && input.engineLoadPercent >= PowerConfig::ActiveEngineLoadPercent) score += 2; + if (flags.obdActive && input.throttlePercent >= PowerConfig::ActiveThrottlePercent) score += 2; if (flags.boardAwake) score += 2; if (flags.userActive) score += 1; if (input.simulationActive) score += 5; diff --git a/lib/simulation/ObdSimulation.cpp b/lib/simulation/ObdSimulation.cpp index 07be5db..434c264 100644 --- a/lib/simulation/ObdSimulation.cpp +++ b/lib/simulation/ObdSimulation.cpp @@ -23,8 +23,8 @@ float displayScenarioValue(const SimulationData::Sample& sample, Scenario scenar return normal ? 2500.0f : 2200.0f; } if (std::strcmp(sample.name, "CoolantTemp") == 0) { - if (critical || mixed) return 108.0f; - if (warning) return 98.0f; + if (critical || mixed) return 120.0f; + if (warning) return 112.0f; return 85.0f; } if (std::strcmp(sample.name, "BatteryVoltage") == 0) { @@ -35,8 +35,8 @@ float displayScenarioValue(const SimulationData::Sample& sample, Scenario scenar return 13.8f; } if (std::strcmp(sample.name, "OilTemp") == 0) { - if (critical) return 128.0f; - if (warning || mixed) return 116.0f; + if (critical) return 142.0f; + if (warning || mixed) return 132.0f; return 90.0f; } if (std::strcmp(sample.name, "EngineLoad") == 0) return warning ? 74.0f : 36.0f; diff --git a/lib/telemetry/LiveData.cpp b/lib/telemetry/LiveData.cpp index 455caad..eac035b 100644 --- a/lib/telemetry/LiveData.cpp +++ b/lib/telemetry/LiveData.cpp @@ -130,6 +130,12 @@ void LiveValueTable::markUnsupported(Metric metric) { validMask_ &= ~(1u << index); } +void LiveValueTable::clear(Metric metric) { + const uint8_t index = static_cast(metric); + if (index >= MetricCount) return; + validMask_ &= ~(1u << index); +} + bool LiveValueTable::has(Metric metric) const { return (validMask_ >> static_cast(metric)) & 1U; } diff --git a/lib/telemetry/LiveData.h b/lib/telemetry/LiveData.h index 01c05fb..320427f 100644 --- a/lib/telemetry/LiveData.h +++ b/lib/telemetry/LiveData.h @@ -92,6 +92,8 @@ class LiveValueTable { void reset(); void update(Metric metric, float value, uint32_t nowMs); void markUnsupported(Metric metric); + // Value no longer meaningful (e.g. L/100 km while standing): shown as "--". + void clear(Metric metric); void setSimulated(bool simulated) { simulated_ = simulated; } bool has(Metric metric) const; float value(Metric metric) const; diff --git a/scripts/read_device_logs.py b/scripts/read_device_logs.py index 670592b..4e1cf9e 100644 --- a/scripts/read_device_logs.py +++ b/scripts/read_device_logs.py @@ -26,8 +26,9 @@ ROOT = Path(__file__).resolve().parents[1] TARGETS = { - "sender": {"chip": "esp32", "usb": "1a86:7523", "csv": "sender_4mb.csv"}, - "display": {"chip": "esp32s3", "usb": "303a:1001", "csv": "display_16mb.csv"}, + # CH340 (sender) is unreliable above 115200 for long reads. + "sender": {"chip": "esp32", "usb": "1a86:7523", "csv": "sender_4mb.csv", "baud": "115200"}, + "display": {"chip": "esp32s3", "usb": "303a:1001", "csv": "display_16mb.csv", "baud": "460800"}, } # Layout of V2.0 - V2.1.0-beta.2 (partitions/ota_4mb.csv, both devices). LEGACY = {"spiffs": (0x3B0000, 0x50000)} @@ -41,7 +42,7 @@ v=$(udevadm info -q property -n "$d" | sed -n 's/^ID_VENDOR_ID=//p'); p=$(udevadm info -q property -n "$d" | sed -n 's/^ID_MODEL_ID=//p') [[ "${v,,}:${p,,}" == "$USBID" ]] && { P=$d; break; }; done [[ -n "$P" ]] || { echo "Board $USBID nicht gefunden" >&2; exit 1; } -"$E" --chip "$CHIP" --port "$P" --baud 460800 read_flash "$OFFSET" "$SIZE" "$OUT" >&2 +"$E" --chip "$CHIP" --port "$P" --baud "$BAUD" read_flash "$OFFSET" "$SIZE" "$OUT" >&2 ''' @@ -55,7 +56,7 @@ def partition(csv_name: str, subtype: str) -> tuple[int, int]: def read_region(target: str, offset: int, size: int, dest: Path, remote: str | None) -> None: env = {"USBID": TARGETS[target]["usb"], "CHIP": TARGETS[target]["chip"], - "OFFSET": hex(offset), "SIZE": hex(size)} + "OFFSET": hex(offset), "SIZE": hex(size), "BAUD": TARGETS[target]["baud"]} if remote: remote_file = f"/tmp/canobd2-read-{os.getpid()}.bin" assignments = " ".join(f"{k}={shlex.quote(v)}" for k, v in {**env, "OUT": remote_file}.items()) diff --git a/src/display/DisplayApp.cpp b/src/display/DisplayApp.cpp index 977b632..911682c 100644 --- a/src/display/DisplayApp.cpp +++ b/src/display/DisplayApp.cpp @@ -26,7 +26,7 @@ void begin() { Security::begin(false); SystemHealth::logBootSummary("display"); DiagnosticLog::appendf("[BOOT] Display firmware=%s protocol=%u mac=%s secrets=%s %s", ProjectConfig::FirmwareVersion, - ProjectConfig::ProtocolVersion, WiFi.macAddress().c_str(), + ProjectConfig::ProtocolVersion, SystemHealth::macAddress(), Security::sourceName(Security::source()), Security::problemText()); // Web first: it sets up the AP on the ESP-NOW channel, then ESP-NOW joins. DisplayWeb::begin(); diff --git a/src/display/DisplayReceiver.cpp b/src/display/DisplayReceiver.cpp index 8bc0883..9aec1b5 100644 --- a/src/display/DisplayReceiver.cpp +++ b/src/display/DisplayReceiver.cpp @@ -69,6 +69,10 @@ void handleStatusText(const String& raw, uint32_t sequence) { } else if (key == "OBD") { runtime().lastObdStatusAt = now; } else if (key == "POWER_STATE") { + // Level based: the state is repeated every second, so a lost packet + // cannot keep the display awake (or asleep). + const bool sleepState = value == "DisplaySleep"; + if (sleepState != (runtime().vehicleState == "DisplaySleep")) runtime().displaySleepRequested = sleepState; runtime().vehicleState = value; runtime().lastPowerStatusAt = now; } else if (key == "ACTIVITY_SCORE") { diff --git a/src/sender/OBDHandler.cpp b/src/sender/OBDHandler.cpp index bb63222..e07360a 100644 --- a/src/sender/OBDHandler.cpp +++ b/src/sender/OBDHandler.cpp @@ -2,6 +2,7 @@ #include "LiveData.h" #include "SenderLiveData.h" #include "PIDs.h" +#include "config/ObdConfig.h" #include "PID_Converter.h" #include "IsoTpHandler.h" #include "BoostCalculator.h" @@ -111,12 +112,15 @@ 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. + // 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); } } @@ -175,9 +179,20 @@ bool OBD2Handler::requestAndSendPID(uint8_t pid) { updateActivityMetrics(pid, result.value); LiveData::Metric metric; - if (LiveData::metricForPid(pid, metric)) SenderLiveData::update(metric, result.value); + const bool fuelFromMaf = ObdConfig::FuelRateFromMaf && pid == ENGINE_FUEL_RATE; + if (!fuelFromMaf && LiveData::metricForPid(pid, metric)) SenderLiveData::update(metric, result.value); + + if (ObdConfig::FuelRateFromMaf && pid == MAF_FLOW_RATE) { + // g/s air -> L/h fuel; overrun (no load) means fuel cut-off. + const bool overrun = Runtime::SenderRuntimeState::lastEngineLoadPercent() < ObdConfig::OverrunLoadPercent; + const float litresPerHour = overrun ? 0.0f + : 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) calcConsumption(pid, result.value); + 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 20ad3c8..84e7ed1 100644 --- a/src/sender/SenderApp.cpp +++ b/src/sender/SenderApp.cpp @@ -12,6 +12,7 @@ #include "config/SenderConfig.h" #include "config/DisplayConfig.h" #include "config/LoggingConfig.h" +#include "config/PowerConfig.h" #include "RuntimeSimulation.h" #include "CANHandler.h" #include "CanRouterHub.h" @@ -105,8 +106,18 @@ Runtime::SenderRuntimeCoordinator::CanAlertResult processCanAlerts(uint32_t wait return {result.rxData, result.errorLedRequested, lastCanError.c_str()}; } +// Requests on the diagnostic CAN wake the vehicle gateway. While the engine +// ECU does not answer (ignition off) nothing is transmitted unless the board +// voltage shows a running alternator - otherwise the sender would keep the +// car's network awake and drain the vehicle battery. +bool vehicleBusMayBeUsed() { + if (Simulation::RuntimeSimulation::enabled()) return true; + if (SenderObdScheduler::supportedPidsInitialized()) return true; + return SenderPower::getLastVoltage() >= PowerConfig::ResumePollingVoltage; +} + void tickObd(Runtime::SenderLoopState& runtimeState) { - if (SenderCapabilityScanner::active()) return; + if (SenderCapabilityScanner::active() || !vehicleBusMayBeUsed()) return; SenderObdScheduler::tick(runtimeState.currentMillis, runtimeState.lastCanMessageAt, SenderTelemetry::lastObdResponseAtRef(), @@ -116,7 +127,7 @@ void tickObd(Runtime::SenderLoopState& runtimeState) { } void tickUds(Runtime::SenderLoopState& runtimeState) { - if (SenderCapabilityScanner::active()) return; + if (SenderCapabilityScanner::active() || !SenderObdScheduler::supportedPidsInitialized()) return; SenderUdsScheduler::tick(runtimeState.currentMillis, runtimeState.lastCanMessageAt, SenderTelemetry::lastObdResponseAtRef(), @@ -170,7 +181,7 @@ void SenderApp::begin() { DiagnosticLog::begin(); Security::begin(true); SystemHealth::logBootSummary("sender"); - DiagnosticLog::appendf("[BOOT] mac=%s secrets=%s %s", WiFi.macAddress().c_str(), + DiagnosticLog::appendf("[BOOT] mac=%s secrets=%s %s", SystemHealth::macAddress(), Security::sourceName(Security::source()), Security::problemText()); DiagnosticLog::appendf("[BOOT] Sender firmware=%s protocol=%u target=%s", ProjectConfig::FirmwareVersion, diff --git a/src/sender/SenderLiveData.cpp b/src/sender/SenderLiveData.cpp index 041dfe1..4ed526f 100644 --- a/src/sender/SenderLiveData.cpp +++ b/src/sender/SenderLiveData.cpp @@ -28,6 +28,10 @@ void markUnsupported(LiveData::Metric metric) { table.markUnsupported(metric); } +void clear(LiveData::Metric metric) { + table.clear(metric); +} + void setSimulated(bool simulated) { table.setSimulated(simulated); } diff --git a/src/sender/SenderLiveData.h b/src/sender/SenderLiveData.h index 8b81c0a..dcda0a2 100644 --- a/src/sender/SenderLiveData.h +++ b/src/sender/SenderLiveData.h @@ -11,6 +11,7 @@ namespace SenderLiveData { void reset(); void update(LiveData::Metric metric, float value); void markUnsupported(LiveData::Metric metric); +void clear(LiveData::Metric metric); void setSimulated(bool simulated); bool has(LiveData::Metric metric); float value(LiveData::Metric metric); diff --git a/src/sender/SenderPower.cpp b/src/sender/SenderPower.cpp index 089f50f..9e9b61e 100644 --- a/src/sender/SenderPower.cpp +++ b/src/sender/SenderPower.cpp @@ -85,6 +85,9 @@ namespace SenderPower { if (lastSnapshot.command != Power::PowerCommand::None) { WebConsoleHandler::log(String("[POWER] command=") + Power::ActivityMonitor::powerCommandName(lastSnapshot.command)); + // The command exists for exactly one update; send it right away instead + // of waiting for the 1 s status cycle (it was practically never sent). + sendPowerStatus(lastSnapshot); } } diff --git a/test/test_activity_monitor/test_activity_monitor.cpp b/test/test_activity_monitor/test_activity_monitor.cpp index 2d84c48..0b14a80 100644 --- a/test/test_activity_monitor/test_activity_monitor.cpp +++ b/test/test_activity_monitor/test_activity_monitor.cpp @@ -87,6 +87,29 @@ void test_parked_starts_sleep_timer_but_does_not_sleep_immediately() { static_cast(snapshot.command)); } +// Regression (vehicle test 01.11.2026): the engine was switched off at idle, +// the last reported RPM (800) and speed stayed in memory and the car was +// considered "running" forever - the display never went to sleep. +void test_stale_rpm_after_ignition_off_does_not_prevent_parking() { + Power::ActivityMonitor monitor; + monitor.reset(0); + Power::ActivityInput input = baseInput(PowerConfig::ParkDetectionTimeoutMs + 20000); + input.batteryVoltage = 12.6f; // realistic resting voltage + input.rpm = 800.0f; // last value before ignition off + input.speedKph = 3.0f; + input.engineLoadPercent = 25.0f; + input.lastCanMessageAtMs = 1000; + input.lastObdResponseAtMs = 1000; + + Power::ActivitySnapshot snapshot = monitor.update(input); + TEST_ASSERT_EQUAL_UINT8(static_cast(Power::VehicleState::Parked), static_cast(snapshot.state)); + + input.nowMs += PowerConfig::DisplaySleepAfterMs + 1; + snapshot = monitor.update(input); + TEST_ASSERT_EQUAL_UINT8(static_cast(Power::VehicleState::DisplaySleep), + static_cast(snapshot.state)); +} + void test_display_sleep_after_parked_timer_elapsed() { Power::ActivityMonitor monitor; monitor.reset(0); @@ -151,6 +174,7 @@ int main(int, char**) { RUN_TEST(test_engine_off_alone_does_not_request_display_sleep); RUN_TEST(test_can_activity_prevents_parked_state); RUN_TEST(test_parked_starts_sleep_timer_but_does_not_sleep_immediately); + RUN_TEST(test_stale_rpm_after_ignition_off_does_not_prevent_parking); RUN_TEST(test_display_sleep_after_parked_timer_elapsed); RUN_TEST(test_wakeup_from_display_sleep_on_new_can_message); RUN_TEST(test_simulation_activity_keeps_power_manager_awake); diff --git a/test/test_display_severity/test_display_severity.cpp b/test/test_display_severity/test_display_severity.cpp index a73817f..c60e311 100644 --- a/test/test_display_severity/test_display_severity.cpp +++ b/test/test_display_severity/test_display_severity.cpp @@ -8,20 +8,20 @@ void tearDown() {} void test_coolant_severity() { TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Ok), - static_cast(DisplayLogic::severityForMetric("CoolantTemp", 85.0f, true))); + static_cast(DisplayLogic::severityForMetric("CoolantTemp", 97.0f, true))); TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Warning), - static_cast(DisplayLogic::severityForMetric("CoolantTemp", 98.0f, true))); + static_cast(DisplayLogic::severityForMetric("CoolantTemp", 112.0f, true))); TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Critical), - static_cast(DisplayLogic::severityForMetric("CoolantTemp", 108.0f, true))); + static_cast(DisplayLogic::severityForMetric("CoolantTemp", 120.0f, true))); } void test_oil_severity() { TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Ok), - static_cast(DisplayLogic::severityForMetric("OilTemp", 90.0f, true))); + static_cast(DisplayLogic::severityForMetric("OilTemp", 105.0f, true))); TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Warning), - static_cast(DisplayLogic::severityForMetric("OilTemp", 116.0f, true))); + static_cast(DisplayLogic::severityForMetric("OilTemp", 132.0f, true))); TEST_ASSERT_EQUAL(static_cast(DisplaySeverity::Critical), - static_cast(DisplayLogic::severityForMetric("OilTemp", 128.0f, true))); + static_cast(DisplayLogic::severityForMetric("OilTemp", 142.0f, true))); } void test_voltage_severity() {