co2_sensor.cpp 10.1 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
#include "led_effects.h"
#include "sensor_console.h"

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

10
namespace config {
Eric Duminil's avatar
Eric Duminil committed
11
  const uint16_t measurement_timestep_bootup = 4; // [s] Measurement timestep during acclimatization.
12
  const uint8_t max_deviation_during_bootup = 20; // [%]
13
14
15
  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.
16
  const uint16_t co2_alert_threshold = 2000; // [ppm] Display a flashing led ring, if concentration exceeds this value
17
  const bool debug_sensor_states = false; // If true, log state transitions over serial console
18
19
}

Eric Duminil's avatar
Eric Duminil committed
20
#if defined(ESP8266)
Eric Duminil's avatar
Eric Duminil committed
21
#  include "src/lib/Esp8266EdgeSoftwareSerial/MySoftwareSerial.h"
22
23
#  define S8_RX_PIN 13         // GPIO13, a.k.a. D7, connected to S8 Tx pin.
#  define S8_TX_PIN 15         // GPIO15, a.k.a. D8, connected to S8 Rx pin.
Eric Duminil's avatar
Eric Duminil committed
24
MySoftwareSerial S8_serial(S8_RX_PIN, S8_TX_PIN);
Eric Duminil's avatar
Eric Duminil committed
25
26
#endif
#if defined(ESP32)
27
28
29
30
// GPIO16 connected to S8 Tx pin.
// GPIO17 connected to S8 Rx pin.
#  define S8_UART_PORT  2
HardwareSerial S8_serial(S8_UART_PORT);
31
#endif
Eric Duminil's avatar
Eric Duminil committed
32

33
namespace sensor {
Eric Duminil's avatar
Eric Duminil committed
34
  S8_UART *sensor_S8;
Eric Duminil's avatar
Eric Duminil committed
35
  S8_sensor s8;
36
  uint16_t co2 = 0;
37
38
  float temperature = 0;
  float humidity = 0;
39
  char timestamp[23];
40
  int16_t stable_measurements = 0;
Eric Duminil's avatar
Eric Duminil committed
41
42
  // I'm not sure it's possible to change S8 measurement interval (constant 4s). But we can check every check_timestep seconds.
  uint16_t check_timestep = 0;
Käppler's avatar
Käppler committed
43
44
45

  /**
   * Define sensor states
46
   * BOOTUP -> initial state, until first >0 ppm values are returned
Käppler's avatar
Käppler committed
47
   * READY -> sensor does output valid information (> 0 ppm) and no other condition takes place
Eric Duminil's avatar
Eric Duminil committed
48
   * NEEDS_CALIBRATION -> sensor measurements are too low (< 250 ppm)
49
50
   * 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
51
   */
52
53
54
  enum state {
    BOOTUP,
    READY,
55
    NEEDS_CALIBRATION,
56
    PREPARE_CALIBRATION_UNSTABLE,
57
    PREPARE_CALIBRATION_STABLE
Käppler's avatar
Käppler committed
58
  };
59
60
61
  const char *state_names[] = {
      "BOOTUP",
      "READY",
62
      "NEEDS_CALIBRATION",
63
      "PREPARE_CALIBRATION_UNSTABLE",
64
      "PREPARE_CALIBRATION_STABLE" };
65

Eric Duminil's avatar
Eric Duminil committed
66
  state current_state = BOOTUP;
Käppler's avatar
Käppler committed
67
  void switchState(state);
Eric Duminil's avatar
Eric Duminil committed
68
69
70
71
  void setCO2forDebugging(int32_t fakeCo2);
  void calibrateSensorToSpecificPPM(int32_t calibrationLevel);
  void calibrateSensorRightNow(int32_t calibrationLevel);
  void setAutoCalibration(int32_t autoCalibration);
Eric Duminil's avatar
Eric Duminil committed
72
  void setTimer(int32_t timestep);
Käppler's avatar
Käppler committed
73

74
  void initialize() {
Eric Duminil's avatar
Eric Duminil committed
75
    Serial.println(F("Sensor   : Senseair S8"));
Eric Duminil's avatar
Eric Duminil committed
76
77
    S8_serial.begin(S8_BAUDRATE);
    sensor_S8 = new S8_UART(S8_serial);
78
    Serial.println();
79

Eric Duminil's avatar
Eric Duminil committed
80
    // Check if S8 is available
Eric Duminil's avatar
Eric Duminil committed
81
82
    sensor_S8->get_firmware_version(s8.firm_version);
    int len = strlen(s8.firm_version);
Eric Duminil's avatar
Eric Duminil committed
83
84
    if (len == 0) {
      Serial.println(F("ERROR - Senseair S8 CO2 sensor not detected. Please check wiring!"));
Eric Duminil's avatar
Eric Duminil committed
85
86
      led_effects::showKITTWheel(color::red, 30);
      ESP.restart();
87
88
    }

Eric Duminil's avatar
Eric Duminil committed
89
    // Show basic S8 sensor info
Eric Duminil's avatar
Eric Duminil committed
90
91
    Serial.print(F("S8 - Firmware : "));
    Serial.println(s8.firm_version);
Eric Duminil's avatar
Eric Duminil committed
92
    s8.sensor_id = sensor_S8->get_sensor_ID();
Eric Duminil's avatar
Eric Duminil committed
93
    Serial.print(F("S8 - ID : 0x"));
Eric Duminil's avatar
Eric Duminil committed
94
    printIntToHex(s8.sensor_id, 4);
Eric Duminil's avatar
Eric Duminil committed
95
    Serial.println();
Eric Duminil's avatar
Eric Duminil committed
96

Eric Duminil's avatar
Eric Duminil committed
97
    //TODO: Auto-calibration on/off?
98

Eric Duminil's avatar
Eric Duminil committed
99
100
101
102
103
104
105
    // S8 has its own timer (constant 4s)
    Serial.println();
    Serial.print(F("Setting S8 timestep to "));
    Serial.print(config::measurement_timestep_bootup);
    Serial.println(F(" s during acclimatization."));
    check_timestep = config::measurement_timestep_bootup;

Eric Duminil's avatar
Eric Duminil committed
106
    sensor_console::defineIntCommand("co2", setCO2forDebugging, F("1500 (Sets co2 level, for debugging)"));
Eric Duminil's avatar
Eric Duminil committed
107
    sensor_console::defineIntCommand("timer", setTimer, F("30 (Sets measurement interval, in s)"));
Eric Duminil's avatar
Eric Duminil committed
108
109
110
111
112
113
//    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)"));
114
115
  }

116
117
118
119
120
121
122
  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
123
    return (co2 > 0 && delta < ((uint32_t) co2 * config::max_deviation_during_bootup / 100));
124
125
  }

Eric Duminil's avatar
Eric Duminil committed
126
  bool enoughStableMeasurements() {
Eric Duminil's avatar
Eric Duminil committed
127
    static int16_t previous_co2 = 0;
Eric Duminil's avatar
Eric Duminil committed
128
129
    if (co2 > (previous_co2 - config::max_deviation_during_calibration)
        && co2 < (previous_co2 + config::max_deviation_during_calibration)) {
130
      stable_measurements++;
Eric Duminil's avatar
Eric Duminil committed
131
      Serial.print(F("Number of stable measurements : "));
132
133
134
      Serial.print(stable_measurements);
      Serial.print(F(" / "));
      Serial.println(config::stable_measurements_before_calibration);
135
      switchState(PREPARE_CALIBRATION_STABLE);
136
137
    } else {
      stable_measurements = 0;
138
      switchState(PREPARE_CALIBRATION_UNSTABLE);
139
    }
Eric Duminil's avatar
Eric Duminil committed
140
    previous_co2 = co2;
141
    return (stable_measurements == config::stable_measurements_before_calibration);
142
143
144
  }

  void startCalibrationProcess() {
Eric Duminil's avatar
Eric Duminil committed
145
    Serial.println(F("Implement ME!"));
146
147
  }

148
  void calibrate() {
Eric Duminil's avatar
Eric Duminil committed
149
    Serial.println(F("Implement ME!"));
150
  }
151

152
  void logToSerial() {
Eric Duminil's avatar
Eric Duminil committed
153
154
    Serial.print(timestamp);
    Serial.print(F(" - co2(ppm): "));
155
    Serial.print(co2);
Eric Duminil's avatar
Eric Duminil committed
156
    Serial.println(F(" temp(C): ? humidity(%): ?"));
157
158
  }

Käppler's avatar
Käppler committed
159
  void switchState(state new_state) {
160
161
162
    if (new_state == current_state) {
      return;
    }
163
164
165
    if (config::debug_sensor_states) {
      Serial.print(F("Changing sensor state: "));
      Serial.print(state_names[current_state]);
Eric Duminil's avatar
Eric Duminil committed
166
      Serial.print(F(" -> "));
167
168
      Serial.println(state_names[new_state]);
    }
Käppler's avatar
Käppler committed
169
170
171
    current_state = new_state;
  }

172
  void switchStateForCurrentPPM() {
173
    if (current_state == BOOTUP) {
Eric Duminil's avatar
Eric Duminil committed
174
175
176
      if (!hasSensorSettled()) {
        return;
      }
177
178
      switchState(READY);
      Serial.println(F("Sensor acclimatization finished."));
Eric Duminil's avatar
Eric Duminil committed
179
180
181
182
      Serial.print(F("Setting S8 timestep to "));
      Serial.print(config::measurement_timestep);
      Serial.println(F(" s."));
      check_timestep = config::measurement_timestep; // [s]
183
    }
Eric Duminil's avatar
Eric Duminil committed
184
185
186

    // 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
187
    if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) {
Eric Duminil's avatar
Eric Duminil committed
188
      if (enoughStableMeasurements()) {
189
        calibrate();
190
191
192
193
194
195
196
197
198
      }
    } else if (co2 < 250) {
      // Sensor should be calibrated.
      switchState(NEEDS_CALIBRATION);
    } else {
      switchState(READY);
    }
  }

