co2_sensor.cpp 9.81 KB
Newer Older
1
2
#include "co2_sensor.h"

Eric Duminil's avatar
Eric Duminil committed
3
#include "web_config.h"
Eric Duminil's avatar
Eric Duminil committed
4
#include "ntp.h"
5
6
7
8
#include "led_effects.h"
#include "sensor_console.h"
#include <Wire.h>

Eric Duminil's avatar
Eric Duminil committed
9
#include "src/lib/S8_UART/s8_uart.h"
Eric Duminil's avatar
Eric Duminil committed
10

11
namespace config {
12
  const uint16_t measurement_timestep_bootup = 5; // [s] Measurement timestep during acclimatization.
13
  const uint8_t max_deviation_during_bootup = 20; // [%]
14
15
16
  const int8_t max_deviation_during_calibration = 30; // [ppm]
  const int16_t timestep_during_calibration = 10; // [s] WARNING: Measurements can be unreliable for timesteps shorter than 10s.
  const int8_t stable_measurements_before_calibration = 120 / timestep_during_calibration; // [-] Stable measurements during at least 2 minutes.
17
  const uint16_t co2_alert_threshold = 2000; // [ppm] Display a flashing led ring, if concentration exceeds this value
18
  const bool debug_sensor_states = false; // If true, log state transitions over serial console
19
20
21
}

namespace sensor {
Eric Duminil's avatar
Eric Duminil committed
22
23
  S8_UART *sensor_S8;
  S8_sensor sensor;
24
  uint16_t co2 = 0;
25
26
  float temperature = 0;
  float humidity = 0;
27
  char timestamp[23];
28
  int16_t stable_measurements = 0;
Käppler's avatar
Käppler committed
29
30
31

  /**
   * Define sensor states
32
   * BOOTUP -> initial state, until first >0 ppm values are returned
Käppler's avatar
Käppler committed
33
   * READY -> sensor does output valid information (> 0 ppm) and no other condition takes place
Eric Duminil's avatar
Eric Duminil committed
34
   * NEEDS_CALIBRATION -> sensor measurements are too low (< 250 ppm)
35
36
   * PREPARE_CALIBRATION_UNSTABLE -> forced calibration was initiated, last measurements were too far apart
   * PREPARE_CALIBRATION_STABLE -> forced calibration was initiated, last measurements were close to each others
Käppler's avatar
Käppler committed
37
   */
38
39
40
  enum state {
    BOOTUP,
    READY,
41
    NEEDS_CALIBRATION,
42
    PREPARE_CALIBRATION_UNSTABLE,
43
    PREPARE_CALIBRATION_STABLE
Käppler's avatar
Käppler committed
44
  };
45
46
47
  const char *state_names[] = {
      "BOOTUP",
      "READY",
48
      "NEEDS_CALIBRATION",
49
      "PREPARE_CALIBRATION_UNSTABLE",
50
      "PREPARE_CALIBRATION_STABLE" };
51
52

