-
-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Remove proprietary Bosch BSEC blob; open in-tree IAQ estimator for BME680 #11381
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
d56009f
Remove proprietary Bosch BSEC blob; open in-tree IAQ estimator for BM…
thebentern 4cdbd17
Address CodeRabbit review feedback
thebentern 485eafc
Address CodeRabbit nitpicks
thebentern b5fcc59
Merge remote-tracking branch 'origin/develop' into feature/open-iaq-r…
thebentern 0f21348
Merge remote-tracking branch 'origin/develop' into pr-merge
thebentern 9d98351
Merge branch 'develop' into feature/open-iaq-remove-bsec
thebentern File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,100 @@ | ||
| // Replays a captured BME680 CSV trace (gas_ohms,rh[,bsec_iaq]) through | ||
| // BME680IaqEstimator for offline tuning. See docs/bme680_iaq_replay.md. | ||
|
|
||
| #include "modules/Telemetry/Sensor/BME680IaqEstimator.h" | ||
|
|
||
| #include <cmath> | ||
| #include <cstdio> | ||
|
|
||
| namespace | ||
| { | ||
| // Same buckets the device UI uses (EnvironmentTelemetry drawFrame) | ||
| int band(int iaq) | ||
| { | ||
| if (iaq <= 25) | ||
| return 0; // Excellent | ||
| if (iaq <= 50) | ||
| return 1; // Good | ||
| if (iaq <= 100) | ||
| return 2; // Moderate | ||
| if (iaq <= 150) | ||
| return 3; // Poor | ||
| if (iaq <= 200) | ||
| return 4; // Unhealthy | ||
| if (iaq <= 300) | ||
| return 5; // Very Unhealthy | ||
| return 6; // Hazardous | ||
| } | ||
| } // namespace | ||
|
|
||
| int main(int argc, char **argv) | ||
| { | ||
| FILE *in = stdin; | ||
| if (argc > 1) { | ||
| in = fopen(argv[1], "r"); | ||
| if (!in) { | ||
| fprintf(stderr, "cannot open %s\n", argv[1]); | ||
| return 1; | ||
| } | ||
| } | ||
|
|
||
| BME680IaqEstimator est; | ||
| char line[256]; | ||
| long lineNo = 0, n = 0, skipped = 0, produced = 0, compared = 0, bandHits = 0; | ||
| double absErrSum = 0; | ||
|
|
||
| printf("n,gas_ohms,rh,est_iaq,bsec_iaq\n"); | ||
| while (fgets(line, sizeof(line), in)) { | ||
| lineNo++; | ||
| if (line[0] == '#' || line[0] == '\n') | ||
| continue; | ||
| float gas, rh, bsec = NAN; | ||
| int fields = sscanf(line, "%f,%f,%f", &gas, &rh, &bsec); | ||
| if (fields < 2) { | ||
| // Tolerate one header row silently; anything else malformed is | ||
| // reported so a damaged trace can't produce a quiet, biased summary | ||
| if (lineNo > 1) { | ||
| skipped++; | ||
| fprintf(stderr, "skipping malformed line %ld: %s", lineNo, line); | ||
| } | ||
| continue; | ||
| } | ||
| n++; | ||
|
thebentern marked this conversation as resolved.
|
||
| uint16_t iaq; | ||
| bool got = est.update(gas, rh, &iaq); | ||
| bool haveBsec = fields >= 3 && std::isfinite(bsec); | ||
|
|
||
| printf("%ld,%.0f,%.2f,", n, gas, rh); | ||
| if (got) | ||
| printf("%u", (unsigned)iaq); | ||
| if (haveBsec) | ||
| printf(",%.0f\n", bsec); | ||
| else | ||
| printf(",\n"); | ||
|
|
||
| if (got) { | ||
| produced++; | ||
| if (haveBsec) { | ||
| compared++; | ||
| absErrSum += std::fabs((double)iaq - (double)bsec); | ||
| if (band(iaq) == band((int)std::lround(bsec))) | ||
| bandHits++; | ||
| } | ||
| } | ||
| } | ||
| if (ferror(in)) { | ||
| fprintf(stderr, "input read error at line %ld\n", lineNo); | ||
| if (in != stdin) | ||
| fclose(in); | ||
| return 1; | ||
| } | ||
|
|
||
| fprintf(stderr, "samples: %ld, estimator outputs: %ld, malformed lines skipped: %ld\n", n, produced, skipped); | ||
| if (compared) { | ||
| fprintf(stderr, "vs BSEC (%ld comparable): mean abs error %.1f IAQ points, band agreement %.1f%%\n", compared, | ||
| absErrSum / compared, 100.0 * bandHits / compared); | ||
| } | ||
| if (in != stdin) | ||
| fclose(in); | ||
| return 0; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| # BME680 IAQ replay harness | ||
|
|
||
| `bin/bme680_iaq_replay.cpp` replays a captured sensor trace through the in-tree | ||
| `BME680IaqEstimator` on a dev machine, for tuning the estimator's constants | ||
| against recorded Bosch BSEC output. The estimator is pure math with no platform | ||
| dependencies, so a trace replays in milliseconds - edit the constants in | ||
| `src/modules/Telemetry/Sensor/BME680IaqEstimator.h`, recompile, rerun. | ||
|
|
||
| ## Build | ||
|
|
||
| From the repo root: | ||
|
|
||
| ```bash | ||
| c++ -std=c++17 -O2 -I src -o /tmp/iaq_replay \ | ||
| bin/bme680_iaq_replay.cpp src/modules/Telemetry/Sensor/BME680IaqEstimator.cpp | ||
| ``` | ||
|
|
||
| ## Input | ||
|
|
||
| CSV on stdin or as a file argument, one sample per line: | ||
|
|
||
| ```text | ||
| gas_ohms,relative_humidity[,bsec_iaq] | ||
| ``` | ||
|
|
||
| Lines starting with `#` are ignored; a single non-numeric header row is | ||
| tolerated; any other malformed line is reported on stderr and skipped. | ||
|
|
||
| ## Capturing a trace | ||
|
|
||
| On a firmware build that still links BSEC (any release tag before the BSEC | ||
| removal), add one log line to `BME680Sensor::getMetrics` in the BSEC branch: | ||
|
|
||
| ```cpp | ||
| LOG_INFO("IAQCSV,%.0f,%.2f,%.0f", bme680.getData(BSEC_OUTPUT_RAW_GAS).signal, | ||
| bme680.getData(BSEC_OUTPUT_SENSOR_HEAT_COMPENSATED_HUMIDITY).signal, | ||
| bme680.getData(BSEC_OUTPUT_IAQ).signal); | ||
| ``` | ||
|
|
||
| then extract the columns from the serial log: | ||
|
|
||
| ```bash | ||
| grep -o 'IAQCSV,.*' serial.log | cut -d, -f2- > trace.csv | ||
| ``` | ||
|
|
||
| BSEC's `RAW_GAS` and heat-compensated humidity are exactly the estimator's | ||
| inputs, so one physical sensor feeds both algorithms identically. | ||
|
|
||
| ## Output | ||
|
|
||
| Per-sample CSV `n,gas_ohms,rh,est_iaq,bsec_iaq` on stdout (empty `est_iaq` | ||
| during the estimator's warm-up/burn-in window), plus a stderr summary with the | ||
| mean absolute error and UI-band agreement against the `bsec_iaq` column, using | ||
| the same 0-500 band thresholds the device screen applies. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,94 @@ | ||
| #include "BME680IaqEstimator.h" | ||
|
|
||
| // std::clamp rather than meshUtils.h's clamp: that header drags in Arduino.h, | ||
| // and this file must stay compilable standalone on a dev host (see the replay | ||
| // harness in bin/bme680_iaq_replay.cpp) | ||
| #include <algorithm> | ||
| #include <math.h> | ||
| #include <string.h> | ||
|
|
||
| bool BME680IaqEstimator::update(float gasOhms, float relativeHumidity, uint16_t *iaqOut) | ||
| { | ||
| if (!(isfinite(gasOhms) && gasOhms > 0.0f)) | ||
| return false; | ||
|
|
||
| // A failed humidity read must not poison the baseline: fall back to the | ||
| // reference, which makes both compensation terms no-ops | ||
| float rh = isfinite(relativeHumidity) ? std::clamp(relativeHumidity, 0.0f, 100.0f) : RH_REF; | ||
|
|
||
| if (warmupRemaining > 0) { | ||
| warmupRemaining--; | ||
| return false; | ||
| } | ||
|
|
||
| float x = logf(gasOhms) + KH * (rh - RH_REF); | ||
| x = std::clamp(x, LN_FLOOR - LN_RANGE, LN_CEIL_MAX); | ||
|
|
||
| if (!seeded) { | ||
| lnCeiling = std::clamp(x, LN_FLOOR, LN_CEIL_MAX); | ||
| seeded = true; | ||
| } else { | ||
| float alpha = (x > lnCeiling) ? ALPHA_UP : ALPHA_DOWN; | ||
| lnCeiling = std::clamp(lnCeiling + alpha * (x - lnCeiling), LN_FLOOR, LN_CEIL_MAX); | ||
| } | ||
|
|
||
| if (sampleCount < UINT32_MAX) | ||
| sampleCount++; | ||
| if (sampleCount < BURN_IN_SAMPLES) | ||
| return false; | ||
|
|
||
| float below = lnCeiling - x; | ||
| if (below < 0.0f) | ||
| below = 0.0f; | ||
| float gasScore = std::clamp(below / LN_RANGE, 0.0f, 1.0f) * 500.0f; | ||
|
|
||
| // Comfort-band penalty: only outside the band, so ordinary indoor humidity | ||
| // can't keep IAQ away from the "Excellent" band | ||
| float humDeviation = rh < RH_COMFORT_MIN ? RH_COMFORT_MIN - rh : (rh > RH_COMFORT_MAX ? rh - RH_COMFORT_MAX : 0.0f); | ||
| float humScore = std::clamp(humDeviation / RH_DEV_NORM, 0.0f, 1.0f) * 500.0f; | ||
|
|
||
| *iaqOut = (uint16_t)lroundf(std::clamp(gasScore + HUM_WEIGHT * humScore, 0.0f, 500.0f)); | ||
| return true; | ||
| } | ||
|
|
||
| uint32_t BME680IaqEstimator::computeHash(const BME680IaqState &s) | ||
| { | ||
| uint32_t words[5]; | ||
| memcpy(words, &s, sizeof(words)); | ||
| return words[0] ^ words[1] ^ words[2] ^ words[3] ^ words[4]; | ||
| } | ||
|
|
||
| void BME680IaqEstimator::serialize(BME680IaqState *out, uint32_t nowSecs) const | ||
| { | ||
| memset(out, 0, sizeof(*out)); | ||
| out->magic = MAGIC; | ||
| out->version = VERSION; | ||
| out->warmupRemaining = (uint8_t)warmupRemaining; | ||
| out->lnCeiling = lnCeiling; | ||
| out->savedAtSecs = nowSecs; | ||
| out->sampleCount = sampleCount; | ||
| out->xorHash = computeHash(*out); | ||
| } | ||
|
|
||
| bool BME680IaqEstimator::restore(const BME680IaqState &in, uint32_t nowSecs) | ||
| { | ||
| if (in.magic != MAGIC || in.version != VERSION) | ||
| return false; | ||
| if (in.xorHash != computeHash(in)) | ||
| return false; | ||
| // The ceiling only exists once a sample has been accepted (sampleCount > 0); | ||
| // pure warm-up progress is persisted with lnCeiling still at 0 | ||
| bool hasBaseline = in.sampleCount > 0; | ||
| if (hasBaseline && !(isfinite(in.lnCeiling) && in.lnCeiling >= LN_FLOOR && in.lnCeiling <= LN_CEIL_MAX)) | ||
| return false; | ||
| // Staleness is only judgeable when the state was stamped with a valid RTC | ||
| // and we have one now; a week-old baseline says nothing about today's air | ||
| if (in.savedAtSecs != 0 && nowSecs != 0 && nowSecs >= in.savedAtSecs && (nowSecs - in.savedAtSecs) > STATE_MAX_AGE_SECS) | ||
| return false; | ||
|
|
||
| lnCeiling = in.lnCeiling; | ||
| sampleCount = in.sampleCount; | ||
| warmupRemaining = in.warmupRemaining <= WARMUP_DISCARD ? in.warmupRemaining : WARMUP_DISCARD; | ||
| seeded = hasBaseline; | ||
| return true; | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.