Compare commits

...
8 Commits
Author SHA1 Message Date
root f639f14427 docs: add roadmap for code structure, optimization and SD logging 2026-11-11 23:13:32 +00:00
root e88623cf6e perf(influx): batch measurements and reuse HTTP connections 2026-11-11 22:57:12 +00:00
root dde4736cc2 feat(display): add air quality pages, history and display settings 2026-11-11 22:24:29 +00:00
admin 62e9d249cb ein Page mit hand in EEZ hinzugefügt 2026-11-11 22:42:10 +01:00
root 69bb47dda1 feat(firmware): support configurable SEN54 and SEN66 boards
Add the pinned Sensirion SEN66 driver, central sensor and board profiles, and a separate GPIO I2C bus for SEN66 with display. Preserve the original display layout and keep NOx and CO2 in InfluxDB. Include protocol tests, hardware workflow documentation and verified deployment results without credentials.
2026-11-09 21:44:04 +00:00
root 45b05d045a feat(linux): add persistent Avahi discovery for InfluxDB
Add a Debian NUC installer, IPv4 service definition and usage guide with backup and legacy alias migration. Document the user-confirmed SEN54-to-InfluxDB connection without including credentials.
2026-11-07 20:00:02 +00:00
root 3dcfdedc18 fix(build): disable optional component update checks
Set IDF_COMPONENT_CHECK_NEW_VERSION before loading ESP-IDF so PlatformIO and VS Code builds do not require a shell export. Document the LVGL Kconfig workaround while preserving the dependency lockfile.
2026-11-07 13:57:12 +00:00
root b10b96f1ae build: pin ESP-IDF 5.5.0 for 8 MB ESP32-C6
Configure the active SDK and defaults for the existing OTA layout. Add repository hardware development instructions and the verified application upload reference.
2026-11-04 22:36:05 +00:00
61 changed files with 7594 additions and 918 deletions
+225
View File
@@ -0,0 +1,225 @@
# ESP32 Hardware Development Workflow
## Entwicklungsumgebung
Dieses Projekt wird mit Codex in einem Docker-Container auf einem VPS entwickelt.
- Versionsverwaltung: Gitea
- Build-System: PlatformIO
- Framework: ESP-IDF 5.5.0 (aktueller getesteter Build)
- PlatformIO-Plattform: `espressif32@6.12.0`
- SDK-Paket: `platformio/framework-espidf@3.50500.0`
- Hardwarezugriff: WireGuard + eingeschränktes SSH-Gateway
- SSH-Alias im Codex-Container: `esp32`
- Gateway-Rechner: Debian 13
Der ESP32 ist physisch am Debian-Rechner angeschlossen. Codex führt sämtliche Builds auf dem VPS aus und verwendet ausschließlich das SSH-Gateway zur Hardwarekommunikation.
## Board-Erkennung
Vor jeder Hardwareoperation das Zielboard eindeutig bestimmen.
```bash
ssh esp32 list
```
Bekanntes Testboard:
- Chip: ESP32-C6FH8
- USB-Seriennummer: `CC:BA:97:F2:52:80`
- Flash: 8 MB
- Revision: v0.2
Weitere bekannte Hardware:
- ESP32-C6FH8, 8 MB, Revision v0.2, USB-Seriennummer `CC:BA:97:F2:5F:7C`; SEN66 und Display-Profil am 09.11.2026 geprüft, aktuelles OTA-Layout statt früherer 1-MiB-Factory-Partition.
- ESP32-C6FH4
- USB-Seriennummer: `9C:9E:6E:7B:5D:C0`
- Flash: 4 MB
Niemals anhand von `/dev/ttyACM0` oder `/dev/ttyUSB0` allein ein Board auswählen, da sich diese Gerätenamen ändern können.
## Gateway-Befehle
```bash
ssh esp32 list
ssh esp32 "info BOARD_ID"
ssh esp32 "flash-id BOARD_ID"
ssh esp32 "monitor BOARD_ID 30"
ssh esp32 "send BOARD_ID HEXDATEN"
ssh esp32 "read BOARD_ID OFFSET GROESSE"
ssh esp32 "write BOARD_ID OFFSET GROESSE SHA256"
ssh esp32 "erase BOARD_ID CONFIRM"
```
Alle boardbezogenen Hardwareoperationen müssen eine explizite Boardkennung verwenden. `list` dient ausschließlich der Erkennung und benötigt keine Boardkennung.
Die `read`-Funktion liefert rohe Binärdaten über stdout.
Die `write`-Funktion erhält die Firmwaredatei über stdin. Die erwartete Dateigröße und SHA-256-Prüfsumme werden vom Gateway geprüft.
## Build-Workflow
Das PlatformIO-Projekt liegt unter `firmware/`. Das aktuelle Environment `esp32-c6-devkitc-1` ist für ESP32-C6 mit **8 MB Flash** konfiguriert. Diesen Build nicht auf das bekannte 4-MB-Board übertragen. Die aktive SDK-Konfiguration ist `firmware/sdkconfig.esp32-c6-devkitc-1`; Defaults stehen in `firmware/sdkconfig.defaults`, die Partitionstabelle in `firmware/partitions.csv`.
Sensor und Peripherieprofil werden zentral in `firmware/components/hardware_config/hardware_config.h` gewählt. Unterstützte Sensoren: SEN54 und SEN66; vorhandene Profile: ESP32-C6 mit Display (Touch auf Hardware-I²C GPIO18/19) und ESP32-C6 ohne Display (Hardware-I²C GPIO7/8), jeweils 8 MB. SEN54 nutzt den Hardware-Bus des Profils. SEN66 bleibt immer auf GPIO7/8 und verwendet beim Display-Profil einen separaten Software-I²C-Bus; ohne Display verwendet er den Hardware-Controller. Die aktuelle Standardauswahl ist SEN66 mit Display. Die Software-I²C-Implementierung hat ACK/NACK-, Clock-Stretching- und Timeout-Tests; keine weiteren Sensorgeräte ohne Prüfung auf diesem Bus hinzufügen. Auswahl und Verdrahtung vor jedem Build prüfen; nicht vom angeschlossenen Port oder einer früheren Auswahl ableiten. Die Auswahl ersetzt keine Prüfung von PlatformIO-Chip, Flash-Größe und Partitionstabelle. Anleitung und Tests: `firmware/HARDWARE.md`. Der SEN66 verwendet den gepinnten offiziellen Sensirion-Treiber; Herkunft und Lizenz sind in `firmware/components/sen5x/SENSIRION-UPSTREAM.md` dokumentiert. Die gemeinsame Sensoranwendung heißt `air_sensor_app`; SEN66 ergänzt das Influx-Feld `co2`, SEN54 darf keine künstlichen CO₂-Werte erzeugen. Die bisherige Messwertseite mit Schriftzug, PM, Temperatur, Feuchte, VOC und Statussymbolen bleibt erhalten. Der neue Benutzerauftrag vom 11.11.2026 erweitert das Display um Raumluft mit CO₂/VOC-/NOx-Index, lokalen Verlauf und Gerätestatus/Einstellungen. EEZ-Projekt und Firmware zusammen pflegen; PlatformIO synchronisiert die Bildschirmdateien vor dem Build automatisch. Details und native UI-Tests stehen in `firmware/HARDWARE.md`.
1. Projektkonfiguration in `platformio.ini` prüfen.
2. PlatformIO-Environment für das Zielboard bestimmen.
3. Firmware kompilieren.
4. Build-Fehler beheben.
5. Firmware-Image und Flash-Layout prüfen.
6. Zielboard über das Gateway identifizieren.
Build aus dem Repository-Hauptverzeichnis:
```bash
pio run -d firmware -e esp32-c6-devkitc-1 -j 2
```
`firmware/CMakeLists.txt` setzt `IDF_COMPONENT_CHECK_NEW_VERSION=0` vor dem Laden des ESP-IDF-Buildsystems. Dadurch bleibt die optionale Suche nach neueren Komponenten-Versionen auch bei Builds über VS Code deaktiviert; ein manuelles `export` ist nicht erforderlich. Die reguläre Abhängigkeitsauflösung und die Verwendung von `dependencies.lock` bleiben aktiv. Hintergrund ist ein bestätigter Build-Abbruch durch fehlende LVGL-Kconfig-Optionen bei eingeschalteter Update-Suche auf einem weiteren Entwicklungsrechner. Abhängigkeitsupdates getrennt und gezielt durchführen, nicht diese Einstellung ungeprüft entfernen.
Die festgelegten Plattform-/SDK-Versionen erhalten. Der frühere Build mit ESP-IDF 6.1.0 scheiterte, weil `REQUIRES driver` dort `esp_driver_ledc` nicht mehr automatisch einbindet. Ein SDK-Upgrade ist eine gesonderte Migration; Versionen nicht ungeprüft anheben.
Die aktuellen OTA-Partitionen reichen bis `0x740000` und passen in 8 MB. Image-Dateinamen und Flash-Adressen aus den tatsächlichen PlatformIO-Artefakten, `flasher_args.json` und gegebenenfalls `envdump` ermitteln. CMake kann logische Dateinamen angeben, während PlatformIO `firmware.bin`, `bootloader.bin` und `partitions.bin` erzeugt.
## Flash-Workflow
Vor jedem Upload:
1. Board-Seriennummer überprüfen.
2. Chiptyp und Flash-Größe prüfen.
3. Firmware-SHA-256 berechnen.
4. Partitionstabelle und OTA-Auswahl prüfen.
5. Schreibadresse aus dem tatsächlichen Build und der aktiven Partitionierung ableiten.
6. Verifizieren, dass der gesamte Schreibbereich einschließlich betroffener Flash-Sektoren innerhalb der vorgesehenen Partition liegt.
7. Sicherstellen, dass ein gültiges Backup verfügbar ist.
Nur notwendige Flash-Bereiche schreiben.
Bootloader, Partitionstabelle, NVS und OTA-Auswahldaten nicht ohne technische Notwendigkeit überschreiben. PHY-Daten ebenfalls erhalten, sofern der konkrete Auftrag keine begründete Änderung vorsieht.
Nach dem Flashen:
1. Geschriebenen Bereich vollständig zurücklesen.
2. Binärdaten bytegenau vergleichen.
3. SHA-256 verifizieren.
4. Bootverhalten kontrollieren.
5. Seriellen Monitor mindestens 60 Sekunden auswerten.
6. WLAN, Netzwerkdienste und Hardwareperipherie prüfen.
Ein erfolgreicher Flash-Vorgang gilt erst nach bestandener Rückleseverifikation als technisch bestätigt. Die Anwendungsfunktion muss separat geprüft werden.
## Sicherheitsregeln
- Keine normale SSH-Shell auf dem Debian-Rechner verwenden.
- Keine Änderungen an WireGuard, SSH-Konfiguration oder Gateway vornehmen, außer wenn ausdrücklich beauftragt.
- Kein vollständiges `erase` ohne ausdrückliche Freigabe.
- Vor destruktiven Operationen Zielboard und Flash-Bereich erneut prüfen.
- Operationen, die sämtliche gespeicherten Daten oder unbekannte persistente Bereiche unwiederbringlich zerstören können, benötigen eine ausdrückliche Benutzerfreigabe.
- Keine automatischen wiederholten Flash-Versuche bei ungeklärten Fehlern.
- Keine privaten SSH-Schlüssel oder Zugangsdaten ausgeben oder committen.
- Private SSH-Schlüssel niemals in das Repository aufnehmen oder ohne gesonderten ausdrücklichen Sicherungsauftrag kopieren.
- Keine Firmware auf ein anderes als das ausgewählte Board schreiben.
- Hardwaretests und Schreiboperationen nicht parallel auf demselben seriellen Gerät ausführen.
- Keine nicht dokumentierten Gateway-Befehle ausprobieren und keine Sicherheitsmechanismen umgehen.
## Erfolgreich getestetes Deployment
Am 04.11.2026 wurde ein Firmware-Upload auf das Board `CC:BA:97:F2:52:80` erfolgreich durchgeführt.
- Chip: ESP32-C6FH8
- Flash: 8 MB
- Build-Environment: `esp32-c6-devkitc-1`
- Framework: ESP-IDF 5.5.0
- Anwendungspartition: `ota_0`
- Schreibadresse: `0x020000`
- Firmwaregröße: 1.741.040 Bytes
- Schreibvorgänge: 1
- Rückleseverifikation: erfolgreich
- SHA-256: `ae6d2892c16e3ac7ced681ca4112a4dc8b5168af4a7b2c9d029db9c095be6fdd`
- Boot: erfolgreich
- WLAN: erfolgreich
- Bootloader, Partitionstabelle, OTA-Auswahl und PHY-Daten: beim Upload unverändert
- Serieller Monitor: 60 Sekunden, keine erkannten Panics oder Neustartschleifen
Dieser Upload ist ein dokumentierter Referenzfall. Die genannten Adressen und Hashwerte dürfen nicht ungeprüft für zukünftige Firmware-Versionen wiederverwendet werden.
## Getestete SEN66-Migration (09.11.2026)
- Ziel: `CC:BA:97:F2:5F:7C`, ESP32-C6FH8, 8 MB; Sensor SEN66 an SDA GPIO7/SCL GPIO8, mit Display und Touch auf separatem Hardware-I²C-Bus GPIO18/19.
- Benutzer hat die Migration und neue Partitionierung ausdrücklich freigegeben. Nach vollständigem geprüftem Backup wurde ohne vollständiges Löschen auf das bestehende nanoPSX-8-MB-Layout mit zwei OTA-Partitionen migriert. Vorhandener gültiger IDF-5.5-Bootloader blieb unverändert.
- Vier Schreibvorgänge, jeweils vollständiges bytegenaues Rücklesen und SHA256 erfolgreich: Anwendung `0x20000` (1.736.144 Bytes, SHA256 `59ee4120dbcdf2edda17bcf57c1f7a81d18b197e8d4413f0a28e283a7871eba9`), Inhalt der bisherigen PHY-Partition nach `0x11000` kopiert (4096 Bytes), OTA-Auswahl bei `0xF000` initialisiert (8192 Bytes), neue Partitionstabelle bei `0x8000` zuletzt aktiviert (3072 Bytes).
- Abschließend vollständige 8 MB ausgelesen: keine Änderungen außerhalb geplanter Sektoren und regulärer NVS-/OTA-Laufzeitbereiche; Bootloader und kopierter PHY-Partitionsinhalt bytegenau erhalten. OTA-Auswahl gültig, Sequenz 1, Zustand 2, Auswahl `ota_0`.
- NVS war vor Aktivierung bytegenau erhalten. Nach Start waren 2032 Rohbytes verändert; der offizielle SDK-NVS-Parser ordnet die logischen Änderungen ausschließlich `phy:cal_data` (Radio-Kalibrierungsblob) zu. Alle anderen vorhandenen logischen Einträge behalten identische Inhaltsfingerprints. Kein NVS-Reset durchgeführt.
- Alle vier Sensor-/Board-Builds und native Hersteller-/Software-I²C-Tests erfolgreich. 60 Sekunden Monitor ohne erkannte Panic oder Sensor-I²C-Fehler; SEN66 erkannt und Messung gestartet, u.a. CO₂ 1149 ppm und PM2.5 7,2 µg/m³. Display initialisiert, kein Touch-Ausfall gemeldet. Eine sichtbare Prüfung des physischen Displays ist über das Gateway nicht möglich.
- Setup-AP `nanoPSX`, Portal `http://192.168.4.1`; auf diesem Board wurde im Test noch keine STA-IP oder erfolgreiche Influx-Übertragung beobachtet. WLAN sowie Organisation/Bucket gegebenenfalls im Portal einrichten. SD-Karten-Timeout besteht weiter.
- Diese Einzelfreigabe ist abgeschlossen und gilt nicht automatisch für erneute Migrationen oder andere Boards. Künftige App-Updates nach erneuter Layout-/OTA-Prüfung planen; keine erneute Migration anhand dieses historischen Eintrags ausführen.
Nachfolgende Benutzerkorrektur am selben Tag: Die zusätzliche CO₂-Anzeige wurde wieder entfernt. Die EEZ-Displaydateien entsprechen bytegenau dem ursprünglichen Git-Stand; keine NOx-/CO₂-Widgets ergänzen, solange kein neuer Auftrag vorliegt. Die entsprechende SEN66-Anwendung wurde ausschließlich bei `0x20000` aktualisiert (1.735.776 Bytes, SHA256 `ed9cec4854c5c19eaaecf69c4a1f5c9740014caf8a2bcd88976bb0bbe7fba4dd`) und vollständig bytegenau/SHA256-verifiziert. Bootloader, Partitionstabelle, OTA-Auswahl und PHY-Partitionsinhalt unverändert. Anwendungseinstellungen in NVS behalten ihre Inhaltsfingerprints; normale Radio-Kalibrierungsänderungen wurden getrennt erfasst. Der anschließende 60-Sekunden-Monitor bestätigte laufende SEN66-Messungen und **55 erfolgreiche Influx-Schreibantworten mit HTTP 204**, keine Schreib-/Sensorfehler und keine Panic. NOx und CO₂ bleiben für InfluxDB erhalten. Der vorherige Setup-AP-Hinweis beschreibt den Zustand vor der inzwischen vom Benutzer eingerichteten WLAN-Verbindung.
## Getestetes Displayseiten-Update (11.11.2026)
- Benutzerauftrag: neue EEZ-Seite übernehmen, Wischen zur zweiten Seite und zurück ermöglichen, bauen und flashen. Git-Stand `62e9d24` enthält die leere `Page_2`; die Firmware-Displayobjekte wurden entsprechend ergänzt. Navigation liegt außerhalb der EEZ-Exportdateien in `firmware/components/eez_gui/ui_navigation.c` und wird nach `ui_init()` unter dem LVGL-Lock initialisiert. Links von `Main` zu `Page_2`, rechts zurück; kein Umlauf. Gesten über Kindobjekten werden zur Bildschirmwurzel weitergereicht, die festen Seiten scrollen nicht.
- Native Tests mit echten LVGL-Quellen, beiden Displayseiten und simuliertem Zeiger bestanden: Tippen, kurze/vertikale Gesten, äußere Grenzen, Kindobjekte und wiederholtes Hin-/Herwechseln. Aufruf und EEZ-Exporthinweise stehen in `firmware/HARDWARE.md`; Test: `python3 firmware/test/ui/run_tests.py`.
- Ziel erneut eindeutig bestätigt: `CC:BA:97:F2:5F:7C`, ESP32-C6FH8, Revision v0.2, 8 MB. Environment `esp32-c6-devkitc-1`, ESP-IDF 5.5.0, SEN66 mit Display, Sensor GPIO7/8 und separater Touch-Bus GPIO18/19.
- Neues vollständiges 8-MB-Backup und unabhängige Anfangs-/Endproben erfolgreich geprüft. Vor Upload Partitionstabelle einschließlich MD5, gültige OTA-Auswahl (`ota_0`, Sequenz 1, Zustand 2, CRC gültig), vorhandener Bootloader, Image-Prüfsumme/Validierungshash und Sektorgrenzen geprüft.
- Genau ein Anwendungsschreibvorgang bei `0x20000`, 1.736.384 Bytes, SHA256 `86021d81ed8b2e2f284f2f1bda0c32efd231a878f3792a705a307fa816c36a46`. Vollständige bytegenaue Rücklese-/SHA256-Verifikation erfolgreich; kein vollständiges Löschen. Anschließender vollständiger Flash-Vergleich bestätigt unveränderten Bootloader, Partitionstabellensektor, OTA-Auswahl, PHY, übrige Flash-Bereiche und 320-Byte-Sektorrand. NVS änderte sich zur Laufzeit um 85 Rohbytes; kein NVS-Schreibbefehl oder Reset ausgeführt, logische Inhaltsgleichheit diesmal nicht separat geprüft.
- 60 Sekunden Monitor: Navigation bereit, laufende SEN66-Messung und 55 erfolgreiche Influx-Antworten mit HTTP 204; keine erkannten Fehler-, Panic-, Reset- oder Sensorfehlerzeilen. Keine physischen Wischgesten im Monitor beobachtet; sichtbares Display und Fingerbedienung müssen vor Ort geprüft werden. `Page_2` bleibt entsprechend dem EEZ-Projekt leer.
- Geschützte Backups und Logs außerhalb des Repositorys enthalten `flash-plan.json`, `backup-report.json`, `write-results.json`, `deployment-report.json`, Build-/UI-Testlogs, Monitor und vollständige Vor-/Nach-Flashdateien. Diese abgeschlossene Ausführung ist keine Freigabe für weitere Schreibvorgänge.
## Vier Displayseiten, Verlauf und Einstellungen (11.11.2026)
- Neuer Benutzerauftrag: vollständige Umsetzung der vorgeschlagenen Display-Erweiterungen einschließlich EEZ-Projekt, Bedienung, Build und Flash. Die bisherige Hauptansicht bleibt erhalten; `Page_2` zeigt CO₂/VOC-/NOx-Index mit CO₂-Verlauf, `History` den wählbaren Verlauf und `Device` WLAN/IP, Alter des letzten HTTP-204-Erfolgs, Sensoralter und Display-Einstellungen. Wischen durch vier Seiten ohne Umlauf; Statussymbole öffnen die Geräteseite.
- `eez/nanopsx.eez-project` und generierte Bildschirmdateien synchronisiert. PlatformIO führt `firmware/tools/export_display.py` vor jedem Build automatisch aus. Native Anwendungslogik und threadgeschütztes Zahlen-/Verlaufsmodell bleiben außerhalb der Exportdateien. Details, unterstützte Exporter-Widgets und Testbefehle: `firmware/HARDWARE.md`.
- Lokaler RAM-Verlauf: 180 Zehn-Sekunden-Mittelwerte, sechs auswählbare Messgrößen, fehlende Werte als Lücken, Neustart leert den Puffer. Veraltete Messungen nach mehr als fünf Sekunden und nicht verfügbare Kanäle werden gekennzeichnet. SEN54 liefert weiterhin keine künstlichen CO₂-Werte.
- Display: Helligkeit 20–100 %, Standard 100 %; Abdunkeln aus/30/60/120 s, Standard 60 s auf 15 %. Erste Berührung weckt ausschließlich. Eigene NVS-Einstellungen in `ui_display`, gespeichert bei Reglerfreigabe bzw. Auswahl, keine Änderung der WLAN-/Influx-Konfiguration.
- Erfolgreicher vollständiger Build für `esp32-c6-devkitc-1`, ESP-IDF 5.5.0, SEN66 mit Display. UI-Integrationstest mit echten LVGL-Quellen und 48 KiB LVGL-Heap bestanden: vierseitige Navigation, kurze/vertikale Gesten und Grenzen, Dropdown-Isolation, Regler, Aufwecken, Abschalten der Abdunklung, fehlende/veraltete Werte, alle sechs Diagrammkanäle sowie Ringpuffer-Mittelwerte, Lücken und Verdrängung. Native Hersteller-/Software-I²C- und Profilauswahltests bestanden. Gerenderte Vorschauen mit simulierten Werten visuell geprüft.
- Ziel erneut per `list`/`info`/`flash-id` bestätigt: `CC:BA:97:F2:5F:7C`, ESP32-C6FH8, Revision v0.2, 8 MB. Frisches vollständiges Backup mit unabhängigen Anfangs-/Endproben; Partitionstabelle, MD5, OTA-Auswahl, Bootloader, Firmware-Prüfsumme/Hash und Sektorrand vor Upload geprüft.
- Genau ein App-Schreibvorgang bei `0x20000`: 1.844.048 Bytes, SHA256 `10826853d6574c272dc91ca9cde0aabadc231172cbc8bdd1e32b628ba3701443`. Vollständige bytegenaue Rücklese-/SHA256-Verifikation erfolgreich. Kein vollständiges Löschen. Abschließender 8-MB-Vergleich bestätigt unveränderten Bootloader, Partitionstabellensektor, OTA-Auswahl, PHY, sonstige Flash-Bereiche und 3248-Byte-Sektorrand. NVS änderte sich zur Laufzeit um 74 Rohbytes; logische Inhalte diesmal nicht separat verglichen.
- 60 Sekunden Monitor: Vier-Seiten-Navigation bereit, SEN66-Messungen und 55 erfolgreiche Influx-Antworten mit HTTP 204. Keine erkannten Panics oder Sensor-/Touch-Fehler. Zwei bekannte SD-Timeout-Fehlerzeilen, keine sonstigen Fehlerzeilen. Physische Wischgesten, sichtbares Displaybild und Speichern/Neuladen der Einstellungen sind am Gerät durch den Benutzer zu prüfen; keine entsprechende Hardwarebetätigung im Monitor beobachtet.
- Geschützte Backups und Logs außerhalb des Repositorys: `flash-plan.json`, `backup-report.json`, `write-results.json`, `deployment-report.json`, Vor-/Nach-Flashdateien, Monitor, Build-/UI-Testlogs und Quellen-Hashes. Ausführung abgeschlossen; keine weitere Schreib-/Löschfreigabe ableiten.
## InfluxDB-Bündelung und Verbindungswiederverwendung (11.11.2026)
- Benutzerauftrag: effizientere Übertragung durch größere Sammelanfragen. Messung und Display bleiben bei nominal 1 Hz; keine Mittelung der Influx-Messpunkte oder Änderung ihrer Felder. Bis zu zehn Punkte / 4096 Bytes pro Anfrage, Restpakete nach maximal zehn Sekunden. Im Normalbetrieb etwa sechs Schreibanfragen pro Minute statt 60; serverseitige Sichtbarkeit entsprechend verzögert.
- Asynchrone API serialisiert beim Einreihen in eine feste Warteschlange mit 32 Einträgen. Keine einzelnen Heap-Allokationen pro Feld. Worker-Stack 8192 Bytes. HTTP-Client/Verbindung werden wiederverwendet; Fehler oder geänderte Konfiguration bauen den Handle neu auf. Token und Payloads werden nicht protokolliert.
- Einzelne UTC-Zeitstempel mit `precision=ms` verhindern Zusammenfallen gebündelter Punkte derselben Serie. Messzeit wird monoton beim Einreihen erfasst. Ein GET `/health` richtet die private Messuhr am HTTP-Date desselben Servers aus (ungefähr sekundengenaue absolute UTC-Zuordnung, kein externer Zeitdienst/kein Stellen der Systemuhr). Ohne gültige Zeitbasis sichere Einzelpunkt-Anfragen statt ungestempelter Mehrpunktpakete. Explizite API-Zeitstempel bleiben erhalten.
- Transport-/Serverfehler behalten Paketinhalt und Zeitstempel für Wiederholungen bei; exponentielle Pause 2 s bis 300 s, Konfiguration nach fünf Fehlern erneut lesen. HTTP 400/413/422 verwirft das abgelehnte Paket mit Meldung. Ohne Zeitbasis werden fehlgeschlagene Einzelpunkte nicht automatisch mit neuer Serverzeit wiederholt. Volle Queue ersetzt die ältesten wartenden Punkte und zählt die Verluste. RAM-Inhalte gehen bei Reset verloren. Details/API-/Testhinweise stehen in `firmware/HARDWARE.md`.
- Zehn native Szenarien mit echtem Worker und FreeRTOS-/HTTP-Simulation unter Address-/UndefinedBehavior-Sanitizer bestanden: Formatierung/escaping/Sentinels, UTC/Kalender, 10er-Pakete, identische Wiederholungen, volle Queue, fehlende Zeitbasis, Einzelpunktfehler, Restpakete, Bytegrenze und abgelehnte Pakete. Client-Lebensdauer und eindeutige Messzeitstempel geprüft. Vollständiger ESP-IDF-5.5-Build im Environment `esp32-c6-devkitc-1` erfolgreich.
- Ziel `CC:BA:97:F2:5F:7C`, ESP32-C6FH8/v0.2/8MB erneut per `list`/`info`/`flash-id` bestätigt. Frisches vollständiges Backup mit unabhängigen Anfangs-/Endproben, Tabelle/MD5, OTA-Auswahl, Bootloader und Sektorrand geprüft. Genau ein App-Schreibvorgang bei `0x20000`, 1.846.464 Bytes, SHA256 `734654f29e16a20aa43086131115cc06d16b09909f55c2bbb14b4e4704a063a7`. Vollständiges bytegenaues/SHA256-Rücklesen erfolgreich, kein vollständiges Löschen.
- Vollständiger anschließender 8-MB-Vergleich: Bootloader, Partitionstabellensektor, OTA-Auswahl, PHY, übrige Flashbereiche und 832-Byte-Sektorrand unverändert. NVS änderte sich zur Laufzeit um 2067 Rohbytes; logische Inhalte diesmal nicht separat verglichen. Neue Influx-Logik liest die vorhandene Konfiguration und schreibt selbst keine NVS-Einstellungen.
- 60 Sekunden Monitor: fünf bestätigte Schreibanfragen mit 10/10/8/10/10 Punkten (48 Punkte gesamt), ein Verbindungsaufbau inklusive initialem Health-Request. Private Messuhr erfolgreich ausgerichtet; protokollierte Paketzeitstempel unterscheiden die Messzeitpunkte. Keine Schreibfehler, keine erkannten Panics, Sensor-/Touch-Fehler oder gezählten Queue-Verluste. Zwei bekannte SD-Timeout-Zeilen, keine anderen Fehlerzeilen. Kleinere Pakete bei Zeitlimit sind vorgesehen; keine Messwerte für fehlende Sensorpakete erfinden.
- Berichte/geschützte Logs außerhalb des Repositorys: `flash-plan.json`, `backup-report.json`, `write-results.json`, `deployment-report.json`, vollständige Flashdateien, Monitor, Build-/Testlogs und Quellen-Hashes. Diese Ausführung ist abgeschlossen; keine weitere automatische Schreib-/Löschfreigabe ableiten.
## Bekannte Anwendungsprobleme (historischer Stand)
Beim letzten Hardwaretest wurden festgestellt:
- InfluxDB-Verbindung zu `10.8.0.4:8086` läuft in HTTP-Timeouts. Genauer: TCP-Verbindungsaufbau mit Timeout, keine HTTP-Antwort; `tls=0`, daher kein nachgewiesener TLS-Zertifikatsfehler.
- SD-Karteninitialisierung meldet Timeout.
- Display-Initialisierung meldet eine Warnung.
- WLAN funktioniert, nutzt jedoch 802.11n statt eines höheren WLAN-Modus.
- mDNS findet weder `_influxdb2._tcp` noch `_http._tcp`.
Diese Anwendungsprobleme sind unabhängig vom erfolgreich getesteten Flash-Workflow zu untersuchen.
Aktualisierung vom 07.11.2026: Für den NUC-WLAN-Access-Point ist die InfluxDB-Adresse `http://192.168.50.1:8086`. Die Einrichtung unter `linux-app/` kündigt `_influxdb2._tcp` über Avahi an. Den vorhandenen Avahi-Hostnamen verwenden; ein zusätzlicher statischer Alias auf dieselbe lokale IP verursachte in dieser Einrichtung `Local name collision`. Der Benutzer bestätigte die Auflösung auf dem WLAN und nach erneuter Konfiguration die funktionierende SEN54-Übertragung zu InfluxDB (Organisation `Home`, Bucket `nanoPSX`). Serielle Tests bestätigten zuvor die HTTP-Erreichbarkeit, aber Authentifizierungsfehler; die abschließende erfolgreiche Datenübertragung wurde vom Benutzer bestätigt. SD-Karten-Timeout und WLAN-Rückfall auf 11N wurden durch die Netzwerkeinrichtung nicht behoben. Tokens weiterhin ausschließlich lokal verwalten und nicht committen.
Der Upload selbst schreibt nicht in NVS. Die Anwendung kann NVS aber zur Laufzeit verändern und löscht NVS bei `ESP_ERR_NVS_NO_FREE_PAGES` oder `ESP_ERR_NVS_NEW_VERSION_FOUND` während der Initialisierung (`firmware/src/main.c`, `firmware/components/storage/src/storage.c`). Keine absolute Unveränderlichkeit von NVS nach Anwendungsstart zusichern. Beim Referenztest änderten sich WLAN-Journal-Einträge für `opmode`; die gültigen Einstellungswerte blieben im Vor-/Nachvergleich gleich.
## Dokumentation
Nach jedem erfolgreichen Hardwaretest dokumentieren:
- Zielboard und USB-Seriennummer
- Build-Environment
- Firmware-Hash
- Flash-Adressen
- Prüfergebnisse
- Boot- und Laufzeitlogs
- Erforderliche nächste Schritte
Temporäre Backups, Firmware-Binärdateien, SSH-Schlüssel und Logdateien dürfen nicht versehentlich in Git eingecheckt werden. Backups und Logs können Zugangsdaten enthalten und sind entsprechend geschützt außerhalb des Repositorys aufzubewahren.
Maschinenspezifische SSH-Schlüsselpfade, Host-Fingerprints, Docker-Mounts und absolute Backup-/Logpfade werden in lokalen Ergänzungen außerhalb des Repositorys gepflegt. Keine privaten Zugangsdaten oder lokalen Binärartefakte in diese Datei übernehmen.
+58
View File
@@ -0,0 +1,58 @@
# nanoPSX Roadmap
Die nächsten Entwicklungsschritte sind eine übersichtlichere Projektstruktur,
die gezielte Optimierung der eigenen Module und die dauerhafte Speicherung
der Messwerte auf einer SD-Karte. Alle drei Punkte sind offen; die Reihenfolge
entspricht der geplanten Priorität.
## 1 Eigenen Projektcode strukturieren
Ziel ist Code, den Menschen und KI leichter verstehen, ändern und prüfen können.
Der Umfang umfasst den selbst entwickelten Code im gesamten Projekt, einschließlich
Firmware, Serveranwendung, Werkzeugen und Tests. Herstellerbibliotheken, SDK und
unverändert übernommene Fremdkomponenten bleiben von der Umstrukturierung ausgenommen.
- [ ] Eigene Module, übernommene Bibliotheken und generierte Dateien erfassen und eindeutig unterscheiden.
- [ ] Große Module nach klaren Verantwortlichkeiten in kleinere Dateien aufteilen; zusammengehörige Logik zusammenhalten.
- [ ] Benennung, Verzeichnisstruktur und öffentliche Schnittstellen vereinheitlichen.
- [ ] Initialisierung, Hardwarezugriff, Datenverarbeitung, Anzeige und Netzwerklogik klar zuordnen.
- [ ] Eine kompakte Architekturübersicht mit Einstiegspunkten, Zuständigkeiten, Abhängigkeiten und Datenflüssen ergänzen.
- [ ] Generierte EEZ-Dateien weiterhin aus ihrer Quelle erzeugen; Anpassungen an der Struktur im Exporter berücksichtigen.
- [ ] Nach jeder abgegrenzten Umstrukturierung Build und passende Tests ausführen; das bisherige Verhalten erhalten.
**Ergebnis:** Kleine, verständliche Module mit klaren Aufgaben und dokumentierten
Schnittstellen. Zusätzliche Dateien entstehen dort, wo sie das Verständnis verbessern;
eine möglichst hohe Dateizahl ist kein eigenes Ziel.
## 2 Logik und Effizienz der eigenen Module prüfen
Jedes selbst entwickelte Modul einzeln durchgehen und untersuchen, ob seine Logik
einfacher, zuverlässiger oder sparsamer umgesetzt werden kann.
- [ ] Aufgaben, Zustände, Datenflüsse und Fehlerfälle jedes eigenen Moduls nachvollziehen.
- [ ] CPU-Zeit, RAM- und Stackbedarf sowie unnötige Speicherallokationen untersuchen.
- [ ] Blockierende Aufrufe, Warteschlangen, Task-Zusammenspiel und gemeinsame Datenzugriffe prüfen.
- [ ] Wiederholte Berechnungen, doppelte Logik und unnötige Hardware-, Netzwerk- oder Flashzugriffe erkennen.
- [ ] Verbesserungen nach messbarem Nutzen priorisieren und in kleinen Schritten umsetzen.
- [ ] Vorher und nachher vergleichen und die relevanten Normal- und Fehlerfälle testen.
**Ergebnis:** Nachvollziehbar effizientere Module. Messfrequenz, Messwertbedeutung,
Bedienung und bestehende Funktionen bleiben erhalten, sofern keine bewusste
Funktionsänderung vereinbart wird.
## 3 Messwerte auf SD-Karte speichern
Die Messwerte sollen zusätzlich zur InfluxDB-Übertragung dauerhaft lokal gespeichert
werden. Aktuell meldet die SD-Karteninitialisierung einen Timeout; dessen Ursache
muss vor der Integration des Datenloggers geklärt werden.
- [ ] SD-Anbindung, Verdrahtung, Pull-ups und Initialisierung prüfen und den bestehenden Timeout beheben.
- [ ] Ein geeignetes Dateiformat für Zeitstempel, Sensortyp, Messwerte und Einheiten festlegen.
- [ ] Einen separaten Schreibpfad mit begrenztem Puffer und gebündelten Schreibvorgängen integrieren.
- [ ] Sensorerfassung, Display und InfluxDB-Übertragung unabhängig von langsamen SD-Zugriffen weiterlaufen lassen.
- [ ] Dateirotation, Speichergrenzen und Verhalten bei voller, fehlender oder entfernter Karte festlegen.
- [ ] Nicht verfügbare Messwerte und eine noch fehlende UTC-Zeit eindeutig kennzeichnen.
- [ ] Lesen und Auswerten der Dateien sowie Neustart, Schreibfehler und Unterbrechungen testen.
**Ergebnis:** Dauerhaft gespeicherte und auswertbare Messdateien auf der SD-Karte.
Probleme mit der Karte werden angezeigt und verhindern den übrigen Gerätebetrieb nicht.
+2012 -13
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -5,6 +5,7 @@
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
"ms-vscode.cpptools-extension-pack",
"pioarduino.pioarduino-ide"
]
}
+4
View File
@@ -1,3 +1,7 @@
cmake_minimum_required(VERSION 3.16.0)
# Avoid LVGL Kconfig failures from the optional component update scan.
set(ENV{IDF_COMPONENT_CHECK_NEW_VERSION} "0")
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(lcd_demo)
+299
View File
@@ -0,0 +1,299 @@
# Sensor und Board auswählen
Die zentrale Konfiguration steht in
[`components/hardware_config/hardware_config.h`](components/hardware_config/hardware_config.h).
Es handelt sich um eine **Build-Konfiguration**: Nach Änderungen neu kompilieren
und die passende Firmware übertragen. Das Webportal verwaltet weiterhin WLAN
und InfluxDB; es ändert den Sensortreiber nicht zur Laufzeit.
## Die zwei Auswahleinstellungen
Aktueller Standard: SEN66 mit Display, Sensor weiterhin an GPIO7/8:
```c
#define NANOPSX_SENSOR NANOPSX_SENSOR_SEN66
#define NANOPSX_BOARD NANOPSX_BOARD_C6_DISPLAY_8MB
```
Für einen SEN66 an GPIO7/8 ohne Display:
```c
#define NANOPSX_SENSOR NANOPSX_SENSOR_SEN66
#define NANOPSX_BOARD NANOPSX_BOARD_C6_DEVKIT_8MB
```
Für den bisher getesteten SEN54 am nanoPSX-Display-Board:
```c
#define NANOPSX_SENSOR NANOPSX_SENSOR_SEN54
#define NANOPSX_BOARD NANOPSX_BOARD_C6_DISPLAY_8MB
```
Diese beiden Zeilen im jeweiligen `#ifndef`-Block der Konfigurationsdatei ändern.
Sensor und Board sind unabhängig wählbar: Auch ein SEN54 am Devkit oder ein
SEN66 am gemeinsamen Display-Bus sind möglich, wenn die Verdrahtung dem
ausgewählten Profil entspricht.
| Boardprofil | Hardware-I²C SDA | Hardware-I²C SCL | I²C-Port | Peripherie |
| --- | --- | --- | --- | --- |
| `NANOPSX_BOARD_C6_DISPLAY_8MB` | GPIO18 | GPIO19 | 0 | Bestehendes LCD, Touch, SD, Batterie und Taste |
| `NANOPSX_BOARD_C6_DEVKIT_8MB` | GPIO7 | GPIO8 | 0 | Sensor, WLAN, Konfigurationsportal, InfluxDB; keine Display-/SD-/Tasteninitialisierung |
| Sensor | I²C-Adresse | Takt | Messgrößen |
| --- | --- | --- | --- |
| SEN54 | `0x69` | 400 kHz | PM1/2.5/4/10, Temperatur, Feuchte, VOC |
| SEN66 | `0x6b` | 100 kHz | PM1/2.5/4/10, Temperatur, Feuchte, VOC, NOx, CO₂ |
SEN54 verwendet die Hardware-I²C-Pins aus dem Boardprofil. SEN66 bleibt
unabhängig vom Profil an **SDA GPIO7 / SCL GPIO8**. Beim Display-Profil benutzt
der Touchscreen den Hardware-I²C-Controller auf GPIO18/19; der SEN66 erhält einen
separaten Software-I²C-Bus auf GPIO7/8. Damit muss der Sensor beim Wechsel zum
Display-Profil nicht umgesteckt werden. Ohne Display wird für GPIO7/8 der
Hardware-Controller verwendet.
Der Software-Bus nutzt ausschließlich Open-Drain-Ausgänge mit internen Pull-ups,
ACK/NACK-Prüfung, Clock-Stretching mit begrenztem Timeout und einen Mutex.
Der Solltakt beträgt 100 kHz; GPIO-Aufrufe und Interrupts können den tatsächlichen
Takt verringern. Die elektrische Verdrahtung und externe Pull-ups entsprechend
dem Sensordatenblatt prüfen. GPIO-Nummern sind keine Steckkontakt-Nummern.
Ein fehlender Touchcontroller wird nach Reset per ACK-Probe erkannt. Die
Firmware protokolliert dies und aktiviert den LVGL-Toucheingang nur bei
vorhandenem Controller. LCD, Sensor und Netzwerk können ohne Touch weiterlaufen.
## Kompilieren
Aus dem Repository-Hauptverzeichnis:
```bash
pio run -d firmware -e esp32-c6-devkitc-1 -j 2
```
Die bekannten Profile setzen ESP32-C6 und **8 MB Flash** voraus. PlatformIO bleibt
auf `espressif32@6.12.0` und ESP-IDF 5.5.0 festgelegt. Der Build bricht ab, wenn
ein unbekanntes Profil, ein anderer Chip oder eine SDK-Konfiguration für eine
andere Flash-Größe ausgewählt wurde. Ein Profil ersetzt keine Boarderkennung.
Für weitere Boards einen neuen expliziten Profilzweig mit eigener Pinbelegung
und Peripherieauswahl hinzufügen. Bei anderen ESP32-Chips oder Flash-Größen
zusätzlich ein passendes PlatformIO-Environment, SDK-Defaults und eine passende
Partitionstabelle einrichten und prüfen. Die aktuelle 8-MB-Partitionstabelle
nicht auf das bekannte 4-MB-Board übertragen. Die zwei vorhandenen Profile
sind keine pauschale Freigabe für andere ESP32-Modelle.
## Treiber und Daten
Der SEN66 verwendet den offiziellen Sensirion-C-Treiber. Der genaue Quellstand,
die Lizenz und die unverändert übernommenen Dateien stehen in
[`SENSIRION-UPSTREAM.md`](components/sen5x/SENSIRION-UPSTREAM.md).
Der Verzeichnisname `sen5x` bleibt aus Kompatibilität bestehen; darin liegen
beide Treiber und die gemeinsame Anwendung `air_sensor_app.c`.
Die Sensoren teilen sich den ESP-IDF-HAL und die Verarbeitung für Anzeige und
InfluxDB. Die Messreihe bleibt `air`, bestehende Felder bleiben
`pm1`, `pm2_5`, `pm4`, `pm10`, `temp`, `rh`, `voc`, `nox`.
SEN66 ergänzt `co2` in ppm. Nicht verfügbare Messgrößen und die vom Sensor
definierten ungültigen Rohwerte werden ausgelassen, nicht als Null übertragen.
Insbesondere erzeugt SEN54 keine künstlichen CO₂-Werte. Die Displayoberfläche entspricht der bisherigen SEN54-Ansicht einschließlich
Schriftzug und Statussymbolen. **NOx und CO₂ werden vorerst nicht auf dem Display
angezeigt.** Diese Werte bleiben für InfluxDB verfügbar; CO₂ erscheint außerdem
in den seriellen SEN66-Messwertmeldungen. Eine erweiterte Displayansicht ist
für einen späteren Auftrag vorgesehen.
Die Anwendung prüft die Datenbereitschaft etwa einmal pro Sekunde und
protokolliert alle zehn erfolgreichen Messungen einen Datensatz ohne
Zugangsdaten. Beim Start meldet sie Boardprofil, Sensor, Pins und Takt; beim
SEN66 wird zusätzlich der Produktname gelesen und geprüft. Sensorkalibrierung,
CO₂-Zwangskalibrierung und Sensoreinstellungen werden nicht automatisch geändert.
## Tests
Mit einem nativen C-Compiler auf Linux, aus dem Repository-Hauptverzeichnis:
```bash
bash firmware/test/sensors/run.sh
```
Diese Tests verwenden die echten SEN54-/SEN66-Treiber mit einer simulierten
I²C-HAL. Sie prüfen Geräteadressen, verschiedene Messbefehle, Datenrahmen,
vorzeichenbehaftete Werte, ungültige Rohwerte, CRC-Fehler und Übertragungsfehler.
Der separate Software-Bus wird zusätzlich auf START/STOP, Adress-/Datenbits,
ACK/NACK, Clock-Stretching, begrenzten Timeout und Freigabe der Leitungen geprüft.
Alle vier Kombinationen der Board-/Sensorauswahl und die Zurückweisung
unbekannter Profile werden ebenfalls geprüft. Das ersetzt keine elektrische
oder vollständige Hardwareprüfung.
Für vollständige ESP-IDF-Builds der Referenzkombinationen kann die Auswahl
vorübergehend pro Prozess überschrieben werden, ohne die Konfigurationsdatei
zu ändern:
```bash
PLATFORMIO_BUILD_FLAGS='-DNANOPSX_SENSOR=54 -DNANOPSX_BOARD=1' pio run -d firmware -e esp32-c6-devkitc-1 -j 2
PLATFORMIO_BUILD_FLAGS='-DNANOPSX_SENSOR=66 -DNANOPSX_BOARD=2' pio run -d firmware -e esp32-c6-devkitc-1 -j 2
```
Die letzte Kompilierung bestimmt den Inhalt von `.pio/build/.../firmware.bin`.
Vor einem Upload immer Auswahl, Build-Erfolg und Image-Hash neu prüfen.
## Vor einem Upload
Den Workflow aus `../AGENTS.md` einhalten: Board über USB-Seriennummer auswählen,
vollständiges Backup bereitstellen und das tatsächlich aktive Partitionslayout
lesen. Eine andere Sensorauswahl benötigt normalerweise nur ein App-Update;
NVS mit WLAN-/Influx-Einstellungen muss dafür nicht gelöscht werden.
Das bekannte Board `CC:BA:97:F2:5F:7C` hatte zunächst eine einzelne
Factory-Partition von 1 MiB bei `0x10000`. Nach ausdrücklicher Freigabe wurde es
am 09.11.2026 ohne vollständiges Löschen auf das nanoPSX-8-MB-Layout mit
`ota_0` bei `0x20000` umgestellt. Die neue Partitionstabelle wurde zuletzt
aktiviert; NVS und Bootloader wurden erhalten und der alte PHY-Partitionsinhalt
an die neue Adresse kopiert. Der gültige OTA-Datensatz wählt `ota_0`.
Für einen weiteren Upload das aktuelle Layout trotzdem erneut auslesen.
Adressen, Images und frühere Einzelfreigaben niemals ungeprüft übernehmen.
Ein vollständiges Löschen ist für einen Sensorwechsel nicht nötig und nicht
automatisch freigegeben.
## Prüfstand vom 09.11.2026
- Vollständige ESP-IDF-Builds für alle vier Kombinationen (SEN54/SEN66,
jeweils Devkit ohne Display/Display-Board): erfolgreich. Dabei wurde die
Auswahl direkt in der zentralen Konfigurationsdatei gewechselt. Die fertigen
ELF-Dateien enthalten jeweils nur den gewählten Sensortreiber. Abschließend
wurden die Standardauswahl und das zugehörige Build-Artefakt
wiederhergestellt.
- Native Treiber-/CRC-/Fehlertests und Auswahltests: erfolgreich.
- Hardwaretest auf `CC:BA:97:F2:5F:7C`, ESP32-C6FH8, 8 MB: neue SEN66-Firmware
mit Display migriert und alle vier geschriebenen Bereiche vollständig
bytegenau sowie per SHA256 bestätigt. Eine vollständige Rückleseprüfung der
8 MB bestätigt zusätzlich den Schutz der übrigen Flash-Bereiche.
- 60 Sekunden Laufzeit ohne erkannte Panic oder Sensor-I²C-Fehler. SEN66
identifiziert, laufende Messungen über Software-I²C GPIO7/8, Displayinitialisierung
erfolgreich, kein Touch-Ausfall gemeldet. Die Anzeige entspricht nach Benutzerkorrektur wieder der bisherigen
SEN54-Ansicht, ohne zusätzliche NOx-/CO₂-Felder. Die sichtbare Anzeige muss am
Gerät beurteilt werden, da das Gateway kein Displaybild liefert.
- Standardauswahl ist jetzt **SEN66 mit Display**. Der bisherige separate
Standalone-SEN66-Build ist auf diesem Board ersetzt. Ein vollständiges Backup
liegt geschützt außerhalb des Repositorys vor.
- Der SD-Karten-Timeout besteht weiter. Im Test war der Setup-AP `nanoPSX`
mit Portal `http://192.168.4.1` aktiv; keine STA-IP oder erfolgreichen
Influx-Schreibvorgänge beobachtet. WLAN und bei Bedarf Organisation `Home` /
Bucket `nanoPSX` im Portal einstellen; Tokens lokal eingeben.
## Displayseiten und Bedienung
Die vier EEZ-Seiten sind `Main` (bisherige Messwertansicht), `Page_2` (Raumluft),
`History` (Verlauf) und `Device` (Gerät). Nach links zur nächsten, nach rechts zur
vorherigen Seite wischen; an den äußeren Seiten gibt es keinen Umlauf. Vier kleine
Markierungen am oberen Rand zeigen die aktuelle Seite. Tippen auf ein Statussymbol
der Hauptseite öffnet die Geräteseite. Dropdowns und Helligkeitsregler verarbeiten
ihre Berührungen selbst, ohne dabei versehentlich die Seite zu wechseln.
- Raumluft: CO₂ in ppm, VOC-/NOx-Index und ein kleiner CO₂-Verlauf. Nicht verfügbare
Kanäle erscheinen als `--`; SEN54 erzeugt keine künstlichen CO₂-Werte.
- Verlauf: Auswahl zwischen CO₂, PM2.5, Temperatur, Feuchte, VOC und NOx. Gezeigt
werden 180 Zehn-Sekunden-Mittelwerte über die letzten 30 Minuten. Die angezeigte
Wertespanne entspricht der automatisch angepassten Diagrammachse. Fehlende
Zeitabschnitte bleiben Lücken. Der feste RAM-Ringpuffer wird bei Neustart geleert;
SD-Karte, WLAN und InfluxDB sind für den lokalen Verlauf nicht erforderlich.
- Gerätestatus: WLAN/IP, Alter der letzten bestätigten Influx-Übertragung (HTTP 204)
und Sensoraktualität. Ein WLAN-Erfolg gilt nicht als erfolgreiche Datenübertragung.
- Helligkeit: 20–100 %, Standard 100 %. Automatisches Abdunkeln: aus oder nach
30/60/120 Sekunden, Standard 60 Sekunden. Abgedunkelt wird auf 15 %. Die erste
Berührung weckt nur das Display und wird bis zum Loslassen verbraucht.
- Display-Einstellungen werden erst nach Änderung gespeichert: Helligkeit beim
Loslassen, Zeitwahl beim Auswählen. Eigener NVS-Namespace `ui_display`, keine
WLAN-/Influx-Einstellungen. Beim ersten Start werden nur die Defaults gelesen.
- Vor dem ersten Sensorpaket erscheint ein Starthinweis. Nach mehr als fünf
Sekunden ohne erfolgreiches Paket werden die aktuellen Anzeigen als veraltet
markiert und die Zahlen durch `--` ersetzt; der vorhandene Verlauf bleibt sichtbar.
## EEZ-Projekt und Firmware zusammen bearbeiten
`eez/nanopsx.eez-project` enthält Layout, Beschriftungen, Namen und Grundkonfiguration
der Widgets. PlatformIO ruft vor jedem Build `tools/export_display.py` auf und hält
`screens.c`/`screens.h` automatisch synchron. Kein manueller EEZ-Studio-Export nötig.
Der projektspezifische Exporter unterstützt die hier verwendeten statischen Screen-,
Panel-, Label-, Image-, Chart-, Slider- und Dropdown-Widgets und deren verwendete
Stile. Nicht unterstützte Widgettypen/Stile brechen den Build ab, statt unbemerkt
wegzufallen; bei Erweiterungen zuerst den Exporter ergänzen. EEZ Flow bleibt aus.
Navigation, dynamische Texte, Chart-Daten, Touch-Aufwecken und Einstellungen liegen
außerhalb der generierten Dateien in `ui_navigation.c`, `ui_dashboard.c` und
`ui_model.c`. Diese werden nach `ui_init()` unter dem LVGL-Lock initialisiert.
Der Sensorproducer übergibt skalierte Zahlen an `ui_model_publish()` und ruft
keine LVGL-Funktionen auf. Snapshot und begrenzter Ringpuffer sind auf dem ESP
mit einem Spinlock geschützt. Die Diagramme werden im GUI-Task aktualisiert.
Prüfungen aus dem Repository-Hauptverzeichnis:
```bash
python3 firmware/tools/export_display.py --check
python3 firmware/test/ui/run_tests.py
bash firmware/test/sensors/run.sh
```
Die UI-Tests verwenden echte LVGL-Quellen und exportierte Displayobjekte bei
48 KiB LVGL-Speicher. Sie prüfen vierseitige Navigation, Tippen, kurze/vertikale
Gesten, äußere Grenzen, Kindobjekte, Dropdown-Isolation, Helligkeitsregler,
Aufweckberührung, Abdunkeln, fehlende/veraltete Werte und Verlaufsmittelwerte,
Lücken und Verdrängung alter Daten. Voraussetzung sind ein C-Compiler und die
bereits aufgelöste LVGL-Komponente unter `firmware/managed_components`.
Ein optionaler Verzeichnispfad hinter dem UI-Testbefehl speichert vier gerenderte
PPM-Vorschauen mit simulierten Messwerten. Physische Darstellung und Fingerbedienung
müssen zusätzlich am Gerät geprüft werden.
## Effiziente InfluxDB-Übertragung
Der Sensor misst weiter mit 1 Hz. Der Influx-Worker bündelt bis zu zehn einzelne
Messpunkte in einer HTTP-Anfrage; spätestens zehn Sekunden nach Beginn eines
Pakets wird auch ein kleineres Restpaket versendet. Ein Paket ist zusätzlich auf
4096 Bytes begrenzt. Keine Mittelung oder Änderung der Influx-Feldnamen/Einheiten;
Display und lokaler Verlauf aktualisieren sich unabhängig vom Netzwerk weiter.
Im normalen 1-Hz-Betrieb entstehen etwa sechs Schreibanfragen pro Minute statt 60,
mit bis zu etwa zehn Sekunden zusätzlicher Sichtbarkeitsverzögerung auf dem Server.
Jeder Punkt erhält einen eigenen Zeitstempel mit `precision=ms`. Der Messzeitpunkt
wird beim Einreihen über den monotonen ESP-Timer erfasst. Ein einmaliger GET auf
`/health` liest den HTTP-`Date`-Header desselben Influx-Servers und richtet damit
nur die interne Messuhr aus; weder ein Internet-Zeitdienst noch eine Änderung der
Systemuhr ist nötig. HTTP Date besitzt Sekundenauflösung: Die absolute Zuordnung
ist entsprechend ungefähr sekundengenau; die Abstände der Sekundenmessungen
bleiben erhalten. Spätere Date-Header gleichen größere Uhrdrift vorsichtig aus.
Explizite Zeitstempel der API bleiben erhalten. Fehlt ein gültiges Date vollständig,
werden sichere Einzelpunkt-Anfragen mit Serverzeit verwendet, bis eine Zeitbasis
verfügbar ist. Mehrere ungestempelte Punkte derselben Serie werden nicht gebündelt.
HTTP-Client und Verbindung werden über mehrere Anfragen wiederverwendet. Ein
Konfigurationswechsel oder Verbindungsfehler verwirft den Handle; der nächste
Versuch baut ihn neu auf. Es werden keine Token oder Messwert-Payloads protokolliert.
Der Worker meldet HTTP-Status, Punkt-/Bytezahl, erste/letzte UTC-Zeit im Paket und
gezählte Verbindungsaufbauten. Die Gerätestatusanzeige zählt nur bestätigte HTTP 204
als erfolgreiche Übertragung; ihr Alter kann jetzt regulär etwa zehn Sekunden betragen.
Der RAM-Puffer enthält 32 vorserialisierte Punkte ohne einzelne Heap-Allokationen
für jeden Feldnamen/Wert. Ein Paket bleibt bei Transportfehlern, Rate-Limits oder
Serverproblemen mit unverändertem Inhalt und Zeitstempeln für einen erneuten
Versuch erhalten (exponentielle Pause von 2 s bis maximal 300 s). Fünf Fehler lösen
ein Neuladen der vorhandenen Konfiguration aus. HTTP 400/413/422 wird als abgelehntes
Paket protokolliert und verworfen; bereits teilweise geschriebene Daten werden dabei
nicht gelöscht. Ohne Zeitbasis werden fehlgeschlagene Einzelpunkte nicht automatisch
wiederholt, da deren Serverzeit sonst neue Punkte erzeugen könnte.
Bei längerem Ausfall ersetzt die volle Warteschlange die ältesten noch nicht
versendeten Punkte; die Verluste werden gezählt und protokolliert. Puffer und
laufendes Paket sind RAM-basiert und gehen bei Neustart verloren. Der Producer
wartet nicht auf HTTP. Beim Stoppen räumt der Worker seine Ressourcen selbst auf;
er wird nicht mitten in einer Anfrage gewaltsam beendet.
Nativer Test mit dem echten Worker und simuliertem FreeRTOS/HTTP unter Address- und
UndefinedBehavior-Sanitizer, vom Repository-Hauptverzeichnis:
```bash
python3 firmware/test/net_influx/run_tests.py
```
Prüft Serialisierung/escaping, fehlende Kanäle, UTC-/Kalenderkonvertierung,
Messzeitabstände, 10er-Pakete, Wiederholungen mit identischem Body, Warteschlangen-
Überlauf, fehlende Zeitbasis, Einzelpunktfehler, Zeitlimit bei Restpaketen,
Bytegrenzen, dauerhaft abgelehnte Pakete und Wiederverwendung/Freigabe des Clients.
@@ -1,6 +1,9 @@
idf_component_register(
SRCS
"ui.c"
"ui_navigation.c"
"ui_dashboard.c"
"ui_model.c"
"images.c"
"screens.c"
"styles.c"
File diff suppressed because it is too large Load Diff
+64 -26
View File
@@ -1,15 +1,22 @@
#ifndef EEZ_LVGL_UI_SCREENS_H
#define EEZ_LVGL_UI_SCREENS_H
/* Generated by firmware/tools/export_display.py from the EEZ project. */
#pragma once
#include <lvgl.h>
#ifdef __cplusplus
extern "C" {
#endif
typedef struct _objects_t {
typedef struct {
lv_obj_t *main;
lv_obj_t *page_2;
lv_obj_t *history;
lv_obj_t *device;
lv_obj_t *obj0;
lv_obj_t *obj5;
lv_obj_t *obj6;
lv_obj_t *obj7;
lv_obj_t *obj8;
lv_obj_t *obj9;
lv_obj_t *obj10;
lv_obj_t *obj11;
lv_obj_t *obj1;
lv_obj_t *obj2;
lv_obj_t *obj3;
@@ -20,32 +27,63 @@ typedef struct _objects_t {
lv_obj_t *influx_off;
lv_obj_t *mdns_ok;
lv_obj_t *mdns_off;
lv_obj_t *obj5;
lv_obj_t *obj6;
lv_obj_t *obj7;
lv_obj_t *obj8;
lv_obj_t *obj9;
lv_obj_t *obj10;
lv_obj_t *obj11;
lv_obj_t *main_notice;
lv_obj_t *page_dot_0_0;
lv_obj_t *page_dot_0_1;
lv_obj_t *page_dot_0_2;
lv_obj_t *page_dot_0_3;
lv_obj_t *page_2_title;
lv_obj_t *room_state;
lv_obj_t *room_co2;
lv_obj_t *room_unit;
lv_obj_t *room_voc;
lv_obj_t *room_nox;
lv_obj_t *room_chart;
lv_obj_t *room_chart_caption;
lv_obj_t *page_dot_1_0;
lv_obj_t *page_dot_1_1;
lv_obj_t *page_dot_1_2;
lv_obj_t *page_dot_1_3;
lv_obj_t *history_title;
lv_obj_t *history_metric;
lv_obj_t *history_range;
lv_obj_t *history_chart;
lv_obj_t *history_caption;
lv_obj_t *page_dot_2_0;
lv_obj_t *page_dot_2_1;
lv_obj_t *page_dot_2_2;
lv_obj_t *page_dot_2_3;
lv_obj_t *device_title;
lv_obj_t *device_wifi;
lv_obj_t *device_influx;
lv_obj_t *device_sensor;
lv_obj_t *brightness_label;
lv_obj_t *brightness;
lv_obj_t *dim_label;
lv_obj_t *dim_timeout;
lv_obj_t *page_dot_3_0;
lv_obj_t *page_dot_3_1;
lv_obj_t *page_dot_3_2;
lv_obj_t *page_dot_3_3;
} objects_t;
extern objects_t objects;
enum ScreensEnum {
SCREEN_ID_MAIN = 1,
SCREEN_ID_PAGE_2 = 2,
SCREEN_ID_HISTORY = 3,
SCREEN_ID_DEVICE = 4,
};
void create_screen_main();
void tick_screen_main();
void tick_screen_by_id(enum ScreensEnum screenId);
void create_screen_main(void);
void tick_screen_main(void);
void create_screen_page_2(void);
void tick_screen_page_2(void);
void create_screen_history(void);
void tick_screen_history(void);
void create_screen_device(void);
void tick_screen_device(void);
void create_screens(void);
void tick_screen(int screen_index);
void create_screens();
void tick_screen_by_id(enum ScreensEnum screen_id);
#ifdef __cplusplus
}
#endif
#endif /*EEZ_LVGL_UI_SCREENS_H*/
+204
View File
@@ -0,0 +1,204 @@
#include "ui_dashboard.h"
#include "ui_model.h"
#include "ui.h"
#include "fonts.h"
#include <math.h>
#include <stdio.h>
static ui_display_config_t config;
static ui_brightness_cb_t set_brightness;
static ui_save_config_cb_t save_config;
static lv_chart_series_t *room_series, *history_series;
static uint32_t last_activity;
static bool initialized, dimmed, suppress_touch;
static const uint16_t dim_seconds[] = {0, 30, 60, 120};
static const char *units[] = {"ppm", "µg/m³", "°C", "%", "Index", "Index"};
static void update_brightness_label(void)
{
lv_label_set_text_fmt(objects.brightness_label, "Licht %u%%", config.brightness);
}
static void settings_event(lv_event_t *event)
{
lv_obj_t *target = lv_event_get_target(event);
if (target == objects.brightness) {
config.brightness = (uint8_t)lv_slider_get_value(target);
set_brightness(config.brightness);
update_brightness_label();
/* Dragging previews immediately, persistence happens only on release. */
if (lv_event_get_code(event) == LV_EVENT_RELEASED && save_config) save_config(&config);
} else if (target == objects.dim_timeout) {
unsigned selected = lv_dropdown_get_selected(target);
if (selected < sizeof(dim_seconds) / sizeof(dim_seconds[0])) {
config.dim_after_s = dim_seconds[selected];
if (save_config) save_config(&config);
}
}
last_activity = lv_tick_get();
}
static void status_clicked(lv_event_t *event)
{
(void)event;
loadScreen(SCREEN_ID_DEVICE);
}
void ui_dashboard_init(ui_display_config_t selected, ui_brightness_cb_t brightness,
ui_save_config_cb_t save)
{
config = selected;
if (config.brightness < 20 || config.brightness > 100) config.brightness = 100;
unsigned dim_index = 2;
for (unsigned i = 0; i < 4; ++i) if (config.dim_after_s == dim_seconds[i]) dim_index = i;
config.dim_after_s = dim_seconds[dim_index];
set_brightness = brightness;
save_config = save;
dimmed = suppress_touch = false;
last_activity = lv_tick_get();
initialized = true;
lv_slider_set_value(objects.brightness, config.brightness, LV_ANIM_OFF);
lv_obj_set_ext_click_area(objects.brightness, 12);
lv_dropdown_set_selected(objects.dim_timeout, dim_index);
update_brightness_label();
/* Custom Ubuntu fonts do not contain LVGL's private-use arrow glyphs. */
lv_obj_set_style_text_font(objects.history_metric, LV_FONT_DEFAULT, LV_PART_INDICATOR);
lv_obj_set_style_text_font(objects.dim_timeout, LV_FONT_DEFAULT, LV_PART_INDICATOR);
lv_obj_add_event_cb(objects.brightness, settings_event, LV_EVENT_VALUE_CHANGED, NULL);
lv_obj_add_event_cb(objects.brightness, settings_event, LV_EVENT_RELEASED, NULL);
lv_obj_add_event_cb(objects.dim_timeout, settings_event, LV_EVENT_VALUE_CHANGED, NULL);
lv_obj_t *icons[] = {objects.wifi_ok, objects.wifi_off, objects.influx_ok,
objects.influx_off, objects.mdns_ok, objects.mdns_off};
for (unsigned i = 0; i < sizeof(icons) / sizeof(icons[0]); ++i) {
lv_obj_add_flag(icons[i], LV_OBJ_FLAG_CLICKABLE);
lv_obj_add_event_cb(icons[i], status_clicked, LV_EVENT_CLICKED, NULL);
}
lv_chart_set_point_count(objects.room_chart, UI_HISTORY_POINTS);
lv_chart_set_point_count(objects.history_chart, UI_HISTORY_POINTS);
room_series = lv_chart_add_series(objects.room_chart, lv_color_hex(0x62D6C5), LV_CHART_AXIS_PRIMARY_Y);
history_series = lv_chart_add_series(objects.history_chart, lv_color_hex(0x62D6C5), LV_CHART_AXIS_PRIMARY_Y);
lv_chart_set_all_value(objects.room_chart, room_series, LV_CHART_POINT_NONE);
lv_chart_set_all_value(objects.history_chart, history_series, LV_CHART_POINT_NONE);
lv_obj_set_style_size(objects.room_chart, 0, LV_PART_INDICATOR);
lv_obj_set_style_size(objects.history_chart, 0, LV_PART_INDICATOR);
lv_obj_set_style_line_width(objects.room_chart, 2, LV_PART_ITEMS);
lv_obj_set_style_line_width(objects.history_chart, 2, LV_PART_ITEMS);
set_brightness(config.brightness);
}
void ui_dashboard_filter_touch(lv_indev_data_t *data)
{
if (!initialized) return;
const bool pressed = data->state == LV_INDEV_STATE_PRESSED;
if (pressed) {
last_activity = lv_tick_get();
if (dimmed) {
dimmed = false;
suppress_touch = true;
set_brightness(config.brightness);
}
}
if (suppress_touch) {
data->state = LV_INDEV_STATE_RELEASED;
if (!pressed) suppress_touch = false;
}
}
static void format_value(lv_obj_t *label, const char *prefix, float value, unsigned decimals)
{
if (!isfinite(value)) lv_label_set_text_fmt(label, "%s--", prefix);
else {
/* LVGL's compact printf is built without floating-point support. */
char text[64];
snprintf(text, sizeof(text), "%s%.*f", prefix, (int)decimals, (double)value);
lv_label_set_text(label, text);
}
}
static void fill_chart(lv_obj_t *chart, lv_chart_series_t *series,
ui_metric_t metric, uint64_t now_ms, lv_obj_t *range_label)
{
float values[UI_HISTORY_POINTS];
ui_model_history(metric, now_ms, values);
float low = INFINITY, high = -INFINITY;
for (unsigned i = 0; i < UI_HISTORY_POINTS; ++i) {
if (isfinite(values[i])) {
if (values[i] < low) low = values[i];
if (values[i] > high) high = values[i];
}
}
/* Values use tenths in the plot. Never overflow LVGL's 16-bit coordinates. */
const float scale = metric == UI_METRIC_CO2 ? 1.0f : 10.0f;
int minimum = isfinite(low) ? (int)floorf(low * scale) : 0;
int maximum = isfinite(high) ? (int)ceilf(high * scale) : 10;
int margin = (maximum - minimum) / 10;
if (margin < 5) margin = 5;
minimum -= margin; maximum += margin;
if (metric != UI_METRIC_TEMP && minimum < 0) minimum = 0;
if (minimum < -32000) minimum = -32000;
if (maximum > 32000) maximum = 32000;
if (maximum <= minimum) maximum = minimum + 1;
lv_chart_set_range(chart, LV_CHART_AXIS_PRIMARY_Y, minimum, maximum);
for (unsigned i = 0; i < UI_HISTORY_POINTS; ++i) {
float value = values[i] * scale;
series->y_points[i] = !isfinite(value) ? LV_CHART_POINT_NONE :
(lv_coord_t)lroundf(fminf(32000, fmaxf(-32000, value)));
}
lv_chart_refresh(chart);
if (range_label) {
if (isfinite(low)) {
char text[64];
snprintf(text, sizeof(text), "%.0f..%.0f %s", minimum / scale, maximum / scale, units[metric]);
lv_label_set_text(range_label, text);
}
else lv_label_set_text(range_label, "Noch keine Daten");
}
}
void ui_dashboard_tick(uint64_t now_ms, const ui_device_status_t *status)
{
if (!initialized) return;
lv_obj_t *on[] = {objects.wifi_ok, objects.influx_ok, objects.mdns_ok};
lv_obj_t *off[] = {objects.wifi_off, objects.influx_off, objects.mdns_off};
bool ok[] = {status->wifi_connected, status->influx_ok, status->mdns_ok};
for (unsigned i = 0; i < 3; ++i) {
lv_obj_add_flag(ok[i] ? off[i] : on[i], LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(ok[i] ? on[i] : off[i], LV_OBJ_FLAG_HIDDEN);
}
if (!dimmed && config.dim_after_s &&
lv_tick_elaps(last_activity) >= (uint32_t)config.dim_after_s * 1000) {
dimmed = true;
set_brightness(15);
}
ui_sample_t sample;
ui_model_snapshot(&sample);
const uint64_t age = sample.available && now_ms >= sample.timestamp_ms ? now_ms - sample.timestamp_ms : 0;
const bool fresh = sample.available && now_ms >= sample.timestamp_ms && age <= UI_SENSOR_STALE_MS;
const char *state = !sample.available ? "Sensor startet ..." : fresh ? "Live / 1 Messung pro Sekunde" : "Messwerte veraltet";
lv_label_set_text(objects.room_state, state);
if (fresh) lv_obj_add_flag(objects.main_notice, LV_OBJ_FLAG_HIDDEN);
else {
lv_obj_clear_flag(objects.main_notice, LV_OBJ_FLAG_HIDDEN);
lv_label_set_text(objects.main_notice, state);
lv_obj_t *values[] = {objects.obj5, objects.obj6, objects.obj7, objects.obj8,
objects.obj9, objects.obj10, objects.obj11};
for (unsigned i = 0; i < sizeof(values) / sizeof(values[0]); ++i) lv_label_set_text(values[i], "--");
}
format_value(objects.room_co2, "", fresh ? sample.values[UI_METRIC_CO2] : NAN, 0);
format_value(objects.room_voc, "VOC-Index ", fresh ? sample.values[UI_METRIC_VOC] : NAN, 0);
format_value(objects.room_nox, "NOx-Index ", fresh ? sample.values[UI_METRIC_NOX] : NAN, 0);
if (fresh && !isfinite(sample.values[UI_METRIC_CO2]))
lv_label_set_text(objects.room_state, "CO2-Kanal nicht verfügbar");
fill_chart(objects.room_chart, room_series, UI_METRIC_CO2, now_ms, NULL);
unsigned metric = lv_dropdown_get_selected(objects.history_metric);
if (metric >= UI_METRIC_COUNT) metric = UI_METRIC_CO2;
fill_chart(objects.history_chart, history_series, (ui_metric_t)metric, now_ms, objects.history_range);
lv_label_set_text_fmt(objects.device_wifi, "WLAN: %s", status->wifi_connected ? status->ip : "nicht verbunden");
if (status->last_influx_success_ms && now_ms >= status->last_influx_success_ms) {
unsigned seconds = (unsigned)((now_ms - status->last_influx_success_ms) / 1000);
if (seconds < 60) lv_label_set_text_fmt(objects.device_influx, "Influx: vor %u s / %s", seconds, status->influx_ok ? "OK" : "Fehler");
else lv_label_set_text_fmt(objects.device_influx, "Influx: vor %u min / %s", seconds / 60, status->influx_ok ? "OK" : "Fehler");
} else lv_label_set_text(objects.device_influx, "Influx: noch keine Übertragung");
if (!sample.available) lv_label_set_text(objects.device_sensor, "Sensor: startet / wartet auf Daten");
else lv_label_set_text_fmt(objects.device_sensor, "Sensor: %s / vor %u s", fresh ? "OK" : "veraltet", (unsigned)(age / 1000));
}
@@ -0,0 +1,23 @@
#pragma once
#include <lvgl.h>
#include <stdbool.h>
#include <stdint.h>
typedef struct {
uint8_t brightness; /* 20..100 percent */
uint16_t dim_after_s; /* 0, 30, 60, 120 */
} ui_display_config_t;
typedef struct {
bool wifi_connected, influx_ok, mdns_ok;
char ip[16];
uint64_t last_influx_success_ms; /* zero until first successful HTTP 204 */
} ui_device_status_t;
typedef void (*ui_brightness_cb_t)(uint8_t percent);
typedef void (*ui_save_config_cb_t)(const ui_display_config_t *config);
/* All calls run on the LVGL task or while its lock is held. */
void ui_dashboard_init(ui_display_config_t config, ui_brightness_cb_t brightness,
ui_save_config_cb_t save);
void ui_dashboard_tick(uint64_t now_ms, const ui_device_status_t *status);
/* Wrap the touch read callback, so the wake-up touch cannot activate controls. */
void ui_dashboard_filter_touch(lv_indev_data_t *data);
+65
View File
@@ -0,0 +1,65 @@
#include "ui_model.h"
#include <math.h>
#include <stddef.h>
#ifdef ESP_PLATFORM
#include "freertos/FreeRTOS.h"
#include "freertos/portmacro.h"
static portMUX_TYPE model_mux = portMUX_INITIALIZER_UNLOCKED;
#define LOCK() portENTER_CRITICAL(&model_mux)
#define UNLOCK() portEXIT_CRITICAL(&model_mux)
#else
#define LOCK() ((void)0)
#define UNLOCK() ((void)0)
#endif
typedef struct {
uint64_t bucket;
float sum[UI_METRIC_COUNT];
uint16_t count[UI_METRIC_COUNT];
bool used;
} history_bin_t;
static ui_sample_t latest;
static history_bin_t bins[UI_HISTORY_POINTS];
void ui_model_publish(const ui_sample_t *sample)
{
if (!sample || !sample->available) return;
const uint64_t bucket = sample->timestamp_ms / UI_HISTORY_BUCKET_MS;
LOCK();
latest = *sample;
history_bin_t *bin = &bins[bucket % UI_HISTORY_POINTS];
if (!bin->used || bin->bucket != bucket) {
*bin = (history_bin_t){.bucket = bucket, .used = true};
}
for (unsigned i = 0; i < UI_METRIC_COUNT; ++i) {
if (isfinite(sample->values[i]) && bin->count[i] < UINT16_MAX) {
bin->sum[i] += sample->values[i];
++bin->count[i];
}
}
UNLOCK();
}
void ui_model_snapshot(ui_sample_t *sample)
{
LOCK();
*sample = latest;
UNLOCK();
}
void ui_model_history(ui_metric_t metric, uint64_t now_ms, float *values)
{
const uint64_t last_bucket = now_ms / UI_HISTORY_BUCKET_MS;
LOCK();
for (unsigned i = 0; i < UI_HISTORY_POINTS; ++i) {
const unsigned age = UI_HISTORY_POINTS - 1 - i;
values[i] = NAN;
if ((unsigned)metric >= UI_METRIC_COUNT || last_bucket < age) continue;
const uint64_t bucket = last_bucket - age;
const history_bin_t *bin = &bins[bucket % UI_HISTORY_POINTS];
if (bin->used && bin->bucket == bucket && bin->count[metric]) {
values[i] = bin->sum[metric] / bin->count[metric];
}
}
UNLOCK();
}
+23
View File
@@ -0,0 +1,23 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
#define UI_HISTORY_POINTS 180
#define UI_HISTORY_BUCKET_MS 10000
#define UI_SENSOR_STALE_MS 5000
typedef enum {
UI_METRIC_CO2, UI_METRIC_PM25, UI_METRIC_TEMP, UI_METRIC_RH,
UI_METRIC_VOC, UI_METRIC_NOX, UI_METRIC_COUNT
} ui_metric_t;
typedef struct {
uint64_t timestamp_ms;
float values[UI_METRIC_COUNT]; /* ppm, ug/m3, degC, %, VOC index, NOx index */
bool available;
} ui_sample_t;
/* Producer submits scaled numbers, with NAN for unavailable channels. No LVGL calls. */
void ui_model_publish(const ui_sample_t *sample);
void ui_model_snapshot(ui_sample_t *sample);
/* 180 fixed ten-second bins, oldest first; empty bins are NAN. RAM only. */
void ui_model_history(ui_metric_t metric, uint64_t now_ms, float *values);
@@ -0,0 +1,47 @@
#include "ui_navigation.h"
#include "esp_log.h"
#include "screens.h"
#include "ui.h"
static void screen_gesture_cb(lv_event_t *event)
{
lv_indev_t *input = lv_indev_get_act();
if (!input || lv_dropdown_is_open(objects.history_metric) ||
lv_dropdown_is_open(objects.dim_timeout)) return;
lv_obj_t *screen = lv_event_get_current_target(event);
lv_obj_t *screens[] = {objects.main, objects.page_2, objects.history, objects.device};
unsigned index = 0;
while (index < 4 && screens[index] != screen) ++index;
if (index >= 4) return;
lv_dir_t direction = lv_indev_get_gesture_dir(input);
unsigned next = index;
if (direction == LV_DIR_LEFT && index < 3) ++next;
else if (direction == LV_DIR_RIGHT && index > 0) --next;
if (next == index) return;
lv_indev_wait_release(input);
loadScreen((enum ScreensEnum)(next + 1));
ESP_LOGI("ui_navigation", "Swipe: page %u -> %u", index + 1, next + 1);
}
static void prepare_gestures(lv_obj_t *object)
{
lv_obj_clear_flag(object, LV_OBJ_FLAG_SCROLLABLE);
lv_obj_add_flag(object, LV_OBJ_FLAG_GESTURE_BUBBLE);
for (uint32_t i = 0; i < lv_obj_get_child_cnt(object); ++i)
prepare_gestures(lv_obj_get_child(object, i));
}
void ui_navigation_init(void)
{
lv_obj_t *screens[] = {objects.main, objects.page_2, objects.history, objects.device};
for (unsigned i = 0; i < 4; ++i) {
prepare_gestures(screens[i]);
lv_obj_clear_flag(screens[i], LV_OBJ_FLAG_GESTURE_BUBBLE);
lv_obj_add_event_cb(screens[i], screen_gesture_cb, LV_EVENT_GESTURE, NULL);
}
/* Sliders/dropdowns own their gestures; changing brightness must not navigate. */
lv_obj_clear_flag(objects.brightness, LV_OBJ_FLAG_GESTURE_BUBBLE);
lv_obj_clear_flag(objects.history_metric, LV_OBJ_FLAG_GESTURE_BUBBLE);
lv_obj_clear_flag(objects.dim_timeout, LV_OBJ_FLAG_GESTURE_BUBBLE);
ESP_LOGI("ui_navigation", "Ready: 4 pages / measurements, air, history, device");
}
@@ -0,0 +1,4 @@
#pragma once
/* Call once after ui_init(), with the LVGL lock held. Kept outside EEZ exports. */
void ui_navigation_init(void);
+1 -1
View File
@@ -2,4 +2,4 @@ file(GLOB_RECURSE SRC_FILES "*.c")
idf_component_register(SRCS ${SRC_FILES}
INCLUDE_DIRS "."
REQUIRES "esp_lcd" "driver" "esp_adc" "esp_lcd_jd9853" "esp_lcd_touch_axs5106" "fatfs" "nvs_flash" "lwip" "esp_wifi")
REQUIRES "hardware_config" "esp_lcd" "driver" "esp_adc" "esp_lcd_jd9853" "esp_lcd_touch_axs5106" "fatfs" "nvs_flash" "lwip" "esp_wifi")
+5 -3
View File
@@ -4,9 +4,11 @@
#include "driver/i2c_master.h"
#include "driver/gpio.h"
#define EXAMPLE_PIN_I2C_SDA GPIO_NUM_18
#define EXAMPLE_PIN_I2C_SCL GPIO_NUM_19
#define I2C_PORT_NUM 0
#include "hardware_config.h"
#define EXAMPLE_PIN_I2C_SDA NANOPSX_I2C_SDA
#define EXAMPLE_PIN_I2C_SCL NANOPSX_I2C_SCL
#define I2C_PORT_NUM NANOPSX_I2C_PORT
#ifdef __cplusplus
extern "C" {
+14 -3
View File
@@ -7,7 +7,7 @@
#include "esp_log.h"
#include "bsp_touch.h"
void bsp_touch_init(esp_lcd_touch_handle_t *touch_handle, i2c_master_bus_handle_t bus_handle, uint16_t xmax, uint16_t ymax, uint16_t rotation)
esp_err_t bsp_touch_init(esp_lcd_touch_handle_t *touch_handle, i2c_master_bus_handle_t bus_handle, uint16_t xmax, uint16_t ymax, uint16_t rotation)
{
static i2c_master_dev_handle_t dev_handle;
i2c_device_config_t dev_cfg = {
@@ -15,7 +15,9 @@ void bsp_touch_init(esp_lcd_touch_handle_t *touch_handle, i2c_master_bus_handle_
.device_address = ESP_LCD_TOUCH_IO_I2C_AXS5106_ADDRESS,
.scl_speed_hz = 400000,
};
ESP_ERROR_CHECK(i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle));
*touch_handle = NULL;
esp_err_t err = i2c_master_bus_add_device(bus_handle, &dev_cfg, &dev_handle);
if (err != ESP_OK) return err;
esp_lcd_touch_config_t tp_cfg = {};
tp_cfg.x_max = xmax < ymax ? xmax : ymax;
@@ -48,5 +50,14 @@ void bsp_touch_init(esp_lcd_touch_handle_t *touch_handle, i2c_master_bus_handle_
tp_cfg.flags.mirror_y = 0;
}
ESP_ERROR_CHECK(esp_lcd_touch_new_i2c_axs5106(dev_handle, &tp_cfg, touch_handle));
err = esp_lcd_touch_new_i2c_axs5106(dev_handle, &tp_cfg, touch_handle);
if (err == ESP_OK) {
err = i2c_master_probe(bus_handle, dev_cfg.device_address, 100);
if (err != ESP_OK) esp_lcd_touch_del(*touch_handle);
}
if (err != ESP_OK) {
i2c_master_bus_rm_device(dev_handle);
*touch_handle = NULL;
}
return err;
}
+1 -1
View File
@@ -13,7 +13,7 @@
extern "C" {
#endif
void bsp_touch_init(esp_lcd_touch_handle_t *touch_handle, i2c_master_bus_handle_t bus_handle, uint16_t xmax, uint16_t ymax, uint16_t rotation);
esp_err_t bsp_touch_init(esp_lcd_touch_handle_t *touch_handle, i2c_master_bus_handle_t bus_handle, uint16_t xmax, uint16_t ymax, uint16_t rotation);
#ifdef __cplusplus
}
#endif
@@ -0,0 +1 @@
idf_component_register(INCLUDE_DIRS ".")
@@ -0,0 +1,72 @@
#pragma once
/* Central build-time hardware selection. See firmware/HARDWARE.md.
* Select sensor and board independently; no credentials belong in this file.
*/
#define NANOPSX_SENSOR_SEN54 54
#define NANOPSX_SENSOR_SEN66 66
#define NANOPSX_BOARD_C6_DISPLAY_8MB 1
#define NANOPSX_BOARD_C6_DEVKIT_8MB 2
#ifndef NANOPSX_SENSOR
#define NANOPSX_SENSOR NANOPSX_SENSOR_SEN66
#endif
#ifndef NANOPSX_BOARD
#define NANOPSX_BOARD NANOPSX_BOARD_C6_DISPLAY_8MB
#endif
/* SEN66 retains its known GPIO7/8 wiring. With a display the sole HP I2C
* controller serves touch on GPIO18/19, so the sensor uses a GPIO bus.
* SEN54 retains the existing shared hardware-bus wiring.
*/
#if NANOPSX_SENSOR == NANOPSX_SENSOR_SEN66
#define NANOPSX_SENSOR_SDA 7
#define NANOPSX_SENSOR_SCL 8
#else
#define NANOPSX_SENSOR_SDA NANOPSX_I2C_SDA
#define NANOPSX_SENSOR_SCL NANOPSX_I2C_SCL
#endif
#define NANOPSX_SENSOR_SOFT_I2C \
(NANOPSX_SENSOR_SDA != NANOPSX_I2C_SDA || NANOPSX_SENSOR_SCL != NANOPSX_I2C_SCL)
#if NANOPSX_BOARD == NANOPSX_BOARD_C6_DISPLAY_8MB
#define NANOPSX_BOARD_NAME "ESP32-C6 display / 8 MB"
#define NANOPSX_HAS_DISPLAY 1
#define NANOPSX_I2C_SDA 18
#define NANOPSX_I2C_SCL 19
#elif NANOPSX_BOARD == NANOPSX_BOARD_C6_DEVKIT_8MB
#define NANOPSX_BOARD_NAME "ESP32-C6 devkit / 8 MB"
#define NANOPSX_HAS_DISPLAY 0
#define NANOPSX_I2C_SDA 7
#define NANOPSX_I2C_SCL 8
#else
#error "Unsupported NANOPSX_BOARD: add a reviewed board profile first"
#endif
#define NANOPSX_I2C_PORT 0
#define NANOPSX_FLASH_BYTES 8388608
#if NANOPSX_SENSOR == NANOPSX_SENSOR_SEN54
#define NANOPSX_SENSOR_NAME "SEN54"
#define NANOPSX_SENSOR_ADDRESS 0x69
#define NANOPSX_SENSOR_I2C_HZ 400000
#elif NANOPSX_SENSOR == NANOPSX_SENSOR_SEN66
#define NANOPSX_SENSOR_NAME "SEN66"
#define NANOPSX_SENSOR_ADDRESS 0x6b
#define NANOPSX_SENSOR_I2C_HZ 100000
#else
#error "Unsupported NANOPSX_SENSOR: use SEN54 or SEN66"
#endif
/* Board profiles describe wiring/peripherals, not a replacement for the
* PlatformIO chip, SDK configuration and partition-table selection.
*/
#ifdef ESP_PLATFORM
#include "sdkconfig.h"
#if !CONFIG_IDF_TARGET_ESP32C6
#error "These board profiles require ESP32-C6"
#endif
#if !CONFIG_ESPTOOLPY_FLASHSIZE_8MB
#error "These board profiles require the 8 MB SDK/partition configuration"
#endif
#endif
@@ -1,6 +1,7 @@
idf_component_register(
SRCS
"src/net_influx.c"
"src/influx_batch.c"
INCLUDE_DIRS
"include"
REQUIRES
@@ -10,5 +11,6 @@ idf_component_register(
storage
esp_http_client
sys_status
esp_timer
)
@@ -2,6 +2,8 @@
#pragma once
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>
#include "freertos/FreeRTOS.h"
#include "esp_err.h"
typedef enum {
@@ -28,15 +30,15 @@ typedef struct {
typedef struct {
const char* measurement; // z.B. "air"
const char* tags; // z.B. "device=xyz,location=lab" (optional, kann NULL sein)
uint64_t ts_ms; // 0 => server time
uint64_t ts_ms; // 0 => acquisition time aligned to the server HTTP Date (async API)
const net_influx_field_t* fields;
size_t num_fields;
} net_influx_point_t;
typedef struct {
// Task/Queue
uint16_t queue_len; // z.B. 16
uint32_t task_stack; // z.B. 6144
uint16_t queue_len; // Standard 32
uint32_t task_stack; // Standard 8192
UBaseType_t task_prio; // z.B. 5
// Init/Retry/Backoff
@@ -68,7 +70,9 @@ esp_err_t net_influx_init_from_nvs(const char* ca_cert_pem_opt, int timeout_ms);
esp_err_t net_influx_start(const net_influx_runtime_cfg_t* rt);
void net_influx_stop(void);
// Asynchron: kopiert point+felder intern und queued sie.
// Asynchron: serialisiert den Punkt sofort in eine feste RAM-Warteschlange.
// 1-Hz-Werte werden bis zu 10 Punkte / 10 s gesammelt, mit eigenen Zeitstempeln.
// Ohne gültige Serverzeit werden sichere Einzelpunkt-Schreibvorgänge verwendet.
// Rückgabe:
// - ESP_OK: queued
// - ESP_ERR_NO_MEM / ESP_ERR_INVALID_ARG / ESP_FAIL: sonst
@@ -0,0 +1,87 @@
#include "influx_batch.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
static bool leap(unsigned year) { return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0); }
bool influx_parse_http_date(const char *date, uint64_t *epoch_ms)
{
if (!date || !epoch_ms || strlen(date) != 29) return false;
char weekday[4], month[4], zone[4], extra;
unsigned day, year, hour, minute, second;
if (sscanf(date, "%3s, %u %3s %u %u:%u:%u %3s%c", weekday, &day, month,
&year, &hour, &minute, &second, zone, &extra) != 8) return false;
if (strcmp(zone, "GMT") || year < 2020 || year > 2261 || hour > 23 || minute > 59 || second > 59) return false;
const char *months[] = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
const unsigned days[] = {31,28,31,30,31,30,31,31,30,31,30,31};
unsigned m = 0;
while (m < 12 && strcmp(month, months[m])) ++m;
if (m == 12 || day == 0 || day > days[m] + (m == 1 && leap(year))) return false;
uint64_t total = 0;
for (unsigned y = 1970; y < year; ++y) total += leap(y) ? 366 : 365;
for (unsigned i = 0; i < m; ++i) total += days[i] + (i == 1 && leap(year));
total += day - 1;
*epoch_ms = ((total * 24 + hour) * 60 * 60 + minute * 60 + second) * 1000;
return true;
}
static uint64_t clock_at(const influx_clock_t *clock, uint64_t mono_ms)
{
return mono_ms >= clock->monotonic_ms ? clock->epoch_ms + mono_ms - clock->monotonic_ms :
clock->epoch_ms - (clock->monotonic_ms - mono_ms);
}
void influx_clock_observe(influx_clock_t *clock, const char *date, uint64_t mono_ms)
{
uint64_t server_ms;
if (!influx_parse_http_date(date, &server_ms)) return;
/* HTTP Date has one-second resolution. Use its midpoint; no external NTP needed. */
if (!clock->ready) {
clock->epoch_ms = server_ms + 500;
clock->monotonic_ms = mono_ms;
clock->ready = true;
} else {
/* Correct oscillator drift gently; header rounding must not jitter every batch. */
int64_t delta = (int64_t)(server_ms + 500) - (int64_t)clock_at(clock, mono_ms);
if (delta > 1500) clock->epoch_ms += 50;
else if (delta < -1500) clock->epoch_ms -= 50;
}
}
bool influx_clock_timestamp(influx_clock_t *clock, uint64_t acquired_ms, uint64_t *timestamp)
{
if (!clock->ready) return false;
uint64_t value = clock_at(clock, acquired_ms);
if (value <= clock->last_timestamp_ms) value = clock->last_timestamp_ms + 1;
clock->last_timestamp_ms = value;
*timestamp = value;
return true;
}
bool influx_batch_add(influx_batch_t *batch, const char *line, uint64_t now_ms)
{
size_t length = strlen(line), separator = batch->points ? 1 : 0;
if (!length || batch->points >= INFLUX_BATCH_POINTS ||
length + separator >= sizeof(batch->body) - batch->bytes) return false;
if (!batch->points) batch->started_ms = now_ms;
if (separator) batch->body[batch->bytes++] = '\n';
memcpy(batch->body + batch->bytes, line, length + 1);
batch->bytes += length;
const char *last_space = strrchr(line, ' ');
if (last_space) {
char *end;
uint64_t timestamp = strtoull(last_space + 1, &end, 10);
if (end != last_space + 1 && *end == 0) {
if (!batch->points) batch->first_timestamp_ms = timestamp;
batch->last_timestamp_ms = timestamp;
}
}
++batch->points;
return true;
}
bool influx_batch_due(const influx_batch_t *batch, uint64_t now_ms)
{
return batch->points && (batch->points >= INFLUX_BATCH_POINTS || now_ms - batch->started_ms >= INFLUX_FLUSH_MS);
}
@@ -0,0 +1,27 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define INFLUX_LINE_CAP 512
#define INFLUX_BATCH_CAP 4096
#define INFLUX_BATCH_POINTS 10
#define INFLUX_FLUSH_MS 10000
typedef struct {
char body[INFLUX_BATCH_CAP];
size_t bytes;
unsigned points;
uint64_t started_ms;
uint64_t first_timestamp_ms, last_timestamp_ms;
} influx_batch_t;
typedef struct {
bool ready;
uint64_t epoch_ms, monotonic_ms, last_timestamp_ms;
} influx_clock_t;
bool influx_parse_http_date(const char *date, uint64_t *epoch_ms);
void influx_clock_observe(influx_clock_t *clock, const char *date, uint64_t mono_ms);
bool influx_clock_timestamp(influx_clock_t *clock, uint64_t acquired_ms, uint64_t *timestamp);
bool influx_batch_add(influx_batch_t *batch, const char *line, uint64_t now_ms);
bool influx_batch_due(const influx_batch_t *batch, uint64_t now_ms);
+284 -316
View File
@@ -6,8 +6,13 @@
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/semphr.h"
#include "esp_timer.h"
#include "influx_batch.h"
#include <stdatomic.h>
#include <string.h>
#include <strings.h>
#include <stdio.h>
#include <stdarg.h>
#include <ctype.h>
@@ -50,11 +55,11 @@ typedef struct {
static QueueHandle_t s_q = NULL;
static TaskHandle_t s_task = NULL;
static bool s_run = false;
static atomic_bool s_run = false;
static net_influx_runtime_cfg_i_t s_rt = {
.queue_len = 16,
.task_stack = 6144,
.queue_len = 32,
.task_stack = 8192,
.task_prio = 5,
.init_retry_ms = 1000,
.backoff_start_ms = 2000,
@@ -131,28 +136,6 @@ static bool parse_base_url(const char* in, base_parts_t* out) {
return true;
}
static void mask_token(const char* token, char* out, size_t out_len) {
if (!token || !out || out_len < 8) return;
size_t n = strlen(token);
if (n <= 8) {
snprintf(out, out_len, "****");
} else {
size_t keep = 4;
snprintf(out, out_len, "%.*s****%.*s",
(int)keep, token,
(int)keep, token + n - keep);
}
}
static char* dup0(const char* str) {
if (!str) return NULL;
size_t n = strlen(str) + 1;
char* p = (char*)malloc(n);
if (!p) return NULL;
memcpy(p, str, n);
return p;
}
/* Minimal escaping für measurement/key: spaces/commas */
static size_t esc_copy(char* dst, size_t cap, const char* src, bool escape_equals) {
size_t pos = 0;
@@ -164,11 +147,11 @@ static size_t esc_copy(char* dst, size_t cap, const char* src, bool escape_equal
char c = *p;
bool esc = (c == ' ' || c == ',' || (escape_equals && c == '='));
if (esc) {
if (pos + 2 >= cap) break;
if (pos + 2 >= cap) { dst[0] = 0; return SIZE_MAX; }
dst[pos++] = '\\';
dst[pos++] = c;
} else {
if (pos + 1 >= cap) break;
if (pos + 1 >= cap) { dst[0] = 0; return SIZE_MAX; }
dst[pos++] = c;
}
}
@@ -176,122 +159,139 @@ static size_t esc_copy(char* dst, size_t cap, const char* src, bool escape_equal
return pos;
}
/* ---------------- HTTP Event Handler (IDF-kompatibel) ---------------- */
static esp_err_t http_evt(esp_http_client_event_t* evt) {
switch (evt->event_id) {
case HTTP_EVENT_ERROR: ESP_LOGE(TAG, "HTTP_EVENT_ERROR"); break;
case HTTP_EVENT_ON_CONNECTED: ESP_LOGI(TAG, "HTTP_EVENT_ON_CONNECTED"); break;
case HTTP_EVENT_HEADER_SENT: ESP_LOGD(TAG, "HTTP_EVENT_HEADER_SENT"); break;
case HTTP_EVENT_ON_HEADER:
ESP_LOGD(TAG, "HDR: %s: %s",
evt->header_key ? evt->header_key : "(null)",
evt->header_value ? evt->header_value : "(null)");
break;
case HTTP_EVENT_ON_DATA: ESP_LOGV(TAG, "DATA chunk len=%d", evt->data_len); break;
case HTTP_EVENT_ON_FINISH: ESP_LOGD(TAG, "HTTP_EVENT_ON_FINISH"); break;
case HTTP_EVENT_DISCONNECTED: ESP_LOGW(TAG, "HTTP_EVENT_DISCONNECTED"); break;
default: break;
/* Persistent HTTP client; shared with the optional synchronous API. */
static esp_http_client_handle_t s_http;
static SemaphoreHandle_t s_http_lock;
static influx_clock_t s_clock;
static char s_write_url[640];
static atomic_uint s_dropped;
static uint64_t monotonic_ms(void) { return (uint64_t)(esp_timer_get_time() / 1000); }
static void http_close(void)
{
if (s_http) esp_http_client_cleanup(s_http);
s_http = NULL;
}
static esp_err_t http_evt(esp_http_client_event_t *event)
{
if (event->event_id == HTTP_EVENT_ON_CONNECTED) ESP_LOGI(TAG, "HTTP connection established.");
if (event->event_id == HTTP_EVENT_ON_HEADER && event->header_key && event->header_value &&
strcasecmp(event->header_key, "Date") == 0) {
bool ready = s_clock.ready;
influx_clock_observe(&s_clock, event->header_value, monotonic_ms());
if (!ready && s_clock.ready) ESP_LOGI(TAG, "Measurement clock aligned to server HTTP Date.");
}
return ESP_OK;
}
/* ---------------- Internal: HTTP send "line protocol" ---------------- */
static esp_err_t net_influx_write_line(const char* line) {
bool ok = false;
if (!line || !*line) {
sys_status_set_influx_ok(false);
return ESP_ERR_INVALID_ARG;
static bool encode_query(char *out, size_t cap, const char *text)
{
static const char hex[] = "0123456789ABCDEF";
size_t n = 0;
for (const unsigned char *p = (const unsigned char *)text; *p; ++p) {
bool plain = isalnum(*p) || *p == '-' || *p == '_' || *p == '.' || *p == '~';
size_t need = plain ? 1 : 3;
if (n + need >= cap) return false;
if (plain) out[n++] = *p;
else { out[n++] = '%'; out[n++] = hex[*p >> 4]; out[n++] = hex[*p & 15]; }
}
if (s.url_base[0] == 0 || s.org[0] == 0 || s.bucket[0] == 0 || s.token[0] == 0) {
sys_status_set_influx_ok(false);
return ESP_ERR_INVALID_STATE;
}
// Base parse → host/port/tls
base_parts_t bp;
if (!parse_base_url(s.url_base, &bp)) {
ESP_LOGE(TAG, "Base-URL ungueltig: \"%s\"", s.url_base);
sys_status_set_influx_ok(false);
return ESP_ERR_INVALID_ARG;
}
if (s.use_tls) bp.tls = true;
int port = (bp.port > 0) ? bp.port : (bp.tls ? 443 : 8086);
// Pfad
char path[192];
snprintf(path, sizeof(path), "/api/v2/write?org=%s&bucket=%s&precision=ms", s.org, s.bucket);
ESP_LOGI(TAG, "HTTP cfg: host=%s, port=%d, path=%s, tls=%d", bp.host, port, path, (int)bp.tls);
ESP_LOGD(TAG, "Line: %s", line);
esp_http_client_config_t cfg = {
.host = bp.host,
.port = port,
.path = path,
.timeout_ms = s.http_timeout_ms,
.cert_pem = bp.tls ? s.ca_cert_pem : NULL,
.method = HTTP_METHOD_POST,
.event_handler = http_evt,
.transport_type = bp.tls ? HTTP_TRANSPORT_OVER_SSL : HTTP_TRANSPORT_OVER_TCP,
.disable_auto_redirect = false,
};
esp_http_client_handle_t h = esp_http_client_init(&cfg);
if (!h) {
ESP_LOGE(TAG, "http_client_init: no mem");
sys_status_set_influx_ok(false);
return ESP_ERR_NO_MEM;
}
// Header
size_t auth_len = strlen(s.token) + 7; // "Token " + '\0'
char* auth = (char*)malloc(auth_len);
if (!auth) {
ESP_LOGE(TAG, "malloc auth header: no mem");
esp_http_client_cleanup(h);
sys_status_set_influx_ok(false);
return ESP_ERR_NO_MEM;
}
snprintf(auth, auth_len, "Token %s", s.token);
esp_http_client_set_header(h, "Authorization", auth);
free(auth);
esp_http_client_set_header(h, "Content-Type", "text/plain; charset=utf-8");
esp_err_t err = esp_http_client_set_post_field(h, line, (int)strlen(line));
if (err != ESP_OK) {
ESP_LOGE(TAG, "set_post_field: %s", esp_err_to_name(err));
esp_http_client_cleanup(h);
sys_status_set_influx_ok(false);
return err;
}
err = esp_http_client_perform(h);
int status = -1;
if (err == ESP_OK) {
status = esp_http_client_get_status_code(h);
int64_t cl = esp_http_client_get_content_length(h);
ESP_LOGI(TAG, "HTTP status=%d, content_length=%lld", status, (long long)cl);
if (status != 204) {
char resp[256] = {0};
int n = esp_http_client_read_response(h, resp, sizeof(resp)-1);
if (n > 0) ESP_LOGW(TAG, "Resp(%d): %.*s", status, n, resp);
else ESP_LOGW(TAG, "Resp(%d): <kein Body>", status);
}
} else {
ESP_LOGE(TAG, "perform: %s", esp_err_to_name(err));
}
esp_http_client_cleanup(h);
ok = (err == ESP_OK && status == 204);
sys_status_set_influx_ok(ok);
return ok ? ESP_OK : ESP_FAIL;
out[n] = 0;
return true;
}
/* Caller holds s_http_lock. URLs/headers are configured once per connection. */
static esp_err_t http_prepare(void)
{
if (s_http) return ESP_OK;
if (!s.url_base[0] || !s.org[0] || !s.bucket[0] || !s.token[0]) return ESP_ERR_INVALID_STATE;
base_parts_t base;
if (!parse_base_url(s.url_base, &base)) return ESP_ERR_INVALID_ARG;
if (s.use_tls) base.tls = true;
int port = base.port > 0 ? base.port : base.tls ? 443 : 8086;
char org[192], bucket[192];
if (!encode_query(org, sizeof(org), s.org) || !encode_query(bucket, sizeof(bucket), s.bucket)) return ESP_ERR_INVALID_SIZE;
int length = snprintf(s_write_url, sizeof(s_write_url), "%s://%s:%d/api/v2/write?org=%s&bucket=%s&precision=ms",
base.tls ? "https" : "http", base.host, port, org, bucket);
if (length < 0 || length >= sizeof(s_write_url)) return ESP_ERR_INVALID_SIZE;
esp_http_client_config_t cfg = {
.url = s_write_url,
.timeout_ms = s.http_timeout_ms,
.cert_pem = base.tls ? s.ca_cert_pem : NULL,
.method = HTTP_METHOD_POST,
.event_handler = http_evt,
.transport_type = base.tls ? HTTP_TRANSPORT_OVER_SSL : HTTP_TRANSPORT_OVER_TCP,
.disable_auto_redirect = true,
.keep_alive_enable = true,
.keep_alive_idle = 30,
.keep_alive_interval = 10,
.keep_alive_count = 3,
};
s_http = esp_http_client_init(&cfg);
if (!s_http) return ESP_ERR_NO_MEM;
char auth[sizeof(s.token) + 7];
snprintf(auth, sizeof(auth), "Token %s", s.token);
esp_err_t err = esp_http_client_set_header(s_http, "Authorization", auth);
if (err == ESP_OK) err = esp_http_client_set_header(s_http, "Content-Type", "text/plain; charset=utf-8");
if (err != ESP_OK) { http_close(); return err; }
ESP_LOGI(TAG, "HTTP client ready / persistent connections enabled.");
return ESP_OK;
}
/* One read-only request bootstraps the private measurement clock, even without Internet/NTP. */
static void clock_bootstrap(void)
{
xSemaphoreTake(s_http_lock, portMAX_DELAY);
if (!s_clock.ready && http_prepare() == ESP_OK) {
char health_url[160];
base_parts_t base;
if (parse_base_url(s.url_base, &base)) {
if (s.use_tls) base.tls = true;
snprintf(health_url, sizeof(health_url), "%s://%s:%d/health", base.tls ? "https" : "http",
base.host, base.port > 0 ? base.port : base.tls ? 443 : 8086);
esp_http_client_set_url(s_http, health_url);
esp_http_client_set_method(s_http, HTTP_METHOD_GET);
esp_http_client_set_post_field(s_http, NULL, 0);
esp_err_t err = esp_http_client_perform(s_http);
if (err != ESP_OK) http_close();
else {
esp_http_client_set_url(s_http, s_write_url);
esp_http_client_set_method(s_http, HTTP_METHOD_POST);
}
}
if (!s_clock.ready) ESP_LOGW(TAG, "No server Date available; safe single-point fallback.");
}
xSemaphoreGive(s_http_lock);
}
static esp_err_t net_influx_write_payload(const char *body, unsigned points, int *status_out)
{
if (status_out) *status_out = 0;
if (!body || !*body || !s_http_lock) return ESP_ERR_INVALID_ARG;
xSemaphoreTake(s_http_lock, portMAX_DELAY);
int status = 0;
esp_err_t err = http_prepare();
if (err == ESP_OK) err = esp_http_client_set_post_field(s_http, body, (int)strlen(body));
if (err == ESP_OK) err = esp_http_client_perform(s_http);
if (err == ESP_OK) status = esp_http_client_get_status_code(s_http);
bool ok = err == ESP_OK && status == 204;
if (ok) {
ESP_LOGI(TAG, "HTTP status=204, points=%u, bytes=%u", points, (unsigned)strlen(body));
sys_status_record_influx_success();
} else {
ESP_LOGW(TAG, "Write failed: HTTP=%d error=%s points=%u", status, esp_err_to_name(err), points);
http_close();
}
/* Do not retain a pointer to the caller's temporary line/batch buffer. */
if (s_http) esp_http_client_set_post_field(s_http, NULL, 0);
sys_status_set_influx_ok(ok);
if (status_out) *status_out = status;
xSemaphoreGive(s_http_lock);
return ok ? ESP_OK : err != ESP_OK ? err : ESP_FAIL;
}
static esp_err_t net_influx_write_line(const char *line) { return net_influx_write_payload(line, 1, NULL); }
/* ---------------- Generic Point/Fields → Line Protocol ---------------- */
static bool field_is_valid(const net_influx_field_t* f) {
if (!f || !f->key || !*f->key) return false;
@@ -305,11 +305,18 @@ static esp_err_t build_line_protocol(const net_influx_point_t* p, char* out, siz
return ESP_ERR_INVALID_ARG;
}
if (strpbrk(p->measurement, "\r\n") || (p->tags && strpbrk(p->tags, "\r\n"))) return ESP_ERR_INVALID_ARG;
for (size_t i = 0; i < p->num_fields; ++i) {
const net_influx_field_t *field = &p->fields[i];
if ((field->key && strpbrk(field->key, "\r\n")) ||
(field->type == NET_INFLUX_F_STRING && field->v.s && strpbrk(field->v.s, "\r\n")))
return ESP_ERR_INVALID_ARG;
}
size_t off = 0;
// measurement escaped (space/comma)
char meas[96];
esc_copy(meas, sizeof(meas), p->measurement, false);
if (esc_copy(meas, sizeof(meas), p->measurement, false) == SIZE_MAX) return ESP_ERR_INVALID_SIZE;
off += snprintf(out + off, out_cap - off, "%s", meas);
if (off >= out_cap) return ESP_FAIL;
@@ -329,7 +336,7 @@ static esp_err_t build_line_protocol(const net_influx_point_t* p, char* out, siz
if (!field_is_valid(f)) continue;
char key[64];
esc_copy(key, sizeof(key), f->key, false);
if (esc_copy(key, sizeof(key), f->key, true) == SIZE_MAX) return ESP_ERR_INVALID_SIZE;
if (!first) {
off += snprintf(out + off, out_cap - off, ",");
@@ -349,7 +356,7 @@ static esp_err_t build_line_protocol(const net_influx_point_t* p, char* out, siz
off += snprintf(out + off, out_cap - off, "%s=%lldi", key, (long long)f->v.i);
break;
case NET_INFLUX_F_UINT:
off += snprintf(out + off, out_cap - off, "%s=%llui", key, (unsigned long long)f->v.u);
off += snprintf(out + off, out_cap - off, "%s=%lluu", key, (unsigned long long)f->v.u);
break;
case NET_INFLUX_F_BOOL:
off += snprintf(out + off, out_cap - off, "%s=%s", key, f->v.b ? "true" : "false");
@@ -386,124 +393,116 @@ static esp_err_t build_line_protocol(const net_influx_point_t* p, char* out, siz
return ESP_OK;
}
/* ---------------- Async Queue Message (deep copy) ---------------- */
/* Fixed-size, pre-serialized queue entries: no per-field heap allocation. */
typedef struct {
char* measurement;
char* tags; // optional
uint64_t ts_ms;
size_t num_fields;
net_influx_field_t* fields; // deep-copied array; keys and string-values are duplicated
char line[INFLUX_LINE_CAP];
uint64_t acquired_ms;
bool timestamped;
} influx_msg_t;
static void free_msg(influx_msg_t* m) {
if (!m) return;
if (m->measurement) free(m->measurement);
if (m->tags) free(m->tags);
if (m->fields) {
for (size_t i = 0; i < m->num_fields; ++i) {
if (m->fields[i].type == NET_INFLUX_F_STRING && m->fields[i].v.s) {
free((void*)m->fields[i].v.s);
}
if (m->fields[i].key) free((void*)m->fields[i].key);
}
free(m->fields);
static bool wait_running(uint32_t ms)
{
while (s_run && ms) {
uint32_t step = ms > 100 ? 100 : ms;
vTaskDelay(pdMS_TO_TICKS(step));
ms -= step;
}
memset(m, 0, sizeof(*m));
return s_run;
}
/* ---------------- Init/Backoff (im Worker) ---------------- */
static bool influx_init_blocking(void) {
static bool influx_init_blocking(void)
{
while (s_run) {
if (net_influx_init_from_nvs(s_rt.ca_cert_pem_opt, s_rt.http_timeout_ms) == ESP_OK) {
ESP_LOGI(TAG, "Influx ready (from NVS).");
return true;
}
ESP_LOGW(TAG, "Influx nicht bereit – retry in %u ms", (unsigned)s_rt.init_retry_ms);
vTaskDelay(pdMS_TO_TICKS(s_rt.init_retry_ms));
if (net_influx_init_from_nvs(s_rt.ca_cert_pem_opt, s_rt.http_timeout_ms) == ESP_OK) return true;
ESP_LOGW(TAG, "Influx configuration unavailable; retrying.");
wait_running(s_rt.init_retry_ms);
}
return false;
}
static bool influx_reinit_with_backoff(uint32_t* backoff_ms) {
if (!backoff_ms) return false;
uint32_t wait_ms = (*backoff_ms == 0) ? s_rt.backoff_start_ms : *backoff_ms;
ESP_LOGW(TAG, "Re-Init Influx in %u ms", (unsigned)wait_ms);
vTaskDelay(pdMS_TO_TICKS(wait_ms));
bool ok = (net_influx_init_from_nvs(s_rt.ca_cert_pem_opt, s_rt.http_timeout_ms) == ESP_OK);
if (ok) {
ESP_LOGI(TAG, "Influx Re-Init OK");
*backoff_ms = s_rt.backoff_start_ms;
return true;
}
if (wait_ms < s_rt.backoff_max_ms) {
uint32_t next = wait_ms * 2;
*backoff_ms = (next > s_rt.backoff_max_ms) ? s_rt.backoff_max_ms : next;
}
return false;
}
/* ---------------- Worker Task ---------------- */
static void net_influx_worker(void* arg) {
static void net_influx_worker(void *arg)
{
(void)arg;
ESP_LOGI(TAG, "Influx worker started.");
if (!influx_init_blocking()) {
ESP_LOGE(TAG, "Worker beendet (Influx init fatal).");
vTaskDelete(NULL);
return;
}
int fail_count = 0;
uint32_t backoff_ms = s_rt.backoff_start_ms;
influx_batch_t *batch = calloc(1, sizeof(*batch));
influx_msg_t carry = {0};
bool have_carry = false, batch_timestamped = true;
unsigned failures = 0;
uint32_t backoff = s_rt.backoff_start_ms;
if (!batch) { ESP_LOGE(TAG, "Cannot allocate Influx batch buffer."); goto done; }
if (!influx_init_blocking()) goto done;
clock_bootstrap();
ESP_LOGI(TAG, "Influx batching ready: up to %u points / %u ms, queue=%u", INFLUX_BATCH_POINTS, INFLUX_FLUSH_MS, s_rt.queue_len);
while (s_run) {
influx_msg_t msg = {0};
if (xQueueReceive(s_q, &msg, portMAX_DELAY) != pdTRUE) continue;
net_influx_point_t p = {
.measurement = msg.measurement,
.tags = msg.tags,
.ts_ms = msg.ts_ms,
.fields = msg.fields,
.num_fields = msg.num_fields,
};
char line[512];
esp_err_t b = build_line_protocol(&p, line, sizeof(line));
if (b == ESP_ERR_INVALID_STATE) {
ESP_LOGW(TAG, "Skipping write: no valid fields.");
free_msg(&msg);
continue;
bool flush = influx_batch_due(batch, monotonic_ms());
if (!flush) {
influx_msg_t msg;
bool received = have_carry;
if (received) { msg = carry; have_carry = false; }
else received = xQueueReceive(s_q, &msg, pdMS_TO_TICKS(100)) == pdTRUE;
if (!received) continue;
if (!msg.timestamped) {
uint64_t timestamp;
xSemaphoreTake(s_http_lock, portMAX_DELAY);
bool known = influx_clock_timestamp(&s_clock, msg.acquired_ms, &timestamp);
xSemaphoreGive(s_http_lock);
if (known) {
size_t used = strlen(msg.line);
int n = snprintf(msg.line + used, sizeof(msg.line) - used, " %llu", (unsigned long long)timestamp);
if (n < 0 || (size_t)n >= sizeof(msg.line) - used) { ESP_LOGW(TAG, "Dropping oversized timestamped point."); continue; }
msg.timestamped = true;
}
}
if ((!msg.timestamped && batch->points) || !influx_batch_add(batch, msg.line, monotonic_ms())) {
carry = msg; have_carry = true; flush = true;
} else {
batch_timestamped = msg.timestamped;
flush = !msg.timestamped || influx_batch_due(batch, monotonic_ms());
}
}
if (b != ESP_OK) {
ESP_LOGW(TAG, "Line build failed: %s", esp_err_to_name(b));
free_msg(&msg);
continue;
}
esp_err_t e = net_influx_write_line(line);
if (e == ESP_OK) {
if (fail_count) ESP_LOGI(TAG, "Influx write recovered.");
fail_count = 0;
backoff_ms = s_rt.backoff_start_ms;
} else {
ESP_LOGW(TAG, "Influx write failed: %s", esp_err_to_name(e));
if (++fail_count >= (int)s_rt.fails_before_reinit) {
(void)influx_reinit_with_backoff(&backoff_ms);
fail_count = 0;
if (!flush || !batch->points) continue;
/* Retries keep the exact body AND timestamps; acknowledged points are never resubmitted. */
while (s_run && batch->points) {
int status;
esp_err_t err = net_influx_write_payload(batch->body, batch->points, &status);
if (err == ESP_OK) {
ESP_LOGI(TAG, "Batch UTC: first_ms=%llu last_ms=%llu dropped=%u",
(unsigned long long)batch->first_timestamp_ms,
(unsigned long long)batch->last_timestamp_ms,
(unsigned)atomic_load(&s_dropped));
memset(batch, 0, sizeof(*batch));
failures = 0; backoff = s_rt.backoff_start_ms;
break;
}
if (!batch_timestamped || status == 400 || status == 413 || status == 422) {
if (!batch_timestamped)
ESP_LOGW(TAG, "Single-point request failed without a clock; no automatic replay with a new server timestamp.");
else
ESP_LOGW(TAG, "Dropping %u rejected points (HTTP %d); inspect schema/payload limits.", batch->points, status);
memset(batch, 0, sizeof(*batch));
break;
}
++failures;
ESP_LOGW(TAG, "Retaining %u points; retry in %u ms.", batch->points, (unsigned)backoff);
if (!wait_running(backoff)) break;
if (failures >= s_rt.fails_before_reinit) {
net_influx_init_from_nvs(s_rt.ca_cert_pem_opt, s_rt.http_timeout_ms);
failures = 0;
}
if (backoff < s_rt.backoff_max_ms) {
uint64_t next = (uint64_t)backoff * 2;
backoff = next > s_rt.backoff_max_ms ? s_rt.backoff_max_ms : (uint32_t)next;
}
}
free_msg(&msg);
}
ESP_LOGI(TAG, "Influx worker stopping.");
done:
if (batch && batch->points) ESP_LOGW(TAG, "Stopping: %u pending points discarded from RAM.", batch->points);
free(batch);
if (s_http_lock) {
xSemaphoreTake(s_http_lock, portMAX_DELAY); http_close(); xSemaphoreGive(s_http_lock);
}
if (s_q) { vQueueDelete(s_q); s_q = NULL; }
s_run = false;
s_task = NULL;
vTaskDelete(NULL);
}
@@ -512,20 +511,26 @@ esp_err_t net_influx_init(const net_influx_cfg_t* cfg) {
if (!cfg || !cfg->url_base || !cfg->org || !cfg->bucket || !cfg->token) {
return ESP_ERR_INVALID_ARG;
}
safe_copy(s.url_base, sizeof(s.url_base), cfg->url_base);
safe_copy(s.org, sizeof(s.org), cfg->org);
safe_copy(s.bucket, sizeof(s.bucket), cfg->bucket);
safe_copy(s.token, sizeof(s.token), cfg->token);
trim_inplace(s.url_base);
s.use_tls = cfg->use_tls;
s.ca_cert_pem = cfg->ca_cert_pem;
s.http_timeout_ms = (cfg->http_timeout_ms > 0) ? cfg->http_timeout_ms : 3000;
char tok[32] = {0};
mask_token(s.token, tok, sizeof(tok));
ESP_LOGI(TAG, "init: base=\"%s\", org=\"%s\", bucket=\"%s\", tls=%d, timeout=%dms, token=%s",
s.url_base, s.org, s.bucket, (int)s.use_tls, s.http_timeout_ms, tok);
if (!s_http_lock) {
s_http_lock = xSemaphoreCreateMutex();
if (!s_http_lock) return ESP_ERR_NO_MEM;
}
net_influx_state_t next = {0};
safe_copy(next.url_base, sizeof(next.url_base), cfg->url_base);
safe_copy(next.org, sizeof(next.org), cfg->org);
safe_copy(next.bucket, sizeof(next.bucket), cfg->bucket);
safe_copy(next.token, sizeof(next.token), cfg->token);
trim_inplace(next.url_base);
next.use_tls = cfg->use_tls;
next.ca_cert_pem = cfg->ca_cert_pem;
next.http_timeout_ms = cfg->http_timeout_ms > 0 ? cfg->http_timeout_ms : 3000;
xSemaphoreTake(s_http_lock, portMAX_DELAY);
bool host_changed = strcmp(s.url_base, next.url_base) || s.use_tls != next.use_tls;
if (memcmp(&s, &next, sizeof(s))) http_close();
if (host_changed) memset(&s_clock, 0, sizeof(s_clock));
s = next;
xSemaphoreGive(s_http_lock);
ESP_LOGI(TAG, "Influx configuration loaded; batching uses existing organization/bucket.");
sys_status_set_influx_ok(false);
return ESP_OK;
}
@@ -552,8 +557,9 @@ esp_err_t net_influx_write_fields(const char* measurement,
char fields[256];
va_list ap;
va_start(ap, fields_fmt);
vsnprintf(fields, sizeof(fields), fields_fmt, ap);
int fields_length = vsnprintf(fields, sizeof(fields), fields_fmt, ap);
va_end(ap);
if (fields_length < 0 || (size_t)fields_length >= sizeof(fields)) return ESP_ERR_INVALID_SIZE;
// 2) Line Protocol
char line[512];
@@ -561,7 +567,7 @@ esp_err_t net_influx_write_fields(const char* measurement,
// measurement escaping (space/comma)
char meas[96];
esc_copy(meas, sizeof(meas), measurement, false);
if (esc_copy(meas, sizeof(meas), measurement, false) == SIZE_MAX) return ESP_ERR_INVALID_SIZE;
off += snprintf(line + off, sizeof(line) - off, "%s", meas);
if (off < 0 || off >= (int)sizeof(line)) { sys_status_set_influx_ok(false); return ESP_FAIL; }
@@ -619,7 +625,7 @@ esp_err_t net_influx_init_from_nvs(const char* ca_cert_pem_opt, int timeout_ms)
/* ---------------- NEW: Start/Stop/Submit (generic, multi-sensor) ---------------- */
esp_err_t net_influx_start(const net_influx_runtime_cfg_t* rt) {
if (s_task) return ESP_OK;
if (s_task) return s_run ? ESP_OK : ESP_ERR_INVALID_STATE;
// runtime cfg übernehmen (mit Defaults)
if (rt) {
@@ -639,6 +645,7 @@ esp_err_t net_influx_start(const net_influx_runtime_cfg_t* rt) {
s_q = xQueueCreate(s_rt.queue_len, sizeof(influx_msg_t));
if (!s_q) return ESP_ERR_NO_MEM;
s_dropped = 0;
s_run = true;
if (xTaskCreate(net_influx_worker, "influx_worker", s_rt.task_stack, NULL, s_rt.task_prio, &s_task) != pdPASS) {
vQueueDelete(s_q);
@@ -649,71 +656,32 @@ esp_err_t net_influx_start(const net_influx_runtime_cfg_t* rt) {
return ESP_OK;
}
void net_influx_stop(void) {
void net_influx_stop(void)
{
s_run = false;
if (s_task) {
vTaskDelete(s_task);
s_task = NULL;
}
if (s_q) {
influx_msg_t msg;
while (xQueueReceive(s_q, &msg, 0) == pdTRUE) {
free_msg(&msg);
}
vQueueDelete(s_q);
s_q = NULL;
}
/* Worker owns its HTTP handle, batch and queue. Never delete it mid-request. */
for (unsigned i = 0; s_task && i < 50; ++i) vTaskDelay(pdMS_TO_TICKS(100));
if (s_task) ESP_LOGW(TAG, "Worker still finishing an HTTP request; cleanup deferred.");
}
esp_err_t net_influx_submit_point(const net_influx_point_t* p) {
if (!p || !p->measurement || !*p->measurement || !p->fields || p->num_fields == 0) {
esp_err_t net_influx_submit_point(const net_influx_point_t *point)
{
if (!point || !point->measurement || !*point->measurement || !point->fields || !point->num_fields || point->ts_ms > 9223372036854ULL)
return ESP_ERR_INVALID_ARG;
}
if (!s_q) return ESP_ERR_INVALID_STATE;
influx_msg_t msg = {0};
msg.measurement = dup0(p->measurement);
msg.tags = (p->tags && *p->tags) ? dup0(p->tags) : NULL;
msg.ts_ms = p->ts_ms;
msg.num_fields = p->num_fields;
msg.fields = (net_influx_field_t*)calloc(p->num_fields, sizeof(net_influx_field_t));
if (!msg.measurement || !msg.fields) {
free_msg(&msg);
return ESP_ERR_NO_MEM;
}
for (size_t i = 0; i < p->num_fields; ++i) {
msg.fields[i] = p->fields[i];
// deep copy key
msg.fields[i].key = dup0(p->fields[i].key);
if (!msg.fields[i].key) {
free_msg(&msg);
return ESP_ERR_NO_MEM;
}
// deep copy string value if needed
if (p->fields[i].type == NET_INFLUX_F_STRING && p->fields[i].v.s) {
msg.fields[i].v.s = dup0(p->fields[i].v.s);
if (!msg.fields[i].v.s) {
free_msg(&msg);
return ESP_ERR_NO_MEM;
}
}
}
// Non-blocking enqueue; wenn voll: drop oldest
if (!s_run || !s_q) return ESP_ERR_INVALID_STATE;
influx_msg_t msg = {.acquired_ms = monotonic_ms(), .timestamped = point->ts_ms != 0};
/* Reserve room for an automatically assigned millisecond timestamp. */
size_t cap = msg.timestamped ? sizeof(msg.line) : sizeof(msg.line) - 24;
esp_err_t err = build_line_protocol(point, msg.line, cap);
if (err != ESP_OK) return err;
if (xQueueSend(s_q, &msg, 0) != pdPASS) {
influx_msg_t dump;
if (xQueueReceive(s_q, &dump, 0) == pdTRUE) free_msg(&dump);
if (xQueueSend(s_q, &msg, 0) != pdPASS) {
free_msg(&msg);
return ESP_FAIL;
influx_msg_t old;
if (xQueueReceive(s_q, &old, 0) == pdTRUE) {
unsigned dropped = atomic_fetch_add(&s_dropped, 1) + 1;
if (dropped == 1 || dropped % 10 == 0)
ESP_LOGW(TAG, "Influx queue full: %u old pending points dropped since start.", dropped);
}
if (xQueueSend(s_q, &msg, 0) != pdPASS) return ESP_FAIL;
}
return ESP_OK;
}
+6 -1
View File
@@ -1,11 +1,13 @@
idf_component_register(
SRCS
"sen5x_i2c.c"
"sen66_i2c.c"
"sensirion_common.c"
"sensirion_i2c.c"
"sensirion_i2c_hal.c"
"sensor_soft_i2c.c"
"i2cdev.c"
"sen5x_app.c"
"air_sensor_app.c"
INCLUDE_DIRS
"."
REQUIRES
@@ -14,4 +16,7 @@ idf_component_register(
log
net_influx
eez_gui
storage
hardware_config
esp_timer
)
@@ -0,0 +1,29 @@
BSD 3-Clause License
Copyright (c) 2026, Sensirion AG
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,19 @@
# Sensirion driver provenance
Source: https://github.com/Sensirion/embedded-i2c-sen66
Pinned commit: `31cae0dd5253d256e8e647408ea1c544eff5d1c2` (retrieved 2026-11-09).
Unmodified upstream files: `sen66_i2c.c`, `sen66_i2c.h`, `sensirion_common.c`,
`sensirion_common.h`, `sensirion_i2c.c`, `sensirion_i2c.h`, `sensirion_config.h`.
License: `LICENSE.sensirion` (BSD-3-Clause). The common helpers also provide the
API used by the existing SEN5x driver. `sensirion_i2c_hal.c` remains our ESP-IDF
port using the shared, mutex-protected i2cdev hardware bus when sensor and
board pins match. SEN66 with the display uses a separate local open-drain GPIO
I2C engine (`sensor_soft_i2c.c/.h`) on GPIO7/8; touch retains hardware I2C on
GPIO18/19. The GPIO engine has its own wire-level ACK/NACK/stretch/timeout tests.
No upstream example HAL is
compiled. The manufacturer driver files retain their original copyright text.
`sen5x_i2c.c/.h` are the existing SEN5x driver; `air_sensor_app.c` selects the
SEN54 or SEN66 command API at compile time using `hardware_config.h`.
@@ -1,6 +1,6 @@
// File: src/sen5x_app.c
// File: src/air_sensor_app.c
#include "sen5x_app.h"
#include "air_sensor_app.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
@@ -9,7 +9,12 @@
#include "esp_log.h"
#include "sensirion_i2c_hal.h"
#include "sensirion_i2c_esp32_config.h"
#include "hardware_config.h"
#if NANOPSX_SENSOR == NANOPSX_SENSOR_SEN66
#include "sen66_i2c.h"
#else
#include "sen5x_i2c.h"
#endif
#include "net_influx.h"
#include "storage.h"
@@ -19,16 +24,18 @@
#include <stdio.h>
#include <math.h> // NAN, isfinite, lround
#include "vars.h"
#include "ui_model.h"
#include "esp_timer.h"
static const char* TAG = "sen5x_app";
static const char* TAG = "air_sensor_app";
/* ====================== Konfiguration ====================== */
#define SEN5X_PROD_STACK 4096
#define SEN5X_PROD_PRIO 6 // Producer leicht höher priorisiert
#define AIR_SENSOR_PROD_STACK 4096
#define AIR_SENSOR_PROD_PRIO 6 // Producer leicht höher priorisiert
// Influx worker runtime (läuft in net_influx.c)
#define INFLUX_QUEUE_LEN 16
#define INFLUX_TASK_STACK 6144
#define INFLUX_QUEUE_LEN 32
#define INFLUX_TASK_STACK 8192
#define INFLUX_TASK_PRIO 5
#define INFLUX_INIT_RETRY_MS 1000
@@ -42,7 +49,7 @@ typedef struct {
uint16_t pm1p0, pm2p5, pm4p0, pm10p0; // Rohwerte (x10)
float temp_c, rh_pct; // skaliert
int16_t voc_idx, nox_idx; // Rohwerte (x10)
} sen5x_sample_t;
} air_sensor_sample_t;
static bool g_inited = false;
static bool g_run = false;
@@ -68,52 +75,54 @@ static char* g_device_tag = NULL; // z.B. "device=xyz"
} \
} while (0)
/* ====================== Lokale Float-Wrapper (optional) ====================== */
static int16_t sen5x_read_measured_values_float(float* pm1p0, float* pm2p5,
float* pm4p0, float* pm10p0,
float* rh, float* t,
float* voc, float* nox) {
uint16_t pm1_i=0, pm2_i=0, pm4_i=0, pm10_i=0;
int16_t rh_i=0, t_i=0, voc_i=0, nox_i=0;
int16_t err = sen5x_read_measured_values(&pm1_i, &pm2_i, &pm4_i, &pm10_i,
&rh_i, &t_i, &voc_i, &nox_i);
if (err) return err;
if (pm1p0) *pm1p0 = (pm1_i == 0xFFFF) ? NAN : pm1_i / 10.0f;
if (pm2p5) *pm2p5 = (pm2_i == 0xFFFF) ? NAN : pm2_i / 10.0f;
if (pm4p0) *pm4p0 = (pm4_i == 0xFFFF) ? NAN : pm4_i / 10.0f;
if (pm10p0) *pm10p0 = (pm10_i == 0xFFFF) ? NAN : pm10_i / 10.0f;
if (rh) *rh = (rh_i == 0x7FFF) ? NAN : rh_i / 100.0f;
if (t) *t = (t_i == 0x7FFF) ? NAN : t_i / 200.0f;
if (voc) *voc = (voc_i == 0x7FFF) ? NAN : voc_i / 10.0f;
if (nox) *nox = (nox_i == 0x7FFF) ? NAN : nox_i / 10.0f;
return 0;
/* One selected command set; shared HAL and presentation/Influx pipeline. */
static int16_t sensor_ready(bool *ready) {
#if NANOPSX_SENSOR == NANOPSX_SENSOR_SEN66
uint8_t padding;
return sen66_get_data_ready(&padding, ready);
#else
return sen5x_read_data_ready(ready);
#endif
}
static int16_t sen5x_read_measured_pm_values_float(float* pm1, float* pm2,
float* pm4, float* pm10,
float* n05, float* n10,
float* n25, float* n40,
float* n100, float* dtyp) {
uint16_t pm1_i=0, pm2_i=0, pm4_i=0, pm10_i=0, n05_i=0, n10_i=0, n25_i=0, n40_i=0, n100_i=0, dtyp_i=0;
int16_t err = sen5x_read_measured_pm_values(&pm1_i, &pm2_i, &pm4_i, &pm10_i,
&n05_i, &n10_i, &n25_i, &n40_i, &n100_i, &dtyp_i);
if (err) return err;
static int16_t sensor_read(uint16_t *pm1, uint16_t *pm2, uint16_t *pm4,
uint16_t *pm10, int16_t *rh, int16_t *temp,
int16_t *voc, int16_t *nox, uint16_t *co2) {
#if NANOPSX_SENSOR == NANOPSX_SENSOR_SEN66
return sen66_read_measured_values_as_integers(pm1, pm2, pm4, pm10,
rh, temp, voc, nox, co2);
#else
*co2 = UINT16_MAX; // SEN54 has no CO2 channel: never submit a fake zero.
return sen5x_read_measured_values(pm1, pm2, pm4, pm10, rh, temp, voc, nox);
#endif
}
if (pm1) *pm1 = (pm1_i == 0xFFFF) ? NAN : pm1_i / 10.0f;
if (pm2) *pm2 = (pm2_i == 0xFFFF) ? NAN : pm2_i / 10.0f;
if (pm4) *pm4 = (pm4_i == 0xFFFF) ? NAN : pm4_i / 10.0f;
if (pm10) *pm10 = (pm10_i == 0xFFFF) ? NAN : pm10_i / 10.0f;
static int16_t sensor_start(void) {
#if NANOPSX_SENSOR == NANOPSX_SENSOR_SEN66
sen66_init(NANOPSX_SENSOR_ADDRESS);
// A sensor can keep measuring across an ESP-only reset.
int16_t rc = sen66_stop_measurement();
if (rc) return rc;
int8_t product[32] = {0};
rc = sen66_get_product_name(product, sizeof(product) - 1);
if (rc) return rc;
if (strncmp((const char *)product, "SEN66", 5) != 0) {
ESP_LOGE(TAG, "Expected SEN66, product=%s", (char *)product);
return -1;
}
ESP_LOGI(TAG, "Sensor identified: %s", (char *)product);
return sen66_start_continuous_measurement();
#else
return sen5x_start_measurement();
#endif
}
if (n05) *n05 = (n05_i == 0xFFFF) ? NAN : n05_i / 10.0f;
if (n10) *n10 = (n10_i == 0xFFFF) ? NAN : n10_i / 10.0f;
if (n25) *n25 = (n25_i == 0xFFFF) ? NAN : n25_i / 10.0f;
if (n40) *n40 = (n40_i == 0xFFFF) ? NAN : n40_i / 10.0f;
if (n100) *n100 = (n100_i == 0xFFFF) ? NAN : n100_i / 10.0f;
if (dtyp) *dtyp = (dtyp_i == 0xFFFF) ? NAN : dtyp_i / 1000.0f; // µm
return 0;
static int16_t sensor_stop(void) {
#if NANOPSX_SENSOR == NANOPSX_SENSOR_SEN66
return sen66_stop_measurement();
#else
return sen5x_stop_measurement();
#endif
}
/* ====================== App-Context: Device Tag ====================== */
@@ -137,7 +146,7 @@ static esp_err_t make_device_tag_once(void) {
}
/* ====================== Producer-Task ====================== */
static void sen5x_task_producer(void* arg) {
static void air_sensor_task_producer(void* arg) {
(void)arg;
const TickType_t period = pdMS_TO_TICKS(1000); // exakt 1 Hz
@@ -147,26 +156,26 @@ static void sen5x_task_producer(void* arg) {
for (; g_run; ) {
bool ready = false;
int16_t rc = sen5x_read_data_ready(&ready);
int16_t rc = sensor_ready(&ready);
if (rc != 0) {
ESP_LOGW(TAG, "sen5x_read_data_ready error: %d", (int)rc);
ESP_LOGW(TAG, "sensor_ready error: %d", (int)rc);
} else if (ready) {
uint16_t pm1p0=0, pm2p5=0, pm4p0=0, pm10p0=0;
uint16_t pm1p0=0, pm2p5=0, pm4p0=0, pm10p0=0, co2_raw=UINT16_MAX;
int16_t rh_raw=0, t_raw=0, voc_idx=0, nox_idx=0;
rc = sen5x_read_measured_values(&pm1p0, &pm2p5, &pm4p0, &pm10p0,
&rh_raw, &t_raw, &voc_idx, &nox_idx);
rc = sensor_read(&pm1p0, &pm2p5, &pm4p0, &pm10p0,
&rh_raw, &t_raw, &voc_idx, &nox_idx, &co2_raw);
if (rc != 0) {
ESP_LOGW(TAG, "sen5x_read_measured_values error: %d", (int)rc);
ESP_LOGW(TAG, "sensor_read error: %d", (int)rc);
} else {
// Roh → Struct (wie bisher)
sen5x_sample_t s = {
air_sensor_sample_t s = {
.pm1p0 = pm1p0,
.pm2p5 = pm2p5,
.pm4p0 = pm4p0,
.pm10p0 = pm10p0,
.temp_c = ((float)t_raw) / 200.0f,
.rh_pct = ((float)rh_raw) / 100.0f,
.temp_c = (t_raw == INT16_MAX) ? NAN : ((float)t_raw) / 200.0f,
.rh_pct = (rh_raw == INT16_MAX) ? NAN : ((float)rh_raw) / 100.0f,
.voc_idx = voc_idx,
.nox_idx = nox_idx
};
@@ -181,26 +190,28 @@ static void sen5x_task_producer(void* arg) {
// float noxf = (s.nox_idx == 0x7FFF) ? NAN : s.nox_idx / 10.0f; // bei Bedarf anzeigen
// Temperatur
snprintf(buf, sizeof(buf), "%.1f", (double)s.temp_c);
if (isfinite(s.temp_c)) snprintf(buf, sizeof(buf), "%.1f", (double)s.temp_c);
else snprintf(buf, sizeof(buf), "--");
set_var_temp(buf);
// Feuchte
snprintf(buf, sizeof(buf), "%.1f", (double)s.rh_pct);
if (isfinite(s.rh_pct)) snprintf(buf, sizeof(buf), "%.1f", (double)s.rh_pct);
else snprintf(buf, sizeof(buf), "--");
set_var_humidity(buf);
// VOC-Index (gerundet), falls NAN → "nan"
if (!isfinite(vocf)) snprintf(buf, sizeof(buf), "nan");
// VOC-Index (gerundet), nicht verfügbare Werte als "--"
if (!isfinite(vocf)) snprintf(buf, sizeof(buf), "--");
else snprintf(buf, sizeof(buf), "%d", (int)lround(vocf));
set_var_voc_ind(buf);
// PM (µg/m³) mit einer Nachkommastelle
if (!isfinite(pm10f)) snprintf(buf, sizeof(buf), "nan"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm10f);
if (!isfinite(pm10f)) snprintf(buf, sizeof(buf), "--"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm10f);
set_var_pm10p0(buf);
if (!isfinite(pm4f)) snprintf(buf, sizeof(buf), "nan"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm4f);
if (!isfinite(pm4f)) snprintf(buf, sizeof(buf), "--"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm4f);
set_var_pm4p0(buf);
if (!isfinite(pm2f)) snprintf(buf, sizeof(buf), "nan"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm2f);
if (!isfinite(pm2f)) snprintf(buf, sizeof(buf), "--"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm2f);
set_var_pm2p5(buf);
if (!isfinite(pm1f)) snprintf(buf, sizeof(buf), "nan"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm1f);
if (!isfinite(pm1f)) snprintf(buf, sizeof(buf), "--"); else snprintf(buf, sizeof(buf), "%.1f", (double)pm1f);
set_var_pm1p0(buf);
/* === Influx submit (generisch, variabel viele Felder) === */
@@ -212,6 +223,21 @@ static void sen5x_task_producer(void* arg) {
const double nox = (s.nox_idx == 0x7FFF) ? NAN : ((double)s.nox_idx / 10.0);
const double temp = (double)s.temp_c;
const double rh = (double)s.rh_pct;
const double co2 = (co2_raw == UINT16_MAX) ? NAN : (double)co2_raw;
#if NANOPSX_HAS_DISPLAY
ui_sample_t display_sample = {
.timestamp_ms = (uint64_t)(esp_timer_get_time() / 1000),
.available = true,
.values = {(float)co2, (float)pm2_5, (float)temp,
(float)rh, (float)voc, (float)nox}
};
ui_model_publish(&display_sample);
#endif
static unsigned samples;
if (++samples % 10 == 0) {
ESP_LOGI(TAG, "%s sample: PM2.5=%.1f temp=%.2f rh=%.2f CO2=%.0f",
NANOPSX_SENSOR_NAME, pm2_5, temp, rh, co2);
}
net_influx_field_t f[] = {
{ .key="pm1", .type=NET_INFLUX_F_FLOAT, .precision=1, .v.f=pm1 },
@@ -222,12 +248,13 @@ static void sen5x_task_producer(void* arg) {
{ .key="rh", .type=NET_INFLUX_F_FLOAT, .precision=3, .v.f=rh },
{ .key="voc", .type=NET_INFLUX_F_FLOAT, .precision=1, .v.f=voc },
{ .key="nox", .type=NET_INFLUX_F_FLOAT, .precision=1, .v.f=nox },
{ .key="co2", .type=NET_INFLUX_F_FLOAT, .precision=0, .v.f=co2 },
};
net_influx_point_t p = {
.measurement = "air",
.tags = g_device_tag ? g_device_tag : "device=unknown",
.ts_ms = 0, // Serverzeit
.ts_ms = 0, // Messzeitpunkt; Worker richtet UTC an Server-HTTP-Date aus
.fields = f,
.num_fields = sizeof(f) / sizeof(f[0]),
};
@@ -245,14 +272,14 @@ static void sen5x_task_producer(void* arg) {
}
/* ====================== Öffentliche API ====================== */
esp_err_t sen5x_app_init(const sen5x_i2c_cfg_t* cfg) {
esp_err_t air_sensor_app_init(const air_sensor_i2c_cfg_t* cfg) {
if (g_inited) {
ESP_LOGW(TAG, "already initialized");
return ESP_OK;
}
if (!cfg) return ESP_ERR_INVALID_ARG;
ESP_LOGI(TAG, "Initializing SEN5x app...");
ESP_LOGI(TAG, "Initializing selected air sensor...");
// 1) I2C-Subsystem
@@ -274,7 +301,7 @@ esp_err_t sen5x_app_init(const sen5x_i2c_cfg_t* cfg) {
CHECK_ESP_OR_RET(sensirion_i2c_esp32_ok());
// 4) Messung starten
CHECK_SEN_OR_RET(sen5x_start_measurement());
CHECK_SEN_OR_RET(sensor_start());
ESP_LOGI(TAG, "Measurement started.");
// 5) Device Tag (App-Kontext)
@@ -299,7 +326,7 @@ esp_err_t sen5x_app_init(const sen5x_i2c_cfg_t* cfg) {
return ESP_OK;
}
void sen5x_app_deinit(void) {
void air_sensor_app_deinit(void) {
if (!g_inited) return;
ESP_LOGI(TAG, "Deinitializing SEN5x app...");
@@ -311,8 +338,8 @@ void sen5x_app_deinit(void) {
}
if (g_task_prod) {
ESP_LOGW(TAG, "Producer did not stop in time; skip sen5x_stop_measurement/HAL free");
// Hier NICHT sen5x_stop_measurement() / HAL free, weil Task evtl. noch I2C nutzt
ESP_LOGW(TAG, "Producer did not stop in time; skip sensor_stop/HAL free");
// Hier NICHT sensor_stop() / HAL free, weil Task evtl. noch I2C nutzt
return;
}
@@ -323,33 +350,33 @@ void sen5x_app_deinit(void) {
g_device_tag = NULL;
}
sen5x_stop_measurement();
sensor_stop();
sensirion_i2c_hal_free();
// i2cdev_done(); // NICHT hier, da Bus global genutzt wird
g_inited = false;
ESP_LOGI(TAG, "SEN5x app deinitialized.");
ESP_LOGI(TAG, "Air sensor app deinitialized.");
}
/**
* Kompatibilität zur bisherigen main.c:
* Diese Task fungiert nun als "Launcher": startet Producer und beendet sich dann.
* In main.c bleibt der Aufruf von xTaskCreate(sen5x_app_task, ...) unverändert.
* In main.c bleibt der Aufruf von xTaskCreate(air_sensor_app_task, ...) unverändert.
*/
void sen5x_app_task(void* arg) {
void air_sensor_app_task(void* arg) {
(void)arg;
if (!g_inited) {
ESP_LOGE(TAG, "sen5x_app_task called before sen5x_app_init()");
ESP_LOGE(TAG, "air_sensor_app_task called before air_sensor_app_init()");
vTaskDelete(NULL);
return;
}
// Producer starten
if (xTaskCreate(sen5x_task_producer, "sen5x_prod",
SEN5X_PROD_STACK, NULL, SEN5X_PROD_PRIO, &g_task_prod) != pdPASS) {
if (xTaskCreate(air_sensor_task_producer, "air_sensor_prod",
AIR_SENSOR_PROD_STACK, NULL, AIR_SENSOR_PROD_PRIO, &g_task_prod) != pdPASS) {
ESP_LOGE(TAG, "Failed to create producer task");
vTaskDelete(NULL);
return;
@@ -5,20 +5,20 @@
// Schlanke I2C/HAL-Konfiguration (wie zuvor genutzt)
typedef struct {
uint8_t addr; // 7-bit I2C-Adresse (0x69)
uint8_t addr; // selected sensor, 7-bit I2C address
int port; // I2C Port (0)
int sda; // GPIO SDA
int scl; // GPIO SCL
bool sda_pullup; // interne Pullups
bool scl_pullup; // interne Pullups
uint32_t freq; // I2C Takt (Hz, z.B. 400000)
} sen5x_i2c_cfg_t;
} air_sensor_i2c_cfg_t;
// Initialisiert I2C/Treiber/HAL und startet die Messung
esp_err_t sen5x_app_init(const sen5x_i2c_cfg_t* cfg);
esp_err_t air_sensor_app_init(const air_sensor_i2c_cfg_t* cfg);
// Endlosschleife (Pollt "data ready" und loggt Messwerte); als FreeRTOS-Task nutzbar
void sen5x_app_task(void* arg);
void air_sensor_app_task(void* arg);
// Stoppt Messung & gibt Ressourcen frei (optional aufzurufen z.B. bei Shutdown)
void sen5x_app_deinit(void);
void air_sensor_app_deinit(void);
+798
View File
@@ -0,0 +1,798 @@
/*
* THIS FILE IS AUTOMATICALLY GENERATED
*
* Generator: sensirion-driver-generator 1.7.0
* Product: sen66
* Model-Version: 1.7.3
*/
/*
* Copyright (c) 2026, Sensirion AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Sensirion AG nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sen66_i2c.h"
#include "sensirion_common.h"
#include "sensirion_i2c.h"
#include "sensirion_i2c_hal.h"
#define sensirion_hal_sleep_us sensirion_i2c_hal_sleep_usec
static uint8_t communication_buffer[48] = {0};
static uint8_t _i2c_address;
void sen66_init(uint8_t i2c_address) {
_i2c_address = i2c_address;
}
int16_t sen66_get_voc_algorithm_tuning_parameters(
int16_t* index_offset, int16_t* learning_time_offset_hours,
int16_t* learning_time_gain_hours, int16_t* gating_max_duration_minutes,
int16_t* std_initial, int16_t* gain_factor) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_GET_VOC_ALGORITHM_TUNING_PARAMETERS_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 12);
if (local_error != NO_ERROR) {
return local_error;
}
*index_offset = sensirion_common_bytes_to_int16_t(&buffer_ptr[0]);
*learning_time_offset_hours =
sensirion_common_bytes_to_int16_t(&buffer_ptr[2]);
*learning_time_gain_hours =
sensirion_common_bytes_to_int16_t(&buffer_ptr[4]);
*gating_max_duration_minutes =
sensirion_common_bytes_to_int16_t(&buffer_ptr[6]);
*std_initial = sensirion_common_bytes_to_int16_t(&buffer_ptr[8]);
*gain_factor = sensirion_common_bytes_to_int16_t(&buffer_ptr[10]);
return local_error;
}
int16_t sen66_set_voc_algorithm_tuning_parameters(
int16_t index_offset, int16_t learning_time_offset_hours,
int16_t learning_time_gain_hours, int16_t gating_max_duration_minutes,
int16_t std_initial, int16_t gain_factor) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_SET_VOC_ALGORITHM_TUNING_PARAMETERS_CMD_ID);
local_offset = sensirion_i2c_add_int16_t_to_buffer(buffer_ptr, local_offset,
index_offset);
local_offset = sensirion_i2c_add_int16_t_to_buffer(
buffer_ptr, local_offset, learning_time_offset_hours);
local_offset = sensirion_i2c_add_int16_t_to_buffer(
buffer_ptr, local_offset, learning_time_gain_hours);
local_offset = sensirion_i2c_add_int16_t_to_buffer(
buffer_ptr, local_offset, gating_max_duration_minutes);
local_offset = sensirion_i2c_add_int16_t_to_buffer(buffer_ptr, local_offset,
std_initial);
local_offset = sensirion_i2c_add_int16_t_to_buffer(buffer_ptr, local_offset,
gain_factor);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t sen66_get_voc_algorithm_state(uint8_t* state, uint16_t state_size) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_VOC_ALGORITHM_STATE_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 8);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_common_copy_bytes(&buffer_ptr[0], (uint8_t*)state, state_size);
return local_error;
}
int16_t sen66_set_voc_algorithm_state(const uint8_t* state,
uint16_t state_size) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_SET_VOC_ALGORITHM_STATE_CMD_ID);
local_offset = sensirion_i2c_add_bytes_to_buffer(buffer_ptr, local_offset,
state, state_size);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
return local_error;
}
int16_t sen66_get_nox_algorithm_tuning_parameters(
int16_t* index_offset, int16_t* learning_time_offset_hours,
int16_t* learning_time_gain_hours, int16_t* gating_max_duration_minutes,
int16_t* std_initial, int16_t* gain_factor) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_GET_NOX_ALGORITHM_TUNING_PARAMETERS_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 12);
if (local_error != NO_ERROR) {
return local_error;
}
*index_offset = sensirion_common_bytes_to_int16_t(&buffer_ptr[0]);
*learning_time_offset_hours =
sensirion_common_bytes_to_int16_t(&buffer_ptr[2]);
*learning_time_gain_hours =
sensirion_common_bytes_to_int16_t(&buffer_ptr[4]);
*gating_max_duration_minutes =
sensirion_common_bytes_to_int16_t(&buffer_ptr[6]);
*std_initial = sensirion_common_bytes_to_int16_t(&buffer_ptr[8]);
*gain_factor = sensirion_common_bytes_to_int16_t(&buffer_ptr[10]);
return local_error;
}
int16_t sen66_set_nox_algorithm_tuning_parameters(
int16_t index_offset, int16_t learning_time_offset_hours,
int16_t learning_time_gain_hours, int16_t gating_max_duration_minutes,
int16_t std_initial, int16_t gain_factor) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_SET_NOX_ALGORITHM_TUNING_PARAMETERS_CMD_ID);
local_offset = sensirion_i2c_add_int16_t_to_buffer(buffer_ptr, local_offset,
index_offset);
local_offset = sensirion_i2c_add_int16_t_to_buffer(
buffer_ptr, local_offset, learning_time_offset_hours);
local_offset = sensirion_i2c_add_int16_t_to_buffer(
buffer_ptr, local_offset, learning_time_gain_hours);
local_offset = sensirion_i2c_add_int16_t_to_buffer(
buffer_ptr, local_offset, gating_max_duration_minutes);
local_offset = sensirion_i2c_add_int16_t_to_buffer(buffer_ptr, local_offset,
std_initial);
local_offset = sensirion_i2c_add_int16_t_to_buffer(buffer_ptr, local_offset,
gain_factor);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t
sen66_perform_forced_co2_recalibration(uint16_t target_co2_concentration,
uint16_t* correction) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_PERFORM_FORCED_CO2_RECALIBRATION_CMD_ID);
local_offset = sensirion_i2c_add_uint16_t_to_buffer(
buffer_ptr, local_offset, target_co2_concentration);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(500 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 2);
if (local_error != NO_ERROR) {
return local_error;
}
*correction = sensirion_common_bytes_to_uint16_t(&buffer_ptr[0]);
return local_error;
}
int16_t sen66_perform_co2_sensor_factory_reset(void) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_PERFORM_CO2_SENSOR_FACTORY_RESET_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(1400 * 1000);
return local_error;
}
int16_t sen66_get_co2_sensor_automatic_self_calibration(uint8_t* padding,
bool* status) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_GET_CO2_SENSOR_AUTOMATIC_SELF_CALIBRATION_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 2);
if (local_error != NO_ERROR) {
return local_error;
}
*padding = (uint8_t)buffer_ptr[0];
*status = (bool)buffer_ptr[1];
return local_error;
}
int16_t sen66_set_co2_sensor_automatic_self_calibration(uint16_t status) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_SET_CO2_SENSOR_AUTOMATIC_SELF_CALIBRATION_CMD_ID);
local_offset =
sensirion_i2c_add_uint16_t_to_buffer(buffer_ptr, local_offset, status);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t sen66_get_ambient_pressure(uint16_t* ambient_pressure) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_AMBIENT_PRESSURE_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 2);
if (local_error != NO_ERROR) {
return local_error;
}
*ambient_pressure = sensirion_common_bytes_to_uint16_t(&buffer_ptr[0]);
return local_error;
}
int16_t sen66_set_ambient_pressure(uint16_t ambient_pressure) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_SET_AMBIENT_PRESSURE_CMD_ID);
local_offset = sensirion_i2c_add_uint16_t_to_buffer(
buffer_ptr, local_offset, ambient_pressure);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t sen66_get_sensor_altitude(uint16_t* altitude) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_SENSOR_ALTITUDE_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 2);
if (local_error != NO_ERROR) {
return local_error;
}
*altitude = sensirion_common_bytes_to_uint16_t(&buffer_ptr[0]);
return local_error;
}
int16_t sen66_set_sensor_altitude(uint16_t altitude) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_SET_SENSOR_ALTITUDE_CMD_ID);
local_offset = sensirion_i2c_add_uint16_t_to_buffer(buffer_ptr,
local_offset, altitude);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t sen66_start_continuous_measurement(void) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_START_CONTINUOUS_MEASUREMENT_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(50 * 1000);
return local_error;
}
int16_t sen66_stop_measurement(void) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_STOP_MEASUREMENT_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(1400 * 1000);
return local_error;
}
int16_t sen66_get_data_ready(uint8_t* padding, bool* data_ready) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_DATA_READY_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 2);
if (local_error != NO_ERROR) {
return local_error;
}
*padding = (uint8_t)buffer_ptr[0];
*data_ready = (bool)buffer_ptr[1];
return local_error;
}
int16_t sen66_read_number_concentration_values_as_integers(
uint16_t* number_concentration_pm0p5, uint16_t* number_concentration_pm1p0,
uint16_t* number_concentration_pm2p5, uint16_t* number_concentration_pm4p0,
uint16_t* number_concentration_pm10p0) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_READ_NUMBER_CONCENTRATION_VALUES_AS_INTEGERS_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 10);
if (local_error != NO_ERROR) {
return local_error;
}
*number_concentration_pm0p5 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[0]);
*number_concentration_pm1p0 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[2]);
*number_concentration_pm2p5 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[4]);
*number_concentration_pm4p0 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[6]);
*number_concentration_pm10p0 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[8]);
return local_error;
}
int16_t sen66_set_temperature_offset_parameters(int16_t offset, int16_t slope,
uint16_t time_constant,
uint16_t slot) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_SET_TEMPERATURE_OFFSET_PARAMETERS_CMD_ID);
local_offset =
sensirion_i2c_add_int16_t_to_buffer(buffer_ptr, local_offset, offset);
local_offset =
sensirion_i2c_add_int16_t_to_buffer(buffer_ptr, local_offset, slope);
local_offset = sensirion_i2c_add_uint16_t_to_buffer(
buffer_ptr, local_offset, time_constant);
local_offset =
sensirion_i2c_add_uint16_t_to_buffer(buffer_ptr, local_offset, slot);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t sen66_set_temperature_acceleration_parameters(uint16_t k, uint16_t p,
uint16_t t1,
uint16_t t2) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_SET_TEMPERATURE_ACCELERATION_PARAMETERS_CMD_ID);
local_offset =
sensirion_i2c_add_uint16_t_to_buffer(buffer_ptr, local_offset, k);
local_offset =
sensirion_i2c_add_uint16_t_to_buffer(buffer_ptr, local_offset, p);
local_offset =
sensirion_i2c_add_uint16_t_to_buffer(buffer_ptr, local_offset, t1);
local_offset =
sensirion_i2c_add_uint16_t_to_buffer(buffer_ptr, local_offset, t2);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t sen66_get_product_type(int8_t* product_type,
uint16_t product_type_size) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_PRODUCT_TYPE_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 32);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_common_copy_bytes(&buffer_ptr[0], (uint8_t*)product_type,
product_type_size);
return local_error;
}
int16_t sen66_get_product_name(int8_t* product_name,
uint16_t product_name_size) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_PRODUCT_NAME_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 32);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_common_copy_bytes(&buffer_ptr[0], (uint8_t*)product_name,
product_name_size);
return local_error;
}
int16_t sen66_get_serial_number(int8_t* serial_number,
uint16_t serial_number_size) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_SERIAL_NUMBER_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 32);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_common_copy_bytes(&buffer_ptr[0], (uint8_t*)serial_number,
serial_number_size);
return local_error;
}
int16_t sen66_read_device_status(sen66_device_status* device_status) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_READ_DEVICE_STATUS_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 4);
if (local_error != NO_ERROR) {
return local_error;
}
(*device_status).value = sensirion_common_bytes_to_uint32_t(&buffer_ptr[0]);
return local_error;
}
int16_t sen66_read_and_clear_device_status(sen66_device_status* device_status) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_READ_AND_CLEAR_DEVICE_STATUS_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 4);
if (local_error != NO_ERROR) {
return local_error;
}
(*device_status).value = sensirion_common_bytes_to_uint32_t(&buffer_ptr[0]);
return local_error;
}
int16_t sen66_get_version(uint8_t* firmware_major, uint8_t* firmware_minor) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_VERSION_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 2);
if (local_error != NO_ERROR) {
return local_error;
}
*firmware_major = (uint8_t)buffer_ptr[0];
*firmware_minor = (uint8_t)buffer_ptr[1];
return local_error;
}
int16_t sen66_device_reset(void) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_DEVICE_RESET_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(1200 * 1000);
return local_error;
}
int16_t sen66_start_fan_cleaning(void) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_START_FAN_CLEANING_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t sen66_activate_sht_heater(void) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_ACTIVATE_SHT_HEATER_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
return local_error;
}
int16_t sen66_get_sht_heater_measurements(int16_t* sht_relative_humidity,
int16_t* sht_temperature) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_GET_SHT_HEATER_MEASUREMENTS_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 4);
if (local_error != NO_ERROR) {
return local_error;
}
*sht_relative_humidity = sensirion_common_bytes_to_int16_t(&buffer_ptr[0]);
*sht_temperature = sensirion_common_bytes_to_int16_t(&buffer_ptr[2]);
return local_error;
}
int16_t sen66_read_measured_values_as_integers(
uint16_t* mass_concentration_pm1p0, uint16_t* mass_concentration_pm2p5,
uint16_t* mass_concentration_pm4p0, uint16_t* mass_concentration_pm10p0,
int16_t* ambient_humidity, int16_t* ambient_temperature, int16_t* voc_index,
int16_t* nox_index, uint16_t* co2) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset,
SEN66_READ_MEASURED_VALUES_AS_INTEGERS_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 18);
if (local_error != NO_ERROR) {
return local_error;
}
*mass_concentration_pm1p0 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[0]);
*mass_concentration_pm2p5 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[2]);
*mass_concentration_pm4p0 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[4]);
*mass_concentration_pm10p0 =
sensirion_common_bytes_to_uint16_t(&buffer_ptr[6]);
*ambient_humidity = sensirion_common_bytes_to_int16_t(&buffer_ptr[8]);
*ambient_temperature = sensirion_common_bytes_to_int16_t(&buffer_ptr[10]);
*voc_index = sensirion_common_bytes_to_int16_t(&buffer_ptr[12]);
*nox_index = sensirion_common_bytes_to_int16_t(&buffer_ptr[14]);
*co2 = sensirion_common_bytes_to_uint16_t(&buffer_ptr[16]);
return local_error;
}
int16_t sen66_read_measured_raw_values(int16_t* raw_humidity,
int16_t* raw_temperature,
uint16_t* raw_voc, uint16_t* raw_nox,
uint16_t* raw_co2) {
int16_t local_error = NO_ERROR;
uint8_t* buffer_ptr = communication_buffer;
uint16_t local_offset = 0;
local_offset = sensirion_i2c_add_command16_to_buffer(
buffer_ptr, local_offset, SEN66_READ_MEASURED_RAW_VALUES_CMD_ID);
local_error =
sensirion_i2c_write_data(_i2c_address, buffer_ptr, local_offset);
if (local_error != NO_ERROR) {
return local_error;
}
sensirion_i2c_hal_sleep_usec(20 * 1000);
local_error = sensirion_i2c_read_data_inplace(_i2c_address, buffer_ptr, 10);
if (local_error != NO_ERROR) {
return local_error;
}
*raw_humidity = sensirion_common_bytes_to_int16_t(&buffer_ptr[0]);
*raw_temperature = sensirion_common_bytes_to_int16_t(&buffer_ptr[2]);
*raw_voc = sensirion_common_bytes_to_uint16_t(&buffer_ptr[4]);
*raw_nox = sensirion_common_bytes_to_uint16_t(&buffer_ptr[6]);
*raw_co2 = sensirion_common_bytes_to_uint16_t(&buffer_ptr[8]);
return local_error;
}
+899
View File
@@ -0,0 +1,899 @@
/*
* THIS FILE IS AUTOMATICALLY GENERATED
*
* Generator: sensirion-driver-generator 1.7.0
* Product: sen66
* Model-Version: 1.7.3
*/
/*
* Copyright (c) 2026, Sensirion AG
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of Sensirion AG nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SEN66_I2C_H
#define SEN66_I2C_H
#ifdef __cplusplus
extern "C" {
#endif
#include "sensirion_config.h"
#define SEN66_I2C_ADDR_6B 0x6b
typedef enum {
SEN66_GET_VOC_ALGORITHM_TUNING_PARAMETERS_CMD_ID = 0x60d0,
SEN66_SET_VOC_ALGORITHM_TUNING_PARAMETERS_CMD_ID = 0x60d0,
SEN66_GET_VOC_ALGORITHM_STATE_CMD_ID = 0x6181,
SEN66_SET_VOC_ALGORITHM_STATE_CMD_ID = 0x6181,
SEN66_GET_NOX_ALGORITHM_TUNING_PARAMETERS_CMD_ID = 0x60e1,
SEN66_SET_NOX_ALGORITHM_TUNING_PARAMETERS_CMD_ID = 0x60e1,
SEN66_PERFORM_FORCED_CO2_RECALIBRATION_CMD_ID = 0x6707,
SEN66_PERFORM_CO2_SENSOR_FACTORY_RESET_CMD_ID = 0x6754,
SEN66_GET_CO2_SENSOR_AUTOMATIC_SELF_CALIBRATION_CMD_ID = 0x6711,
SEN66_SET_CO2_SENSOR_AUTOMATIC_SELF_CALIBRATION_CMD_ID = 0x6711,
SEN66_GET_AMBIENT_PRESSURE_CMD_ID = 0x6720,
SEN66_SET_AMBIENT_PRESSURE_CMD_ID = 0x6720,
SEN66_GET_SENSOR_ALTITUDE_CMD_ID = 0x6736,
SEN66_SET_SENSOR_ALTITUDE_CMD_ID = 0x6736,
SEN66_START_CONTINUOUS_MEASUREMENT_CMD_ID = 0x21,
SEN66_STOP_MEASUREMENT_CMD_ID = 0x104,
SEN66_GET_DATA_READY_CMD_ID = 0x202,
SEN66_READ_NUMBER_CONCENTRATION_VALUES_AS_INTEGERS_CMD_ID = 0x316,
SEN66_SET_TEMPERATURE_OFFSET_PARAMETERS_CMD_ID = 0x60b2,
SEN66_SET_TEMPERATURE_ACCELERATION_PARAMETERS_CMD_ID = 0x6100,
SEN66_GET_PRODUCT_TYPE_CMD_ID = 0xd002,
SEN66_GET_PRODUCT_NAME_CMD_ID = 0xd014,
SEN66_GET_SERIAL_NUMBER_CMD_ID = 0xd033,
SEN66_READ_DEVICE_STATUS_CMD_ID = 0xd206,
SEN66_READ_AND_CLEAR_DEVICE_STATUS_CMD_ID = 0xd210,
SEN66_GET_VERSION_CMD_ID = 0xd100,
SEN66_DEVICE_RESET_CMD_ID = 0xd304,
SEN66_START_FAN_CLEANING_CMD_ID = 0x5607,
SEN66_ACTIVATE_SHT_HEATER_CMD_ID = 0x6765,
SEN66_GET_SHT_HEATER_MEASUREMENTS_CMD_ID = 0x6790,
SEN66_READ_MEASURED_VALUES_AS_INTEGERS_CMD_ID = 0x300,
SEN66_READ_MEASURED_RAW_VALUES_CMD_ID = 0x405,
} SEN66_CMD_ID;
typedef union {
struct {
uint32_t reserved1 : 4;
uint32_t fan_error : 1;
uint32_t reserved2 : 1;
uint32_t rht_error : 1;
uint32_t gas_error : 1;
uint32_t reserved3 : 1;
uint32_t co2_2_error : 1;
uint32_t hcho_error : 1;
uint32_t pm_error : 1;
uint32_t co2_1_error : 1;
uint32_t reserved4 : 8;
uint32_t fan_speed_warning : 1;
uint32_t reserved5 : 10;
};
uint32_t value;
} sen66_device_status;
/**
* @brief Initialize i2c address of driver
*
* @param[in] i2c_address Used i2c address
*
*/
void sen66_init(uint8_t i2c_address);
/**
* @brief sen66_get_voc_algorithm_tuning_parameters
*
* Gets the parameters to customize the VOC algorithm.
*
* @param[out] index_offset VOC index representing typical (average) conditions.
* @param[out] learning_time_offset_hours Time constant to estimate the VOC
* algorithm offset from the history in hours. Past events will be forgotten
* after about twice the learning time.
* @param[out] learning_time_gain_hours Time constant to estimate the VOC
* algorithm gain from the history in hours. Past events will be forgotten after
* about twice the learning time.
* @param[out] gating_max_duration_minutes Maximum duration of gating in minutes
* (freeze of estimator during high VOC index signal). Zero disables the gating.
* @param[out] std_initial Initial estimate for standard deviation. Lower value
* boosts events during initial learning period, but may result in larger
* device-to-device variations.
* @param[out] gain_factor Gain factor to amplify or to attenuate the VOC index
* output.
*
* @note This command is only available in idle mode.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_voc_algorithm_tuning_parameters(
int16_t* index_offset, int16_t* learning_time_offset_hours,
int16_t* learning_time_gain_hours, int16_t* gating_max_duration_minutes,
int16_t* std_initial, int16_t* gain_factor);
/**
* @brief sen66_set_voc_algorithm_tuning_parameters
*
* Sets the parameters to customize the VOC algorithm. This configuration is
* volatile, i.e. the parameters will be reverted to their default values after
* a device reset.
*
* @param[in] index_offset VOC index representing typical (average) conditions.
* Allowed values are in range 1..250. The default value is 100.
* @param[in] learning_time_offset_hours Time constant to estimate the VOC
* algorithm offset from the history in hours. Past events will be forgotten
* after about twice the learning time. Allowed values are in range 1..1000. The
* default value is 12 hours.
* @param[in] learning_time_gain_hours Time constant to estimate the VOC
* algorithm gain from the history in hours. Past events will be forgotten after
* about twice the learning time. Allowed values are in range 1..1000. The
* default value is 12 hours.
* @param[in] gating_max_duration_minutes Maximum duration of gating in minutes
* (freeze of estimator during high VOC index signal). Set to zero to disable
* the gating. Allowed values are in range 0..3000. The default value is 180
* minutes
* @param[in] std_initial Initial estimate for standard deviation. Lower value
* boosts events during initial learning period, but may result in larger
* device-to-device variations. Allowed values are in range 10..5000. The
* default value is 50.
* @param[in] gain_factor Gain factor to amplify or to attenuate the VOC index
* output. Allowed values are in range 1..1000. The default value is 230.
*
* @note This command is available only in idle mode. In measure mode, this
* command has no effect. In addition, it has no effect if at least one
* parameter is outside the specified range.
*
* @return error_code 0 on success, an error code otherwise.
*
* Example:
* --------
*
* @code{.c}
*
* int16_t local_error = 0;
*
* local_error = sen66_set_voc_algorithm_tuning_parameters(100, 12, 12, 180,
* 50, 230); if (local_error != NO_ERROR) { return local_error;
* }
*
* @endcode
*
*/
int16_t sen66_set_voc_algorithm_tuning_parameters(
int16_t index_offset, int16_t learning_time_offset_hours,
int16_t learning_time_gain_hours, int16_t gating_max_duration_minutes,
int16_t std_initial, int16_t gain_factor);
/**
* @brief sen66_get_voc_algorithm_state
*
* Gets the current VOC algorithm state. Allows to backup and restore the VOC
* algorithm state to resume operation after a power cycle or device reset,
* skipping initial learning phase. By default, the VOC Engine is reset and the
* algorithm state is retained if a measurement is stopped and started again.
* If the VOC algorithm state shall be reset, a device reset or a power cycle
* can be executed.
*
* @param[out] state Current VOC algorithm state.
*
* @note This command can be used either in measure mode or in idle mode (which
* will then return the state at the time when the measurement was stopped). In
* measure mode, the state can be read each measure interval to always have the
* latest state available, even in case of a sudden power loss.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_voc_algorithm_state(uint8_t* state, uint16_t state_size);
/**
* @brief sen66_set_voc_algorithm_state
*
* Sets the VOC algorithm state previously received with "Get VOC Algorithm
* State" command. Allows restoration of the VOC algorithm state to resume
* operation after a power cycle or device reset, skipping initial learning
* phase. By default, the VOC Engine is reset, and the algorithm state is
* retained if a measurement is stopped and started again. If the VOC algorithm
* state shall be reset, a device reset, or a power cycle can be executed.
*
* @param[in] state VOC algorithm state to restore.
*
* @note This command is only available in idle mode and the state will be
* applied only once when starting the next measurement. In measure mode, this
* command has no effect.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_set_voc_algorithm_state(const uint8_t* state,
uint16_t state_size);
/**
* @brief sen66_get_nox_algorithm_tuning_parameters
*
* Gets the parameters to customize the NOx algorithm.
*
* @param[out] index_offset NOx index representing typical (average) conditions.
* @param[out] learning_time_offset_hours Time constant to estimate the NOx
* algorithm offset from the history in hours. Past events will be forgotten
* after about twice the learning time.
* @param[out] learning_time_gain_hours The time constant to estimate the NOx
* algorithm gain from the history has no impact for NOx. This parameter is
* still in place for consistency reasons with the VOC tuning parameters
* command.
* @param[out] gating_max_duration_minutes Maximum duration of gating in minutes
* (freeze of estimator during high NOx index signal). Zero disables the gating.
* @param[out] std_initial The initial estimate for standard deviation has no
* impact for NOx. This parameter is still in place for consistency reasons with
* the VOC tuning parameters command.
* @param[out] gain_factor Gain factor to amplify or to attenuate the NOx index
* output.
*
* @note This command is available only in idle mode.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_nox_algorithm_tuning_parameters(
int16_t* index_offset, int16_t* learning_time_offset_hours,
int16_t* learning_time_gain_hours, int16_t* gating_max_duration_minutes,
int16_t* std_initial, int16_t* gain_factor);
/**
* @brief sen66_set_nox_algorithm_tuning_parameters
*
* Sets the parameters to customize the NOx algorithm. This configuration is
* volatile, i.e. the parameters will be reverted to their default values after
* a device reset.
*
* @param[in] index_offset NOx index representing typical (average) conditions.
* Allowed values are in range 1..250. The default value is 1.
* @param[in] learning_time_offset_hours Time constant to estimate the NOx
* algorithm offset from the history in hours. Past events will be forgotten
* after about twice the learning time. Allowed values are in range 1..1000. The
* default value is 12 hours.
* @param[in] learning_time_gain_hours The time constant to estimate the NOx
* algorithm gain from the history has no impact for NOx. This parameter is
* still in place for consistency reasons with the VOC tuning parameters
* command. This parameter must always be set to 12 hours.
* @param[in] gating_max_duration_minutes Maximum duration of gating in minutes
* (freeze of estimator during high NOx index signal). Set to zero to disable
* the gating. Allowed values are in range 0..3000. The default value is 720
* minutes.
* @param[in] std_initial The initial estimate for standard deviation parameter
* has no impact for NOx. This parameter is still in place for consistency
* reasons with the VOC tuning parameters command. This parameter must always be
* set to 50.
* @param[in] gain_factor Gain factor to amplify or to attenuate the NOx index
* output. Allowed values are in range 1..1000. The default value is 230.
*
* @note This command is available only in idle mode. In measure mode, this
* command has no effect. In addition, it has no effect if at least one
* parameter is outside the specified range.
*
* @return error_code 0 on success, an error code otherwise.
*
* Example:
* --------
*
* @code{.c}
*
* int16_t local_error = 0;
*
* local_error = sen66_set_nox_algorithm_tuning_parameters(1, 12, 12, 720,
* 50, 230); if (local_error != NO_ERROR) { return local_error;
* }
*
* @endcode
*
*/
int16_t sen66_set_nox_algorithm_tuning_parameters(
int16_t index_offset, int16_t learning_time_offset_hours,
int16_t learning_time_gain_hours, int16_t gating_max_duration_minutes,
int16_t std_initial, int16_t gain_factor);
/**
* @brief Perform Forced CO₂ Recalibration
*
* Execute the forced recalibration (FRC) of the CO₂. See the datasheet of the
* SCD4x sensor for details how the forced recalibration shall be used.
*
* @param[in] target_co2_concentration Target CO₂ concentration [ppm] of the
* test setup.
* @param[out] correction Correction value as received from the SCD [ppm CO₂].
* FRC correction [ppm CO₂] is calculated as follows: FRC = return_value -
* 0x8000 If the recalibration has failed this returned value is 0xFFFF.
*
* @note After power-on wait at least 1000 ms and after stopping a measurement
* 600 ms before sending this command. This command is not available in measure
* mode. The recalibration procedure will take about 500 ms to complete, during
* which time no other functions can be executed. This configuration is
* persistent, i.e. the parameters will be retained during a device reset or
* power cycle.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t
sen66_perform_forced_co2_recalibration(uint16_t target_co2_concentration,
uint16_t* correction);
/**
* @brief Perform CO₂ Sensor Factory Reset
*
* This command resets all CO₂ sensor configuration settings stored in the
* EEPROM and erases the FRC and ASC algorithm history of the CO₂ sensor. The
* configuration settings are CO₂ sensor temperature offset (cannot be modified
* over I2C interface), sensor altitude and the ASC enabled/disabled parameters
* which are by default stored in the volatile memory (RAM). This command is
* only available in idle mode.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_perform_co2_sensor_factory_reset(void);
/**
* @brief sen66_get_co2_sensor_automatic_self_calibration
*
* The CO₂ sensor supports automatic self calibration (ASC) for long-term
* stability of the CO₂ output. This feature can be enabled or disabled. By
* default it is enabled.
*
* @param[out] padding Padding byte, always 0x00.
* @param[out] status Is set true (0x01) if the automatic self calibration is
* enabled or false (0x00) if the automatic self calibration is disabled.
*
* @note This command is only available in idle mode. This configuration is
* persistent, i.e. the status will be retained during a device reset or power
* cycle.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_co2_sensor_automatic_self_calibration(uint8_t* padding,
bool* status);
/**
* @brief sen66_set_co2_sensor_automatic_self_calibration
*
* Sets the status of the CO₂ sensor automatic self-calibration (ASC). The CO₂
* sensor supports automatic self calibration (ASC) for long-term stability of
* the CO₂ output. This feature can be enabled or disabled. By default it is
* enabled.
*
* @param[in] status Set to true (0x0001) to enable or false (0x0000) to disable
* the automatic CO₂ measurement self calibration feature. High byte of uint16
* is padding and always 0x00.
*
* @note This command is only available in idle mode. This configuration is
* persistent, i.e. the status will be retained during a device reset or power
* cycle.
*
* @return error_code 0 on success, an error code otherwise.
*
* Example:
* --------
*
* @code{.c}
*
* int16_t local_error = 0;
*
* local_error = sen66_set_co2_sensor_automatic_self_calibration(0);
* if (local_error != NO_ERROR) {
* return local_error;
* }
*
* @endcode
*
*/
int16_t sen66_set_co2_sensor_automatic_self_calibration(uint16_t status);
/**
* @brief sen66_get_ambient_pressure
*
* Gets the ambient pressure value. The ambient pressure can be used for
* pressure compensation in the CO₂ sensor.
*
* @param[out] ambient_pressure Currently used ambient pressure [hPa] for
* pressure compensation.
*
* @note This command can be used in any state of the device, i.e. both in idle
* mode and in measure mode.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_ambient_pressure(uint16_t* ambient_pressure);
/**
* @brief sen66_set_ambient_pressure
*
* The ambient pressure can be used for pressure compensation in the CO₂ sensor.
* Setting an ambient pressure overrides any pressure compensation based on a
* previously set sensor altitude. Use of this command is recommended for
* applications experiencing significant ambient pressure changes to ensure CO₂
* sensor accuracy. Valid input values are between 700 to 1'200 hPa. The default
* value is 1013 hPa. This configuration is volatile, i.e. the parameter will be
* reverted to its default value after a device restart.
*
* @param[in] ambient_pressure Ambient pressure [hPa] to be used for pressure
* compensation.
*
* @note This command can be used in any state of the device, i.e. both in idle
* mode and in measure mode.
*
* @return error_code 0 on success, an error code otherwise.
*
* Example:
* --------
*
* @code{.c}
*
* int16_t local_error = 0;
*
* local_error = sen66_set_ambient_pressure(1013);
* if (local_error != NO_ERROR) {
* return local_error;
* }
*
* @endcode
*
*/
int16_t sen66_set_ambient_pressure(uint16_t ambient_pressure);
/**
* @brief sen66_get_sensor_altitude
*
* Gets the current sensor altitude. The sensor altitude can be used for
* pressure compensation in the CO₂ sensor.
*
* @param[out] altitude Current sensor altitude [m].
*
* @note This command is only available in idle mode.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_sensor_altitude(uint16_t* altitude);
/**
* @brief sen66_set_sensor_altitude
*
* The sensor altitude can be used for pressure compensation in the CO₂ sensor.
* The default sensor altitude value is set to 0 meters above sea level. Valid
* input values are between 0 and 3000m. This configuration is volatile, i.e.
* the parameter will be reverted to its default value after a device reset.
*
* @param[in] altitude Sensor altitude [m], valid input between 0 and 3000m.
*
* @return error_code 0 on success, an error code otherwise.
*
* Example:
* --------
*
* @code{.c}
*
* int16_t local_error = 0;
*
* local_error = sen66_set_sensor_altitude(0);
* if (local_error != NO_ERROR) {
* return local_error;
* }
*
* @endcode
*
*/
int16_t sen66_set_sensor_altitude(uint16_t altitude);
/**
* @brief Start a continuous measurement (interval 1s)
*
* Starts a continuous measurement. After starting the measurement, it takes
* some time (~1.1s) until the first measurement results are available. You
* could poll with the command "Get Data Ready" to check when the results are
* ready to read. This command is only available in idle mode. If the device is
* already in any measure mode, this command has no effect.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_start_continuous_measurement(void);
/**
* @brief Stop the continuous measurement
*
* Stops the measurement and returns to idle mode. After sending this command,
* wait at least 1000 ms before starting a new measurement. If the device is
* already in idle mode, this command has no effect.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_stop_measurement(void);
/**
* @brief Check if data is ready to be read out from the sensor
*
* This command can be used to check if new measurement results are ready to
* read. The data ready flag is automatically reset after reading the
* measurement values.
*
* @param[out] padding Padding byte, always 0x00.
* @param[out] data_ready True (0x01) if data is ready, False (0x00) if not.
* When no measurement is running, False will be returned.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_data_ready(uint8_t* padding, bool* data_ready);
/**
* @brief sen66_read_number_concentration_values_as_integers
*
* Returns the measured number concentration values. The command 0x0202 "Get
* Data Ready" can be used to check if new data is available since the last read
* operation. If no new data is available, the previous values will be returned
* again. If no data is available at all (e.g. measurement not running for at
* least one second), all values will be at their upper limit (0xFFFF for
* uint16).
*
* @param[out] number_concentration_pm0p5 Value is scaled with factor 10: PM0.5
* [particles/cm³] = value / 10. *Note: If this value is unknown, 0xFFFF is
* returned.*
* @param[out] number_concentration_pm1p0 Value is scaled with factor 10: PM1.0
* [particles/cm³] = value / 10. *Note: If this value is unknown, 0xFFFF is
* returned.*
* @param[out] number_concentration_pm2p5 Value is scaled with factor 10: PM2.5
* [particles/cm³] = value / 10. *Note: If this value is unknown, 0xFFFF is
* returned.*
* @param[out] number_concentration_pm4p0 Value is scaled with factor 10: PM4.0
* [particles/cm³] = value / 10. *Note: If this value is unknown, 0xFFFF is
* returned.*
* @param[out] number_concentration_pm10p0 Value is scaled with factor 10:
* PM10.0 [particles/cm³] = value / 10. *Note: If this value is unknown, 0xFFFF
* is returned.*
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_read_number_concentration_values_as_integers(
uint16_t* number_concentration_pm0p5, uint16_t* number_concentration_pm1p0,
uint16_t* number_concentration_pm2p5, uint16_t* number_concentration_pm4p0,
uint16_t* number_concentration_pm10p0);
/**
* @brief sen66_set_temperature_offset_parameters
*
* This command allows to compensate temperature effects of the design-in at
* customer side by applying custom temperature offsets to the ambient
* temperature.
*
* The compensated ambient temperature is calculated as follows:
*
*
* * T_Ambient_Compensated = T_Ambient + (slope * T_Ambient) + offset
* Where "slope" and "offset" are the values set with this command, smoothed
* with the specified time constant. All temperatures
* ("T_Ambient_Compensated", "T_Ambient" and "offset") are represented in
* °C. There are 5 temperature offset slots available that all contribute
* additively to "T_Ambient_Compensated". The default values for the
* temperature offset parameters are all zero, meaning that
* "T_Ambient_Compensated" is equal to "T_Ambient" by default. The
* parameters can be changed in any state of the device, i.e. both in idle mode
* and in measure mode.
*
* @param[in] offset Constant temperature offset scaled with factor 200 (T [°C]
* = value / 200).
* @param[in] slope Normalized temperature offset slope scaled with factor 10000
* (applied factor = value / 10000).
* @param[in] time_constant The time constant determines how fast the new slope
* and offset will be applied. After the specified value in seconds, 63% of the
* new slope and offset are applied. A time constant of zero means the new
* values will be applied immediately (within the next measure interval of 1
* second).
* @param[in] slot The temperature offset slot to be modified. Valid values are
* 0 .. 4. If the value is outside this range, the parameters will not be
* applied.
*
* @note This configuration is volatile, i.e. the parameters will be reverted to
* their default value of zero after a device reset.
*
* @return error_code 0 on success, an error code otherwise.
*
* Example:
* --------
*
* @code{.c}
*
* int16_t local_error = 0;
*
* local_error = sen66_set_temperature_offset_parameters(1, 10, 1, 0);
* if (local_error != NO_ERROR) {
* return local_error;
* }
*
* @endcode
*
*/
int16_t sen66_set_temperature_offset_parameters(int16_t offset, int16_t slope,
uint16_t time_constant,
uint16_t slot);
/**
* @brief sen66_set_temperature_acceleration_parameters
*
* This command allows to set custom temperature acceleration parameters of the
* RH/T engine. It overwrites the default temperature acceleration parameters of
* the RH/T engine with custom values. This configuration is volatile, i.e. the
* parameters will be reverted to their default values after a device reset.
*
* @param[in] k Filter constant K scaled with factor 10 (K = value / 10).
* @param[in] p Filter constant P scaled with factor 10 (P = value / 10).
* @param[in] t1 Time constant T1 scaled with factor 10 (T1 [s] = value / 10).
* @param[in] t2 Time constant T2 scaled with factor 10 (T2 [s] = value / 10).
*
* @note The command is only available in idle mode.
*
* @return error_code 0 on success, an error code otherwise.
*
* Example:
* --------
*
* @code{.c}
*
* int16_t local_error = 0;
*
* local_error = sen66_set_temperature_acceleration_parameters(1, 1, 1, 1);
* if (local_error != NO_ERROR) {
* return local_error;
* }
*
* @endcode
*
*/
int16_t sen66_set_temperature_acceleration_parameters(uint16_t k, uint16_t p,
uint16_t t1, uint16_t t2);
/**
* @brief sen66_get_product_type
*
* Gets the product type from the device.
*
* The following product types are expected: - SEN62: '00085800' - SEN63C:
* '00085700' - SEN65: '00085200' - SEN66: '00085300' - SEN68: '00085400' -
* SEN69C: '00085900'
*
* @param[out] product_type Null-terminated ASCII string containing the product
* type. Up to 32 characters can be read from the device.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_product_type(int8_t* product_type,
uint16_t product_type_size);
/**
* @brief sen66_get_product_name
*
* Gets the product name from the device.
*
* @param[out] product_name Null-terminated ASCII string containing the product
* name. Up to 32 characters can be read from the device.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_product_name(int8_t* product_name,
uint16_t product_name_size);
/**
* @brief sen66_get_serial_number
*
* Gets the serial number from the device.
*
* @param[out] serial_number Null-terminated ASCII string containing the serial
* number. Up to 32 characters can be read from the device.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_serial_number(int8_t* serial_number,
uint16_t serial_number_size);
/**
* @brief sen66_read_device_status
*
* Reads the current device status. Use this command to get detailed information
* about the device status. The device status is encoded in flags. Each device
* status flag represents a single bit in a 32-bit integer value. If more than
* one error is present, the device status register value is the sum of the
* corresponding flag values. For details about the available flags, refer to
* the device status flags documentation in the data sheet.
*
* @param[out] device_status Device status (32 flags as an integer value). For
* details, please refer to the device status flags documentation in the
* datasheet.
*
* @note The status flags of type "Error" are sticky, i.e. they are not cleared
* automatically even if the error condition no longer exists. So they can only
* be cleared manually with the command "Read And Clear Device Status" or with a
* device reset. All other flags are not sticky, i.e. they are cleared
* automatically if the trigger condition disappears.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_read_device_status(sen66_device_status* device_status);
/**
* @brief sen66_read_and_clear_device_status
*
* Reads the current device status (like command 0xD206 "Read Device Status")
* and afterwards clears all flags.
*
* @param[out] device_status Device status (32 flags as an integer value)
* **before** clearing it. For details, please refer to the device status flags
* documentation.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_read_and_clear_device_status(sen66_device_status* device_status);
/**
* @brief sen66_get_version
*
* Gets the version information for the firmware.
*
* @param[out] firmware_major Firmware major version number.
* @param[out] firmware_minor Firmware minor version number.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_version(uint8_t* firmware_major, uint8_t* firmware_minor);
/**
* @brief sen66_device_reset
*
* Executes a reset on the device. This has the same effect as a power cycle.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_device_reset(void);
/**
* @brief sen66_start_fan_cleaning
*
* This command triggers fan cleaning. The fan is set to the maximum speed for
* 10 seconds and then automatically stopped. Wait at least 10s after this
* command before starting a measurement.
*
* @note This command is only available in idle mode.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_start_fan_cleaning(void);
/**
* @brief Activate SHT Heater
*
* Activate the heater feature of the SHT4x sensor. This command allows to use
* the inbuilt heater in SHT sensor to decontaminate and reverse creep at high
* humidity. This command activates the SHT sensor heater with 200mW for 1s. The
* SHT heater measurement done just before deactivation can be read using the
* command "Get SHT Heater Measurements" after the duration of the heating
* feature as specified in the SHT4x datasheet. Wait at least 20s after this
* command before starting a measurement to get coherent temperature values
* (heating consequence to disappear).
*
* @note This command is only available in idle mode.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_activate_sht_heater(void);
/**
* @brief Get SHT Heater Measurements
*
* Get the measurement values when the SHT sensor heating is finished.
*
* @param[out] sht_relative_humidity If the sht heating is completed, this value
* indicates the scaled relative humidity of the SHT4x sensor. Value is scaled
* with factor 100: RH [%] = value / 100 *Note: If this value is not available,
* 0x7FFF is returned.*
* @param[out] sht_temperature If the sht heating is completed, this value
* indicates the scaled temperature of the SHT4x sensor. Value is scaled with
* factor 200: T [°C] = value / 200 *Note: If this value is not available,
* 0x7FFF is returned.*
*
* @note This command must be used after the "Activate SHT Heater" command.
* The get sht heater measurements command can be queried every 0.05s to get the
* measurements. This command is only available in idle mode.
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_get_sht_heater_measurements(int16_t* sht_relative_humidity,
int16_t* sht_temperature);
/**
* @brief Read measured values as integers.
*
* Returns the measured values. The command "Get Data Ready" can be used to
* check if new data is available since the last read operation. If no new data
* is available, the previous values will be returned again. If no data is
* available at all (e.g. measurement not running for at least one second), all
* values will be at their upper limit (0xFFFF for uint16, 0x7FFF for int16).
*
* @param[out] mass_concentration_pm1p0 Value is scaled with factor 10: PM1.0
* [µg/m³] = value / 10 *Note: If this value is unknown, 0xFFFF is returned.*
* @param[out] mass_concentration_pm2p5 Value is scaled with factor 10: PM2.5
* [µg/m³] = value / 10 *Note: If this value is unknown, 0xFFFF is returned.*
* @param[out] mass_concentration_pm4p0 Value is scaled with factor 10: PM4.0
* [µg/m³] = value / 10 *Note: If this value is unknown, 0xFFFF is returned.*
* @param[out] mass_concentration_pm10p0 Value is scaled with factor 10: PM10.0
* [µg/m³] = value / 10 *Note: If this value is unknown, 0xFFFF is returned.*
* @param[out] ambient_humidity Value is scaled with factor 100: RH [%] = value
* / 100 *Note: If this value is unknown, 0x7FFF is returned.*
* @param[out] ambient_temperature Value is scaled with factor 200: T [°C] =
* value / 200 *Note: If this value is unknown, 0x7FFF is returned.*
* @param[out] voc_index Value is scaled with factor 10: VOC Index = value / 10
* *Note: If this value is unknown, 0x7FFF is returned.*
* @param[out] nox_index Value is scaled with factor 10: NOx Index = value / 10
* *Note: If this value is unknown, 0x7FFF is returned. During the first 10..11
* seconds after power-on or device reset, this value will be 0x7FFF as well.*
* @param[out] co2 CO₂ concentration [ppm] *Note: If this value is unknown,
* 0xFFFF is returned. During the first 5..6 seconds after power-on or device
* reset, this value will be 0xFFFF as well.*
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_read_measured_values_as_integers(
uint16_t* mass_concentration_pm1p0, uint16_t* mass_concentration_pm2p5,
uint16_t* mass_concentration_pm4p0, uint16_t* mass_concentration_pm10p0,
int16_t* ambient_humidity, int16_t* ambient_temperature, int16_t* voc_index,
int16_t* nox_index, uint16_t* co2);
/**
* @brief sen66_read_measured_raw_values
*
* Returns the measured raw values. The command "Get Data Ready" can be used to
* check if new data is available since the last read operation. If no new data
* is available, the previous values will be returned again. If no data is
* available at all (e.g. measurement not running for at least one second), all
* values will be at their upper limit (0xFFFF for uint16, 0x7FFF for int16).
*
* @param[out] raw_humidity Value is scaled with factor 100: RH [%] = value /
* 100 *Note: If this value is unknown, 0x7FFF is returned.*
* @param[out] raw_temperature Value is scaled with factor 200: T [°C] = value /
* 200 *Note: If this value is unknown, 0x7FFF is returned.*
* @param[out] raw_voc Raw measured VOC ticks without scale factor. *Note: If
* this value is unknown, 0xFFFF is returned.*
* @param[out] raw_nox Raw measured NOx ticks without scale factor. *Note: If
* this value is unknown, 0xFFFF is returned. During the first 10..11 seconds
* after power-on or device reset, this value will be 0xFFFF as well.*
* @param[out] raw_co2 Not interpolated CO₂ concentration [ppm] updated every
* five seconds. *Note: If this value is unknown, 0xFFFF is returned. During the
* first 5..6 seconds after power-on or device reset, this value will be 0xFFFF
* as well.*
*
* @return error_code 0 on success, an error code otherwise.
*/
int16_t sen66_read_measured_raw_values(int16_t* raw_humidity,
int16_t* raw_temperature,
uint16_t* raw_voc, uint16_t* raw_nox,
uint16_t* raw_co2);
#ifdef __cplusplus
}
#endif
#endif // SEN66_I2C_H
+32 -13
View File
@@ -28,7 +28,7 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// File: src/sensirion_common.c
#include "sensirion_common.h"
#include "sensirion_config.h"
@@ -60,27 +60,27 @@ float sensirion_common_bytes_to_float(const uint8_t* bytes) {
}
void sensirion_common_uint32_t_to_bytes(const uint32_t value, uint8_t* bytes) {
bytes[0] = value >> 24;
bytes[1] = value >> 16;
bytes[2] = value >> 8;
bytes[3] = value;
bytes[0] = (uint8_t)(value >> 24);
bytes[1] = (uint8_t)(value >> 16);
bytes[2] = (uint8_t)(value >> 8);
bytes[3] = (uint8_t)(value);
}
void sensirion_common_uint16_t_to_bytes(const uint16_t value, uint8_t* bytes) {
bytes[0] = value >> 8;
bytes[1] = value;
bytes[0] = (uint8_t)(value >> 8);
bytes[1] = (uint8_t)value;
}
void sensirion_common_int32_t_to_bytes(const int32_t value, uint8_t* bytes) {
bytes[0] = value >> 24;
bytes[1] = value >> 16;
bytes[2] = value >> 8;
bytes[3] = value;
bytes[0] = (uint8_t)(value >> 24);
bytes[1] = (uint8_t)(value >> 16);
bytes[2] = (uint8_t)(value >> 8);
bytes[3] = (uint8_t)value;
}
void sensirion_common_int16_t_to_bytes(const int16_t value, uint8_t* bytes) {
bytes[0] = value >> 8;
bytes[1] = value;
bytes[0] = (uint8_t)(value >> 8);
bytes[1] = (uint8_t)value;
}
void sensirion_common_float_to_bytes(const float value, uint8_t* bytes) {
@@ -99,3 +99,22 @@ void sensirion_common_copy_bytes(const uint8_t* source, uint8_t* destination,
destination[i] = source[i];
}
}
void sensirion_common_to_integer(const uint8_t* source, uint8_t* destination,
INT_TYPE int_type, uint8_t data_length) {
if (data_length > int_type) {
data_length = 0; // we do not read at all if data_length is bigger than
// the provided integer!
}
// pad missing bytes
uint8_t offset = int_type - data_length;
for (uint8_t i = 0; i < offset; i++) {
destination[int_type - i - 1] = 0;
}
for (uint8_t i = 1; i <= data_length; i++) {
destination[int_type - offset - i] = source[i - 1];
}
}
@@ -50,6 +50,11 @@ extern "C" {
#define SENSIRION_NUM_WORDS(x) (sizeof(x) / SENSIRION_WORD_SIZE)
#define SENSIRION_MAX_BUFFER_WORDS 32
/**
* Enum to describe the type of an integer
*/
typedef enum { BYTE = 1, SHORT = 2, INTEGER = 4, LONG_INTEGER = 8 } INT_TYPE;
/**
* sensirion_common_bytes_to_int16_t() - Convert an array of bytes to an int16_t
*
@@ -174,6 +179,17 @@ void sensirion_common_float_to_bytes(const float value, uint8_t* bytes);
void sensirion_common_copy_bytes(const uint8_t* source, uint8_t* destination,
uint16_t data_length);
/**
* sensirion_common_to_integer() - Copy bytes from byte array to integer.
*
* @param source Array of bytes to be copied.
* @param int_value Pointer to integer of bytes to be copied to.
* @param int_type Type (size) of the integer to be copied.
* @param data_length Number of bytes to copy.
*/
void sensirion_common_to_integer(const uint8_t* source, uint8_t* destination,
INT_TYPE int_type, uint8_t data_length);
#ifdef __cplusplus
}
#endif
+14 -1
View File
@@ -28,7 +28,7 @@
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
// File: src/sensirion_i2c.c
#include "sensirion_i2c.h"
#include "sensirion_common.h"
#include "sensirion_config.h"
@@ -177,6 +177,19 @@ uint16_t sensirion_i2c_add_command_to_buffer(uint8_t* buffer, uint16_t offset,
return offset;
}
uint16_t sensirion_i2c_add_command16_to_buffer(uint8_t* buffer, uint16_t offset,
uint16_t command) {
buffer[offset++] = (uint8_t)((command & 0xFF00) >> 8);
buffer[offset++] = (uint8_t)((command & 0x00FF) >> 0);
return offset;
}
uint16_t sensirion_i2c_add_command8_to_buffer(uint8_t* buffer, uint16_t offset,
uint8_t command) {
buffer[offset++] = command;
return offset;
}
uint16_t sensirion_i2c_add_uint32_t_to_buffer(uint8_t* buffer, uint16_t offset,
uint32_t data) {
buffer[offset++] = (uint8_t)((data & 0xFF000000) >> 24);
+33
View File
@@ -181,6 +181,39 @@ int16_t sensirion_i2c_read_cmd(uint8_t address, uint16_t cmd,
uint16_t sensirion_i2c_add_command_to_buffer(uint8_t* buffer, uint16_t offset,
uint16_t command);
/**
* sensirion_i2c_add_command16_to_buffer() - Add a command to the buffer at
* the specified offset. This function is equivalent to the
* function sensirion_i2c_add_command_to_buffer().
*
* @param buffer Pointer to buffer in which the write frame will be prepared.
* Caller needs to make sure that there is enough space after
* offset left to write the data into the buffer.
* @param offset Offset of the next free byte in the buffer.
* @param command Command to be written into the buffer.
*
* @return Offset of next free byte in the buffer after writing the data.
*/
uint16_t sensirion_i2c_add_command16_to_buffer(uint8_t* buffer, uint16_t offset,
uint16_t command);
/**
* sensirion_i2c_add_command8_to_buffer() - Add a command to the buffer at
* offset. Adds one bytes command to the buffer.
* This is used for sensor that only take one command byte such as
* SHT.
*
* @param buffer Pointer to buffer in which the write frame will be prepared.
* Caller needs to make sure that there is enough space after
* offset left to write the data into the buffer.
* @param offset Offset of the next free byte in the buffer.
* @param command Command to be written into the buffer.
*
* @return Offset of next free byte in the buffer after writing the data.
*/
uint16_t sensirion_i2c_add_command8_to_buffer(uint8_t* buffer, uint16_t offset,
uint8_t command);
/**
* sensirion_i2c_add_uint32_t_to_buffer() - Add a uint32_t to the buffer at
* offset. Adds 6 bytes to the buffer.
@@ -11,6 +11,9 @@
#include <inttypes.h>
#include "sensirion_i2c_esp32_config.h"
#include "hardware_config.h"
#include "sensor_soft_i2c.h"
#include "esp_rom_sys.h"
static const char* TAG = "sensirion_i2c_hal";
@@ -31,6 +34,45 @@ static i2c_dev_t dev = {0};
static struct esp32_i2c_config i2c_cfg = {0};
static esp_err_t i2c_ok = ESP_OK;
#if NANOPSX_SENSOR_SOFT_I2C
static SemaphoreHandle_t soft_mutex;
static void soft_sda(void *ctx, int release) {
struct esp32_i2c_config *p = ctx;
gpio_set_level(p->sda, release);
}
static void soft_scl(void *ctx, int release) {
struct esp32_i2c_config *p = ctx;
gpio_set_level(p->scl, release);
}
static int soft_read_sda(void *ctx) {
return gpio_get_level(((struct esp32_i2c_config *)ctx)->sda);
}
static int soft_read_scl(void *ctx) {
return gpio_get_level(((struct esp32_i2c_config *)ctx)->scl);
}
static void soft_delay(void *ctx, unsigned us) {
(void)ctx;
esp_rom_delay_us(us);
}
static int8_t soft_transfer(uint8_t address, uint8_t *data, uint16_t count, bool read) {
if (!soft_mutex || !xSemaphoreTake(soft_mutex, pdMS_TO_TICKS(1000)))
return SENSIRION_I2C_HAL_ERROR;
const sensor_soft_i2c_t port = {
.context = &i2c_cfg, .sda = soft_sda, .scl = soft_scl,
.read_sda = soft_read_sda, .read_scl = soft_read_scl,
.delay_us = soft_delay,
.half_period_us = (1000000U + 2 * i2c_cfg.freq - 1) / (2 * i2c_cfg.freq),
.stretch_timeout_us = 5000,
};
int rc = sensor_soft_i2c_transfer(&port, address, data, count, read);
xSemaphoreGive(soft_mutex);
i2c_ok = rc == 0 ? ESP_OK : ESP_FAIL;
if (rc) ESP_LOGW(TAG, "GPIO I2C %s failed addr=0x%02x rc=%d",
read ? "read" : "write", address, rc);
return rc == 0 ? 0 : SENSIRION_I2C_HAL_ERROR;
}
#endif
static int8_t sensirion_map_esp_err(esp_err_t err) {
return (err == ESP_OK) ? (int8_t)NO_ERROR : SENSIRION_I2C_HAL_ERROR;
}
@@ -40,6 +82,9 @@ static int8_t sensirion_map_esp_err(esp_err_t err) {
* Optional for single-bus setups.
*/
int16_t sensirion_i2c_hal_select_bus(uint8_t bus_idx) {
#if NANOPSX_SENSOR_SOFT_I2C
return bus_idx == i2c_cfg.port ? NO_ERROR : SENSIRION_I2C_HAL_ERROR;
#endif
/*
* NOTE:
* - This only switches the I2C port number.
@@ -70,6 +115,30 @@ esp_err_t sensirion_i2c_esp32_ok(void) {
* communication.
*/
void sensirion_i2c_hal_init(void) {
#if NANOPSX_SENSOR_SOFT_I2C
if (!i2c_cfg.freq || i2c_cfg.freq > 100000 ||
!GPIO_IS_VALID_OUTPUT_GPIO(i2c_cfg.sda) || !GPIO_IS_VALID_OUTPUT_GPIO(i2c_cfg.scl) ||
i2c_cfg.sda == i2c_cfg.scl) {
i2c_ok = ESP_ERR_INVALID_ARG;
return;
}
gpio_set_level(i2c_cfg.sda, 1);
gpio_set_level(i2c_cfg.scl, 1);
gpio_config_t pins = {
.pin_bit_mask = (1ULL << i2c_cfg.sda) | (1ULL << i2c_cfg.scl),
.mode = GPIO_MODE_INPUT_OUTPUT_OD,
.pull_up_en = GPIO_PULLUP_ENABLE,
.pull_down_en = GPIO_PULLDOWN_DISABLE,
.intr_type = GPIO_INTR_DISABLE,
};
i2c_ok = gpio_config(&pins);
if (i2c_ok != ESP_OK) return;
soft_mutex = xSemaphoreCreateMutex();
if (!soft_mutex) { i2c_ok = ESP_ERR_NO_MEM; return; }
ESP_LOGI(TAG, "GPIO I2C ready SDA=%d SCL=%d target=%lu Hz; touch uses hardware I2C",
i2c_cfg.sda, i2c_cfg.scl, (unsigned long)i2c_cfg.freq);
return;
#endif
memset(&dev, 0, sizeof(dev));
// Minimal sanity check
@@ -111,6 +180,12 @@ void sensirion_i2c_hal_init(void) {
* Release all resources initialized by sensirion_i2c_hal_init().
*/
void sensirion_i2c_hal_free(void) {
#if NANOPSX_SENSOR_SOFT_I2C
gpio_set_level(i2c_cfg.sda, 1);
gpio_set_level(i2c_cfg.scl, 1);
if (soft_mutex) { vSemaphoreDelete(soft_mutex); soft_mutex = NULL; }
return;
#endif
esp_err_t err = i2c_dev_delete_mutex(&dev);
if (err != ESP_OK) {
ESP_LOGW(TAG, "i2c_dev_delete_mutex failed: %s", esp_err_to_name(err));
@@ -126,6 +201,9 @@ int8_t sensirion_i2c_hal_read(uint8_t address, uint8_t* data, uint16_t count) {
if (count > 0 && data == NULL) {
return SENSIRION_I2C_HAL_ERROR;
}
#if NANOPSX_SENSOR_SOFT_I2C
return soft_transfer(address, data, count, true);
#endif
dev.addr = address;
@@ -163,6 +241,9 @@ int8_t sensirion_i2c_hal_write(uint8_t address, const uint8_t* data, uint16_t co
if (count > 0 && data == NULL) {
return SENSIRION_I2C_HAL_ERROR;
}
#if NANOPSX_SENSOR_SOFT_I2C
return soft_transfer(address, (uint8_t *)data, count, false);
#endif
dev.addr = address;
@@ -0,0 +1,82 @@
#include "sensor_soft_i2c.h"
#include <stddef.h>
static void delay(const sensor_soft_i2c_t *p) {
p->delay_us(p->context, p->half_period_us);
}
static int high(const sensor_soft_i2c_t *p) {
p->scl(p->context, 1);
for (unsigned n = 0; n <= p->stretch_timeout_us; n++) {
if (p->read_scl(p->context)) {
delay(p);
return 0;
}
p->delay_us(p->context, 1);
}
return -1;
}
static int write_bit(const sensor_soft_i2c_t *p, int bit) {
p->sda(p->context, bit);
delay(p);
if (high(p)) return -1;
p->scl(p->context, 0);
return 0;
}
static int read_bit(const sensor_soft_i2c_t *p) {
p->sda(p->context, 1);
delay(p);
if (high(p)) return -1;
int bit = p->read_sda(p->context) != 0;
p->scl(p->context, 0);
return bit;
}
static int write_byte(const sensor_soft_i2c_t *p, uint8_t byte) {
for (int n = 7; n >= 0; n--)
if (write_bit(p, (byte >> n) & 1)) return -1;
return read_bit(p); // ACK=0, NACK=1, bus failure=-1.
}
int sensor_soft_i2c_transfer(const sensor_soft_i2c_t *p, uint8_t address,
uint8_t *data, uint16_t count, bool read) {
if (!p || !p->sda || !p->scl || !p->read_sda || !p->read_scl ||
!p->delay_us || !p->half_period_us || address > 127 || (count && !data))
return -1;
p->sda(p->context, 1);
if (high(p) || !p->read_sda(p->context)) {
p->sda(p->context, 1);
p->scl(p->context, 1);
return -1;
}
p->sda(p->context, 0); // START while clock is high.
delay(p);
p->scl(p->context, 0);
int error = write_byte(p, (uint8_t)((address << 1) | read));
for (uint16_t i = 0; i < count && !error; i++) {
if (!read) {
error = write_byte(p, data[i]);
continue;
}
uint8_t byte = 0;
for (unsigned n = 0; n < 8; n++) {
int bit = read_bit(p);
if (bit < 0) { error = -1; break; }
byte = (uint8_t)((byte << 1) | bit);
}
if (!error) {
data[i] = byte;
error = write_bit(p, i + 1 == count); // NACK only the final byte.
}
}
// STOP on both success and failure; leave neither line driven low.
p->scl(p->context, 0);
p->sda(p->context, 0);
delay(p);
int stop_error = high(p);
p->sda(p->context, 1);
delay(p);
return error ? error : stop_error;
}
@@ -0,0 +1,21 @@
#pragma once
#include <stdbool.h>
#include <stdint.h>
/* Single-master, open-drain GPIO bus. 1 means release, never drive high.
* Port callbacks make the wire protocol testable without ESP hardware.
*/
typedef struct {
void *context;
void (*sda)(void *, int);
void (*scl)(void *, int);
int (*read_sda)(void *);
int (*read_scl)(void *);
void (*delay_us)(void *, unsigned);
unsigned half_period_us;
unsigned stretch_timeout_us;
} sensor_soft_i2c_t;
/* 0 success, 1 NACK, -1 bus/argument error. Always releases lines on failure. */
int sensor_soft_i2c_transfer(const sensor_soft_i2c_t *io, uint8_t address,
uint8_t *data, uint16_t count, bool read);
@@ -3,6 +3,6 @@ idf_component_register(
"src/sys_status.c"
INCLUDE_DIRS
"include"
REQUIRES
REQUIRES esp_timer
)
@@ -1,6 +1,7 @@
// File: firmware/components/sys_status/include/sys_status.h
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "freertos/FreeRTOS.h"
#include "freertos/event_groups.h"
@@ -25,6 +26,10 @@ static inline bool sys_status_get_wifi_ok(void) { return (xEventGroupGetBits(s
static inline bool sys_status_get_influx_ok(void) { return (xEventGroupGetBits(sys_status_group()) & SYS_STATUS_INFLUX_OK) != 0; }
static inline bool sys_status_get_mdns_ok(void) { return (xEventGroupGetBits(sys_status_group()) & SYS_STATUS_MDNS_OK) != 0; }
/* Monotonic timestamp of a confirmed HTTP 204, never merely a WLAN connection. */
void sys_status_record_influx_success(void);
uint64_t sys_status_last_influx_success_ms(void);
#ifdef __cplusplus
}
#endif
@@ -21,3 +21,22 @@ EventGroupHandle_t sys_status_group(void)
if (!s_status_group) sys_status_init();
return s_status_group;
}
#include "esp_timer.h"
#include "freertos/portmacro.h"
static portMUX_TYPE influx_time_mux = portMUX_INITIALIZER_UNLOCKED;
static uint64_t last_influx_success;
void sys_status_record_influx_success(void)
{
uint64_t now = (uint64_t)(esp_timer_get_time() / 1000);
portENTER_CRITICAL(&influx_time_mux);
last_influx_success = now;
portEXIT_CRITICAL(&influx_time_mux);
}
uint64_t sys_status_last_influx_success_ms(void)
{
portENTER_CRITICAL(&influx_time_mux);
uint64_t result = last_influx_success;
portEXIT_CRITICAL(&influx_time_mux);
return result;
}
+5 -2
View File
@@ -1,9 +1,12 @@
[env:esp32-c6-devkitc-1]
platform = espressif32
platform = espressif32@6.12.0
platform_packages =
platformio/framework-espidf@3.50500.0
board = esp32-c6-devkitc-1
framework = espidf
board_upload.flash_size = 8MB
monitor_speed = 115200
monitor_dtr = 0
monitor_rts = 0
board_build.partitions = partitions.csv
; extra_scripts = scripts/enable_ccache.py
extra_scripts = pre:tools/pio_display.py
+3
View File
@@ -1,4 +1,7 @@
CONFIG_IDF_TARGET="esp32c6"
CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_LV_COLOR_16_SWAP=y
CONFIG_LV_FONT_MONTSERRAT_12=y
CONFIG_LV_FONT_MONTSERRAT_16=y
+9 -9
View File
@@ -594,14 +594,14 @@ CONFIG_ESPTOOLPY_FLASHFREQ_80M=y
# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set
CONFIG_ESPTOOLPY_FLASHFREQ="80m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_8MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE="2MB"
CONFIG_ESPTOOLPY_FLASHSIZE="8MB"
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
CONFIG_ESPTOOLPY_BEFORE_RESET=y
# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set
@@ -615,13 +615,13 @@ CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
#
# Partition Table
#
CONFIG_PARTITION_TABLE_SINGLE_APP=y
# CONFIG_PARTITION_TABLE_SINGLE_APP is not set
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
# CONFIG_PARTITION_TABLE_TWO_OTA_LARGE is not set
# CONFIG_PARTITION_TABLE_CUSTOM is not set
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
@@ -2027,9 +2027,9 @@ CONFIG_PTHREAD_TASK_NAME_DEFAULT="pthread"
#
# MMU Config
#
CONFIG_MMU_PAGE_SIZE_32KB=y
CONFIG_MMU_PAGE_MODE="32KB"
CONFIG_MMU_PAGE_SIZE=0x8000
CONFIG_MMU_PAGE_SIZE_64KB=y
CONFIG_MMU_PAGE_MODE="64KB"
CONFIG_MMU_PAGE_SIZE=0x10000
# end of MMU Config
#
+1 -1
View File
@@ -6,5 +6,5 @@ set(app_sources
idf_component_register(
SRCS ${app_sources}
INCLUDE_DIRS "."
REQUIRES dns_captive storage
REQUIRES dns_captive storage hardware_config
)
+80 -69
View File
@@ -5,7 +5,8 @@
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "sen5x_app.h"
#include "air_sensor_app.h"
#include "hardware_config.h"
#include "storage.h"
#include <stdio.h>
@@ -34,6 +35,10 @@
#include "demos/lv_demos.h"
#include "ui.h"
#include "ui_navigation.h"
#include "ui_dashboard.h"
#include "nvs.h"
#include "esp_netif.h"
#include "i2cdev.h"
#include "sys_status.h"
@@ -72,61 +77,6 @@ static void app_save_device_info(
storage_save_influx_softap(org, bucket, token);
}
// ---------- Status-Icons updaten: nutzt die in screens.c erzeugten Objekte ----------
static void ui_update_status_icons(void)
{
static bool first = true;
static bool pw=false, pi=false, pm=false;
bool w = sys_status_get_wifi_ok();
bool i = sys_status_get_influx_ok();
bool m = sys_status_get_mdns_ok();
// WiFi
if (first || w != pw) {
if (objects.wifi_ok && objects.wifi_off) {
if (w) {
lv_obj_clear_flag(objects.wifi_ok, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag (objects.wifi_off, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag (objects.wifi_ok, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(objects.wifi_off, LV_OBJ_FLAG_HIDDEN);
}
}
pw = w;
}
// Influx
if (first || i != pi) {
if (objects.influx_ok && objects.influx_off) {
if (i) {
lv_obj_clear_flag(objects.influx_ok, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag (objects.influx_off, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag (objects.influx_ok, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(objects.influx_off, LV_OBJ_FLAG_HIDDEN);
}
}
pi = i;
}
// mDNS
if (first || m != pm) {
if (objects.mdns_ok && objects.mdns_off) {
if (m) {
lv_obj_clear_flag(objects.mdns_ok, LV_OBJ_FLAG_HIDDEN);
lv_obj_add_flag (objects.mdns_off, LV_OBJ_FLAG_HIDDEN);
} else {
lv_obj_add_flag (objects.mdns_ok, LV_OBJ_FLAG_HIDDEN);
lv_obj_clear_flag(objects.mdns_off, LV_OBJ_FLAG_HIDDEN);
}
}
pm = m;
}
first = false;
}
#define EXAMPLE_DISPLAY_ROTATION 270
#if EXAMPLE_DISPLAY_ROTATION == 90 || EXAMPLE_DISPLAY_ROTATION == 270
@@ -230,17 +180,62 @@ static esp_err_t app_lvgl_init(void)
.disp = lvgl_disp,
.handle = touch_handle,
};
lvgl_touch_indev = lvgl_port_add_touch(&touch_cfg);
if (touch_handle) lvgl_touch_indev = lvgl_port_add_touch(&touch_cfg);
return ESP_OK;
}
#if NANOPSX_HAS_DISPLAY
static void (*original_touch_read)(lv_indev_drv_t *, lv_indev_data_t *);
static void filtered_touch_read(lv_indev_drv_t *driver, lv_indev_data_t *data)
{
original_touch_read(driver, data);
ui_dashboard_filter_touch(data);
}
static ui_display_config_t load_display_config(void)
{
ui_display_config_t result = {.brightness = 100, .dim_after_s = 60};
nvs_handle_t handle;
if (nvs_open("ui_display", NVS_READONLY, &handle) == ESP_OK) {
nvs_get_u8(handle, "brightness", &result.brightness);
nvs_get_u16(handle, "dim_after", &result.dim_after_s);
nvs_close(handle);
}
return result;
}
static void save_display_config(const ui_display_config_t *config)
{
nvs_handle_t handle;
esp_err_t err = nvs_open("ui_display", NVS_READWRITE, &handle);
if (err == ESP_OK) {
err = nvs_set_u8(handle, "brightness", config->brightness);
if (err == ESP_OK) err = nvs_set_u16(handle, "dim_after", config->dim_after_s);
if (err == ESP_OK) err = nvs_commit(handle);
nvs_close(handle);
}
if (err != ESP_OK) ESP_LOGW("display", "Cannot save settings: %s", esp_err_to_name(err));
}
#endif
static void ui_tick_cb(lv_timer_t *t) {
(void)t;
app_update_mdns_status_from_nvs();
if (lvgl_port_lock(0)) {
ui_update_status_icons();
tick_screen(0);
ui_device_status_t status = {
.wifi_connected = sys_status_get_wifi_ok(),
.influx_ok = sys_status_get_influx_ok(),
.mdns_ok = sys_status_get_mdns_ok(),
.last_influx_success_ms = sys_status_last_influx_success_ms()
};
snprintf(status.ip, sizeof(status.ip), "verbunden");
esp_netif_t *netif = esp_netif_get_handle_from_ifkey("WIFI_STA_DEF");
esp_netif_ip_info_t ip;
if (netif && esp_netif_get_ip_info(netif, &ip) == ESP_OK && ip.ip.addr)
snprintf(status.ip, sizeof(status.ip), IPSTR, IP2STR(&ip.ip));
ui_dashboard_tick((uint64_t)(esp_timer_get_time() / 1000), &status);
lvgl_port_unlock();
}
}
@@ -380,12 +375,17 @@ void app_main(void)
ESP_ERROR_CHECK(i2cdev_adopt_bus(I2C_PORT_NUM, i2c_bus_handle,
EXAMPLE_PIN_I2C_SDA, EXAMPLE_PIN_I2C_SCL));
#if NANOPSX_HAS_DISPLAY
// Restliche Peripherie
bsp_spi_init();
bsp_battery_init();
// bsp_qmi8658_init(i2c_bus_handle);
bsp_display_init(&io_handle, &panel_handle, EXAMPLE_LCD_H_RES * EXAMPLE_LCD_DRAW_BUFF_HEIGHT);
bsp_touch_init(&touch_handle, i2c_bus_handle, EXAMPLE_LCD_H_RES, EXAMPLE_LCD_V_RES, EXAMPLE_DISPLAY_ROTATION);
esp_err_t touch_result = bsp_touch_init(&touch_handle, i2c_bus_handle,
EXAMPLE_LCD_H_RES, EXAMPLE_LCD_V_RES, EXAMPLE_DISPLAY_ROTATION);
if (touch_result != ESP_OK)
ESP_LOGW("hardware", "Touch unavailable (%s); display and sensor remain enabled",
esp_err_to_name(touch_result));
bsp_sdcard_init();
ESP_ERROR_CHECK(app_lvgl_init());
lv_fs_fatfs_init();
@@ -398,11 +398,22 @@ void app_main(void)
if (lvgl_port_lock(0)) {
ui_init(); // erzeugt auch die Objekte in screens.c
ui_dashboard_init(load_display_config(), bsp_display_set_brightness, save_display_config);
ui_navigation_init();
if (lvgl_touch_indev) {
original_touch_read = lvgl_touch_indev->driver->read_cb;
lvgl_touch_indev->driver->read_cb = filtered_touch_read;
}
lv_timer_create(ui_tick_cb, 1000, NULL);
lvgl_port_unlock();
}
lv_timer_t *ui_timer = lv_timer_create(ui_tick_cb, 1000, NULL);
(void)ui_timer;
#endif
ESP_LOGI("hardware", "Board=%s Sensor=%s SDA=%d SCL=%d I2C=%lu Hz",
NANOPSX_BOARD_NAME, NANOPSX_SENSOR_NAME, NANOPSX_SENSOR_SDA,
NANOPSX_SENSOR_SCL, (unsigned long)NANOPSX_SENSOR_I2C_HZ);
// WiFi AP+STA starten
wifi_mgr_start();
@@ -451,20 +462,20 @@ void app_main(void)
&cb
));
// SEN5x
const sen5x_i2c_cfg_t cfg = {
.addr = 0x69,
// Selected air sensor
const air_sensor_i2c_cfg_t cfg = {
.addr = NANOPSX_SENSOR_ADDRESS,
.port = I2C_PORT_NUM,
.sda = EXAMPLE_PIN_I2C_SDA,
.scl = EXAMPLE_PIN_I2C_SCL,
.sda = NANOPSX_SENSOR_SDA,
.scl = NANOPSX_SENSOR_SCL,
.sda_pullup = true,
.scl_pullup = true,
.freq = 400000
.freq = NANOPSX_SENSOR_I2C_HZ
};
ESP_ERROR_CHECK(sen5x_app_init(&cfg));
ESP_ERROR_CHECK(air_sensor_app_init(&cfg));
// Task starten
xTaskCreate(sen5x_app_task, "sen5x_task", 4096, NULL, 5, NULL);
xTaskCreate(air_sensor_app_task, "air_sensor_task", 4096, NULL, 5, NULL);
for (;;) vTaskDelay(pdMS_TO_TICKS(1000));
}
+72
View File
@@ -0,0 +1,72 @@
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdarg.h>
typedef int esp_err_t;
#define ESP_OK 0
#define ESP_FAIL -1
#define ESP_ERR_INVALID_ARG 1
#define ESP_ERR_NO_MEM 2
#define ESP_ERR_INVALID_STATE 3
#define ESP_ERR_NOT_FOUND 4
#define ESP_ERR_INVALID_SIZE 5
const char *esp_err_to_name(esp_err_t code);
void fake_log(const char *level, const char *tag, const char *format, ...);
#define ESP_LOGI(tag, ...) fake_log("I", tag, __VA_ARGS__)
#define ESP_LOGW(tag, ...) fake_log("W", tag, __VA_ARGS__)
#define ESP_LOGE(tag, ...) fake_log("E", tag, __VA_ARGS__)
#define ESP_LOGD(tag, ...) fake_log("D", tag, __VA_ARGS__)
#define ESP_LOGV(tag, ...) fake_log("V", tag, __VA_ARGS__)
typedef unsigned UBaseType_t;
typedef int BaseType_t;
typedef uint32_t TickType_t;
typedef void *TaskHandle_t;
typedef struct fake_queue *QueueHandle_t;
typedef void *SemaphoreHandle_t;
#define pdTRUE 1
#define pdPASS 1
#define portMAX_DELAY UINT32_MAX
#define pdMS_TO_TICKS(ms) (ms)
QueueHandle_t xQueueCreate(unsigned count, unsigned size);
int xQueueSend(QueueHandle_t queue, const void *item, unsigned ticks);
int xQueueReceive(QueueHandle_t queue, void *item, unsigned ticks);
void vQueueDelete(QueueHandle_t queue);
int xTaskCreate(void (*task)(void *), const char *name, unsigned stack, void *arg, unsigned prio, TaskHandle_t *out);
void vTaskDelay(unsigned ticks);
void vTaskDelete(TaskHandle_t task);
SemaphoreHandle_t xSemaphoreCreateMutex(void);
int xSemaphoreTake(SemaphoreHandle_t mutex, unsigned ticks);
int xSemaphoreGive(SemaphoreHandle_t mutex);
int64_t esp_timer_get_time(void);
void sys_status_set_influx_ok(bool value);
void sys_status_record_influx_success(void);
bool storage_load_service_url(char **url);
bool storage_get_effective_influx(char **org, char **bucket, char **token);
typedef struct fake_http *esp_http_client_handle_t;
typedef struct {
int event_id;
char *header_key, *header_value;
} esp_http_client_event_t;
#define HTTP_EVENT_ON_HEADER 1
#define HTTP_EVENT_ON_CONNECTED 2
#define HTTP_METHOD_POST 1
#define HTTP_METHOD_GET 2
#define HTTP_TRANSPORT_OVER_SSL 1
#define HTTP_TRANSPORT_OVER_TCP 2
typedef struct {
const char *url;
int timeout_ms, method, transport_type;
const char *cert_pem;
esp_err_t (*event_handler)(esp_http_client_event_t *);
bool disable_auto_redirect, keep_alive_enable;
int keep_alive_idle, keep_alive_interval, keep_alive_count;
} esp_http_client_config_t;
esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *config);
esp_err_t esp_http_client_cleanup(esp_http_client_handle_t client);
esp_err_t esp_http_client_set_header(esp_http_client_handle_t client, const char *key, const char *value);
esp_err_t esp_http_client_set_url(esp_http_client_handle_t client, const char *url);
esp_err_t esp_http_client_set_method(esp_http_client_handle_t client, int method);
esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t client, const char *data, int length);
esp_err_t esp_http_client_perform(esp_http_client_handle_t client);
int esp_http_client_get_status_code(esp_http_client_handle_t client);
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env python3
"""Compile the real Influx worker against a deterministic FreeRTOS/HTTP simulator."""
from pathlib import Path
import subprocess
import tempfile
firmware = Path(__file__).resolve().parents[2]
tests = Path(__file__).resolve().parent
source = firmware / 'components/net_influx'
with tempfile.TemporaryDirectory(prefix='nanopsx-influx-test-') as directory:
build = Path(directory)
for header in ['esp_err.h', 'esp_log.h', 'esp_timer.h', 'esp_http_client.h',
'storage.h', 'sys_status.h', 'freertos/FreeRTOS.h',
'freertos/task.h', 'freertos/queue.h', 'freertos/semphr.h']:
path = build / header
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text('#include "fake_sdk.h"\n')
program = build / 'test_runtime'
subprocess.run(['cc', '-std=c11', '-D_POSIX_C_SOURCE=200809L', '-Wall', '-Wextra',
'-Wno-sign-compare', '-g', '-fsanitize=address,undefined',
'-fno-omit-frame-pointer', '-fno-pie', '-no-pie',
'-I', str(build), '-I', str(tests), '-I', str(source / 'include'),
'-I', str(source / 'src'), str(tests / 'test_runtime.c'),
str(source / 'src/influx_batch.c'), '-lm', '-o', str(program)], check=True)
for scenario in ['format', 'clock', 'normal', 'retry', 'overflow', 'no-date',
'no-date-failure', 'partial', 'max-body', 'reject']:
subprocess.run([str(program), scenario], check=True)
+204
View File
@@ -0,0 +1,204 @@
/* The production worker, formatter, queue submission and client lifetime are exercised below. */
#include "fake_sdk.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "net_influx.c"
static const char *scenario;
static uint64_t now_ms, next_sample_ms=1000;
static unsigned produced, target=30, posts, gets, clients, cleanups, accepted, rejected, successes;
static unsigned failures_left, samples_per_post[128], seen[128], max_queue;
static uint64_t stamp[128];
static bool status_ok;
static char failed_body[INFLUX_BATCH_CAP];
static void (*task_entry)(void *);
struct fake_queue { unsigned cap, size, count, head; unsigned char *data; };
struct fake_http { esp_http_client_config_t cfg; char url[640]; const char *body; int length, method, status; };
const char *esp_err_to_name(esp_err_t code) { return code==0?"ESP_OK":"fake error"; }
void fake_log(const char *level,const char *tag,const char *fmt,...) { (void)level;(void)tag;(void)fmt; }
int64_t esp_timer_get_time(void) { return now_ms*1000; }
void sys_status_set_influx_ok(bool value) { status_ok=value; }
void sys_status_record_influx_success(void) { ++successes; }
SemaphoreHandle_t xSemaphoreCreateMutex(void) { return (void *)1; }
int xSemaphoreTake(SemaphoreHandle_t mutex,unsigned ticks) { (void)ticks;assert(mutex);return pdTRUE; }
int xSemaphoreGive(SemaphoreHandle_t mutex) { assert(mutex);return pdTRUE; }
bool storage_load_service_url(char **value) { *value=strdup("http://influx.test:8086");return true; }
bool storage_get_effective_influx(char **org,char **bucket,char **token)
{ *org=strdup("Home");*bucket=strdup("nanoPSX");*token=strdup("synthetic-test-token");return true; }
QueueHandle_t xQueueCreate(unsigned count,unsigned size)
{
struct fake_queue *q=calloc(1,sizeof(*q));assert(q);
q->cap=count;q->size=size;q->data=calloc(count,size);assert(q->data);return q;
}
int xQueueSend(QueueHandle_t q,const void *data,unsigned ticks)
{
(void)ticks;if(q->count==q->cap)return 0;
memcpy(q->data+((q->head+q->count)%q->cap)*q->size,data,q->size);++q->count;
if(q->count>max_queue)max_queue=q->count;
return pdPASS;
}
static void generate(void)
{
++produced;
char detail[421];memset(detail,'a',sizeof(detail)-1);detail[sizeof(detail)-1]=0;
net_influx_field_t fields[]={
{.key="value",.type=NET_INFLUX_F_INT,.v.i=produced},
{.key="detail",.type=NET_INFLUX_F_STRING,.v.s=detail}
};
net_influx_point_t point={.measurement="air",.tags="device=test",.fields=fields,
.num_fields=!strcmp(scenario,"max-body")?2:1};
assert(net_influx_submit_point(&point)==ESP_OK);
fields[0].v.i=-1;memset(detail,'X',sizeof(detail)-1); /* Queue must own serialized bytes. */
}
static void advance(uint64_t destination)
{
while(produced<target && next_sample_ms<=destination) {
now_ms=next_sample_ms;next_sample_ms+=1000;generate();
}
now_ms=destination;
assert(now_ms<1000000); /* Detect a stuck retry/flush loop. */
}
int xQueueReceive(QueueHandle_t q,void *data,unsigned ticks)
{
if(!q->count && ticks) {
uint64_t destination=now_ms+ticks;
if(produced<target && next_sample_ms<destination)destination=next_sample_ms;
advance(destination);
}
if(!q->count)return 0;
memcpy(data,q->data+q->head*q->size,q->size);q->head=(q->head+1)%q->cap;--q->count;return pdTRUE;
}
void vQueueDelete(QueueHandle_t q) { free(q->data);free(q); }
int xTaskCreate(void (*fn)(void *),const char *name,unsigned stack,void *arg,unsigned prio,TaskHandle_t *out)
{ (void)name;(void)arg;(void)prio;assert(stack>=8192);task_entry=fn;*out=(void *)1;return pdPASS; }
void vTaskDelay(unsigned ticks) { advance(now_ms+ticks); }
void vTaskDelete(TaskHandle_t task) { assert(!task); }
esp_http_client_handle_t esp_http_client_init(const esp_http_client_config_t *cfg)
{
struct fake_http *h=calloc(1,sizeof(*h));assert(h);
h->cfg=*cfg;h->method=cfg->method;snprintf(h->url,sizeof(h->url),"%s",cfg->url);
assert(cfg->keep_alive_enable && cfg->disable_auto_redirect);++clients;
esp_http_client_event_t event={.event_id=HTTP_EVENT_ON_CONNECTED};cfg->event_handler(&event);return h;
}
esp_err_t esp_http_client_cleanup(esp_http_client_handle_t h) { ++cleanups;free(h);return ESP_OK; }
esp_err_t esp_http_client_set_header(esp_http_client_handle_t h,const char *key,const char *value)
{ (void)h;assert(key && value);return ESP_OK; }
esp_err_t esp_http_client_set_url(esp_http_client_handle_t h,const char *url)
{ snprintf(h->url,sizeof(h->url),"%s",url);return ESP_OK; }
esp_err_t esp_http_client_set_method(esp_http_client_handle_t h,int method) { h->method=method;return ESP_OK; }
esp_err_t esp_http_client_set_post_field(esp_http_client_handle_t h,const char *body,int length)
{ h->body=body;h->length=length;return ESP_OK; }
int esp_http_client_get_status_code(esp_http_client_handle_t h) { return h->status; }
static bool no_date(void) { return !strncmp(scenario,"no-date",7); }
static void date_event(esp_http_client_handle_t h)
{
if(no_date())return;
uint64_t base;assert(influx_parse_http_date("Wed, 11 Nov 2026 12:00:00 GMT",&base));
time_t seconds=(time_t)((base+now_ms)/1000);
char date[40];strftime(date,sizeof(date),"%a, %d %b %Y %H:%M:%S GMT",gmtime(&seconds));
esp_http_client_event_t event={.event_id=HTTP_EVENT_ON_HEADER,.header_key="dAtE",.header_value=date};
h->cfg.event_handler(&event);
}
esp_err_t esp_http_client_perform(esp_http_client_handle_t h)
{
date_event(h);
if(h->method==HTTP_METHOD_GET) { assert(strstr(h->url,"/health"));++gets;h->status=200;return ESP_OK; }
assert(strstr(h->url,"/api/v2/write?org=Home&bucket=nanoPSX&precision=ms"));
assert(h->body && h->length>0 && h->length<INFLUX_BATCH_CAP);
unsigned count=1;for(const char *p=h->body;*p;++p)if(*p=='\n')++count;
assert(count<=INFLUX_BATCH_POINTS && posts<128);samples_per_post[posts++]=count;
if(failures_left) {
if(!failed_body[0])snprintf(failed_body,sizeof(failed_body),"%s",h->body);
else assert(!strcmp(failed_body,h->body));
--failures_left;return ESP_FAIL;
}
if(failed_body[0]) { assert(!strcmp(failed_body,h->body));failed_body[0]=0; }
if(!strcmp(scenario,"no-date-failure") && posts==1) { ++rejected;return ESP_FAIL; }
if(!strcmp(scenario,"reject") && posts==1) { rejected+=count;h->status=400;return ESP_OK; }
char payload[INFLUX_BATCH_CAP];snprintf(payload,sizeof(payload),"%s",h->body);
for(char *line=strtok(payload,"\n");line;line=strtok(NULL,"\n")) {
unsigned id;assert(sscanf(line,"air,device=test value=%ui",&id)==1 && id>0 && id<=target);
assert(!seen[id]++);
const char *last=strrchr(line,' ');assert(last);
if(no_date()) { assert(count==1 && !strcmp(last+1,line+16)); }
else {
char *end;uint64_t timestamp=strtoull(last+1,&end,10);assert(*end==0);
uint64_t base;assert(influx_parse_http_date("Wed, 11 Nov 2026 12:00:00 GMT",&base));
assert(timestamp==base+500+id*1000);stamp[id]=timestamp;
}
if(!strcmp(scenario,"max-body")) { assert(strstr(line,"detail=\"aaaa"));assert(!strstr(line,"XXXX")); }
}
accepted+=count;h->status=204;
if(accepted+rejected+atomic_load(&s_dropped)>=target)s_run=false;
return ESP_OK;
}
static void test_format(void)
{
char line[512];
net_influx_field_t fields[]={
{.key="temp",.type=NET_INFLUX_F_FLOAT,.precision=1,.v.f=23.4},
{.key="missing",.type=NET_INFLUX_F_FLOAT,.v.f=NAN},
{.key="a=b",.type=NET_INFLUX_F_UINT,.v.u=42},
{.key="flag",.type=NET_INFLUX_F_BOOL,.v.b=true},
{.key="text",.type=NET_INFLUX_F_STRING,.v.s="a\"b\\c"}
};
net_influx_point_t p={.measurement="air room",.tags="device=test",.ts_ms=123456,.fields=fields,.num_fields=5};
assert(build_line_protocol(&p,line,sizeof(line))==ESP_OK);
assert(!strcmp(line,"air\\ room,device=test temp=23.4,a\\=b=42u,flag=true,text=\"a\\\"b\\\\c\" 123456"));
fields[4].v.s="newline\nnot allowed";assert(build_line_protocol(&p,line,sizeof(line))==ESP_ERR_INVALID_ARG);
p.num_fields=1;fields[0].v.f=NAN;assert(build_line_protocol(&p,line,sizeof(line))==ESP_ERR_INVALID_STATE);
fields[0].v.f=1;
char large[200];memset(large,'a',sizeof(large)-1);large[199]=0;p.measurement=large;
assert(build_line_protocol(&p,line,sizeof(line))==ESP_ERR_INVALID_SIZE);
}
static void test_clock(void)
{
uint64_t epoch;
assert(influx_parse_http_date("Wed, 11 Nov 2026 12:00:00 GMT",&epoch));
assert(epoch==1794398400000ULL);
assert(!influx_parse_http_date("Thu, 29 Feb 2100 00:00:00 GMT",&epoch));
assert(!influx_parse_http_date("Thu, 31 Feb 2024 00:00:00 GMT",&epoch));
assert(!influx_parse_http_date("Wed, 11 Nov 2026 12:00:00 UTC",&epoch));
assert(influx_parse_http_date("Thu, 29 Feb 2024 00:00:00 GMT",&epoch));
influx_clock_t clock={0};uint64_t first,second;
assert(!influx_clock_timestamp(&clock,0,&first));
influx_clock_observe(&clock,"Wed, 11 Nov 2026 12:00:00 GMT",1000);
assert(influx_clock_timestamp(&clock,500,&first));
assert(influx_clock_timestamp(&clock,1500,&second) && second-first==1000);
influx_batch_t b={0};assert(!influx_batch_due(&b,0));
assert(influx_batch_add(&b,"air value=1i 12345",50));
assert(!influx_batch_due(&b,10049) && influx_batch_due(&b,10050));
assert(b.first_timestamp_ms==12345 && b.last_timestamp_ms==12345);
for(int i=1;i<10;++i)assert(influx_batch_add(&b,"air value=2i 12346",100));
assert(influx_batch_due(&b,100) && !influx_batch_add(&b,"air value=3i 12347",100));
}
int main(int argc,char **argv)
{
assert(argc==2);scenario=argv[1];
if(!strcmp(scenario,"format"))test_format();
else if(!strcmp(scenario,"clock"))test_clock();
else {
if(!strcmp(scenario,"retry"))failures_left=1;
if(!strcmp(scenario,"overflow")) { failures_left=5;target=70; }
if(!strcmp(scenario,"partial"))target=3;
if(!strcmp(scenario,"max-body"))target=10;
assert(net_influx_start(NULL)==ESP_OK);assert(task_entry);task_entry(NULL);
assert(!s_task && !s_q && !s_http && clients==cleanups);
assert(accepted+rejected+atomic_load(&s_dropped)==target && max_queue<=32);
if(!strcmp(scenario,"normal"))assert(posts==3 && accepted==30 && clients==1 && gets==1 && successes==3);
if(!strcmp(scenario,"retry"))assert(posts==4 && clients==2 && accepted==30);
if(!strcmp(scenario,"overflow"))assert(atomic_load(&s_dropped)>0 && max_queue==32 && accepted>=32);
if(!strcmp(scenario,"partial"))assert(posts==1 && samples_per_post[0]==3 && now_ms==11000);
if(!strcmp(scenario,"max-body"))assert(posts==2 && accepted==10);
if(!strcmp(scenario,"reject"))assert(posts==3 && accepted==20 && rejected==10);
if(no_date())assert(posts==target && clients<=2);
assert(status_ok);
}
printf("PASS: Influx %s\n",scenario);
}
+31
View File
@@ -0,0 +1,31 @@
#!/usr/bin/env bash
set -euo pipefail
cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.."
test_dir=$(mktemp -d)
trap 'rm -rf -- "$test_dir"' EXIT
driver=components/sen5x
cc -std=c11 -Wall -Wextra -I"$driver" test/sensors/test_protocol.c \
"$driver/sen5x_i2c.c" "$driver/sen66_i2c.c" \
"$driver/sensirion_common.c" "$driver/sensirion_i2c.c" \
-o "$test_dir/protocol"
"$test_dir/protocol"
cc -std=c11 -Wall -Wextra -Werror -I"$driver" \
test/sensors/test_soft_i2c.c "$driver/sensor_soft_i2c.c" -o "$test_dir/soft-i2c"
"$test_dir/soft-i2c"
# Compile all four hardware combinations; invalid selections must fail.
for board in 1 2; do
for sensor in 54 66; do
printf '#include "hardware_config.h"\nint main(void) {return 0;}\n' |
cc -std=c11 -Werror -Icomponents/hardware_config -DNANOPSX_BOARD="$board" \
-DNANOPSX_SENSOR="$sensor" -x c - -o "$test_dir/config"
done
done
for invalid in NANOPSX_BOARD=999 NANOPSX_SENSOR=999; do
if printf '#include "hardware_config.h"\n' |
cc -Icomponents/hardware_config -D"$invalid" -x c -c -o "$test_dir/invalid.o" - 2>/dev/null; then
echo "Invalid configuration was accepted: $invalid" >&2
exit 1
fi
done
echo 'PASS: all four board/sensor selections and invalid-profile rejection'
+83
View File
@@ -0,0 +1,83 @@
/* Host-side tests exercise the real vendor drivers and shared CRC helpers. */
#include <assert.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include "sen5x_i2c.h"
#include "sen66_i2c.h"
static uint8_t expected_address;
static uint16_t command;
static uint16_t words[9];
static bool bad_crc, fail_read, fail_write;
static uint8_t crc(const uint8_t *data) {
uint8_t value = 0xff;
for (unsigned n = 0; n < 2; n++) {
value ^= data[n];
for (unsigned bit = 0; bit < 8; bit++)
value = (value & 0x80) ? (uint8_t)((value << 1) ^ 0x31) : (uint8_t)(value << 1);
}
return value;
}
int8_t sensirion_i2c_hal_write(uint8_t address, const uint8_t *data, uint16_t size) {
assert(address == expected_address && size >= 2);
command = (uint16_t)((data[0] << 8) | data[1]);
return fail_write ? -1 : 0;
}
int8_t sensirion_i2c_hal_read(uint8_t address, uint8_t *data, uint16_t size) {
assert(address == expected_address && size % 3 == 0 && size <= 27);
if (fail_read) return -1;
for (unsigned i = 0; i < size / 3; i++) {
data[3*i] = (uint8_t)(words[i] >> 8);
data[3*i+1] = (uint8_t)words[i];
data[3*i+2] = crc(&data[3*i]);
}
if (bad_crc) data[2] ^= 1;
return 0;
}
void sensirion_i2c_hal_sleep_usec(uint32_t usec) { (void)usec; }
int main(void) {
bool ready = false;
uint8_t padding;
uint16_t pm1, pm2, pm4, pm10, co2;
int16_t rh, temp, voc, nox;
expected_address = 0x6b;
sen66_init(expected_address);
words[0] = 1;
assert(sen66_get_data_ready(&padding, &ready) == 0 && ready && padding == 0);
assert(command == 0x0202);
uint16_t measured[] = {10, 25, 30, 40, 4567, 5000, 1200, 0x7fff, 1456};
memcpy(words, measured, sizeof(measured));
#define READ66() sen66_read_measured_values_as_integers(&pm1, &pm2, &pm4, &pm10, &rh, &temp, &voc, &nox, &co2)
assert(READ66() == 0 && command == 0x0300);
assert(pm2 == 25 && rh == 4567 && temp == 5000 && voc == 1200 && nox == 0x7fff && co2 == 1456);
words[5] = (uint16_t)-1000;
words[8] = 0xffff;
assert(READ66() == 0 && temp == -1000 && co2 == 0xffff);
bad_crc = true;
assert(READ66() != 0);
bad_crc = false; fail_read = true;
assert(READ66() != 0);
fail_read = false; fail_write = true;
assert(READ66() != 0);
fail_write = false;
expected_address = 0x69;
words[0] = 1;
assert(sen5x_read_data_ready(&ready) == 0 && ready && command == 0x0202);
memcpy(words, measured, sizeof(measured));
#define READ54() sen5x_read_measured_values(&pm1, &pm2, &pm4, &pm10, &rh, &temp, &voc, &nox)
assert(READ54() == 0 && command == 0x03c4);
assert(pm2 == 25 && rh == 4567 && temp == 5000 && voc == 1200 && nox == 0x7fff);
bad_crc = true;
assert(READ54() != 0);
bad_crc = false; fail_write = true;
assert(READ54() != 0);
puts("PASS: SEN54/SEN66 address and command selection, measured payloads, signed values, sentinels, CRC and transport errors");
}
+86
View File
@@ -0,0 +1,86 @@
#include "sensor_soft_i2c.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
typedef struct {
int sda, scl;
int samples[64], rises[64];
unsigned sample_count, sample_index, rise_count, starts, stops;
unsigned stretch, one_us_delays;
bool stuck;
} fake_t;
static void sda(void *ctx, int value) {
fake_t *f = ctx;
if (f->scl && f->sda != value) {
if (value) f->stops++; else f->starts++;
}
f->sda = value;
}
static void scl(void *ctx, int value) {
fake_t *f = ctx;
if (value && !f->scl) {
assert(f->rise_count < 64);
f->rises[f->rise_count++] = f->sda;
}
f->scl = value;
}
static int read_sda(void *ctx) {
fake_t *f = ctx;
assert(f->sample_index < f->sample_count);
return f->samples[f->sample_index++];
}
static int read_scl(void *ctx) {
fake_t *f = ctx;
if (f->stuck) return 0;
if (f->stretch) { f->stretch--; return 0; }
return f->scl;
}
static void delay_us(void *ctx, unsigned us) {
if (us == 1) ((fake_t *)ctx)->one_us_delays++;
}
static unsigned transmitted_byte(fake_t *f, unsigned offset) {
unsigned b = 0;
for (unsigned n = 0; n < 8; n++) b = (b << 1) | f->rises[offset+n];
return b;
}
static void reset(fake_t *f) { memset(f, 0, sizeof(*f)); f->sda = f->scl = 1; }
int main(void) {
fake_t f;
sensor_soft_i2c_t p = { .context=&f, .sda=sda, .scl=scl,
.read_sda=read_sda, .read_scl=read_scl, .delay_us=delay_us,
.half_period_us=5, .stretch_timeout_us=10 };
uint8_t command[] = {0, 0x21};
reset(&f);
f.samples[0]=1; // idle bus, followed by three slave ACK bits.
f.sample_count=4;
assert(sensor_soft_i2c_transfer(&p,0x6b,command,2,false)==0);
assert(f.starts==1 && f.stops==1 && f.sda==1 && f.scl==1);
assert(transmitted_byte(&f,0)==0xd6 && transmitted_byte(&f,9)==0 && transmitted_byte(&f,18)==0x21);
reset(&f);
f.samples[0]=1; f.samples[1]=1; f.sample_count=2; // address NACK.
assert(sensor_soft_i2c_transfer(&p,0x6b,command,2,false)==1);
assert(f.starts==1 && f.stops==1 && f.sda==1 && f.scl==1);
reset(&f);
f.samples[0]=1; f.samples[1]=0;
for (unsigned n=0;n<16;n++) f.samples[n+2]=((0xa55aU>>(15-n))&1);
f.sample_count=18;
uint8_t data[2];
assert(sensor_soft_i2c_transfer(&p,0x6b,data,2,true)==0);
assert(data[0]==0xa5 && data[1]==0x5a && transmitted_byte(&f,0)==0xd7);
assert(f.rises[17]==0 && f.rises[26]==1); // ACK then final NACK.
assert(f.starts==1 && f.stops==1);
reset(&f); f.samples[0]=1; f.sample_count=2; f.stretch=3;
assert(sensor_soft_i2c_transfer(&p,0x6b,NULL,0,false)==0 && f.one_us_delays==3);
reset(&f); f.stuck=true;
assert(sensor_soft_i2c_transfer(&p,0x6b,NULL,0,false)==-1);
assert(f.one_us_delays==11 && f.sda==1 && f.scl==1);
assert(sensor_soft_i2c_transfer(&p,0x80,NULL,0,false)==-1);
assert(sensor_soft_i2c_transfer(&p,0x6b,NULL,1,true)==-1);
puts("PASS: GPIO I2C START/STOP, address/data bits, ACK/NACK, reads, stretching, timeout and line release");
}
+23
View File
@@ -0,0 +1,23 @@
#!/usr/bin/env python3
"""Run native UI integration tests against the project's actual LVGL sources."""
from pathlib import Path
import subprocess
import tempfile
import sys
firmware = Path(__file__).resolve().parents[2]
lvgl = firmware / 'managed_components/lvgl__lvgl'
ui = firmware / 'components/eez_gui'
with tempfile.TemporaryDirectory(prefix='nanopsx-ui-') as directory:
build = Path(directory)
(build / 'esp_log.h').write_text('#pragma once\n#define ESP_LOGI(...) ((void)0)\n')
sources = list((lvgl / 'src').rglob('*.c'))
sources += [ui / name for name in ['ui.c', 'screens.c', 'ui_navigation.c', 'ui_dashboard.c', 'ui_model.c', 'ui_font_ubuntu_16.c',
'ui_font_ubuntu_24.c', 'ui_font_pigiarniq_italic_34.c']]
sources += list(ui.glob('ui_image_*.c'))
sources += [Path(__file__).with_name('test_navigation.c')]
subprocess.run(['cc', '-std=c99', '-O0', '-g', '-DLV_CONF_SKIP',
'-DLV_MEM_SIZE=49152', '-I', str(build), '-I', str(lvgl),
'-I', str(ui), *map(str, sources), '-lm',
'-o', str(build / 'test_navigation')], check=True)
subprocess.run([str(build / 'test_navigation'), *sys.argv[1:]], check=True)
+175
View File
@@ -0,0 +1,175 @@
/* Integration tests use the actual LVGL pointer pipeline, charts and EEZ exports. */
#include <assert.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "ui.h"
#include "ui_navigation.h"
#include "ui_dashboard.h"
#include "ui_model.h"
static lv_indev_data_t sample;
static uint32_t framebuffer[172][320];
static unsigned brightness, saved;
static ui_display_config_t saved_config;
static void set_light(uint8_t value) { brightness = value; }
static void save_settings(const ui_display_config_t *value) { saved_config = *value; ++saved; }
static void read_pointer(lv_indev_drv_t *drv, lv_indev_data_t *data)
{
(void)drv; *data = sample;
ui_dashboard_filter_touch(data);
}
static void flush(lv_disp_drv_t *drv, const lv_area_t *area, lv_color_t *colors)
{
for (int y = area->y1; y <= area->y2; ++y)
for (int x = area->x1; x <= area->x2; ++x) {
if (x >= 0 && x < 320 && y >= 0 && y < 172) framebuffer[y][x] = lv_color_to32(*colors);
++colors;
}
lv_disp_flush_ready(drv);
}
static void advance(unsigned ms)
{
for (unsigned i = 0; i < ms; i += 10) { lv_tick_inc(10); lv_timer_handler(); }
}
static void point(int x, int y, bool pressed)
{
sample.point.x = x; sample.point.y = y;
sample.state = pressed ? LV_INDEV_STATE_PRESSED : LV_INDEV_STATE_RELEASED;
advance(40);
}
static void swipe(int x, int y, int dx, int dy)
{
point(x, y, true);
for (int i = 1; i <= 8; ++i) point(x + i * dx, y + i * dy, true);
point(x + 8 * dx, y + 8 * dy, false);
advance(300);
ui_tick();
}
static void screenshot(const char *directory, unsigned page)
{
if (!directory) return;
char path[1024]; snprintf(path,sizeof(path),"%s/page-%u.ppm",directory,page);
FILE *file = fopen(path,"wb"); assert(file);
fprintf(file,"P6\n320 172\n255\n");
for (unsigned y=0;y<172;++y) for(unsigned x=0;x<320;++x) {
uint32_t c=framebuffer[y][x];
unsigned char rgb[]={c>>16,c>>8,c}; fwrite(rgb,1,3,file);
}
fclose(file);
}
#define VALUE(name, text) const char *get_var_##name(void) { return text; }
VALUE(pm1p0,"3.2") VALUE(pm2p5,"6.8") VALUE(pm4p0,"7.1") VALUE(pm10p0,"7.3")
VALUE(voc_ind,"98") VALUE(humidity,"42.1") VALUE(temp,"23.4")
int main(int argc, char **argv)
{
lv_init();
static lv_color_t pixels[320 * 10];
static lv_disp_draw_buf_t buffer;
lv_disp_draw_buf_init(&buffer,pixels,NULL,320*10);
lv_disp_drv_t display; lv_disp_drv_init(&display);
display.hor_res=320; display.ver_res=172; display.draw_buf=&buffer; display.flush_cb=flush;
lv_disp_drv_register(&display);
lv_indev_drv_t pointer; lv_indev_drv_init(&pointer);
pointer.type=LV_INDEV_TYPE_POINTER; pointer.read_cb=read_pointer;
lv_indev_drv_register(&pointer);
ui_init();
ui_dashboard_init((ui_display_config_t){100,60},set_light,save_settings);
ui_navigation_init(); advance(300);
ui_device_status_t status={.wifi_connected=true,.influx_ok=true,.mdns_ok=true,
.ip="192.168.50.86",.last_influx_success_ms=1790000};
ui_dashboard_tick(1000,&status);
assert(strstr(lv_label_get_text(objects.room_state),"startet"));
assert(strcmp(lv_label_get_text(objects.room_co2),"--")==0);
assert(!lv_obj_has_flag(objects.main_notice,LV_OBJ_FLAG_HIDDEN));
ui_sample_t data={.available=true};
/* Realistic 30-minute test data exercises the complete ring buffer and chart. */
for (unsigned i=0;i<180;++i) {
data.timestamp_ms=1000+i*10000;
data.values[UI_METRIC_CO2]=900+150*sinf(i/15.0f);
data.values[UI_METRIC_PM25]=6.8f+2*sinf(i/10.0f);
data.values[UI_METRIC_TEMP]=23.4f;
data.values[UI_METRIC_RH]=42.1f;
data.values[UI_METRIC_VOC]=98;
data.values[UI_METRIC_NOX]=1;
ui_model_publish(&data);
}
ui_dashboard_tick(data.timestamp_ms,&status); tick_screen(0); advance(300);
assert(lv_obj_has_flag(objects.main_notice,LV_OBJ_FLAG_HIDDEN));
assert(atoi(lv_label_get_text(objects.room_co2))>700);
const char *previews=argc>1?argv[1]:NULL;
screenshot(previews,1);
point(160,80,true); point(160,80,false); advance(300);
assert(lv_scr_act()==objects.main);
swipe(140,80,-1,0); assert(lv_scr_act()==objects.main);
swipe(160,20,0,15); assert(lv_scr_act()==objects.main);
swipe(40,80,25,0); assert(lv_scr_act()==objects.main);
swipe(280,80,-25,0); assert(lv_scr_act()==objects.page_2);
screenshot(previews,2);
swipe(280,80,-25,0); assert(lv_scr_act()==objects.history);
for(unsigned i=0;i<UI_METRIC_COUNT;++i) {
lv_dropdown_set_selected(objects.history_metric,i);
ui_dashboard_tick(data.timestamp_ms,&status);
assert(strstr(lv_label_get_text(objects.history_range),"Noch")==NULL);
assert(strstr(lv_label_get_text(objects.history_range),"..")!=NULL);
assert(lv_label_get_text(objects.history_range)[0]!='f');
}
lv_dropdown_set_selected(objects.history_metric,0);
ui_dashboard_tick(data.timestamp_ms,&status); advance(300);
screenshot(previews,3);
/* Popup owns its input, so a gesture on it cannot change the screen. */
lv_dropdown_open(objects.history_metric); advance(100);
swipe(280,20,-25,0); assert(lv_scr_act()==objects.history);
lv_dropdown_close(objects.history_metric);
swipe(280,20,-25,0); assert(lv_scr_act()==objects.device);
screenshot(previews,4);
swipe(280,20,-25,0); assert(lv_scr_act()==objects.device);
/* Sliding the brightness control changes brightness, never the page. */
swipe(270,111,-15,0); assert(lv_scr_act()==objects.device);
assert(brightness>=20 && brightness<100 && saved>0);
unsigned before=brightness, save_count=saved;
advance(61000); ui_dashboard_tick(data.timestamp_ms,&status);
assert(brightness==15);
point(170,111,true); point(170,111,false);
assert(brightness==before && saved==save_count); /* first touch wakes only */
point(220,111,true); point(220,111,false);
assert(brightness!=before && saved>save_count);
lv_dropdown_set_selected(objects.dim_timeout,0);
lv_event_send(objects.dim_timeout,LV_EVENT_VALUE_CHANGED,NULL);
assert(saved_config.dim_after_s==0);
advance(121000); ui_dashboard_tick(data.timestamp_ms,&status);
assert(brightness==saved_config.brightness);
/* Freshness is independent of network connectivity and missing channels. */
ui_dashboard_tick(data.timestamp_ms+6000,&status);
assert(strstr(lv_label_get_text(objects.room_state),"veraltet"));
assert(strcmp(lv_label_get_text(objects.room_co2),"--")==0);
data.values[UI_METRIC_CO2]=NAN;
data.timestamp_ms+=10000; ui_model_publish(&data);
status.wifi_connected=false; status.influx_ok=false;
ui_dashboard_tick(data.timestamp_ms,&status);
assert(strstr(lv_label_get_text(objects.room_state),"nicht verfügbar"));
assert(strstr(lv_label_get_text(objects.device_wifi),"nicht verbunden"));
assert(strstr(lv_label_get_text(objects.device_influx),"Fehler"));
for(unsigned repeat=0;repeat<3;++repeat) {
swipe(40,20,25,0); assert(lv_scr_act()==objects.history);
swipe(40,20,25,0); assert(lv_scr_act()==objects.page_2);
swipe(40,20,25,0); assert(lv_scr_act()==objects.main);
swipe(280,20,-25,0); assert(lv_scr_act()==objects.page_2);
swipe(280,20,-25,0); assert(lv_scr_act()==objects.history);
swipe(280,20,-25,0); assert(lv_scr_act()==objects.device);
}
/* Ten-second means, gap preservation, missing-channel independence, eviction. */
float history[UI_HISTORY_POINTS];
uint64_t base=4000000;
data.timestamp_ms=base; data.values[0]=800; ui_model_publish(&data);
data.timestamp_ms=base+1000; data.values[0]=1000; ui_model_publish(&data);
ui_model_history(UI_METRIC_CO2,base+1000,history);
assert(fabsf(history[179]-900)<0.01f);
ui_model_history(UI_METRIC_CO2,base+20000,history);
assert(isnan(history[179]) && isnan(history[178]) && history[177]==900);
ui_model_history(UI_METRIC_CO2,base+1810000,history);
for(unsigned i=0;i<180;++i) assert(isnan(history[i]));
puts("PASS: four-page navigation, controls, popup isolation, wake-only touch, dim settings, stale/missing data, six charts, history means/gaps/eviction");
}
+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""Export this project's static EEZ/LVGL screens without a desktop installation.
Supports the widget/style subset used here; rejects unsupported widget types.
Application behavior stays in ui_dashboard/ui_navigation, outside generated files.
"""
from pathlib import Path
import argparse
import json
import re
root = Path(__file__).resolve().parents[2]
project = json.loads((root / 'eez/nanopsx.eez-project').read_text())
out = root / 'firmware/components/eez_gui'
def name(value):
return re.sub(r'[^a-z0-9_]', '_', value.lower())
def string(value):
return json.dumps(value, ensure_ascii=False)
def walk(widget):
yield widget
for child in widget.get('children', []):
yield from walk(child)
pages = project['userPages']
roots = [name(page['name']) for page in pages]
fields = list(roots)
for page in pages:
for widget in walk(page['components'][0]):
identifier = widget.get('identifier', '').strip()
if identifier:
assert name(identifier) not in fields, identifier
fields.append(name(identifier))
header = ['/* Generated by firmware/tools/export_display.py from the EEZ project. */',
'#pragma once', '#include <lvgl.h>', '#ifdef __cplusplus', 'extern "C" {', '#endif',
'typedef struct {', *[f' lv_obj_t *{field};' for field in fields],
'} objects_t;', 'extern objects_t objects;', 'enum ScreensEnum {',
*[f' SCREEN_ID_{r.upper()} = {i+1},' for i,r in enumerate(roots)], '};']
for r in roots:
header += [f'void create_screen_{r}(void);', f'void tick_screen_{r}(void);']
header += ['void create_screens(void);', 'void tick_screen(int screen_index);',
'void tick_screen_by_id(enum ScreensEnum screen_id);', '#ifdef __cplusplus', '}', '#endif']
source = ['/* Generated by firmware/tools/export_display.py from the EEZ project. */',
'#include "screens.h"', '#include "fonts.h"', '#include "images.h"',
'#include "vars.h"', '#include <string.h>',
'objects_t objects;', 'lv_obj_t *tick_value_change_obj;', 'uint32_t active_theme_index;']
creators = {'Screen':'lv_obj_create','Panel':'lv_obj_create','Label':'lv_label_create',
'Image':'lv_img_create','Chart':'lv_chart_create','Slider':'lv_slider_create',
'Dropdown':'lv_dropdown_create'}
color_styles = {'bg_color','border_color','text_color','line_color'}
scalar_styles = {'radius','border_width','pad_all','pad_left','pad_right','pad_top','pad_bottom',
'bg_opa','line_width','line_rounded','text_letter_space','text_line_space'}
for page,r in zip(pages, roots):
bindings = []
source.append(f'void create_screen_{r}(void) {{')
for i,widget in enumerate(walk(page['components'][0])):
kind = widget['type'].removeprefix('LVGL').removesuffix('Widget')
assert kind in creators, f'Unsupported EEZ widget: {kind}'
identifier = r if i == 0 else name(widget.get('identifier','').strip())
# Resolve parent from the actual tree, avoiding flattened-index assumptions.
def find_parent(node, target):
for child in node.get('children',[]):
if child is target: return node
found = find_parent(child,target)
if found is not None: return found
tree = list(walk(page['components'][0]))
parent = find_parent(tree[0], widget) if i else None
parent_expr = f'w{next(j for j,node in enumerate(tree) if node is parent)}' if parent else 'NULL'
v=f'w{i}'
source.append(f' lv_obj_t *{v} = {creators[kind]}({parent_expr});')
if identifier: source.append(f' objects.{identifier} = {v};')
source.append(f' lv_obj_set_pos({v}, {widget["left"]}, {widget["top"]});')
width = 'LV_SIZE_CONTENT' if widget.get('widthUnit')=='content' else widget['width']
height = 'LV_SIZE_CONTENT' if widget.get('heightUnit')=='content' else widget['height']
source.append(f' lv_obj_set_size({v}, {width}, {height});')
source.append(f' lv_obj_clear_flag({v}, LV_OBJ_FLAG_SCROLLABLE);')
if widget.get('clickableFlag'): source.append(f' lv_obj_add_flag({v}, LV_OBJ_FLAG_CLICKABLE);')
if widget.get('hiddenFlag'): source.append(f' lv_obj_add_flag({v}, LV_OBJ_FLAG_HIDDEN);')
for part,states in widget.get('localStyles',{}).get('definition',{}).items():
for state,props in states.items():
selector = f'LV_PART_{part} | LV_STATE_{state}'
for prop,value in props.items():
if prop in color_styles: cvalue=f'lv_color_hex(0x{value.lstrip("#")})'
elif prop=='text_font': cvalue='&ui_font_'+name(value)
elif prop in scalar_styles: cvalue=str(value).lower()
else: raise ValueError(f'Unsupported EEZ style: {prop}')
source.append(f' lv_obj_set_style_{prop}({v}, {cvalue}, {selector});')
if kind=='Label':
source.append(f' lv_label_set_long_mode({v}, LV_LABEL_LONG_{widget.get("longMode","WRAP")});')
if widget.get('textType')=='expression':
assert identifier
binding=f'get_var_{name(widget["text"])}()'
source.append(f' lv_label_set_text({v}, {binding});')
bindings.append((identifier,binding))
else: source.append(f' lv_label_set_text({v}, {string(widget.get("text",""))});')
elif kind=='Image': source.append(f' lv_img_set_src({v}, &img_{name(widget["image"])});')
elif kind=='Chart':
source += [f' lv_chart_set_type({v}, LV_CHART_TYPE_LINE);',f' lv_chart_set_point_count({v}, {widget["pointCount"]});',f' lv_chart_set_div_line_count({v}, {widget["divLineCountH"]}, {widget["divLineCountV"]});']
elif kind=='Slider':
source += [f' lv_slider_set_range({v}, {widget["min"]}, {widget["max"]});',f' lv_slider_set_value({v}, {widget["value"]}, LV_ANIM_OFF);']
elif kind=='Dropdown':
source += [f' lv_dropdown_set_options({v}, {string(widget["options"])});',f' lv_dropdown_set_selected({v}, {widget["selected"]});',f' lv_dropdown_set_dir({v}, LV_DIR_{widget["direction"].upper()});']
source += ['}',f'void tick_screen_{r}(void) {{']
for identifier,binding in bindings:
source += [f' if (strcmp(lv_label_get_text(objects.{identifier}), {binding}) != 0)', f' lv_label_set_text(objects.{identifier}, {binding});']
source += ['}']
source += ['void create_screens(void) {', ' lv_disp_t *display = lv_disp_get_default();',
' lv_disp_set_theme(display, lv_theme_default_init(display, lv_palette_main(LV_PALETTE_BLUE), lv_palette_main(LV_PALETTE_RED), true, LV_FONT_DEFAULT));',
*[f' create_screen_{r}();' for r in roots], '}',
'void tick_screen(int index) {', ' switch (index) {',
*[f' case {i}: tick_screen_{r}(); break;' for i,r in enumerate(roots)],
' default: break;', ' }', '}',
'void tick_screen_by_id(enum ScreensEnum id) { tick_screen(id - 1); }']
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--check', action='store_true', help='Fail if checked-in exports differ')
args=parser.parse_args()
for filename,lines in [('screens.h',header),('screens.c',source)]:
data='\n'.join(lines)+'\n'
if args.check:
assert (out/filename).read_text()==data, f'Outdated EEZ export: {filename}'
elif not (out/filename).exists() or (out/filename).read_text() != data:
(out/filename).write_text(data)
print('EEZ screen exports '+('verified' if args.check else 'generated'))
+8
View File
@@ -0,0 +1,8 @@
"""Keep EEZ screen exports in sync before PlatformIO configures the build."""
from pathlib import Path
import subprocess
import sys
Import("env")
script = Path(env.subst("$PROJECT_DIR")) / "tools" / "export_display.py"
subprocess.run([sys.executable, str(script)], check=True)
+158
View File
@@ -0,0 +1,158 @@
# InfluxDB auf dem Linux-NUC per Avahi bekannt machen
Diese Dateien richten eine dauerhafte mDNS/DNS-SD-Ankündigung für die vorhandene
ESP32-Firmware ein. Avahi läuft auf dem **Debian-13-NUC**, außerhalb von Docker.
Die Konfiguration wird nach einem NUC-Neustart automatisch geladen.
## Vorgesehener Aufbau
| Einstellung | Wert |
| --- | --- |
| NUC-WLAN/AP-Interface | `wlp2s0` |
| NUC-WLAN-Adresse | `192.168.50.1/24` |
| InfluxDB-URL für den ESP | `http://192.168.50.1:8086` |
| Diensttyp | `_influxdb2._tcp.local.` |
| Dienstname | `nanoPSX InfluxDB NUC` |
| mDNS-Hostname | vorhandener Avahi-Hostname, auf diesem NUC `nuc.local` |
Der ESP muss mit dem NUC-WLAN verbunden sein. Der InfluxDB-Container muss Port
8086 an `192.168.50.1` veröffentlichen; das ist beim untersuchten NUC bereits
eingerichtet. Ein fehlender Listener an `127.0.0.1:8086` ist dabei erwartbar.
Der Dienst verwendet den vorhandenen Avahi-Hostnamen (`nuc.local` auf diesem
NUC). Es wird kein zusätzlicher Hostname für dieselbe IP registriert, da dies bei
Avahi eine lokale Namenskollision verursachen kann. Auf dem WLAN muss die
Auflösung `192.168.50.1` liefern; dies nach der Installation prüfen. Die allgemeine
Avahi-Interface-Konfiguration bleibt erhalten. Die Ankündigung kann auch auf
anderen von Avahi bedienten Interfaces sichtbar sein. Kein mDNS-Reflector wird
eingerichtet.
## Installation
1. Das Projekt oder mindestens den vollständigen Ordner `linux-app` auf den NUC
kopieren. Die folgenden Befehle dort in einer lokalen Shell ausführen.
2. Das frühere Python-mDNS-Skript bzw. dessen Systemdienst für diese
InfluxDB-Ankündigung beenden und dessen Autostart deaktivieren. Ebenso einen
laufenden Test mit `avahi-publish-service` beenden. Andere mDNS-Dienste erhalten.
3. Im Projektverzeichnis ausführen:
```bash
sudo bash linux-app/install-avahi.sh
```
Das Skript prüft die AP-Adresse und InfluxDB `/health`, installiert mit APT
`avahi-daemon`, `avahi-utils`, `curl` und `python3`, sichert vorhandene Dateien
unter `/var/backups/nanopsx-avahi/install.*` und installiert:
- `/etc/avahi/services/nanopsx-influxdb.service`
- keinen neuen Eintrag in `/etc/avahi/hosts`. Der exakt markierte Alias der ersten
Skriptversion wird nach Sicherung entfernt, falls vorhanden.
Andere Hosteinträge und Dienste bleiben erhalten. Eine unbekannte abweichende
Dienstdatei führt zum Abbruch. Die unveränderte erste Version der mitgelieferten
Dienstdatei wird anhand ihres SHA-256 erkannt und automatisch aktualisiert.
Wiederholtes Ausführen mit unveränderten Einstellungen erzeugt keine doppelten
Hosteinträge. Ein fehlgeschlagener Installationslauf ist kein Erfolgsnachweis;
die ausgegebenen Fehler zuerst prüfen. Bereits installierte Pakete bleiben bei
einem späteren Fehler installiert.
Es werden weder Docker, Firewall, WireGuard, SSH noch ESP-Firmware geändert.
Es sind keine Influx-Tokens oder WLAN-Passwörter in diesen Dateien erforderlich.
## Funktion prüfen
Auf dem NUC:
```bash
systemctl is-enabled avahi-daemon.service
systemctl is-active avahi-daemon.service
curl --noproxy '*' -fsS --max-time 5 http://192.168.50.1:8086/health
avahi-browse -r -t _influxdb2._tcp
```
Erwartet: `enabled`, `active`, Health-Status `pass` und beim aufgelösten Dienst
auf Interface `wlp2s0` mit IPv4 die Adresse `192.168.50.1`, Port `8086`
und Hostname `nuc.local` (sofern der Rechnername nicht geändert wurde).
`avahi-browse` unterstützt weder `-4` noch `-i`; die Ausgabe enthält Interface
und IP-Protokoll als Spalten.
Zusätzlich von einem anderen Linux-Rechner im NUC-WLAN prüfen, sofern verfügbar:
```bash
avahi-browse -r -t _influxdb2._tcp
curl --noproxy '*' -fsS --max-time 5 http://192.168.50.1:8086/health
```
Ein lokaler NUC-Test allein beweist noch keine Erreichbarkeit vom ESP.
Die Firmware sucht ungefähr alle 60 Sekunden, bis sie einen Dienst gefunden
hat, und speichert dessen URL. Hat sie bereits einen anderen Dienst gefunden,
den ESP einmal neu starten, nachdem die richtige Ankündigung aktiv ist.
Die seriellen ESP-Logs sollen anschließend `mDNS URL: http://192.168.50.1:8086`
zeigen. Erst erfolgreiche Influx-Schreibvorgänge mit HTTP-Status `204` und
aktuelle Messwerte im Influx-Bucket bestätigen die vollständige Verbindung.
Organisation, Bucket und ein Token mit Schreibrecht für diesen Bucket müssen
zusätzlich im ESP-Konfigurationsportal hinterlegt sein. Tokens dort lokal
eingeben und nicht in Git oder Diagnoseausgaben veröffentlichen.
Avahi kündigt statisch an: Es überwacht die Verfügbarkeit des Containers nicht.
Die Installation prüft `/health` einmalig. Nach einem NUC-Neustart kann die
Ankündigung schon sichtbar sein, bevor InfluxDB bereit ist; die Firmware muss
Verbindungsversuche wiederholen.
## Fehler untersuchen
```bash
journalctl -u avahi-daemon.service -b --no-pager -n 80
ip -br -4 addr
ss -ltn '( sport = :8086 )'
```
- Kein Dienst gefunden: Avahi-Status und Logs prüfen. In
`/etc/avahi/avahi-daemon.conf` darf `wlp2s0` nicht ausgeschlossen und Publishing
nicht deaktiviert sein. Das Installationsskript überschreibt diese Einstellungen
bewusst nicht.
- Nur lokal sichtbar: Firewall für mDNS (UDP 5353, IPv4-Multicast
`224.0.0.251`) auf dem WLAN und mögliche AP-Client-Isolation prüfen.
- HTTP-Timeout: TCP 8086 vom WLAN, Docker-Portfreigabe und Firewall prüfen.
- HTTP 401/403: Influx-Token und dessen Bucket-Schreibrechte prüfen.
- Mehrere Influx-Dienste: Die Firmware nimmt einen passenden Treffer. Alte
konkurrierende Ankündigungen entfernen, bevor die Erkennung erneut startet.
Keine Firewall-Regeln pauschal löschen und keine unbekannten Dienste abschalten.
Für einen anderen AP die Adresse und das Interface im Installationsskript
gezielt anpassen und die Auflösung auf dem neuen WLAN prüfen.
## Ankündigung entfernen
Nur die von dieser Einrichtung angelegten Einträge entfernen:
```bash
sudo rm /etc/avahi/services/nanopsx-influxdb.service
sudo systemctl reload avahi-daemon.service
```
Falls die Dateien inzwischen manuell geändert wurden, vor dem Entfernen prüfen.
Vorhandene Hosteinträge bleiben erhalten. Avahi und seine anderen Dienste bleiben aktiv. Die Sicherung enthält
die vorherigen Dateien; diese nicht pauschal zurückkopieren, wenn inzwischen
weitere Änderungen vorgenommen wurden.
## Referenzen
- [Debian: statische Avahi-Dienste](https://manpages.debian.org/trixie/avahi-daemon/avahi.service.5.en.html)
- [Debian: avahi-browse und gültige Optionen](https://manpages.debian.org/trixie/avahi-utils/avahi-browse.1.en.html)
- [InfluxDB: Health-Prüfung](https://docs.influxdata.com/influxdb/v2/api/health/)
## Getesteter Stand (2026-11-07)
Skriptsyntax, XML, Installation und Migration der ersten Konfiguration wurden
im Entwicklungscontainer mit isolierten Systemaufrufen geprüft. Der Benutzer
hat die Konfiguration auf dem Debian-NUC installiert und die korrigierte
Dienstdatei ohne zusätzlichen Hostnamen eingesetzt. Seine `avahi-browse`-Ausgabe
bestätigt auf `wlp2s0` die Auflösung von `nuc.local` zu `192.168.50.1:8086`.
Serielle Tests des ESP bestätigten anschließend HTTP-Verbindungen zu dieser
Adresse. Nach Einrichtung von Organisation `Home`, Bucket `nanoPSX` und einem
passenden Token hat der Benutzer die funktionierende SEN54-Übertragung zu
InfluxDB bestätigt. Diese abschließende Funktionsbestätigung stammt vom Benutzer;
eine weitere serielle Aufzeichnung mit erfolgreichen Schreibantworten wurde
danach nicht erstellt. Zugangsdaten gehören nicht in diese Dokumentation.
+11
View File
@@ -0,0 +1,11 @@
<?xml version="1.0" standalone="no"?>
<!DOCTYPE service-group SYSTEM "avahi-service.dtd">
<service-group>
<name replace-wildcards="no">nanoPSX InfluxDB NUC</name>
<service protocol="ipv4">
<type>_influxdb2._tcp</type>
<domain-name>local</domain-name>
<port>8086</port>
<txt-record>path=/</txt-record>
</service>
</service-group>
+80
View File
@@ -0,0 +1,80 @@
#!/usr/bin/env bash
# Auf dem Debian-NUC ausführen, nicht im Codex- oder InfluxDB-Container.
set -euo pipefail
SCRIPT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)
SOURCE="$SCRIPT_DIR/avahi/nanopsx-influxdb.service"
DEST=/etc/avahi/services/nanopsx-influxdb.service
HOSTS=/etc/avahi/hosts
AP_INTERFACE=wlp2s0
AP_ADDRESS=192.168.50.1
# Exakter Hash unserer ersten Version: nur diese darf automatisch migriert werden.
LEGACY_SERVICE_SHA256=b5dadb78f624dd5e6e4fa8b7243af23b687e1adf9c88712207510a4c52bc7357
if (( EUID != 0 )); then
echo "Bitte auf dem NUC mit sudo bash $0 ausführen." >&2
exit 1
fi
if [[ ! -f /etc/debian_version || ! -d /run/systemd/system ]]; then
echo 'Benötigt einen Debian/Ubuntu-Host mit laufendem systemd.' >&2
exit 1
fi
if ! ip -4 -o addr show dev "$AP_INTERFACE" | awk '{print $4}' | cut -d/ -f1 | grep -Fxq "$AP_ADDRESS"; then
echo "Die erwartete AP-Adresse $AP_ADDRESS fehlt auf $AP_INTERFACE. Abbruch." >&2
exit 1
fi
for target in "$HOSTS" "$DEST"; do
if [[ -L "$target" || ( -e "$target" && ! -f "$target" ) ]]; then
echo "Unerwarteter Dateityp: $target. Abbruch." >&2
exit 1
fi
done
if [[ -e "$DEST" ]] && ! cmp -s "$SOURCE" "$DEST"; then
if [[ $(sha256sum "$DEST" | cut -d' ' -f1) != "$LEGACY_SERVICE_SHA256" ]]; then
echo "Abweichende Dienstdatei $DEST vorhanden; bitte zuerst manuell prüfen." >&2
exit 1
fi
fi
apt-get update
apt-get install -y avahi-daemon avahi-utils curl python3
# Vor jeder Änderung: InfluxDB muss an der tatsächlich angekündigten IP antworten.
curl --noproxy '*' --fail --silent --show-error --max-time 5 \
"http://$AP_ADDRESS:8086/health" |
python3 -c 'import json, sys; d=json.load(sys.stdin); sys.exit(0 if d.get("status")=="pass" else "InfluxDB health meldet nicht pass; Abbruch.")'
install -d -m 700 /var/backups/nanopsx-avahi
BACKUP=$(mktemp -d /var/backups/nanopsx-avahi/install.XXXXXXXX)
for target in "$HOSTS" "$DEST"; do
if [[ -e "$target" ]]; then
cp -a -- "$target" "$BACKUP/$(basename -- "$target")"
else
touch "$BACKUP/$(basename -- "$target").was-absent"
fi
done
echo "Sicherung vor Änderungen: $BACKUP"
install -d -m 755 /etc/avahi/services
# Ausschließlich den von unserer ersten Version angelegten Alias entfernen.
# Avahi verwendet für den Dienst seinen vorhandenen lokalen Hostnamen.
python3 - "$HOSTS" <<'PY'
from pathlib import Path
import sys
p = Path(sys.argv[1])
if p.exists():
original = p.read_bytes()
cleaned = b"".join(line for line in original.splitlines(keepends=True)
if line.rstrip(b"\r\n") !=
b"192.168.50.1 nanopsx-influx.local # nanopsx-avahi")
if cleaned != original:
p.write_bytes(cleaned)
PY
install -o root -g root -m 644 "$SOURCE" "$DEST"
systemctl enable --now avahi-daemon.service
systemctl reload avahi-daemon.service
systemctl is-active --quiet avahi-daemon.service
echo "Avahi läuft und startet beim Booten. Ziel: http://$AP_ADDRESS:8086"
echo 'Die erfolgreiche mDNS-Auflösung und ESP-Übertragung jetzt gemäß README prüfen.'