  state current_state = BOOTUP;
Käppler's avatar
Käppler committed
53
  void switchState(state);
Eric Duminil's avatar
Eric Duminil committed
54
55
56
57
  void setCO2forDebugging(int32_t fakeCo2);
  void calibrateSensorToSpecificPPM(int32_t calibrationLevel);
  void calibrateSensorRightNow(int32_t calibrationLevel);
  void setAutoCalibration(int32_t autoCalibration);
Käppler's avatar
Käppler committed
58

59
60
  void initialize() {
#if defined(ESP8266)
61
    Wire.begin(12, 14); // ESP8266 - D6, D5;
62
63
#endif
#if defined(ESP32)
Eric Duminil's avatar
Eric Duminil committed
64
    // For ESP32 : RX on GPIO17, TX on GPIO16
Eric Duminil's avatar
Eric Duminil committed
65
#   define S8_UART_PORT  2
Eric Duminil's avatar
Eric Duminil committed
66
    HardwareSerial S8_serial(S8_UART_PORT);
Eric Duminil's avatar
Eric Duminil committed
67
68
    S8_serial.begin(S8_BAUDRATE);
    sensor_S8 = new S8_UART(S8_serial);
69
#endif
70
    Serial.println();
71

Eric Duminil's avatar
Eric Duminil committed
72
73
74
75
76
    // Check if S8 is available
    sensor_S8->get_firmware_version(sensor.firm_version);
    int len = strlen(sensor.firm_version);
    if (len == 0) {
      Serial.println(F("ERROR - Senseair S8 CO2 sensor not detected. Please check wiring!"));
Eric Duminil's avatar
Eric Duminil committed
77
78
      led_effects::showKITTWheel(color::red, 30);
      ESP.restart();
79
80
    }

Eric Duminil's avatar
Eric Duminil committed
81
82
83
84
85
86
87
88
89
90
    // Show basic S8 sensor info
    Serial.println(">>> SenseAir S8 NDIR CO2 sensor <<<");
    printf("Firmware version: %s\n", sensor.firm_version);
    sensor.sensor_id = sensor_S8->get_sensor_ID();
    Serial.print("Sensor ID: 0x");
    printIntToHex(sensor.sensor_id, 4);
    Serial.println("");

    Serial.println("Setup done!");
    Serial.flush();
91

92
    Serial.print(F("Auto-calibration is "));
93
    Serial.println(config::auto_calibrate_sensor ? "ON." : "OFF.");
94

Eric Duminil's avatar
Eric Duminil committed
95
    sensor_console::defineIntCommand("co2", setCO2forDebugging, F("1500 (Sets co2 level, for debugging)"));
Eric Duminil's avatar
Eric Duminil committed
96
97
98
99
100
101
102
103
//    sensor_console::defineIntCommand("timer", setTimer, F("30 (Sets measurement interval, in s)"));
//    sensor_console::defineCommand("calibrate", startCalibrationProcess, F("(Starts calibration process)"));
//    sensor_console::defineIntCommand("calibrate", calibrateSensorToSpecificPPM,
//        F("600 (Starts calibration process, to given ppm)"));
//    sensor_console::defineIntCommand("calibrate!", calibrateSensorRightNow,
//        F("600 (Calibrates right now, to given ppm)"));
//    sensor_console::defineIntCommand("auto_calibrate", setAutoCalibration, F("0/1 (Disables/enables autocalibration)"));
//    sensor_console::defineCommand("reset_scd", resetSCD, F("(Resets SCD30)"));
104
105
  }

106
107
108
109
110
111
112
  bool hasSensorSettled() {
    static uint16_t last_co2 = 0;
    uint16_t delta;
    delta = abs(co2 - last_co2);
    last_co2 = co2;
    // We assume the sensor has acclimated to the environment if measurements
    // change less than a specified percentage of the current value.
Eric Duminil's avatar
Eric Duminil committed
113
    return (co2 > 0 && delta < ((uint32_t) co2 * config::max_deviation_during_bootup / 100));
114
115
  }

Eric Duminil's avatar
Eric Duminil committed
116
  bool enoughStableMeasurements() {
Eric Duminil's avatar
Eric Duminil committed
117
    static int16_t previous_co2 = 0;
Eric Duminil's avatar
Eric Duminil committed
118
119
    if (co2 > (previous_co2 - config::max_deviation_during_calibration)
        && co2 < (previous_co2 + config::max_deviation_during_calibration)) {
120
      stable_measurements++;
Eric Duminil's avatar
Eric Duminil committed
121
      Serial.print(F("Number of stable measurements : "));
122
123
124
      Serial.print(stable_measurements);
      Serial.print(F(" / "));
      Serial.println(config::stable_measurements_before_calibration);
125
      switchState(PREPARE_CALIBRATION_STABLE);
126
127
    } else {
      stable_measurements = 0;
128
      switchState(PREPARE_CALIBRATION_UNSTABLE);
129
    }
Eric Duminil's avatar
Eric Duminil committed
130
    previous_co2 = co2;
131
    return (stable_measurements == config::stable_measurements_before_calibration);
132
133
134
  }

  void startCalibrationProcess() {
Eric Duminil's avatar
Eric Duminil committed
135
    Serial.println(F("Implement ME!"));
136
137
  }

138
  void calibrate() {
Eric Duminil's avatar
Eric Duminil committed
139
    Serial.println(F("Implement ME!"));
140
  }
141

142
  void logToSerial() {
Eric Duminil's avatar
Eric Duminil committed
143
144
    Serial.print(timestamp);
    Serial.print(F(" - co2(ppm): "));
145
146
    Serial.print(co2);
    Serial.print(F(" temp(C): "));
147
    Serial.print(temperature, 1);
148
    Serial.print(F(" humidity(%): "));
149
    Serial.println(humidity, 1);
150
151
  }

Käppler's avatar
Käppler committed
152
  void switchState(state new_state) {
153
154
155
    if (new_state == current_state) {
      return;
    }
156
157
158
    if (config::debug_sensor_states) {
      Serial.print(F("Changing sensor state: "));
      Serial.print(state_names[current_state]);
Eric Duminil's avatar
Eric Duminil committed
159
      Serial.print(F(" -> "));
160
161
      Serial.println(state_names[new_state]);
    }
Käppler's avatar
Käppler committed
162
163
164
    current_state = new_state;
  }

165
  void switchStateForCurrentPPM() {
166
    if (current_state == BOOTUP) {
Eric Duminil's avatar
Eric Duminil committed
167
168
169
      if (!hasSensorSettled()) {
        return;
      }
170
171
172
      switchState(READY);
      Serial.println(F("Sensor acclimatization finished."));
    }
Eric Duminil's avatar
Eric Duminil committed
173
174
175

    // Check for pre-calibration states first, because we do not want to
    // leave them before calibration is done.
Käppler's avatar
Käppler committed
176
    if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) {
Eric Duminil's avatar
Eric Duminil committed
177
      if (enoughStableMeasurements()) {
178
        calibrate();
179
180
181
182
183
184
185
186
187
      }
    } else if (co2 < 250) {
      // Sensor should be calibrated.
      switchState(NEEDS_CALIBRATION);
    } else {
      switchState(READY);
    }
  }

