Commit 983003b4 authored by Eric Duminil's avatar Eric Duminil
Browse files

Merge branch 'develop'

parents a200c6f8 86309b4a
......@@ -6,6 +6,18 @@ It measures the current CO<sub>2</sub> concentration (in ppm), and displays it o
The room should be ventilated as soon as one LED turns red.
## Features
The *CO<sub>2</sub> Ampel* can:
* Display CO2 concentration on LED ring.
* Allow calibration.
* Get current time over NTP
* Send data over MQTT.
* Send data over LoRaWAN.
* Display measurements and configuration on a small website.
* Log data to a CSV file, directly on the ESP flash memory.
## Hardware Requirements
* [ESP8266](https://en.wikipedia.org/wiki/ESP8266) or [ESP32](https://en.wikipedia.org/wiki/ESP32) microcontroller (this project has been tested with *ESP8266 ESP-12 WIFI* and *TTGO ESP32 SX1276 LoRa*)
......
......@@ -5,25 +5,33 @@
*****************************************************************/
#include "config.h"
#ifndef MEASUREMENT_TIMESTEP
# error Missing config.h file. Please copy config.example.h to config.h.
# error Missing config.h file. Please copy config.public.h to config.h.
#endif
#ifdef MQTT
# include "mqtt.h"
#ifdef AMPEL_CSV
# include "csv_writer.h"
#endif
#include "util.h"
#include "wifi_util.h"
#include "co2_sensor.h"
#ifdef AMPEL_WIFI
# include "wifi_util.h"
# ifdef AMPEL_MQTT
# include "mqtt.h"
# endif
# ifdef AMPEL_HTTP
# include "web_server.h"
# endif
#endif
#ifdef HTTP
# include "web_server.h"
#ifdef AMPEL_LORAWAN
# include "lorawan.h"
#endif
#include "util.h"
#include "co2_sensor.h"
#include "led_effects.h"
#include "csv_writer.h"
#if defined(ESP8266)
//allows sensor to be seen as SENSOR_ID.local, from the local network. For example : espd05cc9.local
//allows sensor to be seen as SENSOR_ID.local, from the local network. For example : espd03cc5.local
# include <ESP8266mDNS.h>
#elif defined(ESP32)
# include <ESPmDNS.h>
......
......@@ -59,14 +59,14 @@
* Setup *
*****************************************************************/
void setup() {
LedEffects::setupOnBoardLED();
LedEffects::onBoardLEDOff();
led_effects::setupOnBoardLED();
led_effects::onBoardLEDOff();
Serial.begin(BAUDS);
pinMode(0, INPUT); // Flash button (used for forced calibration)
pinMode(0, INPUT); // Flash button (used for forced calibration)
LedEffects::setupRing();
led_effects::setupRing();
sensor::initialize();
......@@ -75,6 +75,7 @@ void setup() {
Serial.print(F("Board : "));
Serial.println(BOARD);
#ifdef AMPEL_WIFI
// Try to connect to Wi-Fi
WiFiConnect(SENSOR_ID);
......@@ -82,9 +83,9 @@ void setup() {
Serial.println(WiFi.status());
if (WiFi.status() == WL_CONNECTED) {
#ifdef HTTP
# ifdef AMPEL_HTTP
web_server::initialize();
#endif
# endif
ntp::initialize();
......@@ -95,11 +96,19 @@ void setup() {
Serial.println(F("Error setting up MDNS responder!"));
}
#ifdef MQTT
# ifdef AMPEL_MQTT
mqtt::initialize("CO2sensors/" + SENSOR_ID);
#endif
# endif
}
#endif
#ifdef AMPEL_CSV
csv_writer::initialize();
#endif
#if defined(AMPEL_LORAWAN) && defined(ESP32)
lorawan::initialize();
#endif
}
/*****************************************************************
......@@ -107,73 +116,36 @@ void setup() {
*****************************************************************/
void loop() {
#if defined(AMPEL_LORAWAN) && defined(ESP32)
//LMIC Library seems to be very sensitive to timing issues, so run it first.
lorawan::process();
if (lorawan::waiting_for_confirmation) {
// If node is waiting for join confirmation from Gateway, nothing else should run.
return;
}
#endif
//NOTE: Loop should never take more than 1000ms. Split in smaller methods and logic if needed.
//TODO: Restart every day or week, in order to not let t0 overflow?
uint32_t t0 = millis();
/**
* USER INTERACTION
*/
keepServicesAlive();
// Short press for night mode, Long press for calibration.
checkFlashButton();
/**
* GET DATA
*/
bool freshData = sensor::scd30.dataAvailable(); // Alternative : close to time-step AND dataAvailable, to avoid asking the sensor too often.
if (freshData) {
sensor::co2 = sensor::scd30.getCO2();
sensor::temperature = sensor::scd30.getTemperature();
sensor::humidity = sensor::scd30.getHumidity();
}
//NOTE: Data is available, but it's sometimes erroneous: the sensor outputs zero ppm but non-zero temperature and non-zero humidity.
if (sensor::co2 <= 0) {
// No measurement yet. Waiting.
LedEffects::showWaitingLED(color::blue);
return;
}
/**
* Fresh data. Show it and send it if needed.
*/
if (freshData) {
sensor::timestamp = ntp::getLocalTime();
Serial.println(sensor::timestamp);
Serial.print(F("co2(ppm): "));
Serial.print(sensor::co2);
Serial.print(F(" temp(C): "));
Serial.print(sensor::temperature);
Serial.print(F(" humidity(%): "));
Serial.println(sensor::humidity);
if (sensor::processData()) {
#ifdef AMPEL_CSV
csv_writer::logIfTimeHasCome(sensor::timestamp, sensor::co2, sensor::temperature, sensor::humidity);
#endif
#ifdef MQTT
#if defined(AMPEL_WIFI) && defined(AMPEL_MQTT)
mqtt::publishIfTimeHasCome(sensor::timestamp, sensor::co2, sensor::temperature, sensor::humidity);
#endif
}
if (sensor::co2 < 250) {
// Sensor should be calibrated.
LedEffects::showWaitingLED(color::magenta);
return;
}
/**
* Display data, even if it's "old" (with breathing).
* Those effects include a short delay.
*/
if (sensor::co2 < 2000) {
LedEffects::displayCO2color(sensor::co2);
LedEffects::breathe(sensor::co2);
} else { // >= 2000: entire ring blinks red
LedEffects::redAlert();
#if defined(AMPEL_LORAWAN) && defined(ESP32)
lorawan::preparePayloadIfTimeHasCome(sensor::co2, sensor::temperature, sensor::humidity);
#endif
}
uint32_t duration = millis() - t0;
......@@ -193,34 +165,36 @@ void loop() {
*/
void checkFlashButton() {
if (!digitalRead(0)) { // Button has been pressed
LedEffects::onBoardLEDOn();
led_effects::onBoardLEDOn();
delay(300);
if (digitalRead(0)) {
Serial.println(F("Flash has been pressed for a short time. Should toggle night mode."));
LedEffects::toggleNightMode();
led_effects::toggleNightMode();
} else {
Serial.println(F("Flash has been pressed for a long time. Keep it pressed for calibration."));
if (LedEffects::countdownToZero() < 0) {
if (led_effects::countdownToZero() < 0) {
sensor::startCalibrationProcess();
}
}
LedEffects::onBoardLEDOff();
led_effects::onBoardLEDOff();
}
}
void keepServicesAlive() {
#ifdef AMPEL_WIFI
if (WiFi.status() == WL_CONNECTED) {
#if defined(ESP8266)
# if defined(ESP8266)
//NOTE: Sadly, there seems to be a bug in the current MDNS implementation.
// It stops working after 2 minutes. And forcing a restart leads to a memory leak.
MDNS.update();
#endif
# endif
ntp::update(); // NTP client has its own timer. It will connect to NTP server every 60s.
#ifdef HTTP
# ifdef AMPEL_HTTP
web_server::update();
#endif
#ifdef MQTT
# endif
# ifdef AMPEL_MQTT
mqtt::keepConnection(); // MQTT client has its own timer. It will keep alive every 15s.
#endif
# endif
}
#endif
}
......@@ -2,17 +2,17 @@
namespace config {
// Values should be defined in config.h
uint16_t measurement_timestep = MEASUREMENT_TIMESTEP; // [s] Value between 2 and 1800 (range for SCD30 sensor)
const uint16_t altitude_above_sea_level = ALTITUDE_ABOVE_SEA_LEVEL; // [m]
uint16_t co2_calibration_level = ATMOSPHERIC_CO2_CONCENTRATION; // [ppm]
uint16_t measurement_timestep = MEASUREMENT_TIMESTEP; // [s] Value between 2 and 1800 (range for SCD30 sensor)
const uint16_t altitude_above_sea_level = ALTITUDE_ABOVE_SEA_LEVEL; // [m]
uint16_t co2_calibration_level = ATMOSPHERIC_CO2_CONCENTRATION; // [ppm]
#ifdef TEMPERATURE_OFFSET
// Residual heat from CO2 sensor seems to be high enough to change the temperature reading. How much should it be offset?
// NOTE: Sign isn't relevant. The returned temperature will always be shifted down.
const float temperature_offset = TEMPERATURE_OFFSET; // [K]
const float temperature_offset = TEMPERATURE_OFFSET; // [K]
#else
const float temperature_offset = -3.0; // [K] Temperature measured by sensor is usually at least 3K too high.
#endif
const bool auto_calibrate_sensor = AUTO_CALIBRATE_SENSOR; // [true / false]
const bool auto_calibrate_sensor = AUTO_CALIBRATE_SENSOR; // [true / false]
}
namespace sensor {
......@@ -21,13 +21,16 @@ namespace sensor {
float temperature = 0;
float humidity = 0;
String timestamp = "";
int16_t stable_measurements = 0;
uint32_t waiting_color = color::blue;
bool should_calibrate = false;
void initialize() {
#if defined(ESP8266)
Wire.begin(12, 14); // ESP8266 - D6, D5;
#endif
#if defined(ESP32)
Wire.begin(21, 22); // ESP32
Wire.begin(21, 22); // ESP32
/**
* SCD30 ESP32
* VCC --- 3V3
......@@ -41,46 +44,146 @@ namespace sensor {
if (scd30.begin(config::auto_calibrate_sensor) == false) {
Serial.println("Air sensor not detected. Please check wiring. Freezing...");
while (1) {
LedEffects::showWaitingLED(color::red);
led_effects::showWaitingLED(color::red);
}
}
// SCD30 has its own timer.
Serial.println("\nSetting SCD30 timestep to " + String(config::measurement_timestep) + " s.");
scd30.setMeasurementInterval(config::measurement_timestep); // [s]
//NOTE: The timer seems to be inaccurate, though, possibly depending on voltage. Should it be offset?
Serial.println();
Serial.print(F("Setting SCD30 timestep to "));
Serial.print(config::measurement_timestep);
Serial.println(" s.");
scd30.setMeasurementInterval(config::measurement_timestep); // [s]
Serial.print("Setting temperature offset to -");
Serial.print(F("Setting temperature offset to -"));
Serial.print(abs(config::temperature_offset));
Serial.println(" K.");
scd30.setTemperatureOffset(abs(config::temperature_offset)); // setTemperatureOffset only accepts positive numbers, but shifts the temperature down.
delay(100);
Serial.print("Temperature offset is : -");
Serial.print(F("Temperature offset is : -"));
Serial.print(scd30.getTemperatureOffset());
Serial.println(" K");
Serial.print("Auto-calibration is ");
Serial.print(F("Auto-calibration is "));
Serial.println(config::auto_calibrate_sensor ? "ON." : "OFF.");
}
// Force SCD30 calibration with countdown.
//NOTE: should timer deviation be used to adjust measurement_timestep?
void checkTimerDeviation() {
static int32_t previous_measurement_at = 0;
int32_t now = millis();
Serial.print("Measurement time offset : ");
Serial.print(now - previous_measurement_at - config::measurement_timestep * 1000);
Serial.println(" ms.");
previous_measurement_at = now;
}
void countStableMeasurements() {
static int16_t previous_co2 = 0;
if (co2 > (previous_co2 - 30) && co2 < (previous_co2 + 30)) {
stable_measurements++;
Serial.print(F("Number of stable measurements : "));
Serial.println(stable_measurements);
waiting_color = color::green;
} else {
stable_measurements = 0;
waiting_color = color::red;
}
previous_co2 = co2;
}
void startCalibrationProcess() {
/** From the sensor documentation:
* For best results, the sensor has to be run in a stable environment in continuous mode at
* a measurement rate of 2s for at least two minutes before applying the FRC command and sending the reference value.
*/
Serial.println("Setting SCD30 timestep to 2s, prior to calibration.");
scd30.setMeasurementInterval(2); // [s] The change will only take effect after next measurement.
LedEffects::showKITTWheel(color::blue, config::measurement_timestep);
Serial.println("Waiting 2 minutes.");
LedEffects::showKITTWheel(color::blue, 120);
Serial.print("Starting SCD30 calibration...");
Serial.println(F("Setting SCD30 timestep to 2s, prior to calibration."));
scd30.setMeasurementInterval(2); // [s] The change will only take effect after next measurement.
Serial.println(F("Waiting until the measurements are stable for at least 2 minutes."));
Serial.println(F("It could take a very long time."));
should_calibrate = true;
}
void calibrateAndRestart() {
Serial.print(F("Calibrating SCD30 now..."));
scd30.setAltitudeCompensation(config::altitude_above_sea_level);
scd30.setForcedRecalibrationFactor(config::co2_calibration_level);
Serial.println(" Done!");
Serial.println("Sensor calibrated.");
Serial.println("Sensor will now restart.");
LedEffects::showKITTWheel(color::green, 5);
FS_LIB.end();
ESP.restart();
Serial.println(F(" Done!"));
Serial.println(F("Sensor calibrated."));
ESP.restart(); // softer than ESP.reset
}
void logToSerial() {
Serial.println(timestamp);
Serial.print(F("co2(ppm): "));
Serial.print(co2);
Serial.print(F(" temp(C): "));
Serial.print(temperature, 1);
Serial.print(F(" humidity(%): "));
Serial.println(humidity, 1);
}
void displayCO2OnLedRing() {
if (co2 < 250) {
// Sensor should be calibrated.
led_effects::showWaitingLED(color::magenta);
return;
}
/**
* Display data, even if it's "old" (with breathing).
* Those effects include a short delay.
*/
if (co2 < 2000) {
led_effects::displayCO2color(co2);
led_effects::breathe(co2);
} else {
// >= 2000: entire ring blinks red
led_effects::redAlert();
}
}
/** Gets fresh data if available, checks calibration status, displays CO2 levels.
* Returns true if fresh data is available, for further processing (e.g. MQTT, CSV or LoRa)
*/
bool processData() {
bool freshData = scd30.dataAvailable();
if (freshData) {
// checkTimerDeviation();
timestamp = ntp::getLocalTime();
co2 = scd30.getCO2();
temperature = scd30.getTemperature();
humidity = scd30.getHumidity();
}
//NOTE: Data is available, but it's sometimes erroneous: the sensor outputs zero ppm but non-zero temperature and non-zero humidity.
if (co2 <= 0) {
// No measurement yet. Waiting.
led_effects::showWaitingLED(color::blue);
return false;
}
/**
* Fresh data. Log it and send it if needed.
*/
if (freshData) {
if (should_calibrate) {
countStableMeasurements();
}
logToSerial();
}
if (should_calibrate) {
if (stable_measurements == 60) {
calibrateAndRestart();
}
led_effects::showWaitingLED(waiting_color);
return false;
}
displayCO2OnLedRing();
return freshData;
}
}
......@@ -6,13 +6,13 @@
#include "src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h" // From: http://librarymanager/All#SparkFun_SCD30
#include "config.h"
#include "led_effects.h"
#include "csv_writer.h" // To close filesystem before restart.
#include "util.h"
#include <Wire.h>
namespace config {
extern uint16_t measurement_timestep; // [s] Value between 2 and 1800 (range for SCD30 sensor)
extern uint16_t measurement_timestep; // [s] Value between 2 and 1800 (range for SCD30 sensor)
extern const bool auto_calibrate_sensor; // [true / false]
extern uint16_t co2_calibration_level; // [ppm]
extern uint16_t co2_calibration_level; // [ppm]
extern const float temperature_offset; // [K] Sign isn't relevant.
}
......@@ -24,6 +24,7 @@ namespace sensor {
extern String timestamp;
void initialize();
bool processData();
void startCalibrationProcess();
}
#endif
......@@ -3,14 +3,24 @@
// This file is a config template, and can be copied to config.h. Please don't save any important password in this template.
/**
* SERVICES
*/
// Comment or remove those lines if you want to disable the corresponding services
# define AMPEL_WIFI // Should ESP connect to WiFi? It allows the Ampel to get time from an NTP server.
# define AMPEL_HTTP // Should HTTP web server be started? (AMPEL_WIFI should be enabled too)
# define AMPEL_MQTT // Should data be sent over MQTT? (AMPEL_WIFI should be enabled too)
# define AMPEL_CSV // Should data be logged as CSV, on the ESP flash memory?
// # define AMPEL_LORAWAN // Should data be sent over LoRaWAN? (Requires ESP32 + LoRa modem, and "MCCI LoRaWAN LMIC library")
/**
* WIFI
*/
// Setting WIFI_SSID to "NO_WIFI" will disable WiFi completely, and all other dependent services (MQTT, HTTP, NTP, ...)
# define WIFI_SSID "NO_WIFI"
# define WIFI_SSID "MY_SSID"
# define WIFI_PASSWORD "P4SSW0RD"
# define WIFI_TIMEOUT 20 // [s]
# define WIFI_TIMEOUT 30 // [s]
/**
* Sensor
......@@ -20,15 +30,10 @@
//NOTE: SCD30 timer does not seem to be very precise. Variations may occur.
# define MEASUREMENT_TIMESTEP 60 // [s] Value between 2 and 1800 (range for SCD30 sensor)
// How often measurements should be sent to MQTT server?
// Probably a good idea to use a multiple of MEASUREMENT_TIMESTEP, so that averages can be calculated
// Set to 0 if you want to send values after each measurement
// # define SENDING_INTERVAL MEASUREMENT_TIMESTEP * 5 // [s]
# define SENDING_INTERVAL 300 // [s]
// How often should measurements be appended to CSV ?
// Probably a good idea to use a multiple of MEASUREMENT_TIMESTEP, so that averages can be calculated
// Set to 0 if you want to send values after each measurement
// WARNING: Writing too often might damage the ESP memory
# define CSV_INTERVAL 300 // [s]
// Residual heat from CO2 sensor seems to be high enough to change the temperature reading. How much should it be offset?
......@@ -64,29 +69,26 @@
* available at http://local_ip, with user HTTP_USER and password HTTP_PASSWORD
*/
# define HTTP // Comment or remove this line if you want to disable HTTP webserver
// Define empty strings in order to disable authentication, or remove the constants altogether.
# define HTTP_USER "co2ampel"
# define HTTP_PASSWORD "my_password"
/**
* MQTT SERVER
* MQTT
*/
# define MQTT // Comment or remove this line if you want to disable MQTT
/*
* If MQTT is enabled, co2ampel will publish data every SENDING_INTERVAL seconds.
* If AMPEL_MQTT is enabled, co2ampel will publish data every MQTT_SENDING_INTERVAL seconds.
* An MQTT subscriber can then get the data from the corresponding broker, either encrypted or unencrypted:
*
* ❯ mosquitto_sub -h 'test.mosquitto.org' -p 8883 -t 'CO2sensors/#' --cafile mosquitto.org.crt -v
* CO2sensors/ESPd05cc9 {"time":"2020-12-13 13:14:37+01", "co2":571, "temp":18.9, "rh":50.9}
* CO2sensors/ESPd05cc9 {"time":"2020-12-13 13:14:48+01", "co2":573, "temp":18.9, "rh":50.2}
* CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:14:37+01", "co2":571, "temp":18.9, "rh":50.9}
* CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:14:48+01", "co2":573, "temp":18.9, "rh":50.2}
* ...
*
* ❯ mosquitto_sub -h 'test.mosquitto.org' -t 'CO2sensors/#' -v
* CO2sensors/ESPd05cc9 {"time":"2020-12-13 13:15:09+01", "co2":568, "temp":18.9, "rh":50.1}
* CO2sensors/ESPd05cc9 {"time":"2020-12-13 13:15:20+01", "co2":572, "temp":18.9, "rh":50.3}
* CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:15:09+01", "co2":568, "temp":18.9, "rh":50.1}
* CO2sensors/ESPd03cc5 {"time":"2020-12-13 13:15:20+01", "co2":572, "temp":18.9, "rh":50.3}
* ...
*/
......@@ -98,12 +100,45 @@
*/
# define ALLOW_MQTT_COMMANDS false
// How often measurements should be sent to MQTT server?
// Probably a good idea to use a multiple of MEASUREMENT_TIMESTEP, so that averages can be calculated
// Set to 0 if you want to send values after each measurement
// # define MQTT_SENDING_INTERVAL MEASUREMENT_TIMESTEP * 5 // [s]
# define MQTT_SENDING_INTERVAL 60 // [s]
# define MQTT_SERVER "test.mosquitto.org" // MQTT server URL or IP address
# define MQTT_PORT 8883
# define MQTT_USER ""
# define MQTT_PASSWORD ""
# define MQTT_SERVER_FINGERPRINT "EE BC 4B F8 57 E3 D3 E4 07 54 23 1E F0 C8 A1 56 E0 D3 1A 1C" // SHA1 for test.mosquitto.org
/**
* LoRaWAN
*/
// 1) Requires "MCCI LoRaWAN LMIC library", which will be automatically used with PlatformIO but should be added in "Arduino IDE".
// 2) Region and transceiver type should be specified in:
// * Arduino/libraries/MCCI_LoRaWAN_LMIC_library/project_config/lmic_project_config.h for Arduino IDE
// * platformio.ini for PlatformIO
// See https://github.com/mcci-catena/arduino-lmic#configuration for more information
// 3) It has been tested with "TTGO ESP32 SX1276 LoRa 868" and will only work with an ESP32 + LoRa modem
// 4) In order to use LoRaWAN, a gateway should be close to the co2ampel, and an account, an application and a device should be registered,
// e.g. on https://www.thethingsnetwork.org/docs/applications/
// 5) The corresponding keys should be defined in LORAWAN_DEVICE_EUI, LORAWAN_APPLICATION_EUI and LORAWAN_APPLICATION_KEY
// How often should measurements be sent over LoRaWAN?
# define LORAWAN_SENDING_INTERVAL 300 // [s] This value should not be too low. See https://www.thethingsnetwork.org/docs/lorawan/duty-cycle.html#maximum-duty-cycle
// WARNING: If AMPEL_LORAWAN is enabled, you need to modify the 3 following constants!
// This EUI must be in little-endian format, so least-significant-byte first.
// When copying an EUI from ttnctl output, this means to reverse the bytes.
# define LORAWAN_DEVICE_EUI {0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}
// This should also be in little endian format, see above.
// For TheThingsNetwork issued EUIs the last bytes should be 0xD5, 0xB3, 0x70.
# define LORAWAN_APPLICATION_EUI {0x00, 0x00, 0x00, 0x00, 0x00, 0xD5, 0xB3, 0x70}
// This key should be in big endian format (or, since it is not really a
// number but a block of memory, endianness does not really apply). In
// practice, a key taken from ttnctl can be copied as-is.
# define LORAWAN_APPLICATION_KEY {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
/**
* NTP
*/
......