Merge pull request 'feature/http_call_send_json' (#3) from feature/http_call_send_json into master

Reviewed-on: #3
master
Aaron Fischer 6 months ago
commit 097623dcfc

1
.gitignore vendored

@ -4,3 +4,4 @@ firmware/.DS_Store
schematics/#auto_saved_files#
schematics/_autosave-oko-weatherstation.sch
firmware.ino.bin
firmware/extract me in arduino libraries folder.zip

@ -0,0 +1,20 @@
{
"configurations": [
{
"name": "Mac",
"includePath": [
"${workspaceFolder}/**",
"/Users/klaute/Documents/Arduino/libraries"
],
"defines": [],
"macFrameworkPath": [
"/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/System/Library/Frameworks"
],
"compilerPath": "/usr/bin/clang",
"cStandard": "c17",
"cppStandard": "c++17",
"intelliSenseMode": "macos-clang-arm64"
}
],
"version": 4
}

@ -3,18 +3,21 @@
// config general setting and behavior of the weatherstation
#define WIFI_AUTOCONNECT_TIMEOUT_S 120
#define WIFI_AUTOCONNECT_TIMEOUT_S 60
#define WIFI_CONFIG_PORTAL_TIMEOUT_S 120
#define UPDATE_SENSOR_INTERVAL_S 300
#define UPDATE_WEBSERVER_INTVERVAL_S 1 // Do not change, bigger values will prevent using webupdater webinterface
#define DELAY_LOOP_MS 50
#define UPDATE_WEBSERVER_INTVERVAL_MS 500 // Values greater than 1000 will negative affect availability of the webinterface
#define DELAY_LOOP_MS 100
#define POWERSAVING_SLEEP_S 600
#define EMERGENCY_SLEEP_S 172800 // Sleep for 2 days to recover
#define RESET_ESP_TIME_INTERVAL_MS (60*60*3*1000) // (60*60*6*1000) // reset every 3 hours
#define RESET_ESP_TIME_INTERVAL_MS (60*60*12*1000) // reset every 12 hours
#define WIND_SENSOR_MEAS_TIME_S 15
#define INITIAL_WEBSERVER_TIME 20
#define WATCHDOG_TIMEOUT_MS 30000
#define WIFI_CHECK_INTERVAL_MS 120000
#define INFLUXDB_TIMEOUT_MS 1000
#define ENERGY_SAVING_ITERATIONS 30
#define WIFI_MINIMUM_SIGNAL_QUALITY 10 // percent
#define BAT_LOW_VOLTAGE 3.6
@ -39,6 +42,10 @@
#define BME_CS 10
#define BME_ADDRESS 0x76
#define BMP_ADDRESS 0x76
#define SERIAL_BAUD_RATE 115200
#define WEB_UPDATER_HTTP_PORT 8080
#endif

@ -1,6 +1,5 @@
// Copy this file to config_user.h and adjust it to your needs.
#ifndef __CONFIG_USER_H__
#define __CONFIG_USER_H__
@ -12,35 +11,59 @@
// maybe have a TOO LONG SSID!
String DEVICE_NAME = "weatherstation";
// Enable/Disable features
//#define WEBUPDATER_FEATURE
/********************************************************************************/
// Enable/Disable general features
#define BATTERY_POWERED
// retries to connect after 5 seconds or starts the wifimanager
//#define SLEEP_IF_NO_WLAN_CONNECTION
#define INFLUXDB_FEATURE
#define INFLUXDB_VERSION 1 // 1 or 2
#define SERIAL_FEATURE
//#define BATTERY_POWERED
//#define SENSOR_WIND
//#define LOG_MILLIS_TO_INFLUXDB
//#define SERIAL_FEATURE
#define SENSOR_WIND
#define SENSOR_APDS9960
//#define SENSOR_APDS9930
#define SENSOR_BME280
//#define SENSOR_BMP280
#define SENSOR_BATTERY
//#define BAT_PINS_D34
// Homebridge Webstat is only possible if webupdater is also enabled
//#define HOMEBRIDGE_WEBSTAT
// retries to connect after 5 seconds or starts the wifimanager
#define SLEEP_IF_NO_WLAN_CONNECTION
/********************************************************************************/
// not available or recommended for battery mode
/********************************************************************************/
//#define DISABLE_WIFIMANAGER
// Restarts the firmware every n seconds
//#define RESET_ESP_TIMEINTERVAL // BETA STATUS
//#define HTTP_CALL_ON_WINDSPEED_EXCEED // BETA STATUS
//#define DEBUG_WINDSPEED_MEASUREMENT // for debugging windspeed measurement only
//#define LOG_MILLIS_TO_INFLUXDB
//#define RESET_ESP_TIME_INTERVAL
//#define ENABLE_WATCHDOG
//#define WATCHDOG_TIMEOUT_MS 30000
//#define WEBUPDATER_FEATURE
// only available in case that webupdater is enabled
//#define USE_LOGGER
// only possible if webupdater is also enabled
//#define HOMEBRIDGE_WEBSTAT
// for debugging windspeed measurement only, trigger and results are handled by webupdater
//#define DEBUG_WINDSPEED_MEASUREMENT
//#define HTTP_CALL_ON_WINDSPEED_EXCEED
//#define HTTP_CALL_SEND_JSON_DATA
//#define SHOW_SENSOR_DATA_ON_WEBUPDATER_MAIN_PAGE
/********************************************************************************/
// measurement correction factors
const float HUMIDITY_FACTOR = 1.0;
const float LIGHT_FACTOR = 1.0;
const float TEMP_FACTOR = 1.0;
// InfluxDB credentials
/********************************************************************************/
// InfluxDB1 credentials
const char *INFLUXDB_HOST = "hostname";
const uint16_t INFLUXDB_PORT = 80;
const char *INFLUXDB_DB = "database";
@ -53,13 +76,17 @@ const char *INFLUXDB_URL = "http://192.168.0.123:3124";
const char *INFLUXDB_ORG = "home_org";
const char *INFLUXDB_BUCKET = "mybucket";
const char *INFLUXDB_TOKEN = "your api token";
*/
/********************************************************************************/
// enable HTTP_CALL_ON_WINDSPEED_EXCEED to enable this feature
#define HTTP_CALL_ON_WINDSPEED_EXCEED_MPS 5.0 // 5.0 m/s == 18 km/h
#define HTTP_CALL_ON_WINDSPEED_INTERVAL_S 60 // it's required to be bigger than WIND_SENSOR_MEAS_TIME_S
#define HTTP_CALL_ON_WINDSPEED_URL "http://192.168.178.100:3001/button-windspeedexceed?event=click"
#define HTTP_CALL_SEND_JSON_DATA_INTERVAL_S 300
#define HTTP_CALL_SEND_JSON_DATA_URL "http://192.168.178.123:80/html/index.html?json_weather_data="
// anemometer settings
// thingiverse anemometer settings: https://www.thingiverse.com/thing:2559929/files
#define ROTOR_LENGTH_CM 8.25
@ -76,5 +103,20 @@ const char *INFLUXDB_TOKEN = "your api token";
// china aliexpress anemometer settings (calculation unknown) <add link here>
//#define WINDSPEED_FACTOR 2.4
/********************************************************************************/
#ifdef DISABLE_WIFIMANAGER
// Set your Static IP address
IPAddress local_IP(192, 168, 178, 123);
// Set your Gateway IP address
IPAddress gateway(192, 168, 178, 1);
// Set subnet mask
IPAddress subnet(255, 255, 255, 0);
#define WIFI_SSID "myWifi" // WLAN Netzwerk
#define WIFI_PASSWD "myPass" // WLAN Passwort
#endif
/********************************************************************************/
#endif

@ -18,4 +18,27 @@
#define ENERGY_SAVE_MODE_ENABLED 1.0
#define ENERGY_SAVE_MODE_DISABLED 0.0
#define FSM_STATE_1 0
#define FSM_STATE_2 1
#define FSM_STATE_3 2
#define FSM_STATE_4 3
#define FSM_STATE_5 4
#define FSM_STATE_6 5
#define FSM_STATE_7 6
#define FSM_STATE_8 7
#define FSM_STATE_9 8
#define FSM_STATE_10 9
#define FSM_STATE_11 10
#define FSM_STATE_12 11
const String hb_ws_msg_start = "{";
const String hb_ws_msg_temp = "\"temperature\": ";
const String hb_ws_msg_humi = "\"humidity\": ";
const String hb_ws_msg_light = "\"lightlevel\": ";
const String hb_ws_msg_windspeed = "\"windspeed\": ";
const String hb_ws_msg_pressure = "\"pressure\": ";
const String hb_ws_msg_timestamp = "\"timestamp\": ";
const String hb_ws_msg_valid = "\"valid\": ";
const String hb_ws_msg_end = "}";
#endif

@ -1,19 +1,27 @@
// Standard ESP8266 libs from project folder
#include <ESP8266mDNS.h>
#include <ESP8266HTTPUpdateServer.h>
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h> // WiFiClient
#include <WiFiManager.h> // WiFiManager from bib manager
// Project includes
#include "constants.h"
#include "config.h"
#include "config_user.h"
#ifndef DISABLE_WIFIMANAGER
#include <WiFiManager.h> // WiFiManager from bib manager
#endif
#ifdef HTTP_CALL_ON_WINDSPEED_EXCEED
#include <ESP8266HTTPClient.h>
#endif
#ifdef HTTP_CALL_SEND_JSON_DATA
#include <ESP8266HTTPClient.h>
#include <UrlEncode.h> // from bib manager UrlEncode by Masayuki
#endif
//*************************************************************************//
// check if some settings are correct
@ -26,42 +34,61 @@
//*************************************************************************//
// constant variables
const uint8_t VALUES = 8; // see constants.h file - count of number of SENSOR_ defines
float currentSensorData[VALUES] = {nanf("no value"), nanf("no value"), nanf("no value"), nanf("no value"), nanf("no value"), nanf("no value"), nanf("no value"), nanf("no value")};
float (*sensors[VALUES])() = {};
const uint8_t VALUES = 8; // see constants.h file - count of number of SENSOR_ defines
float currentSensorData[VALUES] = { nanf("no value"), nanf("no value"), nanf("no value"),
nanf("no value"), nanf("no value"), nanf("no value"),
nanf("no value"), nanf("no value") };
uint16_t update_sensor_cnt = 0;
uint16_t update_webserver_cnt = 0;
uint16_t update_windspeed_exceed_cnt = 0;
uint32_t update_sensor_cnt = 0;
uint32_t update_webserver_cnt = 0;
uint32_t update_windspeed_exceed_cnt = 0;
uint32_t wifi_check_interval_counter = 0;
uint32_t http_call_send_json_data_cnt = 0;
boolean validData = false;
#ifndef DISABLE_WIFIMANAGER
const String wifiName = "oko-weather-" + DEVICE_NAME;
WiFiManager wifiManager;
#endif
uint8_t fsm_state = FSM_STATE_1;
uint8_t sensor_cnt = 0;
boolean validData = false;
boolean do_not_read_windsensor = false;
uint32_t wifi_reconnect_cnt = 0;
//*************************************************************************//
void debug(String x)
{
void debug(String x) {
#ifdef DEBUG
Serial.println(x);
#endif
#ifdef USE_LOGGER
logdata(String(millis()) + ":" + x);
#endif
}
void setup()
{
//*************************************************************************//
void setup() {
#if defined(DEBUG) || defined(SERIAL_FEATURE)
Serial.begin(115200);
Serial.begin(SERIAL_BAUD_RATE);
#endif
// Pin settings
pinMode(BAT_CHARGED_PIN, INPUT);
pinMode(BAT_CHARGING_PIN, INPUT);
pinMode(STATUS_LED_PIN, OUTPUT);
pinMode(ANEMOMETER_PIN, INPUT_PULLUP);
pinMode(A0, INPUT);
pinMode(BAT_CHARGED_PIN, INPUT);
pinMode(BAT_CHARGING_PIN, INPUT);
pinMode(STATUS_LED_PIN, OUTPUT);
pinMode(ANEMOMETER_PIN, INPUT_PULLUP);
pinMode(A0, INPUT);
digitalWrite(STATUS_LED_PIN, LOW);
digitalWrite(STATUS_LED_PIN, HIGH);
#ifndef BAT_PINS_D34
debug("D5 D6 used as battery pins");
@ -73,85 +100,200 @@ void setup()
criticalBatCheck();
#endif
wifiConnectionCheck();
wifiConnect();
debug("Connected!");
initWifiBasedSW();
initSensors();
//It's magic! leave in
delay(100);
#ifdef BATTERY_POWERED
debug("battery powered");
_battery_mode_main();
digitalWrite(STATUS_LED_PIN, HIGH);
criticalBatCheck();
WiFi.mode(WIFI_OFF);
WiFi.forceSleepBegin();
debug("deep sleep");
// the ESP.deepSleep requires microseconds as input, after the
// sleep the system will run into the setup routine
ESP.deepSleep(POWERSAVING_SLEEP_S * 1000000, WAKE_RF_DEFAULT);
delay(100);
#else // not in battery mode
#ifdef ENABLE_WATCHDOG
// Enable the internal watchdog
ESP.wdtEnable(WATCHDOG_TIMEOUT_MS);
#endif
#endif
}
//*************************************************************************//
void initWifiBasedSW() {
#ifdef INFLUXDB_FEATURE
influxdb_begin();
#endif
#ifdef WEBUPDATER_FEATURE
#ifndef BATTERY_POWERED
setupWebUpdater(DEVICE_NAME, WiFi.localIP().toString());
#endif
#endif
}
//*************************************************************************//
void initSensors() {
// Initialize and configure the sensors
#ifdef SENSOR_APDS9930
if (sensor_apds9930_begin()) {
sensors[SENSOR_LIGHT] = &apds9930_light;
}
if (sensor_apds9930_begin();
#endif
#ifdef SENSOR_APDS9960
if (sensor_apds9960_begin()) {
sensors[SENSOR_LIGHT] = &apds9960_light;
}
sensor_apds9960_begin();
#endif
#ifdef SENSOR_BME280
//Temperature + pressure
if (sensor_bme280_begin(BME_ADDRESS)) {
sensors[SENSOR_TEMPERATURE] = &bme280_temperature;
sensors[SENSOR_HUMIDITY] = &bme280_humidity;
sensors[SENSOR_PRESSURE] = &bme280_pressure;
}
//Temperature + pressure + humidity
sensor_bme280_begin(BME_ADDRESS);
#endif
#ifdef SENSOR_BMP280
//Temperature + pressure + humidity
sensor_bmp280_begin(BMP_ADDRESS);
#endif
}
//*************************************************************************//
float readSensors(uint8_t s) {
float ret = nan("no value");
switch (s) {
case SENSOR_LIGHT: // Initialize and configure the sensors
#ifdef SENSOR_APDS9930
ret = apds9930_light();
#endif
#ifdef SENSOR_APDS9960
ret = apds9960_light();
#endif
break;
case SENSOR_TEMPERATURE:
#ifdef SENSOR_BME280
ret = bme280_temperature();
#endif
#ifdef SENSOR_BMP280
ret = bmp280_temperature();
#endif
break;
case SENSOR_HUMIDITY:
#ifdef SENSOR_BME280
ret = bme280_humidity();
#endif
break;
case SENSOR_PRESSURE:
#ifdef SENSOR_BME280
ret = bme280_pressure();
#endif
#ifdef SENSOR_BMP280
ret = bmp280_pressure();
#endif
break;
case SENSOR_WINDSPEED:
#ifdef SENSOR_WIND
sensors[SENSOR_WINDSPEED] = &wind_speed;
if (do_not_read_windsensor == false) {
ret = wind_speed();
}
#endif
break;
case SENSOR_BAT_VOLTAGE:
#ifdef SENSOR_BATTERY
sensors[SENSOR_BAT_VOLTAGE] = &battery_voltage;
sensors[SENSOR_BATCHARGESTATE] = &battery_charging;
sensors[SENSOR_ESAVEMODE] = &isEnergySavingMode;
ret = battery_voltage();
#endif
break;
#ifdef WEBUPDATER_FEATURE
#ifndef BATTERY_POWERED
setupWebUpdater(DEVICE_NAME, WiFi.localIP().toString());
case SENSOR_ESAVEMODE:
#ifdef SENSOR_BATTERY
ret = battery_charging();
#endif
break;
case SENSOR_BATCHARGESTATE:
#ifdef SENSOR_BATTERY
ret = isEnergySavingMode();
#endif
break;
//It's magic! leave in
delay(100);
default:
break;
}
#ifdef BATTERY_POWERED
debug("battery powered");
_loop();
return ret;
}
digitalWrite(STATUS_LED_PIN, LOW);
//*************************************************************************//
criticalBatCheck();
void wifiConnectionCheck() {
WiFi.mode(WIFI_OFF);
WiFi.forceSleepBegin();
if ((wifi_check_interval_counter + WIFI_CHECK_INTERVAL_MS) > millis()) {
// if check interval is not exceeded abort check
return;
}
debug("deep sleep");
wifi_check_interval_counter = millis();
// the ESP.deepSleep requires microseconds as input, after the sleep the system will run into the setup routine
ESP.deepSleep(POWERSAVING_SLEEP_S * 1000000, WAKE_RF_DEFAULT);
delay(100);
#endif
if (WiFi.status() == WL_CONNECTED) {
// if we are connected
return;
}
#ifdef ENABLE_WATCHDOG
// Enable the internal watchdog
ESP.wdtEnable(WATCHDOG_TIMEOUT_MS);
wifi_reconnect_cnt++;
debug("no wifi connection, try to reconnect " + String(wifi_reconnect_cnt));
WiFi.disconnect();
WiFi.mode(WIFI_OFF);
WiFi.mode(WIFI_STA);
#ifdef WEBUPDATER_FEATURE
setWifiReconnectCnt(wifi_reconnect_cnt);
#endif
if (wifi_reconnect_cnt >= 5) {
debug("\nReboot");
ESP.restart();
} else {
wifiConnect();
//initWifiBasedSW();
}
}
//*************************************************************************//
void wifiConnectionCheck()
{
// Establish WiFi connection
String wifiName = "oko-weather-" + DEVICE_NAME;
void wifiConnect() {
// Establish WiFi connection if not already applied
#ifndef DISABLE_WIFIMANAGER
wifiManager.setMinimumSignalQuality(WIFI_MINIMUM_SIGNAL_QUALITY);
// the time in seconds to wait for the known wifi connection
@ -159,95 +301,297 @@ void wifiConnectionCheck()
// the time in seconds to wait for the user to configure the device
wifiManager.setTimeout(WIFI_CONFIG_PORTAL_TIMEOUT_S);
while (!wifiManager.autoConnect(wifiName.c_str(), "DEADBEEF"))
{
debug("WiFi connection failed, try again in 5 seconds...");
// If autoconnect to WLAN failed and no client connected, go to deep sleep
while (!wifiManager.autoConnect(wifiName.c_str(), "DEADBEEF")) {
#ifdef SLEEP_IF_NO_WLAN_CONNECTION
// If autoconnect to WLAN failed and no client connected, go to deep sleep
ESP.deepSleep(POWERSAVING_SLEEP_S * 1000000, WAKE_RF_DEFAULT);
delay(100);
#endif
#ifndef SLEEP_IF_NO_WLAN_CONNECTION
// sleep a few seconds and go on trying to connect
debug("WiFi connection failed, try again in 5 seconds...");
delay(5000);
#endif
}
#else // DISABLE_WIFIMANAGER
if (!WiFi.config(local_IP, gateway, subnet)) {
debug("Failed to set IP configuration");
} else {
debug("Successful set IP configuration");
}
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
debug("Connecting to WLAN");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
}
#endif // DISABLE_WIFIMANAGER
}
//*************************************************************************//
#ifdef BATTERY_POWERED
void criticalBatCheck()
{
void criticalBatCheck() {
float volt = battery_voltage();
if (volt <= BAT_EMERGENCY_DEEPSLEEP_VOLTAGE) {
debug("Bat Voltage: " + String(volt) + " V");
debug("Low battery, going into deep sleep.");
// Casting to an unsigned int, so it fits into the integer range
ESP.deepSleep(1U * EMERGENCY_SLEEP_S * 1000000); // battery low, shutting down
ESP.deepSleep(1U * EMERGENCY_SLEEP_S * 1000000u); // battery low, shutting down
delay(100);
}
}
#endif
void loop()
{
//*************************************************************************//
void loop() {
#ifdef ENABLE_WATCHDOG
ESP.wdtFeed();
#endif
wifiConnectionCheck();
#ifdef BATTERY_POWERED
delay(50);
return;
#endif
// call sub loop function
_loop();
#else
// call fsm loop function
_fsm_loop();
// Needed to give WIFI time to function properly
delay(DELAY_LOOP_MS);
update_sensor_cnt++;
#endif
}
//*************************************************************************//
#ifndef BATTERY_POWERED
void _fsm_loop()
{
#ifdef WEBUPDATER_FEATURE
update_webserver_cnt++;
if ((update_webserver_cnt + (UPDATE_WEBSERVER_INTVERVAL_MS)) <= millis())
{
//debug("web updater call");
update_webserver_cnt = millis();
doWebUpdater();
}
#endif
#ifdef HTTP_CALL_SEND_JSON_DATA
if ((http_call_send_json_data_cnt + (HTTP_CALL_SEND_JSON_DATA_INTERVAL_S * 1000)) <= millis() and validData == true)
{
// send the data to the server
debug("Sending weather json data to http webserver");
//debug(String(0) + "=" + String(currentSensorData[0]));
//debug(String(SENSOR_TEMPERATURE) + "=" + String(currentSensorData[SENSOR_TEMPERATURE]));
http_call_send_json_data_cnt = millis();
http_call_send_json_data();
}
#endif
switch (fsm_state)
{
/* -------------------------------------------------------------------------------- */
case FSM_STATE_1:
//debug("wind speed exceeded check if required");
#ifdef HTTP_CALL_ON_WINDSPEED_EXCEED
update_windspeed_exceed_cnt++;
if ((update_windspeed_exceed_cnt + (HTTP_CALL_ON_WINDSPEED_INTERVAL_S * 1000)) <= millis()) {
debug("reading wind sensor exceed");
// reset the wait timer to get a value every HTTP_CALL_ON_WINDSPEED_INTERVAL_S independently to the runtime of the measurement
update_windspeed_exceed_cnt = millis();
// start measurement of wind speed
start_measure_wind();
fsm_state = FSM_STATE_11; // wait untile the wind meas time exceeded
break; // abort case here to prevent read of next sensor in list
}
#endif
fsm_state = FSM_STATE_2;
break;
}
/* -------------------------------------------------------------------------------- */
case FSM_STATE_2:
//debug("reset time check if required");
#ifdef RESET_ESP_TIME_INTERVAL
// if millis() reached interval restart ESP
if (RESET_ESP_TIME_INTERVAL_MS <= millis()) {
debug("resetting firmware intentionally");
// Push reset button after flashing once or do a manual power cycle to get the functionality working.
ESP.restart();
}
#endif
fsm_state = FSM_STATE_3;
break;
void _loop()
{
/* -------------------------------------------------------------------------------- */
case FSM_STATE_3:
wifiConnectionCheck();
fsm_state = FSM_STATE_4;
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_4:
//debug("disable measure of wind speed if required");
#ifdef defined(BATTERY_POWERED) && defined(SENSOR_WIND)
if (energySavingMode() == 1) {
// Disable expensive tasks
//sensors[SENSOR_WINDSPEED] = 0;
//debug("read of wind sensor because of low battery disabled");
do_not_read_windsensor = true;
} else {
//sensors[SENSOR_WINDSPEED] = &wind_speed;
//debug("read of wind sensor because of high battery enabled");
do_not_read_windsensor = false;
}
#endif
sensor_cnt = 0;
fsm_state = FSM_STATE_5;
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_5:
//debug("read sensor data check");
if ((update_sensor_cnt + (UPDATE_SENSOR_INTERVAL_S * 1000)) <= millis() or validData == false) {
debug("read sensor data " + String(sensor_cnt));
if (sensor_cnt != SENSOR_WINDSPEED) {
// read data from sensor
currentSensorData[sensor_cnt] = readSensors(sensor_cnt);
//debug(String(sensor_cnt) + "=" + String(currentSensorData[sensor_cnt]));
} else {
start_measure_wind(); // start measurement of wind speed
fsm_state = FSM_STATE_9; // wait untile the wind meas time exceeded
break; // abort case here to prevent read of next sensor in list
}
if (sensor_cnt < VALUES - 1) {
sensor_cnt++;
fsm_state = FSM_STATE_5; // jump to same state again, more sensors to read
} else {
update_sensor_cnt = millis(); // reset the update interval counter
sensor_cnt = 0;
fsm_state = FSM_STATE_6; // next state
}
} else {
//debug("skip read sensor data");
fsm_state = FSM_STATE_1; // no new data, reset FSM
}
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_6:
//debug("log to serial if required");
#ifdef SERIAL_FEATURE
logToSerial(currentSensorData);
#endif
fsm_state = FSM_STATE_7;
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_7:
//debug("send data to influxdb if required");
#ifdef INFLUXDB_FEATURE
for (uint8_t i = 0; i < 5 and validData == false; i++) { // only check sensor data 0 to 4 -> SENSOR_TEMPERATURE, SENSOR_HUMIDITY, SENSOR_LIGHT, SENSOR_WINDSPEED, SENSOR_PRESSURE
if (currentSensorData[i] != 0 and currentSensorData[i] != nanf("no value") and (not isnan(currentSensorData[i]))) {
validData = true;
}
}
if (validData == true) {
// send data only if valid data is available
pushToInfluxDB(DEVICE_NAME, currentSensorData);
}
#endif
fsm_state = FSM_STATE_8;
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_8:
//debug("set sensor data in webupdater if required");
#ifdef WEBUPDATER_FEATURE
if (UPDATE_WEBSERVER_INTVERVAL_S * 1000 / DELAY_LOOP_MS <= update_webserver_cnt)
{
update_webserver_cnt = 0;
doWebUpdater();
}
#ifdef SHOW_SENSOR_DATA_ON_WEBUPDATER_MAIN_PAGE
setSensorData(currentSensorData);
#endif
#endif
fsm_state = FSM_STATE_1;
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_9:
#ifdef SENSOR_WIND
if (check_measure_wind_done() == false) {
//debug("wait for wind sensor finish");
fsm_state = FSM_STATE_9; // stay here until the wind measurement is done
} else {
//debug("wind sensor read finish");
fsm_state = FSM_STATE_10;
}
#else
// in case that the wind sensor is not used skip this step
sensor_cnt++;
fsm_state = FSM_STATE_5;
#endif
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_10:
#ifdef SENSOR_WIND
currentSensorData[SENSOR_WINDSPEED] = measure_wind_result();
debug("wind sensor " + String(currentSensorData[SENSOR_WINDSPEED]));
#endif
// step into read of next sensor read
sensor_cnt++;
fsm_state = FSM_STATE_5;
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_11:
#ifdef SENSOR_WIND
if (check_measure_wind_done() == false) {
//debug("wait for wind sensor finish");
fsm_state = FSM_STATE_11; // stay here until the wind measurement is done
} else {
//debug("wind sensor read finish");
fsm_state = FSM_STATE_12;
}
#else
// in case that the wind sensor is not used skip this step
sensor_cnt++;
fsm_state = FSM_STATE_5;
#endif
break;
/* -------------------------------------------------------------------------------- */
case FSM_STATE_12:
#ifdef HTTP_CALL_ON_WINDSPEED_EXCEED
if (HTTP_CALL_ON_WINDSPEED_INTERVAL_S * 1000 / DELAY_LOOP_MS <= update_windspeed_exceed_cnt)
{
debug("Reading wind sensor because of exceed call functionality");
if (sensors[SENSOR_WINDSPEED])
{
// read from windspeed sensorSTATUS_LED_PIN
digitalWrite(STATUS_LED_PIN, HIGH);
currentSensorData[SENSOR_WINDSPEED] = sensors[SENSOR_WINDSPEED]();
digitalWrite(STATUS_LED_PIN, LOW);
if (currentSensorData[SENSOR_WINDSPEED] >= HTTP_CALL_ON_WINDSPEED_EXCEED_MPS)
{
digitalWrite(STATUS_LED_PIN, HIGH);
currentSensorData[SENSOR_WINDSPEED] = measure_wind_result();
debug("wind sensor value " + String(currentSensorData[SENSOR_WINDSPEED]));
if (currentSensorData[SENSOR_WINDSPEED] >= HTTP_CALL_ON_WINDSPEED_EXCEED_MPS) {
// windspeed exceeded send http call
digitalWrite(STATUS_LED_PIN, LOW);
// call the url HTTP_CALL_ON_WINDSPEED_URL
WiFiClient client;
@ -259,90 +603,78 @@ void _loop()
if (httpResponseCode > 0) {
String response = http.getString();
#ifdef DEBUG
Serial.println("http response code: " + String(httpResponseCode) + " = " + response);
#endif
debug("http response code: " + String(httpResponseCode) + " = " + response);
// TODO handle response
}
http.end();
debug("Called windspeed exceed callout");
digitalWrite(STATUS_LED_PIN, LOW);
digitalWrite(STATUS_LED_PIN, HIGH);
}
} else {
currentSensorData[SENSOR_WINDSPEED] = nan("no value");
}
update_windspeed_exceed_cnt = 0;
}
#endif
#ifdef RESET_ESP_TIME_INTERVAL
// if millis() reached interval restart ESP
if (RESET_ESP_TIME_INTERVAL_MS <= millis())
{
debug("Resetting firmware intentionally");
// Push reset button after flashing once or do a manual power cycle to get the functionality working.
ESP.restart();
}
#endif
#ifdef WEBUPDATER_FEATURE
#ifdef SHOW_SENSOR_DATA_ON_WEBUPDATER_MAIN_PAGE
sentWindspeed(currentSensorData[SENSOR_WINDSPEED]);
#endif // SHOW_SENSOR_DATA_ON_WEBUPDATER_MAIN_PAGE
#endif // WEBUPDATER_FEATURE
#endif // HTTP_CALL_ON_WINDSPEED_EXCEED
#ifndef BATTERY_POWERED
if (UPDATE_SENSOR_INTERVAL_S * 1000 / DELAY_LOOP_MS > update_sensor_cnt)
// step into read of next fsm state
fsm_state = FSM_STATE_2;
break;
/* -------------------------------------------------------------------------------- */
default:
fsm_state = FSM_STATE_1;
break;
} // close of switch
//debug("FSM state = " + String(fsm_state));
/*if (fsm_state == FSM_STATE_1)
{
return;
}
debug("----------");
}*/
}
#endif
#ifdef defined(BATTERY_POWERED) && defined(SENSOR_WIND)
//*************************************************************************//
void _battery_mode_main() {
if (energySavingMode() == 1) {
// Disable expensive tasks
sensors[SENSOR_WINDSPEED] = 0;
//debug("read of wind sensor because of low battery disabled");
do_not_read_windsensor = true;
} else {
sensors[SENSOR_WINDSPEED] = &wind_speed;
//debug("read of wind sensor because of high battery enabled");
do_not_read_windsensor = false;
}
#endif
update_sensor_cnt = 0;
for (uint8_t i = 0; i < VALUES; i++)
{
if (sensors[i]) {
currentSensorData[i] = sensors[i]();
} else {
currentSensorData[i] = nan("no value");
}
for (uint8_t i = 0; i < VALUES; i++) {
currentSensorData[i] = readSensors(i);
}
#ifdef SERIAL_FEATURE
logToSerial(currentSensorData);
#endif
delay(100);
#ifdef INFLUXDB_FEATURE
for (uint8_t i = 0; i < 5 and validData == false; i++)
{
if (currentSensorData[i] != 0)
{
validData = true; // at least one value is not zero, the data
}
}
if (validData == true)
{
// send data only if valid data is available
pushToInfluxDB(DEVICE_NAME, currentSensorData);
}
pushToInfluxDB(DEVICE_NAME, currentSensorData);
#endif
#ifdef WEBUPDATER_FEATURE
#ifdef SHOW_SENSOR_DATA_ON_WEBUPDATER_MAIN_PAGE
setSensorData(currentSensorData);
#endif
#endif
}
void logToSerial(float sensorValues[])
{
//*************************************************************************//
#ifdef SERIAL_FEATURE
void logToSerial(float sensorValues[]) {
Serial.println("");
Serial.println("Current readings:");
Serial.println("Temperature: " + String(sensorValues[SENSOR_TEMPERATURE]) + " °C");
@ -354,3 +686,68 @@ void logToSerial(float sensorValues[])
Serial.println("Bat charge state: " + String(sensorValues[SENSOR_BATCHARGESTATE]));
Serial.println("Energy saving: " + String(sensorValues[SENSOR_ESAVEMODE]));
}
#endif
//*************************************************************************//
#ifdef HTTP_CALL_SEND_JSON_DATA
String getJsonData()
{
debug(String(SENSOR_TEMPERATURE) + "=" + String(currentSensorData[SENSOR_TEMPERATURE]));
String msg = hb_ws_msg_start +
hb_ws_msg_temp +
String(currentSensorData[SENSOR_TEMPERATURE], 2) +
", " +
hb_ws_msg_humi +
String((isnan(currentSensorData[SENSOR_HUMIDITY]) ? 0.0 : currentSensorData[SENSOR_HUMIDITY]), 2) +
", " +
hb_ws_msg_light +
String(currentSensorData[SENSOR_LIGHT], 0) + // The light level for the homebridge-http-lux2 plugin is only able to parse integer values
", " +
hb_ws_msg_windspeed +
String(currentSensorData[SENSOR_WINDSPEED], 2) +
", " +
hb_ws_msg_pressure +
String(currentSensorData[SENSOR_PRESSURE], 2) +
", " +
hb_ws_msg_timestamp +
String(millis()) +
", " +
hb_ws_msg_valid +
String(validData) +
hb_ws_msg_end;
return msg;
}
void http_call_send_json_data()
{
//debug("http call to " + String(HTTP_CALL_SEND_JSON_DATA_URL));
//debug(String(SENSOR_TEMPERATURE) + "=" + String(currentSensorData[SENSOR_TEMPERATURE]));
// windspeed exceeded send http call
digitalWrite(STATUS_LED_PIN, LOW);
// call the url HTTP_CALL_SEND_JSON_DATA_URL
WiFiClient client;
HTTPClient http;
String tmp_str = HTTP_CALL_SEND_JSON_DATA_URL + urlEncode(getJsonData());
debug("send: " + tmp_str);
http.begin(client, String(tmp_str).c_str());
// Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode > 0) {
String response = http.getString();
debug("http response code: " + String(httpResponseCode) + " = " + response);
// TODO handle response
}
http.end();
digitalWrite(STATUS_LED_PIN, HIGH);
}
#endif

@ -1,12 +1,16 @@
#include "config_user.h"
//*************************************************************************//
#if INFLUXDB_VERSION == 1
#include <ESP8266Influxdb.h> // https://github.com/hwwong/ESP8266Influxdb
Influxdb _influxdb(INFLUXDB_HOST, INFLUXDB_PORT);
const String msg = "weather,device=" + device + " ";
void influxdb_begin() {
// Init variables to influxdb config - doesn't talk to database
_influxdb.opendb(INFLUXDB_DB, INFLUXDB_USER, INFLUXDB_PASS);
@ -16,7 +20,6 @@ void pushToInfluxDB(String device, float sensorValues[]) {
uint8_t tries = 0;
boolean addComma = false;
String msg = "weather,device=" + device + " ";
if (!(isnan(sensorValues[SENSOR_TEMPERATURE])))
{
msg += "temperature=" + String(sensorValues[SENSOR_TEMPERATURE]);
@ -86,6 +89,8 @@ void pushToInfluxDB(String device, float sensorValues[]) {
} while (_influxdb.response() != DB_SUCCESS and tries < 5);
}
//*************************************************************************//
#elif INFLUXDB_VERSION == 2
#include <InfluxDbClient.h> // from bib manager
@ -172,30 +177,42 @@ void pushToInfluxDB(String device, float sensorValues[]) {
}
void _writePoint() {
void _writePoint()
{
uint32_t _timeout = millis();
//debug("InfluxDB2: check connection");
do {
} while (client.validateConnection() and (_timeout + INFLUXDB_TIMEOUT_MS) <= millis());
if (! client.validateConnection())
{
debug("Can't write to InfluxDB2, timeout validating connection");
return;
}
_timeout = millis();
//debug("InfluxDB2: waiting for write ready");
// wait unitl ready
do {
#ifdef DEBUG
Serial.print("InfluxDB: waiting for write ready\n");
#endif
} while (client.canSendRequest() == false);
} while (client.canSendRequest() == false and (_timeout + INFLUXDB_TIMEOUT_MS) <= millis());
if (! client.canSendRequest())
{
debug("Can't write to InfluxDB2, timeout canSendRequest");
return;
}
// Write point
if (!client.writePoint(sensor)) {
#ifdef DEBUG
Serial.print("InfluxDB write failed: ");
Serial.println(client.getLastErrorMessage());
Serial.print("\nErrorcode: ");
Serial.println(client.getLastStatusCode());
Serial.print("\n");
#endif
} else {
#ifdef DEBUG
Serial.print("InfluxDB write done\n");
#endif
if (!client.writePoint(sensor))
{
debug("InfluxDB2 write failed: " + String(client.getLastErrorMessage()) + " Err: " + String(client.getLastStatusCode()));
}
}
#endif // influxdb version 2 check
//*************************************************************************//

@ -0,0 +1,493 @@
/*!
* @file Adafruit_BMP280.cpp
*
* This is a library for the BMP280 orientation sensor
*
* Designed specifically to work with the Adafruit BMP280 Sensor.
*
* Pick one up today in the adafruit shop!
* ------> https://www.adafruit.com/product/2651
*
* These sensors use I2C to communicate, 2 pins are required to interface.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit andopen-source hardware by purchasing products
* from Adafruit!
*
* K.Townsend (Adafruit Industries)
*
* BSD license, all text above must be included in any redistribution
*/
#include <Adafruit_BMP280.h>
/*!
* @brief BMP280 constructor using i2c
* @param *theWire
* optional wire
*/
Adafruit_BMP280::Adafruit_BMP280(TwoWire *theWire) {
_wire = theWire;
temp_sensor = new Adafruit_BMP280_Temp(this);
pressure_sensor = new Adafruit_BMP280_Pressure(this);
}
/*!
* @brief BMP280 constructor using hardware SPI
* @param cspin
* cs pin number
* @param theSPI
* optional SPI object
*/
Adafruit_BMP280::Adafruit_BMP280(int8_t cspin, SPIClass *theSPI) {
spi_dev = new Adafruit_SPIDevice(cspin, 1000000, SPI_BITORDER_MSBFIRST,
SPI_MODE0, theSPI);
temp_sensor = new Adafruit_BMP280_Temp(this);
pressure_sensor = new Adafruit_BMP280_Pressure(this);
}
/*!
* @brief BMP280 constructor using bitbang SPI
* @param cspin
* The pin to use for CS/SSEL.
* @param mosipin
* The pin to use for MOSI.
* @param misopin
* The pin to use for MISO.
* @param sckpin
* The pin to use for SCK.
*/
Adafruit_BMP280::Adafruit_BMP280(int8_t cspin, int8_t mosipin, int8_t misopin,
int8_t sckpin) {
spi_dev = new Adafruit_SPIDevice(cspin, sckpin, misopin, mosipin);
temp_sensor = new Adafruit_BMP280_Temp(this);
pressure_sensor = new Adafruit_BMP280_Pressure(this);
}
Adafruit_BMP280::~Adafruit_BMP280(void) {
if (spi_dev)
delete spi_dev;
if (i2c_dev)
delete i2c_dev;
if (temp_sensor)
delete temp_sensor;
if (pressure_sensor)
delete pressure_sensor;
}
/*!
* Initialises the sensor.
* @param addr
* The I2C address to use (default = 0x77)
* @param chipid
* The expected chip ID (used to validate connection).
* @return True if the init was successful, otherwise false.
*/
bool Adafruit_BMP280::begin(uint8_t addr, uint8_t chipid) {
if (spi_dev == NULL) {
// I2C mode
if (i2c_dev)
delete i2c_dev;
i2c_dev = new Adafruit_I2CDevice(addr, _wire);
if (!i2c_dev->begin())
return false;
} else {
// SPI mode
if (!spi_dev->begin())
return false;
}
// check if sensor, i.e. the chip ID is correct
_sensorID = read8(BMP280_REGISTER_CHIPID);
if (_sensorID != chipid)
return false;
readCoefficients();
// write8(BMP280_REGISTER_CONTROL, 0x3F); /* needed? */
setSampling();
delay(100);
return true;
}
/*!
* Sets the sampling config for the device.
* @param mode
* The operating mode of the sensor.
* @param tempSampling
* The sampling scheme for temp readings.
* @param pressSampling
* The sampling scheme for pressure readings.
* @param filter
* The filtering mode to apply (if any).
* @param duration
* The sampling duration.
*/
void Adafruit_BMP280::setSampling(sensor_mode mode,
sensor_sampling tempSampling,
sensor_sampling pressSampling,
sensor_filter filter,
standby_duration duration) {
if (!_sensorID)
return; // begin() not called yet
_measReg.mode = mode;
_measReg.osrs_t = tempSampling;
_measReg.osrs_p = pressSampling;
_configReg.filter = filter;
_configReg.t_sb = duration;
write8(BMP280_REGISTER_CONFIG, _configReg.get());
write8(BMP280_REGISTER_CONTROL, _measReg.get());
}
/**************************************************************************/
/*!
@brief Writes an 8 bit value over I2C/SPI
*/
/**************************************************************************/
void Adafruit_BMP280::write8(byte reg, byte value) {
byte buffer[2];
buffer[1] = value;
if (i2c_dev) {
buffer[0] = reg;
i2c_dev->write(buffer, 2);
} else {
buffer[0] = reg & ~0x80;
spi_dev->write(buffer, 2);
}
}
/*!
* @brief Reads an 8 bit value over I2C/SPI
* @param reg
* selected register
* @return value from selected register
*/
uint8_t Adafruit_BMP280::read8(byte reg) {
uint8_t buffer[1];
if (i2c_dev) {
buffer[0] = uint8_t(reg);
i2c_dev->write_then_read(buffer, 1, buffer, 1);
} else {
buffer[0] = uint8_t(reg | 0x80);
spi_dev->write_then_read(buffer, 1, buffer, 1);
}
return buffer[0];
}
/*!
* @brief Reads a 16 bit value over I2C/SPI
*/
uint16_t Adafruit_BMP280::read16(byte reg) {
uint8_t buffer[2];
if (i2c_dev) {
buffer[0] = uint8_t(reg);
i2c_dev->write_then_read(buffer, 1, buffer, 2);
} else {
buffer[0] = uint8_t(reg | 0x80);
spi_dev->write_then_read(buffer, 1, buffer, 2);
}
return uint16_t(buffer[0]) << 8 | uint16_t(buffer[1]);
}
uint16_t Adafruit_BMP280::read16_LE(byte reg) {
uint16_t temp = read16(reg);
return (temp >> 8) | (temp << 8);
}
/*!
* @brief Reads a signed 16 bit value over I2C/SPI
*/
int16_t Adafruit_BMP280::readS16(byte reg) { return (int16_t)read16(reg); }
int16_t Adafruit_BMP280::readS16_LE(byte reg) {
return (int16_t)read16_LE(reg);
}
/*!
* @brief Reads a 24 bit value over I2C/SPI
*/
uint32_t Adafruit_BMP280::read24(byte reg) {
uint8_t buffer[3];
if (i2c_dev) {
buffer[0] = uint8_t(reg);
i2c_dev->write_then_read(buffer, 1, buffer, 3);
} else {
buffer[0] = uint8_t(reg | 0x80);
spi_dev->write_then_read(buffer, 1, buffer, 3);
}
return uint32_t(buffer[0]) << 16 | uint32_t(buffer[1]) << 8 |
uint32_t(buffer[2]);
}
/*!
* @brief Reads the factory-set coefficients
*/
void Adafruit_BMP280::readCoefficients() {
_bmp280_calib.dig_T1 = read16_LE(BMP280_REGISTER_DIG_T1);
_bmp280_calib.dig_T2 = readS16_LE(BMP280_REGISTER_DIG_T2);
_bmp280_calib.dig_T3 = readS16_LE(BMP280_REGISTER_DIG_T3);
_bmp280_calib.dig_P1 = read16_LE(BMP280_REGISTER_DIG_P1);
_bmp280_calib.dig_P2 = readS16_LE(BMP280_REGISTER_DIG_P2);
_bmp280_calib.dig_P3 = readS16_LE(BMP280_REGISTER_DIG_P3);
_bmp280_calib.dig_P4 = readS16_LE(BMP280_REGISTER_DIG_P4);
_bmp280_calib.dig_P5 = readS16_LE(BMP280_REGISTER_DIG_P5);
_bmp280_calib.dig_P6 = readS16_LE(BMP280_REGISTER_DIG_P6);
_bmp280_calib.dig_P7 = readS16_LE(BMP280_REGISTER_DIG_P7);
_bmp280_calib.dig_P8 = readS16_LE(BMP280_REGISTER_DIG_P8);
_bmp280_calib.dig_P9 = readS16_LE(BMP280_REGISTER_DIG_P9);
}
/*!
* Reads the temperature from the device.
* @return The temperature in degrees celsius.
*/
float Adafruit_BMP280::readTemperature() {
int32_t var1, var2;
if (!_sensorID)
return NAN; // begin() not called yet
int32_t adc_T = read24(BMP280_REGISTER_TEMPDATA);
adc_T >>= 4;
var1 = ((((adc_T >> 3) - ((int32_t)_bmp280_calib.dig_T1 << 1))) *
((int32_t)_bmp280_calib.dig_T2)) >>
11;
var2 = (((((adc_T >> 4) - ((int32_t)_bmp280_calib.dig_T1)) *
((adc_T >> 4) - ((int32_t)_bmp280_calib.dig_T1))) >>
12) *
((int32_t)_bmp280_calib.dig_T3)) >>
14;
t_fine = var1 + var2;
float T = (t_fine * 5 + 128) >> 8;
return T / 100;
}
/*!
* Reads the barometric pressure from the device.
* @return Barometric pressure in Pa.
*/
float Adafruit_BMP280::readPressure() {
int64_t var1, var2, p;
if (!_sensorID)
return NAN; // begin() not called yet
// Must be done first to get the t_fine variable set up
readTemperature();
int32_t adc_P = read24(BMP280_REGISTER_PRESSUREDATA);
adc_P >>= 4;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)_bmp280_calib.dig_P6;
var2 = var2 + ((var1 * (int64_t)_bmp280_calib.dig_P5) << 17);
var2 = var2 + (((int64_t)_bmp280_calib.dig_P4) << 35);
var1 = ((var1 * var1 * (int64_t)_bmp280_calib.dig_P3) >> 8) +
((var1 * (int64_t)_bmp280_calib.dig_P2) << 12);
var1 =
(((((int64_t)1) << 47) + var1)) * ((int64_t)_bmp280_calib.dig_P1) >> 33;
if (var1 == 0) {
return 0; // avoid exception caused by division by zero
}
p = 1048576 - adc_P;
p = (((p << 31) - var2) * 3125) / var1;
var1 = (((int64_t)_bmp280_calib.dig_P9) * (p >> 13) * (p >> 13)) >> 25;
var2 = (((int64_t)_bmp280_calib.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)_bmp280_calib.dig_P7) << 4);
return (float)p / 256;
}
/*!
* @brief Calculates the approximate altitude using barometric pressure and the
* supplied sea level hPa as a reference.
* @param seaLevelhPa
* The current hPa at sea level.
* @return The approximate altitude above sea level in meters.
*/
float Adafruit_BMP280::readAltitude(float seaLevelhPa) {
float altitude;
float pressure = readPressure(); // in Si units for Pascal
pressure /= 100;
altitude = 44330 * (1.0 - pow(pressure / seaLevelhPa, 0.1903));
return altitude;
}
/*!
* Calculates the pressure at sea level (QNH) from the specified altitude,
* and atmospheric pressure (QFE).
* @param altitude Altitude in m
* @param atmospheric Atmospheric pressure in hPa
* @return The approximate pressure in hPa