From 69bb47dda1bbb8dacb7c16a88ee7ab574c63efff Mon Sep 17 00:00:00 2001 From: root Date: Mon, 9 Nov 2026 21:44:04 +0000 Subject: [PATCH] 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. --- AGENTS.md | 16 + firmware/HARDWARE.md | 181 ++++ firmware/components/esp_bsp/CMakeLists.txt | 2 +- firmware/components/esp_bsp/bsp_i2c.h | 8 +- firmware/components/esp_bsp/bsp_touch.c | 17 +- firmware/components/esp_bsp/bsp_touch.h | 2 +- .../components/hardware_config/CMakeLists.txt | 1 + .../hardware_config/hardware_config.h | 72 ++ firmware/components/sen5x/CMakeLists.txt | 6 +- firmware/components/sen5x/LICENSE.sensirion | 29 + .../components/sen5x/SENSIRION-UPSTREAM.md | 19 + .../sen5x/{sen5x_app.c => air_sensor_app.c} | 156 +-- .../sen5x/{sen5x_app.h => air_sensor_app.h} | 10 +- firmware/components/sen5x/sen66_i2c.c | 798 ++++++++++++++++ firmware/components/sen5x/sen66_i2c.h | 899 ++++++++++++++++++ firmware/components/sen5x/sensirion_common.c | 45 +- firmware/components/sen5x/sensirion_common.h | 16 + firmware/components/sen5x/sensirion_i2c.c | 15 +- firmware/components/sen5x/sensirion_i2c.h | 33 + firmware/components/sen5x/sensirion_i2c_hal.c | 81 ++ firmware/components/sen5x/sensor_soft_i2c.c | 82 ++ firmware/components/sen5x/sensor_soft_i2c.h | 21 + firmware/src/CMakeLists.txt | 2 +- firmware/src/main.c | 34 +- firmware/test/sensors/run.sh | 31 + firmware/test/sensors/test_protocol.c | 83 ++ firmware/test/sensors/test_soft_i2c.c | 86 ++ 27 files changed, 2634 insertions(+), 111 deletions(-) create mode 100644 firmware/HARDWARE.md create mode 100644 firmware/components/hardware_config/CMakeLists.txt create mode 100644 firmware/components/hardware_config/hardware_config.h create mode 100644 firmware/components/sen5x/LICENSE.sensirion create mode 100644 firmware/components/sen5x/SENSIRION-UPSTREAM.md rename firmware/components/sen5x/{sen5x_app.c => air_sensor_app.c} (69%) rename firmware/components/sen5x/{sen5x_app.h => air_sensor_app.h} (74%) create mode 100644 firmware/components/sen5x/sen66_i2c.c create mode 100644 firmware/components/sen5x/sen66_i2c.h create mode 100644 firmware/components/sen5x/sensor_soft_i2c.c create mode 100644 firmware/components/sen5x/sensor_soft_i2c.h create mode 100644 firmware/test/sensors/run.sh create mode 100644 firmware/test/sensors/test_protocol.c create mode 100644 firmware/test/sensors/test_soft_i2c.c diff --git a/AGENTS.md b/AGENTS.md index 6219c4c..e580a7a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -32,6 +32,7 @@ Bekanntes Testboard: 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 @@ -61,6 +62,8 @@ Die `write`-Funktion erhält die Firmwaredatei über stdin. Die erwartete Dateig 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 Displayansicht bleibt auf Benutzerwunsch exakt die bisherige SEN54-Ansicht mit Schriftzug, PM, Temperatur, Feuchte, VOC und Statussymbolen. NOx und CO₂ vorerst nur für InfluxDB verarbeiten; keine zusätzlichen Displayfelder ohne neuen Auftrag hinzufügen. + 1. Projektkonfiguration in `platformio.ini` prüfen. 2. PlatformIO-Environment für das Zielboard bestimmen. 3. Firmware kompilieren. @@ -142,6 +145,19 @@ Am 04.11.2026 wurde ein Firmware-Upload auf das Board `CC:BA:97:F2:52:80` erfolg 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. + ## Bekannte Anwendungsprobleme Beim letzten Hardwaretest wurden festgestellt: diff --git a/firmware/HARDWARE.md b/firmware/HARDWARE.md new file mode 100644 index 0000000..a4f1063 --- /dev/null +++ b/firmware/HARDWARE.md @@ -0,0 +1,181 @@ +# 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. diff --git a/firmware/components/esp_bsp/CMakeLists.txt b/firmware/components/esp_bsp/CMakeLists.txt index e630dfc..846895e 100644 --- a/firmware/components/esp_bsp/CMakeLists.txt +++ b/firmware/components/esp_bsp/CMakeLists.txt @@ -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") diff --git a/firmware/components/esp_bsp/bsp_i2c.h b/firmware/components/esp_bsp/bsp_i2c.h index 086ba78..4be3dd8 100644 --- a/firmware/components/esp_bsp/bsp_i2c.h +++ b/firmware/components/esp_bsp/bsp_i2c.h @@ -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" { diff --git a/firmware/components/esp_bsp/bsp_touch.c b/firmware/components/esp_bsp/bsp_touch.c index 6422302..47a4871 100644 --- a/firmware/components/esp_bsp/bsp_touch.c +++ b/firmware/components/esp_bsp/bsp_touch.c @@ -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; } diff --git a/firmware/components/esp_bsp/bsp_touch.h b/firmware/components/esp_bsp/bsp_touch.h index f883757..2f7243f 100644 --- a/firmware/components/esp_bsp/bsp_touch.h +++ b/firmware/components/esp_bsp/bsp_touch.h @@ -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 diff --git a/firmware/components/hardware_config/CMakeLists.txt b/firmware/components/hardware_config/CMakeLists.txt new file mode 100644 index 0000000..311a0dc --- /dev/null +++ b/firmware/components/hardware_config/CMakeLists.txt @@ -0,0 +1 @@ +idf_component_register(INCLUDE_DIRS ".") diff --git a/firmware/components/hardware_config/hardware_config.h b/firmware/components/hardware_config/hardware_config.h new file mode 100644 index 0000000..dfe339c --- /dev/null +++ b/firmware/components/hardware_config/hardware_config.h @@ -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 diff --git a/firmware/components/sen5x/CMakeLists.txt b/firmware/components/sen5x/CMakeLists.txt index b60bf6c..0e42162 100644 --- a/firmware/components/sen5x/CMakeLists.txt +++ b/firmware/components/sen5x/CMakeLists.txt @@ -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,6 @@ idf_component_register( log net_influx eez_gui + storage + hardware_config ) diff --git a/firmware/components/sen5x/LICENSE.sensirion b/firmware/components/sen5x/LICENSE.sensirion new file mode 100644 index 0000000..8fe04ed --- /dev/null +++ b/firmware/components/sen5x/LICENSE.sensirion @@ -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. diff --git a/firmware/components/sen5x/SENSIRION-UPSTREAM.md b/firmware/components/sen5x/SENSIRION-UPSTREAM.md new file mode 100644 index 0000000..13fc047 --- /dev/null +++ b/firmware/components/sen5x/SENSIRION-UPSTREAM.md @@ -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`. diff --git a/firmware/components/sen5x/sen5x_app.c b/firmware/components/sen5x/air_sensor_app.c similarity index 69% rename from firmware/components/sen5x/sen5x_app.c rename to firmware/components/sen5x/air_sensor_app.c index 23b3759..0da6dba 100644 --- a/firmware/components/sen5x/sen5x_app.c +++ b/firmware/components/sen5x/air_sensor_app.c @@ -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" @@ -20,11 +25,11 @@ #include // NAN, isfinite, lround #include "vars.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 @@ -42,7 +47,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 +73,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 +144,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 +154,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 }; @@ -212,6 +219,12 @@ 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; + 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,6 +235,7 @@ 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 = { @@ -245,14 +259,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 +288,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 +313,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 +325,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 +337,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; diff --git a/firmware/components/sen5x/sen5x_app.h b/firmware/components/sen5x/air_sensor_app.h similarity index 74% rename from firmware/components/sen5x/sen5x_app.h rename to firmware/components/sen5x/air_sensor_app.h index 026efc1..4b9908e 100644 --- a/firmware/components/sen5x/sen5x_app.h +++ b/firmware/components/sen5x/air_sensor_app.h @@ -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); diff --git a/firmware/components/sen5x/sen66_i2c.c b/firmware/components/sen5x/sen66_i2c.c new file mode 100644 index 0000000..e394c4d --- /dev/null +++ b/firmware/components/sen5x/sen66_i2c.c @@ -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; +} diff --git a/firmware/components/sen5x/sen66_i2c.h b/firmware/components/sen5x/sen66_i2c.h new file mode 100644 index 0000000..aa0f1a4 --- /dev/null +++ b/firmware/components/sen5x/sen66_i2c.h @@ -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 diff --git a/firmware/components/sen5x/sensirion_common.c b/firmware/components/sen5x/sensirion_common.c index 03f4906..3cab3c1 100644 --- a/firmware/components/sen5x/sensirion_common.c +++ b/firmware/components/sen5x/sensirion_common.c @@ -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]; + } +} diff --git a/firmware/components/sen5x/sensirion_common.h b/firmware/components/sen5x/sensirion_common.h index cfcd19f..e290933 100644 --- a/firmware/components/sen5x/sensirion_common.h +++ b/firmware/components/sen5x/sensirion_common.h @@ -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 diff --git a/firmware/components/sen5x/sensirion_i2c.c b/firmware/components/sen5x/sensirion_i2c.c index a1c0668..5f709fc 100644 --- a/firmware/components/sen5x/sensirion_i2c.c +++ b/firmware/components/sen5x/sensirion_i2c.c @@ -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); diff --git a/firmware/components/sen5x/sensirion_i2c.h b/firmware/components/sen5x/sensirion_i2c.h index ac1e49d..45ff5c3 100644 --- a/firmware/components/sen5x/sensirion_i2c.h +++ b/firmware/components/sen5x/sensirion_i2c.h @@ -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. diff --git a/firmware/components/sen5x/sensirion_i2c_hal.c b/firmware/components/sen5x/sensirion_i2c_hal.c index 738ab38..1e58c02 100644 --- a/firmware/components/sen5x/sensirion_i2c_hal.c +++ b/firmware/components/sen5x/sensirion_i2c_hal.c @@ -11,6 +11,9 @@ #include #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; diff --git a/firmware/components/sen5x/sensor_soft_i2c.c b/firmware/components/sen5x/sensor_soft_i2c.c new file mode 100644 index 0000000..e141961 --- /dev/null +++ b/firmware/components/sen5x/sensor_soft_i2c.c @@ -0,0 +1,82 @@ +#include "sensor_soft_i2c.h" +#include + +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; +} diff --git a/firmware/components/sen5x/sensor_soft_i2c.h b/firmware/components/sen5x/sensor_soft_i2c.h new file mode 100644 index 0000000..2276722 --- /dev/null +++ b/firmware/components/sen5x/sensor_soft_i2c.h @@ -0,0 +1,21 @@ +#pragma once +#include +#include + +/* 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); diff --git a/firmware/src/CMakeLists.txt b/firmware/src/CMakeLists.txt index a17a1da..c595179 100644 --- a/firmware/src/CMakeLists.txt +++ b/firmware/src/CMakeLists.txt @@ -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 ) diff --git a/firmware/src/main.c b/firmware/src/main.c index fdd0f30..5944a6b 100644 --- a/firmware/src/main.c +++ b/firmware/src/main.c @@ -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 @@ -230,7 +231,7 @@ 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; } @@ -380,12 +381,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(); @@ -404,6 +410,12 @@ void app_main(void) 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 +463,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)); } diff --git a/firmware/test/sensors/run.sh b/firmware/test/sensors/run.sh new file mode 100644 index 0000000..32e4d12 --- /dev/null +++ b/firmware/test/sensors/run.sh @@ -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' diff --git a/firmware/test/sensors/test_protocol.c b/firmware/test/sensors/test_protocol.c new file mode 100644 index 0000000..4e5d1c2 --- /dev/null +++ b/firmware/test/sensors/test_protocol.c @@ -0,0 +1,83 @@ +/* Host-side tests exercise the real vendor drivers and shared CRC helpers. */ +#include +#include +#include +#include +#include +#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"); +} diff --git a/firmware/test/sensors/test_soft_i2c.c b/firmware/test/sensors/test_soft_i2c.c new file mode 100644 index 0000000..263cf68 --- /dev/null +++ b/firmware/test/sensors/test_soft_i2c.c @@ -0,0 +1,86 @@ +#include "sensor_soft_i2c.h" +#include +#include +#include + +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"); +}