188
189
190
  void displayCO2OnLedRing() {
    /**
     * Display data, even if it's "old" (with breathing).
Eric Duminil's avatar
Eric Duminil committed
191
     * A short delay is required in order to let background tasks run on the ESP8266.
192
     * see https://github.com/esp8266/Arduino/issues/3241#issuecomment-301290392
193
     */
194
    if (co2 < config::co2_alert_threshold) {
195
      led_effects::displayCO2color(co2);
196
      delay(100);
197
    } else {
198
      // Display a flashing led ring, if concentration exceeds a specific value
199
      led_effects::alert(color::red);
200
201
202
    }
  }

203
  void showState() {
204
205
206
207
208
    switch (current_state) {
    case BOOTUP:
      led_effects::showWaitingLED(color::blue);
      break;
    case READY:
209
      displayCO2OnLedRing();
210
      break;
211
    case NEEDS_CALIBRATION:
212
213
      led_effects::showWaitingLED(color::magenta);
      break;
214
    case PREPARE_CALIBRATION_UNSTABLE:
215
216
      led_effects::showWaitingLED(color::red);
      break;
217
    case PREPARE_CALIBRATION_STABLE:
218
219
220
      led_effects::showWaitingLED(color::green);
      break;
    default:
Eric Duminil's avatar
Eric Duminil committed
221
      Serial.println(F("Encountered unknown sensor state")); // This should not happen.
222
223
224
    }
  }

Eric Duminil's avatar
Eric Duminil committed
225
  /** Gets fresh data if available, checks calibration status, displays CO2 levels.
226
   * Returns true if fresh data is available, for further processing (e.g. MQTT, CSV or LoRa)
Eric Duminil's avatar
Eric Duminil committed
227
228
   */
  bool processData() {
Eric Duminil's avatar
Eric Duminil committed
229
230
231
    static unsigned long last_measurement = 0;
    unsigned long now = seconds();
    bool freshData = now - last_measurement > config::measurement_timestep;
Eric Duminil's avatar
Eric Duminil committed
232
    if (freshData) {
Eric Duminil's avatar
Eric Duminil committed
233
      last_measurement = now;
234
      ntp::getLocalTime(timestamp);
Eric Duminil's avatar
Eric Duminil committed
235
236
237
      co2 = sensor_S8->get_co2();
      temperature = 0.0;
      humidity = 0.0;
238

239
      switchStateForCurrentPPM();
240

241
242
      // Log every time fresh data is available.
      logToSerial();
243
244
    }

245
    showState();
246

247
248
249
    // Report data for further processing only if the data is reliable
    // (state 'READY') or manual calibration is necessary (state 'NEEDS_CALIBRATION').
    return freshData && (current_state == READY || current_state == NEEDS_CALIBRATION);
250
  }
251

Eric Duminil's avatar
Eric Duminil committed
252
  float getTemperatureOffset() {
Eric Duminil's avatar
Eric Duminil committed
253
    return 0.0;
Eric Duminil's avatar
Eric Duminil committed
254
255
  }

256
257
258
259
260
261
262
  /*****************************************************************
   * Callbacks for sensor commands                                 *
   *****************************************************************/
  void setCO2forDebugging(int32_t fakeCo2) {
    Serial.print(F("DEBUG. Setting CO2 to "));
    co2 = fakeCo2;
    Serial.println(co2);
263
    switchStateForCurrentPPM();
264
265
  }

266
  void setAutoCalibration(int32_t autoCalibration) {
Eric Duminil's avatar
Eric Duminil committed
267
    Serial.println(F("Implement ME!"));
268
269
  }

270
  void setTimer(int32_t timestep) {
Eric Duminil's avatar
Eric Duminil committed
271
    Serial.println(F("Implement ME!"));
272
273
274
275
276
  }

  void calibrateSensorToSpecificPPM(int32_t calibrationLevel) {
    if (calibrationLevel >= 400 && calibrationLevel <= 2000) {
      Serial.print(F("Force calibration, at "));
277
278
      config::co2_calibration_level = calibrationLevel;
      Serial.print(config::co2_calibration_level);
Eric Duminil's avatar
Eric Duminil committed
279
      Serial.println(F(" ppm."));
Eric Duminil's avatar
Eric Duminil committed
280
      startCalibrationProcess();
281
282
283
284
    }
  }

  void calibrateSensorRightNow(int32_t calibrationLevel) {
Eric Duminil's avatar
Eric Duminil committed
285
286
    if (calibrationLevel >= 400 && calibrationLevel <= 2000) {
      Serial.print(F("Force calibration, right now, at "));
287
288
      config::co2_calibration_level = calibrationLevel;
      Serial.print(config::co2_calibration_level);
Eric Duminil's avatar
Eric Duminil committed
289
      Serial.println(F(" ppm."));
290
      calibrate();
Eric Duminil's avatar
Eric Duminil committed
291
    }
292
  }
293
294

  void resetSCD() {
Eric Duminil's avatar
Eric Duminil committed
295
    Serial.println(F("Implement ME!"));
296
  }
297
}