From 1435e91aafe3c3374c82ce962b8c1024a1a6e768 Mon Sep 17 00:00:00 2001
From: Eric Duminil <eric.duminil@gmail.com>
Date: Sat, 24 Apr 2021 20:52:00 +0200
Subject: [PATCH] co2_sensor: Allow to change state by CO2 level

---
 ampel-firmware/co2_sensor.cpp | 41 ++++++++++++++++++++---------------
 1 file changed, 23 insertions(+), 18 deletions(-)

diff --git a/ampel-firmware/co2_sensor.cpp b/ampel-firmware/co2_sensor.cpp
index f17e0f7..b573c4b 100644
--- a/ampel-firmware/co2_sensor.cpp
+++ b/ampel-firmware/co2_sensor.cpp
@@ -183,6 +183,27 @@ namespace sensor {
     current_state = new_state;
   }
 
+  void switchStateForCurrentPPM() {
+    if (co2 == 0) {
+      // NOTE: Data is available, but it's sometimes erroneous: the sensor outputs
+      // zero ppm but non-zero temperature and non-zero humidity.
+      Serial.println(F("Invalid sensor data - CO2 concentration supposedly 0 ppm"));
+      switchState(BOOTUP);
+    } else if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) {
+      // Check for pre-calibration states first, because we do not want to
+      // leave them before calibration is done.
+      bool ready_for_calibration = countStableMeasurements();
+      if (ready_for_calibration) {
+        calibrateAndRestart();
+      }
+    } else if (co2 < 250) {
+      // Sensor should be calibrated.
+      switchState(NEEDS_CALIBRATION);
+    } else {
+      switchState(READY);
+    }
+  }
+
   void displayCO2OnLedRing() {
     /**
      * Display data, even if it's "old" (with breathing).
@@ -235,24 +256,7 @@ namespace sensor {
       temperature = scd30.getTemperature();
       humidity = scd30.getHumidity();
 
-      if (co2 == 0) {
-        // NOTE: Data is available, but it's sometimes erroneous: the sensor outputs
-        // zero ppm but non-zero temperature and non-zero humidity.
-        Serial.println(F("Invalid sensor data - CO2 concentration supposedly 0 ppm"));
-        switchState(BOOTUP);
-      } else if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) {
-        // Check for pre-calibration states first, because we do not want to
-        // leave them before calibration is done.
-        bool ready_for_calibration = countStableMeasurements();
-        if (ready_for_calibration) {
-          calibrateAndRestart();
-        }
-      } else if (co2 < 250) {
-        // Sensor should be calibrated.
-        switchState(NEEDS_CALIBRATION);
-      } else {
-        switchState(READY);
-      }
+      switchStateForCurrentPPM();
 
       // Log every time fresh data is available.
       logToSerial();
@@ -270,6 +274,7 @@ namespace sensor {
     Serial.print(F("DEBUG. Setting CO2 to "));
     co2 = fakeCo2;
     Serial.println(co2);
+    switchStateForCurrentPPM();
   }
 
   void setAutoCalibration(int32_t autoCalibration) {
-- 
GitLab