initial commit

This commit is contained in:
grove5_admin committed 2026-04-27 19:30:45 -07:00
1 parent 8a022ca22e
commit e11564b359
7 files changed
+968

No files matched your search

+418
View File
@@ -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);
}
+252
View File
@@ -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);
};