initial commit
This commit is contained in:
1 parent
8a022ca22e
commit
e11564b359
7 files changed
+968
No files matched your search
@@ -0,0 +1,184 @@
|
||||
# cultivar_env
|
||||
|
||||
Environmental sensor library for the [Grove5](https://grovefive.com) Cultivar appliance.
|
||||
|
||||
**Grove5 — Open source software, honest hardware.**
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
`cultivar_env` runs on the real-time MCU (STM32 on Arduino UNO Q) and is responsible for:
|
||||
|
||||
- Collecting ambient temp/humidity/pressure (BME690, heater off)
|
||||
- Running a 10-point mycology-tuned gas sweep
|
||||
- Reading real CO2 from SCD43 (if populated)
|
||||
- Cross-validating temp/humidity between BME690 and SCD43
|
||||
- Serializing a structured JSON payload for the Linux side
|
||||
|
||||
The Linux side (QRB2210) is responsible for baseline management, CO2e estimation, delta tracking, and anomaly detection. The STM32 just collects and sends.
|
||||
|
||||
---
|
||||
|
||||
## Hardware
|
||||
|
||||
**ENV-1-V0.1** sensor board — two population variants:
|
||||
|
||||
| Variant | Sensors | Chamber |
|
||||
|---------|---------|---------|
|
||||
| Full | BME690 + SCD43 | Fruiting — real CO2, cross-validation, drift detection |
|
||||
| Lite | BME690 only | Colonization — CO2e from gas sweep (Linux side) |
|
||||
|
||||
SCD43 is auto-detected at `begin()` — same firmware for both variants.
|
||||
|
||||
---
|
||||
|
||||
## Dependencies
|
||||
|
||||
- [Sensirion I2C SCD4x](https://github.com/Sensirion/arduino-i2c-scd4x) by Sensirion
|
||||
- Bosch BME690 SensorAPI — copy `bme69x.h`, `bme69x.c`, `bme69x_defs.h` from [boschsensortec/BME690_SensorAPI](https://github.com/boschsensortec/BME690_SensorAPI) into `src/`
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
1. Download [Bosch BME690 SensorAPI](https://github.com/boschsensortec/BME690_SensorAPI)
|
||||
2. Copy `bme69x.h`, `bme69x.c`, `bme69x_defs.h` into `cultivar_env/src/`
|
||||
3. Install `Sensirion I2C SCD4x` via Arduino Library Manager
|
||||
4. Install `cultivar_env` via Sketch → Include Library → Add .ZIP Library
|
||||
|
||||
---
|
||||
|
||||
## Quick Start
|
||||
|
||||
```cpp
|
||||
#include <Wire.h>
|
||||
#include <cultivar_env.h>
|
||||
|
||||
CultivarEnv env;
|
||||
char jsonBuf[768];
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
env.begin(Wire, 42, 41); // SDA, SCL
|
||||
}
|
||||
|
||||
void loop() {
|
||||
CultivarEnvPayload payload;
|
||||
env.collect(payload);
|
||||
env.printPayload(payload);
|
||||
|
||||
env.toJSON(payload, jsonBuf, sizeof(jsonBuf));
|
||||
Serial.println(jsonBuf); // → Linux side
|
||||
|
||||
delay(300000); // 5 min
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10-Point Mycology Gas Sweep
|
||||
|
||||
| # | Temp°C | Dur ms | Zone | Notes |
|
||||
|---|--------|--------|------|-------|
|
||||
| 0 | 200 | 150 | 1 — Baseline | Humidity/CO2 proxy |
|
||||
| 1 | 220 | 150 | 1 — Baseline | Light alcohols low |
|
||||
| 2 | 250 | 150 | 1 — Baseline | Ethanol / light alcohols |
|
||||
| 3 | 280 | 180 | 2 — Biological | Acetic acid / bacterial marker |
|
||||
| 4 | 300 | 180 | 2 — Biological | Terpene zone low |
|
||||
| 5 | 320 | 180 | 2 — Biological | Geosmin / 1-octen-3-ol |
|
||||
| 6 | 340 | 200 | 2 — Biological | Aldehyde zone |
|
||||
| 7 | 360 | 200 | 3 — Heavy | Ammonia / nitrogen compounds |
|
||||
| 8 | 380 | 200 | 3 — Heavy | Sulfur compounds |
|
||||
| 9 | 400 | 200 | 3 — Heavy | Heavy VOC fingerprint |
|
||||
|
||||
**Important:** Resistance values are raw. Humidity correction, baseline normalization, and compound inference are handled on the Linux side. The MOX sensor measures total gas load at each temperature — ratios and deltas are more meaningful than absolute values.
|
||||
|
||||
---
|
||||
|
||||
## JSON Payload
|
||||
|
||||
```json
|
||||
{
|
||||
"ts": 300000,
|
||||
"ambient": {"temp": 23.45, "hum": 82.10, "pres": 929.88, "ok": true},
|
||||
"co2": {"ppm": 1850, "temp": 24.10, "hum": 83.20, "ok": true},
|
||||
"health": {
|
||||
"scd43": true,
|
||||
"tdelta": 0.65, "hdelta": 1.10,
|
||||
"tok": true, "hok": true
|
||||
},
|
||||
"baseline": {"established": false, "samples": 3},
|
||||
"sweep": [
|
||||
{"t": 200, "dur": 150, "zone": 1, "r": 85000000, "stable": true, "ok": true},
|
||||
{"t": 220, "dur": 150, "zone": 1, "r": 72000000, "stable": true, "ok": true},
|
||||
{"t": 250, "dur": 150, "zone": 1, "r": 61000000, "stable": true, "ok": true},
|
||||
{"t": 280, "dur": 180, "zone": 2, "r": 420000, "stable": true, "ok": true},
|
||||
{"t": 300, "dur": 180, "zone": 2, "r": 280000, "stable": true, "ok": true},
|
||||
{"t": 320, "dur": 180, "zone": 2, "r": 195000, "stable": true, "ok": true},
|
||||
{"t": 340, "dur": 200, "zone": 2, "r": 148000, "stable": true, "ok": true},
|
||||
{"t": 360, "dur": 200, "zone": 3, "r": 102400000,"stable": true, "ok": true},
|
||||
{"t": 380, "dur": 200, "zone": 3, "r": 102400000,"stable": true, "ok": true},
|
||||
{"t": 400, "dur": 200, "zone": 3, "r": 102400000,"stable": true, "ok": true}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Baseline Handshake
|
||||
|
||||
The STM32 increments `baseline.samples` every collection cycle. The Linux side determines when enough samples exist to establish a baseline and echoes back `established=true`. The STM32 includes the current baseline state in every payload.
|
||||
|
||||
```cpp
|
||||
// Called when Linux confirms baseline is ready
|
||||
env.setBaselineEstablished(true);
|
||||
|
||||
// Called at start of new cultivation run
|
||||
env.resetBaseline();
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Sensor Health
|
||||
|
||||
When both sensors are populated, `cultivar_env` cross-validates temp and humidity between BME690 and SCD43 every collection cycle. Thresholds:
|
||||
|
||||
- Temp delta warn: **2.0°C**
|
||||
- Humidity delta warn: **5.0%RH**
|
||||
|
||||
A persistent warning may indicate condensation on the BME690, sensor damage, or I2C degradation — all meaningful in a high-humidity grow chamber environment.
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- `collect()` blocks for ~15-25s (ambient settle + 10-point sweep)
|
||||
- SCD43 needs ~30s warmup on first power-on
|
||||
- BME690 gas resistance stabilizes over 15-30 min per session; full calibration takes several days per Bosch documentation
|
||||
- 5-minute collection interval recommended for production — frequent heater cycling causes thermal drift in ambient readings
|
||||
- Altitude not included in payload — compute on Linux side if needed
|
||||
|
||||
---
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
STM32 (cultivar_env) Linux / QRB2210
|
||||
───────────────────── ──────────────────────────────
|
||||
collect() → JSON payload (Serial/UART)
|
||||
readAmbient() baseline management
|
||||
readCO2() humidity correction model
|
||||
runSweep() x10 CO2e estimation
|
||||
computeHealth() delta tracking
|
||||
toJSON() anomaly detection
|
||||
Cultivar UI / MQTT
|
||||
← baseline_established echo
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
MIT — Grove5
|
||||
Bosch BME690 SensorAPI: BSD-3-Clause — Bosch Sensortec GmbH
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* cultivar_sensor.ino
|
||||
* Example sketch for the cultivar_env library.
|
||||
*
|
||||
* Grove5 Cultivar appliance — ENV-1-V0.1 sensor board
|
||||
* BME690 (required) + SCD43 (optional, auto-detected)
|
||||
*
|
||||
* STM32 responsibility: collect, validate, serialize → JSON → Linux
|
||||
* Linux responsibility: baseline, CO2e model, delta tracking, anomaly detection
|
||||
*
|
||||
* Board: ESP32S3 Dev Module (dev) / Arduino UNO Q (production)
|
||||
* I2C: SDA=42, SCL=41 (ESP32S3) — update for UNO Q pinout
|
||||
*
|
||||
* Grove5 — Open source software, honest hardware.
|
||||
* https://grovefive.com
|
||||
*/
|
||||
|
||||
#include <Wire.h>
|
||||
#include <cultivar_env.h>
|
||||
|
||||
// ── Collection interval ───────────────────────────────────────────────────
|
||||
// Production: 5 minutes. Dev/test: 30 seconds.
|
||||
#define COLLECT_INTERVAL_MS (5UL * 60UL * 1000UL)
|
||||
// #define COLLECT_INTERVAL_MS (30UL * 1000UL) // dev
|
||||
|
||||
// ── I2C pins — update for production board ────────────────────────────────
|
||||
#define SDA_PIN 42 // ESP32S3 dev
|
||||
#define SCL_PIN 41 // ESP32S3 dev
|
||||
|
||||
// ── JSON output buffer ────────────────────────────────────────────────────
|
||||
// Size: ~512 bytes for 10-point sweep + all fields
|
||||
static char jsonBuf[1024];
|
||||
|
||||
CultivarEnv env;
|
||||
|
||||
void setup() {
|
||||
Serial.begin(115200);
|
||||
delay(2000);
|
||||
|
||||
Serial.println("\n╔═══════════════════════════════════╗");
|
||||
Serial.println("║ Grove5 Cultivar ENV v0.2.0 ║");
|
||||
Serial.println("║ Open source software, ║");
|
||||
Serial.println("║ honest hardware. ║");
|
||||
Serial.println("║ grovefive.com ║");
|
||||
Serial.println("╚═══════════════════════════════════╝\n");
|
||||
|
||||
if (!env.begin(Wire, SDA_PIN, SCL_PIN)) {
|
||||
Serial.println("[ERROR] BME690 init failed — check wiring");
|
||||
}
|
||||
|
||||
env.scanI2C();
|
||||
|
||||
Serial.printf("[cultivar_env] BME690: %s SCD43: %s\n",
|
||||
env.bme_ok ? "OK" : "FAIL",
|
||||
env.scd4x_ok ? "OK (dual sensor mode)" : "not populated (single sensor mode)");
|
||||
|
||||
if (env.scd4x_ok) {
|
||||
Serial.println("SCD43 warming up (~30s for first CO2 reading)...");
|
||||
}
|
||||
|
||||
Serial.printf("Collection interval: %lu min\n\n",
|
||||
COLLECT_INTERVAL_MS / 60000UL);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
static unsigned long lastCollect = 0;
|
||||
static bool firstRun = true;
|
||||
|
||||
// First collection: wait for SCD43 warmup if present, else 5s
|
||||
unsigned long waitMs = firstRun
|
||||
? (env.scd4x_ok ? 35000UL : 5000UL)
|
||||
: COLLECT_INTERVAL_MS;
|
||||
|
||||
if (millis() - lastCollect >= waitMs) {
|
||||
lastCollect = millis();
|
||||
firstRun = false;
|
||||
|
||||
Serial.println("Starting collection...");
|
||||
|
||||
CultivarEnvPayload payload;
|
||||
env.collect(payload);
|
||||
|
||||
// Human-readable output
|
||||
env.printPayload(payload);
|
||||
|
||||
// JSON → Linux side (Serial or UART to QRB2210)
|
||||
size_t jsonLen = env.toJSON(payload, jsonBuf, sizeof(jsonBuf));
|
||||
Serial.println("\n── JSON ──────────────────────────────");
|
||||
Serial.println(jsonBuf);
|
||||
Serial.println("─────────────────────────────────────\n");
|
||||
|
||||
// Example: Linux side echoes back baseline_established=true
|
||||
// env.setBaselineEstablished(true);
|
||||
}
|
||||
|
||||
// Keep SCD43 active between collections
|
||||
if (env.scd4x_ok) {
|
||||
CultivarCO2 co2;
|
||||
env.pollCO2(co2);
|
||||
// fresh readings available here if needed for display etc.
|
||||
}
|
||||
|
||||
delay(100);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
name=cultivar_env
|
||||
version=0.2.0
|
||||
author=Grove5
|
||||
maintainer=Grove5 <[email protected]>
|
||||
sentence=Environmental sensor library for the Grove5 Cultivar appliance.
|
||||
paragraph=Wraps the Bosch BME690 SensorAPI directly for Arduino-compatible MCUs. Provides ambient sensing, 10-point mycology-tuned gas sweeps, SCD43 CO2 integration, and sensor cross-validation. Designed for the STM32/Linux dual-brain architecture of the Arduino UNO Q. Portable — no ESP32-specific dependencies.
|
||||
category=Sensors
|
||||
url=https://github.com/grove5/cultivar_env
|
||||
architectures=*
|
||||
depends=Sensirion I2C SCD4x
|
||||
@@ -0,0 +1,418 @@
|
||||
/**
|
||||
* cultivar_env.cpp
|
||||
* Grove5 — Open source software, honest hardware.
|
||||
* https://grovefive.com
|
||||
*/
|
||||
|
||||
#include "cultivar_env.h"
|
||||
|
||||
// ── 10-point mycology sweep profile ──────────────────────────────────────
|
||||
static const uint16_t SWEEP_TEMPS[CULTIVAR_SWEEP_COUNT] = {
|
||||
200, 220, 250, // Zone 1 — Baseline
|
||||
280, 300, 320, 340, // Zone 2 — Biological
|
||||
360, 380, 400 // Zone 3 — Heavy
|
||||
};
|
||||
|
||||
static const uint16_t SWEEP_DURS[CULTIVAR_SWEEP_COUNT] = {
|
||||
150, 150, 150, // Zone 1
|
||||
180, 180, 180, 200, // Zone 2
|
||||
200, 200, 200 // Zone 3
|
||||
};
|
||||
|
||||
static const uint8_t SWEEP_ZONES[CULTIVAR_SWEEP_COUNT] = {
|
||||
CULTIVAR_ZONE_BASELINE, CULTIVAR_ZONE_BASELINE, CULTIVAR_ZONE_BASELINE,
|
||||
CULTIVAR_ZONE_BIOLOGICAL, CULTIVAR_ZONE_BIOLOGICAL,
|
||||
CULTIVAR_ZONE_BIOLOGICAL, CULTIVAR_ZONE_BIOLOGICAL,
|
||||
CULTIVAR_ZONE_HEAVY, CULTIVAR_ZONE_HEAVY, CULTIVAR_ZONE_HEAVY
|
||||
};
|
||||
|
||||
// ── Constructor ───────────────────────────────────────────────────────────
|
||||
CultivarEnv::CultivarEnv()
|
||||
: _wire(nullptr), _sda(CULTIVAR_ENV_SDA), _scl(CULTIVAR_ENV_SCL),
|
||||
_bme_addr(CULTIVAR_ENV_BME690_ADDR)
|
||||
{
|
||||
memset(&_dev, 0, sizeof(_dev));
|
||||
memset(&_conf, 0, sizeof(_conf));
|
||||
memset(&_heatr, 0, sizeof(_heatr));
|
||||
_baseline.established = false;
|
||||
_baseline.samples_collected = 0;
|
||||
}
|
||||
|
||||
// ── begin ─────────────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::begin(TwoWire &wire, uint8_t sda, uint8_t scl, uint8_t bme_addr) {
|
||||
_wire = &wire;
|
||||
_sda = sda;
|
||||
_scl = scl;
|
||||
_bme_addr = bme_addr;
|
||||
|
||||
_wire->begin(_sda, _scl);
|
||||
|
||||
bme_ok = _initBME690();
|
||||
scd4x_ok = _initSCD4x();
|
||||
|
||||
return bme_ok; // SCD43 is optional
|
||||
}
|
||||
|
||||
// ── _initBME690 ───────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::_initBME690() {
|
||||
_i2c_handle.wire = _wire;
|
||||
_i2c_handle.addr = _bme_addr;
|
||||
|
||||
_dev.intf = BME69X_I2C_INTF;
|
||||
_dev.read = _i2cRead;
|
||||
_dev.write = _i2cWrite;
|
||||
_dev.delay_us = _delayUs;
|
||||
_dev.intf_ptr = &_i2c_handle;
|
||||
_dev.amb_temp = 25;
|
||||
|
||||
bme_status = bme69x_init(&_dev);
|
||||
if (bme_status != BME69X_OK) return false;
|
||||
|
||||
if (_dev.variant_id != BME690_VARIANT_GAS_HIGH) {
|
||||
Serial.printf("[cultivar_env] Warning: variant_id=0x%02X (expected 0x02 for BME690)\n",
|
||||
_dev.variant_id);
|
||||
}
|
||||
|
||||
// Default sensor config
|
||||
_conf.os_temp = BME69X_OS_2X;
|
||||
_conf.os_pres = BME69X_OS_16X;
|
||||
_conf.os_hum = BME69X_OS_1X;
|
||||
_conf.filter = BME69X_FILTER_SIZE_3;
|
||||
_conf.odr = BME69X_ODR_NONE;
|
||||
|
||||
bme_status = bme69x_set_conf(&_conf, &_dev);
|
||||
return bme_status == BME69X_OK;
|
||||
}
|
||||
|
||||
// ── _initSCD4x ────────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::_initSCD4x() {
|
||||
_scd4x.begin(*_wire, CULTIVAR_ENV_SCD4X_ADDR);
|
||||
uint16_t err = _scd4x.stopPeriodicMeasurement();
|
||||
if (err) return false;
|
||||
err = _scd4x.startPeriodicMeasurement();
|
||||
return err == 0;
|
||||
}
|
||||
|
||||
// ── _forcedRead ───────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::_forcedRead(struct bme69x_data &data) {
|
||||
int8_t r = bme69x_set_op_mode(BME69X_FORCED_MODE, &_dev);
|
||||
if (r != BME69X_OK) return false;
|
||||
|
||||
// Wait for T/P/H measurement + heater duration
|
||||
uint32_t meas_dur = bme69x_get_meas_dur(BME69X_FORCED_MODE, &_conf, &_dev);
|
||||
uint32_t heat_dur = (uint32_t)_heatr.heatr_dur * 1000; // ms -> us
|
||||
_dev.delay_us(meas_dur + heat_dur + 5000, _dev.intf_ptr);
|
||||
|
||||
uint8_t n_data = 0;
|
||||
r = bme69x_get_data(BME69X_FORCED_MODE, &data, &n_data, &_dev);
|
||||
return r == BME69X_OK && n_data > 0;
|
||||
}
|
||||
|
||||
// ── _readAmbient ──────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::_readAmbient(CultivarAmbient &out) {
|
||||
out.valid = false;
|
||||
|
||||
// High oversampling, heater off
|
||||
_conf.os_temp = BME69X_OS_8X;
|
||||
_conf.os_pres = BME69X_OS_16X;
|
||||
_conf.os_hum = BME69X_OS_4X;
|
||||
_conf.filter = BME69X_FILTER_SIZE_7;
|
||||
int8_t r = bme69x_set_conf(&_conf, &_dev);
|
||||
if (r != BME69X_OK) return false;
|
||||
|
||||
_heatr.enable = BME69X_DISABLE;
|
||||
_heatr.heatr_temp = 0;
|
||||
_heatr.heatr_dur = 0;
|
||||
r = bme69x_set_heatr_conf(BME69X_FORCED_MODE, &_heatr, &_dev);
|
||||
if (r != BME69X_OK) return false;
|
||||
|
||||
// Settle — let residual heater heat dissipate
|
||||
delay(CULTIVAR_AMBIENT_SETTLE_MS);
|
||||
|
||||
struct bme69x_data data;
|
||||
if (!_forcedRead(data)) return false;
|
||||
|
||||
out.temperature = data.temperature;
|
||||
out.humidity = data.humidity;
|
||||
out.pressure = data.pressure / 100.0f; // Pa → hPa
|
||||
out.valid = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── _readCO2 ─────────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::_readCO2(CultivarCO2 &out) {
|
||||
out.valid = false;
|
||||
if (!scd4x_ok) return false;
|
||||
|
||||
bool ready = false;
|
||||
uint16_t err = _scd4x.getDataReadyStatus(ready);
|
||||
if (err || !ready) return false;
|
||||
|
||||
uint16_t co2;
|
||||
float temp, hum;
|
||||
err = _scd4x.readMeasurement(co2, temp, hum);
|
||||
if (err || co2 == 0) return false;
|
||||
|
||||
out.co2_ppm = co2;
|
||||
out.temperature = temp;
|
||||
out.humidity = hum;
|
||||
out.valid = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── _computeHealth ────────────────────────────────────────────────────────
|
||||
void CultivarEnv::_computeHealth(CultivarSensorHealth &health,
|
||||
const CultivarAmbient &ambient,
|
||||
const CultivarCO2 &co2) {
|
||||
health.scd43_present = scd4x_ok;
|
||||
|
||||
if (scd4x_ok && ambient.valid && co2.valid) {
|
||||
health.temp_delta = fabsf(ambient.temperature - co2.temperature);
|
||||
health.humidity_delta = fabsf(ambient.humidity - co2.humidity);
|
||||
health.temp_ok = health.temp_delta < CULTIVAR_TEMP_DELTA_WARN;
|
||||
health.humidity_ok = health.humidity_delta < CULTIVAR_HUMIDITY_DELTA_WARN;
|
||||
} else {
|
||||
health.temp_delta = 0.0f;
|
||||
health.humidity_delta = 0.0f;
|
||||
health.temp_ok = true; // can't check — not a failure
|
||||
health.humidity_ok = true;
|
||||
}
|
||||
}
|
||||
|
||||
// ── _runSweep ─────────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::_runSweep(CultivarGasPoint *out, uint8_t &count) {
|
||||
count = 0;
|
||||
|
||||
// Restore standard oversampling for gas measurements
|
||||
_conf.os_temp = BME69X_OS_2X;
|
||||
_conf.os_pres = BME69X_OS_4X;
|
||||
_conf.os_hum = BME69X_OS_1X;
|
||||
_conf.filter = BME69X_FILTER_SIZE_3;
|
||||
int8_t r = bme69x_set_conf(&_conf, &_dev);
|
||||
if (r != BME69X_OK) return false;
|
||||
|
||||
for (uint8_t i = 0; i < CULTIVAR_SWEEP_COUNT; i++) {
|
||||
out[i].heater_temp_c = SWEEP_TEMPS[i];
|
||||
out[i].heater_dur_ms = SWEEP_DURS[i];
|
||||
out[i].zone = SWEEP_ZONES[i];
|
||||
out[i].resistance = 0.0f;
|
||||
out[i].heater_stable = false;
|
||||
out[i].valid = false;
|
||||
|
||||
_heatr.enable = BME69X_ENABLE;
|
||||
_heatr.heatr_temp = SWEEP_TEMPS[i];
|
||||
_heatr.heatr_dur = SWEEP_DURS[i];
|
||||
|
||||
r = bme69x_set_heatr_conf(BME69X_FORCED_MODE, &_heatr, &_dev);
|
||||
if (r != BME69X_OK) continue;
|
||||
|
||||
struct bme69x_data data;
|
||||
if (!_forcedRead(data)) continue;
|
||||
|
||||
bool heater_stable = (data.status & BME69X_HEAT_STAB_MSK) != 0;
|
||||
bool gas_valid = (data.status & BME69X_GASM_VALID_MSK) != 0;
|
||||
|
||||
out[i].resistance = data.gas_resistance;
|
||||
out[i].heater_stable = heater_stable;
|
||||
out[i].valid = gas_valid;
|
||||
|
||||
count++;
|
||||
delay(50); // brief cool-down between profiles
|
||||
}
|
||||
|
||||
return count > 0;
|
||||
}
|
||||
|
||||
// ── collect ───────────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::collect(CultivarEnvPayload &payload) {
|
||||
payload.timestamp_ms = millis();
|
||||
payload.sweep_count = 0;
|
||||
|
||||
bool ok = _readAmbient(payload.ambient);
|
||||
_readCO2(payload.co2);
|
||||
_computeHealth(payload.health, payload.ambient, payload.co2);
|
||||
_runSweep(payload.sweep, payload.sweep_count);
|
||||
|
||||
// Update baseline sample counter
|
||||
_baseline.samples_collected++;
|
||||
payload.baseline = _baseline;
|
||||
|
||||
return ok;
|
||||
}
|
||||
|
||||
// ── pollCO2 ───────────────────────────────────────────────────────────────
|
||||
bool CultivarEnv::pollCO2(CultivarCO2 &out) {
|
||||
return _readCO2(out);
|
||||
}
|
||||
|
||||
// ── toJSON ────────────────────────────────────────────────────────────────
|
||||
size_t CultivarEnv::toJSON(const CultivarEnvPayload &p, char *buf, size_t len) {
|
||||
size_t n = 0;
|
||||
|
||||
n += snprintf(buf + n, len - n, "{");
|
||||
n += snprintf(buf + n, len - n, "\"ts\":%lu,", p.timestamp_ms);
|
||||
|
||||
// Ambient
|
||||
n += snprintf(buf + n, len - n, "\"ambient\":{");
|
||||
if (p.ambient.valid) {
|
||||
n += snprintf(buf + n, len - n,
|
||||
"\"temp\":%.2f,\"hum\":%.2f,\"pres\":%.2f,\"ok\":true",
|
||||
p.ambient.temperature, p.ambient.humidity, p.ambient.pressure);
|
||||
} else {
|
||||
n += snprintf(buf + n, len - n, "\"ok\":false");
|
||||
}
|
||||
n += snprintf(buf + n, len - n, "},");
|
||||
|
||||
// CO2
|
||||
n += snprintf(buf + n, len - n, "\"co2\":{");
|
||||
if (p.co2.valid) {
|
||||
n += snprintf(buf + n, len - n,
|
||||
"\"ppm\":%u,\"temp\":%.2f,\"hum\":%.2f,\"ok\":true",
|
||||
p.co2.co2_ppm, p.co2.temperature, p.co2.humidity);
|
||||
} else {
|
||||
n += snprintf(buf + n, len - n, "\"ok\":false");
|
||||
}
|
||||
n += snprintf(buf + n, len - n, "},");
|
||||
|
||||
// Health
|
||||
n += snprintf(buf + n, len - n,
|
||||
"\"health\":{\"scd43\":%s,\"tdelta\":%.2f,\"hdelta\":%.2f,\"tok\":%s,\"hok\":%s},",
|
||||
p.health.scd43_present ? "true" : "false",
|
||||
p.health.temp_delta,
|
||||
p.health.humidity_delta,
|
||||
p.health.temp_ok ? "true" : "false",
|
||||
p.health.humidity_ok ? "true" : "false");
|
||||
|
||||
// Baseline
|
||||
n += snprintf(buf + n, len - n,
|
||||
"\"baseline\":{\"established\":%s,\"samples\":%u},",
|
||||
p.baseline.established ? "true" : "false",
|
||||
p.baseline.samples_collected);
|
||||
|
||||
// Gas sweep
|
||||
n += snprintf(buf + n, len - n, "\"sweep\":[");
|
||||
for (uint8_t i = 0; i < p.sweep_count; i++) {
|
||||
n += snprintf(buf + n, len - n,
|
||||
"%s{\"t\":%u,\"dur\":%u,\"zone\":%u,\"r\":%.0f,\"stable\":%s,\"ok\":%s}",
|
||||
i > 0 ? "," : "",
|
||||
p.sweep[i].heater_temp_c,
|
||||
p.sweep[i].heater_dur_ms,
|
||||
p.sweep[i].zone,
|
||||
p.sweep[i].resistance,
|
||||
p.sweep[i].heater_stable ? "true" : "false",
|
||||
p.sweep[i].valid ? "true" : "false");
|
||||
}
|
||||
n += snprintf(buf + n, len - n, "]}");
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
// ── printPayload ──────────────────────────────────────────────────────────
|
||||
void CultivarEnv::printPayload(const CultivarEnvPayload &p) {
|
||||
Serial.printf("\n══ Cultivar ENV payload [t=%lums] ══\n", p.timestamp_ms);
|
||||
|
||||
// Ambient
|
||||
Serial.println("── Ambient (BME690, heater off) ──────");
|
||||
if (p.ambient.valid) {
|
||||
Serial.printf(" Temperature: %.2f °C\n", p.ambient.temperature);
|
||||
Serial.printf(" Humidity: %.2f %%RH\n", p.ambient.humidity);
|
||||
Serial.printf(" Pressure: %.2f hPa\n", p.ambient.pressure);
|
||||
} else {
|
||||
Serial.println(" [invalid]");
|
||||
}
|
||||
|
||||
// CO2
|
||||
Serial.println("── CO2 (SCD43) ───────────────────────");
|
||||
if (p.health.scd43_present) {
|
||||
if (p.co2.valid) {
|
||||
Serial.printf(" CO2: %u ppm\n", p.co2.co2_ppm);
|
||||
Serial.printf(" Temperature: %.2f °C\n", p.co2.temperature);
|
||||
Serial.printf(" Humidity: %.2f %%RH\n", p.co2.humidity);
|
||||
} else {
|
||||
Serial.println(" [no data]");
|
||||
}
|
||||
} else {
|
||||
Serial.println(" [not populated]");
|
||||
}
|
||||
|
||||
// Health
|
||||
Serial.println("── Sensor Health ─────────────────────");
|
||||
if (p.health.scd43_present && p.ambient.valid && p.co2.valid) {
|
||||
Serial.printf(" Temp delta: %.2f °C %s\n",
|
||||
p.health.temp_delta,
|
||||
p.health.temp_ok ? "✓" : "⚠ WARN");
|
||||
Serial.printf(" Hum delta: %.2f %%RH %s\n",
|
||||
p.health.humidity_delta,
|
||||
p.health.humidity_ok ? "✓" : "⚠ WARN");
|
||||
} else {
|
||||
Serial.println(" [single sensor mode]");
|
||||
}
|
||||
|
||||
// Baseline
|
||||
Serial.printf("── Baseline [samples=%u, established=%s]\n",
|
||||
p.baseline.samples_collected,
|
||||
p.baseline.established ? "yes" : "no");
|
||||
|
||||
// Gas sweep
|
||||
Serial.println("── Gas Sweep (BME690) ────────────────");
|
||||
Serial.printf(" %-6s %-6s %-5s %-16s %-7s %s\n",
|
||||
"Temp°C", "Dur ms", "Zone", "Resistance Ω", "Stable", "Valid");
|
||||
for (uint8_t i = 0; i < p.sweep_count; i++) {
|
||||
Serial.printf(" %-6u %-6u %-5u %-16.0f %-7s %s\n",
|
||||
p.sweep[i].heater_temp_c,
|
||||
p.sweep[i].heater_dur_ms,
|
||||
p.sweep[i].zone,
|
||||
p.sweep[i].resistance,
|
||||
p.sweep[i].heater_stable ? "✓" : "✗",
|
||||
p.sweep[i].valid ? "✓" : "✗");
|
||||
}
|
||||
Serial.println("─────────────────────────────────────");
|
||||
}
|
||||
|
||||
// ── scanI2C ───────────────────────────────────────────────────────────────
|
||||
void CultivarEnv::scanI2C() {
|
||||
Serial.println("\n── I2C Bus Scan ──────────────────────");
|
||||
int found = 0;
|
||||
for (uint8_t addr = 1; addr < 127; addr++) {
|
||||
_wire->beginTransmission(addr);
|
||||
if (_wire->endTransmission() == 0) {
|
||||
Serial.printf(" 0x%02X", addr);
|
||||
if (addr == 0x62) Serial.print(" ← SCD43");
|
||||
if (addr == 0x76 || addr == 0x77) Serial.print(" ← BME690");
|
||||
if (addr == 0x6B) Serial.print(" ← QMI8658C IMU");
|
||||
Serial.println();
|
||||
found++;
|
||||
}
|
||||
}
|
||||
if (!found) Serial.println(" No devices found");
|
||||
Serial.println("─────────────────────────────────────");
|
||||
}
|
||||
|
||||
// ── Bosch API I2C callbacks ───────────────────────────────────────────────
|
||||
int8_t CultivarEnv::_i2cRead(uint8_t reg_addr, uint8_t *data,
|
||||
uint32_t len, void *intf_ptr) {
|
||||
CultivarI2CHandle *h = (CultivarI2CHandle *)intf_ptr;
|
||||
h->wire->beginTransmission(h->addr);
|
||||
h->wire->write(reg_addr);
|
||||
if (h->wire->endTransmission(false) != 0) return -1;
|
||||
h->wire->requestFrom(h->addr, (uint8_t)len);
|
||||
for (uint32_t i = 0; i < len; i++) {
|
||||
if (!h->wire->available()) return -1;
|
||||
data[i] = h->wire->read();
|
||||
}
|
||||
return BME69X_OK;
|
||||
}
|
||||
|
||||
int8_t CultivarEnv::_i2cWrite(uint8_t reg_addr, const uint8_t *data,
|
||||
uint32_t len, void *intf_ptr) {
|
||||
CultivarI2CHandle *h = (CultivarI2CHandle *)intf_ptr;
|
||||
h->wire->beginTransmission(h->addr);
|
||||
h->wire->write(reg_addr);
|
||||
for (uint32_t i = 0; i < len; i++) h->wire->write(data[i]);
|
||||
return (h->wire->endTransmission() == 0) ? BME69X_OK : -1;
|
||||
}
|
||||
|
||||
void CultivarEnv::_delayUs(uint32_t period, void *intf_ptr) {
|
||||
(void)intf_ptr;
|
||||
delayMicroseconds(period);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
/**
|
||||
* cultivar_env.h
|
||||
* Environmental sensor library for the Grove5 Cultivar appliance.
|
||||
*
|
||||
* Grove5 — Open source software, honest hardware.
|
||||
* https://grovefive.com
|
||||
*
|
||||
* Designed for the STM32/Linux dual-brain architecture (Arduino UNO Q).
|
||||
* STM32 responsibility: collect, validate, serialize.
|
||||
* Linux responsibility: baseline, CO2e model, delta tracking, anomaly detection.
|
||||
*
|
||||
* Sensors:
|
||||
* BME690 — ambient temp/humidity/pressure + 10-point gas sweep
|
||||
* SCD43 — real CO2 (optional, detected at init)
|
||||
*
|
||||
* Hardware: ENV-1-V0.1 (BME690 + optional SCD43)
|
||||
* Default I2C: SDA=42, SCL=41 (ESP32S3 dev board)
|
||||
* Production I2C: SDA/SCL per Arduino UNO Q pinout
|
||||
*
|
||||
* Bosch BME690 SensorAPI: https://github.com/boschsensortec/BME690_SensorAPI
|
||||
* BSD-3-Clause — Bosch Sensortec GmbH
|
||||
*
|
||||
* MIT License — Grove5
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Wire.h>
|
||||
#include <SensirionI2cScd4x.h>
|
||||
|
||||
extern "C" {
|
||||
#include "bme69x.h"
|
||||
#include "bme69x_defs.h"
|
||||
}
|
||||
|
||||
// ── Default I2C pins (ESP32S3 dev board — override for production) ─────────
|
||||
#define CULTIVAR_ENV_SDA 42
|
||||
#define CULTIVAR_ENV_SCL 41
|
||||
|
||||
// ── I2C addresses ─────────────────────────────────────────────────────────
|
||||
#define CULTIVAR_ENV_BME690_ADDR BME69X_I2C_ADDR_LOW // 0x76
|
||||
#define CULTIVAR_ENV_SCD4X_ADDR SCD40_I2C_ADDR_62 // 0x62
|
||||
|
||||
// ── Sensor health thresholds ──────────────────────────────────────────────
|
||||
#define CULTIVAR_TEMP_DELTA_WARN 2.0f // °C
|
||||
#define CULTIVAR_HUMIDITY_DELTA_WARN 5.0f // %RH
|
||||
|
||||
// ── Ambient settle time after heater off ──────────────────────────────────
|
||||
#define CULTIVAR_AMBIENT_SETTLE_MS 3000
|
||||
|
||||
// ── Gas sweep configuration ───────────────────────────────────────────────
|
||||
#define CULTIVAR_SWEEP_COUNT 10
|
||||
|
||||
#define CULTIVAR_ZONE_BASELINE 1 // 200-250°C — humidity/CO2 proxy
|
||||
#define CULTIVAR_ZONE_BIOLOGICAL 2 // 280-340°C — mycelium/contamination
|
||||
#define CULTIVAR_ZONE_HEAVY 3 // 360-400°C — ammonia/sulfur/heavy VOC
|
||||
|
||||
// ── Structs ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Single gas sweep point.
|
||||
* Resistance values are raw — humidity correction and
|
||||
* delta tracking are handled on the Linux side.
|
||||
*/
|
||||
struct CultivarGasPoint {
|
||||
uint16_t heater_temp_c; // Heater setpoint °C
|
||||
uint16_t heater_dur_ms; // Heater duration ms
|
||||
uint8_t zone; // CULTIVAR_ZONE_*
|
||||
float resistance; // Raw resistance Ω
|
||||
bool heater_stable; // HEAT_STAB_MSK was set
|
||||
bool valid; // Gas measurement valid
|
||||
};
|
||||
|
||||
/**
|
||||
* Ambient conditions — BME690 with heater off.
|
||||
* Use for temp/humidity/pressure. No altitude — compute on Linux side.
|
||||
*/
|
||||
struct CultivarAmbient {
|
||||
float temperature; // °C
|
||||
float humidity; // %RH
|
||||
float pressure; // hPa
|
||||
bool valid;
|
||||
};
|
||||
|
||||
/**
|
||||
* CO2 reading from SCD43.
|
||||
* Temperature and humidity included for cross-validation only —
|
||||
* not primary temp/humidity source.
|
||||
*/
|
||||
struct CultivarCO2 {
|
||||
uint16_t co2_ppm;
|
||||
float temperature; // °C — cross-validation only
|
||||
float humidity; // %RH — cross-validation only
|
||||
bool valid;
|
||||
};
|
||||
|
||||
/**
|
||||
* Sensor health — cross-validation between BME690 and SCD43.
|
||||
* If scd43_present is false, delta fields are meaningless.
|
||||
*/
|
||||
struct CultivarSensorHealth {
|
||||
float temp_delta; // abs(bme_temp - scd43_temp)
|
||||
float humidity_delta; // abs(bme_hum - scd43_hum)
|
||||
bool temp_ok; // delta < CULTIVAR_TEMP_DELTA_WARN
|
||||
bool humidity_ok; // delta < CULTIVAR_HUMIDITY_DELTA_WARN
|
||||
bool scd43_present; // SCD43 detected and initialized
|
||||
};
|
||||
|
||||
/**
|
||||
* Baseline handshake state.
|
||||
* STM32 increments samples_collected every sweep.
|
||||
* Linux sets established=true when baseline is ready and echoes back.
|
||||
* STM32 includes current state in every payload.
|
||||
*/
|
||||
struct CultivarBaselineStatus {
|
||||
bool established;
|
||||
uint16_t samples_collected;
|
||||
};
|
||||
|
||||
/**
|
||||
* Full environmental payload — STM32 → Linux.
|
||||
* Serialize to JSON via toJSON(). One payload per collection cycle.
|
||||
*/
|
||||
struct CultivarEnvPayload {
|
||||
uint32_t timestamp_ms;
|
||||
CultivarAmbient ambient;
|
||||
CultivarCO2 co2;
|
||||
CultivarSensorHealth health;
|
||||
CultivarBaselineStatus baseline;
|
||||
CultivarGasPoint sweep[CULTIVAR_SWEEP_COUNT];
|
||||
uint8_t sweep_count;
|
||||
};
|
||||
|
||||
// ── I2C handle for Bosch API callbacks ───────────────────────────────────
|
||||
struct CultivarI2CHandle {
|
||||
TwoWire *wire;
|
||||
uint8_t addr;
|
||||
};
|
||||
|
||||
// ── Main library class ────────────────────────────────────────────────────
|
||||
class CultivarEnv {
|
||||
public:
|
||||
CultivarEnv();
|
||||
|
||||
/**
|
||||
* Initialize sensors.
|
||||
* SCD43 detection is automatic — if not found, health.scd43_present=false
|
||||
* and CO2 fields will be invalid. Library still functions with BME690 only.
|
||||
*
|
||||
* @param wire TwoWire instance
|
||||
* @param sda SDA pin
|
||||
* @param scl SCL pin
|
||||
* @param bme_addr BME690 I2C address (default 0x76)
|
||||
* @return true if BME690 initialized (SCD43 optional)
|
||||
*/
|
||||
bool begin(TwoWire &wire = Wire,
|
||||
uint8_t sda = CULTIVAR_ENV_SDA,
|
||||
uint8_t scl = CULTIVAR_ENV_SCL,
|
||||
uint8_t bme_addr = CULTIVAR_ENV_BME690_ADDR);
|
||||
|
||||
/**
|
||||
* Notify library that Linux has confirmed baseline is established.
|
||||
* Call when Linux side echoes back baseline_established=true.
|
||||
*/
|
||||
void setBaselineEstablished(bool established) {
|
||||
_baseline.established = established;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset baseline state — call at start of new cultivation run.
|
||||
*/
|
||||
void resetBaseline() {
|
||||
_baseline.established = false;
|
||||
_baseline.samples_collected = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Collect a full payload: ambient + CO2 + 10-point gas sweep.
|
||||
* Blocks for ambient settle + sweep duration (~15-25s).
|
||||
* @param payload Output
|
||||
* @return true if BME690 data valid (CO2 valid separately checked)
|
||||
*/
|
||||
bool collect(CultivarEnvPayload &payload);
|
||||
|
||||
/**
|
||||
* Poll CO2 — call frequently between collections to keep SCD43 active.
|
||||
* Non-blocking. Returns false if no new data available.
|
||||
*/
|
||||
bool pollCO2(CultivarCO2 &out);
|
||||
|
||||
/**
|
||||
* Serialize payload to JSON.
|
||||
* Compact format suitable for serial transmission to Linux side.
|
||||
* @param payload Input
|
||||
* @param buf Output buffer
|
||||
* @param len Buffer size
|
||||
* @return bytes written
|
||||
*/
|
||||
size_t toJSON(const CultivarEnvPayload &payload, char *buf, size_t len);
|
||||
|
||||
/**
|
||||
* Print payload human-readable to Serial.
|
||||
*/
|
||||
void printPayload(const CultivarEnvPayload &payload);
|
||||
|
||||
/**
|
||||
* Print I2C bus scan to Serial.
|
||||
*/
|
||||
void scanI2C();
|
||||
|
||||
// Public status
|
||||
bool bme_ok = false;
|
||||
bool scd4x_ok = false;
|
||||
int8_t bme_status = 0;
|
||||
|
||||
private:
|
||||
TwoWire *_wire;
|
||||
uint8_t _sda;
|
||||
uint8_t _scl;
|
||||
uint8_t _bme_addr;
|
||||
|
||||
// Bosch API
|
||||
struct bme69x_dev _dev;
|
||||
struct bme69x_conf _conf;
|
||||
struct bme69x_heatr_conf _heatr;
|
||||
struct CultivarI2CHandle _i2c_handle;
|
||||
|
||||
// SCD43
|
||||
SensirionI2cScd4x _scd4x;
|
||||
|
||||
// Baseline state
|
||||
CultivarBaselineStatus _baseline;
|
||||
|
||||
// Internal
|
||||
bool _initBME690();
|
||||
bool _initSCD4x();
|
||||
bool _readAmbient(CultivarAmbient &out);
|
||||
bool _readCO2(CultivarCO2 &out);
|
||||
bool _runSweep(CultivarGasPoint *out, uint8_t &count);
|
||||
bool _forcedRead(struct bme69x_data &data);
|
||||
void _computeHealth(CultivarSensorHealth &health,
|
||||
const CultivarAmbient &ambient,
|
||||
const CultivarCO2 &co2);
|
||||
|
||||
// Bosch API callbacks
|
||||
static int8_t _i2cRead(uint8_t reg_addr, uint8_t *data,
|
||||
uint32_t len, void *intf_ptr);
|
||||
static int8_t _i2cWrite(uint8_t reg_addr, const uint8_t *data,
|
||||
uint32_t len, void *intf_ptr);
|
||||
static void _delayUs(uint32_t period, void *intf_ptr);
|
||||
};
|
||||
Reference in new issue
Block a user