199
200
201
  void displayCO2OnLedRing() {
    /**
     * Display data, even if it's "old" (with breathing).
Eric Duminil's avatar
Eric Duminil committed
202
     * A short delay is required in order to let background tasks run on the ESP8266.
203
     * see https://github.com/esp8266/Arduino/issues/3241#issuecomment-301290392
204
     */
205
    if (co2 < config::co2_alert_threshold) {
206
      led_effects::displayCO2color(co2);
207
      delay(100);
208
    } else {
209
      // Display a flashing led ring, if concentration exceeds a specific value
210
      led_effects::alert(color::red);
211
212
213
    }
  }

214
  void showState() {
215
216
217
218
219
    switch (current_state) {
    case BOOTUP:
      led_effects::showWaitingLED(color::blue);
      break;
    case READY:
220
      displayCO2OnLedRing();
221
      break;
222
    case NEEDS_CALIBRATION:
223
224
      led_effects::showWaitingLED(color::magenta);
      break;
225
    case PREPARE_CALIBRATION_UNSTABLE:
226
227
      led_effects::showWaitingLED(color::red);
      break;
228
    case PREPARE_CALIBRATION_STABLE:
229
230
231
      led_effects::showWaitingLED(color::green);
      break;
    default:
Eric Duminil's avatar
Eric Duminil committed
232
      Serial.println(F("Encountered unknown sensor state")); // This should not happen.
233
234
235
    }
  }

Eric Duminil's avatar
Eric Duminil committed
236
  /** Gets fresh data if available, checks calibration status, displays CO2 levels.
237
   * Returns true if fresh data is available, for further processing (e.g. MQTT, CSV or LoRa)
Eric Duminil's avatar
Eric Duminil committed
238
239
   */
  bool processData() {
Eric Duminil's avatar
Eric Duminil committed
240
241
    static unsigned long last_measurement = 0;
    unsigned long now = seconds();
Eric Duminil's avatar
Eric Duminil committed
242
    bool freshData = now - last_measurement > check_timestep;
Eric Duminil's avatar
Eric Duminil committed
243
    if (freshData) {
Eric Duminil's avatar
Eric Duminil committed
244
      last_measurement = now;
245
      ntp::getLocalTime(timestamp);
Eric Duminil's avatar
Eric Duminil committed
246
      co2 = sensor_S8->get_co2();
Eric Duminil's avatar
Eric Duminil committed
247
      //TODO: Check if there's really no temperature info available.
Eric Duminil's avatar
Eric Duminil committed
248
249
      temperature = 0.0;
      humidity = 0.0;
250

251
      switchStateForCurrentPPM();
252

253
254
      // Log every time fresh data is available.
      logToSerial();
255
256
    }

257
    showState();
258

259
260
261
    // 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);
262
  }
263

Eric Duminil's avatar
Eric Duminil committed
264
  float getTemperatureOffset() {
Eric Duminil's avatar
Eric Duminil committed
265
    return 0.0;
Eric Duminil's avatar
Eric Duminil committed
266
267
  }

268
269
270
271
272
273
274
  /*****************************************************************
   * Callbacks for sensor commands                                 *
   *****************************************************************/
  void setCO2forDebugging(int32_t fakeCo2) {
    Serial.print(F("DEBUG. Setting CO2 to "));
    co2 = fakeCo2;
    Serial.println(co2);
275
    switchStateForCurrentPPM();
276
277
  }

278
  void setAutoCalibration(int32_t autoCalibration) {
Eric Duminil's avatar
Eric Duminil committed
279
    Serial.println(F("TODO: Implement ME!"));
280
281
  }

282
  void setTimer(int32_t timestep) {
Eric Duminil's avatar
Eric Duminil committed
283
284
285
286
287
288
289
290
    if (timestep >= 4) {
      Serial.print(F("Setting Measurement Interval to : "));
      Serial.print(timestep);
      Serial.println(F("s."));
      check_timestep = timestep;
      config::measurement_timestep = timestep;
      led_effects::showKITTWheel(color::green, 1);
    }
291
292
293
  }

  void calibrateSensorToSpecificPPM(int32_t calibrationLevel) {
Eric Duminil's avatar
Eric Duminil committed
294
    Serial.println(F("TODO: Implement ME!"));
295
296
297
  }

  void calibrateSensorRightNow(int32_t calibrationLevel) {
Eric Duminil's avatar
Eric Duminil committed
298
    Serial.println(F("TODO: Implement ME!"));
299
  }
300
}