Commit daf08852 authored by Eric Duminil's avatar Eric Duminil
Browse files

Simple example with LED ring and CO2 sensor

parent da1f41c0
......@@ -3,14 +3,6 @@
/*****************************************************************
* Libraries *
*****************************************************************/
#include "config.h"
#ifndef MEASUREMENT_TIMESTEP
# error Missing config.h file. Please copy config.public.h to config.h.
#endif
#ifdef AMPEL_CSV
# include "csv_writer.h"
#endif
#ifdef AMPEL_WIFI
# include "wifi_util.h"
......
......@@ -11,211 +11,72 @@
* |___/
*/
#include "ampel-firmware.h"
// Small example, with CO2 sensor and LED ring.
// Required libraries:
// LED Ring:
#include "src/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.h"
// CO2 sensor:
#include "src/lib/SparkFun_SCD30_Arduino_Library/src/SparkFun_SCD30_Arduino_Library.h"
#include <Wire.h>
// How many LEDs on the ring?
const int LED_COUNT = 12;
// Where is LED ring connected to micro-controller?
const int NEOPIXELS_PIN = 5;
// Define LED ring and CO2 sensor
Adafruit_NeoPixel led_ring(LED_COUNT, NEOPIXELS_PIN, NEO_GRB + NEO_KHZ800);
SCD30 sensor;
// Define variables
int which_led;
uint16_t co2;
/*****************************************************************
* GPL License *
*****************************************************************/
/*
* This file is part of the "CO2 Ampel" project ( https://transfer.hft-stuttgart.de/gitlab/co2ampel and
* https://transfer.hft-stuttgart.de/gitlab/co2ampel/ampel-firmware )
* Copyright (c) 2020 HfT Stuttgart.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*****************************************************************
* Authors *
*****************************************************************/
/*
* Eric Duminil
* Robert Otto
* Myriam Guedey
* Tobias Gabriel Erhart
* Jonas Stave
* Michael Käppler
*/
/*****************************************************************
* Configuration *
*****************************************************************/
/*
* Please define settings in 'config.h'.
* There's an example config file called 'config.example.h'.
* You can copy 'config.public.h' (stored in Git) to 'config.h' (not stored in Git),
* and define your credentials and parameters in 'config.h'.
*/
/*****************************************************************
* Setup *
*****************************************************************/
void setup() {
led_effects::setupOnBoardLED();
led_effects::onBoardLEDOff();
Serial.begin(BAUDS);
pinMode(0, INPUT); // Flash button (used for forced calibration)
Serial.println();
Serial.print(F("Sensor ID: "));
Serial.println(ampel.sensorId);
Serial.print(F("MAC : "));
Serial.println(ampel.macAddress);
Serial.print(F("Board : "));
Serial.println(ampel.board);
Serial.print(F("Firmware : "));
Serial.println(ampel.version);
// Transmission speed
Serial.begin(115200);
led_effects::setupRing();
// Initialize LED ring.
led_ring.begin();
led_ring.setBrightness(255);
sensor::initialize();
#ifdef AMPEL_CSV
csv_writer::initialize(ampel.sensorId);
#endif
#ifdef AMPEL_WIFI
wifi::connect(ampel.sensorId);
Serial.print(F("WiFi - Status: "));
Serial.println(WiFi.status());
if (WiFi.status() == WL_CONNECTED) {
# ifdef AMPEL_HTTP
web_server::initialize();
# endif
ntp::initialize();
if (MDNS.begin(ampel.sensorId)) { // Start the mDNS responder for SENSOR_ID.local
MDNS.addService("http", "tcp", 80);
Serial.println(F("mDNS responder started"));
} else {
Serial.println(F("Error setting up MDNS responder!"));
}
# ifdef AMPEL_MQTT
mqtt::initialize(ampel.sensorId);
# endif
}
#endif
// Initialize sensor (should be connected to D6 & D5), without auto-calibration.
Wire.begin(12, 14);
sensor.begin(false);
#if defined(AMPEL_LORAWAN) && defined(ESP32)
lorawan::initialize();
#endif
// One measurement every 10s
sensor.setMeasurementInterval(10);
}
/*****************************************************************
* Helper functions *
*****************************************************************/
void keepServicesAlive();
void checkFlashButton();
void checkSerialInput();
/*****************************************************************
* Main loop *
*****************************************************************/
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.
//NOTE: Only use millis() for duration comparison, not timestamps comparison. Otherwise, problems happen when millis roll over.
uint32_t t0 = millis();
keepServicesAlive();
// Short press for night mode, Long press for calibration.
checkFlashButton();
checkSerialInput();
if (sensor::processData()) {
#ifdef AMPEL_CSV
csv_writer::logIfTimeHasCome(sensor::timestamp, sensor::co2, sensor::temperature, sensor::humidity);
#endif
#if defined(AMPEL_WIFI) && defined(AMPEL_MQTT)
mqtt::publishIfTimeHasCome(sensor::timestamp, sensor::co2, sensor::temperature, sensor::humidity);
#endif
#if defined(AMPEL_LORAWAN) && defined(ESP32)
lorawan::preparePayloadIfTimeHasCome(sensor::co2, sensor::temperature, sensor::humidity);
#endif
}
uint32_t duration = millis() - t0;
if (duration > ampel.max_loop_duration) {
ampel.max_loop_duration = duration;
Serial.print(F("Debug - Max loop duration : "));
Serial.print(ampel.max_loop_duration);
Serial.println(F(" ms."));
if (sensor.dataAvailable()) {
// New measurement is available. Let's display it!
co2 = sensor.getCO2();
Serial.print("CO2 : ");
Serial.print(co2);
Serial.println(" ppm.");
}
}
void checkSerialInput() {
while (Serial.available() > 0) {
sensor_console::processSerialInput(Serial.read());
// Light the next LED
which_led = which_led + 1;
// Come back to first LED if needed.
if (which_led >= LED_COUNT) {
which_led = 0;
}
}
/**
* Checks if flash button has been pressed:
* If not, do nothing.
* If short press, toggle LED display.
* If long press, start calibration process.
*/
void checkFlashButton() {
if (!digitalRead(0)) { // Button has been pressed
led_effects::onBoardLEDOn();
delay(300);
if (digitalRead(0)) {
Serial.println(F("Flash has been pressed for a short time. Should toggle night mode."));
led_effects::toggleNightMode();
} else {
Serial.println(F("Flash has been pressed for a long time. Keep it pressed for calibration."));
if (led_effects::countdownToZero()) {
Serial.println(F("You can now release the button."));
sensor::startCalibrationProcess();
led_effects::showKITTWheel(color::red, 2);
}
}
led_effects::onBoardLEDOff();
// First, disable every LED
led_ring.clear();
// Check if air is good enough
if (co2 <= 1000) {
// Light the LED green if CO2 ppm is low
led_ring.setPixelColor(which_led, 0, 255, 0);
} else {
// Red otherwise.
led_ring.setPixelColor(which_led, 255, 0, 0);
}
}
led_ring.show();
void keepServicesAlive() {
#ifdef AMPEL_WIFI
if (WiFi.status() == WL_CONNECTED) {
# 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
ntp::update(); // NTP client has its own timer. It will connect to NTP server every 60s.
# ifdef AMPEL_HTTP
web_server::update();
# endif
# ifdef AMPEL_MQTT
mqtt::keepConnection(); // MQTT client has its own timer. It will keep alive every 15s.
# endif
}
#endif
// Wait half a second before next loop.
// Micro-controller might crash if it has too much work to do. Please don't remove it!
delay(500);
}
#include "co2_sensor.h"
namespace config {
// UPPERCASE 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]
const uint16_t measurement_timestep_bootup = 5; // [s] Measurement timestep during acclimatization.
const uint8_t max_deviation_during_bootup = 20; // [%]
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.
const uint16_t co2_alert_threshold = 2000; // [ppm] Display a flashing led ring, if concentration exceeds this value
#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]
#else
const float temperature_offset = -3.0; // [K] Temperature measured by sensor is usually at least 3K too high.
#endif
bool auto_calibrate_sensor = AUTO_CALIBRATE_SENSOR; // [true / false]
const bool debug_sensor_states = false; // If true, log state transitions over serial console
}
namespace sensor {
SCD30 scd30;
uint16_t co2 = 0;
float temperature = 0;
float humidity = 0;
char timestamp[23];
int16_t stable_measurements = 0;
/**
* Define sensor states
* BOOTUP -> initial state, until first >0 ppm values are returned
* READY -> sensor does output valid information (> 0 ppm) and no other condition takes place
* NEEDS_CALIBRATION -> sensor measurements are too low (< 250 ppm)
* 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
*/
enum state {
BOOTUP,
READY,
NEEDS_CALIBRATION,
PREPARE_CALIBRATION_UNSTABLE,
PREPARE_CALIBRATION_STABLE
};
const char *state_names[] = {
"BOOTUP",
"READY",
"NEEDS_CALIBRATION",
"PREPARE_CALIBRATION_UNSTABLE",
"PREPARE_CALIBRATION_STABLE" };
state current_state = BOOTUP;
void switchState(state);
void initialize() {
#if defined(ESP8266)
Wire.begin(12, 14); // ESP8266 - D6, D5;
#endif
#if defined(ESP32)
Wire.begin(21, 22); // ESP32
/**
* SCD30 ESP32
* VCC --- 3V3
* GND --- GND
* SCL --- SCL (GPIO22) //NOTE: GPIO3 Would be more convenient (right next to GND)
* SDA --- SDA (GPIO21) //NOTE: GPIO1 would be more convenient (right next to GPO3)
*/
#endif
Serial.println();
scd30.enableDebugging(); // Prints firmware version in the console.
if (!scd30.begin(config::auto_calibrate_sensor)) {
Serial.println(F("ERROR - CO2 sensor not detected. Please check wiring!"));
led_effects::showKITTWheel(color::red, 30);
ESP.restart();
}
// Changes of the SCD30's measurement timestep do not come into effect
// before the next measurement takes place. That means that after a hard reset
// of the ESP the SCD30 sometimes needs a long time until switching back to 2 s
// for acclimatization. Resetting it after startup seems to fix this behaviour.
scd30.reset();
Serial.print(F("Setting temperature offset to -"));
Serial.print(abs(config::temperature_offset));
Serial.println(F(" K."));
scd30.setTemperatureOffset(abs(config::temperature_offset)); // setTemperatureOffset only accepts positive numbers, but shifts the temperature down.
delay(100);
Serial.print(F("Temperature offset is : -"));
Serial.print(scd30.getTemperatureOffset());
Serial.println(F(" K"));
Serial.print(F("Auto-calibration is "));
Serial.println(config::auto_calibrate_sensor ? "ON." : "OFF.");
// SCD30 has its own timer.
//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_bootup);
Serial.println(F(" s during acclimatization."));
scd30.setMeasurementInterval(config::measurement_timestep_bootup); // [s]
sensor_console::defineIntCommand("co2", setCO2forDebugging, F("1500 (Sets co2 level, for debugging purposes)"));
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)"));
}
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.
return (co2 > 0 && delta < ((uint32_t) co2 * config::max_deviation_during_bootup / 100));
}
bool enoughStableMeasurements() {
static int16_t previous_co2 = 0;
if (co2 > (previous_co2 - config::max_deviation_during_calibration)
&& co2 < (previous_co2 + config::max_deviation_during_calibration)) {
stable_measurements++;
Serial.print(F("Number of stable measurements : "));
Serial.print(stable_measurements);
Serial.print(F(" / "));
Serial.println(config::stable_measurements_before_calibration);
switchState(PREPARE_CALIBRATION_STABLE);
} else {
stable_measurements = 0;
switchState(PREPARE_CALIBRATION_UNSTABLE);
}
previous_co2 = co2;
return (stable_measurements == config::stable_measurements_before_calibration);
}
void startCalibrationProcess() {
/** From the sensor documentation:
* Before applying FRC, SCD30 needs to be operated for 2 minutes with the desired measurement period in continuous mode.
*/
Serial.print(F("Setting SCD30 timestep to "));
Serial.print(config::timestep_during_calibration);
Serial.println(F("s, prior to calibration."));
scd30.setMeasurementInterval(config::timestep_during_calibration); // [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."));
switchState(PREPARE_CALIBRATION_UNSTABLE);
}
void calibrate() {
Serial.print(F("Calibrating SCD30 now..."));
scd30.setAltitudeCompensation(config::altitude_above_sea_level);
scd30.setForcedRecalibrationFactor(config::co2_calibration_level);
Serial.println(F(" Done!"));
Serial.println(F("Sensor calibrated."));
switchState(BOOTUP); // In order to stop the calibration and select the desired timestep.
//WARNING: Do not reset the ampel or the SCD30!
//At least one measurement needs to happen in order for the calibration to be correctly applied.
}
void logToSerial() {
Serial.print(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 switchState(state new_state) {
if (new_state == current_state) {
return;
}
if (config::debug_sensor_states) {
Serial.print(F("Changing sensor state: "));
Serial.print(state_names[current_state]);
Serial.print(F(" -> "));
Serial.println(state_names[new_state]);
}
current_state = new_state;
}
void switchStateForCurrentPPM() {
if (current_state == BOOTUP) {
if (!hasSensorSettled()) {
return;
}
switchState(READY);
Serial.println(F("Sensor acclimatization finished."));
Serial.print(F("Setting SCD30 timestep to "));
Serial.print(config::measurement_timestep);
Serial.println(F(" s."));
if (config::measurement_timestep < 10) {
Serial.println(F("WARNING: Timesteps shorter than 10s can lead to unreliable measurements!"));
}
scd30.setMeasurementInterval(config::measurement_timestep); // [s]
}
// Check for pre-calibration states first, because we do not want to
// leave them before calibration is done.
if ((current_state == PREPARE_CALIBRATION_UNSTABLE) || (current_state == PREPARE_CALIBRATION_STABLE)) {
if (enoughStableMeasurements()) {
calibrate();
}
} 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).
* A short delay is required in order to let background tasks run on the ESP8266.
* see https://github.com/esp8266/Arduino/issues/3241#issuecomment-301290392
*/
if (co2 < config::co2_alert_threshold) {
led_effects::displayCO2color(co2);
delay(100);
} else {
// Display a flashing led ring, if concentration exceeds a specific value
led_effects::redAlert();
}
}
void showState() {
switch (current_state) {
case BOOTUP:
led_effects::showWaitingLED(color::blue);
break;
case READY:
displayCO2OnLedRing();
break;
case NEEDS_CALIBRATION:
led_effects::showWaitingLED(color::magenta);
break;
case PREPARE_CALIBRATION_UNSTABLE:
led_effects::showWaitingLED(color::red);
break;
case PREPARE_CALIBRATION_STABLE:
led_effects::showWaitingLED(color::green);
break;
default:
Serial.println(F("Encountered unknown sensor state")); // This should not happen.
}
}
/** 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) {
ntp::getLocalTime(timestamp);
co2 = scd30.getCO2();
temperature = scd30.getTemperature();
humidity = scd30.getHumidity();
switchStateForCurrentPPM();
// Log every time fresh data is available.
logToSerial();
}
showState();
// 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);
}
/*****************************************************************
* Callbacks for sensor commands *
*****************************************************************/
void setCO2forDebugging(int32_t fakeCo2) {
Serial.print(F("DEBUG. Setting CO2 to "));
co2 = fakeCo2;
Serial.println(co2);
switchStateForCurrentPPM();
}
void setAutoCalibration(int32_t autoCalibration) {
config::auto_calibrate_sensor = autoCalibration;
scd30.setAutoSelfCalibration(autoCalibration);
Serial.print(F("Setting auto-calibration to : "));
Serial.println(autoCalibration ? F("On.") : F("Off."));
}
void setTimer(int32_t timestep) {
if (timestep >= 2 && timestep <= 1800) {
Serial.print(F("Setting Measurement Interval to : "));
Serial.print(timestep);
Serial.println(F("s (change will only be applied after next measurement)."));
scd30.setMeasurementInterval(timestep);
config::measurement_timestep = timestep;
led_effects::showKITTWheel(color::green, 1);
}
}
void calibrateSensorToSpecificPPM(int32_t calibrationLevel) {
if (calibrationLevel >= 400 && calibrationLevel <= 2000) {
Serial.print(F("Force calibration, at "));
config::co2_calibration_level = calibrationLevel;
Serial.print(config::co2_calibration_level);
Serial.println(F(" ppm."));
startCalibrationProcess();
}
}
void calibrateSensorRightNow(int32_t calibrationLevel) {
if (calibrationLevel >= 400 && calibrationLevel <= 2000) {
Serial.print(F("Force calibration, right now, at "));
config::co2_calibration_level = calibrationLevel;
Serial.print(config::co2_calibration_level);
Serial.println(F(" ppm."));
calibrate();
}
}
void resetSCD() {
Serial.print(F("Resetting SCD30..."));
scd30.reset();
Serial.println(F("done."));
}
}
#ifndef CO2_SENSOR_H_
#define CO2_SENSOR_H_
// The SCD30 from Sensirion is a high quality Nondispersive Infrared (NDIR) based CO₂ sensor capable of detecting 400 to 10000ppm with an accuracy of ±(30ppm+3%).
// https://github.com/sparkfun/SparkFun_SCD30_Arduino_Library
#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 "util.h"
#include "sensor_console.h"
#include <Wire.h>
namespace config {
extern uint16_t measurement_timestep; // [s] Value between 2 and 1800 (range for SCD30 sensor)
extern bool auto_calibrate_sensor; // [true / false]
extern uint16_t co2_calibration_level; // [ppm]
extern const float temperature_offset; // [K] Sign isn't relevant.
}
namespace sensor {
extern SCD30 scd30;
extern uint16_t co2;
extern float temperature;
extern float humidity;
extern char timestamp[];
void initialize();
bool processData();
void startCalibrationProcess();
void setCO2forDebugging(int32_t fakeCo2);
void setTimer(int32_t timestep);
void calibrateSensorToSpecificPPM(int32_t calibrationLevel);
void calibrateSensorRightNow(int32_t calibrationLevel);
void setAutoCalibration(int32_t autoCalibration);
void resetSCD();
}
#endif
#ifndef CONFIG_H_INCLUDED
# define CONFIG_H_INCLUDED
// 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
*/
# define WIFI_SSID "MY_SSID"
# define WIFI_PASSWORD "P4SSW0RD"
# define WIFI_TIMEOUT 30 // [s]
/**
* Sensor
*/
// How often should measurement be performed, and displayed?
//WARNING: On some sensors, measurements become very unreliable when timestep is set to 2s.
//NOTE: 10s or longer should be fine in order to get reliable results.
//NOTE: SCD30 timer does not seem to be very precise. Time variations may occur.
# define MEASUREMENT_TIMESTEP 60 // [s] Value between 2 and 1800 (range for SCD30 sensor)
// 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?
// NOTE: Sign isn't relevant. The returned temperature will always be shifted down.
# define TEMPERATURE_OFFSET -3 // [K]
// Altitude above sea level
// Used for CO2 calibration
// here: Stuttgart, Schellingstr. 24. (Source: Google Earth)
# define ALTITUDE_ABOVE_SEA_LEVEL 260 // [m]
// The reference CO2 concentration has to be within the range 400 ppm ≤ cref(CO2) ≤ 2000 ppm.
// Used for CO2 calibration
// here : measured concentration in Stuttgart
# define ATMOSPHERIC_CO2_CONCENTRATION 425 // [ppm]
// Should the sensor try to calibrate itself?
// Sensirion recommends 7 days of continuous readings with at least 1 hour a day of 'fresh air' for self-calibration to complete.
# define AUTO_CALIBRATE_SENSOR true // [true / false]
/**
* LEDs
*/
// LED brightness, which can vary between min and max brightness ("LED breathing")
// MAX_BRIGHTNESS must be defined, and should be between 0 and 255.
# define MAX_BRIGHTNESS 255
// MIN_BRIGHTNESS, if defined, should be between 0 and MAX_BRIGHTNESS - 1
// If MIN_BRIGHTNESS is not set, or if it is set to MAX_BRIGHTNESS, breathing is disabled.
# define MIN_BRIGHTNESS 60
// How many LEDs in the ring? 12 and 16 are currently supported. If undefined, 12 is used as default.
# define LED_COUNT 12
/**
* WEB SERVER
* available at http://local_ip, with user HTTP_USER and password HTTP_PASSWORD
*/
// Define empty strings in order to disable authentication, or remove the constants altogether.
# define HTTP_USER "co2ampel"
# define HTTP_PASSWORD "my_password"
/**
* MQTT
*/
/*
* 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/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/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}
* ...
*/
/*
* Allow sensor to be configured over MQTT? Very useful for debugging. For example:
* mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'timer 30'
* mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'calibrate'
* mosquitto_pub -h 'test.mosquitto.org' -t 'CO2sensors/ESPe08dc9/control' -m 'reset'
*/
# define ALLOW_MQTT_COMMANDS false
// How often should measurements 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 ""
/**
* 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
*/
# define NTP_SERVER "pool.ntp.org"
# define UTC_OFFSET_IN_SECONDS 7200 // [s] 3600 for UTC+1, 7200 for UTC+1 and daylight saving time
/**
* Others
*/
# define BAUDS 115200 // Transmission rate
#endif
#include "csv_writer.h"
namespace config {
// Values should be defined in config.h
uint16_t csv_interval = CSV_INTERVAL; // [s]
}
namespace csv_writer {
unsigned long last_written_at = 0;
char last_successful_write[23];
#if defined(ESP8266)
/**
* SPECIFIC FUNCTIONS FOR LITTLEFS
*/
FSInfo fs_info;
bool mountFS() {
return LittleFS.begin(); // format if needed.
}
void updateFsInfo() {
FS_LIB.info(fs_info);
}
int getTotalSpace() {
return fs_info.totalBytes;
}
int getUsedSpace() {
return fs_info.usedBytes;
}
void showFilesystemContent() {
Dir dir = FS_LIB.openDir("/");
while (dir.next()) {
Serial.print(" ");
Serial.print(dir.fileName());
Serial.print(" - ");
if (dir.fileSize()) {
File f = dir.openFile("r");
Serial.println(f.size());
f.close();
} else {
Serial.println("0");
}
}
}
#elif defined(ESP32)
/**
* SPECIFIC FUNCTIONS FOR SPIFFS
*/
bool mountFS() {
return SPIFFS.begin(true); // format if needed.
}
void updateFsInfo() {
// Nothing to do.
}
int getTotalSpace() {
return SPIFFS.totalBytes();
}
int getUsedSpace() {
return SPIFFS.usedBytes();
}
void showFilesystemContent() {
File root = SPIFFS.open("/");
File file = root.openNextFile();
while (file) {
Serial.print(" ");
Serial.print(file.name());
Serial.print(" - ");
Serial.println(file.size());
file = root.openNextFile();
}
}
#endif
char filename[15]; // "/ESPxxxxxx.csv\0"
int getAvailableSpace() {
return getTotalSpace() - getUsedSpace();
}
void initialize(const char *sensorId) {
snprintf(filename, sizeof(filename), "/%s.csv", sensorId);
Serial.println();
Serial.print(F("Initializing FS..."));
if (mountFS()) {
Serial.println(F("done."));
} else {
Serial.println(F("fail."));
return;
}
updateFsInfo();
Serial.println(F("File system info:"));
Serial.print(F(" Total space : "));
Serial.print(getTotalSpace() / 1024);
Serial.println("kB");
Serial.print(F(" Used space : "));
Serial.print(getUsedSpace() / 1024);
Serial.println("kB");
Serial.print(F(" Available space: "));
Serial.print(getAvailableSpace() / 1024);
Serial.println("kB");
Serial.println();
// Open dir folder
Serial.println(F("Filesystem content:"));
showFilesystemContent();
Serial.println();
sensor_console::defineIntCommand("csv", setCSVinterval, F("60 (Sets CSV writing interval, in s)"));
sensor_console::defineCommand("format_filesystem", formatFilesystem, F("(Deletes the whole filesystem)"));
sensor_console::defineCommand("show_csv", showCSVContent, F("(Displays the complete CSV file on Serial)"));
}
File openOrCreate() {
File csv_file;
if (FS_LIB.exists(filename)) {
csv_file = FS_LIB.open(filename, "a+");
} else {
csv_file = FS_LIB.open(filename, "w");
csv_file.print(F("Sensor time;CO2 concentration;Temperature;Humidity\r\n"));
csv_file.print(F("YYYY-MM-DD HH:MM:SS+ZZ;ppm;degC;%\r\n"));
}
return csv_file;
}
void log(const char *timestamp, const int16_t &co2, const float &temperature, const float &humidity) {
led_effects::onBoardLEDOn();
File csv_file = openOrCreate();
char csv_line[42];
snprintf(csv_line, sizeof(csv_line), "%s;%d;%.1f;%.1f\r\n", timestamp, co2, temperature, humidity);
if (csv_file) {
size_t written_bytes = csv_file.print(csv_line);
csv_file.close();
if (written_bytes == 0) {
Serial.println(F("Nothing written. Disk full?"));
} else {
Serial.print(F("CSV - Wrote : "));
Serial.print(csv_line);
ntp::getLocalTime(last_successful_write);
}
updateFsInfo();
delay(50);
} else {
//NOTE: Can it ever happen that outfile is false?
Serial.println(F("Problem on create file!"));
}
led_effects::onBoardLEDOff();
}
void logIfTimeHasCome(const char *timeStamp, const int16_t &co2, const float &temperature, const float &humidity) {
unsigned long now = seconds();
if (now - last_written_at > config::csv_interval) {
last_written_at = now;
log(timeStamp, co2, temperature, humidity);
}
}
/*****************************************************************
* Callbacks for sensor commands *
*****************************************************************/
void setCSVinterval(int32_t csv_interval) {
config::csv_interval = csv_interval;
Serial.print(F("Setting CSV Interval to : "));
Serial.print(config::csv_interval);
Serial.println("s.");
led_effects::showKITTWheel(color::green, 1);
}
void showCSVContent() {
Serial.print(F("### "));
Serial.print(filename);
Serial.println(F(" ###"));
File csv_file;
if (FS_LIB.exists(filename)) {
csv_file = FS_LIB.open(filename, "r");
while (csv_file.available()) {
Serial.write(csv_file.read());
}
csv_file.close();
}
Serial.println(F("######################"));
}
void formatFilesystem() {
FS_LIB.format();
led_effects::showKITTWheel(color::blue, 2);
}
}
#ifndef CSV_WRITER_H_
#define CSV_WRITER_H_
#if defined(ESP8266)
# include <LittleFS.h>
# define FS_LIB LittleFS
#elif defined(ESP32)
# include <SPIFFS.h>
# define FS_LIB SPIFFS
#else
# error Board should be either ESP8266 or ESP832
#endif
#include "config.h"
#include "util.h"
#include "led_effects.h"
#include "sensor_console.h"
namespace config {
extern uint16_t csv_interval; // [s]
}
namespace csv_writer {
extern char last_successful_write[];
void initialize(const char *sensorId);
void logIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temperature, const float &humidity);
int getAvailableSpace();
extern char filename[];
void setCSVinterval(int32_t csv_interval);
void showCSVContent();
void formatFilesystem();
}
#endif
#include "led_effects.h"
/*****************************************************************
* Configuration *
*****************************************************************/
namespace config {
const uint8_t max_brightness = MAX_BRIGHTNESS;
#if defined(MIN_BRIGHTNESS)
const uint8_t min_brightness = MIN_BRIGHTNESS;
#else
const uint8_t min_brightness = MAX_BRIGHTNESS;
#endif
const uint8_t brightness_amplitude = config::max_brightness - config::min_brightness;
const int kitt_tail = 3; // How many dimmer LEDs follow in K.I.T.T. wheel
const uint16_t poor_air_quality_ppm = 1600; // Above this threshold, LED breathing effect is faster.
bool night_mode = false; //NOTE: Use a class instead? NightMode could then be another state.
#if !defined(LED_COUNT)
# define LED_COUNT 12
#endif
const uint16_t led_count = LED_COUNT;
#if LED_COUNT == 12
//NOTE: One value has been prepended, to make calculations easier and avoid out of bounds index.
const uint16_t co2_ticks[led_count + 1] = { 0, 500, 600, 700, 800, 900, 1000, 1200, 1400, 1600, 1800, 2000, 2200 }; // [ppm]
// For a given LED, which color should be displayed? First LED will be pure green (hue angle 120°),
// LEDs >= 1600ppm will be pure red (hue angle 0°), LEDs in-between will be yellowish.
const uint16_t led_hues[led_count] = { 21845U, 19114U, 16383U, 13653U, 10922U, 8191U, 5461U, 2730U, 0, 0, 0, 0 }; // [hue angle]
#elif LED_COUNT == 16
const uint16_t co2_ticks[led_count + 1] = { 0, 500, 600, 700, 800, 900, 1000, 1100, 1200,
1300, 1400, 1500, 1600, 1700, 1800, 2000, 2200 }; // [ppm]
const uint16_t led_hues[led_count] = {21845U, 19859U, 17873U, 15887U, 13901U, 11915U, 9929U, 7943U,
5957U, 3971U, 1985U, 0, 0, 0, 0, 0}; // [hue angle]
#else
# error "Only 12 and 16 LEDs rings are currently supported."
#endif
}
#if defined(ESP8266)
// NeoPixels on GPIO05, aka D1 on ESP8266.
const int NEOPIXELS_PIN = 5;
#elif defined(ESP32)
// NeoPixels on GPIO23 on ESP32. To avoid conflict with LoRa_SCK on TTGO.
const int NEOPIXELS_PIN = 23;
#endif
Adafruit_NeoPixel pixels(config::led_count, NEOPIXELS_PIN, NEO_GRB + NEO_KHZ800);
namespace led_effects {
//On-board LED on D4, aka GPIO02
const int ONBOARD_LED_PIN = 2;
void setupOnBoardLED() {
pinMode(ONBOARD_LED_PIN, OUTPUT);
}
void onBoardLEDOff() {
//NOTE: OFF is LOW on ESP32 and HIGH on ESP8266 :-/
#ifdef ESP8266
digitalWrite(ONBOARD_LED_PIN, HIGH);
#else
digitalWrite(ONBOARD_LED_PIN, LOW);
#endif
}
void onBoardLEDOn() {
#ifdef ESP8266
digitalWrite(ONBOARD_LED_PIN, LOW);
#else
digitalWrite(ONBOARD_LED_PIN, HIGH);
#endif
}
void LEDsOff() {
pixels.clear();
pixels.show();
onBoardLEDOff();
}
void showColor(int32_t color) {
config::night_mode = true; // In order to avoid overwriting the desired color next time CO2 is displayed
pixels.setBrightness(255);
pixels.fill(color);
pixels.show();
}
void setupRing() {
pixels.begin();
pixels.setBrightness(config::max_brightness);
LEDsOff();
sensor_console::defineCommand("night_mode", toggleNightMode, F("(Toggles night mode on/off)"));
sensor_console::defineIntCommand("color", showColor, F("0xFF0015 (Shows color, specified as RGB, for debugging)"));
}
void toggleNightMode() {
config::night_mode = !config::night_mode;
if (config::night_mode) {
Serial.println(F("NIGHT MODE!"));
LEDsOff();
} else {
Serial.println(F("DAY MODE!"));
}
}
//NOTE: basically one iteration of KITT wheel
void showWaitingLED(uint32_t color) {
using namespace config;
delay(80);
if (night_mode) {
return;
}
static uint16_t kitt_offset = 0;
pixels.clear();
for (int j = kitt_tail; j >= 0; j--) {
int ledNumber = abs((kitt_offset - j + led_count) % (2 * led_count) - led_count) % led_count; // Triangular function
pixels.setPixelColor(ledNumber, color * pixels.gamma8(255 - j * 76) / 255);
}
pixels.show();
kitt_offset++;
}
// Start K.I.T.T. led effect. Red color as default.
// Simulate a moving LED with tail. First LED starts at 0, and moves along a triangular function. The tail follows, with decreasing brightness.
// Takes approximately 1s for each direction.
void showKITTWheel(uint32_t color, uint16_t duration_s) {
pixels.setBrightness(config::max_brightness);
for (int i = 0; i < duration_s * config::led_count; ++i) {
showWaitingLED(color);
}
}
/*
* For a given CO2 level and ledId, which brightness should be displayed? 0 for off, 255 for on. Something in-between for partial LED.
* For example, for 1500ppm, every LED between 0 and 7 (500 -> 1400ppm) should be on, LED at 8 (1600ppm) should be half-on.
*/
uint8_t getLedBrightness(uint16_t co2, int ledId) {
if (co2 >= config::co2_ticks[ledId + 1]) {
return 255;
} else {
if (2 * co2 >= config::co2_ticks[ledId] + config::co2_ticks[ledId + 1]) {
// Show partial LED if co2 more than halfway between ticks.
return 27; // Brightness isn't linear, so 27 / 255 looks much brighter than 10%
} else {
// LED off because co2 below previous tick
return 0;
}
}
}
/**
* If enabled, slowly varies the brightness between MAX_BRIGHTNESS & MIN_BRIGHTNESS.
*/
void breathe(int16_t co2) {
static uint8_t breathing_offset = 0;
uint16_t brightness = config::min_brightness + pixels.sine8(breathing_offset) * config::brightness_amplitude / 255;
pixels.setBrightness(brightness);
pixels.show();
breathing_offset += co2 > config::poor_air_quality_ppm ? 6 : 3; // breathing speed. +3 looks like slow human breathing.
}
/**
* Fills the whole ring with green, yellow, orange or black, depending on co2 input and CO2_TICKS.
*/
void displayCO2color(uint16_t co2) {
if (config::night_mode) {
return;
}
pixels.setBrightness(config::max_brightness);
for (int ledId = 0; ledId < config::led_count; ++ledId) {
uint8_t brightness = getLedBrightness(co2, ledId);
pixels.setPixelColor(ledId, pixels.ColorHSV(config::led_hues[ledId], 255, brightness));
}
pixels.show();
if (config::brightness_amplitude > 0) {
breathe(co2);
}
}
void showRainbowWheel(uint16_t duration_ms) {
if (config::night_mode) {
return;
}
static uint16_t wheel_offset = 0;
static uint16_t sine_offset = 0;
unsigned long t0 = millis();
pixels.setBrightness(config::max_brightness);
while (millis() - t0 < duration_ms) {
for (int i = 0; i < config::led_count; i++) {
pixels.setPixelColor(i, pixels.ColorHSV(i * 65535 / config::led_count + wheel_offset));
wheel_offset += (pixels.sine8(sine_offset++ / 50) - 127) / 2;
}
pixels.show();
delay(10);
}
}
void redAlert() {
if (config::night_mode) {
onBoardLEDOn();
delay(500);
onBoardLEDOff();
delay(500);
return;
}
for (int i = 0; i < 10; i++) {
pixels.setBrightness(static_cast<int>(config::max_brightness * (1 - i * 0.1)));
delay(50);
pixels.fill(color::red);
pixels.show();
}
}
/**
* Displays a complete blue circle, and starts removing LEDs one by one.
* Does nothing in night mode and returns false then. Returns true if
* the countdown has finished. Can be used for calibration, e.g. when countdown is 0.
* NOTE: This function is blocking and returns only after the button has
* been released or after every LED has been turned off.
*/
bool countdownToZero() {
if (config::night_mode) {
Serial.println(F("Night mode. Not doing anything."));
delay(1000); // Wait for a while, to avoid coming back to this function too many times when button is pressed.
return false;
}
pixels.fill(color::blue);
pixels.show();
int countdown;
for (countdown = config::led_count; countdown >= 0 && !digitalRead(0); countdown--) {
pixels.setPixelColor(countdown, color::black);
pixels.show();
Serial.println(countdown);
delay(500);
}
return countdown < 0;
}
}
#ifndef LED_EFFECTS_H_INCLUDED
#define LED_EFFECTS_H_INCLUDED
#include <Arduino.h>
#include "config.h"
#include "sensor_console.h"
// Adafruit NeoPixel (Arduino library for controlling single-wire-based LED pixels and strip)
// https://github.com/adafruit/Adafruit_NeoPixel
// Documentation : http://adafruit.github.io/Adafruit_NeoPixel/html/class_adafruit___neo_pixel.html
#include "src/lib/Adafruit_NeoPixel/Adafruit_NeoPixel.h"
namespace color {
const uint32_t red = 0xFF0000;
const uint32_t green = 0x00FF00;
const uint32_t blue = 0x0000FF;
const uint32_t black = 0x000000;
const uint32_t magenta = 0xFF00FF;
}
namespace led_effects {
void setupOnBoardLED();
void onBoardLEDOff();
void onBoardLEDOn();
void toggleNightMode();
void LEDsOff();
void setupRing();
void redAlert();
bool countdownToZero();
void showWaitingLED(uint32_t color);
void showKITTWheel(uint32_t color, uint16_t duration_s = 2);
void showRainbowWheel(uint16_t duration_ms = 1000);
void displayCO2color(uint16_t co2);
}
#endif
#include "lorawan.h"
#if defined(AMPEL_LORAWAN) && defined(ESP32)
namespace config {
// Values should be defined in config.h
uint16_t lorawan_sending_interval = LORAWAN_SENDING_INTERVAL; // [s]
static const u1_t PROGMEM APPEUI[8] = LORAWAN_APPLICATION_EUI;
static const u1_t PROGMEM DEVEUI[8] = LORAWAN_DEVICE_EUI;
static const u1_t PROGMEM APPKEY[16] = LORAWAN_APPLICATION_KEY;
}
// Payloads will be automatically sent via MQTT by TheThingsNetwork, and can be seen with:
// mosquitto_sub -h eu.thethings.network -t '+/devices/+/up' -u 'APPLICATION-NAME' -P 'ttn-account-v2.4xxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx' -v
// or encrypted:
// mosquitto_sub -h eu.thethings.network -t '+/devices/+/up' -u 'APPLICATION-NAME' -P 'ttn-account-v2.4xxxxxxxx-xxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxx' -v --cafile mqtt-ca.pem -p 8883
// ->
// co2ampel-test/devices/esp3a7c94/up {"app_id":"co2ampel-test","dev_id":"esp3a7c94","hardware_serial":"00xxxxxxxx","port":1,"counter":5,"payload_raw":"TJd7","payload_fields":{"co2":760,"rh":61.5,"temp":20.2},"metadata":{"time":"2020-12-23T23:00:51.44020438Z","frequency":867.5,"modulation":"LORA","data_rate":"SF7BW125","airtime":51456000,"coding_rate":"4/5","gateways":[{"gtw_id":"eui-xxxxxxxxxxxxxxxxxx","timestamp":1765406908,"time":"2020-12-23T23:00:51.402519Z","channel":5,"rssi":-64,"snr":7.5,"rf_chain":0,"latitude":22.7,"longitude":114.24,"altitude":450}]}}
// More info : https://www.thethingsnetwork.org/docs/applications/mqtt/quick-start.html
void os_getArtEui(u1_t *buf) {
memcpy_P(buf, config::APPEUI, 8);
}
void os_getDevEui(u1_t *buf) {
memcpy_P(buf, config::DEVEUI, 8);
}
void os_getDevKey(u1_t *buf) {
memcpy_P(buf, config::APPKEY, 16);
}
namespace lorawan {
bool waiting_for_confirmation = false;
bool connected = false;
char last_transmission[23] = "";
void initialize() {
Serial.println(F("Starting LoRaWAN. Frequency plan : " LMIC_FREQUENCY_PLAN " MHz."));
// More info about pin mapping : https://github.com/mcci-catena/arduino-lmic#pin-mapping
// Has been tested successfully with ESP32 TTGO LoRa32 V1, and might work with other ESP32+LoRa boards.
const lmic_pinmap *pPinMap = Arduino_LMIC::GetPinmap_ThisBoard();
// LMIC init.
os_init_ex(pPinMap);
// Reset the MAC state. Session and pending data transfers will be discarded.
LMIC_reset();
// Join, but don't send anything yet.
LMIC_startJoining();
sensor_console::defineIntCommand("lora", setLoRaInterval, F("300 (Sets LoRaWAN sending interval, in s)"));
}
// Checks if OTAA is connected, or if payload should be sent.
// NOTE: while a transaction is in process (i.e. until the TXcomplete event has been received, no blocking code (e.g. delay loops etc.) are allowed, otherwise the LMIC/OS code might miss the event.
// If this rule is not followed, a typical symptom is that the first send is ok and all following ones end with the 'TX not complete' failure.
void process() {
os_runloop_once();
}
void printHex2(unsigned v) {
v &= 0xff;
if (v < 16)
Serial.print('0');
Serial.print(v, HEX);
}
void onEvent(ev_t ev) {
char current_time[23];
ntp::getLocalTime(current_time);
Serial.print("LoRa - ");
Serial.print(current_time);
Serial.print(" - ");
switch (ev) {
case EV_JOINING:
Serial.println(F("EV_JOINING"));
break;
case EV_JOINED:
waiting_for_confirmation = false;
connected = true;
led_effects::onBoardLEDOff();
Serial.println(F("EV_JOINED"));
{
u4_t netid = 0;
devaddr_t devaddr = 0;
u1_t nwkKey[16];
u1_t artKey[16];
LMIC_getSessionKeys(&netid, &devaddr, nwkKey, artKey);
Serial.print(F(" netid: "));
Serial.println(netid, DEC);
Serial.print(F(" devaddr: "));
Serial.println(devaddr, HEX);
Serial.print(F(" AppSKey: "));
for (size_t i = 0; i < sizeof(artKey); ++i) {
if (i != 0)
Serial.print("-");
printHex2(artKey[i]);
}
Serial.println();
Serial.print(F(" NwkSKey: "));
for (size_t i = 0; i < sizeof(nwkKey); ++i) {
if (i != 0)
Serial.print("-");
printHex2(nwkKey[i]);
}
Serial.println();
}
Serial.println(F("Other services may resume, and will not be frozen anymore."));
// Disable link check validation (automatically enabled during join)
LMIC_setLinkCheckMode(0);
break;
case EV_JOIN_FAILED:
Serial.println(F("EV_JOIN_FAILED"));
break;
case EV_REJOIN_FAILED:
Serial.println(F("EV_REJOIN_FAILED"));
break;
case EV_TXCOMPLETE:
ntp::getLocalTime(last_transmission);
Serial.println(F("EV_TXCOMPLETE"));
break;
case EV_TXSTART:
waiting_for_confirmation = !connected;
Serial.println(F("EV_TXSTART"));
break;
case EV_TXCANCELED:
waiting_for_confirmation = false;
led_effects::onBoardLEDOff();
Serial.println(F("EV_TXCANCELED"));
break;
case EV_JOIN_TXCOMPLETE:
waiting_for_confirmation = false;
led_effects::onBoardLEDOff();
Serial.println(F("EV_JOIN_TXCOMPLETE: no JoinAccept."));
Serial.println(F("Other services may resume."));
break;
default:
Serial.print(F("LoRa event: "));
Serial.println((unsigned) ev);
break;
}
if (waiting_for_confirmation) {
led_effects::onBoardLEDOn();
Serial.println(F("LoRa - waiting for OTAA confirmation. Freezing every other service!"));
}
}
void preparePayload(int16_t co2, float temperature, float humidity) {
// Check if there is not a current TX/RX job running
if (LMIC.opmode & OP_TXRXPEND) {
Serial.println(F("OP_TXRXPEND, not sending"));
} else {
uint8_t buff[3];
// Mapping CO2 from 0ppm to 5100ppm to [0, 255], with 20ppm increments.
buff[0] = (util::min(util::max(co2, 0), 5100) + 10) / 20;
// Mapping temperatures from [-10°C, 41°C] to [0, 255], with 0.2°C increment
buff[1] = static_cast<uint8_t>((util::min(util::max(temperature, -10), 41) + 10.1f) * 5);
// Mapping humidity from [0%, 100%] to [0, 200], with 0.5°C increment (0.4°C would also be possible)
buff[2] = static_cast<uint8_t>(util::min(util::max(humidity, 0) + 0.25f, 100) * 2);
Serial.print(F("LoRa - Payload : '"));
printHex2(buff[0]);
Serial.print(" ");
printHex2(buff[1]);
Serial.print(" ");
printHex2(buff[2]);
Serial.print(F("', "));
Serial.print(buff[0] * 20);
Serial.print(F(" ppm, "));
Serial.print(buff[1] * 0.2 - 10);
Serial.print(F(" °C, "));
Serial.print(buff[2] * 0.5);
Serial.println(F(" %."));
// Prepare upstream data transmission at the next possible time.
LMIC_setTxData2(1, buff, sizeof(buff), 0);
//NOTE: To decode in TheThingsNetwork:
//function Decoder(bytes, port) {
// return {
// co2: bytes[0] * 20,
// temp: bytes[1] / 5.0 - 10,
// rh: bytes[2] / 2.0
// };
//}
}
}
void preparePayloadIfTimeHasCome(const int16_t &co2, const float &temperature, const float &humidity) {
static unsigned long last_sent_at = 0;
unsigned long now = seconds();
if (connected && (now - last_sent_at > config::lorawan_sending_interval)) {
last_sent_at = now;
preparePayload(co2, temperature, humidity);
}
}
/*****************************************************************
* Callbacks for sensor commands *
*****************************************************************/
void setLoRaInterval(int32_t sending_interval) {
config::lorawan_sending_interval = sending_interval;
Serial.print(F("Setting LoRa sending interval to : "));
Serial.print(config::lorawan_sending_interval);
Serial.println("s.");
led_effects::showKITTWheel(color::green, 1);
}
}
void onEvent(ev_t ev) {
lorawan::onEvent(ev);
}
#endif
#ifndef AMPEL_LORAWAN_H_
#define AMPEL_LORAWAN_H_
#include "config.h"
#if defined(AMPEL_LORAWAN) && defined(ESP32)
#include <Arduino.h>
// Requires "MCCI LoRaWAN LMIC library", which will be automatically used with PlatformIO but should be added in "Arduino IDE".
// Tested successfully with v3.2.0 and connected to a thethingsnetwork.org app.
#include <lmic.h>
#include <hal/hal.h>
#include <arduino_lmic_hal_boards.h>
#include <SPI.h>
#include "led_effects.h"
#include "sensor_console.h"
#include "util.h"
namespace config {
extern uint16_t lorawan_sending_interval; // [s]
}
#if defined(CFG_eu868)
# define LMIC_FREQUENCY_PLAN "Europe 868"
#elif defined(CFG_us915)
# define LMIC_FREQUENCY_PLAN "US 915"
#elif defined(CFG_au915)
# define LMIC_FREQUENCY_PLAN "Australia 915"
#elif defined(CFG_as923)
# define LMIC_FREQUENCY_PLAN "Asia 923"
#elif defined(CFG_kr920)
# define LMIC_FREQUENCY_PLAN "Korea 920"
#elif defined(CFG_in866)
# define LMIC_FREQUENCY_PLAN "India 866"
#else
# error "Region should be specified"
#endif
namespace lorawan {
extern bool waiting_for_confirmation;
extern bool connected;
extern char last_transmission[];
void initialize();
void process();
void preparePayloadIfTimeHasCome(const int16_t &co2, const float &temp, const float &hum);
void setLoRaInterval(int32_t sending_interval);
}
#endif
#endif
#include "mqtt.h"
namespace config {
// Values should be defined in config.h
uint16_t mqtt_sending_interval = MQTT_SENDING_INTERVAL; // [s]
//INFO: Listen to every CO2 sensor which is connected to the server:
// mosquitto_sub -h MQTT_SERVER -t 'CO2sensors/#' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -v
const char *mqtt_server = MQTT_SERVER;
const uint16_t mqtt_port = MQTT_PORT;
const char *mqtt_user = MQTT_USER;
const char *mqtt_password = MQTT_PASSWORD;
const bool allow_mqtt_commands = ALLOW_MQTT_COMMANDS;
const unsigned long wait_after_fail = 900; // [s] Wait 15 minutes after an MQTT connection fail, before trying again.
}
#if defined(ESP32)
# include <WiFiClientSecure.h>
#endif
WiFiClientSecure espClient;
PubSubClient mqttClient(espClient);
namespace mqtt {
unsigned long last_sent_at = 0;
unsigned long last_failed_at = 0;
bool connected = false;
char publish_topic[21]; // e.g. "CO2sensors/ESPxxxxxx\0"
const char *json_sensor_format;
char last_successful_publish[23] = "";
void initialize(const char *sensorId) {
json_sensor_format = PSTR("{\"time\":\"%s\", \"co2\":%d, \"temp\":%.1f, \"rh\":%.1f}");
snprintf(publish_topic, sizeof(publish_topic), "CO2sensors/%s", sensorId);
// The sensor doesn't check the fingerprint of the MQTT broker, because otherwise this fingerprint should be updated
// on the sensor every 3 months. The connection can still be encrypted, though:
espClient.setInsecure(); // If not available for ESP32, please update Arduino IDE / PlatformIO
mqttClient.setServer(config::mqtt_server, config::mqtt_port);
sensor_console::defineIntCommand("mqtt", setMQTTinterval, F("60 (Sets MQTT sending interval, in s)"));
sensor_console::defineCommand("send_local_ip", sendInfoAboutLocalNetwork,
F("(Sends local IP and SSID via MQTT. Can be useful to find sensor)"));
}
void publish(const char *timestamp, int16_t co2, float temperature, float humidity) {
if (WiFi.status() == WL_CONNECTED && mqttClient.connected()) {
led_effects::onBoardLEDOn();
Serial.print(F("MQTT - Publishing message ... "));
char payload[75]; // Should be enough for json...
snprintf(payload, sizeof(payload), json_sensor_format, timestamp, co2, temperature, humidity);
// Topic is the same as clientID. e.g. 'CO2sensors/ESP3d03da'
if (mqttClient.publish(publish_topic, payload)) {
Serial.println(F("OK"));
ntp::getLocalTime(last_successful_publish);
} else {
Serial.println(F("Failed."));
}
led_effects::onBoardLEDOff();
}
}
/**
* Allows sensor to be controlled by commands over MQTT
*
* mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "reset"
* mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "timer 30"
* mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "mqtt 900"
* mosquitto_pub -h MQTT_SERVER -t 'CO2sensors/SENSOR_ID/control' -p 443 --capath /etc/ssl/certs/ -u "MQTT_USER" -P "MQTT_PASSWORD" -m "calibrate 700"
*/
void controlSensorCallback(char *sub_topic, byte *message, unsigned int length) {
if (length == 0) {
return;
}
led_effects::onBoardLEDOn();
Serial.print(F("Message arrived on topic: "));
Serial.println(sub_topic);
char command[length + 1];
for (unsigned int i = 0; i < length; i++) {
command[i] = message[i];
}
command[length] = 0;
sensor_console::execute(command);
led_effects::onBoardLEDOff();
}
void reconnect() {
if (last_failed_at > 0 && (seconds() - last_failed_at < config::wait_after_fail)) {
// It failed less than wait_after_fail ago. Not even trying.
return;
}
if (WiFi.status() != WL_CONNECTED) { //NOTE: Sadly, WiFi.status is sometimes WL_CONNECTED even though it's really not
// No WIFI
return;
}
Serial.print(F("MQTT - Attempting connection..."));
led_effects::onBoardLEDOn();
// Wait for connection, at most 15s (default)
mqttClient.connect(publish_topic, config::mqtt_user, config::mqtt_password);
led_effects::onBoardLEDOff();
connected = mqttClient.connected();
if (connected) {
if (config::allow_mqtt_commands) {
char control_topic[60]; // Should be enough for "CO2sensors/ESPd03cc5/control"
snprintf(control_topic, sizeof(control_topic), "%s/control", publish_topic);
mqttClient.subscribe(control_topic);
mqttClient.setCallback(controlSensorCallback);
}
Serial.println(F(" Connected."));
last_failed_at = 0;
} else {
last_failed_at = seconds();
Serial.print(F(" Failed! Error code="));
Serial.print(mqttClient.state());
Serial.print(F(". Will try again in "));
Serial.print(config::wait_after_fail);
Serial.println("s.");
}
}
void publishIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temp, const float &hum) {
// Send message via MQTT according to sending interval
unsigned long now = seconds();
if (now - last_sent_at > config::mqtt_sending_interval) {
last_sent_at = now;
publish(timestamp, co2, temp, hum);
}
}
void keepConnection() {
// Keep MQTT connection
if (!mqttClient.connected()) {
reconnect();
}
mqttClient.loop();
}
/*****************************************************************
* Callbacks for sensor commands *
*****************************************************************/
void setMQTTinterval(int32_t sending_interval) {
config::mqtt_sending_interval = sending_interval;
Serial.print(F("Setting MQTT sending interval to : "));
Serial.print(config::mqtt_sending_interval);
Serial.println("s.");
led_effects::showKITTWheel(color::green, 1);
}
// It can be hard to find the local IP of a sensor if it isn't connected to Serial port, and if mDNS is disabled.
// If the sensor can be reach by MQTT, it can answer with info about local_ip and ssid.
// The sensor will send the info to "CO2sensors/ESP123456/info".
void sendInfoAboutLocalNetwork() {
char info_topic[60]; // Should be enough for "CO2sensors/ESP123456/info"
snprintf(info_topic, sizeof(info_topic), "%s/info", publish_topic);
char payload[75]; // Should be enough for info json...
const char *json_info_format = PSTR("{\"local_ip\":\"%s\", \"ssid\":\"%s\"}");
snprintf(payload, sizeof(payload), json_info_format, wifi::local_ip, WIFI_SSID);
mqttClient.publish(info_topic, payload);
}
}
#ifndef MQTT_H_INCLUDED
#define MQTT_H_INCLUDED
#include <Arduino.h>
#include "config.h"
#include "led_effects.h"
#include "sensor_console.h"
#include "src/lib/PubSubClient/src/PubSubClient.h"
#include "wifi_util.h"
namespace config {
extern uint16_t mqtt_sending_interval; // [s]
}
namespace mqtt {
extern char last_successful_publish[];
extern bool connected;
void initialize(const char *sensorId);
void keepConnection();
void publishIfTimeHasCome(const char *timestamp, const int16_t &co2, const float &temp, const float &hum);
void setMQTTinterval(int32_t sending_interval);
void sendInfoAboutLocalNetwork();
}
#endif
#include "sensor_console.h"
namespace sensor_console {
const uint8_t MAX_COMMANDS = 20;
const uint8_t MAX_COMMAND_SIZE = 30;
uint8_t commands_count = 0;
enum input_type {
NONE,
INT32,
STRING
};
struct Command {
const char *name;
union {
void (*voidFunction)();
void (*intFunction)(int32_t);
void (*strFunction)(char*);
};
const char *doc;
input_type parameter_type;
};
struct CommandLine {
char function_name[MAX_COMMAND_SIZE];
input_type argument_type;
int32_t int_argument;
char str_argument[MAX_COMMAND_SIZE];
};
Command commands[MAX_COMMANDS];
bool addCommand(const char *name, const __FlashStringHelper *doc_fstring) {
if (commands_count < MAX_COMMANDS) {
commands[commands_count].name = name;
commands[commands_count].doc = (const char*) doc_fstring;
return true;
} else {
Serial.println(F("Too many commands have been defined."));
return false;
}
}
void defineCommand(const char *name, void (*function)(), const __FlashStringHelper *doc_fstring) {
if (addCommand(name, doc_fstring)) {
commands[commands_count].voidFunction = function;
commands[commands_count++].parameter_type = NONE;
}
}
void defineIntCommand(const char *name, void (*function)(int32_t), const __FlashStringHelper *doc_fstring) {
if (addCommand(name, doc_fstring)) {
commands[commands_count].intFunction = function;
commands[commands_count++].parameter_type = INT32;
}
}
void defineStringCommand(const char *name, void (*function)(char*), const __FlashStringHelper *doc_fstring) {
if (addCommand(name, doc_fstring)) {
commands[commands_count].strFunction = function;
commands[commands_count++].parameter_type = STRING;
}
}
/*
* Tries to split a string command (e.g. 'mqtt 60' or 'show_csv') into
* a CommandLine struct (function_name, argument_type and argument)
*/
void parseCommand(const char *command, CommandLine &command_line) {
if (strlen(command) == 0) {
Serial.println(F("Received empty command"));
command_line.argument_type = NONE;
return;
}
char *first_space;
first_space = strchr(command, ' ');
if (first_space == NULL) {
command_line.argument_type = NONE;
strlcpy(command_line.function_name, command, MAX_COMMAND_SIZE);
return;
}
strlcpy(command_line.function_name, command, first_space - command + 1);
strlcpy(command_line.str_argument, first_space + 1, MAX_COMMAND_SIZE - (first_space - command) - 1);
char *end;
command_line.int_argument = strtol(command_line.str_argument, &end, 0); // Accepts 123 or 0xFF00FF
if (*end) {
command_line.argument_type = STRING;
} else {
command_line.argument_type = INT32;
}
}
int compareCommandNames(const void *s1, const void *s2) {
struct Command *c1 = (struct Command*) s1;
struct Command *c2 = (struct Command*) s2;
return strcmp(c1->name, c2->name);
}
void listAvailableCommands() {
qsort(commands, commands_count, sizeof(commands[0]), compareCommandNames);
for (uint8_t i = 0; i < commands_count; i++) {
Serial.print(F(" "));
Serial.print(commands[i].name);
Serial.print(F(" "));
Serial.print(commands[i].doc);
Serial.println(F("."));
}
}
/*
* Saves bytes from Serial.read() until enter is pressed, and tries to run the corresponding command.
* http://www.gammon.com.au/serial
*/
void processSerialInput(const byte input_byte) {
static char input_line[MAX_COMMAND_SIZE];
static unsigned int input_pos = 0;
switch (input_byte) {
case '\n': // end of text
Serial.println();
input_line[input_pos] = 0;
execute(input_line);
input_pos = 0;
break;
case '\r': // discard carriage return
break;
case '\b': // backspace
if (input_pos > 0) {
input_pos--;
Serial.print(F("\b \b"));
}
break;
default:
if (input_pos == 0) {
Serial.print(F("> "));
}
// keep adding if not full ... allow for terminating null byte
if (input_pos < (MAX_COMMAND_SIZE - 1)) {
input_line[input_pos++] = input_byte;
Serial.print((char) input_byte);
}
break;
}
}
/*
* Tries to find the corresponding callback for a given command. Name and parameter type should fit.
*/
void execute(const char *command_str) {
CommandLine input;
parseCommand(command_str, input);
for (uint8_t i = 0; i < commands_count; i++) {
if (!strcmp(input.function_name, commands[i].name) && input.argument_type == commands[i].parameter_type) {
Serial.print(F("Calling : "));
Serial.print(input.function_name);
switch (input.argument_type) {
case NONE:
Serial.println(F("()"));
commands[i].voidFunction();
return;
case INT32:
Serial.print(F("("));
Serial.print(input.int_argument);
Serial.println(F(")"));
commands[i].intFunction(input.int_argument);
return;
case STRING:
Serial.print(F("('"));
Serial.print(input.str_argument);
Serial.println(F("')"));
commands[i].strFunction(input.str_argument);
return;
}
}
}
Serial.print(F("'"));
Serial.print(command_str);
Serial.println(F("' not supported. Available commands :"));
listAvailableCommands();
}
}
#ifndef SENSOR_CONSOLE_H_INCLUDED
#define SENSOR_CONSOLE_H_INCLUDED
#include <Arduino.h>
/** Other scripts can use this namespace, in order to define commands, via callbacks.
* Those callbacks can then be used to send commands to the sensor (reset, calibrate, night mode, ...)
* The callbacks can either have no parameter, or one int32_t parameter.
*/
namespace sensor_console {
void defineCommand(const char *name, void (*function)(), const __FlashStringHelper *doc_fstring);
void defineIntCommand(const char *name, void (*function)(int32_t), const __FlashStringHelper *doc_fstring);
void defineStringCommand(const char *name, void (*function)(char*), const __FlashStringHelper *doc_fstring);
void processSerialInput(const byte in_byte);
void execute(const char *command_line);
}
#endif
language: c
sudo: false
before_install:
- source <(curl -SLs https://raw.githubusercontent.com/adafruit/travis-ci-arduino/master/install.sh)
script:
- build_platform esp8266
notifications:
email:
on_success: change
on_failure: change
NTPClient 3.1.0 - 2016.05.31
* Added functions for changing the timeOffset and updateInterval later. Thanks @SirUli
NTPClient 3.0.0 - 2016.04.19
* Constructors now require UDP instance argument, to add support for non-ESP8266 boards
* Added optional begin API to override default local port
* Added end API to close UDP socket
* Changed return type of update and forceUpdate APIs to bool, and return success or failure
* Change return type of getDay, getHours, getMinutes, and getSeconds to int
Older
* Changes not recorded
/**
* The MIT License (MIT)
* Copyright (c) 2015 by Fabrice Weinberg
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "NTPClient.h"
NTPClient::NTPClient(UDP& udp) {
this->_udp = &udp;
}
NTPClient::NTPClient(UDP& udp, int timeOffset) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName) {
this->_udp = &udp;
this->_poolServerName = poolServerName;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName, int timeOffset) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerName = poolServerName;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName, int timeOffset, unsigned long updateInterval) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerName = poolServerName;
this->_updateInterval = updateInterval;
}
void NTPClient::begin() {
this->begin(NTP_DEFAULT_LOCAL_PORT);
}
void NTPClient::begin(int port) {
this->_port = port;
this->_udp->begin(this->_port);
this->_udpSetup = true;
}
bool NTPClient::isValid(byte * ntpPacket)
{
//Perform a few validity checks on the packet
if((ntpPacket[0] & 0b11000000) == 0b11000000) //Check for LI=UNSYNC
return false;
if((ntpPacket[0] & 0b00111000) >> 3 < 0b100) //Check for Version >= 4
return false;
if((ntpPacket[0] & 0b00000111) != 0b100) //Check for Mode == Server
return false;
if((ntpPacket[1] < 1) || (ntpPacket[1] > 15)) //Check for valid Stratum
return false;
if( ntpPacket[16] == 0 && ntpPacket[17] == 0 &&
ntpPacket[18] == 0 && ntpPacket[19] == 0 &&
ntpPacket[20] == 0 && ntpPacket[21] == 0 &&
ntpPacket[22] == 0 && ntpPacket[22] == 0) //Check for ReferenceTimestamp != 0
return false;
return true;
}
bool NTPClient::forceUpdate() {
#ifdef DEBUG_NTPClient
Serial.println("Update from NTP Server");
#endif
// flush any existing packets
while(this->_udp->parsePacket() != 0)
this->_udp->flush();
this->sendNTPPacket();
// Wait till data is there or timeout...
byte timeout = 0;
int cb = 0;
do {
delay ( 10 );
cb = this->_udp->parsePacket();
if(cb > 0)
{
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
if(!this->isValid(this->_packetBuffer))
cb = 0;
}
if (timeout > 100) return false; // timeout after 1000 ms
timeout++;
} while (cb == 0);
this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
this->_currentEpoc = secsSince1900 - SEVENZYYEARS;
return true;
}
bool NTPClient::update() {
if ((millis() - this->_lastUpdate >= this->_updateInterval) // Update after _updateInterval
|| this->_lastUpdate == 0) { // Update if there was no update yet.
if (!this->_udpSetup) this->begin(); // setup the UDP client if needed
return this->forceUpdate();
}
return true;
}
unsigned long NTPClient::getEpochTime() {
return this->_timeOffset + // User offset
this->_currentEpoc + // Epoc returned by the NTP server
((millis() - this->_lastUpdate) / 1000); // Time since last update
}
int NTPClient::getDay() {
return (((this->getEpochTime() / 86400L) + 4 ) % 7); //0 is Sunday
}
int NTPClient::getHours() {
return ((this->getEpochTime() % 86400L) / 3600);
}
int NTPClient::getMinutes() {
return ((this->getEpochTime() % 3600) / 60);
}
int NTPClient::getSeconds() {
return (this->getEpochTime() % 60);
}
void NTPClient::getFormattedTime(char *formatted_time, unsigned long secs) {
unsigned long rawTime = secs ? secs : this->getEpochTime();
unsigned int hours = (rawTime % 86400L) / 3600;
unsigned int minutes = (rawTime % 3600) / 60;
unsigned int seconds = rawTime % 60;
snprintf(formatted_time, 9, "%02d:%02d:%02d", hours, minutes, seconds);
}
// Based on https://github.com/PaulStoffregen/Time/blob/master/Time.cpp
void NTPClient::getFormattedDate(char *formatted_date, unsigned long secs) {
unsigned long rawTime = (secs ? secs : this->getEpochTime()) / 86400L; // in days
unsigned long days = 0, year = 1970;
uint8_t month;
static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};
while((days += (LEAP_YEAR(year) ? 366 : 365)) <= rawTime)
year++;
rawTime -= days - (LEAP_YEAR(year) ? 366 : 365); // now it is days in this year, starting at 0
days=0;
for (month=0; month<12; month++) {
uint8_t monthLength;
if (month==1) { // february
monthLength = LEAP_YEAR(year) ? 29 : 28;
} else {
monthLength = monthDays[month];
}
if (rawTime < monthLength) break;
rawTime -= monthLength;
}
month++; // jan is month 1
rawTime++; // first day is day 1
char formatted_time[9];
this->getFormattedTime(formatted_time, secs);
snprintf(formatted_date, 23, "%4lu-%02d-%02lu %s%+03d", year, month, rawTime, formatted_time, this->_timeOffset / 3600);
}
void NTPClient::end() {
this->_udp->stop();
this->_udpSetup = false;
}
void NTPClient::setTimeOffset(int timeOffset) {
this->_timeOffset = timeOffset;
}
void NTPClient::setUpdateInterval(unsigned long updateInterval) {
this->_updateInterval = updateInterval;
}
void NTPClient::sendNTPPacket() {
// set all bytes in the buffer to 0
memset(this->_packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
this->_packetBuffer[0] = 0b11100011; // LI, Version, Mode
this->_packetBuffer[1] = 0; // Stratum, or type of clock
this->_packetBuffer[2] = 6; // Polling Interval
this->_packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
this->_packetBuffer[12] = 0x49;
this->_packetBuffer[13] = 0x4E;
this->_packetBuffer[14] = 0x49;
this->_packetBuffer[15] = 0x52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
this->_udp->beginPacket(this->_poolServerName, 123); //NTP requests are to port 123
this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
this->_udp->endPacket();
}
void NTPClient::setEpochTime(unsigned long secs) {
this->_currentEpoc = secs;
}
#pragma once
#include "Arduino.h"
#include <Udp.h>
#define SEVENZYYEARS 2208988800UL
#define NTP_PACKET_SIZE 48
#define NTP_DEFAULT_LOCAL_PORT 1337
#define LEAP_YEAR(Y) ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) ) )
class NTPClient {
private:
UDP* _udp;
bool _udpSetup = false;
const char* _poolServerName = "pool.ntp.org"; // Default time server
int _port = NTP_DEFAULT_LOCAL_PORT;
int _timeOffset = 0;
unsigned long _updateInterval = 60000; // In ms
unsigned long _currentEpoc = 0; // In s
unsigned long _lastUpdate = 0; // In ms
byte _packetBuffer[NTP_PACKET_SIZE];
void sendNTPPacket();
bool isValid(byte * ntpPacket);
public:
NTPClient(UDP& udp);
NTPClient(UDP& udp, int timeOffset);
NTPClient(UDP& udp, const char* poolServerName);
NTPClient(UDP& udp, const char* poolServerName, int timeOffset);
NTPClient(UDP& udp, const char* poolServerName, int timeOffset, unsigned long updateInterval);
/**
* Starts the underlying UDP client with the default local port
*/
void begin();
/**
* Starts the underlying UDP client with the specified local port
*/
void begin(int port);
/**
* This should be called in the main loop of your application. By default an update from the NTP Server is only
* made every 60 seconds. This can be configured in the NTPClient constructor.
*
* @return true on success, false on failure
*/
bool update();
/**
* This will force the update from the NTP Server.
*
* @return true on success, false on failure
*/
bool forceUpdate();
int getDay();
int getHours();
int getMinutes();
int getSeconds();
/**
* Changes the time offset. Useful for changing timezones dynamically
*/
void setTimeOffset(int timeOffset);
/**
* Set the update interval to another frequency. E.g. useful when the
* timeOffset should not be set in the constructor
*/
void setUpdateInterval(unsigned long updateInterval);
/**
* @return secs argument (or 0 for current time) formatted like `hh:mm:ss`
*/
void getFormattedTime(char *formatted_time, unsigned long secs = 0);
/**
* @return time in seconds since Jan. 1, 1970
*/
unsigned long getEpochTime();
/**
* @return secs argument (or 0 for current date) formatted to ISO 8601
* like `2004-02-12T15:19:21+00:00`
*/
void getFormattedDate(char *formatted_date, unsigned long secs = 0);
/**
* Stops the underlying UDP client
*/
void end();
/**
* Replace the NTP-fetched time with seconds since Jan. 1, 1970
*/
void setEpochTime(unsigned long secs);
};
# NTPClient
[![Build Status](https://travis-ci.org/arduino-libraries/NTPClient.svg?branch=master)](https://travis-ci.org/arduino-libraries/NTPClient)
Connect to a NTP server, here is how:
```cpp
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>
const char *ssid = "<SSID>";
const char *password = "<PASSWORD>";
WiFiUDP ntpUDP;
// By default 'pool.ntp.org' is used with 60 seconds update interval and
// no offset
NTPClient timeClient(ntpUDP);
// You can specify the time server pool and the offset, (in seconds)
// additionaly you can specify the update interval (in milliseconds).
// NTPClient timeClient(ntpUDP, "europe.pool.ntp.org", 3600, 60000);
void setup(){
Serial.begin(115200);
WiFi.begin(ssid, password);
while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}
timeClient.begin();
}
void loop() {
timeClient.update();
Serial.println(timeClient.getFormattedTime());
delay(1000);
}
```
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment