diff --git a/.gitignore b/.gitignore index 3762d44..04b527a 100755 --- a/.gitignore +++ b/.gitignore @@ -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 diff --git a/firmware/.vscode/c_cpp_properties.json b/firmware/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..eb19e57 --- /dev/null +++ b/firmware/.vscode/c_cpp_properties.json @@ -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 +} \ No newline at end of file diff --git a/firmware/config.h b/firmware/config.h index 1ecdf35..4c5ba71 100644 --- a/firmware/config.h +++ b/firmware/config.h @@ -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 diff --git a/firmware/config_user.h.example b/firmware/config_user.h.example index b81c72f..9375af4 100755 --- a/firmware/config_user.h.example +++ b/firmware/config_user.h.example @@ -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 -// 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 ENABLE_WATCHDOG -//#define WATCHDOG_TIMEOUT_MS 30000 +//#define BAT_PINS_D34 + +/********************************************************************************/ +// not available or recommended for battery mode +/********************************************************************************/ + +//#define DISABLE_WIFIMANAGER +// Restarts the firmware every n seconds +//#define RESET_ESP_TIME_INTERVAL +//#define ENABLE_WATCHDOG +//#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) //#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 diff --git a/firmware/constants.h b/firmware/constants.h index 19da869..cab8a7d 100644 --- a/firmware/constants.h +++ b/firmware/constants.h @@ -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 diff --git a/firmware/firmware.ino b/firmware/firmware.ino index fbc636a..e3dc09a 100644 --- a/firmware/firmware.ino +++ b/firmware/firmware.ino @@ -1,19 +1,27 @@ // Standard ESP8266 libs from project folder #include -#include #include -#include -#include -#include #include // WiFiClient -#include // WiFiManager from bib manager // Project includes #include "constants.h" #include "config.h" #include "config_user.h" +#ifndef DISABLE_WIFIMANAGER +#include // WiFiManager from bib manager +#endif + +#ifdef HTTP_CALL_ON_WINDSPEED_EXCEED +#include +#endif + +#ifdef HTTP_CALL_SEND_JSON_DATA +#include +#include // 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; + +#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; -WiFiManager wifiManager; +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,59 +100,22 @@ void setup() criticalBatCheck(); #endif - wifiConnectionCheck(); + wifiConnect(); debug("Connected!"); -#ifdef INFLUXDB_FEATURE - influxdb_begin(); -#endif + initWifiBasedSW(); - // Initialize and configure the sensors -#ifdef SENSOR_APDS9930 - if (sensor_apds9930_begin()) { - sensors[SENSOR_LIGHT] = &apds9930_light; - } -#endif - -#ifdef SENSOR_APDS9960 - if (sensor_apds9960_begin()) { - sensors[SENSOR_LIGHT] = &apds9960_light; - } -#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; - } -#endif - -#ifdef SENSOR_WIND - sensors[SENSOR_WINDSPEED] = &wind_speed; -#endif - -#ifdef SENSOR_BATTERY - sensors[SENSOR_BAT_VOLTAGE] = &battery_voltage; - sensors[SENSOR_BATCHARGESTATE] = &battery_charging; - sensors[SENSOR_ESAVEMODE] = &isEnergySavingMode; -#endif - -#ifdef WEBUPDATER_FEATURE -#ifndef BATTERY_POWERED - setupWebUpdater(DEVICE_NAME, WiFi.localIP().toString()); -#endif -#endif + initSensors(); //It's magic! leave in delay(100); #ifdef BATTERY_POWERED debug("battery powered"); - _loop(); - digitalWrite(STATUS_LED_PIN, LOW); + _battery_mode_main(); + + digitalWrite(STATUS_LED_PIN, HIGH); criticalBatCheck(); @@ -134,24 +124,176 @@ void setup() debug("deep sleep"); - // the ESP.deepSleep requires microseconds as input, after the sleep the system will run into the setup routine + // 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 + +#else // not in battery mode #ifdef ENABLE_WATCHDOG // Enable the internal watchdog ESP.wdtEnable(WATCHDOG_TIMEOUT_MS); #endif - +#endif } //*************************************************************************// -void wifiConnectionCheck() -{ - // Establish WiFi connection - String wifiName = "oko-weather-" + DEVICE_NAME; +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(); +#endif + +#ifdef SENSOR_APDS9960 + sensor_apds9960_begin(); +#endif + +#ifdef SENSOR_BME280 + //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 + if (do_not_read_windsensor == false) { + ret = wind_speed(); + } +#endif + break; + + case SENSOR_BAT_VOLTAGE: +#ifdef SENSOR_BATTERY + ret = battery_voltage(); +#endif + break; + + case SENSOR_ESAVEMODE: +#ifdef SENSOR_BATTERY + ret = battery_charging(); +#endif + break; + + case SENSOR_BATCHARGESTATE: +#ifdef SENSOR_BATTERY + ret = isEnergySavingMode(); +#endif + break; + + default: + break; + } + + return ret; +} + +//*************************************************************************// + +void wifiConnectionCheck() { + + if ((wifi_check_interval_counter + WIFI_CHECK_INTERVAL_MS) > millis()) { + // if check interval is not exceeded abort check + return; + } + + wifi_check_interval_counter = millis(); + + if (WiFi.status() == WL_CONNECTED) { + // if we are connected + return; + } + + 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 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++; - -#ifdef WEBUPDATER_FEATURE - update_webserver_cnt++; #endif - -#ifdef HTTP_CALL_ON_WINDSPEED_EXCEED - update_windspeed_exceed_cnt++; -#endif - } -void _loop() +//*************************************************************************// + +#ifndef BATTERY_POWERED +void _fsm_loop() { #ifdef WEBUPDATER_FEATURE - if (UPDATE_WEBSERVER_INTVERVAL_S * 1000 / DELAY_LOOP_MS <= update_webserver_cnt) + if ((update_webserver_cnt + (UPDATE_WEBSERVER_INTVERVAL_MS)) <= millis()) { - update_webserver_cnt = 0; + //debug("web updater call"); + update_webserver_cnt = millis(); doWebUpdater(); } #endif -#ifdef HTTP_CALL_ON_WINDSPEED_EXCEED - if (HTTP_CALL_ON_WINDSPEED_INTERVAL_S * 1000 / DELAY_LOOP_MS <= update_windspeed_exceed_cnt) +#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) { - 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); + // 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 - if (currentSensorData[SENSOR_WINDSPEED] >= HTTP_CALL_ON_WINDSPEED_EXCEED_MPS) - { - digitalWrite(STATUS_LED_PIN, HIGH); + switch (fsm_state) + { + + /* -------------------------------------------------------------------------------- */ + case FSM_STATE_1: + //debug("wind speed exceeded check if required"); +#ifdef HTTP_CALL_ON_WINDSPEED_EXCEED + 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; + + /* -------------------------------------------------------------------------------- */ + 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 +#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 + 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()) +#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 + + // 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) { - debug("Resetting firmware intentionally"); - // Push reset button after flashing once or do a manual power cycle to get the functionality working. - ESP.restart(); - } + debug("----------"); + }*/ +} #endif -#ifndef BATTERY_POWERED - if (UPDATE_SENSOR_INTERVAL_S * 1000 / DELAY_LOOP_MS > update_sensor_cnt) - { - return; - } -#endif +//*************************************************************************// + +void _battery_mode_main() { -#ifdef defined(BATTERY_POWERED) && defined(SENSOR_WIND) if (energySavingMode() == 1) { // Disable expensive tasks - sensors[SENSOR_WINDSPEED] = 0; - } else { - sensors[SENSOR_WINDSPEED] = &wind_speed; - } -#endif + //debug("read of wind sensor because of low battery disabled"); + do_not_read_windsensor = true; - 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"); - } + } else { + //debug("read of wind sensor because of high battery enabled"); + do_not_read_windsensor = false; + } + + 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 diff --git a/firmware/influxdb.ino b/firmware/influxdb.ino index 0e0b881..a3d2174 100644 --- a/firmware/influxdb.ino +++ b/firmware/influxdb.ino @@ -1,12 +1,16 @@ #include "config_user.h" +//*************************************************************************// + #if INFLUXDB_VERSION == 1 #include // 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 // 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 + +//*************************************************************************// diff --git a/firmware/libraries/Adafruit_BMP280_Library/Adafruit_BMP280.cpp b/firmware/libraries/Adafruit_BMP280_Library/Adafruit_BMP280.cpp new file mode 100644 index 0000000..ac113a6 --- /dev/null +++ b/firmware/libraries/Adafruit_BMP280_Library/Adafruit_BMP280.cpp @@ -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 + +/*! + * @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 + */ +float Adafruit_BMP280::seaLevelForAltitude(float altitude, float atmospheric) { + // Equation taken from BMP180 datasheet (page 17): + // http://www.adafruit.com/datasheets/BST-BMP180-DS000-09.pdf + + // Note that using the equation from wikipedia can give bad results + // at high altitude. See this thread for more information: + // http://forums.adafruit.com/viewtopic.php?f=22&t=58064 + return atmospheric / pow(1.0 - (altitude / 44330.0), 5.255); +} + +/*! + @brief calculates the boiling point of water by a given pressure + @param pressure pressure in hPa + @return temperature in °C +*/ + +float Adafruit_BMP280::waterBoilingPoint(float pressure) { + // Magnusformular for calculation of the boiling point of water at a given + // pressure + return (234.175 * log(pressure / 6.1078)) / + (17.08085 - log(pressure / 6.1078)); +} + +/*! + @brief Take a new measurement (only possible in forced mode) + @return true if successful, otherwise false + */ +bool Adafruit_BMP280::takeForcedMeasurement() { + // If we are in forced mode, the BME sensor goes back to sleep after each + // measurement and we need to set it to forced mode once at this point, so + // it will take the next measurement and then return to sleep again. + // In normal mode simply does new measurements periodically. + if (_measReg.mode == MODE_FORCED) { + // set to forced mode, i.e. "take next measurement" + write8(BMP280_REGISTER_CONTROL, _measReg.get()); + // wait until measurement has been completed, otherwise we would read + // the values from the last measurement + while (read8(BMP280_REGISTER_STATUS) & 0x08) + delay(1); + return true; + } + return false; +} + +/*! + * @brief Resets the chip via soft reset + */ +void Adafruit_BMP280::reset(void) { + write8(BMP280_REGISTER_SOFTRESET, MODE_SOFT_RESET_CODE); +} + +/*! + * Returns Sensor ID for diagnostics + * @returns 0x61 for BME680, 0x60 for BME280, 0x56, 0x57, 0x58 for BMP280 + */ +uint8_t Adafruit_BMP280::sensorID(void) { return _sensorID; }; + +/*! + @brief Gets the most recent sensor event from the hardware status register. + @return Sensor status as a byte. + */ +uint8_t Adafruit_BMP280::getStatus(void) { + return read8(BMP280_REGISTER_STATUS); +} + +/*! + @brief Gets an Adafruit Unified Sensor object for the temp sensor component + @return Adafruit_Sensor pointer to temperature sensor + */ +Adafruit_Sensor *Adafruit_BMP280::getTemperatureSensor(void) { + return temp_sensor; +} + +/*! + @brief Gets an Adafruit Unified Sensor object for the pressure sensor + component + @return Adafruit_Sensor pointer to pressure sensor + */ +Adafruit_Sensor *Adafruit_BMP280::getPressureSensor(void) { + return pressure_sensor; +} + +/**************************************************************************/ +/*! + @brief Gets the sensor_t data for the BMP280's temperature sensor +*/ +/**************************************************************************/ +void Adafruit_BMP280_Temp::getSensor(sensor_t *sensor) { + /* Clear the sensor_t object */ + memset(sensor, 0, sizeof(sensor_t)); + + /* Insert the sensor name in the fixed length char array */ + strncpy(sensor->name, "BMP280", sizeof(sensor->name) - 1); + sensor->name[sizeof(sensor->name) - 1] = 0; + sensor->version = 1; + sensor->sensor_id = _sensorID; + sensor->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; + sensor->min_delay = 0; + sensor->min_value = -40.0; /* Temperature range -40 ~ +85 C */ + sensor->max_value = +85.0; + sensor->resolution = 0.01; /* 0.01 C */ +} + +/**************************************************************************/ +/*! + @brief Gets the temperature as a standard sensor event + @param event Sensor event object that will be populated + @returns True +*/ +/**************************************************************************/ +bool Adafruit_BMP280_Temp::getEvent(sensors_event_t *event) { + /* Clear the event */ + memset(event, 0, sizeof(sensors_event_t)); + + event->version = sizeof(sensors_event_t); + event->sensor_id = _sensorID; + event->type = SENSOR_TYPE_AMBIENT_TEMPERATURE; + event->timestamp = millis(); + event->temperature = _theBMP280->readTemperature(); + return true; +} + +/**************************************************************************/ +/*! + @brief Gets the sensor_t data for the BMP280's pressure sensor +*/ +/**************************************************************************/ +void Adafruit_BMP280_Pressure::getSensor(sensor_t *sensor) { + /* Clear the sensor_t object */ + memset(sensor, 0, sizeof(sensor_t)); + + /* Insert the sensor name in the fixed length char array */ + strncpy(sensor->name, "BMP280", sizeof(sensor->name) - 1); + sensor->name[sizeof(sensor->name) - 1] = 0; + sensor->version = 1; + sensor->sensor_id = _sensorID; + sensor->type = SENSOR_TYPE_PRESSURE; + sensor->min_delay = 0; + sensor->min_value = 300.0; /* 300 ~ 1100 hPa */ + sensor->max_value = 1100.0; + sensor->resolution = 0.012; /* 0.12 hPa relative */ +} + +/**************************************************************************/ +/*! + @brief Gets the pressure as a standard sensor event + @param event Sensor event object that will be populated + @returns True +*/ +/**************************************************************************/ +bool Adafruit_BMP280_Pressure::getEvent(sensors_event_t *event) { + /* Clear the event */ + memset(event, 0, sizeof(sensors_event_t)); + + event->version = sizeof(sensors_event_t); + event->sensor_id = _sensorID; + event->type = SENSOR_TYPE_PRESSURE; + event->timestamp = millis(); + event->pressure = _theBMP280->readPressure() / 100; // convert Pa to hPa + return true; +} diff --git a/firmware/libraries/Adafruit_BMP280_Library/Adafruit_BMP280.h b/firmware/libraries/Adafruit_BMP280_Library/Adafruit_BMP280.h new file mode 100644 index 0000000..9b34306 --- /dev/null +++ b/firmware/libraries/Adafruit_BMP280_Library/Adafruit_BMP280.h @@ -0,0 +1,267 @@ +/*! + * @file Adafruit_BMP280.h + * + * This is a library for the Adafruit BMP280 Breakout. + * + * Designed specifically to work with the Adafruit BMP280 Breakout. + * + * 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 + */ +#ifndef __BMP280_H__ +#define __BMP280_H__ + +// clang-format off +#include +#include +#include +#include +// clang-format on + +/*! + * I2C ADDRESS/BITS/SETTINGS + */ +#define BMP280_ADDRESS (0x77) /**< The default I2C address for the sensor. */ +#define BMP280_ADDRESS_ALT \ + (0x76) /**< Alternative I2C address for the sensor. */ +#define BMP280_CHIPID (0x58) /**< Default chip ID. */ + +/*! + * Registers available on the sensor. + */ +enum { + BMP280_REGISTER_DIG_T1 = 0x88, + BMP280_REGISTER_DIG_T2 = 0x8A, + BMP280_REGISTER_DIG_T3 = 0x8C, + BMP280_REGISTER_DIG_P1 = 0x8E, + BMP280_REGISTER_DIG_P2 = 0x90, + BMP280_REGISTER_DIG_P3 = 0x92, + BMP280_REGISTER_DIG_P4 = 0x94, + BMP280_REGISTER_DIG_P5 = 0x96, + BMP280_REGISTER_DIG_P6 = 0x98, + BMP280_REGISTER_DIG_P7 = 0x9A, + BMP280_REGISTER_DIG_P8 = 0x9C, + BMP280_REGISTER_DIG_P9 = 0x9E, + BMP280_REGISTER_CHIPID = 0xD0, + BMP280_REGISTER_VERSION = 0xD1, + BMP280_REGISTER_SOFTRESET = 0xE0, + BMP280_REGISTER_CAL26 = 0xE1, /**< R calibration = 0xE1-0xF0 */ + BMP280_REGISTER_STATUS = 0xF3, + BMP280_REGISTER_CONTROL = 0xF4, + BMP280_REGISTER_CONFIG = 0xF5, + BMP280_REGISTER_PRESSUREDATA = 0xF7, + BMP280_REGISTER_TEMPDATA = 0xFA, +}; + +/*! + * Struct to hold calibration data. + */ +typedef struct { + uint16_t dig_T1; /**< dig_T1 cal register. */ + int16_t dig_T2; /**< dig_T2 cal register. */ + int16_t dig_T3; /**< dig_T3 cal register. */ + + uint16_t dig_P1; /**< dig_P1 cal register. */ + int16_t dig_P2; /**< dig_P2 cal register. */ + int16_t dig_P3; /**< dig_P3 cal register. */ + int16_t dig_P4; /**< dig_P4 cal register. */ + int16_t dig_P5; /**< dig_P5 cal register. */ + int16_t dig_P6; /**< dig_P6 cal register. */ + int16_t dig_P7; /**< dig_P7 cal register. */ + int16_t dig_P8; /**< dig_P8 cal register. */ + int16_t dig_P9; /**< dig_P9 cal register. */ +} bmp280_calib_data; + +class Adafruit_BMP280; + +/** Adafruit Unified Sensor interface for temperature component of BMP280 */ +class Adafruit_BMP280_Temp : public Adafruit_Sensor { +public: + /** @brief Create an Adafruit_Sensor compatible object for the temp sensor + @param parent A pointer to the BMP280 class */ + Adafruit_BMP280_Temp(Adafruit_BMP280 *parent) { _theBMP280 = parent; } + bool getEvent(sensors_event_t *); + void getSensor(sensor_t *); + +private: + int _sensorID = 280; + Adafruit_BMP280 *_theBMP280 = NULL; +}; + +/** Adafruit Unified Sensor interface for pressure component of BMP280 */ +class Adafruit_BMP280_Pressure : public Adafruit_Sensor { +public: + /** @brief Create an Adafruit_Sensor compatible object for the pressure sensor + @param parent A pointer to the BMP280 class */ + Adafruit_BMP280_Pressure(Adafruit_BMP280 *parent) { _theBMP280 = parent; } + bool getEvent(sensors_event_t *); + void getSensor(sensor_t *); + +private: + int _sensorID = 0; + Adafruit_BMP280 *_theBMP280 = NULL; +}; + +/** + * Driver for the Adafruit BMP280 barometric pressure sensor. + */ +class Adafruit_BMP280 { +public: + /** Oversampling rate for the sensor. */ + enum sensor_sampling { + /** No over-sampling. */ + SAMPLING_NONE = 0x00, + /** 1x over-sampling. */ + SAMPLING_X1 = 0x01, + /** 2x over-sampling. */ + SAMPLING_X2 = 0x02, + /** 4x over-sampling. */ + SAMPLING_X4 = 0x03, + /** 8x over-sampling. */ + SAMPLING_X8 = 0x04, + /** 16x over-sampling. */ + SAMPLING_X16 = 0x05 + }; + + /** Operating mode for the sensor. */ + enum sensor_mode { + /** Sleep mode. */ + MODE_SLEEP = 0x00, + /** Forced mode. */ + MODE_FORCED = 0x01, + /** Normal mode. */ + MODE_NORMAL = 0x03, + /** Software reset. */ + MODE_SOFT_RESET_CODE = 0xB6 + }; + + /** Filtering level for sensor data. */ + enum sensor_filter { + /** No filtering. */ + FILTER_OFF = 0x00, + /** 2x filtering. */ + FILTER_X2 = 0x01, + /** 4x filtering. */ + FILTER_X4 = 0x02, + /** 8x filtering. */ + FILTER_X8 = 0x03, + /** 16x filtering. */ + FILTER_X16 = 0x04 + }; + + /** Standby duration in ms */ + enum standby_duration { + /** 1 ms standby. */ + STANDBY_MS_1 = 0x00, + /** 62.5 ms standby. */ + STANDBY_MS_63 = 0x01, + /** 125 ms standby. */ + STANDBY_MS_125 = 0x02, + /** 250 ms standby. */ + STANDBY_MS_250 = 0x03, + /** 500 ms standby. */ + STANDBY_MS_500 = 0x04, + /** 1000 ms standby. */ + STANDBY_MS_1000 = 0x05, + /** 2000 ms standby. */ + STANDBY_MS_2000 = 0x06, + /** 4000 ms standby. */ + STANDBY_MS_4000 = 0x07 + }; + + Adafruit_BMP280(TwoWire *theWire = &Wire); + Adafruit_BMP280(int8_t cspin, SPIClass *theSPI = &SPI); + Adafruit_BMP280(int8_t cspin, int8_t mosipin, int8_t misopin, int8_t sckpin); + ~Adafruit_BMP280(void); + + bool begin(uint8_t addr = BMP280_ADDRESS, uint8_t chipid = BMP280_CHIPID); + void reset(void); + uint8_t getStatus(void); + uint8_t sensorID(void); + + float readTemperature(); + float readPressure(void); + float readAltitude(float seaLevelhPa = 1013.25); + float seaLevelForAltitude(float altitude, float atmospheric); + float waterBoilingPoint(float pressure); + bool takeForcedMeasurement(); + + Adafruit_Sensor *getTemperatureSensor(void); + Adafruit_Sensor *getPressureSensor(void); + + void setSampling(sensor_mode mode = MODE_NORMAL, + sensor_sampling tempSampling = SAMPLING_X16, + sensor_sampling pressSampling = SAMPLING_X16, + sensor_filter filter = FILTER_OFF, + standby_duration duration = STANDBY_MS_1); + +private: + TwoWire *_wire; /**< Wire object */ + Adafruit_I2CDevice *i2c_dev = NULL; ///< Pointer to I2C bus interface + Adafruit_SPIDevice *spi_dev = NULL; ///< Pointer to SPI bus interface + + Adafruit_BMP280_Temp *temp_sensor = NULL; + Adafruit_BMP280_Pressure *pressure_sensor = NULL; + + /** Encapsulates the config register */ + struct config { + /** Initialize to power-on-reset state */ + config() : t_sb(STANDBY_MS_1), filter(FILTER_OFF), none(0), spi3w_en(0) {} + /** Inactive duration (standby time) in normal mode */ + unsigned int t_sb : 3; + /** Filter settings */ + unsigned int filter : 3; + /** Unused - don't set */ + unsigned int none : 1; + /** Enables 3-wire SPI */ + unsigned int spi3w_en : 1; + /** Used to retrieve the assembled config register's byte value. */ + unsigned int get() { return (t_sb << 5) | (filter << 2) | spi3w_en; } + }; + + /** Encapsulates trhe ctrl_meas register */ + struct ctrl_meas { + /** Initialize to power-on-reset state */ + ctrl_meas() + : osrs_t(SAMPLING_NONE), osrs_p(SAMPLING_NONE), mode(MODE_SLEEP) {} + /** Temperature oversampling. */ + unsigned int osrs_t : 3; + /** Pressure oversampling. */ + unsigned int osrs_p : 3; + /** Device mode */ + unsigned int mode : 2; + /** Used to retrieve the assembled ctrl_meas register's byte value. */ + unsigned int get() { return (osrs_t << 5) | (osrs_p << 2) | mode; } + }; + + void readCoefficients(void); + uint8_t spixfer(uint8_t x); + void write8(byte reg, byte value); + uint8_t read8(byte reg); + uint16_t read16(byte reg); + uint32_t read24(byte reg); + int16_t readS16(byte reg); + uint16_t read16_LE(byte reg); + int16_t readS16_LE(byte reg); + + uint8_t _i2caddr; + + int32_t _sensorID = 0; + int32_t t_fine; + // int8_t _cs, _mosi, _miso, _sck; + bmp280_calib_data _bmp280_calib; + config _configReg; + ctrl_meas _measReg; +}; + +#endif diff --git a/firmware/libraries/Adafruit_BMP280_Library/README.md b/firmware/libraries/Adafruit_BMP280_Library/README.md new file mode 100644 index 0000000..dbca8f9 --- /dev/null +++ b/firmware/libraries/Adafruit_BMP280_Library/README.md @@ -0,0 +1,47 @@ +# Adafruit BMP280 Driver (Barometric Pressure Sensor) [![Build Status](https://travis-ci.com/adafruit/Adafruit_BMP280_Library.svg?branch=master)](https://travis-ci.com/adafruit/Adafruit_BMP280_Library) + +This driver is for the [Adafruit BMP280 Breakout](http://www.adafruit.com/products/2651) + + + +## About the BMP280 ## + +This precision sensor from Bosch is the best low-cost sensing solution for measuring barometric pressure and temperature. Because pressure changes with altitude you can also use it as an altimeter! + +## About this Driver ## + +Adafruit invests time and resources providing this open source code. Please support Adafruit and open-source hardware by purchasing products from Adafruit! + +Written by Kevin (KTOWN) Townsend for Adafruit Industries. + + + +## Compatibility + +MCU | Tested Works | Doesn't Work | Not Tested | Notes +------------------ | :----------: | :----------: | :---------: | ----- +Atmega328 @ 16MHz | X | | | +Atmega328 @ 12MHz | X | | | +Atmega32u4 @ 16MHz | X | | | Use SDA/SCL on pins D2 & D3 +Atmega32u4 @ 8MHz | X | | | Use SDA/SCL on pins D2 & D3 +ESP8266 | X | | | SDA/SCL default to pins 4 & 5 but any two pins can be assigned as SDA/SCL using Wire.begin(SDA,SCL) +Atmega2560 @ 16MHz | X | | | Use SDA/SCL on pins 20 & 21 +ATSAM3X8E | X | | | Use SDA/SCL on pins 20 & 21 +ATSAM21D | X | | | +ATtiny85 @ 16MHz | | X | | +ATtiny85 @ 8MHz | | X | | +Intel Curie @ 32MHz | | | X | +STM32F2 | | | X | + + * ATmega328 @ 16MHz : Arduino UNO, Adafruit Pro Trinket 5V, Adafruit Metro 328, Adafruit Metro Mini + * ATmega328 @ 12MHz : Adafruit Pro Trinket 3V + * ATmega32u4 @ 16MHz : Arduino Leonardo, Arduino Micro, Arduino Yun, Teensy 2.0 + * ATmega32u4 @ 8MHz : Adafruit Flora, Bluefruit Micro + * ESP8266 : Adafruit Huzzah + * ATmega2560 @ 16MHz : Arduino Mega + * ATSAM3X8E : Arduino Due + * ATSAM21D : Arduino Zero, M0 Pro + * ATtiny85 @ 16MHz : Adafruit Trinket 5V + * ATtiny85 @ 8MHz : Adafruit Gemma, Arduino Gemma, Adafruit Trinket 3V + + diff --git a/firmware/libraries/Adafruit_BMP280_Library/assets/board.jpg b/firmware/libraries/Adafruit_BMP280_Library/assets/board.jpg new file mode 100644 index 0000000..cd0d947 Binary files /dev/null and b/firmware/libraries/Adafruit_BMP280_Library/assets/board.jpg differ diff --git a/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280_forced/bmp280_forced.ino b/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280_forced/bmp280_forced.ino new file mode 100644 index 0000000..9f48144 --- /dev/null +++ b/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280_forced/bmp280_forced.ino @@ -0,0 +1,72 @@ +/*************************************************************************** + This is a library for the BMP280 humidity, temperature & pressure sensor + + Designed specifically to work with the Adafruit BMP280 Breakout + ----> http://www.adafruit.com/products/2651 + + These sensors use I2C or SPI to communicate, 2 or 4 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! + + Written by Limor Fried & Kevin Townsend for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ***************************************************************************/ + +#include + +#define BMP_SCK (13) +#define BMP_MISO (12) +#define BMP_MOSI (11) +#define BMP_CS (10) + +Adafruit_BMP280 bmp; // I2C +//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI +//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK); + +void setup() { + Serial.begin(9600); + Serial.println(F("BMP280 Forced Mode Test.")); + + //if (!bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID)) { + if (!bmp.begin()) { + Serial.println(F("Could not find a valid BMP280 sensor, check wiring or " + "try a different address!")); + while (1) delay(10); + } + + /* Default settings from datasheet. */ + bmp.setSampling(Adafruit_BMP280::MODE_FORCED, /* Operating Mode. */ + Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */ + Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */ + Adafruit_BMP280::FILTER_X16, /* Filtering. */ + Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */ +} + +void loop() { + // must call this to wake sensor up and get new measurement data + // it blocks until measurement is complete + if (bmp.takeForcedMeasurement()) { + // can now print out the new measurements + Serial.print(F("Temperature = ")); + Serial.print(bmp.readTemperature()); + Serial.println(" *C"); + + Serial.print(F("Pressure = ")); + Serial.print(bmp.readPressure()); + Serial.println(" Pa"); + + Serial.print(F("Approx altitude = ")); + Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */ + Serial.println(" m"); + + Serial.println(); + delay(2000); + } else { + Serial.println("Forced measurement failed!"); + } + + +} diff --git a/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280_sensortest/bmp280_sensortest.ino b/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280_sensortest/bmp280_sensortest.ino new file mode 100644 index 0000000..01adb05 --- /dev/null +++ b/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280_sensortest/bmp280_sensortest.ino @@ -0,0 +1,71 @@ +/*************************************************************************** + This is a library for the BMP280 humidity, temperature & pressure sensor + This example shows how to take Sensor Events instead of direct readings + + Designed specifically to work with the Adafruit BMP280 Breakout + ----> http://www.adafruit.com/products/2651 + + These sensors use I2C or SPI to communicate, 2 or 4 pins are required + to interface. + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing products + from Adafruit! + + Written by Limor Fried & Kevin Townsend for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ***************************************************************************/ + +#include +#include +#include + +Adafruit_BMP280 bmp; // use I2C interface +Adafruit_Sensor *bmp_temp = bmp.getTemperatureSensor(); +Adafruit_Sensor *bmp_pressure = bmp.getPressureSensor(); + +void setup() { + Serial.begin(9600); + while ( !Serial ) delay(100); // wait for native usb + Serial.println(F("BMP280 Sensor event test")); + + unsigned status; + //status = bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID); + status = bmp.begin(); + if (!status) { + Serial.println(F("Could not find a valid BMP280 sensor, check wiring or " + "try a different address!")); + Serial.print("SensorID was: 0x"); Serial.println(bmp.sensorID(),16); + Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n"); + Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n"); + Serial.print(" ID of 0x60 represents a BME 280.\n"); + Serial.print(" ID of 0x61 represents a BME 680.\n"); + while (1) delay(10); + } + + /* Default settings from datasheet. */ + bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */ + Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */ + Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */ + Adafruit_BMP280::FILTER_X16, /* Filtering. */ + Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */ + + bmp_temp->printSensorDetails(); +} + +void loop() { + sensors_event_t temp_event, pressure_event; + bmp_temp->getEvent(&temp_event); + bmp_pressure->getEvent(&pressure_event); + + Serial.print(F("Temperature = ")); + Serial.print(temp_event.temperature); + Serial.println(" *C"); + + Serial.print(F("Pressure = ")); + Serial.print(pressure_event.pressure); + Serial.println(" hPa"); + + Serial.println(); + delay(2000); +} diff --git a/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280test/bmp280test.ino b/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280test/bmp280test.ino new file mode 100644 index 0000000..57838c4 --- /dev/null +++ b/firmware/libraries/Adafruit_BMP280_Library/examples/bmp280test/bmp280test.ino @@ -0,0 +1,72 @@ +/*************************************************************************** + This is a library for the BMP280 humidity, temperature & pressure sensor + + Designed specifically to work with the Adafruit BMP280 Breakout + ----> http://www.adafruit.com/products/2651 + + These sensors use I2C or SPI to communicate, 2 or 4 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! + + Written by Limor Fried & Kevin Townsend for Adafruit Industries. + BSD license, all text above must be included in any redistribution + ***************************************************************************/ + +#include +#include +#include + +#define BMP_SCK (13) +#define BMP_MISO (12) +#define BMP_MOSI (11) +#define BMP_CS (10) + +Adafruit_BMP280 bmp; // I2C +//Adafruit_BMP280 bmp(BMP_CS); // hardware SPI +//Adafruit_BMP280 bmp(BMP_CS, BMP_MOSI, BMP_MISO, BMP_SCK); + +void setup() { + Serial.begin(9600); + while ( !Serial ) delay(100); // wait for native usb + Serial.println(F("BMP280 test")); + unsigned status; + //status = bmp.begin(BMP280_ADDRESS_ALT, BMP280_CHIPID); + status = bmp.begin(); + if (!status) { + Serial.println(F("Could not find a valid BMP280 sensor, check wiring or " + "try a different address!")); + Serial.print("SensorID was: 0x"); Serial.println(bmp.sensorID(),16); + Serial.print(" ID of 0xFF probably means a bad address, a BMP 180 or BMP 085\n"); + Serial.print(" ID of 0x56-0x58 represents a BMP 280,\n"); + Serial.print(" ID of 0x60 represents a BME 280.\n"); + Serial.print(" ID of 0x61 represents a BME 680.\n"); + while (1) delay(10); + } + + /* Default settings from datasheet. */ + bmp.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */ + Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */ + Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */ + Adafruit_BMP280::FILTER_X16, /* Filtering. */ + Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */ +} + +void loop() { + Serial.print(F("Temperature = ")); + Serial.print(bmp.readTemperature()); + Serial.println(" *C"); + + Serial.print(F("Pressure = ")); + Serial.print(bmp.readPressure()); + Serial.println(" Pa"); + + Serial.print(F("Approx altitude = ")); + Serial.print(bmp.readAltitude(1013.25)); /* Adjusted to local forecast! */ + Serial.println(" m"); + + Serial.println(); + delay(2000); +} diff --git a/firmware/libraries/Adafruit_BMP280_Library/keywords.txt b/firmware/libraries/Adafruit_BMP280_Library/keywords.txt new file mode 100644 index 0000000..f0bec42 --- /dev/null +++ b/firmware/libraries/Adafruit_BMP280_Library/keywords.txt @@ -0,0 +1,57 @@ +####################################### +# Syntax Coloring Map for BMP280 library +####################################### + +####################################### +# Datatypes (KEYWORD1) +####################################### +Adafruit_BMP280 KEYWORD1 +Adafruit_BMP280_Temp KEYWORD1 +Adafruit_BMP280_Pressure KEYWORD1 +bmp280_calib_data KEYWORD1 + +####################################### +# Methods and Functions (KEYWORD2) +####################################### +begin KEYWORD2 +reset KEYWORD2 +getStatus KEYWORD2 +sensorID KEYWORD2 +getEvent KEYWORD2 +getSensor KEYWORD2 +readTemperature KEYWORD2 +readPressure KEYWORD2 +readAltitude KEYWORD2 +seaLevelForAltitude KEYWORD2 +waterBoilingPoint KEYWORD2 +takeForcedMeasurement KEYWORD2 +getTemperatureSensor KEYWORD2 +getPressureSensor KEYWORD2 +setSampling KEYWORD2 + +####################################### +# Constants (LITERAL1) +####################################### +SAMPLING_NONE LITERAL1 +SAMPLING_X1 LITERAL1 +SAMPLING_X2 LITERAL1 +SAMPLING_X4 LITERAL1 +SAMPLING_X8 LITERAL1 +SAMPLING_X16 LITERAL1 +MODE_SLEEP LITERAL1 +MODE_FORCED LITERAL1 +MODE_NORMAL LITERAL1 +MODE_SOFT_RESET_CODE LITERAL1 +FILTER_OFF LITERAL1 +FILTER_X2 LITERAL1 +FILTER_X4 LITERAL1 +FILTER_X8 LITERAL1 +FILTER_X16 LITERAL1 +STANDBY_MS_1 LITERAL1 +STANDBY_MS_63 LITERAL1 +STANDBY_MS_125 LITERAL1 +STANDBY_MS_250 LITERAL1 +STANDBY_MS_500 LITERAL1 +STANDBY_MS_1000 LITERAL1 +STANDBY_MS_2000 LITERAL1 +STANDBY_MS_4000 LITERAL1 diff --git a/firmware/libraries/Adafruit_BMP280_Library/library.properties b/firmware/libraries/Adafruit_BMP280_Library/library.properties new file mode 100644 index 0000000..957e4b3 --- /dev/null +++ b/firmware/libraries/Adafruit_BMP280_Library/library.properties @@ -0,0 +1,10 @@ +name=Adafruit BMP280 Library +version=2.6.6 +author=Adafruit +maintainer=Adafruit +sentence=Arduino library for BMP280 sensors. +paragraph=Arduino library for BMP280 pressure and altitude sensors. +category=Sensors +url=https://github.com/adafruit/Adafruit_BMP280_Library +architectures=* +depends=Adafruit Unified Sensor, Adafruit BusIO diff --git a/firmware/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp b/firmware/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp new file mode 100644 index 0000000..a28193f --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.cpp @@ -0,0 +1,365 @@ +#include + +#if !defined(SPI_INTERFACES_COUNT) || \ + (defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0)) + +/*! + * @brief Create a register we access over an I2C Device (which defines the + * bus and address) + * @param i2cdevice The I2CDevice to use for underlying I2C access + * @param reg_addr The address pointer value for the I2C/SMBus register, can + * be 8 or 16 bits + * @param width The width of the register data itself, defaults to 1 byte + * @param byteorder The byte order of the register (used when width is > 1), + * defaults to LSBFIRST + * @param address_width The width of the register address itself, defaults + * to 1 byte + */ +Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice, + uint16_t reg_addr, + uint8_t width, + uint8_t byteorder, + uint8_t address_width) { + _i2cdevice = i2cdevice; + _spidevice = nullptr; + _addrwidth = address_width; + _address = reg_addr; + _byteorder = byteorder; + _width = width; +} + +/*! + * @brief Create a register we access over an SPI Device (which defines the + * bus and CS pin) + * @param spidevice The SPIDevice to use for underlying SPI access + * @param reg_addr The address pointer value for the SPI register, can + * be 8 or 16 bits + * @param type The method we use to read/write data to SPI (which is not + * as well defined as I2C) + * @param width The width of the register data itself, defaults to 1 byte + * @param byteorder The byte order of the register (used when width is > 1), + * defaults to LSBFIRST + * @param address_width The width of the register address itself, defaults + * to 1 byte + */ +Adafruit_BusIO_Register::Adafruit_BusIO_Register(Adafruit_SPIDevice *spidevice, + uint16_t reg_addr, + Adafruit_BusIO_SPIRegType type, + uint8_t width, + uint8_t byteorder, + uint8_t address_width) { + _spidevice = spidevice; + _spiregtype = type; + _i2cdevice = nullptr; + _addrwidth = address_width; + _address = reg_addr; + _byteorder = byteorder; + _width = width; +} + +/*! + * @brief Create a register we access over an I2C or SPI Device. This is a + * handy function because we can pass in nullptr for the unused interface, + * allowing libraries to mass-define all the registers + * @param i2cdevice The I2CDevice to use for underlying I2C access, if + * nullptr we use SPI + * @param spidevice The SPIDevice to use for underlying SPI access, if + * nullptr we use I2C + * @param reg_addr The address pointer value for the I2C/SMBus/SPI register, + * can be 8 or 16 bits + * @param type The method we use to read/write data to SPI (which is not + * as well defined as I2C) + * @param width The width of the register data itself, defaults to 1 byte + * @param byteorder The byte order of the register (used when width is > 1), + * defaults to LSBFIRST + * @param address_width The width of the register address itself, defaults + * to 1 byte + */ +Adafruit_BusIO_Register::Adafruit_BusIO_Register( + Adafruit_I2CDevice *i2cdevice, Adafruit_SPIDevice *spidevice, + Adafruit_BusIO_SPIRegType type, uint16_t reg_addr, uint8_t width, + uint8_t byteorder, uint8_t address_width) { + _spidevice = spidevice; + _i2cdevice = i2cdevice; + _spiregtype = type; + _addrwidth = address_width; + _address = reg_addr; + _byteorder = byteorder; + _width = width; +} + +/*! + * @brief Write a buffer of data to the register location + * @param buffer Pointer to data to write + * @param len Number of bytes to write + * @return True on successful write (only really useful for I2C as SPI is + * uncheckable) + */ +bool Adafruit_BusIO_Register::write(uint8_t *buffer, uint8_t len) { + + uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF), + (uint8_t)(_address >> 8)}; + + if (_i2cdevice) { + return _i2cdevice->write(buffer, len, true, addrbuffer, _addrwidth); + } + if (_spidevice) { + if (_spiregtype == ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE) { + // very special case! + + // pass the special opcode address which we set as the high byte of the + // regaddr + addrbuffer[0] = + (uint8_t)(_address >> 8) & ~0x01; // set bottom bit low to write + // the 'actual' reg addr is the second byte then + addrbuffer[1] = (uint8_t)(_address & 0xFF); + // the address appears to be a byte longer + return _spidevice->write(buffer, len, addrbuffer, _addrwidth + 1); + } + + if (_spiregtype == ADDRBIT8_HIGH_TOREAD) { + addrbuffer[0] &= ~0x80; + } + if (_spiregtype == ADDRBIT8_HIGH_TOWRITE) { + addrbuffer[0] |= 0x80; + } + if (_spiregtype == AD8_HIGH_TOREAD_AD7_HIGH_TOINC) { + addrbuffer[0] &= ~0x80; + addrbuffer[0] |= 0x40; + } + return _spidevice->write(buffer, len, addrbuffer, _addrwidth); + } + return false; +} + +/*! + * @brief Write up to 4 bytes of data to the register location + * @param value Data to write + * @param numbytes How many bytes from 'value' to write + * @return True on successful write (only really useful for I2C as SPI is + * uncheckable) + */ +bool Adafruit_BusIO_Register::write(uint32_t value, uint8_t numbytes) { + if (numbytes == 0) { + numbytes = _width; + } + if (numbytes > 4) { + return false; + } + + // store a copy + _cached = value; + + for (int i = 0; i < numbytes; i++) { + if (_byteorder == LSBFIRST) { + _buffer[i] = value & 0xFF; + } else { + _buffer[numbytes - i - 1] = value & 0xFF; + } + value >>= 8; + } + return write(_buffer, numbytes); +} + +/*! + * @brief Read data from the register location. This does not do any error + * checking! + * @return Returns 0xFFFFFFFF on failure, value otherwise + */ +uint32_t Adafruit_BusIO_Register::read(void) { + if (!read(_buffer, _width)) { + return -1; + } + + uint32_t value = 0; + + for (int i = 0; i < _width; i++) { + value <<= 8; + if (_byteorder == LSBFIRST) { + value |= _buffer[_width - i - 1]; + } else { + value |= _buffer[i]; + } + } + + return value; +} + +/*! + * @brief Read cached data from last time we wrote to this register + * @return Returns 0xFFFFFFFF on failure, value otherwise + */ +uint32_t Adafruit_BusIO_Register::readCached(void) { return _cached; } + +/*! + * @brief Read a buffer of data from the register location + * @param buffer Pointer to data to read into + * @param len Number of bytes to read + * @return True on successful write (only really useful for I2C as SPI is + * uncheckable) + */ +bool Adafruit_BusIO_Register::read(uint8_t *buffer, uint8_t len) { + uint8_t addrbuffer[2] = {(uint8_t)(_address & 0xFF), + (uint8_t)(_address >> 8)}; + + if (_i2cdevice) { + return _i2cdevice->write_then_read(addrbuffer, _addrwidth, buffer, len); + } + if (_spidevice) { + if (_spiregtype == ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE) { + // very special case! + + // pass the special opcode address which we set as the high byte of the + // regaddr + addrbuffer[0] = + (uint8_t)(_address >> 8) | 0x01; // set bottom bit high to read + // the 'actual' reg addr is the second byte then + addrbuffer[1] = (uint8_t)(_address & 0xFF); + // the address appears to be a byte longer + return _spidevice->write_then_read(addrbuffer, _addrwidth + 1, buffer, + len); + } + if (_spiregtype == ADDRBIT8_HIGH_TOREAD) { + addrbuffer[0] |= 0x80; + } + if (_spiregtype == ADDRBIT8_HIGH_TOWRITE) { + addrbuffer[0] &= ~0x80; + } + if (_spiregtype == AD8_HIGH_TOREAD_AD7_HIGH_TOINC) { + addrbuffer[0] |= 0x80 | 0x40; + } + return _spidevice->write_then_read(addrbuffer, _addrwidth, buffer, len); + } + return false; +} + +/*! + * @brief Read 2 bytes of data from the register location + * @param value Pointer to uint16_t variable to read into + * @return True on successful write (only really useful for I2C as SPI is + * uncheckable) + */ +bool Adafruit_BusIO_Register::read(uint16_t *value) { + if (!read(_buffer, 2)) { + return false; + } + + if (_byteorder == LSBFIRST) { + *value = _buffer[1]; + *value <<= 8; + *value |= _buffer[0]; + } else { + *value = _buffer[0]; + *value <<= 8; + *value |= _buffer[1]; + } + return true; +} + +/*! + * @brief Read 1 byte of data from the register location + * @param value Pointer to uint8_t variable to read into + * @return True on successful write (only really useful for I2C as SPI is + * uncheckable) + */ +bool Adafruit_BusIO_Register::read(uint8_t *value) { + if (!read(_buffer, 1)) { + return false; + } + + *value = _buffer[0]; + return true; +} + +/*! + * @brief Pretty printer for this register + * @param s The Stream to print to, defaults to &Serial + */ +void Adafruit_BusIO_Register::print(Stream *s) { + uint32_t val = read(); + s->print("0x"); + s->print(val, HEX); +} + +/*! + * @brief Pretty printer for this register + * @param s The Stream to print to, defaults to &Serial + */ +void Adafruit_BusIO_Register::println(Stream *s) { + print(s); + s->println(); +} + +/*! + * @brief Create a slice of the register that we can address without + * touching other bits + * @param reg The Adafruit_BusIO_Register which defines the bus/register + * @param bits The number of bits wide we are slicing + * @param shift The number of bits that our bit-slice is shifted from LSB + */ +Adafruit_BusIO_RegisterBits::Adafruit_BusIO_RegisterBits( + Adafruit_BusIO_Register *reg, uint8_t bits, uint8_t shift) { + _register = reg; + _bits = bits; + _shift = shift; +} + +/*! + * @brief Read 4 bytes of data from the register + * @return data The 4 bytes to read + */ +uint32_t Adafruit_BusIO_RegisterBits::read(void) { + uint32_t val = _register->read(); + val >>= _shift; + return val & ((1 << (_bits)) - 1); +} + +/*! + * @brief Write 4 bytes of data to the register + * @param data The 4 bytes to write + * @return True on successful write (only really useful for I2C as SPI is + * uncheckable) + */ +bool Adafruit_BusIO_RegisterBits::write(uint32_t data) { + uint32_t val = _register->read(); + + // mask off the data before writing + uint32_t mask = (1 << (_bits)) - 1; + data &= mask; + + mask <<= _shift; + val &= ~mask; // remove the current data at that spot + val |= data << _shift; // and add in the new data + + return _register->write(val, _register->width()); +} + +/*! + * @brief The width of the register data, helpful for doing calculations + * @returns The data width used when initializing the register + */ +uint8_t Adafruit_BusIO_Register::width(void) { return _width; } + +/*! + * @brief Set the default width of data + * @param width the default width of data read from register + */ +void Adafruit_BusIO_Register::setWidth(uint8_t width) { _width = width; } + +/*! + * @brief Set register address + * @param address the address from register + */ +void Adafruit_BusIO_Register::setAddress(uint16_t address) { + _address = address; +} + +/*! + * @brief Set the width of register address + * @param address_width the width for register address + */ +void Adafruit_BusIO_Register::setAddressWidth(uint16_t address_width) { + _addrwidth = address_width; +} + +#endif // SPI exists diff --git a/firmware/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.h b/firmware/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.h new file mode 100644 index 0000000..c6d58de --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/Adafruit_BusIO_Register.h @@ -0,0 +1,105 @@ +#ifndef Adafruit_BusIO_Register_h +#define Adafruit_BusIO_Register_h + +#include + +#if !defined(SPI_INTERFACES_COUNT) || \ + (defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0)) + +#include +#include + +typedef enum _Adafruit_BusIO_SPIRegType { + ADDRBIT8_HIGH_TOREAD = 0, + /*!< + * ADDRBIT8_HIGH_TOREAD + * When reading a register you must actually send the value 0x80 + register + * address to the device. e.g. To read the register 0x0B the register value + * 0x8B is sent and to write 0x0B is sent. + */ + AD8_HIGH_TOREAD_AD7_HIGH_TOINC = 1, + + /*!< + * ADDRBIT8_HIGH_TOWRITE + * When writing to a register you must actually send the value 0x80 + + * the register address to the device. e.g. To write to the register 0x19 the + * register value 0x99 is sent and to read 0x19 is sent. + */ + ADDRBIT8_HIGH_TOWRITE = 2, + + /*!< + * ADDRESSED_OPCODE_LOWBIT_TO_WRITE + * Used by the MCP23S series, we send 0x40 |'rd with the opcode + * Then set the lowest bit to write + */ + ADDRESSED_OPCODE_BIT0_LOW_TO_WRITE = 3, + +} Adafruit_BusIO_SPIRegType; + +/*! + * @brief The class which defines a device register (a location to read/write + * data from) + */ +class Adafruit_BusIO_Register { +public: + Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice, uint16_t reg_addr, + uint8_t width = 1, uint8_t byteorder = LSBFIRST, + uint8_t address_width = 1); + + Adafruit_BusIO_Register(Adafruit_SPIDevice *spidevice, uint16_t reg_addr, + Adafruit_BusIO_SPIRegType type, uint8_t width = 1, + uint8_t byteorder = LSBFIRST, + uint8_t address_width = 1); + + Adafruit_BusIO_Register(Adafruit_I2CDevice *i2cdevice, + Adafruit_SPIDevice *spidevice, + Adafruit_BusIO_SPIRegType type, uint16_t reg_addr, + uint8_t width = 1, uint8_t byteorder = LSBFIRST, + uint8_t address_width = 1); + + bool read(uint8_t *buffer, uint8_t len); + bool read(uint8_t *value); + bool read(uint16_t *value); + uint32_t read(void); + uint32_t readCached(void); + bool write(uint8_t *buffer, uint8_t len); + bool write(uint32_t value, uint8_t numbytes = 0); + + uint8_t width(void); + + void setWidth(uint8_t width); + void setAddress(uint16_t address); + void setAddressWidth(uint16_t address_width); + + void print(Stream *s = &Serial); + void println(Stream *s = &Serial); + +private: + Adafruit_I2CDevice *_i2cdevice; + Adafruit_SPIDevice *_spidevice; + Adafruit_BusIO_SPIRegType _spiregtype; + uint16_t _address; + uint8_t _width, _addrwidth, _byteorder; + uint8_t _buffer[4]; // we won't support anything larger than uint32 for + // non-buffered read + uint32_t _cached = 0; +}; + +/*! + * @brief The class which defines a slice of bits from within a device register + * (a location to read/write data from) + */ +class Adafruit_BusIO_RegisterBits { +public: + Adafruit_BusIO_RegisterBits(Adafruit_BusIO_Register *reg, uint8_t bits, + uint8_t shift); + bool write(uint32_t value); + uint32_t read(void); + +private: + Adafruit_BusIO_Register *_register; + uint8_t _bits, _shift; +}; + +#endif // SPI exists +#endif // BusIO_Register_h diff --git a/firmware/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp b/firmware/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp new file mode 100644 index 0000000..9b518b4 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/Adafruit_I2CDevice.cpp @@ -0,0 +1,313 @@ +#include "Adafruit_I2CDevice.h" + +//#define DEBUG_SERIAL Serial + +/*! + * @brief Create an I2C device at a given address + * @param addr The 7-bit I2C address for the device + * @param theWire The I2C bus to use, defaults to &Wire + */ +Adafruit_I2CDevice::Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire) { + _addr = addr; + _wire = theWire; + _begun = false; +#ifdef ARDUINO_ARCH_SAMD + _maxBufferSize = 250; // as defined in Wire.h's RingBuffer +#elif defined(ESP32) + _maxBufferSize = I2C_BUFFER_LENGTH; +#else + _maxBufferSize = 32; +#endif +} + +/*! + * @brief Initializes and does basic address detection + * @param addr_detect Whether we should attempt to detect the I2C address + * with a scan. 99% of sensors/devices don't mind but once in a while, they spaz + * on a scan! + * @return True if I2C initialized and a device with the addr found + */ +bool Adafruit_I2CDevice::begin(bool addr_detect) { + _wire->begin(); + _begun = true; + + if (addr_detect) { + return detected(); + } + return true; +} + +/*! + * @brief De-initialize device, turn off the Wire interface + */ +void Adafruit_I2CDevice::end(void) { + // Not all port implement Wire::end(), such as + // - ESP8266 + // - AVR core without WIRE_HAS_END + // - ESP32: end() is implemented since 2.0.1 which is latest at the moment. + // Temporarily disable for now to give time for user to update. +#if !(defined(ESP8266) || \ + (defined(ARDUINO_ARCH_AVR) && !defined(WIRE_HAS_END)) || \ + defined(ARDUINO_ARCH_ESP32)) + _wire->end(); + _begun = false; +#endif +} + +/*! + * @brief Scans I2C for the address - note will give a false-positive + * if there's no pullups on I2C + * @return True if I2C initialized and a device with the addr found + */ +bool Adafruit_I2CDevice::detected(void) { + // Init I2C if not done yet + if (!_begun && !begin()) { + return false; + } + + // A basic scanner, see if it ACK's + _wire->beginTransmission(_addr); + if (_wire->endTransmission() == 0) { +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.println(F("Detected")); +#endif + return true; + } +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.println(F("Not detected")); +#endif + return false; +} + +/*! + * @brief Write a buffer or two to the I2C device. Cannot be more than + * maxBufferSize() bytes. + * @param buffer Pointer to buffer of data to write. This is const to + * ensure the content of this buffer doesn't change. + * @param len Number of bytes from buffer to write + * @param prefix_buffer Pointer to optional array of data to write before + * buffer. Cannot be more than maxBufferSize() bytes. This is const to + * ensure the content of this buffer doesn't change. + * @param prefix_len Number of bytes from prefix buffer to write + * @param stop Whether to send an I2C STOP signal on write + * @return True if write was successful, otherwise false. + */ +bool Adafruit_I2CDevice::write(const uint8_t *buffer, size_t len, bool stop, + const uint8_t *prefix_buffer, + size_t prefix_len) { + if ((len + prefix_len) > maxBufferSize()) { + // currently not guaranteed to work if more than 32 bytes! + // we will need to find out if some platforms have larger + // I2C buffer sizes :/ +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.println(F("\tI2CDevice could not write such a large buffer")); +#endif + return false; + } + + _wire->beginTransmission(_addr); + + // Write the prefix data (usually an address) + if ((prefix_len != 0) && (prefix_buffer != nullptr)) { + if (_wire->write(prefix_buffer, prefix_len) != prefix_len) { +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.println(F("\tI2CDevice failed to write")); +#endif + return false; + } + } + + // Write the data itself + if (_wire->write(buffer, len) != len) { +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.println(F("\tI2CDevice failed to write")); +#endif + return false; + } + +#ifdef DEBUG_SERIAL + + DEBUG_SERIAL.print(F("\tI2CWRITE @ 0x")); + DEBUG_SERIAL.print(_addr, HEX); + DEBUG_SERIAL.print(F(" :: ")); + if ((prefix_len != 0) && (prefix_buffer != nullptr)) { + for (uint16_t i = 0; i < prefix_len; i++) { + DEBUG_SERIAL.print(F("0x")); + DEBUG_SERIAL.print(prefix_buffer[i], HEX); + DEBUG_SERIAL.print(F(", ")); + } + } + for (uint16_t i = 0; i < len; i++) { + DEBUG_SERIAL.print(F("0x")); + DEBUG_SERIAL.print(buffer[i], HEX); + DEBUG_SERIAL.print(F(", ")); + if (i % 32 == 31) { + DEBUG_SERIAL.println(); + } + } + + if (stop) { + DEBUG_SERIAL.print("\tSTOP"); + } +#endif + + if (_wire->endTransmission(stop) == 0) { +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.println(); + // DEBUG_SERIAL.println("Sent!"); +#endif + return true; + } else { +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.println("\tFailed to send!"); +#endif + return false; + } +} + +/*! + * @brief Read from I2C into a buffer from the I2C device. + * Cannot be more than maxBufferSize() bytes. + * @param buffer Pointer to buffer of data to read into + * @param len Number of bytes from buffer to read. + * @param stop Whether to send an I2C STOP signal on read + * @return True if read was successful, otherwise false. + */ +bool Adafruit_I2CDevice::read(uint8_t *buffer, size_t len, bool stop) { + size_t pos = 0; + while (pos < len) { + size_t read_len = + ((len - pos) > maxBufferSize()) ? maxBufferSize() : (len - pos); + bool read_stop = (pos < (len - read_len)) ? false : stop; + if (!_read(buffer + pos, read_len, read_stop)) + return false; + pos += read_len; + } + return true; +} + +bool Adafruit_I2CDevice::_read(uint8_t *buffer, size_t len, bool stop) { +#if defined(TinyWireM_h) + size_t recv = _wire->requestFrom((uint8_t)_addr, (uint8_t)len); +#elif defined(ARDUINO_ARCH_MEGAAVR) + size_t recv = _wire->requestFrom(_addr, len, stop); +#else + size_t recv = _wire->requestFrom((uint8_t)_addr, (uint8_t)len, (uint8_t)stop); +#endif + + if (recv != len) { + // Not enough data available to fulfill our obligation! +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.print(F("\tI2CDevice did not receive enough data: ")); + DEBUG_SERIAL.println(recv); +#endif + return false; + } + + for (uint16_t i = 0; i < len; i++) { + buffer[i] = _wire->read(); + } + +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.print(F("\tI2CREAD @ 0x")); + DEBUG_SERIAL.print(_addr, HEX); + DEBUG_SERIAL.print(F(" :: ")); + for (uint16_t i = 0; i < len; i++) { + DEBUG_SERIAL.print(F("0x")); + DEBUG_SERIAL.print(buffer[i], HEX); + DEBUG_SERIAL.print(F(", ")); + if (len % 32 == 31) { + DEBUG_SERIAL.println(); + } + } + DEBUG_SERIAL.println(); +#endif + + return true; +} + +/*! + * @brief Write some data, then read some data from I2C into another buffer. + * Cannot be more than maxBufferSize() bytes. The buffers can point to + * same/overlapping locations. + * @param write_buffer Pointer to buffer of data to write from + * @param write_len Number of bytes from buffer to write. + * @param read_buffer Pointer to buffer of data to read into. + * @param read_len Number of bytes from buffer to read. + * @param stop Whether to send an I2C STOP signal between the write and read + * @return True if write & read was successful, otherwise false. + */ +bool Adafruit_I2CDevice::write_then_read(const uint8_t *write_buffer, + size_t write_len, uint8_t *read_buffer, + size_t read_len, bool stop) { + if (!write(write_buffer, write_len, stop)) { + return false; + } + + return read(read_buffer, read_len); +} + +/*! + * @brief Returns the 7-bit address of this device + * @return The 7-bit address of this device + */ +uint8_t Adafruit_I2CDevice::address(void) { return _addr; } + +/*! + * @brief Change the I2C clock speed to desired (relies on + * underlying Wire support! + * @param desiredclk The desired I2C SCL frequency + * @return True if this platform supports changing I2C speed. + * Not necessarily that the speed was achieved! + */ +bool Adafruit_I2CDevice::setSpeed(uint32_t desiredclk) { +#if defined(__AVR_ATmega328__) || \ + defined(__AVR_ATmega328P__) // fix arduino core set clock + // calculate TWBR correctly + + if ((F_CPU / 18) < desiredclk) { +#ifdef DEBUG_SERIAL + Serial.println(F("I2C.setSpeed too high.")); +#endif + return false; + } + uint32_t atwbr = ((F_CPU / desiredclk) - 16) / 2; + if (atwbr > 16320) { +#ifdef DEBUG_SERIAL + Serial.println(F("I2C.setSpeed too low.")); +#endif + return false; + } + + if (atwbr <= 255) { + atwbr /= 1; + TWSR = 0x0; + } else if (atwbr <= 1020) { + atwbr /= 4; + TWSR = 0x1; + } else if (atwbr <= 4080) { + atwbr /= 16; + TWSR = 0x2; + } else { // if (atwbr <= 16320) + atwbr /= 64; + TWSR = 0x3; + } + TWBR = atwbr; + +#ifdef DEBUG_SERIAL + Serial.print(F("TWSR prescaler = ")); + Serial.println(pow(4, TWSR)); + Serial.print(F("TWBR = ")); + Serial.println(atwbr); +#endif + return true; +#elif (ARDUINO >= 157) && !defined(ARDUINO_STM32_FEATHER) && \ + !defined(TinyWireM_h) + _wire->setClock(desiredclk); + return true; + +#else + (void)desiredclk; + return false; +#endif +} diff --git a/firmware/libraries/Adafruit_BusIO/Adafruit_I2CDevice.h b/firmware/libraries/Adafruit_BusIO/Adafruit_I2CDevice.h new file mode 100644 index 0000000..6bda7ba --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/Adafruit_I2CDevice.h @@ -0,0 +1,36 @@ +#ifndef Adafruit_I2CDevice_h +#define Adafruit_I2CDevice_h + +#include +#include + +///< The class which defines how we will talk to this device over I2C +class Adafruit_I2CDevice { +public: + Adafruit_I2CDevice(uint8_t addr, TwoWire *theWire = &Wire); + uint8_t address(void); + bool begin(bool addr_detect = true); + void end(void); + bool detected(void); + + bool read(uint8_t *buffer, size_t len, bool stop = true); + bool write(const uint8_t *buffer, size_t len, bool stop = true, + const uint8_t *prefix_buffer = nullptr, size_t prefix_len = 0); + bool write_then_read(const uint8_t *write_buffer, size_t write_len, + uint8_t *read_buffer, size_t read_len, + bool stop = false); + bool setSpeed(uint32_t desiredclk); + + /*! @brief How many bytes we can read in a transaction + * @return The size of the Wire receive/transmit buffer */ + size_t maxBufferSize() { return _maxBufferSize; } + +private: + uint8_t _addr; + TwoWire *_wire; + bool _begun; + size_t _maxBufferSize; + bool _read(uint8_t *buffer, size_t len, bool stop); +}; + +#endif // Adafruit_I2CDevice_h diff --git a/firmware/libraries/Adafruit_BusIO/Adafruit_I2CRegister.h b/firmware/libraries/Adafruit_BusIO/Adafruit_I2CRegister.h new file mode 100644 index 0000000..186850f --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/Adafruit_I2CRegister.h @@ -0,0 +1,10 @@ +#ifndef _ADAFRUIT_I2C_REGISTER_H_ +#define _ADAFRUIT_I2C_REGISTER_H_ + +#include +#include + +typedef Adafruit_BusIO_Register Adafruit_I2CRegister; +typedef Adafruit_BusIO_RegisterBits Adafruit_I2CRegisterBits; + +#endif diff --git a/firmware/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp b/firmware/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp new file mode 100644 index 0000000..6f0069b --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/Adafruit_SPIDevice.cpp @@ -0,0 +1,508 @@ +#include "Adafruit_SPIDevice.h" + +//#define DEBUG_SERIAL Serial + +/*! + * @brief Create an SPI device with the given CS pin and settings + * @param cspin The arduino pin number to use for chip select + * @param freq The SPI clock frequency to use, defaults to 1MHz + * @param dataOrder The SPI data order to use for bits within each byte, + * defaults to SPI_BITORDER_MSBFIRST + * @param dataMode The SPI mode to use, defaults to SPI_MODE0 + * @param theSPI The SPI bus to use, defaults to &theSPI + */ +Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, uint32_t freq, + BusIOBitOrder dataOrder, + uint8_t dataMode, SPIClass *theSPI) { +#ifdef BUSIO_HAS_HW_SPI + _cs = cspin; + _sck = _mosi = _miso = -1; + _spi = theSPI; + _begun = false; + _spiSetting = new SPISettings(freq, dataOrder, dataMode); + _freq = freq; + _dataOrder = dataOrder; + _dataMode = dataMode; +#else + // unused, but needed to suppress compiler warns + (void)cspin; + (void)freq; + (void)dataOrder; + (void)dataMode; + (void)theSPI; +#endif +} + +/*! + * @brief Create an SPI device with the given CS pin and settings + * @param cspin The arduino pin number to use for chip select + * @param sckpin The arduino pin number to use for SCK + * @param misopin The arduino pin number to use for MISO, set to -1 if not + * used + * @param mosipin The arduino pin number to use for MOSI, set to -1 if not + * used + * @param freq The SPI clock frequency to use, defaults to 1MHz + * @param dataOrder The SPI data order to use for bits within each byte, + * defaults to SPI_BITORDER_MSBFIRST + * @param dataMode The SPI mode to use, defaults to SPI_MODE0 + */ +Adafruit_SPIDevice::Adafruit_SPIDevice(int8_t cspin, int8_t sckpin, + int8_t misopin, int8_t mosipin, + uint32_t freq, BusIOBitOrder dataOrder, + uint8_t dataMode) { + _cs = cspin; + _sck = sckpin; + _miso = misopin; + _mosi = mosipin; + +#ifdef BUSIO_USE_FAST_PINIO + csPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(cspin)); + csPinMask = digitalPinToBitMask(cspin); + if (mosipin != -1) { + mosiPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(mosipin)); + mosiPinMask = digitalPinToBitMask(mosipin); + } + if (misopin != -1) { + misoPort = (BusIO_PortReg *)portInputRegister(digitalPinToPort(misopin)); + misoPinMask = digitalPinToBitMask(misopin); + } + clkPort = (BusIO_PortReg *)portOutputRegister(digitalPinToPort(sckpin)); + clkPinMask = digitalPinToBitMask(sckpin); +#endif + + _freq = freq; + _dataOrder = dataOrder; + _dataMode = dataMode; + _begun = false; +} + +/*! + * @brief Release memory allocated in constructors + */ +Adafruit_SPIDevice::~Adafruit_SPIDevice() { + if (_spiSetting) + delete _spiSetting; +} + +/*! + * @brief Initializes SPI bus and sets CS pin high + * @return Always returns true because there's no way to test success of SPI + * init + */ +bool Adafruit_SPIDevice::begin(void) { + if (_cs != -1) { + pinMode(_cs, OUTPUT); + digitalWrite(_cs, HIGH); + } + + if (_spi) { // hardware SPI +#ifdef BUSIO_HAS_HW_SPI + _spi->begin(); +#endif + } else { + pinMode(_sck, OUTPUT); + + if ((_dataMode == SPI_MODE0) || (_dataMode == SPI_MODE1)) { + // idle low on mode 0 and 1 + digitalWrite(_sck, LOW); + } else { + // idle high on mode 2 or 3 + digitalWrite(_sck, HIGH); + } + if (_mosi != -1) { + pinMode(_mosi, OUTPUT); + digitalWrite(_mosi, HIGH); + } + if (_miso != -1) { + pinMode(_miso, INPUT); + } + } + + _begun = true; + return true; +} + +/*! + * @brief Transfer (send/receive) a buffer over hard/soft SPI, without + * transaction management + * @param buffer The buffer to send and receive at the same time + * @param len The number of bytes to transfer + */ +void Adafruit_SPIDevice::transfer(uint8_t *buffer, size_t len) { + // + // HARDWARE SPI + // + if (_spi) { +#ifdef BUSIO_HAS_HW_SPI +#if defined(SPARK) + _spi->transfer(buffer, buffer, len, nullptr); +#elif defined(STM32) + for (size_t i = 0; i < len; i++) { + _spi->transfer(buffer[i]); + } +#else + _spi->transfer(buffer, len); +#endif + return; +#endif + } + + // + // SOFTWARE SPI + // + uint8_t startbit; + if (_dataOrder == SPI_BITORDER_LSBFIRST) { + startbit = 0x1; + } else { + startbit = 0x80; + } + + bool towrite, lastmosi = !(buffer[0] & startbit); + uint8_t bitdelay_us = (1000000 / _freq) / 2; + + for (size_t i = 0; i < len; i++) { + uint8_t reply = 0; + uint8_t send = buffer[i]; + + /* + Serial.print("\tSending software SPI byte 0x"); + Serial.print(send, HEX); + Serial.print(" -> 0x"); + */ + + // Serial.print(send, HEX); + for (uint8_t b = startbit; b != 0; + b = (_dataOrder == SPI_BITORDER_LSBFIRST) ? b << 1 : b >> 1) { + + if (bitdelay_us) { + delayMicroseconds(bitdelay_us); + } + + if (_dataMode == SPI_MODE0 || _dataMode == SPI_MODE2) { + towrite = send & b; + if ((_mosi != -1) && (lastmosi != towrite)) { +#ifdef BUSIO_USE_FAST_PINIO + if (towrite) + *mosiPort |= mosiPinMask; + else + *mosiPort &= ~mosiPinMask; +#else + digitalWrite(_mosi, towrite); +#endif + lastmosi = towrite; + } + +#ifdef BUSIO_USE_FAST_PINIO + *clkPort |= clkPinMask; // Clock high +#else + digitalWrite(_sck, HIGH); +#endif + + if (bitdelay_us) { + delayMicroseconds(bitdelay_us); + } + + if (_miso != -1) { +#ifdef BUSIO_USE_FAST_PINIO + if (*misoPort & misoPinMask) { +#else + if (digitalRead(_miso)) { +#endif + reply |= b; + } + } + +#ifdef BUSIO_USE_FAST_PINIO + *clkPort &= ~clkPinMask; // Clock low +#else + digitalWrite(_sck, LOW); +#endif + } else { // if (_dataMode == SPI_MODE1 || _dataMode == SPI_MODE3) + +#ifdef BUSIO_USE_FAST_PINIO + *clkPort |= clkPinMask; // Clock high +#else + digitalWrite(_sck, HIGH); +#endif + + if (bitdelay_us) { + delayMicroseconds(bitdelay_us); + } + + if (_mosi != -1) { +#ifdef BUSIO_USE_FAST_PINIO + if (send & b) + *mosiPort |= mosiPinMask; + else + *mosiPort &= ~mosiPinMask; +#else + digitalWrite(_mosi, send & b); +#endif + } + +#ifdef BUSIO_USE_FAST_PINIO + *clkPort &= ~clkPinMask; // Clock low +#else + digitalWrite(_sck, LOW); +#endif + + if (_miso != -1) { +#ifdef BUSIO_USE_FAST_PINIO + if (*misoPort & misoPinMask) { +#else + if (digitalRead(_miso)) { +#endif + reply |= b; + } + } + } + if (_miso != -1) { + buffer[i] = reply; + } + } + } + return; +} + +/*! + * @brief Transfer (send/receive) one byte over hard/soft SPI, without + * transaction management + * @param send The byte to send + * @return The byte received while transmitting + */ +uint8_t Adafruit_SPIDevice::transfer(uint8_t send) { + uint8_t data = send; + transfer(&data, 1); + return data; +} + +/*! + * @brief Manually begin a transaction (calls beginTransaction if hardware + * SPI) + */ +void Adafruit_SPIDevice::beginTransaction(void) { + if (_spi) { +#ifdef BUSIO_HAS_HW_SPI + _spi->beginTransaction(*_spiSetting); +#endif + } +} + +/*! + * @brief Manually end a transaction (calls endTransaction if hardware SPI) + */ +void Adafruit_SPIDevice::endTransaction(void) { + if (_spi) { +#ifdef BUSIO_HAS_HW_SPI + _spi->endTransaction(); +#endif + } +} + +/*! + * @brief Assert/Deassert the CS pin if it is defined + * @param value The state the CS is set to + */ +void Adafruit_SPIDevice::setChipSelect(int value) { + if (_cs != -1) { + digitalWrite(_cs, value); + } +} + +/*! + * @brief Write a buffer or two to the SPI device, with transaction + * management. + * @brief Manually begin a transaction (calls beginTransaction if hardware + * SPI) with asserting the CS pin + */ +void Adafruit_SPIDevice::beginTransactionWithAssertingCS() { + beginTransaction(); + setChipSelect(LOW); +} + +/*! + * @brief Manually end a transaction (calls endTransaction if hardware SPI) + * with deasserting the CS pin + */ +void Adafruit_SPIDevice::endTransactionWithDeassertingCS() { + setChipSelect(HIGH); + endTransaction(); +} + +/*! + * @brief Write a buffer or two to the SPI device, with transaction + * management. + * @param buffer Pointer to buffer of data to write + * @param len Number of bytes from buffer to write + * @param prefix_buffer Pointer to optional array of data to write before + * buffer. + * @param prefix_len Number of bytes from prefix buffer to write + * @return Always returns true because there's no way to test success of SPI + * writes + */ +bool Adafruit_SPIDevice::write(const uint8_t *buffer, size_t len, + const uint8_t *prefix_buffer, + size_t prefix_len) { + beginTransactionWithAssertingCS(); + + // do the writing +#if defined(ARDUINO_ARCH_ESP32) + if (_spi) { + if (prefix_len > 0) { + _spi->transferBytes(prefix_buffer, nullptr, prefix_len); + } + if (len > 0) { + _spi->transferBytes(buffer, nullptr, len); + } + } else +#endif + { + for (size_t i = 0; i < prefix_len; i++) { + transfer(prefix_buffer[i]); + } + for (size_t i = 0; i < len; i++) { + transfer(buffer[i]); + } + } + endTransactionWithDeassertingCS(); + +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.print(F("\tSPIDevice Wrote: ")); + if ((prefix_len != 0) && (prefix_buffer != nullptr)) { + for (uint16_t i = 0; i < prefix_len; i++) { + DEBUG_SERIAL.print(F("0x")); + DEBUG_SERIAL.print(prefix_buffer[i], HEX); + DEBUG_SERIAL.print(F(", ")); + } + } + for (uint16_t i = 0; i < len; i++) { + DEBUG_SERIAL.print(F("0x")); + DEBUG_SERIAL.print(buffer[i], HEX); + DEBUG_SERIAL.print(F(", ")); + if (i % 32 == 31) { + DEBUG_SERIAL.println(); + } + } + DEBUG_SERIAL.println(); +#endif + + return true; +} + +/*! + * @brief Read from SPI into a buffer from the SPI device, with transaction + * management. + * @param buffer Pointer to buffer of data to read into + * @param len Number of bytes from buffer to read. + * @param sendvalue The 8-bits of data to write when doing the data read, + * defaults to 0xFF + * @return Always returns true because there's no way to test success of SPI + * writes + */ +bool Adafruit_SPIDevice::read(uint8_t *buffer, size_t len, uint8_t sendvalue) { + memset(buffer, sendvalue, len); // clear out existing buffer + + beginTransactionWithAssertingCS(); + transfer(buffer, len); + endTransactionWithDeassertingCS(); + +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.print(F("\tSPIDevice Read: ")); + for (uint16_t i = 0; i < len; i++) { + DEBUG_SERIAL.print(F("0x")); + DEBUG_SERIAL.print(buffer[i], HEX); + DEBUG_SERIAL.print(F(", ")); + if (len % 32 == 31) { + DEBUG_SERIAL.println(); + } + } + DEBUG_SERIAL.println(); +#endif + + return true; +} + +/*! + * @brief Write some data, then read some data from SPI into another buffer, + * with transaction management. The buffers can point to same/overlapping + * locations. This does not transmit-receive at the same time! + * @param write_buffer Pointer to buffer of data to write from + * @param write_len Number of bytes from buffer to write. + * @param read_buffer Pointer to buffer of data to read into. + * @param read_len Number of bytes from buffer to read. + * @param sendvalue The 8-bits of data to write when doing the data read, + * defaults to 0xFF + * @return Always returns true because there's no way to test success of SPI + * writes + */ +bool Adafruit_SPIDevice::write_then_read(const uint8_t *write_buffer, + size_t write_len, uint8_t *read_buffer, + size_t read_len, uint8_t sendvalue) { + beginTransactionWithAssertingCS(); + // do the writing +#if defined(ARDUINO_ARCH_ESP32) + if (_spi) { + if (write_len > 0) { + _spi->transferBytes(write_buffer, nullptr, write_len); + } + } else +#endif + { + for (size_t i = 0; i < write_len; i++) { + transfer(write_buffer[i]); + } + } + +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.print(F("\tSPIDevice Wrote: ")); + for (uint16_t i = 0; i < write_len; i++) { + DEBUG_SERIAL.print(F("0x")); + DEBUG_SERIAL.print(write_buffer[i], HEX); + DEBUG_SERIAL.print(F(", ")); + if (write_len % 32 == 31) { + DEBUG_SERIAL.println(); + } + } + DEBUG_SERIAL.println(); +#endif + + // do the reading + for (size_t i = 0; i < read_len; i++) { + read_buffer[i] = transfer(sendvalue); + } + +#ifdef DEBUG_SERIAL + DEBUG_SERIAL.print(F("\tSPIDevice Read: ")); + for (uint16_t i = 0; i < read_len; i++) { + DEBUG_SERIAL.print(F("0x")); + DEBUG_SERIAL.print(read_buffer[i], HEX); + DEBUG_SERIAL.print(F(", ")); + if (read_len % 32 == 31) { + DEBUG_SERIAL.println(); + } + } + DEBUG_SERIAL.println(); +#endif + + endTransactionWithDeassertingCS(); + + return true; +} + +/*! + * @brief Write some data and read some data at the same time from SPI + * into the same buffer, with transaction management. This is basicaly a wrapper + * for transfer() with CS-pin and transaction management. This /does/ + * transmit-receive at the same time! + * @param buffer Pointer to buffer of data to write/read to/from + * @param len Number of bytes from buffer to write/read. + * @return Always returns true because there's no way to test success of SPI + * writes + */ +bool Adafruit_SPIDevice::write_and_read(uint8_t *buffer, size_t len) { + beginTransactionWithAssertingCS(); + transfer(buffer, len); + endTransactionWithDeassertingCS(); + + return true; +} diff --git a/firmware/libraries/Adafruit_BusIO/Adafruit_SPIDevice.h b/firmware/libraries/Adafruit_BusIO/Adafruit_SPIDevice.h new file mode 100644 index 0000000..7a6c0f5 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/Adafruit_SPIDevice.h @@ -0,0 +1,138 @@ +#ifndef Adafruit_SPIDevice_h +#define Adafruit_SPIDevice_h + +#include + +#if !defined(SPI_INTERFACES_COUNT) || \ + (defined(SPI_INTERFACES_COUNT) && (SPI_INTERFACES_COUNT > 0)) +// HW SPI available +#include +#define BUSIO_HAS_HW_SPI +#else +// SW SPI ONLY +enum { SPI_MODE0, SPI_MODE1, SPI_MODE2, _SPI_MODE4 }; +typedef uint8_t SPIClass; +#endif + +// some modern SPI definitions don't have BitOrder enum +#if (defined(__AVR__) && !defined(ARDUINO_ARCH_MEGAAVR)) || \ + defined(ESP8266) || defined(TEENSYDUINO) || defined(SPARK) || \ + defined(ARDUINO_ARCH_SPRESENSE) || defined(MEGATINYCORE) || \ + defined(DXCORE) || defined(ARDUINO_AVR_ATmega4809) || \ + defined(ARDUINO_AVR_ATmega4808) || defined(ARDUINO_AVR_ATmega3209) || \ + defined(ARDUINO_AVR_ATmega3208) || defined(ARDUINO_AVR_ATmega1609) || \ + defined(ARDUINO_AVR_ATmega1608) || defined(ARDUINO_AVR_ATmega809) || \ + defined(ARDUINO_AVR_ATmega808) || defined(ARDUINO_ARCH_ARC32) + +typedef enum _BitOrder { + SPI_BITORDER_MSBFIRST = MSBFIRST, + SPI_BITORDER_LSBFIRST = LSBFIRST, +} BusIOBitOrder; + +#elif defined(ESP32) || defined(__ASR6501__) || defined(__ASR6502__) + +// some modern SPI definitions don't have BitOrder enum and have different SPI +// mode defines +typedef enum _BitOrder { + SPI_BITORDER_MSBFIRST = SPI_MSBFIRST, + SPI_BITORDER_LSBFIRST = SPI_LSBFIRST, +} BusIOBitOrder; + +#else +// Some platforms have a BitOrder enum but its named MSBFIRST/LSBFIRST +#define SPI_BITORDER_MSBFIRST MSBFIRST +#define SPI_BITORDER_LSBFIRST LSBFIRST +typedef BitOrder BusIOBitOrder; +#endif + +#if defined(__IMXRT1062__) // Teensy 4.x +// *Warning* I disabled the usage of FAST_PINIO as the set/clear operations +// used in the cpp file are not atomic and can effect multiple IO pins +// and if an interrupt happens in between the time the code reads the register +// and writes out the updated value, that changes one or more other IO pins +// on that same IO port, those change will be clobbered when the updated +// values are written back. A fast version can be implemented that uses the +// ports set and clear registers which are atomic. +// typedef volatile uint32_t BusIO_PortReg; +// typedef uint32_t BusIO_PortMask; +//#define BUSIO_USE_FAST_PINIO + +#elif defined(__AVR__) || defined(TEENSYDUINO) +typedef volatile uint8_t BusIO_PortReg; +typedef uint8_t BusIO_PortMask; +#define BUSIO_USE_FAST_PINIO + +#elif defined(ESP8266) || defined(ESP32) || defined(__SAM3X8E__) || \ + defined(ARDUINO_ARCH_SAMD) +typedef volatile uint32_t BusIO_PortReg; +typedef uint32_t BusIO_PortMask; +#define BUSIO_USE_FAST_PINIO + +#elif (defined(__arm__) || defined(ARDUINO_FEATHER52)) && \ + !defined(ARDUINO_ARCH_MBED) && !defined(ARDUINO_ARCH_RP2040) +typedef volatile uint32_t BusIO_PortReg; +typedef uint32_t BusIO_PortMask; +#if !defined(__ASR6501__) && !defined(__ASR6502__) +#define BUSIO_USE_FAST_PINIO +#endif + +#else +#undef BUSIO_USE_FAST_PINIO +#endif + +/**! The class which defines how we will talk to this device over SPI **/ +class Adafruit_SPIDevice { +public: +#ifdef BUSIO_HAS_HW_SPI + Adafruit_SPIDevice(int8_t cspin, uint32_t freq = 1000000, + BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST, + uint8_t dataMode = SPI_MODE0, SPIClass *theSPI = &SPI); +#else + Adafruit_SPIDevice(int8_t cspin, uint32_t freq = 1000000, + BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST, + uint8_t dataMode = SPI_MODE0, SPIClass *theSPI = nullptr); +#endif + Adafruit_SPIDevice(int8_t cspin, int8_t sck, int8_t miso, int8_t mosi, + uint32_t freq = 1000000, + BusIOBitOrder dataOrder = SPI_BITORDER_MSBFIRST, + uint8_t dataMode = SPI_MODE0); + ~Adafruit_SPIDevice(); + + bool begin(void); + bool read(uint8_t *buffer, size_t len, uint8_t sendvalue = 0xFF); + bool write(const uint8_t *buffer, size_t len, + const uint8_t *prefix_buffer = nullptr, size_t prefix_len = 0); + bool write_then_read(const uint8_t *write_buffer, size_t write_len, + uint8_t *read_buffer, size_t read_len, + uint8_t sendvalue = 0xFF); + bool write_and_read(uint8_t *buffer, size_t len); + + uint8_t transfer(uint8_t send); + void transfer(uint8_t *buffer, size_t len); + void beginTransaction(void); + void endTransaction(void); + void beginTransactionWithAssertingCS(); + void endTransactionWithDeassertingCS(); + +private: +#ifdef BUSIO_HAS_HW_SPI + SPIClass *_spi = nullptr; + SPISettings *_spiSetting = nullptr; +#else + uint8_t *_spi = nullptr; + uint8_t *_spiSetting = nullptr; +#endif + uint32_t _freq; + BusIOBitOrder _dataOrder; + uint8_t _dataMode; + void setChipSelect(int value); + + int8_t _cs, _sck, _mosi, _miso; +#ifdef BUSIO_USE_FAST_PINIO + BusIO_PortReg *mosiPort, *clkPort, *misoPort, *csPort; + BusIO_PortMask mosiPinMask, misoPinMask, clkPinMask, csPinMask; +#endif + bool _begun; +}; + +#endif // Adafruit_SPIDevice_h diff --git a/firmware/libraries/Adafruit_BusIO/CMakeLists.txt b/firmware/libraries/Adafruit_BusIO/CMakeLists.txt new file mode 100644 index 0000000..a7ea6e9 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/CMakeLists.txt @@ -0,0 +1,11 @@ +# Adafruit Bus IO Library +# https://github.com/adafruit/Adafruit_BusIO +# MIT License + +cmake_minimum_required(VERSION 3.5) + +idf_component_register(SRCS "Adafruit_I2CDevice.cpp" "Adafruit_BusIO_Register.cpp" "Adafruit_SPIDevice.cpp" + INCLUDE_DIRS "." + REQUIRES arduino) + +project(Adafruit_BusIO) diff --git a/firmware/libraries/Adafruit_BusIO/LICENSE b/firmware/libraries/Adafruit_BusIO/LICENSE new file mode 100644 index 0000000..860e3e2 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2017 Adafruit Industries + +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. \ No newline at end of file diff --git a/firmware/libraries/Adafruit_BusIO/README.md b/firmware/libraries/Adafruit_BusIO/README.md new file mode 100644 index 0000000..1cc06a1 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/README.md @@ -0,0 +1,8 @@ +# Adafruit Bus IO Library [![Build Status](https://github.com/adafruit/Adafruit_BusIO/workflows/Arduino%20Library%20CI/badge.svg)](https://github.com/adafruit/Adafruit_BusIO/actions) + + +This is a helper library to abstract away I2C & SPI transactions and registers + +Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! + +MIT license, all text above must be included in any redistribution diff --git a/firmware/libraries/Adafruit_BusIO/component.mk b/firmware/libraries/Adafruit_BusIO/component.mk new file mode 100644 index 0000000..004b18e --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/component.mk @@ -0,0 +1 @@ +COMPONENT_ADD_INCLUDEDIRS = . diff --git a/firmware/libraries/Adafruit_BusIO/examples/i2c_address_detect/i2c_address_detect.ino b/firmware/libraries/Adafruit_BusIO/examples/i2c_address_detect/i2c_address_detect.ino new file mode 100644 index 0000000..b150525 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/examples/i2c_address_detect/i2c_address_detect.ino @@ -0,0 +1,21 @@ +#include + +Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(0x10); + +void setup() { + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("I2C address detection test"); + + if (!i2c_dev.begin()) { + Serial.print("Did not find device at 0x"); + Serial.println(i2c_dev.address(), HEX); + while (1); + } + Serial.print("Device found on address 0x"); + Serial.println(i2c_dev.address(), HEX); +} + +void loop() { + +} diff --git a/firmware/libraries/Adafruit_BusIO/examples/i2c_readwrite/i2c_readwrite.ino b/firmware/libraries/Adafruit_BusIO/examples/i2c_readwrite/i2c_readwrite.ino new file mode 100644 index 0000000..909cf31 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/examples/i2c_readwrite/i2c_readwrite.ino @@ -0,0 +1,41 @@ +#include + +#define I2C_ADDRESS 0x60 +Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS); + + +void setup() { + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("I2C device read and write test"); + + if (!i2c_dev.begin()) { + Serial.print("Did not find device at 0x"); + Serial.println(i2c_dev.address(), HEX); + while (1); + } + Serial.print("Device found on address 0x"); + Serial.println(i2c_dev.address(), HEX); + + uint8_t buffer[32]; + // Try to read 32 bytes + i2c_dev.read(buffer, 32); + Serial.print("Read: "); + for (uint8_t i=0; i<32; i++) { + Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", "); + } + Serial.println(); + + // read a register by writing first, then reading + buffer[0] = 0x0C; // we'll reuse the same buffer + i2c_dev.write_then_read(buffer, 1, buffer, 2, false); + Serial.print("Write then Read: "); + for (uint8_t i=0; i<2; i++) { + Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", "); + } + Serial.println(); +} + +void loop() { + +} diff --git a/firmware/libraries/Adafruit_BusIO/examples/i2c_registers/i2c_registers.ino b/firmware/libraries/Adafruit_BusIO/examples/i2c_registers/i2c_registers.ino new file mode 100644 index 0000000..41a3043 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/examples/i2c_registers/i2c_registers.ino @@ -0,0 +1,38 @@ +#include +#include + +#define I2C_ADDRESS 0x60 +Adafruit_I2CDevice i2c_dev = Adafruit_I2CDevice(I2C_ADDRESS); + + +void setup() { + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("I2C device register test"); + + if (!i2c_dev.begin()) { + Serial.print("Did not find device at 0x"); + Serial.println(i2c_dev.address(), HEX); + while (1); + } + Serial.print("Device found on address 0x"); + Serial.println(i2c_dev.address(), HEX); + + Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(&i2c_dev, 0x0C, 2, LSBFIRST); + uint16_t id; + id_reg.read(&id); + Serial.print("ID register = 0x"); Serial.println(id, HEX); + + Adafruit_BusIO_Register thresh_reg = Adafruit_BusIO_Register(&i2c_dev, 0x01, 2, LSBFIRST); + uint16_t thresh; + thresh_reg.read(&thresh); + Serial.print("Initial threshold register = 0x"); Serial.println(thresh, HEX); + + thresh_reg.write(~thresh); + + Serial.print("Post threshold register = 0x"); Serial.println(thresh_reg.read(), HEX); +} + +void loop() { + +} \ No newline at end of file diff --git a/firmware/libraries/Adafruit_BusIO/examples/i2corspi_register/i2corspi_register.ino b/firmware/libraries/Adafruit_BusIO/examples/i2corspi_register/i2corspi_register.ino new file mode 100644 index 0000000..992a2e0 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/examples/i2corspi_register/i2corspi_register.ino @@ -0,0 +1,38 @@ +#include + +// Define which interface to use by setting the unused interface to NULL! + +#define SPIDEVICE_CS 10 +Adafruit_SPIDevice *spi_dev = NULL; // new Adafruit_SPIDevice(SPIDEVICE_CS); + +#define I2C_ADDRESS 0x5D +Adafruit_I2CDevice *i2c_dev = new Adafruit_I2CDevice(I2C_ADDRESS); + +void setup() { + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("I2C or SPI device register test"); + + if (spi_dev && !spi_dev->begin()) { + Serial.println("Could not initialize SPI device"); + } + + if (i2c_dev) { + if (i2c_dev->begin()) { + Serial.print("Device found on I2C address 0x"); + Serial.println(i2c_dev->address(), HEX); + } else { + Serial.print("Did not find I2C device at 0x"); + Serial.println(i2c_dev->address(), HEX); + } + } + + Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(i2c_dev, spi_dev, ADDRBIT8_HIGH_TOREAD, 0x0F); + uint8_t id=0; + id_reg.read(&id); + Serial.print("ID register = 0x"); Serial.println(id, HEX); +} + +void loop() { + +} diff --git a/firmware/libraries/Adafruit_BusIO/examples/spi_modetest/spi_modetest.ino b/firmware/libraries/Adafruit_BusIO/examples/spi_modetest/spi_modetest.ino new file mode 100644 index 0000000..10168c5 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/examples/spi_modetest/spi_modetest.ino @@ -0,0 +1,29 @@ +#include + +#define SPIDEVICE_CS 10 +Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS, 100000, SPI_BITORDER_MSBFIRST, SPI_MODE1); +//Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS, 13, 12, 11, 100000, SPI_BITORDER_MSBFIRST, SPI_MODE1); + + +void setup() { + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("SPI device mode test"); + + if (!spi_dev.begin()) { + Serial.println("Could not initialize SPI device"); + while (1); + } +} + +void loop() { + Serial.println("\n\nTransfer test"); + for (uint16_t x=0; x<=0xFF; x++) { + uint8_t i = x; + Serial.print("0x"); Serial.print(i, HEX); + spi_dev.read(&i, 1, i); + Serial.print("/"); Serial.print(i, HEX); + Serial.print(", "); + delay(25); + } +} \ No newline at end of file diff --git a/firmware/libraries/Adafruit_BusIO/examples/spi_readwrite/spi_readwrite.ino b/firmware/libraries/Adafruit_BusIO/examples/spi_readwrite/spi_readwrite.ino new file mode 100644 index 0000000..6f2c063 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/examples/spi_readwrite/spi_readwrite.ino @@ -0,0 +1,39 @@ +#include + +#define SPIDEVICE_CS 10 +Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS); + + +void setup() { + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("SPI device read and write test"); + + if (!spi_dev.begin()) { + Serial.println("Could not initialize SPI device"); + while (1); + } + + uint8_t buffer[32]; + + // Try to read 32 bytes + spi_dev.read(buffer, 32); + Serial.print("Read: "); + for (uint8_t i=0; i<32; i++) { + Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", "); + } + Serial.println(); + + // read a register by writing first, then reading + buffer[0] = 0x8F; // we'll reuse the same buffer + spi_dev.write_then_read(buffer, 1, buffer, 2, false); + Serial.print("Write then Read: "); + for (uint8_t i=0; i<2; i++) { + Serial.print("0x"); Serial.print(buffer[i], HEX); Serial.print(", "); + } + Serial.println(); +} + +void loop() { + +} diff --git a/firmware/libraries/Adafruit_BusIO/examples/spi_register_bits/spi_register_bits.ino b/firmware/libraries/Adafruit_BusIO/examples/spi_register_bits/spi_register_bits.ino new file mode 100644 index 0000000..e70a17b --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/examples/spi_register_bits/spi_register_bits.ino @@ -0,0 +1,192 @@ +/*************************************************** + + This is an example for how to use Adafruit_BusIO_RegisterBits from Adafruit_BusIO library. + + Designed specifically to work with the Adafruit RTD Sensor + ----> https://www.adafruit.com/products/3328 + uisng a MAX31865 RTD-to-Digital Converter + ----> https://datasheets.maximintegrated.com/en/ds/MAX31865.pdf + + This sensor uses SPI to communicate, 4 pins are required to + interface. + A fifth pin helps to detect when a new conversion is ready. + + Adafruit invests time and resources providing this open source code, + please support Adafruit and open-source hardware by purchasing + products from Adafruit! + + Example written (2020/3) by Andreas Hardtung/AnHard. + BSD license, all text above must be included in any redistribution + ****************************************************/ + +#include +#include + +#define MAX31865_SPI_SPEED (5000000) +#define MAX31865_SPI_BITORDER (SPI_BITORDER_MSBFIRST) +#define MAX31865_SPI_MODE (SPI_MODE1) + +#define MAX31865_SPI_CS (10) +#define MAX31865_READY_PIN (2) + + +Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice( MAX31865_SPI_CS, MAX31865_SPI_SPEED, MAX31865_SPI_BITORDER, MAX31865_SPI_MODE, &SPI); // Hardware SPI +// Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice( MAX31865_SPI_CS, 13, 12, 11, MAX31865_SPI_SPEED, MAX31865_SPI_BITORDER, MAX31865_SPI_MODE); // Software SPI + +// MAX31865 chip related ********************************************************************************************* +Adafruit_BusIO_Register config_reg = Adafruit_BusIO_Register(&spi_dev, 0x00, ADDRBIT8_HIGH_TOWRITE, 1, MSBFIRST); +Adafruit_BusIO_RegisterBits bias_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 7); +Adafruit_BusIO_RegisterBits auto_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 6); +Adafruit_BusIO_RegisterBits oneS_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 5); +Adafruit_BusIO_RegisterBits wire_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 4); +Adafruit_BusIO_RegisterBits faultT_bits = Adafruit_BusIO_RegisterBits(&config_reg, 2, 2); +Adafruit_BusIO_RegisterBits faultR_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 1); +Adafruit_BusIO_RegisterBits fi50hz_bit = Adafruit_BusIO_RegisterBits(&config_reg, 1, 0); + +Adafruit_BusIO_Register rRatio_reg = Adafruit_BusIO_Register(&spi_dev, 0x01, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST); +Adafruit_BusIO_RegisterBits rRatio_bits = Adafruit_BusIO_RegisterBits(&rRatio_reg, 15, 1); +Adafruit_BusIO_RegisterBits fault_bit = Adafruit_BusIO_RegisterBits(&rRatio_reg, 1, 0); + +Adafruit_BusIO_Register maxRratio_reg = Adafruit_BusIO_Register(&spi_dev, 0x03, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST); +Adafruit_BusIO_RegisterBits maxRratio_bits = Adafruit_BusIO_RegisterBits(&maxRratio_reg, 15, 1); + +Adafruit_BusIO_Register minRratio_reg = Adafruit_BusIO_Register(&spi_dev, 0x05, ADDRBIT8_HIGH_TOWRITE, 2, MSBFIRST); +Adafruit_BusIO_RegisterBits minRratio_bits = Adafruit_BusIO_RegisterBits(&minRratio_reg, 15, 1); + +Adafruit_BusIO_Register fault_reg = Adafruit_BusIO_Register(&spi_dev, 0x07, ADDRBIT8_HIGH_TOWRITE, 1, MSBFIRST); +Adafruit_BusIO_RegisterBits range_high_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 7); +Adafruit_BusIO_RegisterBits range_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 6); +Adafruit_BusIO_RegisterBits refin_high_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 5); +Adafruit_BusIO_RegisterBits refin_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 4); +Adafruit_BusIO_RegisterBits rtdin_low_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 3); +Adafruit_BusIO_RegisterBits voltage_fault_bit = Adafruit_BusIO_RegisterBits(&fault_reg, 1, 2); + +// Print the details of the configuration register. +void printConfig( void ) { + Serial.print("BIAS: "); if (bias_bit.read() ) Serial.print("ON"); else Serial.print("OFF"); + Serial.print(", AUTO: "); if (auto_bit.read() ) Serial.print("ON"); else Serial.print("OFF"); + Serial.print(", ONES: "); if (oneS_bit.read() ) Serial.print("ON"); else Serial.print("OFF"); + Serial.print(", WIRE: "); if (wire_bit.read() ) Serial.print("3"); else Serial.print("2/4"); + Serial.print(", FAULTCLEAR: "); if (faultR_bit.read() ) Serial.print("ON"); else Serial.print("OFF"); + Serial.print(", "); if (fi50hz_bit.read() ) Serial.print("50HZ"); else Serial.print("60HZ"); + Serial.println(); +} + +// Check and print faults. Then clear them. +void checkFaults( void ) { + if (fault_bit.read()) { + Serial.print("MAX: "); Serial.println(maxRratio_bits.read()); + Serial.print("VAL: "); Serial.println( rRatio_bits.read()); + Serial.print("MIN: "); Serial.println(minRratio_bits.read()); + + if (range_high_fault_bit.read() ) Serial.println("Range high fault"); + if ( range_low_fault_bit.read() ) Serial.println("Range low fault"); + if (refin_high_fault_bit.read() ) Serial.println("REFIN high fault"); + if ( refin_low_fault_bit.read() ) Serial.println("REFIN low fault"); + if ( rtdin_low_fault_bit.read() ) Serial.println("RTDIN low fault"); + if ( voltage_fault_bit.read() ) Serial.println("Voltage fault"); + + faultR_bit.write(1); // clear fault + } +} + +void setup() { + #if (MAX31865_1_READY_PIN != -1) + pinMode(MAX31865_READY_PIN ,INPUT_PULLUP); + #endif + + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("SPI Adafruit_BusIO_RegisterBits test on MAX31865"); + + if (!spi_dev.begin()) { + Serial.println("Could not initialize SPI device"); + while (1); + } + + // Set up for automode 50Hz. We don't care about selfheating. We want the highest possible sampling rate. + auto_bit.write(0); // Don't switch filtermode while auto_mode is on. + fi50hz_bit.write(1); // Set filter to 50Hz mode. + faultR_bit.write(1); // Clear faults. + bias_bit.write(1); // In automode we want to have the bias current always on. + delay(5); // Wait until bias current settles down. + // 10.5 time constants of the input RC network is required. + // 10ms worst case for 10kω reference resistor and a 0.1µF capacitor across the RTD inputs. + // Adafruit Module has 0.1µF and only 430/4300ω So here 0.43/4.3ms + auto_bit.write(1); // Now we can set automode. Automatically starting first conversion. + + // Test the READY_PIN + #if (defined( MAX31865_READY_PIN ) && (MAX31865_READY_PIN != -1)) + int i = 0; + while (digitalRead(MAX31865_READY_PIN) && i++ <= 100) { delay(1); } + if (i >= 100) { + Serial.print("ERROR: Max31865 Pin detection does not work. PIN:"); + Serial.println(MAX31865_READY_PIN); + } + #else + delay(100); + #endif + + // Set ratio range. + // Setting the temperatures would need some more calculation - not related to Adafruit_BusIO_RegisterBits. + uint16_t ratio = rRatio_bits.read(); + maxRratio_bits.write( (ratio < 0x8fffu-1000u) ? ratio + 1000u : 0x8fffu ); + minRratio_bits.write( (ratio > 1000u) ? ratio - 1000u : 0u ); + + printConfig(); + checkFaults(); +} + +void loop() { + #if (defined( MAX31865_READY_PIN ) && (MAX31865_1_READY_PIN != -1)) + // Is conversion ready? + if (!digitalRead(MAX31865_READY_PIN)) + #else + // Warant conversion is ready. + delay(21); // 21ms for 50Hz-mode. 19ms in 60Hz-mode. + #endif + { + // Read ratio, calculate temperature, scale, filter and print. + Serial.println( rRatio2C( rRatio_bits.read() ) * 100.0f, 0); // Temperature scaled by 100 + // Check, print, clear faults. + checkFaults(); + } + + // Do something else. + //delay(15000); +} + + +// Module/Sensor related. Here Adafruit PT100 module with a 2_Wire PT100 Class C ***************************** +float rRatio2C(uint16_t ratio) { + // A simple linear conversion. + const float R0 = 100.0f; + const float Rref = 430.0f; + const float alphaPT = 0.003850f; + const float ADCmax = (1u << 15) - 1.0f; + const float rscale = Rref / ADCmax; + // Measured temperature in boiling water 101.08°C with factor a = 1 and b = 0. Rref and MAX at about 22±2°C. + // Measured temperature in ice/water bath 0.76°C with factor a = 1 and b = 0. Rref and MAX at about 22±2°C. + //const float a = 1.0f / (alphaPT * R0); + const float a = (100.0f/101.08f) / (alphaPT * R0); + //const float b = 0.0f; // 101.08 + const float b = -0.76f; // 100.32 > 101.08 + + return filterRing( ((ratio * rscale) - R0) * a + b ); +} + +// General purpose ********************************************************************************************* +#define RINGLENGTH 250 +float filterRing( float newVal ) { + static float ring[RINGLENGTH] = { 0.0 }; + static uint8_t ringIndex = 0; + static bool ringFull = false; + + if ( ringIndex == RINGLENGTH ) { ringFull = true; ringIndex = 0; } + ring[ringIndex] = newVal; + uint8_t loopEnd = (ringFull) ? RINGLENGTH : ringIndex + 1; + float ringSum = 0.0f; + for (uint8_t i = 0; i < loopEnd; i++) ringSum += ring[i]; + ringIndex++; + return ringSum / loopEnd; +} diff --git a/firmware/libraries/Adafruit_BusIO/examples/spi_registers/spi_registers.ino b/firmware/libraries/Adafruit_BusIO/examples/spi_registers/spi_registers.ino new file mode 100644 index 0000000..091a353 --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/examples/spi_registers/spi_registers.ino @@ -0,0 +1,34 @@ +#include +#include + +#define SPIDEVICE_CS 10 +Adafruit_SPIDevice spi_dev = Adafruit_SPIDevice(SPIDEVICE_CS); + +void setup() { + while (!Serial) { delay(10); } + Serial.begin(115200); + Serial.println("SPI device register test"); + + if (!spi_dev.begin()) { + Serial.println("Could not initialize SPI device"); + while (1); + } + + Adafruit_BusIO_Register id_reg = Adafruit_BusIO_Register(&spi_dev, 0x0F, ADDRBIT8_HIGH_TOREAD); + uint8_t id = 0; + id_reg.read(&id); + Serial.print("ID register = 0x"); Serial.println(id, HEX); + + Adafruit_BusIO_Register thresh_reg = Adafruit_BusIO_Register(&spi_dev, 0x0C, ADDRBIT8_HIGH_TOREAD, 2, LSBFIRST); + uint16_t thresh = 0; + thresh_reg.read(&thresh); + Serial.print("Initial threshold register = 0x"); Serial.println(thresh, HEX); + + thresh_reg.write(~thresh); + + Serial.print("Post threshold register = 0x"); Serial.println(thresh_reg.read(), HEX); +} + +void loop() { + +} diff --git a/firmware/libraries/Adafruit_BusIO/library.properties b/firmware/libraries/Adafruit_BusIO/library.properties new file mode 100644 index 0000000..f0ef63f --- /dev/null +++ b/firmware/libraries/Adafruit_BusIO/library.properties @@ -0,0 +1,9 @@ +name=Adafruit BusIO +version=1.14.1 +author=Adafruit +maintainer=Adafruit +sentence=This is a library for abstracting away UART, I2C and SPI interfacing +paragraph=This is a library for abstracting away UART, I2C and SPI interfacing +category=Signal Input/Output +url=https://github.com/adafruit/Adafruit_BusIO +architectures=* diff --git a/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.cpp b/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.cpp new file mode 100644 index 0000000..e97aa46 --- /dev/null +++ b/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.cpp @@ -0,0 +1,81 @@ +#include "Adafruit_Sensor.h" + +/**************************************************************************/ +/*! + @brief Prints sensor information to serial console +*/ +/**************************************************************************/ +void Adafruit_Sensor::printSensorDetails(void) { + sensor_t sensor; + getSensor(&sensor); + Serial.println(F("------------------------------------")); + Serial.print(F("Sensor: ")); + Serial.println(sensor.name); + Serial.print(F("Type: ")); + switch ((sensors_type_t)sensor.type) { + case SENSOR_TYPE_ACCELEROMETER: + Serial.print(F("Acceleration (m/s2)")); + break; + case SENSOR_TYPE_MAGNETIC_FIELD: + Serial.print(F("Magnetic (uT)")); + break; + case SENSOR_TYPE_ORIENTATION: + Serial.print(F("Orientation (degrees)")); + break; + case SENSOR_TYPE_GYROSCOPE: + Serial.print(F("Gyroscopic (rad/s)")); + break; + case SENSOR_TYPE_LIGHT: + Serial.print(F("Light (lux)")); + break; + case SENSOR_TYPE_PRESSURE: + Serial.print(F("Pressure (hPa)")); + break; + case SENSOR_TYPE_PROXIMITY: + Serial.print(F("Distance (cm)")); + break; + case SENSOR_TYPE_GRAVITY: + Serial.print(F("Gravity (m/s2)")); + break; + case SENSOR_TYPE_LINEAR_ACCELERATION: + Serial.print(F("Linear Acceleration (m/s2)")); + break; + case SENSOR_TYPE_ROTATION_VECTOR: + Serial.print(F("Rotation vector")); + break; + case SENSOR_TYPE_RELATIVE_HUMIDITY: + Serial.print(F("Relative Humidity (%)")); + break; + case SENSOR_TYPE_AMBIENT_TEMPERATURE: + Serial.print(F("Ambient Temp (C)")); + break; + case SENSOR_TYPE_OBJECT_TEMPERATURE: + Serial.print(F("Object Temp (C)")); + break; + case SENSOR_TYPE_VOLTAGE: + Serial.print(F("Voltage (V)")); + break; + case SENSOR_TYPE_CURRENT: + Serial.print(F("Current (mA)")); + break; + case SENSOR_TYPE_COLOR: + Serial.print(F("Color (RGBA)")); + break; + case SENSOR_TYPE_TVOC: + Serial.print(F("Total Volatile Organic Compounds (ppb)")); + break; + } + + Serial.println(); + Serial.print(F("Driver Ver: ")); + Serial.println(sensor.version); + Serial.print(F("Unique ID: ")); + Serial.println(sensor.sensor_id); + Serial.print(F("Min Value: ")); + Serial.println(sensor.min_value); + Serial.print(F("Max Value: ")); + Serial.println(sensor.max_value); + Serial.print(F("Resolution: ")); + Serial.println(sensor.resolution); + Serial.println(F("------------------------------------\n")); +} diff --git a/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.h b/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.h index 8ac638f..432cfa6 100755 --- a/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.h +++ b/firmware/libraries/Adafruit_Unified_Sensor/Adafruit_Sensor.h @@ -1,155 +1,189 @@ /* -* Copyright (C) 2008 The Android Open Source Project -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software< /span> -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ + * Copyright (C) 2008 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software< /span> + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ /* Update by K. Townsend (Adafruit Industries) for lighter typedefs, and * extended sensor support to include color, voltage and current */ - + #ifndef _ADAFRUIT_SENSOR_H #define _ADAFRUIT_SENSOR_H #ifndef ARDUINO - #include +#include #elif ARDUINO >= 100 - #include "Arduino.h" - #include "Print.h" +#include "Arduino.h" +#include "Print.h" #else - #include "WProgram.h" +#include "WProgram.h" #endif -/* Intentionally modeled after sensors.h in the Android API: - * https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h */ - /* Constants */ -#define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */ -#define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */ -#define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */ -#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH) -#define SENSORS_MAGFIELD_EARTH_MAX (60.0F) /**< Maximum magnetic field on Earth's surface */ -#define SENSORS_MAGFIELD_EARTH_MIN (30.0F) /**< Minimum magnetic field on Earth's surface */ -#define SENSORS_PRESSURE_SEALEVELHPA (1013.25F) /**< Average sea level pressure is 1013.25 hPa */ -#define SENSORS_DPS_TO_RADS (0.017453293F) /**< Degrees/s to rad/s multiplier */ -#define SENSORS_GAUSS_TO_MICROTESLA (100) /**< Gauss to micro-Tesla multiplier */ +#define SENSORS_GRAVITY_EARTH (9.80665F) /**< Earth's gravity in m/s^2 */ +#define SENSORS_GRAVITY_MOON (1.6F) /**< The moon's gravity in m/s^2 */ +#define SENSORS_GRAVITY_SUN (275.0F) /**< The sun's gravity in m/s^2 */ +#define SENSORS_GRAVITY_STANDARD (SENSORS_GRAVITY_EARTH) +#define SENSORS_MAGFIELD_EARTH_MAX \ + (60.0F) /**< Maximum magnetic field on Earth's surface */ +#define SENSORS_MAGFIELD_EARTH_MIN \ + (30.0F) /**< Minimum magnetic field on Earth's surface */ +#define SENSORS_PRESSURE_SEALEVELHPA \ + (1013.25F) /**< Average sea level pressure is 1013.25 hPa */ +#define SENSORS_DPS_TO_RADS \ + (0.017453293F) /**< Degrees/s to rad/s multiplier \ + */ +#define SENSORS_RADS_TO_DPS \ + (57.29577793F) /**< Rad/s to degrees/s multiplier */ +#define SENSORS_GAUSS_TO_MICROTESLA \ + (100) /**< Gauss to micro-Tesla multiplier */ /** Sensor types */ -typedef enum -{ - SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */ - SENSOR_TYPE_MAGNETIC_FIELD = (2), - SENSOR_TYPE_ORIENTATION = (3), - SENSOR_TYPE_GYROSCOPE = (4), - SENSOR_TYPE_LIGHT = (5), - SENSOR_TYPE_PRESSURE = (6), - SENSOR_TYPE_PROXIMITY = (8), - SENSOR_TYPE_GRAVITY = (9), - SENSOR_TYPE_LINEAR_ACCELERATION = (10), /**< Acceleration not including gravity */ - SENSOR_TYPE_ROTATION_VECTOR = (11), - SENSOR_TYPE_RELATIVE_HUMIDITY = (12), - SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), - SENSOR_TYPE_VOLTAGE = (15), - SENSOR_TYPE_CURRENT = (16), - SENSOR_TYPE_COLOR = (17) +typedef enum { + SENSOR_TYPE_ACCELEROMETER = (1), /**< Gravity + linear acceleration */ + SENSOR_TYPE_MAGNETIC_FIELD = (2), + SENSOR_TYPE_ORIENTATION = (3), + SENSOR_TYPE_GYROSCOPE = (4), + SENSOR_TYPE_LIGHT = (5), + SENSOR_TYPE_PRESSURE = (6), + SENSOR_TYPE_PROXIMITY = (8), + SENSOR_TYPE_GRAVITY = (9), + SENSOR_TYPE_LINEAR_ACCELERATION = + (10), /**< Acceleration not including gravity */ + SENSOR_TYPE_ROTATION_VECTOR = (11), + SENSOR_TYPE_RELATIVE_HUMIDITY = (12), + SENSOR_TYPE_AMBIENT_TEMPERATURE = (13), + SENSOR_TYPE_OBJECT_TEMPERATURE = (14), + SENSOR_TYPE_VOLTAGE = (15), + SENSOR_TYPE_CURRENT = (16), + SENSOR_TYPE_COLOR = (17), + SENSOR_TYPE_TVOC = (18) } sensors_type_t; /** struct sensors_vec_s is used to return a vector in a common format. */ typedef struct { - union { - float v[3]; - struct { - float x; - float y; - float z; - }; - /* Orientation sensors */ - struct { - float roll; /**< Rotation around the longitudinal axis (the plane body, 'X axis'). Roll is positive and increasing when moving downward. -90°<=roll<=90° */ - float pitch; /**< Rotation around the lateral axis (the wing span, 'Y axis'). Pitch is positive and increasing when moving upwards. -180°<=pitch<=180°) */ - float heading; /**< Angle between the longitudinal axis (the plane body) and magnetic north, measured clockwise when viewing from the top of the device. 0-359° */ - }; - }; - int8_t status; - uint8_t reserved[3]; + union { + float v[3]; ///< 3D vector elements + struct { + float x; ///< X component of vector + float y; ///< Y component of vector + float z; ///< Z component of vector + }; ///< Struct for holding XYZ component + /* Orientation sensors */ + struct { + float roll; /**< Rotation around the longitudinal axis (the plane body, 'X + axis'). Roll is positive and increasing when moving + downward. -90 degrees <= roll <= 90 degrees */ + float pitch; /**< Rotation around the lateral axis (the wing span, 'Y + axis'). Pitch is positive and increasing when moving + upwards. -180 degrees <= pitch <= 180 degrees) */ + float heading; /**< Angle between the longitudinal axis (the plane body) + and magnetic north, measured clockwise when viewing from + the top of the device. 0-359 degrees */ + }; ///< Struct for holding roll/pitch/heading + }; ///< Union that can hold 3D vector array, XYZ components or + ///< roll/pitch/heading + int8_t status; ///< Status byte + uint8_t reserved[3]; ///< Reserved } sensors_vec_t; /** struct sensors_color_s is used to return color data in a common format. */ typedef struct { - union { - float c[3]; - /* RGB color space */ - struct { - float r; /**< Red component */ - float g; /**< Green component */ - float b; /**< Blue component */ - }; - }; - uint32_t rgba; /**< 24-bit RGBA value */ + union { + float c[3]; ///< Raw 3-element data + /* RGB color space */ + struct { + float r; /**< Red component */ + float g; /**< Green component */ + float b; /**< Blue component */ + }; ///< RGB data in floating point notation + }; ///< Union of various ways to describe RGB colorspace + uint32_t rgba; /**< 24-bit RGBA value */ } sensors_color_t; /* Sensor event (36 bytes) */ -/** struct sensor_event_s is used to provide a single sensor event in a common format. */ -typedef struct -{ - int32_t version; /**< must be sizeof(struct sensors_event_t) */ - int32_t sensor_id; /**< unique sensor identifier */ - int32_t type; /**< sensor type */ - int32_t reserved0; /**< reserved */ - int32_t timestamp; /**< time is in milliseconds */ - union - { - float data[4]; - sensors_vec_t acceleration; /**< acceleration values are in meter per second per second (m/s^2) */ - sensors_vec_t magnetic; /**< magnetic vector values are in micro-Tesla (uT) */ - sensors_vec_t orientation; /**< orientation values are in degrees */ - sensors_vec_t gyro; /**< gyroscope values are in rad/s */ - float temperature; /**< temperature is in degrees centigrade (Celsius) */ - float distance; /**< distance in centimeters */ - float light; /**< light in SI lux units */ - float pressure; /**< pressure in hectopascal (hPa) */ - float relative_humidity; /**< relative humidity in percent */ - float current; /**< current in milliamps (mA) */ - float voltage; /**< voltage in volts (V) */ - sensors_color_t color; /**< color in RGB component values */ - }; +/** struct sensor_event_s is used to provide a single sensor event in a common + * format. */ +typedef struct { + int32_t version; /**< must be sizeof(struct sensors_event_t) */ + int32_t sensor_id; /**< unique sensor identifier */ + int32_t type; /**< sensor type */ + int32_t reserved0; /**< reserved */ + int32_t timestamp; /**< time is in milliseconds */ + union { + float data[4]; ///< Raw data + sensors_vec_t acceleration; /**< acceleration values are in meter per second + per second (m/s^2) */ + sensors_vec_t + magnetic; /**< magnetic vector values are in micro-Tesla (uT) */ + sensors_vec_t orientation; /**< orientation values are in degrees */ + sensors_vec_t gyro; /**< gyroscope values are in rad/s */ + float temperature; /**< temperature is in degrees centigrade (Celsius) */ + float distance; /**< distance in centimeters */ + float light; /**< light in SI lux units */ + float pressure; /**< pressure in hectopascal (hPa) */ + float relative_humidity; /**< relative humidity in percent */ + float current; /**< current in milliamps (mA) */ + float voltage; /**< voltage in volts (V) */ + float tvoc; /**< Total Volatile Organic Compounds, in ppb */ + sensors_color_t color; /**< color in RGB component values */ + }; ///< Union for the wide ranges of data we can carry } sensors_event_t; /* Sensor details (40 bytes) */ -/** struct sensor_s is used to describe basic information about a specific sensor. */ -typedef struct -{ - char name[12]; /**< sensor name */ - int32_t version; /**< version of the hardware + driver */ - int32_t sensor_id; /**< unique sensor identifier */ - int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */ - float max_value; /**< maximum value of this sensor's value in SI units */ - float min_value; /**< minimum value of this sensor's value in SI units */ - float resolution; /**< smallest difference between two values reported by this sensor */ - int32_t min_delay; /**< min delay in microseconds between events. zero = not a constant rate */ +/** struct sensor_s is used to describe basic information about a specific + * sensor. */ +typedef struct { + char name[12]; /**< sensor name */ + int32_t version; /**< version of the hardware + driver */ + int32_t sensor_id; /**< unique sensor identifier */ + int32_t type; /**< this sensor's type (ex. SENSOR_TYPE_LIGHT) */ + float max_value; /**< maximum value of this sensor's value in SI units */ + float min_value; /**< minimum value of this sensor's value in SI units */ + float resolution; /**< smallest difference between two values reported by this + sensor */ + int32_t min_delay; /**< min delay in microseconds between events. zero = not a + constant rate */ } sensor_t; +/** @brief Common sensor interface to unify various sensors. + * Intentionally modeled after sensors.h in the Android API: + * https://github.com/android/platform_hardware_libhardware/blob/master/include/hardware/sensors.h + */ class Adafruit_Sensor { - public: +public: // Constructor(s) Adafruit_Sensor() {} virtual ~Adafruit_Sensor() {} // These must be defined by the subclass - virtual void enableAutoRange(bool enabled) { (void)enabled; /* suppress unused warning */ }; - virtual bool getEvent(sensors_event_t*) = 0; - virtual void getSensor(sensor_t*) = 0; - - private: + + /*! @brief Whether we should automatically change the range (if possible) for + higher precision + @param enabled True if we will try to autorange */ + virtual void enableAutoRange(bool enabled) { + (void)enabled; /* suppress unused warning */ + }; + + /*! @brief Get the latest sensor event + @returns True if able to fetch an event */ + virtual bool getEvent(sensors_event_t *) = 0; + /*! @brief Get info about the sensor itself */ + virtual void getSensor(sensor_t *) = 0; + + void printSensorDetails(void); + +private: bool _autoRange; }; diff --git a/firmware/libraries/Adafruit_Unified_Sensor/LICENSE.txt b/firmware/libraries/Adafruit_Unified_Sensor/LICENSE.txt new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/firmware/libraries/Adafruit_Unified_Sensor/LICENSE.txt @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/firmware/libraries/Adafruit_Unified_Sensor/README.md b/firmware/libraries/Adafruit_Unified_Sensor/README.md old mode 100755 new mode 100644 index fd99597..18839d6 --- a/firmware/libraries/Adafruit_Unified_Sensor/README.md +++ b/firmware/libraries/Adafruit_Unified_Sensor/README.md @@ -52,11 +52,11 @@ The following drivers are based on the Adafruit Unified Sensor Driver: Any driver that supports the Adafruit unified sensor abstraction layer will implement the Adafruit\_Sensor base class. There are two main typedefs and one enum defined in Adafruit_Sensor.h that are used to 'abstract' away the sensor details and values: -**Sensor Types (sensors\_type\_t)** +## Sensor Types (`sensors_type_t`) These pre-defined sensor types are used to properly handle the two related typedefs below, and allows us determine what types of units the sensor uses, etc. -``` +```c++ /** Sensor types */ typedef enum { @@ -78,11 +78,11 @@ typedef enum } sensors_type_t; ``` -**Sensor Details (sensor\_t)** +## Sensor Details (`sensor_t`) This typedef describes the specific capabilities of this sensor, and allows us to know what sensor we are using beneath the abstraction layer. -``` +```c++ /* Sensor details (40 bytes) */ /** struct sensor_s is used to describe basic information about a specific sensor. */ typedef struct @@ -109,11 +109,11 @@ The individual fields are intended to be used as follows: - **resolution**: The smallest difference between two values that this sensor can report (in the appropriate SI unit) - **min\_delay**: The minimum delay in microseconds between two sensor events, or '0' if there is no constant sensor rate -**Sensor Data/Events (sensors\_event\_t)** +## Sensor Data/Events (`sensors_event_t`) This typedef is used to return sensor data from any sensor supported by the abstraction layer, using standard SI units and scales. -``` +```c++ /* Sensor event (36 bytes) */ /** struct sensor_event_s is used to provide a single sensor event in a common format. */ typedef struct @@ -149,21 +149,21 @@ It includes the following fields: - **timestamp**: time in milliseconds when the sensor value was read - **data[4]**: An array of four 32-bit values that allows us to encapsulate any type of sensor data via a simple union (further described below) -**Required Functions** +## Required Functions In addition to the two standard types and the sensor type enum, all drivers based on Adafruit_Sensor must also implement the following two functions: -``` +```c++ bool getEvent(sensors_event_t*); ``` Calling this function will populate the supplied sensors\_event\_t reference with the latest available sensor data. You should call this function as often as you want to update your data. -``` +```c++ void getSensor(sensor_t*); ``` Calling this function will provide some basic information about the sensor (the sensor name, driver version, min and max values, etc. -**Standardised SI values for sensors\_event\_t** +## Standardised SI values for `sensors_event_t` A key part of the abstraction layer is the standardisation of values on SI units of a particular scale, which is accomplished via the data[4] union in sensors\_event\_t above. This 16 byte union includes fields for each main sensor type, and uses the following SI units and scales: @@ -188,7 +188,7 @@ Every compliant sensor can now be read using a single, well-known 'type' (sensor An example of reading the [TSL2561](https://github.com/adafruit/Adafruit_TSL2561) light sensor can be seen below: -``` +```c++ Adafruit_TSL2561 tsl = Adafruit_TSL2561(TSL2561_ADDR_FLOAT, 12345); ... /* Get a new sensor event */ @@ -210,7 +210,7 @@ An example of reading the [TSL2561](https://github.com/adafruit/Adafruit_TSL2561 Similarly, we can get the basic technical capabilities of this sensor with the following code: -``` +```c++ sensor_t sensor; sensor_t sensor; diff --git a/firmware/libraries/Adafruit_Unified_Sensor/examples/sensortest/sensortest.ino b/firmware/libraries/Adafruit_Unified_Sensor/examples/sensortest/sensortest.ino new file mode 100644 index 0000000..d87f60d --- /dev/null +++ b/firmware/libraries/Adafruit_Unified_Sensor/examples/sensortest/sensortest.ino @@ -0,0 +1,153 @@ +#include +#include +#include + +/* Assign a unique ID to this sensor at the same time */ +/* Uncomment following line for default Wire bus */ +Adafruit_ADXL343 accel = Adafruit_ADXL343(12345); + +/* NeoTrellis M4, etc. */ +/* Uncomment following line for Wire1 bus */ +//Adafruit_ADXL343 accel = Adafruit_ADXL343(12345, &Wire1); + +void displaySensorDetails(void) +{ + sensor_t sensor; + accel.getSensor(&sensor); + Serial.println("------------------------------------"); + Serial.print ("Sensor: "); Serial.println(sensor.name); + Serial.print ("Driver Ver: "); Serial.println(sensor.version); + Serial.print ("Unique ID: "); Serial.println(sensor.sensor_id); + Serial.print ("Max Value: "); Serial.print(sensor.max_value); Serial.println(" m/s^2"); + Serial.print ("Min Value: "); Serial.print(sensor.min_value); Serial.println(" m/s^2"); + Serial.print ("Resolution: "); Serial.print(sensor.resolution); Serial.println(" m/s^2"); + Serial.println("------------------------------------"); + Serial.println(""); + delay(500); +} + +void displayDataRate(void) +{ + Serial.print ("Data Rate: "); + + switch(accel.getDataRate()) + { + case ADXL343_DATARATE_3200_HZ: + Serial.print ("3200 "); + break; + case ADXL343_DATARATE_1600_HZ: + Serial.print ("1600 "); + break; + case ADXL343_DATARATE_800_HZ: + Serial.print ("800 "); + break; + case ADXL343_DATARATE_400_HZ: + Serial.print ("400 "); + break; + case ADXL343_DATARATE_200_HZ: + Serial.print ("200 "); + break; + case ADXL343_DATARATE_100_HZ: + Serial.print ("100 "); + break; + case ADXL343_DATARATE_50_HZ: + Serial.print ("50 "); + break; + case ADXL343_DATARATE_25_HZ: + Serial.print ("25 "); + break; + case ADXL343_DATARATE_12_5_HZ: + Serial.print ("12.5 "); + break; + case ADXL343_DATARATE_6_25HZ: + Serial.print ("6.25 "); + break; + case ADXL343_DATARATE_3_13_HZ: + Serial.print ("3.13 "); + break; + case ADXL343_DATARATE_1_56_HZ: + Serial.print ("1.56 "); + break; + case ADXL343_DATARATE_0_78_HZ: + Serial.print ("0.78 "); + break; + case ADXL343_DATARATE_0_39_HZ: + Serial.print ("0.39 "); + break; + case ADXL343_DATARATE_0_20_HZ: + Serial.print ("0.20 "); + break; + case ADXL343_DATARATE_0_10_HZ: + Serial.print ("0.10 "); + break; + default: + Serial.print ("???? "); + break; + } + Serial.println(" Hz"); +} + +void displayRange(void) +{ + Serial.print ("Range: +/- "); + + switch(accel.getRange()) + { + case ADXL343_RANGE_16_G: + Serial.print ("16 "); + break; + case ADXL343_RANGE_8_G: + Serial.print ("8 "); + break; + case ADXL343_RANGE_4_G: + Serial.print ("4 "); + break; + case ADXL343_RANGE_2_G: + Serial.print ("2 "); + break; + default: + Serial.print ("?? "); + break; + } + Serial.println(" g"); +} + +void setup(void) +{ + Serial.begin(9600); + while (!Serial); + Serial.println("Accelerometer Test"); Serial.println(""); + + /* Initialise the sensor */ + if(!accel.begin()) + { + /* There was a problem detecting the ADXL343 ... check your connections */ + Serial.println("Ooops, no ADXL343 detected ... Check your wiring!"); + while(1); + } + + /* Set the range to whatever is appropriate for your project */ + accel.setRange(ADXL343_RANGE_16_G); + // accel.setRange(ADXL343_RANGE_8_G); + // accel.setRange(ADXL343_RANGE_4_G); + // accel.setRange(ADXL343_RANGE_2_G); + + /* Display some basic information on this sensor */ + displaySensorDetails(); + displayDataRate(); + displayRange(); + Serial.println(""); +} + +void loop(void) +{ + /* Get a new sensor event */ + sensors_event_t event; + accel.getEvent(&event); + + /* Display the results (acceleration is measured in m/s^2) */ + Serial.print("X: "); Serial.print(event.acceleration.x); Serial.print(" "); + Serial.print("Y: "); Serial.print(event.acceleration.y); Serial.print(" "); + Serial.print("Z: "); Serial.print(event.acceleration.z); Serial.print(" ");Serial.println("m/s^2 "); + delay(500); +} diff --git a/firmware/libraries/Adafruit_Unified_Sensor/library.properties b/firmware/libraries/Adafruit_Unified_Sensor/library.properties old mode 100755 new mode 100644 index e0bcd3e..d2d3af1 --- a/firmware/libraries/Adafruit_Unified_Sensor/library.properties +++ b/firmware/libraries/Adafruit_Unified_Sensor/library.properties @@ -1,5 +1,5 @@ name=Adafruit Unified Sensor -version=1.0.3 +version=1.1.6 author=Adafruit maintainer=Adafruit sentence=Required for all Adafruit Unified Sensor based libraries. @@ -8,3 +8,4 @@ category=Sensors url=https://github.com/adafruit/Adafruit_Sensor architectures=* includes=Adafruit_Sensor.h + diff --git a/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.cpp b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.cpp new file mode 100755 index 0000000..caf16bc --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.cpp @@ -0,0 +1,176 @@ +#include "Arduino.h" +#include "ESP8266Influxdb.h" +#include + +#define DEBUG_PRINT // comment this line to disable debug print + +#ifndef DEBUG_PRINT +#define DEBUG_PRINT(a) +#else +#define DEBUG_PRINT(a) (Serial.println(String(F("[Debug]: "))+(a))) +#define _DEBUG +#endif + +Influxdb::Influxdb(const char *host, uint16_t port) : WiFiClient() { + _port = port; + _host = host; +} + +DB_RESPONSE Influxdb::opendb(String db, String user, String password) { + _db = "db=" + db + "&u=" + user + "&p=" + password; +} + +DB_RESPONSE Influxdb::opendb(String db) { + _db = "db=" + db; + +} + +DB_RESPONSE Influxdb::write(FIELD data) { + return write(data.postString()); +} + +DB_RESPONSE Influxdb::write(String data) { + if (!connect(_host, _port)) { + DEBUG_PRINT("connection failed"); + _response = DB_CONNECT_FAILED; + return _response; + } + String postHead = "POST /write?" + _db + " HTTP/1.1\r\n"; + postHead += "Host: " + String(_host) + ":" + String(_port) + "\r\n"; + // postHead += "Content-Type: application/x-www-form-urlencoded\r\n"; + postHead += "Content-Length: " + String(data.length()) + "\r\n\r\n"; + + DEBUG_PRINT("Writing data to " + String(_host) + ":" + String(_port)); + print(postHead + data); + DEBUG_PRINT(postHead + data); + + uint8_t t = 0; + // Check the reply whether writing is success or not + while (!available() && t < 200) { + delay(10); + t++; + } + if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out. + +#if !defined _DEBUG + if (available()) { + _response = (findUntil("204", "\r")) ? DB_SUCCESS : DB_ERROR; + return _response; + } +#else + _response=DB_ERROR; + while (available()) { + String line = readStringUntil('\n'); + if (line.substring(9,12)=="204") + _response = DB_SUCCESS; + DEBUG_PRINT("(Responsed): " + line); + } + return _response; +#endif + return DB_ERROR; +} + +DB_RESPONSE Influxdb::query(String sql) { + + if (!connect(_host, _port)) { + DEBUG_PRINT("connection failed"); + _response = DB_CONNECT_FAILED; + return _response; + } + + String url = "/query?"; +#if defined _DEBUG + url += "pretty=true&"; +#endif + url += _db; + url += "&q=" + URLEncode(sql); + DEBUG_PRINT("Requesting URL: "); + DEBUG_PRINT(url); + + // This will send the request to the server + print(String("GET ") + url + " HTTP/1.1\r\n" + "Host: " + _host + + ":" + _port + "\r\n" + "Connection: close\r\n\r\n"); + + // Read all the lines of the reply from server and print them to Serial + uint8_t t = 0; + while (!available() && t < 200) { + delay(10); + t++; + } + if (t==200) {_response = DB_ERROR; return DB_ERROR; } // Return error if time out. + + DEBUG_PRINT("Receiving...."); + uint8_t i=0; + String line = readStringUntil('\n'); + DEBUG_PRINT("[HEAD] " + line); + + if (line.substring(9,12) == "200") { + while (available()) { + line = readStringUntil('\n'); + DEBUG_PRINT("(HEAD) " + line); + if (i < 6 ) i++; else return _response; + } + _response = DB_SUCCESS; + } + else{ + _response = DB_ERROR; +#if defined _DEBUG + while (available()) { + line = readStringUntil('\n'); + DEBUG_PRINT("[HEAD] " + line); + } +#endif + } + + return _response; +} + +DB_RESPONSE Influxdb::response() { + return _response; +} + +/* -----------------------------------------------*/ +// Field object +/* -----------------------------------------------*/ +FIELD::FIELD(String m) { + measurement = m; +} + +void FIELD::empty() { + _data = ""; + _tag = ""; +} + +void FIELD::addTag(String key, String value) { + _tag += "," + key + "=" + value; +} + +void FIELD::addField(String key, float value) { + _data = (_data == "") ? (" ") : (_data += ","); + _data += key + "=" + String(value); +} + +String FIELD::postString() { + // uint32_t utc = 1448114561 + millis() /1000; + return measurement + _tag + _data; +} + +// URL Encode with Arduino String object +String URLEncode(String msg) { + const char *hex = "0123456789abcdef"; + String encodedMsg = ""; + + uint16_t i; + for (i = 0; i < msg.length(); i++) { + if (('a' <= msg.charAt(i) && msg.charAt(i) <= 'z') || + ('A' <= msg.charAt(i) && msg.charAt(i) <= 'Z') || + ('0' <= msg.charAt(i) && msg.charAt(i) <= '9')) { + encodedMsg += msg.charAt(i); + } else { + encodedMsg += '%'; + encodedMsg += hex[msg.charAt(i) >> 4]; + encodedMsg += hex[msg.charAt(i) & 15]; + } + } + return encodedMsg; +} diff --git a/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.h b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.h new file mode 100755 index 0000000..4b0f78e --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/ESP8266Influxdb 2.h @@ -0,0 +1,72 @@ +/* Influxdb library + + MIT license + Written by HW Wong + */ + +#ifndef INFLUXDB_H +#define INFLUXDB_H +#include "Arduino.h" +#include + +enum DB_RESPONSE {DB_SUCCESS, DB_ERROR, DB_CONNECT_FAILED}; + +// Url encode function +String URLEncode(String msg); + +class FIELD +{ +public: + FIELD(String m); + + String measurement; + + void addField(String key, float value); + void addTag(String key, String value); + void empty(); + String postString(); + +private: + String _data; + String _tag; + +}; + +class Influxdb : private WiFiClient +{ +public: + Influxdb(const char* host, uint16_t port); + + DB_RESPONSE opendb(String db); + DB_RESPONSE opendb(String db, String user, String password); + DB_RESPONSE write(FIELD data); + DB_RESPONSE write(String data); + DB_RESPONSE query(String sql); + //uint8_t createDatabase(char *dbname); + DB_RESPONSE response(); + + using WiFiClient::available; + using WiFiClient::read; + using WiFiClient::flush; + using WiFiClient::find; + using WiFiClient::findUntil; + using WiFiClient::peek; + using WiFiClient::readBytes; + using WiFiClient::readBytesUntil; + using WiFiClient::readString; + using WiFiClient::readStringUntil; + using WiFiClient::parseInt; + using WiFiClient::setTimeout; + +private: + uint16_t _port; + const char* _host; + String _db; + DB_RESPONSE _response; + +}; + + + + +#endif diff --git a/firmware/libraries/ESP8266Influxdb/README 2.md b/firmware/libraries/ESP8266Influxdb/README 2.md new file mode 100755 index 0000000..99ad2ec --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/README 2.md @@ -0,0 +1 @@ +# ESP8266Influxdb diff --git a/firmware/libraries/ESP8266Influxdb/keywords 2.txt b/firmware/libraries/ESP8266Influxdb/keywords 2.txt new file mode 100755 index 0000000..6b493f8 --- /dev/null +++ b/firmware/libraries/ESP8266Influxdb/keywords 2.txt @@ -0,0 +1,24 @@ +################################################## +# Syntax Coloring Map For ESP8266 Influxdb library +################################################## + +################################################## +# Datatypes (KEYWORD1) +################################################## + +Influxdb KEYWORD1 +FIELD KEYWORD1 +DB_RESPOND KEYWORD1 + +################################################## +# Methods and Functions (KEYWORD2) +################################################## + +addField KEYWORD2 +addTag KEYWORD2 +empty KEYWORD2 +opendb KEYWORD2 +write KEYWORD2 +query KEYWORD2 +postString KEYWORD2 +response KEYWORD2 diff --git a/firmware/libraries/ESP8266_Influxdb/CHANGELOG.md b/firmware/libraries/ESP8266_Influxdb/CHANGELOG.md new file mode 100644 index 0000000..fb8da21 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/CHANGELOG.md @@ -0,0 +1,148 @@ +# Changelog +## 3.12.1 [2022-08-29] +### Fixes +- [193](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/193) - Automatically adjusting point timestamp according to the setting of write precision. + +## 3.12.0 [2022-03-21] +### Features +- [185](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/185) - Added diagnostic server connection state getter `bool InfluxDBClient::isConnected()` + +## 3.11.0 [2022-02-18] +### Features + - [174](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/174),[181](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/181) - All API methods with a string param allow specifying string by all basic types: + - Arduino `String` class + - C `char *` or `char[]` + - Flash string using `F`,`PSTR` or `FPSTR` macros +### Fixes + - [176](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/176) - Cleared all compiler warnings + +## 3.10.0 [2022-01-20] +### Features + - [167](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/167) - Added `InfluxDBClient::writeRecord(const char *record)`. + - [167](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/167) - Added possibility to disable retrying by setting `maxRetryAttempts` to zero: `client.setWriteOptions(WriteOptions().maxRetryAttempts(0));` + - [172](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/172) - Added directly streaming batch for write. It can be enabled by `InfluxDBClient::setStreamWrite(bool enable = true)`. Writing by streaming lines of batch saves RAM as it sends data without allocating a buffer. On the other hand, this way of writing is about half times slower than the classic way, when allocating the buffer for writing the whole batch. + - [172](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/172) - Allowing larger batch size, > 255. + - [173](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/173) - Added Flux query parameters. Now supported by InfluxDB Cloud only. + +## 3.9.0 [2021-09-17] +### Features + - [#147](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/147) - Updated InfluxDB 2 Cloud CA root certificate to _ISRG Root X1_. + Current InfluxDB 2 Cloud CA root certificate _DST Root CA X3_ expires on September 30th 2021! + - [#157](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/157) - Added Buckets sub-client for managing buckets in InfluxDB 2. + +### Fixes + - [#150](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/150) - `HTTPOptions::httpReadTimeout` is also set as the connect timeout for HTTP connection on ESP32. It also works for HTTPS connection since ESP32 Arduino Core 2.0.0. + - [#156](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/156) - Correctly rounding _writeBufferSize_, when _bufferSize/batchSize >= 256_. + - [#162](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/162) - Fixed flushing of not full buffer after the flush timeout. + + ### Documentation + - [#163](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/163) - More precise description of supported devices. + +## 3.8.0 [2021-04-01] +### Features + - [#143](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/143) - `InfluxDBClient::setInsecure` now works also for ESP32. Requires Arduino ESP32 SDK 1.0.5 or higher + +### Documentation + - [#134](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/134): + - Added untrusted connection (skipping certificate validation) info to Readme + - `SecureWrite` and `SecureBatchWrite` demos enhanced with example about using untrusted connection + - Various fixes of typos + +### Fixes + - [#137](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/137) - Fixed parsing Flux response with unexpected annotations + +## 3.7.0 [2020-12-24] +### Features + - [#125](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/124) - Added credentials to the InfluxDB 1.x validation endpoint (/ping). To leverage this, [enable ping authentication](https://docs.influxdata.com/influxdb/v1.8/administration/config/#ping-auth-enabled-false) + +### Fixes + - [#129](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/129) - Updated InfluxDB 2 Cloud CA certificate to trust servers from all cloud providers (AWS, Azure, GCP) + +## 3.6.1 [2020-11-30] +### Features +### Fixes +- [#121](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/121) - Fixed compile error in case of warning is treated as an error +- [#122](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/122) - Deleting WiFiClient instance to avoid memory leaking when the InfluxDBClient is reinitialized +- [#124](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/124) - Fixed compilation warnings + +### Doc +- [#120](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/120) - Improved language wording in the Readme + +## 3.6.0 [2020-11-10] +### Features +- [#117](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/117) - Added `InfluxDBClient::pointToLineProtocol(const Point& point)` for simple creation of InfluxDB line-protocol string with respect to default tags + +### Fixes +- [#114](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/114) - Renamed `getRemaingRetryTime()`->`getRemainingRetryTime()` +- [#115](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/115) - Restored writing capability after a connection failure +- [#118](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/118) - Added escaping of URL params (org, bucker, V1 username and pass) + +## 3.5.0 [2020-10-30] +### Features + - [#107](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/107) - Added possibility to set default tags. Use `WriteOptions::addDefaultTag()` to add a tag that will be added to each written point using the `writePoint()` function. + - [#109](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/109) - Retry strategy improvements: + - Added `canSendRequest()` function to check if retry strategy is applied + - Added `getRemaingRetryTime()` function to get wait time before another request (write/query) can be sent + - Removed applying retry wait time in case of network error + - Better explanatory error message when a request is about to be sent in the retry wait state + +### Fixes +- [#108](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/108) - Added optional param for specifying decimal places of double.: `void Point::addField(String name, double value, int decimalPlaces = 2)` +- [#111](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/111) - Fixed blocked writing after another point reached max retry count (#110) + +## 3.4.0 [2020-10-02] +### Features + - [#89](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/89) - ESP8266 only - Added Max Fragment Length Negotiation for TLS communication to reduce memory allocation. If server supports MFLN, it saves ~10kB. Standalone InfluxDB OSS server doesn't support MFLN, Cloud yes. To leverage MFLN for standalone OSS, a reverse proxy needs to be used. + - [#91](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/91) - Improved API for settings of write and HTTP options: + - Introduced `WriteOptions` to wrap the write related options (write precision, batch-size, etc). It offers fluent style API allowing to change only the required options. `InfluxDBClient` has overloaded `setWriteOptions(const WriteOptions& writeOptions)` method. + - Introduced `HTTPOptions` to wrap the HTTP related options (e.g. reusing connection). It offers fluent style API allowing to change only the required options. `InfluxDBClient` has `setHTTPOptions(const HTTPOptions& httpOptions)` method. + - Added possibility to set HTTP response read timeout (part of the `HTTPOptions`). + - Method `InfluxDBClient::void setWriteOptions(WritePrecision precision, uint16_t batchSize = 1, uint16_t bufferSize = 5, uint16_t flushInterval = 60, bool preserveConnection = true)` is deprecated and it will be removed in the next release. + - [#93](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/93) - Write logic improvements + - Retry on failure logic unification with other InfluxDB clients (exponential retry, max retry count 3, max retry interval) + - Better write buffer memory management + +### Documentation + - [#87](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/87) - Fixed include file name in the Readme + - [#99](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/99) - Changed default InfluxDB 2 port from 9999 to 8086 (default since InfluxDB 2 RC0) + +### Fixes + - [#90](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/90) - Fixed boolean type recognition of InfluxDB Flux + - [#101](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/pull/101) - Better memory efficient point line composition + +## Version 3.3.0 (2020-07-07) + - [NEW] Added possibility skip server certification validation (`setInsecure()` method) + - [NEW] Added possibility to query flux on secured InfluxDB 1.8 using V1 approach + - [NEW] `validateConnection()` can be used also for the [forward compatibility](https://docs.influxdata.com/influxdb/latest/tools/api/#influxdb-2-0-api-compatibility-endpoints) connection to InfluxDB 1.8 + - [FIX] More precise default timestamp generating, up to microseconds + - [FIX] Debug compilation error + - [FIX] SecureBatchWrite compile error + +## Version 3.2.0 (2020-06-09) +- [NEW] Added possibility to read data from InfluxDB using Flux queries +- [NEW] `timeSync` utility function for synchronous time synchronization using NTP +- [FIX] Properly initialize member variable (#59) +- [FIX] ASCII chars & compilation warning fix (#60) +- [Update] ESP8266 SDK 2.7+ required + +## Version 3.1.3 (2020-04-27) + - [FIX] SecureWrite crash (#54) + +## Version 3.1.2 (2020-04-18) + - [FIX] Compilation error on fields order (#43) + - [FIX] Invalid precision constant for microseconds (#49) + - [FIX] Write error in case point has no tags (#50) + +## Version 3.1.1 (2020-04-06) + - [Updated] CA Certificate for SSL (#38) + +## Version 3.1.0 (2020-03-12) + - [NEW] Added User-agent header + - [FIX] status code check when pinging an InfluxDB version 1.x instance + +## Version 3.0.0 (2020-02-11) + - New API with similar keywords as other official InfluxDB clients + - Richer set of data types for fields and timestamp methods + - Advanced features, such as implicit batching, automatic retrying on server back-pressure and connection failure, along with secured communication over TLS supported for both devices and authentication + - Special characters escaping + - Backward support for original API of V1/V2 diff --git a/firmware/libraries/ESP8266_Influxdb/LICENSE b/firmware/libraries/ESP8266_Influxdb/LICENSE new file mode 100644 index 0000000..35659e0 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018-2020 Tobias Schürg, InfluxData + +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. diff --git a/firmware/libraries/ESP8266_Influxdb/README.md b/firmware/libraries/ESP8266_Influxdb/README.md new file mode 100644 index 0000000..35e5058 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/README.md @@ -0,0 +1,696 @@ +[![PlatformIO](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/workflows/PlatformIO/badge.svg)](https://github.com/tobiasschuerg/InfluxDB-Client-for-Arduino/actions/) + +# InfluxDB Arduino Client + +Simple Arduino client for writing and reading data from [InfluxDB](https://www.influxdata.com/products/influxdb-overview/), no matter whether it is a local server or InfluxDB Cloud. The library supports authentication, secure communication over TLS, [batching](#writing-in-batches), [automatic retrying](#buffer-handling-and-retrying) on server back-pressure and connection failure. + +It also allows setting data in various formats, automatically escapes special characters and offers specifying timestamp in various precisions. + +Library supports both [InfluxDB 2](#basic-code-for-influxdb-2) and [InfluxDB 1](#basic-code-for-influxdb-2). + +This is a new implementation and the API, [original API](#original-api) is still supported. + +Supported devices: + - ESP8266 with [Arduino core for ESP8266](https://github.com/esp8266/Arduino) at least version [3.0.2](https://github.com/esp8266/Arduino/releases/tag/3.0.2). + - ESP32 with [Arduino core for the ESP32](https://github.com/espressif/arduino-esp32) at least version [2.0.2](https://github.com/espressif/arduino-esp32/releases/tag/2.0.2). + +This library doesn't support using those devices as a peripheral. + +:warning: Only connection over internal WiFi capability is supported for now. + +## Table of contents +- [InfluxDB Arduino Client](#influxdb-arduino-client) + - [Basic code for InfluxDB 2](#basic-code-for-influxdb-2) + - [Basic code for InfluxDB 1](#basic-code-for-influxdb-1) + - [Connecting to InfluxDB Cloud 2](#connecting-to-influxdb-cloud-2) + - [Writing in Batches](#writing-in-batches) + - [Timestamp](#timestamp) + - [Configure Time](#configure-time) + - [Batch Size](#batch-size) + - [Large Batch Size](#large-batch-size) + - [Write Modes](#write-modes) + - [Buffer Handling and Retrying](#buffer-handling-and-retrying) + - [Write Options](#write-options) + - [HTTP Options](#http-options) + - [Secure Connection](#secure-connection) + - [InfluxDb 2](#influxdb-2) + - [InfluxDb 1](#influxdb-1) + - [Skipping certificate validation](#skipping-certificate-validation) + - [Querying](#querying) + - [Parametrized Queries](#parametrized-queries) + - [Original API](#original-api) + - [Initialization](#initialization) + - [Sending a single measurement](#sending-a-single-measurement) + - [Write multiple data points at once](#write-multiple-data-points-at-once) + - [Troubleshooting](#troubleshooting) + - [Contributing](#contributing) + - [License](#license) + + +## Basic code for InfluxDB 2 +After [setting up an InfluxDB 2 server](https://docs.influxdata.com/influxdb/v2.0/get-started/), first define connection parameters and a client instance: +```cpp +// InfluxDB 2 server url, e.g. http://192.168.1.48:8086 (Use: InfluxDB UI -> Load Data -> Client Libraries) +#define INFLUXDB_URL "influxdb-url" +// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> ) +#define INFLUXDB_TOKEN "token" +// InfluxDB 2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> ) +#define INFLUXDB_ORG "org" +// InfluxDB 2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets) +#define INFLUXDB_BUCKET "bucket" +``` + +You need to pass an additional parameter to the client constructor, which is a certificate of the server to trust. The constant `InfluxDbCloud2CACert` contains the InfluxDB Cloud 2 CA certificate, which is predefined in this library: +```cpp +// Single InfluxDB instance +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); +``` +Read more about [secure connection](#secure-connection). + +Additionally, time needs to be synced: +```cpp +// Synchronize time with NTP servers and set timezone +// Accurate time is necessary for certificate validation and writing in batches +// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ +configTzTime(TZ_INFO "pool.ntp.org", "time.nis.gov"); +``` +Read more about time synchronization in [Configure Time](#configure-time). + +Defining data and writing it to the DB is the same as in the case of [BasicWrite](#basic-code): +```cpp +// Define data point with measurement name 'device_status` +Point pointDevice("device_status"); +// Set tags +pointDevice.addTag("device", "ESP8266"); +pointDevice.addTag("SSID", WiFi.SSID()); +// Add data +pointDevice.addField("rssi", WiFi.RSSI()); +pointDevice.addField("uptime", millis()); + +// Write data +client.writePoint(pointDevice); +``` +Complete source code is available in [SecureWrite example](examples/SecureWrite/SecureWrite.ino). + +## Writing in Batches +InfluxDB client for Arduino can also write data in batches. A batch is simply a set of points that will be sent at once. To create a batch, the client will keep all points until the number of points reaches the batch size and then it will write all points at once to the InfluxDB server. This is often more efficient than writing each point separately. + +### Timestamp +If using batch writes, the timestamp should be employed. Timestamp specifies the time when data was gathered and it is used in the form of a number of seconds (milliseconds, etc) from epoch (1.1.1970) UTC. +If points have no timestamp assigned, InfluxDB assigns a timestamp at the time of writing, which could happen much later than the data has been obtained, because the final batch write will happen when the batch is full (or when [flush buffer](#buffer-handling-and-retrying) is forced). + +InfluxDB allows sending timestamps in various precisions - nanoseconds, microseconds, milliseconds or seconds. The milliseconds precision is usually enough for using on Arduino. The maximum available precision is microseconds. Setting the timestamp to nanoseconds will just add zeroes for microseconds fraction and will not improve timestamp accuracy. + +The client has to be configured with a time precision. The default settings is to not use the timestamp, which means that the server will assign a timestamp when the data is written to the database. The `setWriteOptions` functions allows setting custom `WriteOptions` params and one of them is __write precision__: +``` cpp +// Set write precision to milliseconds. Leave other parameters default. +client.setWriteOptions(WriteOptions().writePrecision(WritePrecision::MS)); +``` +When a write precision is configured, the client will automatically assign the current time to the timestamp of each written point which doesn't have a timestamp assigned. + +If you want to manage timestamp on your own, there are several ways to set the timestamp explicitly. +- `setTime(WritePrecision writePrecision)` - Sets the timestamp to the actual time in the desired precision. The same precision must set in WriteOptions. +- `setTime(unsigned long long timestamp)` - Sets the timestamp to an offset since the epoch. Correct precision must be set InfluxDBClient::setWriteOptions. +- `setTime(String timestamp)` - Sets the timestamp to an offset since the epoch. Correct precision must be set InfluxDBClient::setWriteOptions. + +The `getTime()` method allows copying the timestamp between points. + + +### Configure Time +Dealing with timestamps, and also validating server or CA certificate, requires that the device has correctly set the time. This can be done with one line of code: +```cpp +// Synchronize time with NTP servers and set timezone +// Accurate time is necessary for certificate validation and writing in batches +// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ +configTzTime("PST8PDT", "pool.ntp.org", "time.nis.gov"); +``` +The `configTzTime` function starts the time synchronization with NTP servers. The first parameter specifies the timezone information, which is important for distinguishing between UTC and a local timezone and for daylight saving changes. +The last two string parameters are the internet addresses of NTP servers. Check [pool.ntp.org](https://www.pool.ntp.org/zone) for address of some local NTP servers. + +Timezone string details are described at [https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html](https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html). +Values for some timezones: +- Central Europe: `CET-1CEST,M3.5.0,M10.5.0/3` +- Eastern: `EST5EDT` +- Japanese: `JST-9` +- Pacific Time: `PST8PDT` + +There is also another function for syncing the time, which takes timezone and DST offset. As DST info is set via static offset it will create local time problem when DST change occurs. +It's declaration is following: +```cpp +configTime(long gmtOffset_sec, int daylightOffset_sec, const char* server1, const char* server2 = nullptr, const char* server3 = nullptr); +``` + +In the example code it would be: +```cpp +// Synchronize time with NTP servers +// Accurate time is necessary for certificate validation and writing in batches +configTime(3600, 3600, "pool.ntp.org", "time.nis.gov"); +``` + +Both `configTzTime` and `configTime` functions are asynchronous. This means that calling the functions just starts the time synchronization. Time is often not synchronized yet upon returning from call. + +There is a helper function `timeSync` provided with the this library. The function starts time synchronization by calling the `configTzTime` and waits maximum 20 seconds for time to be synchronized. It prints progress info and final local time to the `Serial` console. +`timeSync` has the same signature as `configTzTime` and it is included with the main header file `InfluxDbClient.h`: +```cpp +// Synchronize time with NTP servers and waits for competition. Prints waiting progress and final synchronized time to the Serial. +// Accurate time is necessary for certificate validation and writing points in batch +// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ +void timeSync(const char *tzInfo, const char* ntpServer1, const char* ntpServer2 = nullptr, const char* ntpServer3 = nullptr); +``` + +### Batch Size +Setting batch size depends on data gathering and DB updating strategy. + +If data is written in short periods (seconds), the batch size should be set according to your expected write periods and update frequency requirements. +For example, if you would like to see updates (on the dashboard or in processing) each minute and you are measuring a single value (1 point) every 10s (6 points per minute), the batch size should be 6. If it is sufficient to update each hour and you are creating 1 point each minute, your batch size should be 60. + +In cases where the data should be written in longer periods and gathered data consists of several points, the batch size should be set to the expected number of points to be gathered. + +To set the batch size we use `WriteOptions` object and [setWriteOptions](#write-options) function: +```cpp +// Enable lines batching +client.setWriteOptions(WriteOptions().batchSize(10)); +``` +Writing the point will add a point to the underlying buffer until the batch size is reached: +```cpp +// Write first point to the buffer +// Buffered write always returns `true` +client.writePoint(point1); +// Write second point to the buffer +client.writePoint(point2); +.. +// Write ninth point to the buffer +client.writePoint(point9); +// Writing tenth point will cause flushing buffer and returns actual write result. +if(!client.writePoint(point10)) { + Serial.print("InfluxDB write failed: "); + Serial.println(client.getLastErrorMessage()); +} +``` + +In case cases where the number of points is not always the same, set the batch size to the maximum number of points and use the `flushBuffer()` function to force writing to the database. See [Buffer Handling](#buffer-handling-and-retrying) for more details. + +### Large batch size +The maximum batch size depends on the available RAM of the device (~45KB for ESP8266 and ~260KB for ESP32). Larger batch size, >100 for ESP8255, >2000 for ESP32, must be chosen carefully to not crash the app with out of memory error. The Stream write mode must be used, see [Write Modes](#write-modes) + +Always determine your typical line length using `client.pointToLineProtocol(point).length()`. For example, ESP32 can handle 2048 lines with an average length of 69. When the length of line or batch size is increased, the device becomes unstable, even there is more than 76k, it cannot send data or even crashes. ESP8266 handles successfully 330 of such lines. + +:warning: Thoroughly test your app when using large batch files. + +### Write Modes +Client has two modes of writing: + - Buffer (default) + - Stream + +Writing is performed the way that client keeps written lines (points) separately and when a batch is completed, it allocates a data buffer for sending to a server via WiFi Client. +This is the fastest way to write data but requires some amount of free memory. Thus a big batch size cannot be used. + +Another way of writing is *stream write*. +```cpp + // Enables stream write + client.setStreamWrite(true); +``` +In this mode client continuously streams lines from batch to WiFi Client. No buffer allocation. As lines are allocated separately, it avoids problems with max allocable block size. The downside is, that writing is about 50% slower than in the Buffer mode. + +## Buffer Handling and Retrying +InfluxDB contains an underlying buffer for handling writing in batches and automatic retrying on server back-pressure and connection failure. + +Its size is controlled by the `bufferSize` param of [WriteOptions](#write-options) object: +```cpp +// Increase buffer to allow caching of failed writes +client.setWriteOptions(WriteOptions().bufferSize(50)); +``` +The recommended size is at least 2 x batch size. + +The state of the buffer can be determined via two functions: + - `isBufferEmpty()` - Returns true if buffer is empty + - `isBufferFull()` - Returns true if buffer is full + + A full buffer can occur when there is a problem with the internet connection or the InfluxDB server is overloaded. In such cases, points to write remain in the buffer. When more points are added and connection problem remains, the buffer will reach the top and new points will overwrite older points. + + Each attempt to write a point will try to send older points in the buffer. So, the `isBufferFull()` function can be used to skip low priority points. + +The `flushBuffer()` function can be used to force writing, even if the number of points in the buffer is lower than the batch size. With the help of the `isBufferEmpty()` function a check can be made before a device goes to sleep: + + ```cpp + // Check whether buffer in not empty + if (!client.isBufferEmpty()) { + // Write all remaining points to db + client.flushBuffer(); + } +``` + +Other functions for dealing with buffer: + - `checkBuffer()` - Checks point buffer status and flushes if the number of points reaches batch size or flush interval runs out. This is the main function for controlling the buffer and it is used internally. + - `resetBuffer()` - Clears the buffer. + +Check [SecureBatchWrite example](examples/SecureBatchWrite/SecureBatchWrite.ino) for example code of buffer handling functions. + +## Write Options +Writing points can be controlled via `WriteOptions`, which is set in the `setWriteOptions` function: + +| Parameter | Default Value | Meaning | +|-----------|---------------|---------| +| writePrecision | `WritePrecision::NoTime` | Timestamp precision of written data | +| batchSize | `1` | Number of points that will be written to the database at once | +| bufferSize | `5` | Maximum number of points in buffer. Buffer contains new data that will be written to the database and also data that failed to be written due to network failure or server overloading | +| flushInterval | `60` | Maximum time(in seconds) data will be held in buffer before points are written to the db | +| retryInterval | `5` | Default retry interval in sec, if not sent by server. Value `0` disables retrying | +| maxRetryInterval | `300` | Maximum retry interval in sec | +| maxRetryAttempts | `3` | Maximum count of retry attempts of failed writes | + +## HTTP Options +`HTTPOptions` controls some aspects of HTTP communication and they are set via `setHTTPOptions` function: +| Parameter | Default Value | Meaning | +|-----------|---------------|---------| +| connectionReuse | `false` | Whether HTTP connection should be kept open after initial communication. Usable for frequent writes/queries. | +| httpReadTimeout | `5000` | Timeout (ms) for reading server response | + +## Secure Connection +Connecting to a secured server requires configuring the client to trust the server. This is achieved by providing the client with a server certificate, certificate authority certificate or certificate SHA1 fingerprint. + +:memo: In ESP32 arduino SDK (1.0.4), `WiFiClientSecure` doesn't support fingerprint to validate the server certificate. + +The certificate (in PEM format) or SHA1 fingerprint should be placed in flash memory to save RAM. +Code bellow is an example certificate in PEM format. Valid InfluxDB 2 Cloud CA certificate is included in the library in the constant `InfluxDbCloud2CACert`, located in the `InfluxDBCloud.h`. + +You can use a custom server certificate by exporting it, e.g. using a web browser: +```cpp +// Server certificate in PEM format, placed in the program (flash) memory to save RAM +const char ServerCert[] PROGMEM = R"EOF( +-----BEGIN CERTIFICATE----- +MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw +TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh +cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4 +WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu +ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY +MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc +h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+ +0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U +A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW +T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH +B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC +B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv +KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn +OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn +jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw +qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI +rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV +HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq +hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL +ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ +3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK +NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5 +ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur +TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC +jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc +oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq +4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA +mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d +emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc= +-----END CERTIFICATE----- +)EOF"; + +// Alternatively, use a fingerprint of server certificate to set trust. Works only for ESP8266. +const char ServerCert[] PROGMEM = "cabd2a79a1076a31f21d253635cb039d4329a5e8"; +``` + +### InfluxDb 2 +There are two ways to set the certificate or fingerprint to trust a server: + - Use full param constructor +```cpp +// InfluxDB client instance with preconfigured InfluxCloud certificate +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert); +``` +- Use `setConnectionParams` function: +```cpp +// InfluxDB client instance +InfluxDBClient client; + +void setup() { + // configure client + client.setConnectionParams(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, ServerCert); +} +``` +### InfluxDb 1 + +Use `setConnectionParamsV1` function: +```cpp +// InfluxDB client instance +InfluxDBClient client; + +void setup() { + // configure client + client.setConnectionParamsV1(INFLUXDB_URL, INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASSWORD, ServerCert); +} +``` +Another important prerequisite to successfully validate a server or CA certificate is to have properly synchronized time. More on this in [Configure Time](#configure-time). + +:information_source: Time synchronization is not required for validating server certificate via SHA1 fingerprint. + +### Skipping certificate validation +The CA certificate provided with the library is ISRG Root X1. This certificate lasts a very long time, until 2035. It is not necessary to update your device until then when using ISRG Root X1. + +If you are using your own certificate, plase keep in mind server certificates have limited validity period, often only a few months. It will be necessary to frequently change trusted certificate in the source code and reflashing the device. A solution could be using OTA update, but you will still need to care about certificate validity and updating it ahead of time to avoid connection failures. + +The best way to prevent frequent updates is to use a root certificate like the one provided with the library. If you are unable to use a root certificate from a trusted authority, you may want to use insecure mode instead. This is done with the help of `InfluxDBClient::setInsecure()` method. +You will also save space in flash (and RAM) by leaving certificate param empty when calling constructor or `setConnectionParams` method. + +:memo: The `InfluxDBClient::setInsecure()` method must be called before calling any function that will establish connection. The best place to call it is in the `setup` method: + +```cpp +// InfluxDB client instance without a server certificate +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN); + +void setup() { + // Set insecure connection to skip server certificate validation + client.setInsecure(); +} +``` + +:warning: Using untrusted connection is a security risk. + +## Querying +InfluxDB 2 and InfluxDB 1.7+ (with [enabled flux](https://docs.influxdata.com/influxdb/latest/administration/config/#flux-enabled-false)) uses [Flux](https://www.influxdata.com/products/flux/) to process and query data. InfluxDB client for Arduino offers a simple, but powerful, way how to query data with `query` function. It parses response line by line, so it can read a huge responses (thousands data lines), without consuming a lot device memory. + +The `query` returns `FluxQueryResult` object, which parses response and provides useful getters for accessing values from result set. + +The InfluxDB flux query result set is returned in CSV format. In the example below, the first line contains type information and the second column names, and the rest is data: +```CSV +#datatype,string,long,dateTime:RFC3339,dateTime:RFC3339,dateTime:RFC3339,long,string,string,string,string +,result,table,_start,_stop,_time,_value,SSID,_field,_measurement,device +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:13Z,-55,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:27Z,-54,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:40Z,-54,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:07:54Z,-54,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:08:07Z,-55,667G,rssi,wifi_status,ESP32 +,_result,0,2020-05-18T15:06:00.475253281Z,2020-05-19T15:06:00.475253281Z,2020-05-19T13:08:20Z,-56,667G,rssi,wifi_status,ESP32 +``` + +Accessing data using `FluxQueryResult` requires knowing the query result structure, especially the name and the type of the column. The best practice is to tune the query +in the `InfluxDB Data Explorer` and use the final query with this library. + + Browsing thought the result set is done by repeatedly calling the `next()` method, until it returns false. Unsuccessful reading is distinguished by a non empty value from the `getError()` method. + As a flux query result can contain several tables, differing by grouping key, use the `hasTableChanged()` method to determine when there is a new table. + Single values are returned using the `getValueByIndex()` or `getValueByName()` methods. + All row values at once are retrieved by the `getValues()` method. + Always call the `close()` method at the of reading. + +A value in the flux query result column, retrieved by the `getValueByIndex()` or `getValueByName()` methods, is represented by the `FluxValue` object. +It provides getter methods for supported flux types: + +| Flux type | Getter | C type | +| ----- | ------ | --- | +| long | getLong() | long | +| unsignedLong | getUnsignedLong() | unsigned long | +| dateTime:RFC3339, dateTime:RFC3339Nano | getDateTime() | [FluxDateTime](src/query/FluxTypes.h#L100) | +| bool | getBool() | bool | +| double | bool | double | +| string, base64binary, duration | getString() | String | + +Calling improper type getter will result in a zero (empty) value. + +Check for null (missing) value using the `isNull()` method. + +Use the `getRawValue()` method for getting the original string form. + +```cpp +// Construct a Flux query +// Query will find RSSI for last 24 hours for each connected WiFi network with this device computed by given selector function +String query = "from(bucket: \"my-bucket\") |> range(start: -24h) |> filter(fn: (r) => r._measurement == \"wifi_status\" and r._field == \"rssi\""; +query += "and r.device == \"ESP32\")"; +query += "|> max()"; + +// Send query to the server and get result +FluxQueryResult result = client.query(query); + +// Iterate over rows. Even there is just one row, next() must be called at least once. +while (result.next()) { + // Get typed value for flux result column 'SSID' + String ssid = result.getValueByName("SSID").getString(); + Serial.print("SSID '"); + Serial.print(ssid); + + Serial.print("' with RSSI "); + + // Get converted value for flux result column '_value' where there is RSSI value + long value = result.getValueByName("_value").getLong(); + Serial.print(value); + + // Format date-time for printing + // Format string according to http://www.cplusplus.com/reference/ctime/strftime/ + String timeStr = time.format("%F %T"); + + Serial.print(" at "); + Serial.print(timeStr); + + Serial.println(); +} + +// Check if there was an error +if(result.getError() != "") { + Serial.print("Query result error: "); + Serial.println(result.getError()); +} +``` +Complete source code is available in [QueryAggregated example](examples/QueryAggregated/QueryAggregated.ino). + +### Parametrized Queries +InfluxDB Cloud supports [Parameterized Queries](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/) +that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more +reusable and can also be used to help prevent injection attacks. + +InfluxDB Cloud inserts the params object into the Flux query as a Flux record named `params`. Use dot or bracket +notation to access parameters in the `params` record in your Flux query. Parameterized Flux queries support only `int` +, `float`, and `string` data types. To convert the supported data types into +other [Flux basic data types, use Flux type conversion functions](https://docs.influxdata.com/influxdb/cloud/query-data/parameterized-queries/#supported-parameter-data-types). + +Parameterized query example: +> :warning: Parameterized Queries are supported only in InfluxDB Cloud. There is no support in InfluxDB OSS currently. + +```cpp +// Prepare query parameters +QueryParams params; +params.add("bucket", INFLUXDB_BUCKET); +params.add("since", "-5m"); +params.add("device", DEVICE); +params.add("rssiThreshold", -50); + +// Construct a Flux query using parameters +// Parameters are accessed via the 'params' Flux object +// Flux only supports only string, float and int as parameters. Duration can be converted from string. +// Query will find RSSI less than defined threshold +String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \ + |> filter(fn: (r) => r._measurement == \"wifi_status\") \ + |> filter(fn: (r) => r._field == \"rssi\") \ + |> filter(fn: (r) => r.device == params.device) \ + |> filter(fn: (r) => r._value < params.rssiThreshold)"; + +// Print ouput header +// Print composed query +Serial.print("Querying with: "); +Serial.println(query); + +// Send query to the server and get result +FluxQueryResult result = client.query(query, params); + +//Print header +Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI"); + +for(int i=0;i<37;i++) { + Serial.print('-'); +} +Serial.println(); + +// Iterate over rows. Even there is just one row, next() must be called at least once. +int c = 0; +while (result.next()) { + // Get converted value for flux result column 'SSID' + String ssid = result.getValueByName("SSID").getString(); + + // Get converted value for flux result column '_value' where there is RSSI value + long rssi = result.getValueByName("_value").getLong(); + + // Get converted value for the _time column + FluxDateTime time = result.getValueByName("_time").getDateTime(); + + // Format date-time for printing + // Format string according to http://www.cplusplus.com/reference/ctime/strftime/ + String timeStr = time.format("%F %T"); + // Print formatted row + Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi); + c++; +} +if(!c) { + Serial.println(" No data found"); +} + +// Check if there was an error +if(result.getError() != "") { + Serial.print("Query result error: "); + Serial.println(result.getError()); +} + +// Close the result +result.close(); +``` +Complete source code is available in [QueryParams example](examples/QueryParams/QueryParams.ino). + +## Original API + +### Initialization +```cpp + #define INFLUXDB_HOST "192.168.0.32" + #define INFLUXDB_PORT 1337 + #define INFLUXDB_DATABASE "test" + //if used with authentication + #define INFLUXDB_USER "user" + #define INFLUXDB_PASS "password" + + // connect to WiFi + + Influxdb influx(INFLUXDB_HOST); // port defaults to 8086 + // or to use a custom port + Influxdb influx(INFLUXDB_HOST, INFLUXDB_PORT); + + // set the target database + influx.setDb(INFLUXDB_DATABASE); + // or use a db with auth + influx.setDbAuth(INFLUXDB_DATABASE, INFLUXDB_USER, INFLUXDB_PASS) // with authentication + +// To use the v2.0 InfluxDB +influx.setVersion(2); +influx.setOrg("myOrganization"); +influx.setBucket("myBucket"); +influx.setToken("myToken"); +influx.setPort(8086); +``` + +### Sending a single measurement +**Using an InfluxData object:** +```cpp +// create a measurement object +InfluxData measurement ("temperature"); +measurement.addTag("device", d2); +measurement.addTag("sensor", "dht11"); +measurement.addValue("value", 24.0); + +// write it into db +influx.write(measurement); +``` + +**Using raw-data** +```cpp + influx.write("temperature,device=d2,sensor=dht11 value=24.0") +``` + +### Write multiple data points at once +Batching measurements and send them with a single request will result in a much higher performance. +```cpp + +InfluxData measurement1 = readTemperature() +influx.prepare(measurement1) + +InfluxData measurement2 = readLight() +influx.prepare(measurement2) + +InfluxData measurement3 = readVoltage() +influx.prepare(measurement3) + +// writes all prepared measurements with a single request into db. +boolean success = influx.write(); +``` + +## Troubleshooting +All db methods return status. Value `false` means something went wrong. Call `getLastErrorMessage()` to get the error message. + +When error message doesn't help to explain the bad behavior, go to the library sources and in the file `src/util/debug.h` uncomment line 33: +```cpp +// Uncomment bellow in case of a problem and rebuild sketch +#define INFLUXDB_CLIENT_DEBUG_ENABLE +``` +Then upload your sketch again and see the debug output in the Serial Monitor. + +If you couldn't solve a problem by yourself, please, post an issue including the debug output. + +## Contributing + +If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the `master` branch. + +## License + +The InfluxDB Arduino Client is released under the [MIT License](https://opensource.org/licenses/MIT). diff --git a/firmware/libraries/ESP8266_Influxdb/examples/BasicWrite/BasicWrite.ino b/firmware/libraries/ESP8266_Influxdb/examples/BasicWrite/BasicWrite.ino new file mode 100644 index 0000000..e9e1784 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/examples/BasicWrite/BasicWrite.ino @@ -0,0 +1,98 @@ +/** + * Basic Write Example code for InfluxDBClient library for Arduino + * Data can be immediately seen in a InfluxDB UI: wifi_status measurement + * Enter WiFi and InfluxDB parameters below + * + * Measures signal level of the actually connected WiFi network + * This example supports only InfluxDB running from unsecure (http://...) + * For secure (https://...) or Influx Cloud 2 use SecureWrite example + **/ + +#if defined(ESP32) +#include +WiFiMulti wifiMulti; +#define DEVICE "ESP32" +#elif defined(ESP8266) +#include +ESP8266WiFiMulti wifiMulti; +#define DEVICE "ESP8266" +#endif + +#include + +// WiFi AP SSID +#define WIFI_SSID "ssid" +// WiFi password +#define WIFI_PASSWORD "password" +// InfluxDB server url. Don't use localhost, always server name or ip address. +// E.g. http://192.168.1.48:8086 (In InfluxDB 2 UI -> Load Data -> Client Libraries), +#define INFLUXDB_URL "influxdb-url" +// InfluxDB 2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> ) +// This token must have all buckets permission +#define INFLUXDB_TOKEN "toked-id" +// InfluxDB 2 organization id (Use: InfluxDB UI -> Settings -> Profile -> ) +#define INFLUXDB_ORG "org" +// Bucket name that doesn't exist in the db yet +#define INFLUXDB_BUCKET "test-bucket" + +void setup() { + Serial.begin(74880); + + // Connect WiFi + Serial.println("Connecting to " WIFI_SSID); + WiFi.mode(WIFI_STA); + wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); + while (wifiMulti.run() != WL_CONNECTED) { + Serial.print("."); + delay(500); + } + Serial.println(); +} + +// Creates client, bucket, writes data, verifies data and deletes bucket +void testClient() { + // InfluxDB client instance + InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN); + + // Check server connection + if (client.validateConnection()) { + Serial.print("Connected to InfluxDB: "); + Serial.println(client.getServerUrl()); + } else { + Serial.print("InfluxDB connection failed: "); + Serial.println(client.getLastErrorMessage()); + return; + } + + // Get dedicated client for buckets management + BucketsClient buckets = client.getBucketsClient(); + + // Verify bucket does not exist, or delete it + if(buckets.checkBucketExists(INFLUXDB_BUCKET)) { + Serial.println("Bucket " INFLUXDB_BUCKET " already exists, deleting" ); + // get reference + Bucket b = buckets.findBucket(INFLUXDB_BUCKET); + // Delete bucket + buckets.deleteBucket(b.getID()); + } + + // create a bucket with retention policy one month. Leave out or set zero to infinity + uint32_t monthSec = 30*24*3600; + Bucket b = buckets.createBucket(INFLUXDB_BUCKET, monthSec); + if(!b) { + // some error occurred + Serial.print("Bucket creating error: "); + Serial.println(buckets.getLastErrorMessage()); + return; + } + Serial.print("Created bucket: "); + Serial.println(b.toString()); + + int numPoints = 10; + // Write some points + for(int i=0;i range(start: -1h) |> pivot(rowKey:[\"_time\"],columnKey: [\"_field\"],valueColumn: \"_value\") |> count(column: \"humidity\")"; + FluxQueryResult result = client.query(query); + // We expect one row + if(result.next()) { + // Get count value + FluxValue val = result.getValueByName("humidity"); + if(val.getLong() != numPoints) { + Serial.print("Test failure, expected "); + Serial.print(numPoints); + Serial.print(" got "); + Serial.println(val.getLong()); + } else { + Serial.println("Test successfull"); + } + // Advance to the end + result.next(); + } else { + Serial.print("Query error: "); + Serial.println(result.getError()); + }; + result.close(); + + buckets.deleteBucket(b.getID()); +} + +void loop() { + // Lets do an E2E test + // call a client test + testClient(); + + Serial.println("Stopping"); + // Stop here, don't loop + while(1) delay(1); +} diff --git a/firmware/libraries/ESP8266_Influxdb/examples/QueryAggregated/QueryAggregated.ino b/firmware/libraries/ESP8266_Influxdb/examples/QueryAggregated/QueryAggregated.ino new file mode 100644 index 0000000..d20913d --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/examples/QueryAggregated/QueryAggregated.ino @@ -0,0 +1,163 @@ +/** + * QueryAggregated Example code for InfluxDBClient library for Arduino. + * + * This example demonstrates querying basic aggregated statistic parameters of WiFi signal level measured and stored in BasicWrite and SecureWrite examples. + * + * Demonstrates connection to any InfluxDB instance accesible via: + * - unsecured http://... + * - secure https://... (appropriate certificate is required) + * - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured) + * + * Enter WiFi and InfluxDB parameters below + **/ + +#if defined(ESP32) +#include +WiFiMulti wifiMulti; +#define DEVICE "ESP32" +#elif defined(ESP8266) +#include +ESP8266WiFiMulti wifiMulti; +#define DEVICE "ESP8266" +#endif + +#include +#include + +// WiFi AP SSID +#define WIFI_SSID "SSID" +// WiFi password +#define WIFI_PASSWORD "PASSWORD" +// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries) +// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086 +#define INFLUXDB_URL "server-url" +// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> ) +// InfluxDB 1.8+ (v2 compatibility API) use form user:password, eg. admin:adminpass +#define INFLUXDB_TOKEN "server token" +// InfluxDB v2 organization name or id (Use: InfluxDB UI -> Settings -> Profile -> ) +// InfluxDB 1.8+ (v2 compatibility API) use any non empty string +#define INFLUXDB_ORG "org name/id" +// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets) +// InfluxDB 1.8+ (v2 compatibility API) use database name +#define INFLUXDB_BUCKET "bucket name" + +// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html +// Examples: +// Pacific Time: "PST8PDT" +// Eastern: "EST5EDT" +// Japanesse: "JST-9" +// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3" +#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3" + +// InfluxDB client instance with preconfigured InfluxCloud certificate +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); + +void setup() { + Serial.begin(115200); + + // Setup wifi + WiFi.mode(WIFI_STA); + wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); + + Serial.print("Connecting to wifi"); + while (wifiMulti.run() != WL_CONNECTED) { + Serial.print("."); + delay(500); + } + Serial.println(); + + + // Accurate time is necessary for certificate validation + // For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ + // Syncing progress and the time will be printed to Serial + timeSync(TZ_INFO, "pool.ntp.org", "time.nis.gov"); + + // Check server connection + if (client.validateConnection()) { + Serial.print("Connected to InfluxDB: "); + Serial.println(client.getServerUrl()); + } else { + Serial.print("InfluxDB connection failed: "); + Serial.println(client.getLastErrorMessage()); + } +} + + +// Queries WiFi signal level values bellow a certain threshold using parameters inserted into the Flux query +// Prints composed query and the result values. +void loop() { + // Prepare query parameters + QueryParams params; + params.add("bucket", INFLUXDB_BUCKET); + params.add("since", "-5m"); + params.add("device", DEVICE); + params.add("rssiTreshold", -50); + + // Construct a Flux query using parameters + // Parameters are accessed via the 'params' Flux object + // Flux only supports only string, float and int as parameters. Duration can be converted from string. + // Query will find RSSI less than defined treshold + String query = "from(bucket: params.bucket) |> range(start: duration(v: params.since)) \ + |> filter(fn: (r) => r._measurement == \"wifi_status\") \ + |> filter(fn: (r) => r._field == \"rssi\") \ + |> filter(fn: (r) => r.device == params.device) \ + |> filter(fn: (r) => r._value < params.rssiTreshold)"; + + // Print ouput header + // Print composed query + Serial.print("Querying with: "); + Serial.println(query); + + // Send query to the server and get result + FluxQueryResult result = client.query(query, params); + + //Print header + Serial.printf("%10s %20s %5s\n","Time","SSID","RSSI"); + + for(int i=0;i<37;i++) { + Serial.print('-'); + } + Serial.println(); + + // Iterate over rows. Even there is just one row, next() must be called at least once. + int c = 0; + while (result.next()) { + // Get converted value for flux result column 'SSID' + String ssid = result.getValueByName("SSID").getString(); + + // Get converted value for flux result column '_value' where there is RSSI value + long rssi = result.getValueByName("_value").getLong(); + + // Get converted value for the _time column + FluxDateTime time = result.getValueByName("_time").getDateTime(); + + // Format date-time for printing + // Format string according to http://www.cplusplus.com/reference/ctime/strftime/ + String timeStr = time.format("%F %T"); + // Print formatted row + Serial.printf("%20s %10s %5d\n", timeStr.c_str(), ssid.c_str() ,rssi); + c++; + } + if(!c) { + Serial.println(" No data found"); + } + + // Check if there was an error + if(result.getError() != "") { + Serial.print("Query result error: "); + Serial.println(result.getError()); + } + + // Close the result + result.close(); + // Wait 15s + delay(15000); +} diff --git a/firmware/libraries/ESP8266_Influxdb/examples/QueryTable/QueryTable.ino b/firmware/libraries/ESP8266_Influxdb/examples/QueryTable/QueryTable.ino new file mode 100644 index 0000000..adc7b38 --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/examples/QueryTable/QueryTable.ino @@ -0,0 +1,148 @@ +/** + * QueryTable Example code for InfluxDBClient library for Arduino. + * + * This example demonstrates querying recent history of values of WiFi signal level measured and stored in BasicWrite and SecureWrite examples. + * + * Demonstrates connection to any InfluxDB instance accesible via: + * - unsecured http://... + * - secure https://... (appropriate certificate is required) + * - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured) + * + * Enter WiFi and InfluxDB parameters below + **/ + +#if defined(ESP32) +#include +WiFiMulti wifiMulti; +#define DEVICE "ESP32" +#elif defined(ESP8266) +#include +ESP8266WiFiMulti wifiMulti; +#define DEVICE "ESP8266" +#endif + +#include +#include + +// WiFi AP SSID +#define WIFI_SSID "SSID" +// WiFi password +#define WIFI_PASSWORD "PASSWORD" +// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries) +// InfluxDB 1.8+ (v2 compatibility API) server url, e.g. http://192.168.1.48:8086 +#define INFLUXDB_URL "server-url" +// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> ) +#define INFLUXDB_TOKEN "server token" +// InfluxDB v2 organization id (Use: InfluxDB UI -> Settings -> Profile -> ) +#define INFLUXDB_ORG "org id" +// InfluxDB v2 bucket name (Use: InfluxDB UI -> Load Data -> Buckets) +#define INFLUXDB_BUCKET "bucket name" +// Set timezone string according to https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html +// Examples: +// Pacific Time: "PST8PDT" +// Eastern: "EST5EDT" +// Japanesse: "JST-9" +// Central Europe: "CET-1CEST,M3.5.0,M10.5.0/3" +#define TZ_INFO "CET-1CEST,M3.5.0,M10.5.0/3" +// NTP servers the for time synchronization. +// For the fastest time sync find NTP servers in your area: https://www.pool.ntp.org/zone/ +#define NTP_SERVER1 "pool.ntp.org" +#define NTP_SERVER2 "time.nis.gov" +#define WRITE_PRECISION WritePrecision::S +#define MAX_BATCH_SIZE 10 +#define WRITE_BUFFER_SIZE 30 + +// InfluxDB client instance with preconfigured InfluxCloud certificate +InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN, InfluxDbCloud2CACert); +// InfluxDB client instance without preconfigured InfluxCloud certificate for insecure connection +//InfluxDBClient client(INFLUXDB_URL, INFLUXDB_ORG, INFLUXDB_BUCKET, INFLUXDB_TOKEN); + +// Data point +Point sensorStatus("wifi_status"); + +// Number for loops to sync time using NTP +int iterations = 0; + +void setup() { + Serial.begin(115200); + + // Setup wifi + WiFi.mode(WIFI_STA); + wifiMulti.addAP(WIFI_SSID, WIFI_PASSWORD); + + Serial.print("Connecting to wifi"); + while (wifiMulti.run() != WL_CONNECTED) { + Serial.print("."); + delay(500); + } + Serial.println(); + + // Add tags + sensorStatus.addTag("device", DEVICE); + sensorStatus.addTag("SSID", WiFi.SSID()); + + // Alternatively, set insecure connection to skip server certificate validation + //client.setInsecure(); + + // Accurate time is necessary for certificate validation and writing in batches + // Syncing progress and the time will be printed to Serial. + timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2); + + // Check server connection + if (client.validateConnection()) { + Serial.print("Connected to InfluxDB: "); + Serial.println(client.getServerUrl()); + } else { + Serial.print("InfluxDB connection failed: "); + Serial.println(client.getLastErrorMessage()); + } + + // Enable messages batching and retry buffer + client.setWriteOptions(WriteOptions().writePrecision(WRITE_PRECISION).batchSize(MAX_BATCH_SIZE).bufferSize(WRITE_BUFFER_SIZE)); +} + +void loop() { + // Sync time for batching once per hour + if (iterations++ >= 360) { + timeSync(TZ_INFO, NTP_SERVER1, NTP_SERVER2); + iterations = 0; + } + + // Report networks (low priority data) just in case we successfully wrote the previous batch + if (client.isBufferEmpty()) { + // Report all the detected wifi networks + int networks = WiFi.scanNetworks(); + // Set identical time for the whole network scan + time_t tnow = time(nullptr); + for (int i = 0; i < networks; i++) { + Point sensorNetworks("wifi_networks"); + sensorNetworks.addTag("device", DEVICE); + sensorNetworks.addTag("SSID", WiFi.SSID(i)); + sensorNetworks.addTag("channel", String(WiFi.channel(i))); + sensorNetworks.addTag("open", String(WiFi.encryptionType(i) == WIFI_AUTH_OPEN)); + sensorNetworks.addField("rssi", WiFi.RSSI(i)); + sensorNetworks.setTime(tnow); //set the time + + // Print what are we exactly writing + Serial.print("Writing: "); + Serial.println(client.pointToLineProtocol(sensorNetworks)); + + // Write point into buffer - low priority measures + client.writePoint(sensorNetworks); + } + } else + Serial.println("Wifi networks reporting skipped due to communication issues"); + + // Report RSSI of currently connected network + sensorStatus.setTime(time(nullptr)); + sensorStatus.addField("rssi", WiFi.RSSI()); + + // Print what are we exactly writing + Serial.print("Writing: "); + Serial.println(client.pointToLineProtocol(sensorStatus)); + + // Write point into buffer - high priority measure + client.writePoint(sensorStatus); + + // Clear fields for next usage. Tags remain the same. + sensorStatus.clearFields(); + + // If no Wifi signal, try to reconnect it + if (wifiMulti.run() != WL_CONNECTED) { + Serial.println("Wifi connection lost"); + } + + // End of the iteration - force write of all the values into InfluxDB as single transaction + Serial.println("Flushing data into InfluxDB"); + if (!client.flushBuffer()) { + Serial.print("InfluxDB flush failed: "); + Serial.println(client.getLastErrorMessage()); + Serial.print("Full buffer: "); + Serial.println(client.isBufferFull() ? "Yes" : "No"); + } + + // Wait 10s + Serial.println("Wait 10s"); + delay(10000); +} \ No newline at end of file diff --git a/firmware/libraries/ESP8266_Influxdb/examples/SecureWrite/SecureWrite.ino b/firmware/libraries/ESP8266_Influxdb/examples/SecureWrite/SecureWrite.ino new file mode 100644 index 0000000..4b49fea --- /dev/null +++ b/firmware/libraries/ESP8266_Influxdb/examples/SecureWrite/SecureWrite.ino @@ -0,0 +1,113 @@ +/** + * Secure Write Example code for InfluxDBClient library for Arduino + * Enter WiFi and InfluxDB parameters below + * + * Demonstrates connection to any InfluxDB instance accesible via: + * - unsecured http://... + * - secure https://... (appropriate certificate is required) + * - InfluxDB 2 Cloud at https://cloud2.influxdata.com/ (certificate is preconfigured) + * Measures signal level of the actually connected WiFi network + * This example demonstrates time handling, secure connection and measurement writing into InfluxDB + * Data can be immediately seen in a InfluxDB 2 Cloud UI - measurement wifi_status + **/ + +#if defined(ESP32) +#include +WiFiMulti wifiMulti; +#define DEVICE "ESP32" +#elif defined(ESP8266) +#include +ESP8266WiFiMulti wifiMulti; +#define DEVICE "ESP8266" +#endif + +#include +#include + +// WiFi AP SSID +#define WIFI_SSID "SSID" +// WiFi password +#define WIFI_PASSWORD "PASSWORD" +// InfluxDB v2 server url, e.g. https://eu-central-1-1.aws.cloud2.influxdata.com (Use: InfluxDB UI -> Load Data -> Client Libraries) +#define INFLUXDB_URL "server-url" +// InfluxDB v2 server or cloud API authentication token (Use: InfluxDB UI -> Load Data -> Tokens -> "; + // if no ID use customhtml for item, else generate from param string + if (_params[i]->getID() != NULL) { + if(tok_I)pitem.replace(FPSTR(T_I), (String)FPSTR(S_parampre)+(String)i); // T_I id number + if(tok_i)pitem.replace(FPSTR(T_i), _params[i]->getID()); // T_i id name + if(tok_n)pitem.replace(FPSTR(T_n), _params[i]->getID()); // T_n id name alias + if(tok_p)pitem.replace(FPSTR(T_p), FPSTR(T_t)); // T_p replace legacy placeholder token + if(tok_t)pitem.replace(FPSTR(T_t), _params[i]->getLabel()); // T_t title/label + snprintf(valLength, 5, "%d", _params[i]->getValueLength()); + if(tok_l)pitem.replace(FPSTR(T_l), valLength); // T_l value length + if(tok_v)pitem.replace(FPSTR(T_v), _params[i]->getValue()); // T_v value + if(tok_c)pitem.replace(FPSTR(T_c), _params[i]->getCustomHTML()); // T_c meant for additional attributes, not html, but can stuff + } else { + pitem = _params[i]->getCustomHTML(); + } + + page += pitem; + } + } + + return page; +} + +void WiFiManager::handleWiFiStatus(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi status ")); + #endif + handleRequest(); + String page; + // String page = "{\"result\":true,\"count\":1}"; + #ifdef WM_JSTEST + page = FPSTR(HTTP_JS); + #endif + HTTPSend(page); +} + +/** + * HTTPD CALLBACK save form and redirect to WLAN config page again + */ void WiFiManager::handleWifiSave() { - DEBUG_WM(F("WiFi save")); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP WiFi save ")); + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + #endif + handleRequest(); //SAVE/connect here - _ssid = server->arg("s").c_str(); - _pass = server->arg("p").c_str(); + _ssid = server->arg(F("s")).c_str(); + _pass = server->arg(F("p")).c_str(); + + // set static ips from server args + if (server->arg(FPSTR(S_ip)) != "") { + //_sta_static_ip.fromString(server->arg(FPSTR(S_ip)); + String ip = server->arg(FPSTR(S_ip)); + optionalIPFromString(&_sta_static_ip, ip.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("static ip:"),ip); + #endif + } + if (server->arg(FPSTR(S_gw)) != "") { + String gw = server->arg(FPSTR(S_gw)); + optionalIPFromString(&_sta_static_gw, gw.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("static gateway:"),gw); + #endif + } + if (server->arg(FPSTR(S_sn)) != "") { + String sn = server->arg(FPSTR(S_sn)); + optionalIPFromString(&_sta_static_sn, sn.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("static netmask:"),sn); + #endif + } + if (server->arg(FPSTR(S_dns)) != "") { + String dns = server->arg(FPSTR(S_dns)); + optionalIPFromString(&_sta_static_dns, dns.c_str()); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("static DNS:"),dns); + #endif + } + + if (_presavewificallback != NULL) { + _presavewificallback(); // @CALLBACK + } + + if(_paramsInWifi) doParamSave(); + + String page; + + if(_ssid == ""){ + page = getHTTPHead(FPSTR(S_titlewifisettings)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + } + else { + page = getHTTPHead(FPSTR(S_titlewifisaved)); // @token titlewifisaved + page += FPSTR(HTTP_SAVED); + } + page += FPSTR(HTTP_END); + + server->sendHeader(FPSTR(HTTP_HEAD_CORS), FPSTR(HTTP_HEAD_CORS_ALLOW_ALL)); // @HTTPHEAD send cors + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Sent wifi save page")); + #endif + + connect = true; //signal ready to connect/reset process in processConfigPortal +} + +void WiFiManager::handleParamSave() { + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Param save ")); + #endif + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Method:"),server->method() == HTTP_GET ? (String)FPSTR(S_GET) : (String)FPSTR(S_POST)); + #endif + handleRequest(); + + doParamSave(); + + String page = getHTTPHead(FPSTR(S_titleparamsaved)); // @token titleparamsaved + page += FPSTR(HTTP_PARAMSAVED); + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Sent param save page")); + #endif +} + +void WiFiManager::doParamSave(){ + // @todo use new callback for before paramsaves, is this really needed? + if ( _presaveparamscallback != NULL) { + _presaveparamscallback(); // @CALLBACK + } //parameters - for (int i = 0; i < _paramsCount; i++) { - if (_params[i] == NULL) { - break; + if(_paramsCount > 0){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Parameters")); + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + #endif + + for (int i = 0; i < _paramsCount; i++) { + if (_params[i] == NULL || _params[i]->_length == 0) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFiManagerParameter is out of scope")); + #endif + break; // @todo might not be needed anymore + } + //read parameter from server + String name = (String)FPSTR(S_parampre)+(String)i; + String value; + if(server->hasArg(name)) { + value = server->arg(name); + } else { + value = server->arg(_params[i]->getID()); + } + + //store it in params array + value.toCharArray(_params[i]->_value, _params[i]->_length+1); // length+1 null terminated + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,(String)_params[i]->getID() + ":",value); + #endif } - //read parameter - String value = server->arg(_params[i]->getID()).c_str(); - //store it in array - value.toCharArray(_params[i]->_value, _params[i]->_length + 1); - DEBUG_WM(F("Parameter")); - DEBUG_WM(_params[i]->getID()); - DEBUG_WM(value); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,FPSTR(D_HR)); + #endif } - if (server->arg("ip") != "") { - DEBUG_WM(F("static ip")); - DEBUG_WM(server->arg("ip")); - //_sta_static_ip.fromString(server->arg("ip")); - String ip = server->arg("ip"); - optionalIPFromString(&_sta_static_ip, ip.c_str()); + if ( _saveparamscallback != NULL) { + _saveparamscallback(); // @CALLBACK } - if (server->arg("gw") != "") { - DEBUG_WM(F("static gateway")); - DEBUG_WM(server->arg("gw")); - String gw = server->arg("gw"); - optionalIPFromString(&_sta_static_gw, gw.c_str()); - } - if (server->arg("sn") != "") { - DEBUG_WM(F("static netmask")); - DEBUG_WM(server->arg("sn")); - String sn = server->arg("sn"); - optionalIPFromString(&_sta_static_sn, sn.c_str()); - } - - String page = FPSTR(HTTP_HEAD); - page.replace("{v}", "Credentials Saved"); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); - page += FPSTR(HTTP_SAVED); - page += FPSTR(HTTP_END); - - server->sendHeader("Content-Length", String(page.length())); - server->send(200, "text/html", page); - - DEBUG_WM(F("Sent wifi save page")); - - connect = true; //signal ready to connect/reset + } -/** Handle the info page */ +/** + * HTTPD CALLBACK info page + */ void WiFiManager::handleInfo() { - DEBUG_WM(F("Info")); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Info")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleinfo)); // @token titleinfo + reportStatus(page); - String page = FPSTR(HTTP_HEAD); - page.replace("{v}", "Info"); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); - page += F("
"); - page += F("
Chip ID
"); - page += ESP.getChipId(); - page += F("
"); - page += F("
Flash Chip ID
"); - page += ESP.getFlashChipId(); - page += F("
"); - page += F("
IDE Flash Size
"); - page += ESP.getFlashChipSize(); - page += F(" bytes
"); - page += F("
Real Flash Size
"); - page += ESP.getFlashChipRealSize(); - page += F(" bytes
"); - page += F("
Soft AP IP
"); - page += WiFi.softAPIP().toString(); - page += F("
"); - page += F("
Soft AP MAC
"); - page += WiFi.softAPmacAddress(); - page += F("
"); - page += F("
Station MAC
"); - page += WiFi.macAddress(); - page += F("
"); - page += F("
"); - page += FPSTR(HTTP_END); + uint16_t infos = 0; - server->sendHeader("Content-Length", String(page.length())); - server->send(200, "text/html", page); + //@todo convert to enum or refactor to strings + //@todo wrap in build flag to remove all info code for memory saving + #ifdef ESP8266 + infos = 28; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("fchipid"), + F("idesize"), + F("flashsize"), + F("corever"), + F("bootver"), + F("cpufreq"), + F("freeheap"), + F("memsketch"), + F("memsmeter"), + F("lastreset"), + F("wifihead"), + F("conx"), + F("stassid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("autoconx"), + F("wifiaphead"), + F("apssid"), + F("apip"), + F("apbssid"), + F("apmac") + }; - DEBUG_WM(F("Sent info page")); -} + #elif defined(ESP32) + // add esp_chip_info ? + infos = 26; + String infoids[] = { + F("esphead"), + F("uptime"), + F("chipid"), + F("chiprev"), + F("idesize"), + F("flashsize"), + F("cpufreq"), + F("freeheap"), + F("memsketch"), + F("memsmeter"), + F("lastreset"), + F("wifihead"), + F("conx"), + F("stassid"), + F("staip"), + F("stagw"), + F("stasub"), + F("dnss"), + F("host"), + F("stamac"), + F("apssid"), + F("wifiaphead"), + F("apip"), + F("apmac"), + F("aphost"), + F("apbssid") + // F("temp") + }; + #endif -/** Handle the reset page */ -void WiFiManager::handleReset() { - DEBUG_WM(F("Reset")); - - String page = FPSTR(HTTP_HEAD); - page.replace("{v}", "Info"); - page += FPSTR(HTTP_SCRIPT); - page += FPSTR(HTTP_STYLE); - page += _customHeadElement; - page += FPSTR(HTTP_HEAD_END); - page += F("Module will reset in a few seconds."); - page += FPSTR(HTTP_END); - - server->sendHeader("Content-Length", String(page.length())); - server->send(200, "text/html", page); - - DEBUG_WM(F("Sent reset page")); - delay(5000); - ESP.reset(); - delay(2000); -} - -void WiFiManager::handleNotFound() { - if (captivePortal()) { // If captive portal redirect instead of displaying the error page. - return; + for(size_t i=0; i"); + + page += F("

About


"); + page += getInfoData("aboutver"); + page += getInfoData("aboutarduinover"); + page += getInfoData("aboutidfver"); + page += getInfoData("aboutdate"); + page += F("
"); + + if(_showInfoUpdate){ + page += HTTP_PORTAL_MENU[8]; + page += HTTP_PORTAL_MENU[9]; + } + if(_showInfoErase) page += FPSTR(HTTP_ERASEBTN); + if(_showBack) page += FPSTR(HTTP_BACKBTN); + page += FPSTR(HTTP_HELP); + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("Sent info page")); + #endif +} + +String WiFiManager::getInfoData(String id){ + + String p; + // @todo add WM versioning + if(id==F("esphead"))p = FPSTR(HTTP_INFO_esphead); + else if(id==F("wifihead"))p = FPSTR(HTTP_INFO_wifihead); + else if(id==F("uptime")){ + // subject to rollover! + p = FPSTR(HTTP_INFO_uptime); + p.replace(FPSTR(T_1),(String)(millis() / 1000 / 60)); + p.replace(FPSTR(T_2),(String)((millis() / 1000) % 60)); + } + else if(id==F("chipid")){ + p = FPSTR(HTTP_INFO_chipid); + p.replace(FPSTR(T_1),String(WIFI_getChipId(),HEX)); + } + #ifdef ESP32 + else if(id==F("chiprev")){ + p = FPSTR(HTTP_INFO_chiprev); + String rev = (String)ESP.getChipRevision(); + #ifdef _SOC_EFUSE_REG_H_ + String revb = (String)(REG_READ(EFUSE_BLK0_RDATA3_REG) >> (EFUSE_RD_CHIP_VER_RESERVE_S)&&EFUSE_RD_CHIP_VER_RESERVE_V); + p.replace(FPSTR(T_1),rev+"
"+revb); + #else + p.replace(FPSTR(T_1),rev); + #endif + } + #endif + #ifdef ESP8266 + else if(id==F("fchipid")){ + p = FPSTR(HTTP_INFO_fchipid); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipId()); + } + #endif + else if(id==F("idesize")){ + p = FPSTR(HTTP_INFO_idesize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipSize()); + } + else if(id==F("flashsize")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_flashsize); + p.replace(FPSTR(T_1),(String)ESP.getFlashChipRealSize()); + #elif defined ESP32 + p = FPSTR(HTTP_INFO_psrsize); + p.replace(FPSTR(T_1),(String)ESP.getPsramSize()); + #endif + } + else if(id==F("corever")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_corever); + p.replace(FPSTR(T_1),(String)ESP.getCoreVersion()); + #endif + } + #ifdef ESP8266 + else if(id==F("bootver")){ + p = FPSTR(HTTP_INFO_bootver); + p.replace(FPSTR(T_1),(String)system_get_boot_version()); + } + #endif + else if(id==F("cpufreq")){ + p = FPSTR(HTTP_INFO_cpufreq); + p.replace(FPSTR(T_1),(String)ESP.getCpuFreqMHz()); + } + else if(id==F("freeheap")){ + p = FPSTR(HTTP_INFO_freeheap); + p.replace(FPSTR(T_1),(String)ESP.getFreeHeap()); + } + else if(id==F("memsketch")){ + p = FPSTR(HTTP_INFO_memsketch); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + else if(id==F("memsmeter")){ + p = FPSTR(HTTP_INFO_memsmeter); + p.replace(FPSTR(T_1),(String)(ESP.getSketchSize())); + p.replace(FPSTR(T_2),(String)(ESP.getSketchSize()+ESP.getFreeSketchSpace())); + } + else if(id==F("lastreset")){ + #ifdef ESP8266 + p = FPSTR(HTTP_INFO_lastreset); + p.replace(FPSTR(T_1),(String)ESP.getResetReason()); + #elif defined(ESP32) && defined(_ROM_RTC_H_) + // requires #include + p = FPSTR(HTTP_INFO_lastreset); + for(int i=0;i<2;i++){ + int reason = rtc_get_reset_reason(i); + String tok = (String)T_ss+(String)(i+1)+(String)T_es; + switch (reason) + { + //@todo move to array + case 1 : p.replace(tok,F("Vbat power on reset"));break; + case 3 : p.replace(tok,F("Software reset digital core"));break; + case 4 : p.replace(tok,F("Legacy watch dog reset digital core"));break; + case 5 : p.replace(tok,F("Deep Sleep reset digital core"));break; + case 6 : p.replace(tok,F("Reset by SLC module, reset digital core"));break; + case 7 : p.replace(tok,F("Timer Group0 Watch dog reset digital core"));break; + case 8 : p.replace(tok,F("Timer Group1 Watch dog reset digital core"));break; + case 9 : p.replace(tok,F("RTC Watch dog Reset digital core"));break; + case 10 : p.replace(tok,F("Instrusion tested to reset CPU"));break; + case 11 : p.replace(tok,F("Time Group reset CPU"));break; + case 12 : p.replace(tok,F("Software reset CPU"));break; + case 13 : p.replace(tok,F("RTC Watch dog Reset CPU"));break; + case 14 : p.replace(tok,F("for APP CPU, reseted by PRO CPU"));break; + case 15 : p.replace(tok,F("Reset when the vdd voltage is not stable"));break; + case 16 : p.replace(tok,F("RTC Watch dog reset digital core and rtc module"));break; + default : p.replace(tok,F("NO_MEAN")); + } + } + #endif + } + else if(id==F("apip")){ + p = FPSTR(HTTP_INFO_apip); + p.replace(FPSTR(T_1),WiFi.softAPIP().toString()); + } + else if(id==F("apmac")){ + p = FPSTR(HTTP_INFO_apmac); + p.replace(FPSTR(T_1),(String)WiFi.softAPmacAddress()); + } + #ifdef ESP32 + else if(id==F("aphost")){ + p = FPSTR(HTTP_INFO_aphost); + p.replace(FPSTR(T_1),WiFi.softAPgetHostname()); + } + #endif + #ifndef WM_NOSOFTAPSSID + #ifdef ESP8266 + else if(id==F("apssid")){ + p = FPSTR(HTTP_INFO_apssid); + p.replace(FPSTR(T_1),htmlEntities(WiFi.softAPSSID())); + } + #endif + #endif + else if(id==F("apbssid")){ + p = FPSTR(HTTP_INFO_apbssid); + p.replace(FPSTR(T_1),(String)WiFi.BSSIDstr()); + } + // softAPgetHostname // esp32 + // softAPSubnetCIDR + // softAPNetworkID + // softAPBroadcastIP + + else if(id==F("stassid")){ + p = FPSTR(HTTP_INFO_stassid); + p.replace(FPSTR(T_1),htmlEntities((String)WiFi_SSID())); + } + else if(id==F("staip")){ + p = FPSTR(HTTP_INFO_staip); + p.replace(FPSTR(T_1),WiFi.localIP().toString()); + } + else if(id==F("stagw")){ + p = FPSTR(HTTP_INFO_stagw); + p.replace(FPSTR(T_1),WiFi.gatewayIP().toString()); + } + else if(id==F("stasub")){ + p = FPSTR(HTTP_INFO_stasub); + p.replace(FPSTR(T_1),WiFi.subnetMask().toString()); + } + else if(id==F("dnss")){ + p = FPSTR(HTTP_INFO_dnss); + p.replace(FPSTR(T_1),WiFi.dnsIP().toString()); + } + else if(id==F("host")){ + p = FPSTR(HTTP_INFO_host); + #ifdef ESP32 + p.replace(FPSTR(T_1),WiFi.getHostname()); + #else + p.replace(FPSTR(T_1),WiFi.hostname()); + #endif + } + else if(id==F("stamac")){ + p = FPSTR(HTTP_INFO_stamac); + p.replace(FPSTR(T_1),WiFi.macAddress()); + } + else if(id==F("conx")){ + p = FPSTR(HTTP_INFO_conx); + p.replace(FPSTR(T_1),WiFi.isConnected() ? FPSTR(S_y) : FPSTR(S_n)); + } + #ifdef ESP8266 + else if(id==F("autoconx")){ + p = FPSTR(HTTP_INFO_autoconx); + p.replace(FPSTR(T_1),WiFi.getAutoConnect() ? FPSTR(S_enable) : FPSTR(S_disable)); + } + #endif + #if defined(ESP32) && !defined(WM_NOTEMP) + else if(id==F("temp")){ + // temperature is not calibrated, varying large offsets are present, use for relative temp changes only + p = FPSTR(HTTP_INFO_temp); + p.replace(FPSTR(T_1),(String)temperatureRead()); + p.replace(FPSTR(T_2),(String)((temperatureRead()+32)*1.8)); + // p.replace(FPSTR(T_3),(String)hallRead()); + p.replace(FPSTR(T_3),"NA"); + } + #endif + else if(id==F("aboutver")){ + p = FPSTR(HTTP_INFO_aboutver); + p.replace(FPSTR(T_1),FPSTR(WM_VERSION_STR)); + } + else if(id==F("aboutarduinover")){ + #ifdef VER_ARDUINO_STR + p = FPSTR(HTTP_INFO_aboutarduino); + p.replace(FPSTR(T_1),String(VER_ARDUINO_STR)); + #endif + } + // else if(id==F("aboutidfver")){ + // #ifdef VER_IDF_STR + // p = FPSTR(HTTP_INFO_aboutidf); + // p.replace(FPSTR(T_1),String(VER_IDF_STR)); + // #endif + // } + else if(id==F("aboutsdkver")){ + p = FPSTR(HTTP_INFO_sdkver); + #ifdef ESP32 + p.replace(FPSTR(T_1),(String)esp_get_idf_version()); + // p.replace(FPSTR(T_1),(String)system_get_sdk_version()); // deprecated + #else + p.replace(FPSTR(T_1),(String)system_get_sdk_version()); + #endif + } + else if(id==F("aboutdate")){ + p = FPSTR(HTTP_INFO_aboutdate); + p.replace(FPSTR(T_1),String(__DATE__ " " __TIME__)); + } + return p; +} + +/** + * HTTPD CALLBACK exit, closes configportal if blocking, if non blocking undefined + */ +void WiFiManager::handleExit() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Exit")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleexit)); // @token titleexit + page += FPSTR(S_exiting); // @token exiting + // ('Logout', 401, {'WWW-Authenticate': 'Basic realm="Login required"'}) + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); // @HTTPHEAD send cache + HTTPSend(page); + delay(2000); + abort = true; +} + +/** + * HTTPD CALLBACK reset page + */ +void WiFiManager::handleReset() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP Reset")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titlereset)); //@token titlereset + page += FPSTR(S_resetting); //@token resetting + page += FPSTR(HTTP_END); + + HTTPSend(page); + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("RESETTING ESP")); + #endif + delay(1000); + reboot(); +} + +/** + * HTTPD CALLBACK erase page + */ + +// void WiFiManager::handleErase() { +// handleErase(false); +// } +void WiFiManager::handleErase(boolean opt) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_NOTIFY,F("<- HTTP Erase")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleerase)); // @token titleerase + + bool ret = erase(opt); + + if(ret) page += FPSTR(S_resetting); // @token resetting + else { + page += FPSTR(S_error); // @token erroroccur + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] WiFi EraseConfig failed")); + #endif + } + + page += FPSTR(HTTP_END); + HTTPSend(page); + + if(ret){ + delay(2000); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("RESETTING ESP")); + #endif + reboot(); + } +} + +/** + * HTTPD CALLBACK 404 + */ +void WiFiManager::handleNotFound() { + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + handleRequest(); + String message = FPSTR(S_notfound); // @token notfound + message += FPSTR(S_uri); // @token uri message += server->uri(); - message += "\nMethod: "; - message += ( server->method() == HTTP_GET ) ? "GET" : "POST"; - message += "\nArguments: "; + message += FPSTR(S_method); // @token method + message += ( server->method() == HTTP_GET ) ? FPSTR(S_GET) : FPSTR(S_POST); + message += FPSTR(S_args); // @token args message += server->args(); - message += "\n"; + message += F("\n"); for ( uint8_t i = 0; i < server->args(); i++ ) { message += " " + server->argName ( i ) + ": " + server->arg ( i ) + "\n"; } - server->sendHeader("Cache-Control", "no-cache, no-store, must-revalidate"); - server->sendHeader("Pragma", "no-cache"); - server->sendHeader("Expires", "-1"); - server->sendHeader("Content-Length", String(message.length())); - server->send ( 404, "text/plain", message ); + server->sendHeader(F("Cache-Control"), F("no-cache, no-store, must-revalidate")); // @HTTPHEAD send cache + server->sendHeader(F("Pragma"), F("no-cache")); + server->sendHeader(F("Expires"), F("-1")); + server->send ( 404, FPSTR(HTTP_HEAD_CT2), message ); } - -/** Redirect to captive portal if we got a request for another domain. Return true in that case so the page handler do not try to handle the request again. */ +/** + * HTTPD redirector + * Redirect to captive portal if we got a request for another domain. + * Return true in that case so the page handler do not try to handle the request again. + */ boolean WiFiManager::captivePortal() { - if (!isIp(server->hostHeader()) ) { - DEBUG_WM(F("Request redirected to captive portal")); - server->sendHeader("Location", String("http://") + toStringIp(server->client().localIP()), true); - server->send ( 302, "text/plain", ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_MAX,"-> " + server->hostHeader()); + #endif + + if(!_enableCaptivePortal) return false; // skip redirections, @todo maybe allow redirection even when no cp ? might be useful + + String serverLoc = toStringIp(server->client().localIP()); + if(_httpPort != 80) serverLoc += ":" + (String)_httpPort; // add port if not default + bool doredirect = serverLoc != server->hostHeader(); // redirect if hostheader not server ip, prevent redirect loops + // doredirect = !isIp(server->hostHeader()) // old check + + if (doredirect) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- Request redirected to captive portal")); + #endif + server->sendHeader(F("Location"), (String)F("http://") + serverLoc, true); // @HTTPHEAD send redirect + server->send ( 302, FPSTR(HTTP_HEAD_CT2), ""); // Empty content inhibits Content-length header so we have to close the socket ourselves. server->client().stop(); // Stop is needed because we sent no content length return true; } return false; } -//start up config portal callback -void WiFiManager::setAPCallback( void (*func)(WiFiManager* myWiFiManager) ) { +void WiFiManager::stopCaptivePortal(){ + _enableCaptivePortal= false; + // @todo maybe disable configportaltimeout(optional), or just provide callback for user +} + +// HTTPD CALLBACK, handle close, stop captive portal, if not enabled undefined +void WiFiManager::handleClose(){ + DEBUG_WM(DEBUG_VERBOSE,F("Disabling Captive Portal")); + stopCaptivePortal(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- HTTP close")); + #endif + handleRequest(); + String page = getHTTPHead(FPSTR(S_titleclose)); // @token titleclose + page += FPSTR(S_closing); // @token closing + HTTPSend(page); +} + +void WiFiManager::reportStatus(String &page){ + // updateConxResult(WiFi.status()); // @todo: this defeats the purpose of last result, update elsewhere or add logic here + DEBUG_WM(DEBUG_DEV,F("[WIFI] reportStatus prev:"),getWLStatusString(_lastconxresult)); + DEBUG_WM(DEBUG_DEV,F("[WIFI] reportStatus current:"),getWLStatusString(WiFi.status())); + String str; + if (WiFi_SSID() != ""){ + if (WiFi.status()==WL_CONNECTED){ + str = FPSTR(HTTP_STATUS_ON); + str.replace(FPSTR(T_i),WiFi.localIP().toString()); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + } + else { + str = FPSTR(HTTP_STATUS_OFF); + str.replace(FPSTR(T_v),htmlEntities(WiFi_SSID())); + if(_lastconxresult == WL_STATION_WRONG_PASSWORD){ + // wrong password + str.replace(FPSTR(T_c),"D"); // class + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFPW)); + } + else if(_lastconxresult == WL_NO_SSID_AVAIL){ + // connect failed, or ap not found + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFNOAP)); + } + else if(_lastconxresult == WL_CONNECT_FAILED){ + // connect failed + str.replace(FPSTR(T_c),"D"); + str.replace(FPSTR(T_r),FPSTR(HTTP_STATUS_OFFFAIL)); + } + else{ + str.replace(FPSTR(T_c),""); + str.replace(FPSTR(T_r),""); + } + } + } + else { + str = FPSTR(HTTP_STATUS_NONE); + } + page += str; +} + +// PUBLIC + +// METHODS + +/** + * reset wifi settings, clean stored ap password + */ + +/** + * [stopConfigPortal description] + * @return {[type]} [description] + */ +bool WiFiManager::stopConfigPortal(){ + if(_configPortalIsBlocking){ + abort = true; + return true; + } + return shutdownConfigPortal(); +} + +/** + * disconnect + * @access public + * @since $dev + * @return bool success + */ +bool WiFiManager::disconnect(){ + if(WiFi.status() != WL_CONNECTED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("Disconnecting: Not connected")); + #endif + return false; + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Disconnecting")); + #endif + return WiFi_Disconnect(); +} + +/** + * reboot the device + * @access public + */ +void WiFiManager::reboot(){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Restarting")); + #endif + ESP.restart(); +} + +/** + * reboot the device + * @access public + */ +bool WiFiManager::erase(){ + return erase(false); +} + +bool WiFiManager::erase(bool opt){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM("Erasing"); + #endif + + #if defined(ESP32) && ((defined(WM_ERASE_NVS) || defined(nvs_flash_h))) + // if opt true, do nvs erase + if(opt){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing NVS")); + #endif + esp_err_t err; + err = nvs_flash_init(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("nvs_flash_init: "),err!=ESP_OK ? (String)err : "Success"); + #endif + err = nvs_flash_erase(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("nvs_flash_erase: "), err!=ESP_OK ? (String)err : "Success"); + #endif + return err == ESP_OK; + } + #elif defined(ESP8266) && defined(spiffs_api_h) + if(opt){ + bool ret = false; + if(SPIFFS.begin()){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing SPIFFS")); + #endif + bool ret = SPIFFS.format(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("spiffs erase: "),ret ? "Success" : "ERROR"); + #endif + } else{ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("[ERROR] Could not start SPIFFS")); + #endif + } + return ret; + } + #else + (void)opt; + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("Erasing WiFi Config")); + #endif + return WiFi_eraseConfig(); +} + +/** + * [resetSettings description] + * ERASES STA CREDENTIALS + * @access public + */ +void WiFiManager::resetSettings() { +#ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("resetSettings")); + #endif + WiFi_enableSTA(true,true); // must be sta to disconnect erase + delay(500); // ensure sta is enabled + if (_resetcallback != NULL){ + _resetcallback(); // @CALLBACK + } + + #ifdef ESP32 + WiFi.disconnect(true,true); + #else + WiFi.persistent(true); + WiFi.disconnect(true); + WiFi.persistent(false); + #endif + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("SETTINGS ERASED")); + #endif +} + +// SETTERS + +/** + * [setTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setTimeout(unsigned long seconds) { + setConfigPortalTimeout(seconds); +} + +/** + * [setConfigPortalTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConfigPortalTimeout(unsigned long seconds) { + _configPortalTimeout = seconds * 1000; +} + +/** + * [setConnectTimeout description] + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setConnectTimeout(unsigned long seconds) { + _connectTimeout = seconds * 1000; +} + +/** + * [setConnectRetries description] + * @access public + * @param {[type]} uint8_t numRetries [description] + */ +void WiFiManager::setConnectRetries(uint8_t numRetries){ + _connectRetries = constrain(numRetries,1,10); +} + +/** + * toggle _cleanconnect, always disconnect before connecting + * @param {[type]} bool enable [description] + */ +void WiFiManager::setCleanConnect(bool enable){ + _cleanConnect = enable; +} + +/** + * [setConnectTimeout description + * @access public + * @param {[type]} unsigned long seconds [description] + */ +void WiFiManager::setSaveConnectTimeout(unsigned long seconds) { + _saveTimeout = seconds * 1000; +} + +/** + * Set save portal connect on save option, + * if false, will only save credentials not connect + * @access public + * @param {[type]} bool connect [description] + */ +void WiFiManager::setSaveConnect(bool connect) { + _connectonsave = connect; +} + +/** + * [setDebugOutput description] + * @access public + * @param {[type]} boolean debug [description] + */ +void WiFiManager::setDebugOutput(boolean debug) { + _debug = debug; + if(_debug && _debugLevel == DEBUG_DEV) debugPlatformInfo(); +} + +void WiFiManager::setDebugOutput(boolean debug, String prefix) { + _debugPrefix = prefix; + setDebugOutput(debug); +} + +/** + * [setAPStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _ap_static_ip = ip; + _ap_static_gw = gw; + _ap_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn) { + _sta_static_ip = ip; + _sta_static_gw = gw; + _sta_static_sn = sn; +} + +/** + * [setSTAStaticIPConfig description] + * @since $dev + * @access public + * @param {[type]} IPAddress ip [description] + * @param {[type]} IPAddress gw [description] + * @param {[type]} IPAddress sn [description] + * @param {[type]} IPAddress dns [description] + */ +void WiFiManager::setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns) { + setSTAStaticIPConfig(ip,gw,sn); + _sta_static_dns = dns; +} + +/** + * [setMinimumSignalQuality description] + * @access public + * @param {[type]} int quality [description] + */ +void WiFiManager::setMinimumSignalQuality(int quality) { + _minimumQuality = quality; +} + +/** + * [setBreakAfterConfig description] + * @access public + * @param {[type]} boolean shouldBreak [description] + */ +void WiFiManager::setBreakAfterConfig(boolean shouldBreak) { + _shouldBreakAfterConfig = shouldBreak; +} + +/** + * setAPCallback, set a callback when softap is started + * @access public + * @param {[type]} void (*func)(WiFiManager* wminstance) + */ +void WiFiManager::setAPCallback( std::function func ) { _apcallback = func; } -//start up save config callback -void WiFiManager::setSaveConfigCallback( void (*func)(void) ) { - _savecallback = func; +/** + * setWebServerCallback, set a callback after webserver is reset, and before routes are setup + * if we set webserver handlers before wm, they are used and wm is not by esp webserver + * on events cannot be overrided once set, and are not mutiples + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setWebServerCallback( std::function func ) { + _webservercallback = func; } -//sets a custom element to add to head, like a new style tag -void WiFiManager::setCustomHeadElement(const char* element) { - _customHeadElement = element; +/** + * setSaveConfigCallback, set a save config callback after closing configportal + * @note calls only if wifi is saved or changed, or setBreakAfterConfig(true) + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveConfigCallback( std::function func ) { + _savewificallback = func; } -//if this is true, remove duplicated Access Points - defaut true +/** + * setPreSaveConfigCallback, set a callback to fire before saving wifi or params + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreSaveConfigCallback( std::function func ) { + _presavewificallback = func; +} + +/** + * setConfigResetCallback, set a callback to occur when a resetSettings() occurs + * @access public + * @param {[type]} void(*func)(void) + */ +void WiFiManager::setConfigResetCallback( std::function func ) { + _resetcallback = func; +} + +/** + * setSaveParamsCallback, set a save params callback on params save in wifi or params pages + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setSaveParamsCallback( std::function func ) { + _saveparamscallback = func; +} + +/** + * setPreSaveParamsCallback, set a pre save params callback on params save prior to anything else + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreSaveParamsCallback( std::function func ) { + _presaveparamscallback = func; +} + +/** + * setPreOtaUpdateCallback, set a callback to fire before OTA update + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setPreOtaUpdateCallback( std::function func ) { + _preotaupdatecallback = func; +} + +/** + * setConfigPortalTimeoutCallback, set a callback to config portal is timeout + * @access public + * @param {[type]} void (*func)(void) + */ +void WiFiManager::setConfigPortalTimeoutCallback( std::function func ) { + _configportaltimeoutcallback = func; +} + +/** + * set custom head html + * custom element will be added to head, eg. new meta,style,script tag etc. + * @access public + * @param char element + */ +void WiFiManager::setCustomHeadElement(const char* html) { + _customHeadElement = html; +} + +/** + * set custom menu html + * custom element will be added to menu under custom menu item. + * @access public + * @param char element + */ +void WiFiManager::setCustomMenuHTML(const char* html) { + _customMenuHTML = html; +} + +/** + * toggle wifiscan hiding of duplicate ssid names + * if this is false, wifiscan will remove duplicat Access Points - defaut true + * @access public + * @param boolean removeDuplicates [true] + */ void WiFiManager::setRemoveDuplicateAPs(boolean removeDuplicates) { _removeDuplicateAPs = removeDuplicates; } +/** + * toggle configportal blocking loop + * if enabled, then the configportal will enter a blocking loop and wait for configuration + * if disabled use with process() to manually process webserver + * @since $dev + * @access public + * @param boolean shoudlBlock [false] + */ +void WiFiManager::setConfigPortalBlocking(boolean shouldBlock) { + _configPortalIsBlocking = shouldBlock; +} + +/** + * toggle restore persistent, track internally + * sets ESP wifi.persistent so we can remember it and restore user preference on destruct + * there is no getter in esp8266 platform prior to https://github.com/esp8266/Arduino/pull/3857 + * @since $dev + * @access public + * @param boolean persistent [true] + */ +void WiFiManager::setRestorePersistent(boolean persistent) { + _userpersistent = persistent; + if(!persistent){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("persistent is off")); + #endif + } +} + +/** + * toggle showing static ip form fields + * if enabled, then the static ip, gateway, subnet fields will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowStaticFields(boolean alwaysShow){ + if(_disableIpFields) _staShowStaticFields = alwaysShow ? 1 : -1; + else _staShowStaticFields = alwaysShow ? 1 : 0; +} + +/** + * toggle showing dns fields + * if enabled, then the dns1 field will be visible, even if not set in code + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowDnsFields(boolean alwaysShow){ + if(_disableIpFields) _staShowDns = alwaysShow ? 1 : -1; + _staShowDns = alwaysShow ? 1 : 0; +} + +/** + * toggle showing password in wifi password field + * if not enabled, placeholder will be S_passph + * @since $dev + * @access public + * @param boolean alwaysShow [false] + */ +void WiFiManager::setShowPassword(boolean show){ + _showPassword = show; +} + +/** + * toggle captive portal + * if enabled, then devices that use captive portal checks will be redirected to root + * if not you will automatically have to navigate to ip [192.168.4.1] + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setCaptivePortalEnable(boolean enabled){ + _enableCaptivePortal = enabled; +} + +/** + * toggle wifi autoreconnect policy + * if enabled, then wifi will autoreconnect automatically always + * On esp8266 we force this on when autoconnect is called, see notes + * On esp32 this is handled on SYSTEM_EVENT_STA_DISCONNECTED since it does not exist in core yet + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWiFiAutoReconnect(boolean enabled){ + _wifiAutoReconnect = enabled; +} + +/** + * toggle configportal timeout wait for station client + * if enabled, then the configportal will start timeout when no stations are connected to softAP + * disabled by default as rogue stations can keep it open if there is no auth + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setAPClientCheck(boolean enabled){ + _apClientCheck = enabled; +} + +/** + * toggle configportal timeout wait for web client + * if enabled, then the configportal will restart timeout when client requests come in + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setWebPortalClientCheck(boolean enabled){ + _webClientCheck = enabled; +} + +/** + * toggle wifiscan percentages or quality icons + * @since $dev + * @access public + * @param boolean enabled [false] + */ +void WiFiManager::setScanDispPerc(boolean enabled){ + _scanDispOptions = enabled; +} + +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be activated on autoconnect failure + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setEnableConfigPortal(boolean enable) +{ + _enableConfigPortal = enable; +} + +/** + * toggle configportal if autoconnect failed + * if enabled, then the configportal will be de-activated on wifi save + * @since $dev + * @access public + * @param boolean enabled [true] + */ +void WiFiManager::setDisableConfigPortal(boolean enable) +{ + _disableConfigPortal = enable; +} + +/** + * set the hostname (dhcp client id) + * @since $dev + * @access public + * @param char* hostname 32 character hostname to use for sta+ap in esp32, sta in esp8266 + * @return bool false if hostname is not valid + */ +bool WiFiManager::setHostname(const char * hostname){ + //@todo max length 32 + _hostname = String(hostname); + return true; +} + +bool WiFiManager::setHostname(String hostname){ + //@todo max length 32 + _hostname = hostname; + return true; +} + +/** + * set the soft ao channel, ignored if channelsync is true and connected + * @param int32_t wifi channel, 0 to disable + */ +void WiFiManager::setWiFiAPChannel(int32_t channel){ + _apChannel = channel; +} + +/** + * set the soft ap hidden + * @param bool wifi ap hidden, default is false + */ +void WiFiManager::setWiFiAPHidden(bool hidden){ + _apHidden = hidden; +} +/** + * toggle showing erase wifi config button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoErase(boolean enabled){ + _showInfoErase = enabled; +} + +/** + * toggle showing update upload web ota button on info page + * @param boolean enabled + */ +void WiFiManager::setShowInfoUpdate(boolean enabled){ + _showInfoUpdate = enabled; +} + +/** + * check if the config portal is running + * @return bool true if active + */ +bool WiFiManager::getConfigPortalActive(){ + return configPortalActive; +} + +/** + * [getConfigPortalActive description] + * @return bool true if active + */ +bool WiFiManager::getWebPortalActive(){ + return webPortalActive; +} + + +String WiFiManager::getWiFiHostname(){ + #ifdef ESP32 + return (String)WiFi.getHostname(); + #else + return (String)WiFi.hostname(); + #endif +} + +/** + * [setTitle description] + * @param String title, set app title + */ +void WiFiManager::setTitle(String title){ + _title = title; +} + +/** + * set menu items and order + * if param is present in menu , params will be removed from wifi page automatically + * eg. + * const char * menu[] = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * @since $dev + * @param uint8_t menu[] array of menu ids + */ +void WiFiManager::setMenu(const char * menu[], uint8_t size){ +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,"setmenu array"); + #endif + _menuIds.clear(); + for(size_t i = 0; i < size; i++){ + for(size_t j = 0; j < _nummenutokens; j++){ + if(menu[i] == _menutokens[j]){ + if((String)menu[i] == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(getMenuOut()); + #endif +} + +/** + * setMenu with vector + * eg. + * std::vector menu = {"wifi","setup","sep","info","exit"}; + * WiFiManager.setMenu(menu); + * tokens can be found in _menutokens array in strings_en.h + * @shiftIncrement $dev + * @param {[type]} std::vector& menu [description] + */ +void WiFiManager::setMenu(std::vector& menu){ +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,"setmenu vector"); + #endif + _menuIds.clear(); + for(auto menuitem : menu ){ + for(size_t j = 0; j < _nummenutokens; j++){ + if(menuitem == _menutokens[j]){ + if((String)menuitem == "param") _paramsInWifi = false; // param auto flag + _menuIds.push_back(j); + } + } + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_DEV,getMenuOut()); + #endif +} + + +/** + * set params as sperate page not in wifi + * NOT COMPATIBLE WITH setMenu! + * @todo scan menuids and insert param after wifi or something, same for ota + * @param bool enable + * @since $dev + */ +void WiFiManager::setParamsPage(bool enable){ + _paramsInWifi = !enable; + setMenu(enable ? _menuIdsParams : _menuIdsDefault); +} + +// GETTERS + +/** + * get config portal AP SSID + * @since 0.0.1 + * @access public + * @return String the configportal ap name + */ +String WiFiManager::getConfigPortalSSID() { + return _apName; +} + +/** + * return the last known connection result + * logged on autoconnect and wifisave, can be used to check why failed + * get as readable string with getWLStatusString(getLastConxResult); + * @since $dev + * @access public + * @return bool return wl_status codes + */ +uint8_t WiFiManager::getLastConxResult(){ + return _lastconxresult; +} + +/** + * check if wifi has a saved ap or not + * @since $dev + * @access public + * @return bool true if a saved ap config exists + */ +bool WiFiManager::getWiFiIsSaved(){ + return WiFi_hasAutoConnect(); +} + +/** + * getDefaultAPName + * @since $dev + * @return string + */ +String WiFiManager::getDefaultAPName(){ + String hostString = String(WIFI_getChipId(),HEX); + hostString.toUpperCase(); + // char hostString[16] = {0}; + // sprintf(hostString, "%06X", ESP.getChipId()); + return _wifissidprefix + "_" + hostString; +} + +/** + * setCountry + * @since $dev + * @param String cc country code, must be defined in WiFiSetCountry, US, JP, CN + */ +void WiFiManager::setCountry(String cc){ + _wificountry = cc; +} + +/** + * setClass + * @param String str body class string + */ +void WiFiManager::setClass(String str){ + _bodyClass = str; +} + +/** + * setDarkMode + * @param bool enable, enable dark mode via invert class + */ +void WiFiManager::setDarkMode(bool enable){ + _bodyClass = enable ? "invert" : ""; +} + +/** + * setHttpPort + * @param uint16_t port webserver port number default 80 + */ +void WiFiManager::setHttpPort(uint16_t port){ + _httpPort = port; +} + + +bool WiFiManager::preloadWiFi(String ssid, String pass){ + _defaultssid = ssid; + _defaultpass = pass; + return true; +} + +// HELPERS + +/** + * getWiFiSSID + * @since $dev + * @param bool persistent + * @return String + */ +String WiFiManager::getWiFiSSID(bool persistent){ + return WiFi_SSID(persistent); +} + +/** + * getWiFiPass + * @since $dev + * @param bool persistent + * @return String + */ +String WiFiManager::getWiFiPass(bool persistent){ + return WiFi_psk(persistent); +} + +// DEBUG +// @todo fix DEBUG_WM(0,0); template void WiFiManager::DEBUG_WM(Generic text) { - if (_debug) { - Serial.print("*WM: "); - Serial.println(text); + DEBUG_WM(DEBUG_NOTIFY,text,""); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text) { + if(_debugLevel >= level) DEBUG_WM(level,text,""); +} + +template +void WiFiManager::DEBUG_WM(Generic text,Genericb textb) { + DEBUG_WM(DEBUG_NOTIFY,text,textb); +} + +template +void WiFiManager::DEBUG_WM(wm_debuglevel_t level,Generic text,Genericb textb) { + if(!_debug || _debugLevel < level) return; + + if(_debugLevel >= DEBUG_MAX){ + #ifdef ESP8266 + // uint32_t free; + // uint16_t max; + // uint8_t frag; + // ESP.getHeapStats(&free, &max, &frag);// @todo Does not exist in 2.3.0 + // _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + #elif defined ESP32 + // total_free_bytes; ///< Total free bytes in the heap. Equivalent to multi_free_heap_size(). + // total_allocated_bytes; ///< Total bytes allocated to data in the heap. + // largest_free_block; ///< Size of largest free block in the heap. This is the largest malloc-able size. + // minimum_free_bytes; ///< Lifetime minimum free heap size. Equivalent to multi_minimum_free_heap_size(). + // allocated_blocks; ///< Number of (variable size) blocks allocated in the heap. + // free_blocks; ///< Number of (variable size) free blocks in the heap. + // total_blocks; ///< Total number of (variable size) blocks in the heap. + multi_heap_info_t info; + heap_caps_get_info(&info, MALLOC_CAP_INTERNAL); + uint32_t free = info.total_free_bytes; + uint16_t max = info.largest_free_block; + uint8_t frag = 100 - (max * 100) / free; + _debugPort.printf("[MEM] free: %5d | max: %5d | frag: %3d%% \n", free, max, frag); + #endif } + _debugPort.print(_debugPrefix); + if(_debugLevel >= debugLvlShow) _debugPort.print("["+(String)level+"] "); + _debugPort.print(text); + if(textb){ + _debugPort.print(" "); + _debugPort.print(textb); + } + _debugPort.println(); +} + +/** + * [debugSoftAPConfig description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugSoftAPConfig(){ + + #ifdef ESP8266 + softap_config config; + wifi_softap_get_config(&config); + #if !defined(WM_NOCOUNTRY) + wifi_country_t country; + wifi_get_country(&country); + #endif + #elif defined(ESP32) + wifi_country_t country; + wifi_config_t conf_config; + esp_wifi_get_config(WIFI_IF_AP, &conf_config); // == ESP_OK + wifi_ap_config_t config = conf_config.ap; + esp_wifi_get_country(&country); + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("SoftAP Configuration")); + DEBUG_WM(FPSTR(D_HR)); + DEBUG_WM(F("ssid: "),(char *) config.ssid); + DEBUG_WM(F("password: "),(char *) config.password); + DEBUG_WM(F("ssid_len: "),config.ssid_len); + DEBUG_WM(F("channel: "),config.channel); + DEBUG_WM(F("authmode: "),config.authmode); + DEBUG_WM(F("ssid_hidden: "),config.ssid_hidden); + DEBUG_WM(F("max_connection: "),config.max_connection); + #endif + #if !defined(WM_NOCOUNTRY) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("country: "),(String)country.cc); + #endif + DEBUG_WM(F("beacon_interval: "),(String)config.beacon_interval + "(ms)"); + DEBUG_WM(FPSTR(D_HR)); + #endif +} + +/** + * [debugPlatformInfo description] + * @access public + * @return {[type]} [description] + */ +void WiFiManager::debugPlatformInfo(){ + #ifdef ESP8266 + system_print_meminfo(); + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("getCoreVersion(): "),ESP.getCoreVersion()); + DEBUG_WM(F("system_get_sdk_version(): "),system_get_sdk_version()); + DEBUG_WM(F("system_get_boot_version():"),system_get_boot_version()); + DEBUG_WM(F("getFreeHeap(): "),(String)ESP.getFreeHeap()); + #endif + #elif defined(ESP32) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("WM version: "), WM_VERSION_STR); + DEBUG_WM(F("Arduino version: "), VER_ARDUINO_STR); + DEBUG_WM(F("ESP SDK version: "), ESP.getSdkVersion()); + DEBUG_WM(F("Free heap: "), ESP.getFreeHeap()); + #endif + // esp_chip_info_t chipInfo; + // esp_chip_info(&chipInfo); + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM("Chip Info: Model: ",chipInfo.model); + // DEBUG_WM("Chip Info: Cores: ",chipInfo.cores); + // DEBUG_WM("Chip Info: Rev: ",chipInfo.revision); + // DEBUG_WM(printf("Chip Info: Model: %d, cores: %d, revision: %d", chipInfo.model.c_str(), chipInfo.cores, chipInfo.revision)); + // DEBUG_WM("Chip Rev: ",(String)ESP.getChipRevision()); + #endif + // core version is not avail + #endif } int WiFiManager::getRSSIasQuality(int RSSI) { @@ -815,3 +3417,530 @@ String WiFiManager::toStringIp(IPAddress ip) { res += String(((ip >> 8 * 3)) & 0xFF); return res; } + +boolean WiFiManager::validApPassword(){ + // check that ap password is valid, return false + if (_apPassword == NULL) _apPassword = ""; + if (_apPassword != "") { + if (_apPassword.length() < 8 || _apPassword.length() > 63) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(F("AccessPoint set password is INVALID or <8 chars")); + #endif + _apPassword = ""; + return false; // @todo FATAL or fallback to empty , currently fatal, fail secure. + } + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("AccessPoint set password is VALID")); + DEBUG_WM(DEBUG_DEV,"ap pass",_apPassword); + #endif + } + return true; +} + +/** + * encode htmlentities + * @since $dev + * @param string str string to replace entities + * @return string encoded string + */ +String WiFiManager::htmlEntities(String str, bool whitespace) { + str.replace("&","&"); + str.replace("<","<"); + str.replace(">",">"); + str.replace("'","'"); + if(whitespace) str.replace(" "," "); + // str.replace("-","–"); + // str.replace("\"","""); + // str.replace("/": "/"); + // str.replace("`": "`"); + // str.replace("=": "="); +return str; +} + +/** + * [getWLStatusString description] + * @access public + * @param {[type]} uint8_t status [description] + * @return {[type]} [description] + */ +String WiFiManager::getWLStatusString(uint8_t status){ + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + +String WiFiManager::getWLStatusString(){ + uint8_t status = WiFi.status(); + if(status <= 7) return WIFI_STA_STATUS[status]; + return FPSTR(S_NA); +} + +String WiFiManager::encryptionTypeStr(uint8_t authmode) { +#ifdef WM_DEBUG_LEVEL + // DEBUG_WM("enc_tye: ",authmode); + #endif + return AUTH_MODE_NAMES[authmode]; +} + +String WiFiManager::getModeString(uint8_t mode){ + if(mode <= 3) return WIFI_MODES[mode]; + return FPSTR(S_NA); +} + +bool WiFiManager::WiFiSetCountry(){ + if(_wificountry == "") return false; // skip not set + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("WiFiSetCountry to"),_wificountry); + #endif + +/* + * @return + * - ESP_OK: succeed + * - ESP_ERR_WIFI_NOT_INIT: WiFi is not initialized by eps_wifi_init + * - ESP_ERR_WIFI_IF: invalid interface + * - ESP_ERR_WIFI_ARG: invalid argument + * - others: refer to error codes in esp_err.h + */ + + // @todo move these definitions, and out of cpp `esp_wifi_set_country(&WM_COUNTRY_US)` + bool ret = true; + // ret = esp_wifi_set_bandwidth(WIFI_IF_AP,WIFI_BW_HT20); // WIFI_BW_HT40 + #ifdef ESP32 + esp_err_t err = ESP_OK; + // @todo check if wifi is init, no idea how, doesnt seem to be exposed atm ( check again it might be now! ) + if(WiFi.getMode() == WIFI_MODE_NULL){ + DEBUG_WM(DEBUG_ERROR,"[ERROR] cannot set country, wifi not init"); + } // exception if wifi not init! + // Assumes that _wificountry is set to one of the supported country codes : "01"(world safe mode) "AT","AU","BE","BG","BR", + // "CA","CH","CN","CY","CZ","DE","DK","EE","ES","FI","FR","GB","GR","HK","HR","HU", + // "IE","IN","IS","IT","JP","KR","LI","LT","LU","LV","MT","MX","NL","NO","NZ","PL","PT", + // "RO","SE","SI","SK","TW","US" + // If an invalid country code is passed, ESP_ERR_WIFI_ARG will be returned + // This also uses 802.11d mode, which matches the STA to the country code of the AP it connects to (meaning + // that the country code will be overridden if connecting to a "foreign" AP) + else { + #ifndef WM_NOCOUNTRY + err = esp_wifi_set_country_code(_wificountry.c_str(), true); + #else + DEBUG_WM(DEBUG_ERROR,"[ERROR] esp wifi set country is not available"); + err = true; + #endif + } + #ifdef WM_DEBUG_LEVEL + if(err){ + if(err == ESP_ERR_WIFI_NOT_INIT) DEBUG_WM(DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_NOT_INIT"); + else if(err == ESP_ERR_INVALID_ARG) DEBUG_WM(DEBUG_ERROR,"[ERROR] ESP_ERR_WIFI_ARG (invalid country code)"); + else if(err != ESP_OK)DEBUG_WM(DEBUG_ERROR,"[ERROR] unknown error",(String)err); + } + #endif + ret = err == ESP_OK; + + #elif defined(ESP8266) && !defined(WM_NOCOUNTRY) + // if(WiFi.getMode() == WIFI_OFF); // exception if wifi not init! + if(_wificountry == "US") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_US); + else if(_wificountry == "JP") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_JP); + else if(_wificountry == "CN") ret = wifi_set_country((wifi_country_t*)&WM_COUNTRY_CN); + #ifdef WM_DEBUG_LEVEL + else DEBUG_WM(DEBUG_ERROR,F("[ERROR] country code not found")); + #endif + #endif + + #ifdef WM_DEBUG_LEVEL + if(ret) DEBUG_WM(DEBUG_VERBOSE,F("[OK] esp_wifi_set_country: "),_wificountry); + else DEBUG_WM(DEBUG_ERROR,F("[ERROR] esp_wifi_set_country failed")); + #endif + return ret; +} + +// set mode ignores WiFi.persistent +bool WiFiManager::WiFi_Mode(WiFiMode_t m,bool persistent) { + bool ret; + #ifdef ESP8266 + if((wifi_get_opmode() == (uint8) m ) && !persistent) { + return true; + } + ETS_UART_INTR_DISABLE(); + if(persistent) ret = wifi_set_opmode(m); + else ret = wifi_set_opmode_current(m); + ETS_UART_INTR_ENABLE(); + return ret; + #elif defined(ESP32) + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.mode(m); // @todo persistent check persistant mode, was eventually added to esp lib, but have to add version checking probably + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} +bool WiFiManager::WiFi_Mode(WiFiMode_t m) { + return WiFi_Mode(m,false); +} + +// sta disconnect without persistent +bool WiFiManager::WiFi_Disconnect() { + #ifdef ESP8266 + if((WiFi.getMode() & WIFI_STA) != 0) { + bool ret; + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi station disconnect")); + #endif + ETS_UART_INTR_DISABLE(); // @todo possibly not needed + ret = wifi_station_disconnect(); + ETS_UART_INTR_ENABLE(); + return ret; + } + #elif defined(ESP32) + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi station disconnect")); + #endif + return WiFi.disconnect(); // not persistent atm + #endif + return false; +} + +// toggle STA without persistent +bool WiFiManager::WiFi_enableSTA(bool enable,bool persistent) { +#ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi_enableSTA"),(String) enable? "enable" : "disable"); + #endif + #ifdef ESP8266 + WiFiMode_t newMode; + WiFiMode_t currentMode = WiFi.getMode(); + bool isEnabled = (currentMode & WIFI_STA) != 0; + if(enable) newMode = (WiFiMode_t)(currentMode | WIFI_STA); + else newMode = (WiFiMode_t)(currentMode & (~WIFI_STA)); + + if((isEnabled != enable) || persistent) { + if(enable) { + #ifdef WM_DEBUG_LEVEL + if(persistent) DEBUG_WM(DEBUG_DEV,F("enableSTA PERSISTENT ON")); + #endif + return WiFi_Mode(newMode,persistent); + } + else { + return WiFi_Mode(newMode,persistent); + } + } else { + return true; + } + #elif defined(ESP32) + bool ret; + if(persistent && esp32persistent) WiFi.persistent(true); + ret = WiFi.enableSTA(enable); // @todo handle persistent when it is implemented in platform + if(persistent && esp32persistent) WiFi.persistent(false); + return ret; + #endif +} + +bool WiFiManager::WiFi_enableSTA(bool enable) { + return WiFi_enableSTA(enable,false); +} + +bool WiFiManager::WiFi_eraseConfig() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_DEV,F("WiFi_eraseConfig")); + #endif + + #ifdef ESP8266 + #ifndef WM_FIXERASECONFIG + return ESP.eraseConfig(); + #else + // erase config BUG replacement + // https://github.com/esp8266/Arduino/pull/3635 + const size_t cfgSize = 0x4000; + size_t cfgAddr = ESP.getFlashChipSize() - cfgSize; + + for (size_t offset = 0; offset < cfgSize; offset += SPI_FLASH_SEC_SIZE) { + if (!ESP.flashEraseSector((cfgAddr + offset) / SPI_FLASH_SEC_SIZE)) { + return false; + } + } + return true; + #endif + #elif defined(ESP32) + + bool ret; + WiFi.mode(WIFI_AP_STA); // cannot erase if not in STA mode ! + WiFi.persistent(true); + ret = WiFi.disconnect(true,true); // disconnect(bool wifioff, bool eraseap) + delay(500); + WiFi.persistent(false); + return ret; + #endif +} + +uint8_t WiFiManager::WiFi_softap_num_stations(){ + #ifdef ESP8266 + return wifi_softap_get_station_num(); + #elif defined(ESP32) + return WiFi.softAPgetStationNum(); + #endif +} + +bool WiFiManager::WiFi_hasAutoConnect(){ + return WiFi_SSID(true) != ""; +} + +String WiFiManager::WiFi_SSID(bool persistent) const{ + + #ifdef ESP8266 + struct station_config conf; + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[33]; //ssid can be up to 32chars, => plus null term + memcpy(tmp, conf.ssid, sizeof(conf.ssid)); + tmp[32] = 0; //nullterm in case of 32 char ssid + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + if(persistent){ + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.ssid)); + } + else { + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_ap_record_t info; + if(!esp_wifi_sta_get_ap_info(&info)) { + return String(reinterpret_cast(info.ssid)); + } + return String(); + } + #endif +} + +String WiFiManager::WiFi_psk(bool persistent) const { + #ifdef ESP8266 + struct station_config conf; + + if(persistent) wifi_station_get_config_default(&conf); + else wifi_station_get_config(&conf); + + char tmp[65]; //psk is 64 bytes hex => plus null term + memcpy(tmp, conf.password, sizeof(conf.password)); + tmp[64] = 0; //null term in case of 64 byte psk + return String(reinterpret_cast(tmp)); + + #elif defined(ESP32) + // only if wifi is init + if(WiFiGenericClass::getMode() == WIFI_MODE_NULL){ + return String(); + } + wifi_config_t conf; + esp_wifi_get_config(WIFI_IF_STA, &conf); + return String(reinterpret_cast(conf.sta.password)); + #endif +} + +#ifdef ESP32 + #ifdef WM_ARDUINOEVENTS + void WiFiManager::WiFiEvent(WiFiEvent_t event,arduino_event_info_t info){ + #else + void WiFiManager::WiFiEvent(WiFiEvent_t event,system_event_info_t info){ + #define wifi_sta_disconnected disconnected + #define ARDUINO_EVENT_WIFI_STA_DISCONNECTED SYSTEM_EVENT_STA_DISCONNECTED + #define ARDUINO_EVENT_WIFI_SCAN_DONE SYSTEM_EVENT_SCAN_DONE + #endif + if(!_hasBegun){ + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_VERBOSE,"[ERROR] WiFiEvent, not ready"); + #endif + // Serial.println(F("\n[EVENT] WiFiEvent logging (wm debug not available)")); + // Serial.print(F("[EVENT] ID: ")); + // Serial.println(event); + return; + } + #ifdef WM_DEBUG_LEVEL + // DEBUG_WM(DEBUG_VERBOSE,"[EVENT]",event); + #endif + if(event == ARDUINO_EVENT_WIFI_STA_DISCONNECTED){ + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: "),info.wifi_sta_disconnected.reason); + #endif + if(info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_EXPIRE || info.wifi_sta_disconnected.reason == WIFI_REASON_AUTH_FAIL){ + _lastconxresulttmp = 7; // hack in wrong password internally, sdk emit WIFI_REASON_AUTH_EXPIRE on some routers on auth_fail + } else _lastconxresulttmp = WiFi.status(); + #ifdef WM_DEBUG_LEVEL + if(info.wifi_sta_disconnected.reason == WIFI_REASON_NO_AP_FOUND) DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: NO_AP_FOUND")); + if(info.wifi_sta_disconnected.reason == WIFI_REASON_ASSOC_FAIL){ + if(_aggresiveReconn) _connectRetries+=4; + DEBUG_WM(DEBUG_VERBOSE,F("[EVENT] WIFI_REASON: AUTH FAIL")); + } + #endif + #ifdef esp32autoreconnect + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("[Event] SYSTEM_EVENT_STA_DISCONNECTED, reconnecting")); + #endif + WiFi.reconnect(); + #endif + } + else if(event == ARDUINO_EVENT_WIFI_SCAN_DONE && _asyncScan){ + uint16_t scans = WiFi.scanComplete(); + WiFi_scanComplete(scans); + } +} +#endif + +void WiFiManager::WiFi_autoReconnect(){ + #ifdef ESP8266 + WiFi.setAutoReconnect(_wifiAutoReconnect); + #elif defined(ESP32) + // if(_wifiAutoReconnect){ + // @todo move to seperate method, used for event listener now + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("ESP32 event handler enabled")); + #endif + using namespace std::placeholders; + if(wm_event_id == 0) wm_event_id = WiFi.onEvent(std::bind(&WiFiManager::WiFiEvent,this,_1,_2)); + // } + #endif +} + +// Called when /update is requested +void WiFiManager::handleUpdate() { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("<- Handle update")); + #endif + if (captivePortal()) return; // If captive portal redirect instead of displaying the page + String page = getHTTPHead(_title); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_t), _title); + str.replace(FPSTR(T_v), configPortalActive ? _apName : (getWiFiHostname() + " - " + WiFi.localIP().toString())); // use ip if ap is not active for heading + page += str; + + page += FPSTR(HTTP_UPDATE); + page += FPSTR(HTTP_END); + + HTTPSend(page); + +} + +// upload via /u POST +void WiFiManager::handleUpdating(){ + // @todo + // cannot upload files in captive portal, file select is not allowed, show message with link or hide + // cannot upload if softreset after upload, maybe check for hard reset at least for dev, ERROR[11]: Invalid bootstrapping state, reset ESP8266 before updating + // add upload status to webpage somehow + // abort upload if error detected ? + // [x] supress cp timeout on upload, so it doesnt keep uploading? + // add progress handler for debugging + // combine route handlers into one callback and use argument or post checking instead of mutiple functions maybe, if POST process else server upload page? + // [x] add upload checking, do we need too check file? + // convert output to debugger if not moving to example + + // if (captivePortal()) return; // If captive portal redirect instead of displaying the page + bool error = false; + unsigned long _configPortalTimeoutSAV = _configPortalTimeout; // store cp timeout + _configPortalTimeout = 0; // disable timeout + + // handler for the file upload, get's the sketch bytes, and writes + // them through the Update object + HTTPUpload& upload = server->upload(); + + // UPLOAD START + if (upload.status == UPLOAD_FILE_START) { + // if(_debug) Serial.setDebugOutput(true); + uint32_t maxSketchSpace; + + // Use new callback for before OTA update + if (_preotaupdatecallback != NULL) { + _preotaupdatecallback(); // @CALLBACK + } + #ifdef ESP8266 + WiFiUDP::stopAll(); + maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + #elif defined(ESP32) + // Think we do not need to stop WiFIUDP because we haven't started a listener + // maxSketchSpace = (ESP.getFlashChipSize() - 0x1000) & 0xFFFFF000; + // #define UPDATE_SIZE_UNKNOWN 0xFFFFFFFF // include update.h + maxSketchSpace = UPDATE_SIZE_UNKNOWN; + #endif + + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,"[OTA] Update file: ", upload.filename.c_str()); + #endif + + // Update.onProgress(THandlerFunction_Progress fn); + // Update.onProgress([](unsigned int progress, unsigned int total) { + // Serial.printf("Progress: %u%%\r", (progress / (total / 100))); + // }); + + if (!Update.begin(maxSketchSpace)) { // start with max available size + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] OTA Update ERROR"), Update.getError()); + #endif + error = true; + Update.end(); // Not sure the best way to abort, I think client will keep sending.. + } + } + // UPLOAD WRITE + else if (upload.status == UPLOAD_FILE_WRITE) { + // Serial.print("."); + if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) { + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_ERROR,F("[ERROR] OTA Update WRITE ERROR"), Update.getError()); + //Update.printError(Serial); // write failure + #endif + error = true; + } + } + // UPLOAD FILE END + else if (upload.status == UPLOAD_FILE_END) { + if (Update.end(true)) { // true to set the size to the current progress + #ifdef WM_DEBUG_LEVEL + DEBUG_WM(DEBUG_VERBOSE,F("\n\n[OTA] OTA FILE END bytes: "), upload.totalSize); + // Serial.printf("Updated: %u bytes\r\nRebooting...\r\n", upload.totalSize); + #endif + } + else { + // Update.printError(Serial); + error = true; + } + } + // UPLOAD ABORT + else if (upload.status == UPLOAD_FILE_ABORTED) { + Update.end(); + DEBUG_WM(F("[OTA] Update was aborted")); + error = true; + } + if(error) _configPortalTimeout = _configPortalTimeoutSAV; + delay(0); +} + +// upload and ota done, show status +void WiFiManager::handleUpdateDone() { + DEBUG_WM(DEBUG_VERBOSE, F("<- Handle update done")); + // if (captivePortal()) return; // If captive portal redirect instead of displaying the page + + String page = getHTTPHead(FPSTR(S_options)); // @token options + String str = FPSTR(HTTP_ROOT_MAIN); + str.replace(FPSTR(T_t),_title); + str.replace(FPSTR(T_v), configPortalActive ? _apName : WiFi.localIP().toString()); // use ip if ap is not active for heading + page += str; + + if (Update.hasError()) { + page += FPSTR(HTTP_UPDATE_FAIL); + #ifdef ESP32 + page += "OTA Error: " + (String)Update.errorString(); + #else + page += "OTA Error: " + (String)Update.getError(); + #endif + DEBUG_WM(F("[OTA] update failed")); + } + else { + page += FPSTR(HTTP_UPDATE_SUCCESS); + DEBUG_WM(F("[OTA] update ok")); + } + page += FPSTR(HTTP_END); + + HTTPSend(page); + + delay(1000); // send page + if (!Update.hasError()) { + ESP.restart(); + } +} + +#endif diff --git a/firmware/libraries/WiFiManager/WiFiManager.h b/firmware/libraries/WiFiManager/WiFiManager.h old mode 100755 new mode 100644 index 3da163e..08643a6 --- a/firmware/libraries/WiFiManager/WiFiManager.h +++ b/firmware/libraries/WiFiManager/WiFiManager.h @@ -1,69 +1,197 @@ -/************************************************************** - WiFiManager is a library for the ESP8266/Arduino platform - (https://github.com/esp8266/Arduino) to enable easy - configuration and reconfiguration of WiFi credentials using a Captive Portal - inspired by: - http://www.esp8266.com/viewtopic.php?f=29&t=2520 - https://github.com/chriscook8/esp-arduino-apboot - https://github.com/esp8266/Arduino/tree/master/libraries/DNSServer/examples/CaptivePortalAdvanced - Built by AlexT https://github.com/tzapu - Licensed under MIT license - **************************************************************/ +/** + * WiFiManager.h + * + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + #ifndef WiFiManager_h #define WiFiManager_h -#include -#include +#if defined(ESP8266) || defined(ESP32) + +#ifdef ESP8266 +#include +#endif + +#include + +// #define WM_MDNS // includes MDNS, also set MDNS with sethostname +// #define WM_FIXERASECONFIG // use erase flash fix +// #define WM_ERASE_NVS // esp32 erase(true) will erase NVS +// #define WM_RTC // esp32 info page will include reset reasons + +// #define WM_JSTEST // build flag for enabling js xhr tests +// #define WIFI_MANAGER_OVERRIDE_STRINGS // build flag for using own strings include + +#ifdef ARDUINO_ESP8266_RELEASE_2_3_0 +#warning "ARDUINO_ESP8266_RELEASE_2_3_0, some WM features disabled" +// @todo check failing on platform = espressif8266@1.7.3 +#define WM_NOASYNC // esp8266 no async scan wifi +#define WM_NOCOUNTRY // esp8266 no country +#define WM_NOAUTH // no httpauth +#define WM_NOSOFTAPSSID // no softapssid() @todo shim +#endif + +// #ifdef ARDUINO_ESP32S3_DEV +#ifdef ESP32 +#define WM_NOTEMP // disabled temp sensor, have to determine which chip we are on +#endif + +// #include "soc/efuse_reg.h" // include to add efuse chip rev to info, getChipRevision() is almost always the same though, so not sure why it matters. + +// #define esp32autoreconnect // implement esp32 autoreconnect event listener kludge, @DEPRECATED +// autoreconnect is WORKING https://github.com/espressif/arduino-esp32/issues/653#issuecomment-405604766 + +#define WM_WEBSERVERSHIM // use webserver shim lib + +#define WM_G(string_literal) (String(FPSTR(string_literal)).c_str()) + +#ifdef ESP8266 + + extern "C" { + #include "user_interface.h" + } + #include + #include + + #ifdef WM_MDNS + #include + #endif + + #define WIFI_getChipId() ESP.getChipId() + #define WM_WIFIOPEN ENC_TYPE_NONE + +#elif defined(ESP32) + + #include + #include + #include + + #define WIFI_getChipId() (uint32_t)ESP.getEfuseMac() + #define WM_WIFIOPEN WIFI_AUTH_OPEN + + #ifndef WEBSERVER_H + #ifdef WM_WEBSERVERSHIM + #include + #else + #include + // Forthcoming official ? probably never happening + // https://github.com/esp8266/ESPWebServer + #endif + #endif + + #ifdef WM_ERASE_NVS + #include + #include + #endif + + #ifdef WM_MDNS + #include + #endif + + #ifdef WM_RTC + #include + #endif + +#else +#endif + #include #include +#include "strings_en.h" -extern "C" { - #include "user_interface.h" -} +// prep string concat vars +#define WM_STRING2(x) #x +#define WM_STRING(x) WM_STRING2(x) -const char HTTP_HEAD[] PROGMEM = "{v}"; -const char HTTP_STYLE[] PROGMEM = ""; -const char HTTP_SCRIPT[] PROGMEM = ""; -const char HTTP_HEAD_END[] PROGMEM = "
"; -const char HTTP_PORTAL_OPTIONS[] PROGMEM = "



"; -const char HTTP_ITEM[] PROGMEM = "
{v} {r}%
"; -const char HTTP_FORM_START[] PROGMEM = "


"; -const char HTTP_FORM_PARAM[] PROGMEM = "
"; -const char HTTP_FORM_END[] PROGMEM = "
"; -const char HTTP_SCAN_LINK[] PROGMEM = "
"; -const char HTTP_SAVED[] PROGMEM = "
Credentials Saved
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; -const char HTTP_END[] PROGMEM = "
"; + +// #include +#ifdef ESP_IDF_VERSION + // #pragma message "ESP_IDF_VERSION_MAJOR = " WM_STRING(ESP_IDF_VERSION_MAJOR) + // #pragma message "ESP_IDF_VERSION_MINOR = " WM_STRING(ESP_IDF_VERSION_MINOR) + // #pragma message "ESP_IDF_VERSION_PATCH = " WM_STRING(ESP_IDF_VERSION_PATCH) + #define VER_IDF_STR WM_STRING(ESP_IDF_VERSION_MAJOR) "." WM_STRING(ESP_IDF_VERSION_MINOR) "." WM_STRING(ESP_IDF_VERSION_PATCH) +#else + #define VER_IDF_STR "Unknown" +#endif + +#ifdef Arduino_h + #ifdef ESP32 + #include "esp_arduino_version.h" + #endif + // esp_get_idf_version + #ifdef ESP_ARDUINO_VERSION + // #pragma message "ESP_ARDUINO_VERSION_MAJOR = " WM_STRING(ESP_ARDUINO_VERSION_MAJOR) + // #pragma message "ESP_ARDUINO_VERSION_MINOR = " WM_STRING(ESP_ARDUINO_VERSION_MINOR) + // #pragma message "ESP_ARDUINO_VERSION_PATCH = " WM_STRING(ESP_ARDUINO_VERSION_PATCH) + #define VER_ARDUINO_STR WM_STRING(ESP_ARDUINO_VERSION_MAJOR) "." WM_STRING(ESP_ARDUINO_VERSION_MINOR) "." WM_STRING(ESP_ARDUINO_VERSION_PATCH) + #else + #include + // #pragma message "ESP_ARDUINO_VERSION_GIT = " WM_STRING(ARDUINO_ESP32_GIT_VER)// 0x46d5afb1 + // #pragma message "ESP_ARDUINO_VERSION_DESC = " WM_STRING(ARDUINO_ESP32_GIT_DESC) // 1.0.6 + // #pragma message "ESP_ARDUINO_VERSION_REL = " WM_STRING(ARDUINO_ESP32_RELEASE) //"1_0_6" + #define VER_ARDUINO_STR WM_STRING(ESP_ARDUINO_VERSION_MAJOR) "." WM_STRING(ESP_ARDUINO_VERSION_MINOR) "." WM_STRING(ESP_ARDUINO_VERSION_PATCH) + #endif +#else +#define VER_ARDUINO_STR "Unknown" +#endif + + +// #pragma message "VER_IDF_STR = " WM_STRING(VER_IDF_STR) +// #pragma message "VER_ARDUINO_STR = " WM_STRING(VER_ARDUINO_STR) #ifndef WIFI_MANAGER_MAX_PARAMS -#define WIFI_MANAGER_MAX_PARAMS 10 + #define WIFI_MANAGER_MAX_PARAMS 5 // params will autoincrement and realloc by this amount when max is reached #endif +#define WFM_LABEL_BEFORE 1 +#define WFM_LABEL_AFTER 2 +#define WFM_NO_LABEL 0 +#define WFM_LABEL_DEFAULT 1 + class WiFiManagerParameter { public: /** Create custom parameters that can be added to the WiFiManager setup web page @id is used for HTTP queries and must not contain spaces nor other special characters */ + WiFiManagerParameter(); WiFiManagerParameter(const char *custom); - WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length); - WiFiManagerParameter(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); + WiFiManagerParameter(const char *id, const char *label); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom); + WiFiManagerParameter(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); ~WiFiManagerParameter(); + // WiFiManagerParameter& operator=(const WiFiManagerParameter& rhs); + + const char *getID() const; + const char *getValue() const; + const char *getLabel() const; + const char *getPlaceholder() const; // @deprecated, use getLabel + int getValueLength() const; + int getLabelPlacement() const; + virtual const char *getCustomHTML() const; + void setValue(const char *defaultValue, int length); + + protected: + void init(const char *id, const char *label, const char *defaultValue, int length, const char *custom, int labelPlacement); - const char *getID(); - const char *getValue(); - const char *getPlaceholder(); - int getValueLength(); - const char *getCustomHTML(); private: + WiFiManagerParameter& operator=(const WiFiManagerParameter&); const char *_id; - const char *_placeholder; + const char *_label; char *_value; int _length; + int _labelPlacement; + protected: const char *_customHTML; - - void init(const char *id, const char *placeholder, const char *defaultValue, int length, const char *custom); - friend class WiFiManager; }; @@ -71,133 +199,599 @@ class WiFiManagerParameter { class WiFiManager { public: + WiFiManager(Print& consolePort); WiFiManager(); ~WiFiManager(); + void WiFiManagerInit(); + // auto connect to saved wifi, or custom, and start config portal on failures boolean autoConnect(); boolean autoConnect(char const *apName, char const *apPassword = NULL); - //if you want to always start the config portal, without trying to connect first - boolean startConfigPortal(); + //manually start the config portal, autoconnect does this automatically on connect failure + boolean startConfigPortal(); // auto generates apname boolean startConfigPortal(char const *apName, char const *apPassword = NULL); + //manually stop the config portal if started manually, stop immediatly if non blocking, flag abort if blocking + bool stopConfigPortal(); + + //manually start the web portal, autoconnect does this automatically on connect failure + void startWebPortal(); + + //manually stop the web portal if started manually + void stopWebPortal(); + + // Run webserver processing, if setConfigPortalBlocking(false) + boolean process(); + // get the AP name of the config portal, so it can be used in the callback String getConfigPortalSSID(); + int getRSSIasQuality(int RSSI); + // erase wifi credentials void resetSettings(); - //sets timeout before webserver loop ends and exits even if there has been no setup. + // reboot esp + void reboot(); + + // disconnect wifi, without persistent saving or erasing + bool disconnect(); + + // erase esp + bool erase(); + bool erase(bool opt); + + //adds a custom parameter, returns false on failure + bool addParameter(WiFiManagerParameter *p); + + //returns the list of Parameters + WiFiManagerParameter** getParameters(); + + // returns the Parameters Count + int getParametersCount(); + + // SET CALLBACKS + + //called after AP mode and config portal has started + void setAPCallback( std::function func ); + + //called after webserver has started + void setWebServerCallback( std::function func ); + + //called when settings reset have been triggered + void setConfigResetCallback( std::function func ); + + //called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) + void setSaveConfigCallback( std::function func ); + + //called when saving params-in-wifi or params before anything else happens (eg wifi) + void setPreSaveConfigCallback( std::function func ); + + //called when saving params before anything else happens + void setPreSaveParamsCallback( std::function func ); + + //called when saving either params-in-wifi or params page + void setSaveParamsCallback( std::function func ); + + //called just before doing OTA update + void setPreOtaUpdateCallback( std::function func ); + + //called when config portal is timeout + void setConfigPortalTimeoutCallback( std::function func ); + + //sets timeout before AP,webserver loop ends and exits even if there has been no setup. //useful for devices that failed to connect at some point and got stuck in a webserver loop - //in seconds setConfigPortalTimeout is a new name for setTimeout + //in seconds setConfigPortalTimeout is a new name for setTimeout, ! not used if setConfigPortalBlocking void setConfigPortalTimeout(unsigned long seconds); - void setTimeout(unsigned long seconds); + void setTimeout(unsigned long seconds); // @deprecated, alias //sets timeout for which to attempt connecting, useful if you get a lot of failed connects void setConnectTimeout(unsigned long seconds); - + // sets number of retries for autoconnect, force retry after wait failure exit + void setConnectRetries(uint8_t numRetries); // default 1 + + //sets timeout for which to attempt connecting on saves, useful if there are bugs in esp waitforconnectloop + void setSaveConnectTimeout(unsigned long seconds); + + // lets you disable automatically connecting after save from webportal + void setSaveConnect(bool connect = true); + + // toggle debug output void setDebugOutput(boolean debug); - //defaults to not showing anything under 8% signal quality if called + void setDebugOutput(boolean debug, String prefix); // log line prefix, default "*wm:" + + //set min quality percentage to include in scan, defaults to 8% if not specified void setMinimumSignalQuality(int quality = 8); + //sets a custom ip /gateway /subnet configuration void setAPStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); + //sets config for a static IP void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn); - //called when AP mode and config portal is started - void setAPCallback( void (*func)(WiFiManager*) ); - //called when settings have been changed and connection was successful - void setSaveConfigCallback( void (*func)(void) ); - //adds a custom parameter, returns false on failure - bool addParameter(WiFiManagerParameter *p); + + //sets config for a static IP with DNS + void setSTAStaticIPConfig(IPAddress ip, IPAddress gw, IPAddress sn, IPAddress dns); + //if this is set, it will exit after config, even if connection is unsuccessful. void setBreakAfterConfig(boolean shouldBreak); - //if this is set, try WPS setup when starting (this will delay config portal for up to 2 mins) - //TODO + + // if this is set, portal will be blocking and wait until save or exit, + // is false user must manually `process()` to handle config portal, + // setConfigPortalTimeout is ignored in this mode, user is responsible for closing configportal + void setConfigPortalBlocking(boolean shouldBlock); + + //add custom html at inside for all pages + void setCustomHeadElement(const char* html); + //if this is set, customise style - void setCustomHeadElement(const char* element); + void setCustomMenuHTML(const char* html); + //if this is true, remove duplicated Access Points - defaut true void setRemoveDuplicateAPs(boolean removeDuplicates); + + //setter for ESP wifi.persistent so we can remember it and restore user preference, as WIFi._persistent is protected + void setRestorePersistent(boolean persistent); + + //if true, always show static net inputs, IP, subnet, gateway, else only show if set via setSTAStaticIPConfig + void setShowStaticFields(boolean alwaysShow); + + //if true, always show static dns, esle only show if set via setSTAStaticIPConfig + void setShowDnsFields(boolean alwaysShow); + + // toggle showing the saved wifi password in wifi form, could be a security issue. + void setShowPassword(boolean show); + + //if false, disable captive portal redirection + void setCaptivePortalEnable(boolean enabled); + + //if false, timeout captive portal even if a STA client connected to softAP (false), suggest disabling if captiveportal is open + void setAPClientCheck(boolean enabled); + + //if true, reset timeout when webclient connects (true), suggest disabling if captiveportal is open + void setWebPortalClientCheck(boolean enabled); + + // if true, enable autoreconnecting + void setWiFiAutoReconnect(boolean enabled); + + // if true, wifiscan will show percentage instead of quality icons, until we have better templating + void setScanDispPerc(boolean enabled); + + // if true (default) then start the config portal from autoConnect if connection failed + void setEnableConfigPortal(boolean enable); + + // if true (default) then stop the config portal from autoConnect when wifi is saved + void setDisableConfigPortal(boolean enable); + + // set a custom hostname, sets sta and ap dhcp client id for esp32, and sta for esp8266 + bool setHostname(const char * hostname); + bool setHostname(String hostname); + + // show erase wifi onfig button on info page, true + void setShowInfoErase(boolean enabled); + + // show OTA upload button on info page + void setShowInfoUpdate(boolean enabled); + + // set ap channel + void setWiFiAPChannel(int32_t channel); + + // set ap hidden + void setWiFiAPHidden(bool hidden); // default false + + // clean connect, always disconnect before connecting + void setCleanConnect(bool enable); // default false + + // set custom menu items and order, vector or arr + // see _menutokens for ids + void setMenu(std::vector& menu); + void setMenu(const char* menu[], uint8_t size); + + // set the webapp title, default WiFiManager + void setTitle(String title); + + // add params to its own menu page and remove from wifi, NOT TO BE COMBINED WITH setMenu! + void setParamsPage(bool enable); + + // get last connection result, includes autoconnect and wifisave + uint8_t getLastConxResult(); + + // get a status as string + String getWLStatusString(uint8_t status); + String getWLStatusString(); + + // get wifi mode as string + String getModeString(uint8_t mode); + + // check if the module has a saved ap to connect to + bool getWiFiIsSaved(); + + // helper to get saved password, if persistent get stored, else get current if connected + String getWiFiPass(bool persistent = true); + + // helper to get saved ssid, if persistent get stored, else get current if connected + String getWiFiSSID(bool persistent = true); + + // debug output the softap config + void debugSoftAPConfig(); + + // debug output platform info and versioning + void debugPlatformInfo(); + + // helper for html + String htmlEntities(String str, bool whitespace = false); + + // set the country code for wifi settings, CN + void setCountry(String cc); + + // set body class (invert), may be used for hacking in alt classes + void setClass(String str); + + // set dark mode via invert class + void setDarkMode(bool enable); + + // get default ap esp uses , esp_chipid etc + String getDefaultAPName(); + + // set port of webserver, 80 + void setHttpPort(uint16_t port); + + // check if config portal is active (true) + bool getConfigPortalActive(); + + // check if web portal is active (true) + bool getWebPortalActive(); + + // to preload autoconnect for test fixtures or other uses that skip esp sta config + bool preloadWiFi(String ssid, String pass); + + // get hostname helper + String getWiFiHostname(); + + + std::unique_ptr dnsServer; + + #if defined(ESP32) && defined(WM_WEBSERVERSHIM) + using WM_WebServer = WebServer; + #else + using WM_WebServer = ESP8266WebServer; + #endif + + std::unique_ptr server; private: - std::unique_ptr dnsServer; - std::unique_ptr server; - - //const int WM_DONE = 0; - //const int WM_WAIT = 10; - - //const String HTTP_HEAD = "{v}"; - - void setupConfigPortal(); - void startWPS(); - - const char* _apName = "no-net"; - const char* _apPassword = NULL; - String _ssid = ""; - String _pass = ""; - unsigned long _configPortalTimeout = 0; - unsigned long _connectTimeout = 0; - unsigned long _configPortalStart = 0; + // vars + std::vector _menuIds; + std::vector _menuIdsParams = {"wifi","param","info","exit"}; + std::vector _menuIdsUpdate = {"wifi","param","info","update","exit"}; + std::vector _menuIdsDefault = {"wifi","info","exit","sep","update"}; + // ip configs @todo struct ? IPAddress _ap_static_ip; IPAddress _ap_static_gw; IPAddress _ap_static_sn; IPAddress _sta_static_ip; IPAddress _sta_static_gw; IPAddress _sta_static_sn; + IPAddress _sta_static_dns; - int _paramsCount = 0; - int _minimumQuality = -1; - boolean _removeDuplicateAPs = true; - boolean _shouldBreakAfterConfig = false; - boolean _tryWPS = false; + unsigned long _configPortalStart = 0; // ms config portal start time (updated for timeouts) + unsigned long _webPortalAccessed = 0; // ms last web access time + uint8_t _lastconxresult = WL_IDLE_STATUS; // store last result when doing connect operations + int _numNetworks = 0; // init index for numnetworks wifiscans + unsigned long _lastscan = 0; // ms for timing wifi scans + unsigned long _startscan = 0; // ms for timing wifi scans + unsigned long _startconn = 0; // ms for timing wifi connects - const char* _customHeadElement = ""; + // defaults + const byte DNS_PORT = 53; + String _apName = "no-net"; + String _apPassword = ""; + String _ssid = ""; // var temp ssid + String _pass = ""; // var temp psk + String _defaultssid = ""; // preload ssid + String _defaultpass = ""; // preload pass - //String getEEPROMString(int start, int len); - //void setEEPROMString(int start, int len, String string); + // options flags + unsigned long _configPortalTimeout = 0; // ms close config portal loop if set (depending on _cp/webClientCheck options) + unsigned long _connectTimeout = 0; // ms stop trying to connect to ap if set + unsigned long _saveTimeout = 0; // ms stop trying to connect to ap on saves, in case bugs in esp waitforconnectresult + + WiFiMode_t _usermode = WIFI_STA; // Default user mode + String _wifissidprefix = FPSTR(S_ssidpre); // auto apname prefix prefix+chipid + int _cpclosedelay = 2000; // delay before wifisave, prevents captive portal from closing to fast. + bool _cleanConnect = false; // disconnect before connect in connectwifi, increases stability on connects + bool _connectonsave = true; // connect to wifi when saving creds + bool _disableSTA = false; // disable sta when starting ap, always + bool _disableSTAConn = true; // disable sta when starting ap, if sta is not connected ( stability ) + bool _channelSync = false; // use same wifi sta channel when starting ap + int32_t _apChannel = 0; // default channel to use for ap, 0 for auto + bool _apHidden = false; // store softap hidden value + uint16_t _httpPort = 80; // port for webserver + // uint8_t _retryCount = 0; // counter for retries, probably not needed if synchronous + uint8_t _connectRetries = 1; // number of sta connect retries, force reconnect, wait loop (connectimeout) does not always work and first disconnect bails + bool _aggresiveReconn = true; // use an agrressive reconnect strategy, WILL delay conxs + // on some conn failure modes will add delays and many retries to work around esp and ap bugs, ie, anti de-auth protections + // https://github.com/tzapu/WiFiManager/issues/1067 + bool _allowExit = true; // allow exit in nonblocking, else user exit/abort calls will be ignored including cptimeout + + #ifdef ESP32 + wifi_event_id_t wm_event_id = 0; + static uint8_t _lastconxresulttmp; // tmp var for esp32 callback + #endif + + #ifndef WL_STATION_WRONG_PASSWORD + uint8_t WL_STATION_WRONG_PASSWORD = 7; // @kludge define a WL status for wrong password + #endif + + // parameter options + int _minimumQuality = -1; // filter wifiscan ap by this rssi + int _staShowStaticFields = 0; // ternary 1=always show static ip fields, 0=only if set, -1=never(cannot change ips via web!) + int _staShowDns = 0; // ternary 1=always show dns, 0=only if set, -1=never(cannot change dns via web!) + boolean _removeDuplicateAPs = true; // remove dup aps from wifiscan + boolean _showPassword = false; // show or hide saved password on wifi form, might be a security issue! + boolean _shouldBreakAfterConfig = false; // stop configportal on save failure + boolean _configPortalIsBlocking = true; // configportal enters blocking loop + boolean _enableCaptivePortal = true; // enable captive portal redirection + boolean _userpersistent = true; // users preffered persistence to restore + boolean _wifiAutoReconnect = true; // there is no platform getter for this, we must assume its true and make it so + boolean _apClientCheck = false; // keep cp alive if ap have station + boolean _webClientCheck = true; // keep cp alive if web have client + boolean _scanDispOptions = false; // show percentage in scans not icons + boolean _paramsInWifi = true; // show custom parameters on wifi page + boolean _showInfoErase = true; // info page erase button + boolean _showInfoUpdate = true; // info page update button + boolean _showBack = false; // show back button + boolean _enableConfigPortal = true; // FOR autoconnect - start config portal if autoconnect failed + boolean _disableConfigPortal = true; // FOR autoconnect - stop config portal if cp wifi save + String _hostname = ""; // hostname for esp8266 for dhcp, and or MDNS + + const char* _customHeadElement = ""; // store custom head element html from user isnide + const char* _customMenuHTML = ""; // store custom head element html from user inside <> + String _bodyClass = ""; // class to add to body + String _title = FPSTR(S_brand); // app title - default WiFiManager + + // internal options + + // wifiscan notes + // currently disabled due to issues with caching, sometimes first scan is empty esp32 wifi not init yet race, or portals hit server nonstop flood + // The following are background wifi scanning optimizations + // experimental to make scans faster, preload scans after starting cp, and visiting home page, so when you click wifi its already has your list + // ideally we would add async and xhr here but I am holding off on js requirements atm + // might be slightly buggy since captive portals hammer the home page, @todo workaround this somehow. + // cache time helps throttle this + // async enables asyncronous scans, so they do not block anything + // the refresh button bypasses cache + // no aps found is problematic as scans are always going to want to run, leading to page load delays + // + // These settings really only make sense with _preloadwifiscan true + // but not limited to, we could run continuous background scans on various page hits, or xhr hits + // which would be better coupled with asyncscan + // atm preload is only done on root hit and startcp + boolean _preloadwifiscan = true; // preload wifiscan if true + unsigned int _scancachetime = 30000; // ms cache time for preload scans + boolean _asyncScan = true; // perform wifi network scan async + + boolean _autoforcerescan = false; // automatically force rescan if scan networks is 0, ignoring cache + + boolean _disableIpFields = false; // modify function of setShow_X_Fields(false), forces ip fields off instead of default show if set, eg. _staShowStaticFields=-1 + + String _wificountry = ""; // country code, @todo define in strings lang + + // wrapper functions for handling setting and unsetting persistent for now. + bool esp32persistent = false; + bool _hasBegun = false; // flag wm loaded,unloaded + void _begin(); + void _end(); + + void setupConfigPortal(); + bool shutdownConfigPortal(); + bool setupHostname(bool restart); + +#ifdef NO_EXTRA_4K_HEAP + boolean _tryWPS = false; // try WPS on save failure, unsupported + void startWPS(); +#endif + + bool startAP(); + void setupDNSD(); + void setupHTTPServer(); + + uint8_t connectWifi(String ssid, String pass, bool connect = true); + bool setSTAConfig(); + bool wifiConnectDefault(); + bool wifiConnectNew(String ssid, String pass,bool connect = true); - int status = WL_IDLE_STATUS; - int connectWifi(String ssid, String pass); uint8_t waitForConnectResult(); + uint8_t waitForConnectResult(uint32_t timeout); + void updateConxResult(uint8_t status); + // webserver handlers + void HTTPSend(String content); void handleRoot(); void handleWifi(boolean scan); void handleWifiSave(); void handleInfo(); void handleReset(); void handleNotFound(); - void handle204(); + void handleExit(); + void handleClose(); + // void handleErase(); + void handleErase(boolean opt); + void handleParam(); + void handleWiFiStatus(); + void handleRequest(); + void handleParamSave(); + void doParamSave(); + boolean captivePortal(); boolean configPortalHasTimeout(); + uint8_t processConfigPortal(); + void stopCaptivePortal(); + // OTA Update handler + void handleUpdate(); + void handleUpdating(); + void handleUpdateDone(); - // DNS server - const byte DNS_PORT = 53; + // wifi platform abstractions + bool WiFi_Mode(WiFiMode_t m); + bool WiFi_Mode(WiFiMode_t m,bool persistent); + bool WiFi_Disconnect(); + bool WiFi_enableSTA(bool enable); + bool WiFi_enableSTA(bool enable,bool persistent); + bool WiFi_eraseConfig(); + uint8_t WiFi_softap_num_stations(); + bool WiFi_hasAutoConnect(); + void WiFi_autoReconnect(); + String WiFi_SSID(bool persistent = true) const; + String WiFi_psk(bool persistent = true) const; + bool WiFi_scanNetworks(); + bool WiFi_scanNetworks(bool force,bool async); + bool WiFi_scanNetworks(unsigned int cachetime,bool async); + bool WiFi_scanNetworks(unsigned int cachetime); + void WiFi_scanComplete(int networksFound); + bool WiFiSetCountry(); + + #ifdef ESP32 + + // check for arduino or system event system, handle esp32 arduino v2 and IDF + #if defined(ESP_ARDUINO_VERSION) && defined(ESP_ARDUINO_VERSION_VAL) + + #define WM_ARDUINOVERCHECK ESP_ARDUINO_VERSION >= ESP_ARDUINO_VERSION_VAL(2, 0, 0) + #define WM_ARDUINOVERCHECK_204 ESP_ARDUINO_VERSION <= ESP_ARDUINO_VERSION_VAL(2, 0, 5) + + #ifdef WM_ARDUINOVERCHECK + #define WM_ARDUINOEVENTS + #else + #define WM_NOSOFTAPSSID + #define WM_NOCOUNTRY + #endif + + #ifdef WM_ARDUINOVERCHECK_204 + #define WM_DISCONWORKAROUND + #endif + + #else + #define WM_NOCOUNTRY + #endif + + #ifdef WM_NOCOUNTRY + #warning "ESP32 set country unavailable" + #endif + + + #ifdef WM_ARDUINOEVENTS + void WiFiEvent(WiFiEvent_t event, arduino_event_info_t info); + #else + void WiFiEvent(WiFiEvent_t event, system_event_info_t info); + #endif + #endif + + // output helpers + String getParamOut(); + String getIpForm(String id, String title, String value); + String getScanItemOut(); + String getStaticOut(); + String getHTTPHead(String title); + String getMenuOut(); //helpers - int getRSSIasQuality(int RSSI); boolean isIp(String str); String toStringIp(IPAddress ip); + boolean validApPassword(); + String encryptionTypeStr(uint8_t authmode); + void reportStatus(String &page); + String getInfoData(String id); - boolean connect; - boolean _debug = true; + // flags + boolean connect = false; + boolean abort = false; + boolean reset = false; + boolean configPortalActive = false; + boolean webPortalActive = false; + boolean portalTimeoutResult = false; + boolean portalAbortResult = false; + boolean storeSTAmode = true; // option store persistent STA mode in connectwifi + int timer = 0; // timer for debug throttle for numclients, and portal timeout messages + + // WiFiManagerParameter + int _paramsCount = 0; + int _max_params; + WiFiManagerParameter** _params = NULL; - void (*_apcallback)(WiFiManager*) = NULL; - void (*_savecallback)(void) = NULL; + // debugging + typedef enum { + DEBUG_ERROR = 0, + DEBUG_NOTIFY = 1, // default stable + DEBUG_VERBOSE = 2, + DEBUG_DEV = 3, // default dev + DEBUG_MAX = 4 + } wm_debuglevel_t; - int _max_params; - WiFiManagerParameter** _params; + boolean _debug = true; + String _debugPrefix = FPSTR(S_debugPrefix); + + wm_debuglevel_t debugLvlShow = DEBUG_VERBOSE; // at which level start showing [n] level tags + + // build debuglevel support + // @todo use DEBUG_ESP_x? + + // Set default debug level + #ifndef WM_DEBUG_LEVEL + #define WM_DEBUG_LEVEL DEBUG_VERBOSE // development default, not release + #endif + + // override debug level OFF + #ifdef WM_NODEBUG + #undef WM_DEBUG_LEVEL + #endif + + #ifdef WM_DEBUG_LEVEL + uint8_t _debugLevel = (uint8_t)WM_DEBUG_LEVEL; + #else + uint8_t _debugLevel = DEBUG_VERBOSE; // default debug level + #endif + + // @todo use DEBUG_ESP_PORT ? + #ifdef WM_DEBUG_PORT + Print& _debugPort = WM_DEBUG_PORT; + #else + Print& _debugPort = Serial; // debug output stream ref + #endif template - void DEBUG_WM(Generic text); + void DEBUG_WM(Generic text); + + template + void DEBUG_WM(wm_debuglevel_t level,Generic text); + template + void DEBUG_WM(Generic text,Genericb textb); + template + void DEBUG_WM(wm_debuglevel_t level, Generic text,Genericb textb); + + // callbacks + // @todo use cb list (vector) maybe event ids, allow no return value + std::function _apcallback; + std::function _webservercallback; + std::function _savewificallback; + std::function _presavewificallback; + std::function _presaveparamscallback; + std::function _saveparamscallback; + std::function _resetcallback; + std::function _preotaupdatecallback; + std::function _configportaltimeoutcallback; template auto optionalIPFromString(T *obj, const char *s) -> decltype( obj->fromString(s) ) { return obj->fromString(s); } auto optionalIPFromString(...) -> bool { - DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."); + // DEBUG_WM("NO fromString METHOD ON IPAddress, you need ESP8266 core 2.1.0 or newer for Custom IP configuration to work."); return false; } + }; #endif + +#endif diff --git a/firmware/libraries/WiFiManager/examples/Advanced/Advanced.ino b/firmware/libraries/WiFiManager/examples/Advanced/Advanced.ino new file mode 100644 index 0000000..3834e56 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Advanced/Advanced.ino @@ -0,0 +1,141 @@ +/** + * WiFiManager advanced demo, contains advanced configurartion options + * Implements TRIGGEN_PIN button press, press for ondemand configportal, hold for 3 seconds for reset settings. + */ +#include // https://github.com/tzapu/WiFiManager + +#define TRIGGER_PIN 0 + +// wifimanager can run in a blocking mode or a non blocking mode +// Be sure to know how to process loops with no delay() if using non blocking +bool wm_nonblocking = false; // change to true to use non blocking + +WiFiManager wm; // global wm instance +WiFiManagerParameter custom_field; // global param ( for non blocking w params ) + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(3000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT); + + // wm.resetSettings(); // wipe settings + + if(wm_nonblocking) wm.setConfigPortalBlocking(false); + + // add a custom input field + int customFieldLength = 40; + + + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\""); + + // test custom html input type(checkbox) + // new (&custom_field) WiFiManagerParameter("customfieldid", "Custom Field Label", "Custom Field Value", customFieldLength,"placeholder=\"Custom Field Placeholder\" type=\"checkbox\""); // custom html type + + // test custom html(radio) + const char* custom_radio_str = "
One
Two
Three"; + new (&custom_field) WiFiManagerParameter(custom_radio_str); // custom html input + + wm.addParameter(&custom_field); + wm.setSaveParamsCallback(saveParamCallback); + + // custom menu via array or vector + // + // menu tokens, "wifi","wifinoscan","info","param","close","sep","erase","restart","exit" (sep is seperator) (if param is in menu, params will not show up in wifi page!) + // const char* menu[] = {"wifi","info","param","sep","restart","exit"}; + // wm.setMenu(menu,6); + std::vector menu = {"wifi","info","param","sep","restart","exit"}; + wm.setMenu(menu); + + // set dark theme + wm.setClass("invert"); + + + //set static ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); // set static ip,gw,sn + // wm.setShowStaticFields(true); // force show static ip fields + // wm.setShowDnsFields(true); // force show dns field always + + // wm.setConnectTimeout(20); // how long to try to connect for before continuing + wm.setConfigPortalTimeout(30); // auto close configportal after n seconds + // wm.setCaptivePortalEnable(false); // disable captive portal redirection + // wm.setAPClientCheck(true); // avoid timeout if client connected to softap + + // wifi scan settings + // wm.setRemoveDuplicateAPs(false); // do not remove duplicate ap names (true) + // wm.setMinimumSignalQuality(20); // set min RSSI (percentage) to show in scans, null = 8% + // wm.setShowInfoErase(false); // do not show erase button on info page + // wm.setScanDispPerc(true); // show RSSI as percentage not graph icons + + // wm.setBreakAfterConfig(true); // always exit configportal even if wifi save fails + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect or hit timeout"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } +} + +void checkButton(){ + // check for button press + if ( digitalRead(TRIGGER_PIN) == LOW ) { + // poor mans debounce/press-hold, code not ideal for production + delay(50); + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Button Pressed"); + // still holding button for 3000 ms, reset settings, code not ideaa for production + delay(3000); // reset delay hold + if( digitalRead(TRIGGER_PIN) == LOW ){ + Serial.println("Button Held"); + Serial.println("Erasing Config, restarting"); + wm.resetSettings(); + ESP.restart(); + } + + // start portal w delay + Serial.println("Starting config portal"); + wm.setConfigPortalTimeout(120); + + if (!wm.startConfigPortal("OnDemandAP","password")) { + Serial.println("failed to connect or hit timeout"); + delay(3000); + // ESP.restart(); + } else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + } + } +} + + +String getParam(String name){ + //read parameter from server, for customhmtl input + String value; + if(wm.server->hasArg(name)) { + value = wm.server->arg(name); + } + return value; +} + +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); + Serial.println("PARAM customfieldid = " + getParam("customfieldid")); +} + +void loop() { + if(wm_nonblocking) wm.process(); // avoid delays() in loop when non-blocking and other long running code + checkButton(); + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/AutoConnect/AutoConnect.ino b/firmware/libraries/WiFiManager/examples/AutoConnect/AutoConnect.ino deleted file mode 100755 index 0c44909..0000000 --- a/firmware/libraries/WiFiManager/examples/AutoConnect/AutoConnect.ino +++ /dev/null @@ -1,38 +0,0 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - //reset saved settings - //wifiManager.resetSettings(); - - //set custom ip for portal - //wifiManager.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - - //fetches ssid and pass from eeprom and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - wifiManager.autoConnect("AutoConnectAP"); - //or use this for auto generated name ESP + ChipID - //wifiManager.autoConnect(); - - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/firmware/libraries/WiFiManager/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino b/firmware/libraries/WiFiManager/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino deleted file mode 100755 index 77b264b..0000000 --- a/firmware/libraries/WiFiManager/examples/AutoConnectWithFeedbackLED/AutoConnectWithFeedbackLED.ino +++ /dev/null @@ -1,68 +0,0 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - -//for LED status -#include -Ticker ticker; - -void tick() -{ - //toggle state - int state = digitalRead(BUILTIN_LED); // get the current state of GPIO1 pin - digitalWrite(BUILTIN_LED, !state); // set pin to the opposite state -} - -//gets called when WiFiManager enters configuration mode -void configModeCallback (WiFiManager *myWiFiManager) { - Serial.println("Entered config mode"); - Serial.println(WiFi.softAPIP()); - //if you used auto generated SSID, print it - Serial.println(myWiFiManager->getConfigPortalSSID()); - //entered config mode, make led toggle faster - ticker.attach(0.2, tick); -} - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - - //set led pin as output - pinMode(BUILTIN_LED, OUTPUT); - // start ticker with 0.5 because we start in AP mode and try to connect - ticker.attach(0.6, tick); - - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - //reset settings - for testing - //wifiManager.resetSettings(); - - //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode - wifiManager.setAPCallback(configModeCallback); - - //fetches ssid and pass and tries to connect - //if it does not connect it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - if (!wifiManager.autoConnect()) { - Serial.println("failed to connect and hit timeout"); - //reset and try again, or maybe put it to deep sleep - ESP.reset(); - delay(1000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - ticker.detach(); - //keep LED on - digitalWrite(BUILTIN_LED, LOW); -} - -void loop() { - // put your main code here, to run repeatedly: - -} diff --git a/firmware/libraries/WiFiManager/examples/Basic/Basic.ino b/firmware/libraries/WiFiManager/examples/Basic/Basic.ino new file mode 100644 index 0000000..bf1e263 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Basic/Basic.ino @@ -0,0 +1,41 @@ +#include // https://github.com/tzapu/WiFiManager + + +void setup() { + // WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // it is a good practice to make sure your code sets wifi mode how you want it. + + // put your setup code here, to run once: + Serial.begin(115200); + + //WiFiManager, Local intialization. Once its business is done, there is no need to keep it around + WiFiManager wm; + + // reset settings - wipe stored credentials for testing + // these are stored by the esp library + // wm.resetSettings(); + + // Automatically connect using saved credentials, + // if connection fails, it starts an access point with the specified name ( "AutoConnectAP"), + // if empty will auto generate SSID, if password is blank it will be anonymous AP (wm.autoConnect()) + // then goes into a blocking loop awaiting configuration and will return success result + + bool res; + // res = wm.autoConnect(); // auto generated AP name from chipid + // res = wm.autoConnect("AutoConnectAP"); // anonymous ap + res = wm.autoConnect("AutoConnectAP","password"); // password protected ap + + if(!res) { + Serial.println("Failed to connect"); + // ESP.restart(); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + +} + +void loop() { + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino b/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino new file mode 100644 index 0000000..ab52396 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlocking/AutoConnectNonBlocking.ino @@ -0,0 +1,27 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + + wm.setConfigPortalBlocking(false); + wm.setConfigPortalTimeout(60); + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino b/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino new file mode 100644 index 0000000..3af79f0 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/NonBlocking/AutoConnectNonBlockingwParams/AutoConnectNonBlockingwParams.ino @@ -0,0 +1,36 @@ +#include // https://github.com/tzapu/WiFiManager +WiFiManager wm; +WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + + //reset settings - wipe credentials for testing + //wm.resetSettings(); + wm.addParameter(&custom_mqtt_server); + wm.setConfigPortalBlocking(false); + wm.setSaveParamsCallback(saveParamsCallback); + + //automatically connect using saved credentials if they exist + //If connection fails it starts an access point with the specified name + if(wm.autoConnect("AutoConnectAP")){ + Serial.println("connected...yeey :)"); + } + else { + Serial.println("Configportal running"); + } +} + +void loop() { + wm.process(); + // put your main code here, to run repeatedly: +} + +void saveParamsCallback () { + Serial.println("Get Params:"); + Serial.print(custom_mqtt_server.getID()); + Serial.print(" : "); + Serial.println(custom_mqtt_server.getValue()); +} diff --git a/firmware/libraries/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino b/firmware/libraries/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino new file mode 100644 index 0000000..0bc3992 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/NonBlocking/OnDemandNonBlocking/onDemandNonBlocking.ino @@ -0,0 +1,85 @@ +/** + * OnDemandNonBlocking.ino + * example of running the webportal or configportal manually and non blocking + * trigger pin will start a webportal for 120 seconds then turn it off. + * startAP = true will start both the configportal AP and webportal + */ +#include // https://github.com/tzapu/WiFiManager + +// include MDNS +#ifdef ESP8266 +#include +#elif defined(ESP32) +#include +#endif + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +unsigned int timeout = 120; // seconds to run for +unsigned int startTime = millis(); +bool portalRunning = false; +bool startAP = false; // start AP and webserver if true, else start only webserver + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once + Serial.begin(115200); + Serial.setDebugOutput(true); + delay(1000); + Serial.println("\n Starting"); + + pinMode(TRIGGER_PIN, INPUT_PULLUP); + + // wm.resetSettings(); + wm.setHostname("MDNSEXAMPLE"); + // wm.setEnableConfigPortal(false); + // wm.setConfigPortalBlocking(false); + wm.autoConnect(); +} + +void loop() { + #ifdef ESP8266 + MDNS.update(); + #endif + doWiFiManager(); + // put your main code here, to run repeatedly: +} + +void doWiFiManager(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); // do processing + + // check for timeout + if((millis()-startTime) > (timeout*1000)){ + Serial.println("portaltimeout"); + portalRunning = false; + if(startAP){ + wm.stopConfigPortal(); + } + else{ + wm.stopWebPortal(); + } + } + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW && (!portalRunning)) { + if(startAP){ + Serial.println("Button Pressed, Starting Config Portal"); + wm.setConfigPortalBlocking(false); + wm.startConfigPortal(); + } + else{ + Serial.println("Button Pressed, Starting Web Portal"); + wm.startWebPortal(); + } + portalRunning = true; + startTime = millis(); + } +} + + diff --git a/firmware/libraries/WiFiManager/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino old mode 100755 new mode 100644 similarity index 83% rename from firmware/libraries/WiFiManager/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino rename to firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino index 9491760..d3c4ed8 --- a/firmware/libraries/WiFiManager/examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino +++ b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithFeedback/AutoConnectWithFeedback.ino @@ -1,9 +1,4 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include "WiFiManager.h" //https://github.com/tzapu/WiFiManager +#include // https://github.com/tzapu/WiFiManager void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("Entered config mode"); @@ -32,7 +27,7 @@ void setup() { if(!wifiManager.autoConnect()) { Serial.println("failed to connect and hit timeout"); //reset and try again, or maybe put it to deep sleep - ESP.reset(); + ESP.restart(); delay(1000); } diff --git a/firmware/libraries/WiFiManager/examples/AutoConnectWithReset/AutoConnectWithReset.ino b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino old mode 100755 new mode 100644 similarity index 75% rename from firmware/libraries/WiFiManager/examples/AutoConnectWithReset/AutoConnectWithReset.ino rename to firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino index 5af3b1f..53a0d13 --- a/firmware/libraries/WiFiManager/examples/AutoConnectWithReset/AutoConnectWithReset.ino +++ b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithReset/AutoConnectWithReset.ino @@ -1,11 +1,5 @@ -#include //this needs to be first, or it all crashes and burns... - -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager void setup() { // put your setup code here, to run once: @@ -30,7 +24,7 @@ void setup() { if (!wifiManager.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect, we should reset as see if it connects"); delay(3000); - ESP.reset(); + ESP.restart(); delay(5000); } diff --git a/firmware/libraries/WiFiManager/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino old mode 100755 new mode 100644 similarity index 86% rename from firmware/libraries/WiFiManager/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino rename to firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino index 86556d3..9f88e47 --- a/firmware/libraries/WiFiManager/examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino +++ b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithStaticIP/AutoConnectWithStaticIP.ino @@ -1,12 +1,5 @@ -#include //this needs to be first, or it all crashes and burns... - -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - +#include // this needs to be first, or it all crashes and burns... +#include // https://github.com/tzapu/WiFiManager /************************************************************************************** * this example shows how to set a static IP configuration for the ESP @@ -15,9 +8,7 @@ * if you want the ability to configure and persist the new IP configuration * look at the FS examples, which save the config to file *************************************************************************************/ - - - + //default custom static IP //char static_ip[16] = "10.0.1.59"; //char static_gw[16] = "10.0.1.1"; @@ -61,7 +52,7 @@ void setup() { if (!wifiManager.autoConnect("AutoConnectAP", "password")) { Serial.println("failed to connect, we should reset as see if it connects"); delay(3000); - ESP.reset(); + ESP.restart(); delay(5000); } diff --git a/firmware/libraries/WiFiManager/examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino old mode 100755 new mode 100644 similarity index 78% rename from firmware/libraries/WiFiManager/examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino rename to firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino index c90cf10..9df428d --- a/firmware/libraries/WiFiManager/examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino +++ b/firmware/libraries/WiFiManager/examples/Old_examples/AutoConnectWithTimeout/AutoConnectWithTimeout.ino @@ -1,11 +1,4 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - - +#include // https://github.com/tzapu/WiFiManager void setup() { // put your setup code here, to run once: @@ -20,7 +13,7 @@ void setup() { //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds - wifiManager.setTimeout(180); + wifiManager.setConfigPortalTimeout(180); //fetches ssid and pass and tries to connect //if it does not connect it starts an access point with the specified name @@ -30,7 +23,7 @@ void setup() { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep - ESP.reset(); + ESP.restart(); delay(5000); } diff --git a/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino b/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 0000000..a45122a --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,47 @@ +/** + * OnDemandConfigPortal.ino + * example of running the configPortal AP manually, independantly from the captiveportal + * trigger pin will start a configPortal AP for 120 seconds then turn it off. + * + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +int timeout = 120; // seconds to run for + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + // is configuration portal requested? + if ( digitalRead(TRIGGER_PIN) == LOW) { + WiFiManager wm; + + //reset settings - for testing + //wm.resetSettings(); + + // set configportal timeout + wm.setConfigPortalTimeout(timeout); + + if (!wm.startConfigPortal("OnDemandAP")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + //reset and try again, or maybe put it to deep sleep + ESP.restart(); + delay(5000); + } + + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + + } + + // put your main code here, to run repeatedly: +} diff --git a/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino b/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino new file mode 100644 index 0000000..33fa384 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/OnDemand/OnDemandWebPortal/onDemandWebPortal.ino @@ -0,0 +1,51 @@ +/** + * OnDemandWebPortal.ino + * example of running the webportal (always NON blocking) + */ +#include // https://github.com/tzapu/WiFiManager + +// select which pin will trigger the configuration portal when set to LOW +#define TRIGGER_PIN 0 + +WiFiManager wm; + +bool portalRunning = false; + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once + Serial.begin(115200); + Serial.println("\n Starting"); + pinMode(TRIGGER_PIN, INPUT_PULLUP); +} + +void loop() { + checkButton(); + // put your main code here, to run repeatedly: +} + +void checkButton(){ + // is auto timeout portal running + if(portalRunning){ + wm.process(); + } + + // is configuration portal requested? + if(digitalRead(TRIGGER_PIN) == LOW) { + delay(50); + if(digitalRead(TRIGGER_PIN) == LOW) { + if(!portalRunning){ + Serial.println("Button Pressed, Starting Portal"); + wm.startWebPortal(); + portalRunning = true; + } + else{ + Serial.println("Button Pressed, Stopping Portal"); + wm.stopWebPortal(); + portalRunning = false; + } + } + } +} + + diff --git a/firmware/libraries/WiFiManager/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino b/firmware/libraries/WiFiManager/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino deleted file mode 100755 index 2f2d0cc..0000000 --- a/firmware/libraries/WiFiManager/examples/OnDemandConfigPortal/OnDemandConfigPortal.ino +++ /dev/null @@ -1,60 +0,0 @@ -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include -#include //https://github.com/tzapu/WiFiManager - -// select which pin will trigger the configuration portal when set to LOW -// ESP-01 users please note: the only pins available (0 and 2), are shared -// with the bootloader, so always set them HIGH at power-up -#define TRIGGER_PIN 0 - - -void setup() { - // put your setup code here, to run once: - Serial.begin(115200); - Serial.println("\n Starting"); - - pinMode(TRIGGER_PIN, INPUT); -} - - -void loop() { - // is configuration portal requested? - if ( digitalRead(TRIGGER_PIN) == LOW ) { - //WiFiManager - //Local intialization. Once its business is done, there is no need to keep it around - WiFiManager wifiManager; - - //reset settings - for testing - //wifiManager.resetSettings(); - - //sets timeout until configuration portal gets turned off - //useful to make it all retry or go to sleep - //in seconds - //wifiManager.setTimeout(120); - - //it starts an access point with the specified name - //here "AutoConnectAP" - //and goes into a blocking loop awaiting configuration - - //WITHOUT THIS THE AP DOES NOT SEEM TO WORK PROPERLY WITH SDK 1.5 , update to at least 1.5.1 - //WiFi.mode(WIFI_STA); - - if (!wifiManager.startConfigPortal("OnDemandAP")) { - Serial.println("failed to connect and hit timeout"); - delay(3000); - //reset and try again, or maybe put it to deep sleep - ESP.reset(); - delay(5000); - } - - //if you get here you have connected to the WiFi - Serial.println("connected...yeey :)"); - } - - - // put your main code here, to run repeatedly: - -} diff --git a/firmware/libraries/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino b/firmware/libraries/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino new file mode 100644 index 0000000..188b3c1 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Parameters/LittleFS/LittleFSParameters.ino @@ -0,0 +1,79 @@ +/** + * Basic example using LittleFS to store data + */ + +#include +#include +#include + +String readFile(fs::FS &fs, const char * path){ + Serial.printf("Reading file: %s\r\n", path); + File file = fs.open(path, "r"); + if(!file || file.isDirectory()){ + Serial.println("- empty file or failed to open file"); + return String(); + } + Serial.println("- read from file:"); + String fileContent; + while(file.available()){ + fileContent+=String((char)file.read()); + } + file.close(); + Serial.println(fileContent); + return fileContent; +} +void writeFile(fs::FS &fs, const char * path, const char * message){ + Serial.printf("Writing file: %s\r\n", path); + File file = fs.open(path, "w"); + if(!file){ + Serial.println("- failed to open file for writing"); + return; + } + if(file.print(message)){ + Serial.println("- file written"); + } else { + Serial.println("- write failed"); + } + file.close(); +} + +int data = 4; + +#include +#define TRIGGER_PIN 2 +int timeout = 120; // seconds to run for + +void setup() { +if (!LittleFS.begin()) { //to start littlefs +Serial.println("LittleFS mount failed"); +return; +} +data = readFile(LittleFS, "/data.txt").toInt(); +WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + // put your setup code here, to run once: + pinMode(TRIGGER_PIN, INPUT_PULLUP); + WiFiManager wm; + //wm.resetSettings(); + bool res; + res = wm.autoConnect("Setup"); + if(!res) { + Serial.println("Failed to connect"); + // ESP.restart(); + } + +} + +void loop() { +if ( digitalRead(TRIGGER_PIN) == LOW) { + WiFiManager wm; + //wm.resetSettings(); + wm.setConfigPortalTimeout(timeout); + if (!wm.startConfigPortal("Sharmander")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + ESP.restart(); + delay(5000); + } + Serial.println("connected...yeey :)"); +} +} \ No newline at end of file diff --git a/firmware/libraries/WiFiManager/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino b/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino old mode 100755 new mode 100644 similarity index 77% rename from firmware/libraries/WiFiManager/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino rename to firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino index 7e6c373..a9c7b79 --- a/firmware/libraries/WiFiManager/examples/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino +++ b/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParameters/AutoConnectWithFSParameters.ino @@ -1,18 +1,16 @@ #include //this needs to be first, or it all crashes and burns... - -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include #include //https://github.com/tzapu/WiFiManager +#ifdef ESP32 + #include +#endif + #include //https://github.com/bblanchon/ArduinoJson //define your default values here, if there are different values in config.json, they are overwritten. char mqtt_server[40]; char mqtt_port[6] = "8080"; -char blynk_token[34] = "YOUR_BLYNK_TOKEN"; +char api_token[34] = "YOUR_API_TOKEN"; //flag for saving data bool shouldSaveConfig = false; @@ -23,7 +21,6 @@ void saveConfigCallback () { shouldSaveConfig = true; } - void setup() { // put your setup code here, to run once: Serial.begin(115200); @@ -48,16 +45,22 @@ void setup() { std::unique_ptr buf(new char[size]); configFile.readBytes(buf.get(), size); + + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + DynamicJsonDocument json(1024); + auto deserializeError = deserializeJson(json, buf.get()); + serializeJson(json, Serial); + if ( ! deserializeError ) { +#else DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { +#endif Serial.println("\nparsed json"); - strcpy(mqtt_server, json["mqtt_server"]); strcpy(mqtt_port, json["mqtt_port"]); - strcpy(blynk_token, json["blynk_token"]); - + strcpy(api_token, json["api_token"]); } else { Serial.println("failed to load json config"); } @@ -69,14 +72,12 @@ void setup() { } //end read - - // The extra parameters to be configured (can be either global or just in the setup) // After connecting, parameter.getValue() will get you the configured value // id/name placeholder/prompt default length WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 6); - WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 32); + WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 32); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around @@ -86,12 +87,12 @@ void setup() { wifiManager.setSaveConfigCallback(saveConfigCallback); //set static ip - wifiManager.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); - + wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0)); + //add all your parameters here wifiManager.addParameter(&custom_mqtt_server); wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_blynk_token); + wifiManager.addParameter(&custom_api_token); //reset settings - for testing //wifiManager.resetSettings(); @@ -99,7 +100,7 @@ void setup() { //set minimu quality of signal so it ignores AP's under that quality //defaults to 8% //wifiManager.setMinimumSignalQuality(); - + //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds @@ -113,7 +114,7 @@ void setup() { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep - ESP.reset(); + ESP.restart(); delay(5000); } @@ -123,35 +124,46 @@ void setup() { //read updated parameters strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(blynk_token, custom_blynk_token.getValue()); + strcpy(api_token, custom_api_token.getValue()); + Serial.println("The values in the file are: "); + Serial.println("\tmqtt_server : " + String(mqtt_server)); + Serial.println("\tmqtt_port : " + String(mqtt_port)); + Serial.println("\tapi_token : " + String(api_token)); //save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + DynamicJsonDocument json(1024); +#else DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); +#endif json["mqtt_server"] = mqtt_server; json["mqtt_port"] = mqtt_port; - json["blynk_token"] = blynk_token; + json["api_token"] = api_token; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { Serial.println("failed to open config file for writing"); } +#if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + serializeJson(json, Serial); + serializeJson(json, configFile); +#else json.printTo(Serial); json.printTo(configFile); +#endif configFile.close(); //end save } Serial.println("local ip"); Serial.println(WiFi.localIP()); - } void loop() { // put your main code here, to run repeatedly: - } diff --git a/firmware/libraries/WiFiManager/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino b/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino old mode 100755 new mode 100644 similarity index 82% rename from firmware/libraries/WiFiManager/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino rename to firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino index 3f391ae..63523e9 --- a/firmware/libraries/WiFiManager/examples/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino +++ b/firmware/libraries/WiFiManager/examples/Parameters/SPIFFS/AutoConnectWithFSParametersAndCustomIP/AutoConnectWithFSParametersAndCustomIP.ino @@ -1,19 +1,18 @@ #include //this needs to be first, or it all crashes and burns... -#include //https://github.com/esp8266/Arduino - -//needed for library -#include -#include #include //https://github.com/tzapu/WiFiManager +#ifdef ESP32 + #include +#endif + #include //https://github.com/bblanchon/ArduinoJson //define your default values here, if there are different values in config.json, they are overwritten. -//length should be max size + 1 +//length should be max size + 1 char mqtt_server[40]; char mqtt_port[6] = "8080"; -char blynk_token[33] = "YOUR_BLYNK_TOKEN"; +char api_token[34] = "YOUR_APITOKEN"; //default custom static IP char static_ip[16] = "10.0.1.56"; char static_gw[16] = "10.0.1.1"; @@ -52,29 +51,29 @@ void setup() { std::unique_ptr buf(new char[size]); configFile.readBytes(buf.get(), size); + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + DynamicJsonDocument json(1024); + auto deserializeError = deserializeJson(json, buf.get()); + serializeJson(json, Serial); + if ( ! deserializeError ) { +#else DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); json.printTo(Serial); if (json.success()) { +#endif Serial.println("\nparsed json"); strcpy(mqtt_server, json["mqtt_server"]); strcpy(mqtt_port, json["mqtt_port"]); - strcpy(blynk_token, json["blynk_token"]); + strcpy(api_token, json["api_token"]); - if(json["ip"]) { + if (json["ip"]) { Serial.println("setting custom ip from config"); - //static_ip = json["ip"]; strcpy(static_ip, json["ip"]); strcpy(static_gw, json["gateway"]); strcpy(static_sn, json["subnet"]); - //strcat(static_ip, json["ip"]); - //static_gw = json["gateway"]; - //static_sn = json["subnet"]; Serial.println(static_ip); -/* Serial.println("converting ip"); - IPAddress ip = ipFromCharArray(static_ip); - Serial.println(ip);*/ } else { Serial.println("no custom ip in config"); } @@ -88,7 +87,7 @@ void setup() { } //end read Serial.println(static_ip); - Serial.println(blynk_token); + Serial.println(api_token); Serial.println(mqtt_server); @@ -97,7 +96,7 @@ void setup() { // id/name placeholder/prompt default length WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, 40); WiFiManagerParameter custom_mqtt_port("port", "mqtt port", mqtt_port, 5); - WiFiManagerParameter custom_blynk_token("blynk", "blynk token", blynk_token, 34); + WiFiManagerParameter custom_api_token("apikey", "API token", api_token, 34); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around @@ -107,17 +106,17 @@ void setup() { wifiManager.setSaveConfigCallback(saveConfigCallback); //set static ip - IPAddress _ip,_gw,_sn; + IPAddress _ip, _gw, _sn; _ip.fromString(static_ip); _gw.fromString(static_gw); _sn.fromString(static_sn); wifiManager.setSTAStaticIPConfig(_ip, _gw, _sn); - + //add all your parameters here wifiManager.addParameter(&custom_mqtt_server); wifiManager.addParameter(&custom_mqtt_port); - wifiManager.addParameter(&custom_blynk_token); + wifiManager.addParameter(&custom_api_token); //reset settings - for testing //wifiManager.resetSettings(); @@ -125,7 +124,7 @@ void setup() { //set minimu quality of signal so it ignores AP's under that quality //defaults to 8% wifiManager.setMinimumSignalQuality(); - + //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds @@ -139,7 +138,7 @@ void setup() { Serial.println("failed to connect and hit timeout"); delay(3000); //reset and try again, or maybe put it to deep sleep - ESP.reset(); + ESP.restart(); delay(5000); } @@ -149,16 +148,20 @@ void setup() { //read updated parameters strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(mqtt_port, custom_mqtt_port.getValue()); - strcpy(blynk_token, custom_blynk_token.getValue()); + strcpy(api_token, custom_api_token.getValue()); //save the custom parameters to FS if (shouldSaveConfig) { Serial.println("saving config"); + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + DynamicJsonDocument json(1024); +#else DynamicJsonBuffer jsonBuffer; JsonObject& json = jsonBuffer.createObject(); +#endif json["mqtt_server"] = mqtt_server; json["mqtt_port"] = mqtt_port; - json["blynk_token"] = blynk_token; + json["api_token"] = api_token; json["ip"] = WiFi.localIP().toString(); json["gateway"] = WiFi.gatewayIP().toString(); @@ -169,8 +172,13 @@ void setup() { Serial.println("failed to open config file for writing"); } - json.prettyPrintTo(Serial); + #if defined(ARDUINOJSON_VERSION_MAJOR) && ARDUINOJSON_VERSION_MAJOR >= 6 + serializeJson(json, Serial); + serializeJson(json, configFile); +#else + json.printTo(Serial); json.printTo(configFile); +#endif configFile.close(); //end save } @@ -183,6 +191,4 @@ void setup() { void loop() { // put your main code here, to run repeatedly: - - } diff --git a/firmware/libraries/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino b/firmware/libraries/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino new file mode 100644 index 0000000..8739a05 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/ParamsChildClass/ParamsChildClass.ino @@ -0,0 +1,143 @@ +/** + * WiFiManagerParameter child class example + */ +#include // https://github.com/tzapu/WiFiManager +#include +#include + +#define SETUP_PIN 0 + +class IPAddressParameter : public WiFiManagerParameter { +public: + IPAddressParameter(const char *id, const char *placeholder, IPAddress address) + : WiFiManagerParameter("") { + init(id, placeholder, address.toString().c_str(), 16, "", WFM_LABEL_BEFORE); + } + + bool getValue(IPAddress &ip) { + return ip.fromString(WiFiManagerParameter::getValue()); + } +}; + +class IntParameter : public WiFiManagerParameter { +public: + IntParameter(const char *id, const char *placeholder, long value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + long getValue() { + return String(WiFiManagerParameter::getValue()).toInt(); + } +}; + +class FloatParameter : public WiFiManagerParameter { +public: + FloatParameter(const char *id, const char *placeholder, float value, const uint8_t length = 10) + : WiFiManagerParameter("") { + init(id, placeholder, String(value).c_str(), length, "", WFM_LABEL_BEFORE); + } + + float getValue() { + return String(WiFiManagerParameter::getValue()).toFloat(); + } +}; + +struct Settings { + float f; + int i; + char s[20]; + uint32_t ip; +} sett; + + +void setup() { + WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP + pinMode(SETUP_PIN, INPUT_PULLUP); + Serial.begin(115200); + + //Delay to push SETUP button + Serial.println("Press setup button"); + for (int sec = 3; sec > 0; sec--) { + Serial.print(sec); + Serial.print(".."); + delay(1000); + } + + // warning for example only, this will initialize empty memory into your vars + // always init flash memory or add some checksum bits + EEPROM.begin( 512 ); + EEPROM.get(0, sett); + Serial.println("Settings loaded"); + + if (digitalRead(SETUP_PIN) == LOW) { + // Button pressed + Serial.println("SETUP"); + + WiFiManager wm; + + sett.s[19] = '\0'; //add null terminator at the end cause overflow + WiFiManagerParameter param_str( "str", "param_string", sett.s, 20); + FloatParameter param_float( "float", "param_float", sett.f); + IntParameter param_int( "int", "param_int", sett.i); + + IPAddress ip(sett.ip); + IPAddressParameter param_ip("ip", "param_ip", ip); + + wm.addParameter( ¶m_str ); + wm.addParameter( ¶m_float ); + wm.addParameter( ¶m_int ); + wm.addParameter( ¶m_ip ); + + //SSID & password parameters already included + wm.startConfigPortal(); + + strncpy(sett.s, param_str.getValue(), 20); + sett.s[19] = '\0'; + sett.f = param_float.getValue(); + sett.i = param_int.getValue(); + + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + + if (param_ip.getValue(ip)) { + sett.ip = ip; + + Serial.print("IP param: "); + Serial.println(ip); + } else { + Serial.println("Incorrect IP"); + } + + EEPROM.put(0, sett); + if (EEPROM.commit()) { + Serial.println("Settings saved"); + } else { + Serial.println("EEPROM error"); + } + } + else { + Serial.println("WORK"); + + //connect to saved SSID + WiFi.begin(); + + //do smth + Serial.print("String param: "); + Serial.println(sett.s); + Serial.print("Float param: "); + Serial.println(sett.f); + Serial.print("Int param: "); + Serial.println(sett.i, DEC); + Serial.print("IP param: "); + IPAddress ip(sett.ip); + Serial.println(ip); + } +} + +void loop() { +} diff --git a/firmware/libraries/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino b/firmware/libraries/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino new file mode 100644 index 0000000..a648366 --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Super/OnDemandConfigPortal/OnDemandConfigPortal.ino @@ -0,0 +1,416 @@ +/** + * This is a kind of unit test for DEV for now + * It contains many of the public methods + * + */ +#include // https://github.com/tzapu/WiFiManager +#include +#include + +#define USEOTA +// enable OTA +#ifdef USEOTA +#include +#include +#endif + +const char* modes[] = { "NULL", "STA", "AP", "STA+AP" }; + +unsigned long mtime = 0; + + +WiFiManager wm; + + +// TEST OPTION FLAGS +bool TEST_CP = false; // always start the configportal, even if ap found +int TESP_CP_TIMEOUT = 90; // test cp timeout + +bool TEST_NET = true; // do a network test after connect, (gets ntp time) +bool ALLOWONDEMAND = true; // enable on demand +int ONDDEMANDPIN = 0; // gpio for button +bool WMISBLOCKING = true; // use blocking or non blocking mode, non global params wont work in non blocking + +// char ssid[] = "*************"; // your network SSID (name) +// char pass[] = "********"; // your network password + + +//callbacks + // called after AP mode and config portal has started + // setAPCallback( std::function func ); + // called after webserver has started + // setWebServerCallback( std::function func ); + // called when settings reset have been triggered + // setConfigResetCallback( std::function func ); + // called when wifi settings have been changed and connection was successful ( or setBreakAfterConfig(true) ) + // setSaveConfigCallback( std::function func ); + // called when saving either params-in-wifi or params page + // setSaveParamsCallback( std::function func ); + // called when saving params-in-wifi or params before anything else happens (eg wifi) + // setPreSaveConfigCallback( std::function func ); + // called just before doing OTA update + // setPreOtaUpdateCallback( std::function func ); + +void saveWifiCallback(){ + Serial.println("[CALLBACK] saveCallback fired"); +} + +//gets called when WiFiManager enters configuration mode +void configModeCallback (WiFiManager *myWiFiManager) { + Serial.println("[CALLBACK] configModeCallback fired"); + // myWiFiManager->setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // Serial.println(WiFi.softAPIP()); + //if you used auto generated SSID, print it + // Serial.println(myWiFiManager->getConfigPortalSSID()); + // + // esp_wifi_set_bandwidth(WIFI_IF_AP, WIFI_BW_HT20); +} + +void saveParamCallback(){ + Serial.println("[CALLBACK] saveParamCallback fired"); + // wm.stopConfigPortal(); +} + +void bindServerCallback(){ + wm.server->on("/custom",handleRoute); // this is now crashing esp32 for some reason + // wm.server->on("/info",handleRoute); // you can override wm! +} + +void handleRoute(){ + Serial.println("[HTTP] handle route"); + wm.server->send(200, "text/plain", "hello from user code"); +} + +void handlePreOtaUpdateCallback(){ + Update.onProgress([](unsigned int progress, unsigned int total) { + Serial.printf("CUSTOM Progress: %u%%\r", (progress / (total / 100))); + }); +} + +void setup() { + // WiFi.mode(WIFI_STA); // explicitly set mode, esp can default to STA+AP + + // put your setup code here, to run once: + Serial.begin(115200); + + // Serial.setDebugOutput(true); + + Serial.println("\n Starting"); + // WiFi.setSleepMode(WIFI_NONE_SLEEP); // disable sleep, can improve ap stability + + Serial.println("Error - TEST"); + Serial.println("Information- - TEST"); + + Serial.println("[ERROR] TEST"); + Serial.println("[INFORMATION] TEST"); + + + wm.setDebugOutput(true); + wm.debugPlatformInfo(); + + //reset settings - for testing + // wm.resetSettings(); + // wm.erase(); + + // setup some parameters + + WiFiManagerParameter custom_html("

This Is Custom HTML

"); // only custom html + WiFiManagerParameter custom_mqtt_server("server", "mqtt server", "", 40); + WiFiManagerParameter custom_mqtt_port("port", "mqtt port", "", 6); + WiFiManagerParameter custom_token("api_token", "api token", "", 16); + WiFiManagerParameter custom_tokenb("invalid token", "invalid token", "", 0); // id is invalid, cannot contain spaces + WiFiManagerParameter custom_ipaddress("input_ip", "input IP", "", 15,"pattern='\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}'"); // custom input attrs (ip mask) + WiFiManagerParameter custom_input_type("input_pwd", "input pass", "", 15,"type='password'"); // custom input attrs (ip mask) + + const char _customHtml_checkbox[] = "type=\"checkbox\""; + WiFiManagerParameter custom_checkbox("my_checkbox", "My Checkbox", "T", 2, _customHtml_checkbox,WFM_LABEL_AFTER); + + const char *bufferStr = R"( + +
+

Select Choice

+ +
+ +
+ + +
+ + + )"; + + WiFiManagerParameter custom_html_inputs(bufferStr); + + // callbacks + wm.setAPCallback(configModeCallback); + wm.setWebServerCallback(bindServerCallback); + wm.setSaveConfigCallback(saveWifiCallback); + wm.setSaveParamsCallback(saveParamCallback); + wm.setPreOtaUpdateCallback(handlePreOtaUpdateCallback); + + // add all your parameters here + wm.addParameter(&custom_html); + wm.addParameter(&custom_mqtt_server); + wm.addParameter(&custom_mqtt_port); + wm.addParameter(&custom_token); + wm.addParameter(&custom_tokenb); + wm.addParameter(&custom_ipaddress); + wm.addParameter(&custom_checkbox); + wm.addParameter(&custom_input_type); + + wm.addParameter(&custom_html_inputs); + + // set values later if you want + custom_html.setValue("test",4); + custom_token.setValue("test",4); + + // const char* icon = " + // "; + + + // set custom html head content , inside + // examples of favicon, or meta tags etc + // const char* headhtml = ""; + // const char* headhtml = ""; + // wm.setCustomHeadElement(headhtml); + + // set custom html menu content , inside menu item "custom", see setMenu() + const char* menuhtml = "

\n"; + wm.setCustomMenuHTML(menuhtml); + + // invert theme, dark + wm.setDarkMode(true); + + // show scan RSSI as percentage, instead of signal stength graphic + // wm.setScanDispPerc(true); + +/* + Set cutom menu via menu[] or vector + const char* menu[] = {"wifi","wifinoscan","info","param","close","sep","erase","restart","exit"}; + wm.setMenu(menu,9); // custom menu array must provide length +*/ + + std::vector menu = {"wifi","wifinoscan","info","param","custom","close","sep","erase","update","restart","exit"}; + wm.setMenu(menu); // custom menu, pass vector + + // wm.setParamsPage(true); // move params to seperate page, not wifi, do not combine with setmenu! + + // set STA static ip + // wm.setSTAStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setShowStaticFields(false); + // wm.setShowDnsFields(false); + + // set AP static ip + // wm.setAPStaticIPConfig(IPAddress(10,0,1,1), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + // wm.setAPStaticIPConfig(IPAddress(10,0,1,99), IPAddress(10,0,1,1), IPAddress(255,255,255,0)); + + // set country + // setting wifi country seems to improve OSX soft ap connectivity, + // may help others as well, default is CN which has different channels + + // wm.setCountry("US"); // crashing on esp32 2.0 + + // set Hostname + + wm.setHostname(("WM_"+wm.getDefaultAPName()).c_str()); + // wm.setHostname("WM_RANDO_1234"); + + // set custom channel + // wm.setWiFiAPChannel(13); + + // set AP hidden + // wm.setAPHidden(true); + + // show password publicly in form + // wm.setShowPassword(true); + + // sets wether wm configportal is a blocking loop(legacy) or not, use wm.process() in loop if false + // wm.setConfigPortalBlocking(false); + + if(!WMISBLOCKING){ + wm.setConfigPortalBlocking(false); + } + + //sets timeout until configuration portal gets turned off + //useful to make it all retry or go to sleep in seconds + wm.setConfigPortalTimeout(120); + + // set min quality to show in web list, default 8% + // wm.setMinimumSignalQuality(50); + + // set connection timeout + // wm.setConnectTimeout(20); + + // set wifi connect retries + // wm.setConnectRetries(2); + + // connect after portal save toggle + // wm.setSaveConnect(false); // do not connect, only save + + // show static ip fields + // wm.setShowStaticFields(true); + + // wm.startConfigPortal("AutoConnectAP", "password"); + + // This is sometimes necessary, it is still unknown when and why this is needed but it may solve some race condition or bug in esp SDK/lib + // wm.setCleanConnect(true); // disconnect before connect, clean connect + + wm.setBreakAfterConfig(true); // needed to use saveWifiCallback + + // set custom webserver port, automatic captive portal does not work with custom ports! + // wm.setHttpPort(8080); + + //fetches ssid and pass and tries to connect + //if it does not connect it starts an access point with the specified name + //here "AutoConnectAP" + //and goes into a blocking loop awaiting configuration + + // use autoconnect, but prevent configportal from auto starting + // wm.setEnableConfigPortal(false); + + wifiInfo(); + + // to preload autoconnect with credentials + // wm.preloadWiFi("ssid","password"); + + if(!wm.autoConnect("WM_AutoConnectAP","12345678")) { + Serial.println("failed to connect and hit timeout"); + } + else if(TEST_CP) { + // start configportal always + delay(1000); + Serial.println("TEST_CP ENABLED"); + wm.setConfigPortalTimeout(TESP_CP_TIMEOUT); + wm.startConfigPortal("WM_ConnectAP","12345678"); + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + } + + wifiInfo(); + pinMode(ONDDEMANDPIN, INPUT_PULLUP); + + #ifdef USEOTA + ArduinoOTA.begin(); + #endif + +} + +void wifiInfo(){ + // can contain gargbage on esp32 if wifi is not ready yet + Serial.println("[WIFI] WIFI INFO DEBUG"); + // WiFi.printDiag(Serial); + Serial.println("[WIFI] SAVED: " + (String)(wm.getWiFiIsSaved() ? "YES" : "NO")); + Serial.println("[WIFI] SSID: " + (String)wm.getWiFiSSID()); + Serial.println("[WIFI] PASS: " + (String)wm.getWiFiPass()); + Serial.println("[WIFI] HOSTNAME: " + (String)WiFi.getHostname()); +} + +void loop() { + + if(!WMISBLOCKING){ + wm.process(); + } + + #ifdef USEOTA + ArduinoOTA.handle(); + #endif + // is configuration portal requested? + if (ALLOWONDEMAND && digitalRead(ONDDEMANDPIN) == LOW ) { + delay(100); + if ( digitalRead(ONDDEMANDPIN) == LOW ){ + Serial.println("BUTTON PRESSED"); + + // button reset/reboot + // wm.resetSettings(); + // wm.reboot(); + // delay(200); + // return; + + wm.setConfigPortalTimeout(140); + wm.setParamsPage(false); // move params to seperate page, not wifi, do not combine with setmenu! + + // disable captive portal redirection + // wm.setCaptivePortalEnable(false); + + if (!wm.startConfigPortal("OnDemandAP","12345678")) { + Serial.println("failed to connect and hit timeout"); + delay(3000); + } + } + else { + //if you get here you have connected to the WiFi + Serial.println("connected...yeey :)"); + getTime(); + } + } + + // every 10 seconds + if(millis()-mtime > 10000 ){ + if(WiFi.status() == WL_CONNECTED){ + getTime(); + } + else Serial.println("No Wifi"); + mtime = millis(); + } + // put your main code here, to run repeatedly: + delay(100); +} + +void getTime() { + int tz = -5; + int dst = 0; + time_t now = time(nullptr); + unsigned timeout = 5000; // try for timeout + unsigned start = millis(); + configTime(tz * 3600, dst * 3600, "pool.ntp.org", "time.nist.gov"); + Serial.print("Waiting for NTP time sync: "); + while (now < 8 * 3600 * 2 ) { // what is this ? + delay(100); + Serial.print("."); + now = time(nullptr); + if((millis() - start) > timeout){ + Serial.println("\n[ERROR] Failed to get NTP time."); + return; + } + } + Serial.println(""); + struct tm timeinfo; + gmtime_r(&now, &timeinfo); + Serial.print("Current time: "); + Serial.print(asctime(&timeinfo)); +} + +void debugchipid(){ + // WiFi.mode(WIFI_STA); + // WiFi.printDiag(Serial); + // Serial.println(modes[WiFi.getMode()]); + + // ESP.eraseConfig(); + // wm.resetSettings(); + // wm.erase(true); + WiFi.mode(WIFI_AP); + // WiFi.softAP(); + WiFi.enableAP(true); + delay(500); + // esp_wifi_start(); + delay(1000); + WiFi.printDiag(Serial); + delay(60000); + ESP.restart(); + + // AP esp_267751 + // 507726A4AE30 + // ESP32 Chip ID = 507726A4AE30 +} diff --git a/firmware/libraries/WiFiManager/examples/Tests/wifi_softap/wifi_softap.ino b/firmware/libraries/WiFiManager/examples/Tests/wifi_softap/wifi_softap.ino new file mode 100644 index 0000000..aa3e45c --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Tests/wifi_softap/wifi_softap.ino @@ -0,0 +1,51 @@ +// wifi_basic.ino + +#include +#include + +// #define NVSERASE +#ifdef NVSERASE +#include +#include +#endif + +void setup(){ + Serial.begin(115200); + delay(2000); + Serial.println("Startup...."); + + #ifdef NVSERASE + esp_err_t err; + err = nvs_flash_init(); + err = nvs_flash_erase(); + #endif + + Serial.setDebugOutput(true); + + WiFi.begin("hellowifi","noonehere"); + + while (WiFi.status() != WL_CONNECTED && millis()<15000) { + delay(500); + Serial.print("."); + } + + if(WiFi.status() == WL_CONNECTED){ + Serial.println(""); + Serial.println("WiFi connected."); + Serial.println("IP address: "); + // Serial.println(WiFi.localIP()); + } + else { + Serial.println("WiFi NOT CONNECTED, starting ap"); + /////////////// + /// BUG + // WiFi.enableSTA(false); // BREAKS softap start, says ok BUT no ap found + + delay(2000); + WiFi.softAP("espsoftap","12345678"); + } +} + +void loop(){ + +} \ No newline at end of file diff --git a/firmware/libraries/WiFiManager/examples/Unique/cb/AnonymousCB.ino b/firmware/libraries/WiFiManager/examples/Unique/cb/AnonymousCB.ino new file mode 100644 index 0000000..f34d80f --- /dev/null +++ b/firmware/libraries/WiFiManager/examples/Unique/cb/AnonymousCB.ino @@ -0,0 +1,26 @@ +#include // https://github.com/tzapu/WiFiManager + +bool _enteredConfigMode = false; + +void setup(){ + Serial.begin(115200); + WiFiManager wifiManager; + + // wifiManager.setAPCallback([this](WiFiManager* wifiManager) { + wifiManager.setAPCallback([&](WiFiManager* wifiManager) { + Serial.printf("Entered config mode:ip=%s, ssid='%s'\n", + WiFi.softAPIP().toString().c_str(), + wifiManager->getConfigPortalSSID().c_str()); + _enteredConfigMode = true; + }); + wifiManager.resetSettings(); + if (!wifiManager.autoConnect()) { + Serial.printf("*** Failed to connect and hit timeout\n"); + ESP.restart(); + delay(1000); + } +} + +void loop(){ + +} diff --git a/firmware/libraries/WiFiManager/extras/WiFiManager.template.html b/firmware/libraries/WiFiManager/extras/WiFiManager.template.html old mode 100755 new mode 100644 index e15593b..d928a8c --- a/firmware/libraries/WiFiManager/extras/WiFiManager.template.html +++ b/firmware/libraries/WiFiManager/extras/WiFiManager.template.html @@ -6,72 +6,387 @@ {v} - + - -
+ +
+ - - - - - - + +

/


+ -



- -
{v} {r}%
-
PMisa 100%
- -
PMisa 8%
- + +

+

+

+

+

+

+

+

+

+

+ + +

/wifi


+ + + + + + + + + + + + + + + + -
{v} {r}%
+ -


+

Show Password
+ +

custom parameter


+
+
+ + +
+
-
+
-
+
-
Credentials Saved
Trying to connect ESP to network.
If it fails reconnect to AP to try again
+

Saving Credentials

Trying to connect ESP to network.
If it fails reconnect to AP to try again
+ +
Connected to {v}
with IP {i}
+ + +
Not Connected to {v}{r}
+ + +
Not Connected to apname + + +
Authentication Failure + + +
AP not found + + +
Could not Connect + +
+ +
No AP set
+ + +

H4 Color Header P

content
+ + +

H4 Color Header S

content
+ + +

/info


+
+
Chip ID
123456
+
Flash Chip ID
1234556
+
IDE Flash Size
4194304 bytes
+
Real Flash Size
4194304 bytes
+
Empty
+
Soft AP IP
192.168.4.1
+
Soft AP MAC
00:00:00:00:00:00
+
Station MAC
00:00:00:00:00:00
+
+ + +

Available Pages


+ + + + + + + + + + + + + + + + + + + + +
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/closeClose the configuration server and configuration WiFi network.
/infoInformation page
/closeClose the captiveportal popup,configportal will remain active
/exitExit Config Portal, configportal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.
+

About


+ Version v1.x.x-xxxxx
+ Build_date
+ Build_file
+ Arduino_version
+

Github https://github.com/tzapu/WiFiManager + + +

Form UPLOAD
+

+ + + * Upload may not function inside captive portal, Open in browser - http://192.168.4.1 + + +



+
+ +
+ +
+ + + + +
+ + +

Select Choice

+ +
+ +
+ + +
+ + + +
+ +
diff --git a/firmware/libraries/WiFiManager/extras/parse.js b/firmware/libraries/WiFiManager/extras/parse.js old mode 100755 new mode 100644 diff --git a/firmware/libraries/WiFiManager/extras/png_signal_strength_master.png b/firmware/libraries/WiFiManager/extras/png_signal_strength_master.png new file mode 100644 index 0000000..f03c947 Binary files /dev/null and b/firmware/libraries/WiFiManager/extras/png_signal_strength_master.png differ diff --git a/firmware/libraries/WiFiManager/extras/template.h b/firmware/libraries/WiFiManager/extras/template.h old mode 100755 new mode 100644 diff --git a/firmware/libraries/WiFiManager/extras/test.html b/firmware/libraries/WiFiManager/extras/test.html new file mode 100644 index 0000000..816d0c9 --- /dev/null +++ b/firmware/libraries/WiFiManager/extras/test.html @@ -0,0 +1,182 @@ + + + + + + Config ESP + + + + + + + + + + + + diff --git a/firmware/libraries/WiFiManager/keywords.txt b/firmware/libraries/WiFiManager/keywords.txt old mode 100755 new mode 100644 diff --git a/firmware/libraries/WiFiManager/library.json b/firmware/libraries/WiFiManager/library.json old mode 100755 new mode 100644 index 8f0830a..d8bbf98 --- a/firmware/libraries/WiFiManager/library.json +++ b/firmware/libraries/WiFiManager/library.json @@ -1,13 +1,29 @@ { - "name": "WifiManager", - "keywords": "wifi, wi-fi", - "description": "ESP8266 WiFi Connection manager with fallback web configuration portal", + "name": "WiFiManager", + "version": "2.0.13-beta", + "keywords": "wifi,wi-fi,esp,esp8266,esp32,espressif8266,espressif32,nodemcu,wemos,arduino", + "description": "WiFi Configuration manager with web configuration portal for ESP boards", + "authors": + [ + { + "name": "tzapu", + "url": "https://github.com/tzapu" + }, + { + "name": "tablatronix", + "url": "https://github.com/tablatronix", + "maintainer": true + } + ], "repository": { "type": "git", "url": "https://github.com/tzapu/WiFiManager.git" }, "frameworks": "arduino", - "platforms": "espressif8266", - "version": "0.14" -} + "platforms": + [ + "espressif8266", + "espressif32" + ] +} \ No newline at end of file diff --git a/firmware/libraries/WiFiManager/library.properties b/firmware/libraries/WiFiManager/library.properties old mode 100755 new mode 100644 index e0420ad..791cd61 --- a/firmware/libraries/WiFiManager/library.properties +++ b/firmware/libraries/WiFiManager/library.properties @@ -1,9 +1,9 @@ name=WiFiManager -version=0.14 +version=2.0.13-beta author=tzapu -maintainer=tzapu -sentence=ESP8266 WiFi Connection manager with fallback web configuration portal -paragraph=Library for configuring ESP8266 modules WiFi credentials at runtime. +maintainer=tablatronix +sentence=WiFi Configuration manager with web configuration portal for Espressif ESPx boards, by tzapu +paragraph=Library for configuring ESP8266/ESP32 modules WiFi credentials and custom parameters at runtime with captive portal. category=Communication url=https://github.com/tzapu/WiFiManager.git -architectures=esp8266 +architectures=esp8266,esp32 diff --git a/firmware/libraries/WiFiManager/strings_en.h b/firmware/libraries/WiFiManager/strings_en.h new file mode 100644 index 0000000..382ab01 --- /dev/null +++ b/firmware/libraries/WiFiManager/strings_en.h @@ -0,0 +1,501 @@ +/** + * strings_en.h + * engligh strings for + * WiFiManager, a library for the ESP8266/Arduino platform + * for configuration of WiFi credentials using a Captive Portal + * + * @author Creator tzapu + * @author tablatronix + * @version 0.0.0 + * @license MIT + */ + +#ifndef _WM_STRINGS_H_ +#define _WM_STRINGS_H_ + + +#ifndef WIFI_MANAGER_OVERRIDE_STRINGS +// !!! ABOVE WILL NOT WORK if you define in your sketch, must be build flag, if anyone one knows how to order includes to be able to do this it would be neat.. I have seen it done.. + +const char WM_VERSION_STR[] PROGMEM = "v2.0.13-beta"; + +const char HTTP_HEAD_START[] PROGMEM = "" +"" +"" +"" +"" +"{v}"; + +const char HTTP_SCRIPT[] PROGMEM = ""; // @todo add button states, disable on click , show ack , spinner etc + +const char HTTP_HEAD_END[] PROGMEM = "
"; // {c} = _bodyclass +// example of embedded logo, base64 encoded inline, No styling here +// const char HTTP_ROOT_MAIN[] PROGMEM = "

{v}

WiFiManager

"; +const char HTTP_ROOT_MAIN[] PROGMEM = "

{t}

{v}

"; + +const char * const HTTP_PORTAL_MENU[] PROGMEM = { +"

\n", // MENU_WIFI +"

\n", // MENU_WIFINOSCAN +"

\n", // MENU_INFO +"

\n",//MENU_PARAM +"

\n", // MENU_CLOSE +"

\n",// MENU_RESTART +"

\n", // MENU_EXIT +"

\n", // MENU_ERASE +"

\n",// MENU_UPDATE +"

" // MENU_SEP +}; + +// const char HTTP_PORTAL_OPTIONS[] PROGMEM = strcat(HTTP_PORTAL_MENU[0] , HTTP_PORTAL_MENU[3] , HTTP_PORTAL_MENU[7]); +const char HTTP_PORTAL_OPTIONS[] PROGMEM = ""; +const char HTTP_ITEM_QI[] PROGMEM = ""; // rssi icons +const char HTTP_ITEM_QP[] PROGMEM = "
{r}%
"; // rssi percentage {h} = hidden showperc pref +const char HTTP_ITEM[] PROGMEM = "
{v}{qi}{qp}
"; // {q} = HTTP_ITEM_QI, {r} = HTTP_ITEM_QP +// const char HTTP_ITEM[] PROGMEM = "
{v} {R} {r}% {q} {e}
"; // test all tokens + +const char HTTP_FORM_START[] PROGMEM = "
"; +const char HTTP_FORM_WIFI[] PROGMEM = "
Show Password"; +const char HTTP_FORM_WIFI_END[] PROGMEM = ""; +const char HTTP_FORM_STATIC_HEAD[] PROGMEM = "

"; +const char HTTP_FORM_END[] PROGMEM = "

"; +const char HTTP_FORM_LABEL[] PROGMEM = ""; +const char HTTP_FORM_PARAM_HEAD[] PROGMEM = "

"; +const char HTTP_FORM_PARAM[] PROGMEM = "
\n"; // do not remove newline! + +const char HTTP_SCAN_LINK[] PROGMEM = "
"; +const char HTTP_SAVED[] PROGMEM = "
Saving Credentials
Trying to connect ESP to network.
If it fails reconnect to AP to try again
"; +const char HTTP_PARAMSAVED[] PROGMEM = "
Saved
"; +const char HTTP_END[] PROGMEM = "
"; +const char HTTP_ERASEBTN[] PROGMEM = "
"; +const char HTTP_UPDATEBTN[] PROGMEM = "
"; +const char HTTP_BACKBTN[] PROGMEM = "

"; + +const char HTTP_STATUS_ON[] PROGMEM = "
Connected to {v}
with IP {i}
"; +const char HTTP_STATUS_OFF[] PROGMEM = "
Not Connected to {v}{r}
"; // {c=class} {v=ssid} {r=status_off} +const char HTTP_STATUS_OFFPW[] PROGMEM = "
Authentication Failure"; // STATION_WRONG_PASSWORD, no eps32 +const char HTTP_STATUS_OFFNOAP[] PROGMEM = "
AP not found"; // WL_NO_SSID_AVAIL +const char HTTP_STATUS_OFFFAIL[] PROGMEM = "
Could not Connect"; // WL_CONNECT_FAILED +const char HTTP_STATUS_NONE[] PROGMEM = "
No AP set
"; +const char HTTP_BR[] PROGMEM = "
"; + +const char HTTP_STYLE[] PROGMEM = ""; + +#ifndef WM_NOHELP +const char HTTP_HELP[] PROGMEM = + "

Available Pages


" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "" + "
PageFunction
/Menu page.
/wifiShow WiFi scan results and enter WiFi configuration.(/0wifi noscan)
/wifisaveSave WiFi configuration information and configure device. Needs variables supplied.
/paramParameter page
/infoInformation page
/uOTA Update
/closeClose the captiveportal popup,configportal will remain active
/exitExit Config Portal, configportal will close
/restartReboot the device
/eraseErase WiFi configuration and reboot Device. Device will not reconnect to a network until new WiFi configuration data is entered.
" + "

Github https://github.com/tzapu/WiFiManager."; +#else +const char HTTP_HELP[] PROGMEM = ""; +#endif + +const char HTTP_UPDATE[] PROGMEM = "Upload New Firmware

* May not function inside captive portal, Open in browser http://192.168.4.1"; +const char HTTP_UPDATE_FAIL[] PROGMEM = "
Update Failed!
Reboot device and try again
"; +const char HTTP_UPDATE_SUCCESS[] PROGMEM = "
Update Successful.
Device Rebooting now...
"; + +#ifdef WM_JSTEST +const char HTTP_JS[] PROGMEM = +""; +#endif + +// Info html +// @todo remove html elements from progmem, repetetive strings +#ifdef ESP32 + const char HTTP_INFO_esphead[] PROGMEM = "

esp32


"; + const char HTTP_INFO_chiprev[] PROGMEM = "
Chip Rev
{1}
"; + const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
CPU0: {1}
CPU1: {2}
"; + const char HTTP_INFO_aphost[] PROGMEM = "
Access Point Hostname
{1}
"; + const char HTTP_INFO_psrsize[] PROGMEM = "
PSRAM Size
{1} bytes
"; + const char HTTP_INFO_temp[] PROGMEM = "
Temperature
{1} C° / {2} F°
Hall
{3}
"; +#else + const char HTTP_INFO_esphead[] PROGMEM = "

esp8266


"; + const char HTTP_INFO_fchipid[] PROGMEM = "
Flash Chip ID
{1}
"; + const char HTTP_INFO_corever[] PROGMEM = "
Core Version
{1}
"; + const char HTTP_INFO_bootver[] PROGMEM = "
Boot Version
{1}
"; + const char HTTP_INFO_lastreset[] PROGMEM = "
Last reset reason
{1}
"; + const char HTTP_INFO_flashsize[] PROGMEM = "
Real Flash Size
{1} bytes
"; +#endif + +const char HTTP_INFO_memsmeter[] PROGMEM = "
"; +const char HTTP_INFO_memsketch[] PROGMEM = "
Memory - Sketch Size
Used / Total bytes
{1} / {2}"; +const char HTTP_INFO_freeheap[] PROGMEM = "
Memory - Free Heap
{1} bytes available
"; +const char HTTP_INFO_wifihead[] PROGMEM = "

WiFi


"; +const char HTTP_INFO_uptime[] PROGMEM = "
Uptime
{1} Mins {2} Secs
"; +const char HTTP_INFO_chipid[] PROGMEM = "
Chip ID
{1}
"; +const char HTTP_INFO_idesize[] PROGMEM = "
Flash Size
{1} bytes
"; +const char HTTP_INFO_sdkver[] PROGMEM = "
SDK Version
{1}
"; +const char HTTP_INFO_cpufreq[] PROGMEM = "
CPU Frequency
{1}MHz
"; +const char HTTP_INFO_apip[] PROGMEM = "
Access Point IP
{1}
"; +const char HTTP_INFO_apmac[] PROGMEM = "
Access Point MAC
{1}
"; +const char HTTP_INFO_apssid[] PROGMEM = "
Access Point SSID
{1}
"; +const char HTTP_INFO_apbssid[] PROGMEM = "
BSSID
{1}
"; +const char HTTP_INFO_stassid[] PROGMEM = "
Station SSID
{1}
"; +const char HTTP_INFO_staip[] PROGMEM = "
Station IP
{1}
"; +const char HTTP_INFO_stagw[] PROGMEM = "
Station Gateway
{1}
"; +const char HTTP_INFO_stasub[] PROGMEM = "
Station Subnet
{1}
"; +const char HTTP_INFO_dnss[] PROGMEM = "
DNS Server
{1}
"; +const char HTTP_INFO_host[] PROGMEM = "
Hostname
{1}
"; +const char HTTP_INFO_stamac[] PROGMEM = "
Station MAC
{1}
"; +const char HTTP_INFO_conx[] PROGMEM = "
Connected
{1}
"; +const char HTTP_INFO_autoconx[] PROGMEM = "
Autoconnect
{1}
"; + +const char HTTP_INFO_aboutver[] PROGMEM = "
WiFiManager
{1}
"; +const char HTTP_INFO_aboutarduino[] PROGMEM = "
Arduino
{1}
"; +const char HTTP_INFO_aboutsdk[] PROGMEM = "
ESP-SDK/IDF
{1}
"; +const char HTTP_INFO_aboutdate[] PROGMEM = "
Build Date
{1}
"; + +const char S_brand[] PROGMEM = "WiFiManager"; +const char S_debugPrefix[] PROGMEM = "*wm:"; +const char S_y[] PROGMEM = "Yes"; +const char S_n[] PROGMEM = "No"; +const char S_enable[] PROGMEM = "Enabled"; +const char S_disable[] PROGMEM = "Disabled"; +const char S_GET[] PROGMEM = "GET"; +const char S_POST[] PROGMEM = "POST"; +const char S_NA[] PROGMEM = "Unknown"; +const char S_passph[] PROGMEM = "********"; +const char S_titlewifisaved[] PROGMEM = "Credentials Saved"; +const char S_titlewifisettings[] PROGMEM = "Settings Saved"; +const char S_titlewifi[] PROGMEM = "Config ESP"; +const char S_titleinfo[] PROGMEM = "Info"; +const char S_titleparam[] PROGMEM = "Setup"; +const char S_titleparamsaved[] PROGMEM = "Setup Saved"; +const char S_titleexit[] PROGMEM = "Exit"; +const char S_titlereset[] PROGMEM = "Reset"; +const char S_titleerase[] PROGMEM = "Erase"; +const char S_titleclose[] PROGMEM = "Close"; +const char S_options[] PROGMEM = "options"; +const char S_nonetworks[] PROGMEM = "No networks found. Refresh to scan again."; +const char S_staticip[] PROGMEM = "Static IP"; +const char S_staticgw[] PROGMEM = "Static Gateway"; +const char S_staticdns[] PROGMEM = "Static DNS"; +const char S_subnet[] PROGMEM = "Subnet"; +const char S_exiting[] PROGMEM = "Exiting"; +const char S_resetting[] PROGMEM = "Module will reset in a few seconds."; +const char S_closing[] PROGMEM = "You can close the page, portal will continue to run"; +const char S_error[] PROGMEM = "An Error Occured"; +const char S_notfound[] PROGMEM = "File Not Found\n\n"; +const char S_uri[] PROGMEM = "URI: "; +const char S_method[] PROGMEM = "\nMethod: "; +const char S_args[] PROGMEM = "\nArguments: "; +const char S_parampre[] PROGMEM = "param_"; + +// debug strings +const char D_HR[] PROGMEM = "--------------------"; + +// END WIFI_MANAGER_OVERRIDE_STRINGS +#endif + +// ----------------------------------------------------------------------------------------------- +// DO NOT EDIT BELOW THIS LINE + +const uint8_t _nummenutokens = 11; +const char * const _menutokens[_nummenutokens] PROGMEM = { + "wifi", + "wifinoscan", + "info", + "param", + "close", + "restart", + "exit", + "erase", + "update", + "sep", + "custom" +}; + +const char R_root[] PROGMEM = "/"; +const char R_wifi[] PROGMEM = "/wifi"; +const char R_wifinoscan[] PROGMEM = "/0wifi"; +const char R_wifisave[] PROGMEM = "/wifisave"; +const char R_info[] PROGMEM = "/info"; +const char R_param[] PROGMEM = "/param"; +const char R_paramsave[] PROGMEM = "/paramsave"; +const char R_restart[] PROGMEM = "/restart"; +const char R_exit[] PROGMEM = "/exit"; +const char R_close[] PROGMEM = "/close"; +const char R_erase[] PROGMEM = "/erase"; +const char R_status[] PROGMEM = "/status"; +const char R_update[] PROGMEM = "/update"; +const char R_updatedone[] PROGMEM = "/u"; + + +//Strings +const char S_ip[] PROGMEM = "ip"; +const char S_gw[] PROGMEM = "gw"; +const char S_sn[] PROGMEM = "sn"; +const char S_dns[] PROGMEM = "dns"; + +// softap ssid default prefix +#ifdef ESP8266 + const char S_ssidpre[] PROGMEM = "ESP"; +#elif defined(ESP32) + const char S_ssidpre[] PROGMEM = "ESP32"; +#else + const char S_ssidpre[] PROGMEM = "WM"; +#endif + +//Tokens +//@todo consolidate and reduce +const char T_ss[] PROGMEM = "{"; // token start sentinel +const char T_es[] PROGMEM = "}"; // token end sentinel +const char T_1[] PROGMEM = "{1}"; // @token 1 +const char T_2[] PROGMEM = "{2}"; // @token 2 +const char T_3[] PROGMEM = "{3}"; // @token 2 +const char T_v[] PROGMEM = "{v}"; // @token v +const char T_V[] PROGMEM = "{V}"; // @token v +const char T_I[] PROGMEM = "{I}"; // @token I +const char T_i[] PROGMEM = "{i}"; // @token i +const char T_n[] PROGMEM = "{n}"; // @token n +const char T_p[] PROGMEM = "{p}"; // @token p +const char T_t[] PROGMEM = "{t}"; // @token t +const char T_l[] PROGMEM = "{l}"; // @token l +const char T_c[] PROGMEM = "{c}"; // @token c +const char T_e[] PROGMEM = "{e}"; // @token e +const char T_q[] PROGMEM = "{q}"; // @token q +const char T_r[] PROGMEM = "{r}"; // @token r +const char T_R[] PROGMEM = "{R}"; // @token R +const char T_h[] PROGMEM = "{h}"; // @token h + +// http +const char HTTP_HEAD_CL[] PROGMEM = "Content-Length"; +const char HTTP_HEAD_CT[] PROGMEM = "text/html"; +const char HTTP_HEAD_CT2[] PROGMEM = "text/plain"; +const char HTTP_HEAD_CORS[] PROGMEM = "Access-Control-Allow-Origin"; +const char HTTP_HEAD_CORS_ALLOW_ALL[] PROGMEM = "*"; + +const char * const WIFI_STA_STATUS[] PROGMEM +{ + "WL_IDLE_STATUS", // 0 STATION_IDLE + "WL_NO_SSID_AVAIL", // 1 STATION_NO_AP_FOUND + "WL_SCAN_COMPLETED", // 2 + "WL_CONNECTED", // 3 STATION_GOT_IP + "WL_CONNECT_FAILED", // 4 STATION_CONNECT_FAIL, STATION_WRONG_PASSWORD(NI) + "WL_CONNECTION_LOST", // 5 + "WL_DISCONNECTED", // 6 + "WL_STATION_WRONG_PASSWORD" // 7 KLUDGE +}; + +#ifdef ESP32 +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "OPEN", + "WEP", + "WPA_PSK", + "WPA2_PSK", + "WPA_WPA2_PSK", + "WPA2_ENTERPRISE", + "MAX" +}; +#elif defined(ESP8266) +const char * const AUTH_MODE_NAMES[] PROGMEM +{ + "", + "", + "WPA_PSK", // 2 ENC_TYPE_TKIP + "", + "WPA2_PSK", // 4 ENC_TYPE_CCMP + "WEP", // 5 ENC_TYPE_WEP + "", + "OPEN", //7 ENC_TYPE_NONE + "WPA_WPA2_PSK", // 8 ENC_TYPE_AUTO +}; +#endif + +const char* const WIFI_MODES[] PROGMEM = { "NULL", "STA", "AP", "STA+AP" }; + + +#ifdef ESP32 +// as 2.5.2 +// typedef struct { +// char cc[3]; /**< country code string */ +// uint8_t schan; /**< start channel */ +// uint8_t nchan; /**< total channel number */ +// int8_t max_tx_power; /**< This field is used for getting WiFi maximum transmitting power, call esp_wifi_set_max_tx_power to set the maximum transmitting power. */ +// wifi_country_policy_t policy; /**< country policy */ +// } wifi_country_t; +const wifi_country_t WM_COUNTRY_US{"US",1,11,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,CONFIG_ESP32_PHY_MAX_WIFI_TX_POWER,WIFI_COUNTRY_POLICY_AUTO}; +#elif defined(ESP8266) && !defined(WM_NOCOUNTRY) +// typedef struct { +// char cc[3]; /**< country code string */ +// uint8_t schan; /**< start channel */ +// uint8_t nchan; /**< total channel number */ +// uint8_t policy; /**< country policy */ +// } wifi_country_t; +const wifi_country_t WM_COUNTRY_US{"US",1,11,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_CN{"CN",1,13,WIFI_COUNTRY_POLICY_AUTO}; +const wifi_country_t WM_COUNTRY_JP{"JP",1,14,WIFI_COUNTRY_POLICY_AUTO}; +#endif + + +/* +* ESP32 WiFi Events + +0 SYSTEM_EVENT_WIFI_READY < ESP32 WiFi ready +1 SYSTEM_EVENT_SCAN_DONE < ESP32 finish scanning AP +2 SYSTEM_EVENT_STA_START < ESP32 station start +3 SYSTEM_EVENT_STA_STOP < ESP32 station stop +4 SYSTEM_EVENT_STA_CONNECTED < ESP32 station connected to AP +5 SYSTEM_EVENT_STA_DISCONNECTED < ESP32 station disconnected from AP +6 SYSTEM_EVENT_STA_AUTHMODE_CHANGE < the auth mode of AP connected by ESP32 station changed +7 SYSTEM_EVENT_STA_GOT_IP < ESP32 station got IP from connected AP +8 SYSTEM_EVENT_STA_LOST_IP < ESP32 station lost IP and the IP is reset to 0 +9 SYSTEM_EVENT_STA_WPS_ER_SUCCESS < ESP32 station wps succeeds in enrollee mode +10 SYSTEM_EVENT_STA_WPS_ER_FAILED < ESP32 station wps fails in enrollee mode +11 SYSTEM_EVENT_STA_WPS_ER_TIMEOUT < ESP32 station wps timeout in enrollee mode +12 SYSTEM_EVENT_STA_WPS_ER_PIN < ESP32 station wps pin code in enrollee mode +13 SYSTEM_EVENT_AP_START < ESP32 soft-AP start +14 SYSTEM_EVENT_AP_STOP < ESP32 soft-AP stop +15 SYSTEM_EVENT_AP_STACONNECTED < a station connected to ESP32 soft-AP +16 SYSTEM_EVENT_AP_STADISCONNECTED < a station disconnected from ESP32 soft-AP +17 SYSTEM_EVENT_AP_STAIPASSIGNED < ESP32 soft-AP assign an IP to a connected station +18 SYSTEM_EVENT_AP_PROBEREQRECVED < Receive probe request packet in soft-AP interface +19 SYSTEM_EVENT_GOT_IP6 < ESP32 station or ap or ethernet interface v6IP addr is preferred +20 SYSTEM_EVENT_ETH_START < ESP32 ethernet start +21 SYSTEM_EVENT_ETH_STOP < ESP32 ethernet stop +22 SYSTEM_EVENT_ETH_CONNECTED < ESP32 ethernet phy link up +23 SYSTEM_EVENT_ETH_DISCONNECTED < ESP32 ethernet phy link down +24 SYSTEM_EVENT_ETH_GOT_IP < ESP32 ethernet got IP from connected AP +25 SYSTEM_EVENT_MAX + + +typedef enum { + ARDUINO_EVENT_WIFI_READY = 0, + ARDUINO_EVENT_WIFI_SCAN_DONE, + ARDUINO_EVENT_WIFI_STA_START, + ARDUINO_EVENT_WIFI_STA_STOP, + ARDUINO_EVENT_WIFI_STA_CONNECTED, + ARDUINO_EVENT_WIFI_STA_DISCONNECTED, + ARDUINO_EVENT_WIFI_STA_AUTHMODE_CHANGE, + ARDUINO_EVENT_WIFI_STA_GOT_IP, + ARDUINO_EVENT_WIFI_STA_GOT_IP6, + ARDUINO_EVENT_WIFI_STA_LOST_IP, + ARDUINO_EVENT_WIFI_AP_START, + ARDUINO_EVENT_WIFI_AP_STOP, + ARDUINO_EVENT_WIFI_AP_STACONNECTED, + ARDUINO_EVENT_WIFI_AP_STADISCONNECTED, + ARDUINO_EVENT_WIFI_AP_STAIPASSIGNED, + ARDUINO_EVENT_WIFI_AP_PROBEREQRECVED, + ARDUINO_EVENT_WIFI_AP_GOT_IP6, + ARDUINO_EVENT_WIFI_FTM_REPORT, + ARDUINO_EVENT_ETH_START, + ARDUINO_EVENT_ETH_STOP, + ARDUINO_EVENT_ETH_CONNECTED, + ARDUINO_EVENT_ETH_DISCONNECTED, + ARDUINO_EVENT_ETH_GOT_IP, + ARDUINO_EVENT_ETH_GOT_IP6, + ARDUINO_EVENT_WPS_ER_SUCCESS, + ARDUINO_EVENT_WPS_ER_FAILED, + ARDUINO_EVENT_WPS_ER_TIMEOUT, + ARDUINO_EVENT_WPS_ER_PIN, + ARDUINO_EVENT_WPS_ER_PBC_OVERLAP, + ARDUINO_EVENT_SC_SCAN_DONE, + ARDUINO_EVENT_SC_FOUND_CHANNEL, + ARDUINO_EVENT_SC_GOT_SSID_PSWD, + ARDUINO_EVENT_SC_SEND_ACK_DONE, + ARDUINO_EVENT_PROV_INIT, + ARDUINO_EVENT_PROV_DEINIT, + ARDUINO_EVENT_PROV_START, + ARDUINO_EVENT_PROV_END, + ARDUINO_EVENT_PROV_CRED_RECV, + ARDUINO_EVENT_PROV_CRED_FAIL, + ARDUINO_EVENT_PROV_CRED_SUCCESS, + ARDUINO_EVENT_MAX +} arduino_event_id_t; + +typedef union { + wifi_event_sta_scan_done_t wifi_scan_done; + wifi_event_sta_authmode_change_t wifi_sta_authmode_change; + wifi_event_sta_connected_t wifi_sta_connected; + wifi_event_sta_disconnected_t wifi_sta_disconnected; + wifi_event_sta_wps_er_pin_t wps_er_pin; + wifi_event_sta_wps_fail_reason_t wps_fail_reason; + wifi_event_ap_probe_req_rx_t wifi_ap_probereqrecved; + wifi_event_ap_staconnected_t wifi_ap_staconnected; + wifi_event_ap_stadisconnected_t wifi_ap_stadisconnected; + wifi_event_ftm_report_t wifi_ftm_report; + ip_event_ap_staipassigned_t wifi_ap_staipassigned; + ip_event_got_ip_t got_ip; + ip_event_got_ip6_t got_ip6; + smartconfig_event_got_ssid_pswd_t sc_got_ssid_pswd; + esp_eth_handle_t eth_connected; + wifi_sta_config_t prov_cred_recv; + wifi_prov_sta_fail_reason_t prov_fail_reason; +} arduino_event_info_t; + +*/ +#endif diff --git a/firmware/libraries/WiFiManager/travis/common.sh b/firmware/libraries/WiFiManager/travis/common.sh old mode 100755 new mode 100644 index d115085..4b3e655 --- a/firmware/libraries/WiFiManager/travis/common.sh +++ b/firmware/libraries/WiFiManager/travis/common.sh @@ -2,6 +2,7 @@ function build_examples() { + excludes=("$@") # track the exit code for this platform local exit_code=0 # loop through results and add them to the array @@ -19,6 +20,14 @@ function build_examples() # store the filename for the example without the path local example_file=$(basename $example) + # skip files listed as excludes + for exclude in "${excludes[@]}"; do + if [ "${example_file}" == "${exclude}" ] ; then + echo ">>>>>>>>>>>>>>>>>>>>>>>> Skipping ${example_file} <<<<<<<<<<<<<<<<<<<<<<<<<<" + continue 2 + fi + done + echo "$example_file: " local sketch="$example_dir/$example_file" echo "$sketch" diff --git a/firmware/sensor_apds9930.ino b/firmware/sensor_apds9930.ino index 0917dd5..0790208 100644 --- a/firmware/sensor_apds9930.ino +++ b/firmware/sensor_apds9930.ino @@ -2,21 +2,30 @@ APDS9930 _sensor_apds9930 = APDS9930(); -bool sensor_apds9930_begin() { +bool sensor_apds9930_begin() +{ bool status = _sensor_apds9930.init(); - if (status) { + + if (status) + { _sensor_apds9930.enableLightSensor(false); debug("APDS9930 Connected"); + } else { debug("Could not find a valid APDS9930 sensor, check wiring!"); } + return status; } -float apds9930_light() { +float apds9930_light() +{ float ambient_light = 0; - if (_sensor_apds9930.readAmbientLightLux(ambient_light)) { + + if (_sensor_apds9930.readAmbientLightLux(ambient_light)) + { return ambient_light; + } else { return 0; } diff --git a/firmware/sensor_apds9960.ino b/firmware/sensor_apds9960.ino index b6ad2ab..ea0bd4a 100644 --- a/firmware/sensor_apds9960.ino +++ b/firmware/sensor_apds9960.ino @@ -2,26 +2,34 @@ Adafruit_APDS9960 _sensor_apds9960; -bool sensor_apds9960_begin() { +bool sensor_apds9960_begin() +{ bool status = _sensor_apds9960.begin(); - if (status) { + + if (status) + { _sensor_apds9960.enableColor(true); debug("APDS9960 Connected"); + } else { debug("Could not find a valid APDS9960 sensor, check wiring!"); } return status; } -float apds9960_light() { +float apds9960_light() +{ uint16_t red, green, blue, white, lux; - while(!_sensor_apds9960.colorDataReady()) { + while(!_sensor_apds9960.colorDataReady()) + { delay(5); } _sensor_apds9960.getColorData(&red, &green, &blue, &white); + //calculate lux lux = _sensor_apds9960.calculateLux(red, green, blue); + return lux * LIGHT_FACTOR; } diff --git a/firmware/sensor_bme280.ino b/firmware/sensor_bme280.ino index ae22d3f..0e9afeb 100644 --- a/firmware/sensor_bme280.ino +++ b/firmware/sensor_bme280.ino @@ -3,22 +3,32 @@ Adafruit_BME280 _sensor_bme280; -bool sensor_bme280_begin(uint8_t addr) { +bool sensor_bme280_begin(uint8_t addr) +{ bool status = _sensor_bme280.begin(addr); - if (status) { + + if (status) + { debug("BME280 Connected"); + } else { debug("Could not find a valid BME280 sensor, check wiring!"); } + return status; } -float bme280_temperature() { +float bme280_temperature() +{ return _sensor_bme280.readTemperature() * TEMP_FACTOR; } -float bme280_pressure() { + +float bme280_pressure() +{ return _sensor_bme280.readPressure() / 100.0F; } -float bme280_humidity() { + +float bme280_humidity() +{ return _sensor_bme280.readHumidity() * HUMIDITY_FACTOR; } diff --git a/firmware/sensor_bmp280.ino b/firmware/sensor_bmp280.ino new file mode 100644 index 0000000..f44acb2 --- /dev/null +++ b/firmware/sensor_bmp280.ino @@ -0,0 +1,46 @@ +#include // Install from library manager - sensor board info: https://www.bastelgarage.ch/bmp280-temperatur-luftdruck-sensor + +Adafruit_BMP280 _sensor_bmp280; +Adafruit_Sensor *_sensor_bmp280_temp = _sensor_bmp280.getTemperatureSensor(); +Adafruit_Sensor *_sensor_bmp280_pressure = _sensor_bmp280.getPressureSensor(); + +bool sensor_bmp280_begin(uint8_t addr) +{ + bool status = _sensor_bmp280.begin(addr); + + if (status) + { + debug("BMP280 Connected"); + + _sensor_bmp280.setSampling(Adafruit_BMP280::MODE_NORMAL, /* Operating Mode. */ + Adafruit_BMP280::SAMPLING_X2, /* Temp. oversampling */ + Adafruit_BMP280::SAMPLING_X16, /* Pressure oversampling */ + Adafruit_BMP280::FILTER_X16, /* Filtering. */ + Adafruit_BMP280::STANDBY_MS_500); /* Standby time. */ + + } else { + debug("Could not find a valid BMP280 sensor, check wiring or try a different address!"); + debug("SensorID was: " + String(_sensor_bmp280.sensorID())); + debug(" ID of 0xFF probably means a bad address, a BMP180 or BMP085"); + debug(" ID of 0x56-0x58 represents a BMP280,"); + debug(" ID of 0x60 represents a BME280,"); + debug(" ID of 0x61 represents a BME680."); + + } + + return status; +} + +float bmp280_temperature() +{ + sensors_event_t temp_event, pressure_event; + _sensor_bmp280_temp->getEvent(&temp_event); + return temp_event.temperature * TEMP_FACTOR; +} + +float bmp280_pressure() +{ + sensors_event_t pressure_event; + _sensor_bmp280_pressure->getEvent(&pressure_event); + return pressure_event.pressure; +} diff --git a/firmware/sensor_wind.ino b/firmware/sensor_wind.ino index f7cd6bd..4b366e0 100644 --- a/firmware/sensor_wind.ino +++ b/firmware/sensor_wind.ino @@ -2,33 +2,51 @@ #include "config_user.h" #include "config.h" -unsigned int anemometerRotations = 0; +volatile unsigned int anemometerRotations = 0; +uint32_t start_meas_wind_time = 0; +int interruptNumber; -ICACHE_RAM_ATTR void _anemometerInterrupt() +void ICACHE_RAM_ATTR _anemometerInterrupt() { anemometerRotations++; #ifdef DEBUG Serial.print("*"); + debug("*"); #endif } float wind_speed() { - anemometerRotations = 0; - - int interruptNumber = digitalPinToInterrupt(ANEMOMETER_PIN); - - attachInterrupt(interruptNumber, _anemometerInterrupt, RISING); - delay(1000 * WIND_SENSOR_MEAS_TIME_S); // time to measure - detachInterrupt(interruptNumber); - - // calculate the speed as km/h - float tmp_speed = (float)anemometerRotations * WINDSPEED_FACTOR; - -#ifdef DEBUG - Serial.print("Windspeed: " + String(tmp_speed)); -#endif - - return tmp_speed; - + start_measure_wind(); + do { + delay(1000); // minimum delay of measurement time is 1 second + } while (check_measure_wind_done() == false); + return measure_wind_result(); +} + +void start_measure_wind() +{ + start_meas_wind_time = millis(); + anemometerRotations = 0; + interruptNumber = digitalPinToInterrupt(ANEMOMETER_PIN); + attachInterrupt(interruptNumber, _anemometerInterrupt, FALLING); +} + +boolean check_measure_wind_done() +{ + if ((start_meas_wind_time + (WIND_SENSOR_MEAS_TIME_S * 1000)) <= millis()) + { + detachInterrupt(interruptNumber); + return true; + } + return false; +} + +float measure_wind_result() +{ + start_meas_wind_time = 0; +#ifdef DEBUG + debug("rotations = " + String((float)anemometerRotations)); +#endif + return (float)anemometerRotations * WINDSPEED_FACTOR; } diff --git a/firmware/webUpdater.ino b/firmware/webUpdater.ino index 25af4b7..40d4d84 100644 --- a/firmware/webUpdater.ino +++ b/firmware/webUpdater.ino @@ -11,30 +11,31 @@ #include #include -#include // WiFiManager from bib manager +#include // WiFiManager from bib manager by tzapu #include "config.h" #include "config_user.h" +//*************************************************************************// + ESP8266WebServer httpServer(WEB_UPDATER_HTTP_PORT); ESP8266HTTPUpdateServer httpUpdater; String _webUpdater_ip = "127.0.0.1"; String _webUpdater_dev = "unknown"; -float _webUpdater_sensValues[VALUES]; -String hb_ws_msg_start = "{"; -String hb_ws_msg_temp = "\"temperature\": "; -String hb_ws_msg_humi = "\"humidity\": "; -String hb_ws_msg_light = "\"lightlevel\": "; -String hb_ws_msg_windspeed = "\"windspeed\": "; -String hb_ws_msg_pressure = "\"pressure\": "; -String hb_ws_msg_timestamp = "\"timestamp\": "; -String hb_ws_msg_valid = "\"valid\": "; -String hb_ws_msg_end = "}"; +float _webUpdater_sensValues[VALUES]; + +#define TR_TD_START_STR "" +#define TR_TD_END_STR "" +#define TD_TD_MID_STR "" boolean wuValidData = false; +uint32_t _wifi_reconnect_cnt = 0; + +//*************************************************************************// + void setupWebUpdater(String device, String ip) { debug("Starting WebUpdater... " + ip); @@ -44,100 +45,154 @@ void setupWebUpdater(String device, String ip) httpUpdater.setup(&httpServer); httpServer.on("/", showHTMLMain); +#ifndef DISABLE_WIFIMANAGER httpServer.on("/resetWifiManager", resetWifiManager); +#endif #ifdef HOMEBRIDGE_WEBSTAT httpServer.on("/hbWebstat", hb_webstat_send); #endif #ifdef DEBUG_WINDSPEED_MEASUREMENT httpServer.on("/measWind", measureWindspeed); #endif - +#ifdef USE_LOGGER + httpServer.on("/showlog", showLog); +#endif httpServer.begin(); debug("HTTPUpdateServer ready!"); } +//*************************************************************************// + void doWebUpdater(void) { digitalWrite(D0, HIGH); httpServer.handleClient(); } +//*************************************************************************// +#ifdef SHOW_SENSOR_DATA_ON_WEBUPDATER_MAIN_PAGE +void sentWindspeed(float ws) +{ + _webUpdater_sensValues[SENSOR_WINDSPEED] = ws; +} +#endif + +void setWifiReconnectCnt(uint32_t wrc) +{ + _wifi_reconnect_cnt = wrc; +} + +#ifdef SHOW_SENSOR_DATA_ON_WEBUPDATER_MAIN_PAGE void setSensorData(float sensorValues[]) { for (uint8_t i = 0; i < 5 and wuValidData == false; i++) { - if (sensorValues[i] != 0) + if (sensorValues[i] != 0 and sensorValues[i] != nanf("no value") and (not isnan(sensorValues[i]))) { wuValidData = true; // at least one value is not zero, the data } } - for (uint8_t i = 0; i < VALUES; i++) { - _webUpdater_sensValues[i] = sensorValues[i]; + for (uint8_t i = 0; i < VALUES; i++) + { + if (sensorValues[i] != nanf("no value") and (not isnan(sensorValues[i]))) + { + // only copy real float values + //debug(String(i) + "=" + String(sensorValues[i])); + _webUpdater_sensValues[i] = sensorValues[i]; + } } } +#endif + +//*************************************************************************// void showHTMLMain(void) { String message = "OKO Weatherstation - " + String(_webUpdater_dev) + "" -"" -"" -"
firmware update

" -"" -"" -"" -"" -"" -"" -"" -"" -"" -"
temperature" + String(_webUpdater_sensValues[SENSOR_TEMPERATURE]) + "
humidity" + String(_webUpdater_sensValues[SENSOR_HUMIDITY]) + "
light" + String(_webUpdater_sensValues[SENSOR_LIGHT]) + "
windspeed" + String(_webUpdater_sensValues[SENSOR_WINDSPEED]) + "
pressure" + String(_webUpdater_sensValues[SENSOR_PRESSURE]) + "
batvoltage" + String(_webUpdater_sensValues[SENSOR_BAT_VOLTAGE]) + "
millis" + String(millis()) + "
valid" + String(wuValidData) + "
" -""; + "" + "" + "
firmware update

" +#ifdef USE_LOGGER + "
logfile
" +#endif +#ifdef DEBUG_WINDSPEED_MEASUREMENT + "
manual wind measurement
" +#endif +#ifdef HOMEBRIDGE_WEBSTAT + "
homebridge websatt
" +#endif +#ifdef SHOW_SENSOR_DATA_ON_WEBUPDATER_MAIN_PAGE + "

" + TR_TD_START_STR + "temperature" + TD_TD_MID_STR + String(_webUpdater_sensValues[SENSOR_TEMPERATURE]) + TR_TD_END_STR + TR_TD_START_STR + "humidity" + TD_TD_MID_STR + String(_webUpdater_sensValues[SENSOR_HUMIDITY]) + TR_TD_END_STR + TR_TD_START_STR + "light" + TD_TD_MID_STR + String(_webUpdater_sensValues[SENSOR_LIGHT]) + TR_TD_END_STR + TR_TD_START_STR + "windspeed" + TD_TD_MID_STR + String(_webUpdater_sensValues[SENSOR_WINDSPEED]) + TR_TD_END_STR + TR_TD_START_STR + "pressure" + TD_TD_MID_STR + String(_webUpdater_sensValues[SENSOR_PRESSURE]) + TR_TD_END_STR + TR_TD_START_STR + "batvoltage" + TD_TD_MID_STR + String(_webUpdater_sensValues[SENSOR_BAT_VOLTAGE]) + TR_TD_END_STR + TR_TD_START_STR + "millis" + TD_TD_MID_STR + String(millis()) + TR_TD_END_STR + TR_TD_START_STR + "valid" + TD_TD_MID_STR + String(wuValidData) + TR_TD_END_STR + TR_TD_START_STR + "wifi rssi" + TD_TD_MID_STR + WiFi.RSSI() + TR_TD_END_STR + TR_TD_START_STR + "wifi rec cnt" + TD_TD_MID_STR + String(_wifi_reconnect_cnt) + TR_TD_END_STR + "
" +#endif +#ifndef DISABLE_WIFIMANAGER + "




reset WiFi Manager
" +#endif + ""; httpServer.send(200, "text/html", message); } +//*************************************************************************// + +#ifdef HOMEBRIDGE_WEBSTAT void hb_webstat_send(void) { + String msg = hb_ws_msg_start + - hb_ws_msg_temp + - String(_webUpdater_sensValues[SENSOR_TEMPERATURE], 2) + - ", " + - hb_ws_msg_humi + - String(_webUpdater_sensValues[SENSOR_HUMIDITY], 2) + - ", " + - hb_ws_msg_light + - String(_webUpdater_sensValues[SENSOR_LIGHT], 0) + // The light level for the homebridge-http-lux2 plugin is only able to parse integer values - ", " + - hb_ws_msg_windspeed + - String(_webUpdater_sensValues[SENSOR_WINDSPEED], 2) + - ", " + - hb_ws_msg_pressure + - String(_webUpdater_sensValues[SENSOR_PRESSURE], 2) + - ", " + - hb_ws_msg_timestamp + - String(millis()) + - ", " + - hb_ws_msg_valid + - String(wuValidData) + - hb_ws_msg_end; + hb_ws_msg_temp + + String(_webUpdater_sensValues[SENSOR_TEMPERATURE], 2) + + ", " + + hb_ws_msg_humi + + String(_webUpdater_sensValues[SENSOR_HUMIDITY], 2) + + ", " + + hb_ws_msg_light + + String(_webUpdater_sensValues[SENSOR_LIGHT], 0) + // The light level for the homebridge-http-lux2 plugin is only able to parse integer values + ", " + + hb_ws_msg_windspeed + + String(_webUpdater_sensValues[SENSOR_WINDSPEED], 2) + + ", " + + hb_ws_msg_pressure + + String(_webUpdater_sensValues[SENSOR_PRESSURE], 2) + + ", " + + hb_ws_msg_timestamp + + String(millis()) + + ", " + + hb_ws_msg_valid + + String(wuValidData) + + hb_ws_msg_end; httpServer.send(200, "text/html", msg); } +#endif + +//*************************************************************************// + +#ifndef DISABLE_WIFIMANAGER void resetWifiManager() { - String message = "OKO Weatherstation - " + String(_webUpdater_dev) + "" -"" -"" -"Reset WifiManager config.
" -"Rebooting...
" -""; + String message = "OKO Weatherstation - " + String(_webUpdater_dev) + " - reset WiFi manager" + "" + "" + "Reset WifiManager config.
" + "Rebooting...
" + ""; httpServer.send(200, "text/html", message); @@ -151,6 +206,12 @@ void resetWifiManager() ESP.restart(); } +#endif + +//*************************************************************************// + +#ifdef DEBUG_WINDSPEED_MEASUREMENT +#ifdef SENSOR_WIND void measureWindspeed() { @@ -160,11 +221,59 @@ void measureWindspeed() float tmp_windspeed = wind_speed(); digitalWrite(STATUS_LED_PIN, LOW); - String message = "OKO Weatherstation - " + String(_webUpdater_dev) + "" -"" -"Windsensor measurement result: " + String(tmp_windspeed) + "
" -""; + String message = "OKO Weatherstation - " + String(_webUpdater_dev) + " - manual wind measurement" + "" + "Windsensor measurement result: " + String(tmp_windspeed) + "
" + ""; httpServer.send(200, "text/html", message); } +#endif +#endif + +//*************************************************************************// + +#ifdef USE_LOGGER + +#define LOGFILE_SIZE 25 + +String logfile[LOGFILE_SIZE]; + +uint16_t logger_pos = 0; + +void logdata(String s) +{ + logfile[logger_pos] = s; + logger_pos++; + + if (logger_pos > LOGFILE_SIZE -1) + { + for (uint16_t i = 1; i < LOGFILE_SIZE; i++) + { + logfile[i-1] = logfile[i]; // overwrite previous element with current element + } + logger_pos--; // reduce the position in the log + } +} + +void showLog() +{ + String message = "OKO Weatherstation - " + String(_webUpdater_dev) + " - logfile" + "" + "" + "Logfile data:
"; + + for (uint16_t lp = 0; lp < logger_pos; lp++) + { + message = message + logfile[lp] + "
"; + } + + message = message + ""; + + httpServer.send(200, "text/html", message); +} + +#endif + +//*************************************************************************// diff --git a/schematics/oko-weatherstation.kicad_prl b/schematics/oko-weatherstation.kicad_prl new file mode 100644 index 0000000..fe4fe61 --- /dev/null +++ b/schematics/oko-weatherstation.kicad_prl @@ -0,0 +1,75 @@ +{ + "board": { + "active_layer": 0, + "active_layer_preset": "", + "auto_track_width": true, + "hidden_nets": [], + "high_contrast_mode": 0, + "net_color_mode": 1, + "opacity": { + "pads": 1.0, + "tracks": 1.0, + "vias": 1.0, + "zones": 0.6 + }, + "ratsnest_display_mode": 0, + "selection_filter": { + "dimensions": true, + "footprints": true, + "graphics": true, + "keepouts": true, + "lockedItems": true, + "otherItems": true, + "pads": true, + "text": true, + "tracks": true, + "vias": true, + "zones": true + }, + "visible_items": [ + 0, + 1, + 2, + 3, + 4, + 5, + 8, + 9, + 10, + 11, + 12, + 13, + 14, + 15, + 16, + 17, + 18, + 19, + 20, + 21, + 22, + 23, + 24, + 25, + 26, + 27, + 28, + 29, + 30, + 32, + 33, + 34, + 35, + 36 + ], + "visible_layers": "fffffff_ffffffff", + "zone_display_mode": 0 + }, + "meta": { + "filename": "oko-weatherstation.kicad_prl", + "version": 3 + }, + "project": { + "files": [] + } +} diff --git a/schematics/oko-weatherstation.kicad_pro b/schematics/oko-weatherstation.kicad_pro new file mode 100644 index 0000000..3faac1f --- /dev/null +++ b/schematics/oko-weatherstation.kicad_pro @@ -0,0 +1,325 @@ +{ + "board": { + "design_settings": { + "defaults": { + "board_outline_line_width": 0.1, + "copper_line_width": 0.2, + "copper_text_size_h": 1.5, + "copper_text_size_v": 1.5, + "copper_text_thickness": 0.3, + "other_line_width": 0.15, + "silk_line_width": 0.15, + "silk_text_size_h": 1.0, + "silk_text_size_v": 1.0, + "silk_text_thickness": 0.15 + }, + "diff_pair_dimensions": [], + "drc_exclusions": [], + "rules": { + "solder_mask_clearance": 0.0, + "solder_mask_min_width": 0.0 + }, + "track_widths": [], + "via_dimensions": [] + }, + "layer_presets": [] + }, + "boards": [], + "cvpcb": { + "equivalence_files": [] + }, + "erc": { + "erc_exclusions": [], + "meta": { + "version": 0 + }, + "pin_map": [ + [ + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 2 + ], + [ + 0, + 2, + 0, + 1, + 0, + 0, + 1, + 0, + 2, + 2, + 2, + 2 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 1, + 0, + 1, + 2 + ], + [ + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 1, + 2, + 1, + 1, + 2 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 2 + ], + [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 2 + ], + [ + 1, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 1, + 1, + 1, + 2 + ], + [ + 0, + 0, + 0, + 1, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 2 + ], + [ + 0, + 2, + 1, + 2, + 0, + 0, + 1, + 0, + 2, + 2, + 2, + 2 + ], + [ + 0, + 2, + 0, + 1, + 0, + 0, + 1, + 0, + 2, + 0, + 0, + 2 + ], + [ + 0, + 2, + 1, + 1, + 0, + 0, + 1, + 0, + 2, + 0, + 0, + 2 + ], + [ + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2, + 2 + ] + ], + "rule_severities": { + "bus_definition_conflict": "error", + "bus_entry_needed": "error", + "bus_label_syntax": "error", + "bus_to_bus_conflict": "error", + "bus_to_net_conflict": "error", + "different_unit_footprint": "error", + "different_unit_net": "error", + "duplicate_reference": "error", + "duplicate_sheet_names": "error", + "extra_units": "error", + "global_label_dangling": "warning", + "hier_label_mismatch": "error", + "label_dangling": "error", + "lib_symbol_issues": "warning", + "multiple_net_names": "warning", + "net_not_bus_member": "warning", + "no_connect_connected": "warning", + "no_connect_dangling": "warning", + "pin_not_connected": "error", + "pin_not_driven": "error", + "pin_to_pin": "warning", + "power_pin_not_driven": "error", + "similar_labels": "warning", + "unannotated": "error", + "unit_value_mismatch": "error", + "unresolved_variable": "error", + "wire_dangling": "error" + } + }, + "libraries": { + "pinned_footprint_libs": [], + "pinned_symbol_libs": [] + }, + "meta": { + "filename": "oko-weatherstation.kicad_pro", + "version": 1 + }, + "net_settings": { + "classes": [ + { + "bus_width": 12.0, + "clearance": 0.2, + "diff_pair_gap": 0.25, + "diff_pair_via_gap": 0.25, + "diff_pair_width": 0.2, + "line_style": 0, + "microvia_diameter": 0.3, + "microvia_drill": 0.1, + "name": "Default", + "pcb_color": "rgba(0, 0, 0, 0.000)", + "schematic_color": "rgba(0, 0, 0, 0.000)", + "track_width": 0.25, + "via_diameter": 0.8, + "via_drill": 0.4, + "wire_width": 6.0 + } + ], + "meta": { + "version": 2 + }, + "net_colors": null + }, + "pcbnew": { + "last_paths": { + "gencad": "", + "idf": "", + "netlist": "", + "specctra_dsn": "", + "step": "", + "vrml": "" + }, + "page_layout_descr_file": "" + }, + "schematic": { + "annotate_start_num": 0, + "drawing": { + "default_line_thickness": 6.0, + "default_text_size": 50.0, + "field_names": [], + "intersheets_ref_own_page": false, + "intersheets_ref_prefix": "", + "intersheets_ref_short": false, + "intersheets_ref_show": false, + "intersheets_ref_suffix": "", + "junction_size_choice": 3, + "label_size_ratio": 0.25, + "pin_symbol_size": 0.0, + "text_offset_ratio": 0.08 + }, + "legacy_lib_dir": "", + "legacy_lib_list": [], + "meta": { + "version": 1 + }, + "net_format_name": "", + "ngspice": { + "fix_include_paths": true, + "fix_passive_vals": false, + "meta": { + "version": 0 + }, + "model_mode": 0, + "workbook_filename": "" + }, + "page_layout_descr_file": "", + "plot_directory": "", + "spice_adjust_passive_values": false, + "spice_external_command": "spice \"%I\"", + "subpart_first_id": 65, + "subpart_id_separator": 0 + }, + "sheets": [ + [ + "3172f2e2-18d2-4a80-ae30-5707b3409798", + "" + ] + ], + "text_variables": {} +} diff --git a/schematics/oko-weatherstation.kicad_sch b/schematics/oko-weatherstation.kicad_sch new file mode 100644 index 0000000..bfb00be --- /dev/null +++ b/schematics/oko-weatherstation.kicad_sch @@ -0,0 +1,1633 @@ +(kicad_sch (version 20211123) (generator eeschema) + + (uuid 3172f2e2-18d2-4a80-ae30-5707b3409798) + + (paper "A4") + + (lib_symbols + (symbol "Connector_Generic:Conn_01x01" (pin_names (offset 1.016) hide) (in_bom yes) (on_board yes) + (property "Reference" "J" (id 0) (at 0 2.54 0) + (effects (font (size 1.27 1.27))) + ) + (property "Value" "Conn_01x01" (id 1) (at 0 -2.54 0) + (effects (font (size 1.27 1.27))) + ) + (property "Footprint" "" (id 2) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_keywords" "connector" (id 4) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_description" "Generic connector, single row, 01x01, script generated (kicad-library-utils/schlib/autogen/connector/)" (id 5) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_fp_filters" "Connector*:*_1x??_*" (id 6) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (symbol "Conn_01x01_1_1" + (rectangle (start -1.27 0.127) (end 0 -0.127) + (stroke (width 0.1524) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + (rectangle (start -1.27 1.27) (end 1.27 -1.27) + (stroke (width 0.254) (type default) (color 0 0 0 0)) + (fill (type background)) + ) + (pin passive line (at -5.08 0 0) (length 3.81) + (name "Pin_1" (effects (font (size 1.27 1.27)))) + (number "1" (effects (font (size 1.27 1.27)))) + ) + ) + ) + (symbol "Connector_Generic:Conn_01x06" (pin_names (offset 1.016) hide) (in_bom yes) (on_board yes) + (property "Reference" "J" (id 0) (at 0 7.62 0) + (effects (font (size 1.27 1.27))) + ) + (property "Value" "Conn_01x06" (id 1) (at 0 -10.16 0) + (effects (font (size 1.27 1.27))) + ) + (property "Footprint" "" (id 2) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_keywords" "connector" (id 4) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_description" "Generic connector, single row, 01x06, script generated (kicad-library-utils/schlib/autogen/connector/)" (id 5) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_fp_filters" "Connector*:*_1x??_*" (id 6) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (symbol "Conn_01x06_1_1" + (rectangle (start -1.27 -7.493) (end 0 -7.747) + (stroke (width 0.1524) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + (rectangle (start -1.27 -4.953) (end 0 -5.207) + (stroke (width 0.1524) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + (rectangle (start -1.27 -2.413) (end 0 -2.667) + (stroke (width 0.1524) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + (rectangle (start -1.27 0.127) (end 0 -0.127) + (stroke (width 0.1524) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + (rectangle (start -1.27 2.667) (end 0 2.413) + (stroke (width 0.1524) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + (rectangle (start -1.27 5.207) (end 0 4.953) + (stroke (width 0.1524) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + (rectangle (start -1.27 6.35) (end 1.27 -8.89) + (stroke (width 0.254) (type default) (color 0 0 0 0)) + (fill (type background)) + ) + (pin passive line (at -5.08 5.08 0) (length 3.81) + (name "Pin_1" (effects (font (size 1.27 1.27)))) + (number "1" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at -5.08 2.54 0) (length 3.81) + (name "Pin_2" (effects (font (size 1.27 1.27)))) + (number "2" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at -5.08 0 0) (length 3.81) + (name "Pin_3" (effects (font (size 1.27 1.27)))) + (number "3" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at -5.08 -2.54 0) (length 3.81) + (name "Pin_4" (effects (font (size 1.27 1.27)))) + (number "4" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at -5.08 -5.08 0) (length 3.81) + (name "Pin_5" (effects (font (size 1.27 1.27)))) + (number "5" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at -5.08 -7.62 0) (length 3.81) + (name "Pin_6" (effects (font (size 1.27 1.27)))) + (number "6" (effects (font (size 1.27 1.27)))) + ) + ) + ) + (symbol "Device:C" (pin_numbers hide) (pin_names (offset 0.254)) (in_bom yes) (on_board yes) + (property "Reference" "C" (id 0) (at 0.635 2.54 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "C" (id 1) (at 0.635 -2.54 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 0.9652 -3.81 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_keywords" "cap capacitor" (id 4) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_description" "Unpolarized capacitor" (id 5) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_fp_filters" "C_*" (id 6) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (symbol "C_0_1" + (polyline + (pts + (xy -2.032 -0.762) + (xy 2.032 -0.762) + ) + (stroke (width 0.508) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + (polyline + (pts + (xy -2.032 0.762) + (xy 2.032 0.762) + ) + (stroke (width 0.508) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + ) + (symbol "C_1_1" + (pin passive line (at 0 3.81 270) (length 2.794) + (name "~" (effects (font (size 1.27 1.27)))) + (number "1" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at 0 -3.81 90) (length 2.794) + (name "~" (effects (font (size 1.27 1.27)))) + (number "2" (effects (font (size 1.27 1.27)))) + ) + ) + ) + (symbol "Device:R" (pin_numbers hide) (pin_names (offset 0)) (in_bom yes) (on_board yes) + (property "Reference" "R" (id 0) (at 2.032 0 90) + (effects (font (size 1.27 1.27))) + ) + (property "Value" "R" (id 1) (at 0 0 90) + (effects (font (size 1.27 1.27))) + ) + (property "Footprint" "" (id 2) (at -1.778 0 90) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_keywords" "R res resistor" (id 4) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_description" "Resistor" (id 5) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "ki_fp_filters" "R_*" (id 6) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (symbol "R_0_1" + (rectangle (start -1.016 -2.54) (end 1.016 2.54) + (stroke (width 0.254) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + ) + (symbol "R_1_1" + (pin passive line (at 0 3.81 270) (length 1.27) + (name "~" (effects (font (size 1.27 1.27)))) + (number "1" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at 0 -3.81 90) (length 1.27) + (name "~" (effects (font (size 1.27 1.27)))) + (number "2" (effects (font (size 1.27 1.27)))) + ) + ) + ) + (symbol "oko-weatherstation-rescue:GY-BME280-oko" (pin_names (offset 1.016)) (in_bom yes) (on_board yes) + (property "Reference" "U" (id 0) (at 0 -7.62 0) + (effects (font (size 1.27 1.27))) + ) + (property "Value" "GY-BME280-oko" (id 1) (at 0 0 90) + (effects (font (size 1.27 1.27))) + ) + (property "Footprint" "" (id 2) (at 0 -2.54 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "" (id 3) (at 0 -2.54 0) + (effects (font (size 1.27 1.27)) hide) + ) + (symbol "GY-BME280-oko_0_1" + (rectangle (start -1.27 6.35) (end 6.35 -8.89) + (stroke (width 0) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + ) + (symbol "GY-BME280-oko_1_1" + (pin bidirectional line (at 8.89 -7.62 180) (length 2.54) + (name "SDO" (effects (font (size 1.27 1.27)))) + (number "1" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 8.89 -5.08 180) (length 2.54) + (name "CSB" (effects (font (size 1.27 1.27)))) + (number "2" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 8.89 -2.54 180) (length 2.54) + (name "SDA" (effects (font (size 1.27 1.27)))) + (number "3" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 8.89 0 180) (length 2.54) + (name "SCL" (effects (font (size 1.27 1.27)))) + (number "4" (effects (font (size 1.27 1.27)))) + ) + (pin unspecified line (at 8.89 2.54 180) (length 2.54) + (name "GND" (effects (font (size 1.27 1.27)))) + (number "5" (effects (font (size 1.27 1.27)))) + ) + (pin unspecified line (at 8.89 5.08 180) (length 2.54) + (name "VCC" (effects (font (size 1.27 1.27)))) + (number "6" (effects (font (size 1.27 1.27)))) + ) + ) + ) + (symbol "oko:03962A" (pin_names (offset 1.016)) (in_bom yes) (on_board yes) + (property "Reference" "U" (id 0) (at 1.27 -11.43 0) + (effects (font (size 1.27 1.27))) + ) + (property "Value" "03962A" (id 1) (at -6.35 6.35 0) + (effects (font (size 1.27 1.27))) + ) + (property "Footprint" "" (id 2) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "" (id 3) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (symbol "03962A_0_1" + (rectangle (start -16.51 7.62) (end 2.54 -8.89) + (stroke (width 0) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + ) + (symbol "03962A_1_1" + (pin passive line (at -19.05 2.54 0) (length 2.54) + (name "VCC_IN" (effects (font (size 1.27 1.27)))) + (number "1" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at 5.08 -3.81 180) (length 2.54) + (name "VCC_OUT" (effects (font (size 1.27 1.27)))) + (number "2" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at 5.08 2.54 180) (length 2.54) + (name "VCC_BAT" (effects (font (size 1.27 1.27)))) + (number "3" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at 5.08 0 180) (length 2.54) + (name "GND_BAT" (effects (font (size 1.27 1.27)))) + (number "4" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at 5.08 -6.35 180) (length 2.54) + (name "GND_OUT" (effects (font (size 1.27 1.27)))) + (number "5" (effects (font (size 1.27 1.27)))) + ) + (pin passive line (at -19.05 0 0) (length 2.54) + (name "GND_IN" (effects (font (size 1.27 1.27)))) + (number "6" (effects (font (size 1.27 1.27)))) + ) + ) + ) + (symbol "oko:APDS-9900" (pin_names (offset 1.016)) (in_bom yes) (on_board yes) + (property "Reference" "U" (id 0) (at 0 -11.43 0) + (effects (font (size 1.27 1.27))) + ) + (property "Value" "APDS-9900" (id 1) (at 0 -2.54 90) + (effects (font (size 1.27 1.27))) + ) + (property "Footprint" "" (id 2) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "" (id 3) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + (symbol "APDS-9900_0_1" + (rectangle (start -1.27 5.08) (end 6.35 -10.16) + (stroke (width 0) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + ) + (symbol "APDS-9900_1_1" + (pin bidirectional line (at 8.89 -8.89 180) (length 2.54) + (name "VL" (effects (font (size 1.27 1.27)))) + (number "1" (effects (font (size 1.27 1.27)))) + ) + (pin unspecified line (at 8.89 -6.35 180) (length 2.54) + (name "GND" (effects (font (size 1.27 1.27)))) + (number "2" (effects (font (size 1.27 1.27)))) + ) + (pin unspecified line (at 8.89 -3.81 180) (length 2.54) + (name "VCC" (effects (font (size 1.27 1.27)))) + (number "3" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 8.89 -1.27 180) (length 2.54) + (name "SDA" (effects (font (size 1.27 1.27)))) + (number "4" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 8.89 1.27 180) (length 2.54) + (name "SCL" (effects (font (size 1.27 1.27)))) + (number "5" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 8.89 3.81 180) (length 2.54) + (name "INT" (effects (font (size 1.27 1.27)))) + (number "6" (effects (font (size 1.27 1.27)))) + ) + ) + ) + (symbol "wemos_mini:WeMos_mini" (pin_names (offset 1.016)) (in_bom yes) (on_board yes) + (property "Reference" "U" (id 0) (at 0 12.7 0) + (effects (font (size 1.524 1.524))) + ) + (property "Value" "WeMos_mini" (id 1) (at 0 -12.7 0) + (effects (font (size 1.524 1.524))) + ) + (property "Footprint" "" (id 2) (at 13.97 -17.78 0) + (effects (font (size 1.524 1.524))) + ) + (property "Datasheet" "" (id 3) (at 13.97 -17.78 0) + (effects (font (size 1.524 1.524))) + ) + (symbol "WeMos_mini_0_1" + (rectangle (start -7.62 11.43) (end 7.62 -13.97) + (stroke (width 0) (type default) (color 0 0 0 0)) + (fill (type none)) + ) + ) + (symbol "WeMos_mini_1_1" + (pin power_in line (at -12.7 8.89 0) (length 5.08) + (name "5V" (effects (font (size 1.27 1.27)))) + (number "1" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 12.7 -6.35 180) (length 5.08) + (name "A0" (effects (font (size 1.27 1.27)))) + (number "10" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 12.7 -3.81 180) (length 5.08) + (name "D0" (effects (font (size 1.27 1.27)))) + (number "11" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 12.7 -1.27 180) (length 5.08) + (name "D5" (effects (font (size 1.27 1.27)))) + (number "12" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 12.7 1.27 180) (length 5.08) + (name "D6" (effects (font (size 1.27 1.27)))) + (number "13" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 12.7 3.81 180) (length 5.08) + (name "D7" (effects (font (size 1.27 1.27)))) + (number "14" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 12.7 6.35 180) (length 5.08) + (name "D8" (effects (font (size 1.27 1.27)))) + (number "15" (effects (font (size 1.27 1.27)))) + ) + (pin power_out line (at 12.7 8.89 180) (length 5.08) + (name "3.3V" (effects (font (size 1.27 1.27)))) + (number "16" (effects (font (size 1.27 1.27)))) + ) + (pin power_in line (at -12.7 6.35 0) (length 5.08) + (name "GND" (effects (font (size 1.27 1.27)))) + (number "2" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at -12.7 3.81 0) (length 5.08) + (name "D4" (effects (font (size 1.27 1.27)))) + (number "3" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at -12.7 1.27 0) (length 5.08) + (name "D3" (effects (font (size 1.27 1.27)))) + (number "4" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at -12.7 -1.27 0) (length 5.08) + (name "D2" (effects (font (size 1.27 1.27)))) + (number "5" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at -12.7 -3.81 0) (length 5.08) + (name "D1" (effects (font (size 1.27 1.27)))) + (number "6" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at -12.7 -6.35 0) (length 5.08) + (name "Rx" (effects (font (size 1.27 1.27)))) + (number "7" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at -12.7 -8.89 0) (length 5.08) + (name "Tx" (effects (font (size 1.27 1.27)))) + (number "8" (effects (font (size 1.27 1.27)))) + ) + (pin bidirectional line (at 12.7 -8.89 180) (length 5.08) + (name "Rst" (effects (font (size 1.27 1.27)))) + (number "9" (effects (font (size 1.27 1.27)))) + ) + ) + ) + ) + + (junction (at 194.31 95.25) (diameter 0) (color 0 0 0 0) + (uuid 14c51520-6d91-4098-a59a-5121f2a898f7) + ) + (junction (at 186.69 62.23) (diameter 0) (color 0 0 0 0) + (uuid 275aa44a-b61f-489f-9e2a-819a0fe0d1eb) + ) + (junction (at 233.68 59.69) (diameter 0) (color 0 0 0 0) + (uuid 639c0e59-e95c-4114-bccd-2e7277505454) + ) + (junction (at 179.07 95.25) (diameter 0) (color 0 0 0 0) + (uuid 84e5506c-143e-495f-9aa4-d3a71622f213) + ) + (junction (at 198.12 67.31) (diameter 0) (color 0 0 0 0) + (uuid b447dbb1-d38e-4a15-93cb-12c25382ea53) + ) + (junction (at 186.69 67.31) (diameter 0) (color 0 0 0 0) + (uuid b7199d9b-bebb-4100-9ad3-c2bd31e21d65) + ) + + (no_connect (at 148.59 83.82) (uuid 182b2d54-931d-49d6-9f39-60a752623e36)) + (no_connect (at 228.6 125.73) (uuid 1e8701fc-ad24-40ea-846a-e3db538d6077)) + (no_connect (at 203.2 125.73) (uuid 25d545dc-8f50-4573-922c-35ef5a2a3a19)) + (no_connect (at 203.2 113.03) (uuid c830e3bc-dc64-4f65-8f47-3b106bae2807)) + (no_connect (at 228.6 123.19) (uuid d5641ac9-9be7-46bf-90b3-6c83d852b5ba)) + (no_connect (at 148.59 81.28) (uuid f202141e-c20d-4cac-b016-06a44f2ecce8)) + + (wire (pts (xy 148.59 68.58) (xy 144.78 68.58)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 0147f16a-c952-4891-8f53-a9fb8cddeb8d) + ) + (wire (pts (xy 134.62 115.57) (xy 142.24 115.57)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 03c52831-5dc5-43c5-a442-8d23643b46fb) + ) + (wire (pts (xy 179.07 95.25) (xy 179.07 100.33)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 097edb1b-8998-4e70-b670-bba125982348) + ) + (wire (pts (xy 113.03 66.04) (xy 116.84 66.04)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 0a3cc030-c9dd-4d74-9d50-715ed2b361a2) + ) + (wire (pts (xy 173.99 71.12) (xy 186.69 71.12)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 0b21a65d-d20b-411e-920a-75c343ac5136) + ) + (wire (pts (xy 173.99 66.04) (xy 179.07 66.04)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 0d0bb7b2-a6e5-46d2-9492-a1aa6e5a7b2f) + ) + (wire (pts (xy 193.04 100.33) (xy 194.31 100.33)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 0e1ed1c5-7428-4dc7-b76e-49b2d5f8177d) + ) + (wire (pts (xy 113.03 62.23) (xy 116.84 62.23)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 24f7628d-681d-4f0e-8409-40a129e929d9) + ) + (wire (pts (xy 134.62 110.49) (xy 142.24 110.49)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 29e78086-2175-405e-9ba3-c48766d2f50c) + ) + (wire (pts (xy 194.31 95.25) (xy 198.12 95.25)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 2d67a417-188f-4014-9282-000265d80009) + ) + (wire (pts (xy 203.2 115.57) (xy 208.28 115.57)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 2e642b3e-a476-4c54-9a52-dcea955640cd) + ) + (wire (pts (xy 81.28 91.44) (xy 87.63 91.44)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 2f215f15-3d52-4c91-93e6-3ea03a95622f) + ) + (wire (pts (xy 83.82 62.23) (xy 88.9 62.23)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 30f15357-ce1d-48b9-93dc-7d9b1b2aa048) + ) + (wire (pts (xy 113.03 59.69) (xy 116.84 59.69)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 3a7648d8-121a-4921-9b92-9b35b76ce39b) + ) + (wire (pts (xy 134.62 120.65) (xy 142.24 120.65)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 3cd1bda0-18db-417d-b581-a0c50623df68) + ) + (wire (pts (xy 194.31 67.31) (xy 198.12 67.31)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 3e903008-0276-4a73-8edb-5d9dfde6297c) + ) + (wire (pts (xy 186.69 71.12) (xy 186.69 67.31)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 45008225-f50f-4d6b-b508-6730a9408caf) + ) + (wire (pts (xy 228.6 113.03) (xy 233.68 113.03)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 46918595-4a45-48e8-84c0-961b4db7f35f) + ) + (wire (pts (xy 194.31 95.25) (xy 194.31 100.33)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 477311b9-8f81-40c8-9c55-fd87e287247a) + ) + (wire (pts (xy 186.69 62.23) (xy 186.69 58.42)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 57c0c267-8bf9-4cc7-b734-d71a239ac313) + ) + (wire (pts (xy 186.69 58.42) (xy 189.23 58.42)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 5ca4be1c-537e-4a4a-b344-d0c8ffde8546) + ) + (wire (pts (xy 179.07 81.28) (xy 179.07 95.25)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 5fc27c35-3e1c-4f96-817c-93b5570858a6) + ) + (wire (pts (xy 81.28 86.36) (xy 87.63 86.36)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 61fe293f-6808-4b7f-9340-9aaac7054a97) + ) + (wire (pts (xy 81.28 76.2) (xy 87.63 76.2)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 63ff1c93-3f96-4c33-b498-5dd8c33bccc0) + ) + (wire (pts (xy 71.12 115.57) (xy 73.66 115.57)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 65134029-dbd2-409a-85a8-13c2a33ff019) + ) + (wire (pts (xy 173.99 83.82) (xy 180.34 83.82)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 6595b9c7-02ee-4647-bde5-6b566e35163e) + ) + (wire (pts (xy 193.04 95.25) (xy 194.31 95.25)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 66116376-6967-4178-9f23-a26cdeafc400) + ) + (wire (pts (xy 144.78 66.04) (xy 148.59 66.04)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 6a44418c-7bb4-4e99-8836-57f153c19721) + ) + (wire (pts (xy 144.78 76.2) (xy 148.59 76.2)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 6a955fc7-39d9-4c75-9a69-676ca8c0b9b2) + ) + (wire (pts (xy 198.12 58.42) (xy 198.12 67.31)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 6c67e4f6-9d04-4539-b356-b76e915ce848) + ) + (wire (pts (xy 179.07 95.25) (xy 185.42 95.25)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 6c9b793c-e74d-4754-a2c0-901e73b26f1c) + ) + (wire (pts (xy 148.59 73.66) (xy 144.78 73.66)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 6ec113ca-7d27-4b14-a180-1e5e2fd1c167) + ) + (wire (pts (xy 81.28 137.16) (xy 87.63 137.16)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 70e15522-1572-4451-9c0d-6d36ac70d8c6) + ) + (wire (pts (xy 134.62 123.19) (xy 142.24 123.19)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 75ffc65c-7132-4411-9f2a-ae0c73d79338) + ) + (wire (pts (xy 180.34 76.2) (xy 173.99 76.2)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 770ad51a-7219-4633-b24a-bd20feb0a6c5) + ) + (wire (pts (xy 186.69 62.23) (xy 184.15 62.23)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 7cee474b-af8f-4832-b07a-c43c1ab0b464) + ) + (wire (pts (xy 81.28 115.57) (xy 86.36 115.57)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 7f2301df-e4bc-479e-a681-cc59c9a2dbbb) + ) + (wire (pts (xy 71.12 127) (xy 73.66 127)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 8087f566-a94d-4bbc-985b-e49ee7762296) + ) + (wire (pts (xy 113.03 68.58) (xy 116.84 68.58)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 8322f275-268c-4e87-a69f-4cfbf05e747f) + ) + (wire (pts (xy 186.69 62.23) (xy 186.69 67.31)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 853ee787-6e2c-4f32-bc75-6c17337dd3d5) + ) + (wire (pts (xy 203.2 118.11) (xy 208.28 118.11)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 87371631-aa02-498a-998a-09bdb74784c1) + ) + (wire (pts (xy 81.28 147.32) (xy 87.63 147.32)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 8a650ebf-3f78-4ca4-a26b-a5028693e36d) + ) + (wire (pts (xy 233.68 59.69) (xy 234.95 59.69)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 8ca3e20d-bcc7-4c5e-9deb-562dfed9fecb) + ) + (wire (pts (xy 81.28 96.52) (xy 87.63 96.52)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 8da933a9-35f8-42e6-8504-d1bab7264306) + ) + (wire (pts (xy 81.28 127) (xy 86.36 127)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 98c78427-acd5-4f90-9ad6-9f61c4809aec) + ) + (wire (pts (xy 196.85 58.42) (xy 198.12 58.42)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 9cb12cc8-7f1a-4a01-9256-c119f11a8a02) + ) + (wire (pts (xy 228.6 115.57) (xy 233.68 115.57)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid 9ccf03e8-755a-4cd9-96fc-30e1d08fa253) + ) + (wire (pts (xy 134.62 113.03) (xy 142.24 113.03)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid a1823eb2-fb0d-4ed8-8b96-04184ac3a9d5) + ) + (wire (pts (xy 203.2 120.65) (xy 208.28 120.65)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid a7520ad3-0f8b-4788-92d4-8ffb277041e6) + ) + (wire (pts (xy 203.2 123.19) (xy 208.28 123.19)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid a795f1ba-cdd5-4cc5-9a52-08586e982934) + ) + (wire (pts (xy 226.06 73.66) (xy 226.06 78.74)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid aca4de92-9c41-4c2b-9afa-540d02dafa1c) + ) + (wire (pts (xy 180.34 73.66) (xy 173.99 73.66)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid b1c649b1-f44d-46c7-9dea-818e75a1b87e) + ) + (wire (pts (xy 81.28 81.28) (xy 87.63 81.28)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid b88717bd-086f-46cd-9d3f-0396009d0996) + ) + (wire (pts (xy 228.6 118.11) (xy 233.68 118.11)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid bb7f0588-d4d8-44bf-9ebf-3c533fe4d6ae) + ) + (wire (pts (xy 148.59 71.12) (xy 144.78 71.12)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid bd065eaf-e495-4837-bdb3-129934de1fc7) + ) + (wire (pts (xy 81.28 101.6) (xy 87.63 101.6)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid bd5408e4-362d-4e43-9d39-78fb99eb52c8) + ) + (wire (pts (xy 195.58 78.74) (xy 195.58 83.82)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid c144caa5-b0d4-4cef-840a-d4ad178a2102) + ) + (wire (pts (xy 226.06 59.69) (xy 233.68 59.69)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid c25a772d-af9c-4ebc-96f6-0966738c13a8) + ) + (wire (pts (xy 233.68 73.66) (xy 233.68 78.74)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid c43663ee-9a0d-4f27-a292-89ba89964065) + ) + (wire (pts (xy 81.28 142.24) (xy 87.63 142.24)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid c5eb1e4c-ce83-470e-8f32-e20ff1f886a3) + ) + (wire (pts (xy 198.12 67.31) (xy 200.66 67.31)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid cfa5c16e-7859-460d-a0b8-cea7d7ea629c) + ) + (wire (pts (xy 233.68 66.04) (xy 233.68 59.69)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid d3c11c8f-a73d-4211-934b-a6da255728ad) + ) + (wire (pts (xy 134.62 118.11) (xy 142.24 118.11)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid d57dcfee-5058-4fc2-a68b-05f9a48f685b) + ) + (wire (pts (xy 226.06 59.69) (xy 226.06 66.04)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid d7269d2a-b8c0-422d-8f25-f79ea31bf75e) + ) + (wire (pts (xy 83.82 59.69) (xy 88.9 59.69)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid d8603679-3e7b-4337-8dbc-1827f5f54d8a) + ) + (wire (pts (xy 173.99 68.58) (xy 179.07 68.58)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid e4c6fdbb-fdc7-4ad4-a516-240d84cdc120) + ) + (wire (pts (xy 144.78 78.74) (xy 148.59 78.74)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid e8314017-7be6-4011-9179-37449a29b311) + ) + (wire (pts (xy 173.99 81.28) (xy 179.07 81.28)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid efeac2a2-7682-4dc7-83ee-f6f1b23da506) + ) + (wire (pts (xy 228.6 120.65) (xy 233.68 120.65)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid f1830a1b-f0cc-47ae-a2c9-679c82032f14) + ) + (wire (pts (xy 173.99 78.74) (xy 195.58 78.74)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid f3628265-0155-43e2-a467-c40ff783e265) + ) + (wire (pts (xy 179.07 100.33) (xy 185.42 100.33)) + (stroke (width 0) (type default) (color 0 0 0 0)) + (uuid f40d350f-0d3e-4f8a-b004-d950f2f8f1ba) + ) + + (text "only one capacitor needed, \ndouble footprint for SMD/THT" + (at 195.58 57.15 0) + (effects (font (size 1.27 1.27)) (justify left bottom)) + (uuid 37e8181c-a81e-498b-b2e2-0aef0c391059) + ) + (text "only one resistor needed, \ndouble footprint for SMD/THT" + (at 191.77 91.44 0) + (effects (font (size 1.27 1.27)) (justify left bottom)) + (uuid 676efd2f-1c48-4786-9e4b-2444f1e8f6ff) + ) + + (global_label "VCC_BAT" (shape input) (at 116.84 59.69 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 0217dfc4-fc13-4699-99ad-d9948522648e) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "BAT_CHARGING" (shape input) (at 71.12 115.57 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 03caada9-9e22-4e2d-9035-b15433dfbb17) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "BAT_CHARGED" (shape input) (at 180.34 73.66 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 0c3dceba-7c95-4b3d-b590-0eb581444beb) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "VCC_BAT" (shape input) (at 142.24 115.57 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 0eaa98f0-9565-4637-ace3-42a5231b07f7) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "ANEMOMETER" (shape input) (at 142.24 120.65 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 0f22151c-f260-4674-b486-4710a2c42a55) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "NSTBY" (shape input) (at 85.09 127 90) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 101ef598-601d-400e-9ef6-d655fbb1dbfa) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND" (shape input) (at 116.84 68.58 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 15875808-74d5-4210-b8ca-aa8fbc04ae21) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GPIO8" (shape input) (at 179.07 68.58 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 16a9ae8c-3ad2-439b-8efe-377c994670c7) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND" (shape input) (at 208.28 123.19 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 1860e030-7a36-4298-b7fc-a16d48ab15ba) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "3V3" (shape input) (at 234.95 59.69 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 40165eda-4ba6-4565-9bb4-b9df6dbb08da) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "5V" (shape input) (at 198.12 95.25 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 44d8279a-9cd1-4db6-856f-0363131605fc) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "SDA" (shape input) (at 226.06 78.74 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 4780a290-d25c-4459-9579-eba3f7678762) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "5V" (shape input) (at 81.28 96.52 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 4a4ec8d9-3d72-4952-83d4-808f65849a2b) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND" (shape input) (at 144.78 68.58 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 4e3d7c0d-12e3-42f2-b944-e4bcdbbcac2a) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "5V" (shape input) (at 144.78 66.04 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 5b2b5c7d-f943-4634-9f0a-e9561705c49d) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "SDA" (shape input) (at 233.68 120.65 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 5cbb5968-dbb5-4b84-864a-ead1cacf75b9) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "ANEMOMETER" (shape input) (at 184.15 62.23 90) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 6475547d-3216-45a4-a15c-48314f1dd0f9) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND_SOLAR" (shape input) (at 81.28 81.28 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 66043bca-a260-4915-9fce-8a51d324c687) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "3V3" (shape input) (at 233.68 113.03 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 67f6e996-3c99-493c-8f6f-e739e2ed5d7a) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND_BAT" (shape input) (at 116.84 62.23 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 6bfe5804-2ef9-4c65-b2a7-f01e4014370a) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GPIO3" (shape input) (at 81.28 137.16 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 6d26d68f-1ca7-4ff3-b058-272f1c399047) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "BAT_CHARGING" (shape input) (at 180.34 76.2 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 730b670c-9bcf-4dcd-9a8d-fcaa61fb0955) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "VCC_SOLAR" (shape input) (at 83.82 59.69 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 749dfe75-c0d6-4872-9330-29c5bbcb8ff8) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GPIO4" (shape input) (at 144.78 71.12 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 789ca812-3e0c-4a3f-97bc-a916dd9bce80) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "SCL" (shape input) (at 144.78 78.74 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 78cbdd6c-4878-4cc5-9a58-0e506478e37d) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "VCC_BAT" (shape input) (at 81.28 86.36 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 7bbf981c-a063-4e30-8911-e4228e1c0743) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND_BAT" (shape input) (at 81.28 91.44 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 7edc9030-db7b-43ac-a1b3-b87eeacb4c2d) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND_SOLAR" (shape input) (at 142.24 113.03 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 8174b4de-74b1-48db-ab8e-c8432251095b) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "BAT_CHARGED" (shape input) (at 71.12 127 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 8412992d-8754-44de-9e08-115cec1a3eff) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND" (shape input) (at 142.24 123.19 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 9340c285-5767-42d5-8b6d-63fe2a40ddf3) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "SDA" (shape input) (at 144.78 76.2 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid 94c158d1-8503-4553-b511-bf42f506c2a8) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "SCL" (shape input) (at 208.28 115.57 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid 983c426c-24e0-4c65-ab69-1f1824adc5c6) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND" (shape input) (at 233.68 115.57 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid a05d7640-f2f6-4ba7-8c51-5a4af431fc13) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "NCHRG" (shape input) (at 85.09 115.57 90) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid a8447faf-e0a0-4c4a-ae53-4d4b28669151) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "5V" (shape input) (at 116.84 66.04 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid b1169a2d-8998-4b50-a48d-c520bcc1b8e1) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "VCC_SOLAR" (shape input) (at 81.28 76.2 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid b5352a33-563a-4ffe-a231-2e68fb54afa3) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "3V3" (shape input) (at 208.28 120.65 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid b6270a28-e0d9-4655-a18a-03dbf007b940) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "SCL" (shape input) (at 233.68 78.74 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid babeabf2-f3b0-4ed5-8d9e-0215947e6cf3) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GPIO8" (shape input) (at 81.28 147.32 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid ca87f11b-5f48-4b57-8535-68d3ec2fe5a9) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND_SOLAR" (shape input) (at 83.82 62.23 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid cbdcaa78-3bbc-413f-91bf-2709119373ce) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GPIO3" (shape input) (at 144.78 73.66 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid cdfb07af-801b-44ba-8c30-d021a6ad3039) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND_BAT" (shape input) (at 142.24 118.11 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid ce83728b-bebd-48c2-8734-b6a50d837931) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "3V3" (shape input) (at 179.07 66.04 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid d1262c4d-2245-4c4f-8f35-7bb32cd9e21e) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "SCL" (shape input) (at 233.68 118.11 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid da469d11-a8a4-414b-9449-d151eeaf4853) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "SDA" (shape input) (at 208.28 118.11 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid e9bb29b2-2bb9-4ea2-acd9-2bb3ca677a12) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GPIO4" (shape input) (at 81.28 142.24 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid ec31c074-17b2-48e1-ab01-071acad3fa04) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND" (shape input) (at 81.28 101.6 180) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify right)) + (uuid f2c93195-af12-4d3e-acdf-bdd0ff675c24) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "GND" (shape input) (at 200.66 67.31 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid f4f99e3d-7269-4f6a-a759-16ad2a258779) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + (global_label "VCC_SOLAR" (shape input) (at 142.24 110.49 0) (fields_autoplaced) + (effects (font (size 1.27 1.27)) (justify left)) + (uuid f71da641-16e6-4257-80c3-0b9d804fee4f) + (property "Intersheet References" "${INTERSHEET_REFS}" (id 0) (at 0 0 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + + (symbol (lib_id "wemos_mini:WeMos_mini") (at 161.29 74.93 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c36643e) + (property "Reference" "U2" (id 0) (at 161.29 58.7502 0) + (effects (font (size 1.524 1.524))) + ) + (property "Value" "" (id 1) (at 161.29 61.4426 0) + (effects (font (size 1.524 1.524))) + ) + (property "Footprint" "" (id 2) (at 175.26 92.71 0) + (effects (font (size 1.524 1.524)) hide) + ) + (property "Datasheet" "" (id 3) (at 175.26 92.71 0) + (effects (font (size 1.524 1.524))) + ) + (pin "1" (uuid 643d80ef-8daf-4495-97c7-1b6d29d8dfef)) + (pin "10" (uuid 84f63bb6-4eb9-4689-a4f3-3048ae3cbd72)) + (pin "11" (uuid ab16641d-b852-4f13-b79d-d22411190cab)) + (pin "12" (uuid 0595a04f-7477-4b42-9542-5d6e7a468e5a)) + (pin "13" (uuid aefc7a08-8cec-449e-858c-c9cd83cd8be6)) + (pin "14" (uuid 456a0f4d-8f08-4af5-9ebc-bd56ca7b864e)) + (pin "15" (uuid a46bc207-7a2b-4c2c-8664-12f06b8e7eb1)) + (pin "16" (uuid 2a765a46-48b1-4bb6-b6ce-2f340037e5cf)) + (pin "2" (uuid 06ac3bb5-5357-4aa0-9b0b-4f43394f12a7)) + (pin "3" (uuid b86b2bdf-9993-44ff-91e3-13270234b4d0)) + (pin "4" (uuid 51c0aba4-67d4-4c68-a0f5-c131bc9fee2f)) + (pin "5" (uuid 68241e35-c8b4-4c7d-85bc-ea8375a3e979)) + (pin "6" (uuid c980b7ff-8a8c-4a71-94b5-28a9decd5230)) + (pin "7" (uuid d338c701-2b93-410c-9ecd-57e3e942d213)) + (pin "8" (uuid 900147d5-2fd5-44de-a569-13801c881b8f)) + (pin "9" (uuid 0293c64d-258d-417b-8c4c-df5bec9d92d9)) + ) + + (symbol (lib_id "oko:03962A") (at 107.95 62.23 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c3666e0) + (property "Reference" "U1" (id 0) (at 100.965 50.419 0)) + (property "Value" "" (id 1) (at 100.965 52.7304 0)) + (property "Footprint" "" (id 2) (at 107.95 62.23 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "" (id 3) (at 107.95 62.23 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 31776fac-ddd1-4f7f-99a2-a1d80744f444)) + (pin "2" (uuid cff0e65d-e3fa-4a63-89b2-ee95d2eadf50)) + (pin "3" (uuid 126bb32d-88df-4efe-a752-e5e2f11f288b)) + (pin "4" (uuid f8c88117-930f-4fb6-80c5-667e779502ed)) + (pin "5" (uuid 65ab014e-a547-434d-9a5d-f81cb1c67711)) + (pin "6" (uuid bca3f06c-4493-484f-b5c2-48437b3371ee)) + ) + + (symbol (lib_id "oko:APDS-9900") (at 194.31 116.84 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c366782) + (property "Reference" "U3" (id 0) (at 198.2724 107.315 0)) + (property "Value" "" (id 1) (at 198.2724 109.6264 0)) + (property "Footprint" "" (id 2) (at 194.31 116.84 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "" (id 3) (at 194.31 116.84 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 887417aa-cab8-43aa-a3d3-197eaed6ffeb)) + (pin "2" (uuid 650ff32f-e860-41da-a740-6dff7dd3c425)) + (pin "3" (uuid f9f45df7-1122-4c62-a34a-929b18114bdc)) + (pin "4" (uuid 585cc372-ca56-43bf-8790-b49ee6f01e0e)) + (pin "5" (uuid 1ae73ada-1e72-4cee-9a3d-a155873facb9)) + (pin "6" (uuid 5397c2be-023b-4748-a02e-8f9a6bf72339)) + ) + + (symbol (lib_id "oko-weatherstation-rescue:GY-BME280-oko") (at 219.71 118.11 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c36680f) + (property "Reference" "U4" (id 0) (at 223.6724 107.315 0)) + (property "Value" "" (id 1) (at 223.6724 109.6264 0)) + (property "Footprint" "" (id 2) (at 219.71 120.65 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "" (id 3) (at 219.71 120.65 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid c17c9aea-bfc6-434a-a11f-397ae1b0c5d4)) + (pin "2" (uuid c86dcb16-8607-4be4-b822-2099316b7e47)) + (pin "3" (uuid 5b629dcf-0906-41e0-a929-f9b345877a71)) + (pin "4" (uuid 10d6edb4-9d3a-4b74-b32e-d4bc3e12568d)) + (pin "5" (uuid b8aad927-7690-4de6-8646-4e630a458e9d)) + (pin "6" (uuid 74ff0d84-4f69-4630-870d-b6cc76b5b3aa)) + ) + + (symbol (lib_id "Device:C") (at 190.5 67.31 270) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c36b0bf) + (property "Reference" "C1" (id 0) (at 190.5 60.9092 90)) + (property "Value" "" (id 1) (at 190.5 63.2206 90)) + (property "Footprint" "" (id 2) (at 186.69 68.2752 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 190.5 67.31 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 3dc507ae-48ea-4f1e-8962-e73c0e5934f6)) + (pin "2" (uuid 03b222f2-b421-4321-bd3f-6d6f6cf41dce)) + ) + + (symbol (lib_id "Device:R") (at 189.23 95.25 270) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c36b93e) + (property "Reference" "R1" (id 0) (at 189.23 92.71 90)) + (property "Value" "" (id 1) (at 189.23 95.25 90)) + (property "Footprint" "" (id 2) (at 189.23 93.472 90) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 189.23 95.25 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 153fd416-78c9-434c-892e-ba9eaea2bb66)) + (pin "2" (uuid 852c7d7d-9901-46e3-ada0-94c7b50e19ea)) + ) + + (symbol (lib_id "oko-weatherstation-rescue:Jumper-Device") (at 187.96 83.82 180) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c3808d5) + (property "Reference" "JP1" (id 0) (at 187.96 85.09 0)) + (property "Value" "" (id 1) (at 187.96 82.55 0)) + (property "Footprint" "" (id 2) (at 187.96 83.82 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 187.96 83.82 0) + (effects (font (size 1.27 1.27)) hide) + ) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x06") (at 129.54 118.11 180) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c389fc7) + (property "Reference" "J7" (id 0) (at 131.572 104.775 0)) + (property "Value" "" (id 1) (at 131.572 107.0864 0)) + (property "Footprint" "" (id 2) (at 129.54 118.11 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 129.54 118.11 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid eda9daf8-4a7f-4ce2-b674-13d1c7c860fd)) + (pin "2" (uuid acd23b79-317c-4d2e-90fe-1c7f88c75ef5)) + (pin "3" (uuid 0ca7582a-2cf2-4166-a70e-351e9f98bc70)) + (pin "4" (uuid e2bb0953-02c3-4b33-b1e3-3d35bc85d7f2)) + (pin "5" (uuid cc9c3383-c2c7-4fb3-a64a-dab85c8d1537)) + (pin "6" (uuid 75a7be90-106e-482c-a464-110e4aa676c5)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 76.2 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c38d2cb) + (property "Reference" "J1" (id 0) (at 94.7166 75.1332 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.7166 77.4446 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 76.2 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 76.2 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 54994a58-1603-48d7-b511-7b9b7204faaa)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 81.28 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c38d8bf) + (property "Reference" "J2" (id 0) (at 94.7166 80.2132 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.7166 82.5246 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 81.28 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 81.28 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid d5141b2d-71c8-40a8-9603-c4616cd66d9e)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 86.36 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c38d924) + (property "Reference" "J3" (id 0) (at 94.7166 85.2932 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.7166 87.6046 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 86.36 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 86.36 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 26d7ef4d-55f6-4c25-b836-f3312479386a)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 91.44 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c38d96a) + (property "Reference" "J4" (id 0) (at 94.742 90.3732 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.742 92.6846 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 91.44 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 91.44 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid fb98e058-6eff-4d22-b03c-2bfdd5213164)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 96.52 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c38d9a1) + (property "Reference" "J5" (id 0) (at 94.7166 95.4532 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.7166 97.7646 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 96.52 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 96.52 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 35dd081b-9c90-4f35-84d1-6d53ae6bd97a)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 101.6 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c38db5f) + (property "Reference" "J6" (id 0) (at 94.7166 100.5332 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.7166 102.8446 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 101.6 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 101.6 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid d9a0c187-3bfb-40a4-a7be-69e695db4255)) + ) + + (symbol (lib_id "Device:R") (at 226.06 69.85 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c4d91c5) + (property "Reference" "R2" (id 0) (at 227.838 68.6816 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 227.838 70.993 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 224.282 69.85 90) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 226.06 69.85 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid a33ae006-8c92-4c8a-8134-42b6731b6c81)) + (pin "2" (uuid 195e4170-a623-4614-a488-a41ba6c02605)) + ) + + (symbol (lib_id "Device:R") (at 233.68 69.85 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c4d924a) + (property "Reference" "R3" (id 0) (at 235.458 68.6816 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 235.458 70.993 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 231.902 69.85 90) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 233.68 69.85 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 1da254ed-29b1-422b-95d9-60841f7f8478)) + (pin "2" (uuid a2164008-657b-47d6-89c6-d33a0f994fb2)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 91.44 115.57 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c5715cf) + (property "Reference" "J8" (id 0) (at 93.4466 114.5032 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 93.4466 116.8146 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 91.44 115.57 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 91.44 115.57 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 75cc9cb5-bd03-4ad9-bb99-9b71e3501a51)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 91.44 127 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c57277c) + (property "Reference" "J9" (id 0) (at 93.4466 125.9332 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 93.4466 128.2446 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 91.44 127 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 91.44 127 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid e182f9d1-2a8f-4b91-a06f-be8a63e79366)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 137.16 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c573a1a) + (property "Reference" "J10" (id 0) (at 94.7166 136.0932 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.7166 138.4046 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 137.16 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 137.16 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 01ac9b4d-f91a-4df0-a3d2-d17461e07f90)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 142.24 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c574db6) + (property "Reference" "J11" (id 0) (at 94.7166 141.1732 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.7166 143.4846 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 142.24 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 142.24 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 8b2186f3-3f57-4130-95c5-776060a854fd)) + ) + + (symbol (lib_id "Connector_Generic:Conn_01x01") (at 92.71 147.32 0) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c576251) + (property "Reference" "J12" (id 0) (at 94.7166 146.2532 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Value" "" (id 1) (at 94.7166 148.5646 0) + (effects (font (size 1.27 1.27)) (justify left)) + ) + (property "Footprint" "" (id 2) (at 92.71 147.32 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 92.71 147.32 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 9f448f8f-d6b3-4566-ba2a-f3473c09a657)) + ) + + (symbol (lib_id "Device:C") (at 193.04 58.42 270) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c576327) + (property "Reference" "C2" (id 0) (at 193.04 52.0192 90)) + (property "Value" "" (id 1) (at 193.04 54.3306 90)) + (property "Footprint" "" (id 2) (at 189.23 59.3852 0) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 193.04 58.42 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 971c0335-c37f-4b11-8944-3c6bcd551cc7)) + (pin "2" (uuid 51f2f019-0400-459d-ba65-9b144ff75eda)) + ) + + (symbol (lib_id "Device:R") (at 189.23 100.33 270) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c57ff00) + (property "Reference" "R4" (id 0) (at 189.23 97.79 90)) + (property "Value" "" (id 1) (at 189.23 100.33 90)) + (property "Footprint" "" (id 2) (at 189.23 98.552 90) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 189.23 100.33 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid d6a2d9d9-391f-4955-a92f-e6f4f5742fa8)) + (pin "2" (uuid 2943f8f6-7441-42eb-918b-ea5d98022792)) + ) + + (symbol (lib_id "Device:R") (at 77.47 115.57 270) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c58eb09) + (property "Reference" "R5" (id 0) (at 77.47 113.03 90)) + (property "Value" "" (id 1) (at 77.47 115.57 90)) + (property "Footprint" "" (id 2) (at 77.47 113.792 90) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 77.47 115.57 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid dbf2f322-fde2-4da3-b2ce-f14564b17d40)) + (pin "2" (uuid 67b6c32d-3788-4bf6-969c-0ef260bf7b8e)) + ) + + (symbol (lib_id "Device:R") (at 77.47 127 270) (unit 1) + (in_bom yes) (on_board yes) + (uuid 00000000-0000-0000-0000-00005c58eb15) + (property "Reference" "R6" (id 0) (at 77.47 124.46 90)) + (property "Value" "" (id 1) (at 77.47 127 90)) + (property "Footprint" "" (id 2) (at 77.47 125.222 90) + (effects (font (size 1.27 1.27)) hide) + ) + (property "Datasheet" "~" (id 3) (at 77.47 127 0) + (effects (font (size 1.27 1.27)) hide) + ) + (pin "1" (uuid 338f364d-5a55-4824-bb89-ff4127ce60cd)) + (pin "2" (uuid 8c601592-aacc-4161-9bbb-d9e6a0568229)) + ) + + (sheet_instances + (path "/" (page "1")) + ) + + (symbol_instances + (path "/00000000-0000-0000-0000-00005c36b0bf" + (reference "C1") (unit 1) (value "100n") (footprint "Capacitors_ThroughHole:C_Rect_L4.6mm_W2.0mm_P2.50mm_MKS02_FKP02") + ) + (path "/00000000-0000-0000-0000-00005c576327" + (reference "C2") (unit 1) (value "100n") (footprint "Capacitors_SMD:C_0603_1608Metric") + ) + (path "/00000000-0000-0000-0000-00005c38d2cb" + (reference "J1") (unit 1) (value "VCC_SOLAR") (footprint "Measurement_Points:Measurement_Point_Square-SMD-Pad_Small") + ) + (path "/00000000-0000-0000-0000-00005c38d8bf" + (reference "J2") (unit 1) (value "GND_SOLAR") (footprint "Measurement_Points:Measurement_Point_Square-SMD-Pad_Small") + ) + (path "/00000000-0000-0000-0000-00005c38d924" + (reference "J3") (unit 1) (value "VCC_BAT") (footprint "Measurement_Points:Measurement_Point_Square-SMD-Pad_Small") + ) + (path "/00000000-0000-0000-0000-00005c38d96a" + (reference "J4") (unit 1) (value "GND_BAT") (footprint "Measurement_Points:Measurement_Point_Square-SMD-Pad_Small") + ) + (path "/00000000-0000-0000-0000-00005c38d9a1" + (reference "J5") (unit 1) (value "5V") (footprint "Measurement_Points:Measurement_Point_Square-SMD-Pad_Small") + ) + (path "/00000000-0000-0000-0000-00005c38db5f" + (reference "J6") (unit 1) (value "GND") (footprint "Measurement_Points:Measurement_Point_Square-SMD-Pad_Small") + ) + (path "/00000000-0000-0000-0000-00005c389fc7" + (reference "J7") (unit 1) (value "Conn_01x06") (footprint "Pin_Headers:Pin_Header_Angled_1x06_Pitch2.54mm") + ) + (path "/00000000-0000-0000-0000-00005c5715cf" + (reference "J8") (unit 1) (value "BAT_CHARGING") (footprint "TestPoint:TestPoint_THTPad_1.5x1.5mm_Drill0.7mm") + ) + (path "/00000000-0000-0000-0000-00005c57277c" + (reference "J9") (unit 1) (value "BAT_CHARGED") (footprint "TestPoint:TestPoint_THTPad_1.5x1.5mm_Drill0.7mm") + ) + (path "/00000000-0000-0000-0000-00005c573a1a" + (reference "J10") (unit 1) (value "GPIO3") (footprint "TestPoint:TestPoint_Pad_1.5x1.5mm") + ) + (path "/00000000-0000-0000-0000-00005c574db6" + (reference "J11") (unit 1) (value "GPIO4") (footprint "TestPoint:TestPoint_Pad_1.5x1.5mm") + ) + (path "/00000000-0000-0000-0000-00005c576251" + (reference "J12") (unit 1) (value "GPIO8") (footprint "TestPoint:TestPoint_Pad_1.5x1.5mm") + ) + (path "/00000000-0000-0000-0000-00005c3808d5" + (reference "JP1") (unit 1) (value "Jumper") (footprint "Pin_Headers:Pin_Header_Angled_1x02_Pitch2.54mm") + ) + (path "/00000000-0000-0000-0000-00005c36b93e" + (reference "R1") (unit 1) (value "100k") (footprint "Resistors_THT:R_Axial_DIN0207_L6.3mm_D2.5mm_P7.62mm_Horizontal") + ) + (path "/00000000-0000-0000-0000-00005c4d91c5" + (reference "R2") (unit 1) (value "4k7") (footprint "Resistors_SMD:R_0603_1608Metric") + ) + (path "/00000000-0000-0000-0000-00005c4d924a" + (reference "R3") (unit 1) (value "4k7") (footprint "Resistors_SMD:R_0603_1608Metric") + ) + (path "/00000000-0000-0000-0000-00005c57ff00" + (reference "R4") (unit 1) (value "100k") (footprint "Resistors_SMD:R_0603_1608Metric") + ) + (path "/00000000-0000-0000-0000-00005c58eb09" + (reference "R5") (unit 1) (value "1k") (footprint "Resistors_SMD:R_0603_1608Metric") + ) + (path "/00000000-0000-0000-0000-00005c58eb15" + (reference "R6") (unit 1) (value "1k") (footprint "Resistors_SMD:R_0603_1608Metric") + ) + (path "/00000000-0000-0000-0000-00005c3666e0" + (reference "U1") (unit 1) (value "03962A") (footprint "oko:03962A") + ) + (path "/00000000-0000-0000-0000-00005c36643e" + (reference "U2") (unit 1) (value "WeMos D1 mini") (footprint "oko:wemos-d1-mini-connectors-only") + ) + (path "/00000000-0000-0000-0000-00005c366782" + (reference "U3") (unit 1) (value "APDS-9900") (footprint "oko:APDS-9960") + ) + (path "/00000000-0000-0000-0000-00005c36680f" + (reference "U4") (unit 1) (value "GY-BME280") (footprint "oko:GY-BME280") + ) + ) +)