Refactor webserver, changes to formulaCreation

This commit is contained in:
Magnus Persson
2022-01-04 19:46:37 +01:00
parent 0783a206b2
commit 5a7858ecaf
9 changed files with 284 additions and 220 deletions

View File

@ -28,10 +28,12 @@ build_flags =
#-D DEBUG_ESP_HTTP_CLIENT
#-D DEBUG_ESP_HTTP_SERVER
#-D DEBUG_ESP_PORT=Serial
#-D DEBUG_ESP_WIFI
#-D DEBUG_ESP_CORE
#-D SKIP_SLEEPMODE
#-D DOUBLERESETDETECTOR_DEBUG true
-D USE_LITTLEFS=true
-D EMBED_HTML # If this is not used the html files needs to be on the file system (can be uploaded)
#-D EMBED_HTML # If this is not used the html files needs to be on the file system (can be uploaded)
-D USER_SSID=\""\"" # =\""myssid\""
-D USER_SSID_PWD=\""\"" # =\""mypwd\""
-D CFG_APPVER="\"0.4.9\""
@ -61,13 +63,14 @@ build_unflags =
${common_env_data.build_unflags}
build_flags =
-D PIO_FRAMEWORK_ARDUINO_ENABLE_EXCEPTIONS
#-D DEACTIVATE_SLEEPMODE
#-D SKIP_SLEEPMODE
${common_env_data.build_flags}
-D COLLECT_PERFDATA # This option will collect runtime data for a few defined methods to measure time, dumped to serial and/or influxdb
-D LOG_LEVEL=6 # Maximum log level for the debug build.
lib_deps =
${common_env_data.lib_deps}
board = ${common_env_data.board}
#board = ${common_env_data.board}
board = nodemcuv2
build_type = debug
board_build.filesystem = littlefs
monitor_filters = esp8266_exception_decoder

View File

@ -30,7 +30,6 @@ SOFTWARE.
#define FORMULA_MAX_DEVIATION 1.5
//
// Use values to derive a formula
//
@ -61,6 +60,10 @@ int createFormula( RawFormulaData& fd, char *formulaBuffer, int order ) {
//Returned value is 0 if no error
if( ret == 0 ) {
#if LOG_LEVEL==6
Log.verbose(F("CALC: Finshied processing data points." CR));
#endif
// Print the formula based on 'order'
if( order == 4 ) {
sprintf( formulaBuffer, "%.8f*tilt^4+%.8f*tilt^3+%.8f*tilt^2+%.8f*tilt+%.8f", coeffs[0], coeffs[1], coeffs[2], coeffs[3], coeffs[4] );
@ -72,6 +75,10 @@ int createFormula( RawFormulaData& fd, char *formulaBuffer, int order ) {
sprintf( formulaBuffer, "%.8f*tilt+%.8f", coeffs[0], coeffs[1] );
}
#if LOG_LEVEL==6
Log.verbose(F("CALC: Formula: %s" CR), formulaBuffer );
#endif
bool valid = true;
for( int i = 0; i < 5; i++ ) {

View File

@ -60,6 +60,8 @@ void Config::createJson(DynamicJsonDocument& doc) {
doc[ CFG_PARAM_MDNS ] = getMDNS();
doc[ CFG_PARAM_ID ] = getID();
doc[ CFG_PARAM_OTA ] = getOtaURL();
doc[ CFG_PARAM_SSID ] = getWifiSSID();
doc[ CFG_PARAM_PASS ] = getWifiPass();
doc[ CFG_PARAM_TEMPFORMAT ] = String( getTempFormat() );
doc[ CFG_PARAM_PUSH_BREWFATHER ] = getBrewfatherPushUrl();
doc[ CFG_PARAM_PUSH_HTTP ] = getHttpPushUrl();
@ -178,6 +180,10 @@ bool Config::loadFile() {
setOtaURL( doc[ CFG_PARAM_OTA ] );
if( !doc[ CFG_PARAM_MDNS ].isNull() )
setMDNS( doc[ CFG_PARAM_MDNS ] );
if( !doc[ CFG_PARAM_SSID ].isNull() )
setWifiSSID( doc[ CFG_PARAM_SSID ] );
if( !doc[ CFG_PARAM_PASS ].isNull() )
setWifiPass( doc[ CFG_PARAM_PASS ] );
if( !doc[ CFG_PARAM_TEMPFORMAT ].isNull() ) {
String s = doc[ CFG_PARAM_TEMPFORMAT ];
setTempFormat( s.charAt(0) );
@ -287,6 +293,7 @@ void Config::debug() {
#if LOG_LEVEL==6
Log.verbose(F("CFG : Dumping configration " CFG_FILENAME "." CR));
Log.verbose(F("CFG : ID; '%s'." CR), getID());
Log.verbose(F("CFG : WIFI; '%s', '%s'." CR), getWifiSSID(), getWifiPass() );
Log.verbose(F("CFG : mDNS; '%s'." CR), getMDNS() );
Log.verbose(F("CFG : Sleep interval; %d." CR), getSleepInterval() );
Log.verbose(F("CFG : OTA; '%s'." CR), getOtaURL() );

View File

@ -45,6 +45,9 @@ SOFTWARE.
#define CFG_PARAM_ID "id"
#define CFG_PARAM_MDNS "mdns" // Device name
#define CFG_PARAM_OTA "ota-url" // Base URL for OTA
#define CFG_PARAM_SSID "wifi-ssid" // WIFI
#define CFG_PARAM_PASS "wifi-pass" // WIFI
#define CFG_PARAM_PUSH_BREWFATHER "brewfather-push" // URL (brewfather format)
#define CFG_PARAM_PUSH_HTTP "http-push" // URL (iSpindle format)
#define CFG_PARAM_PUSH_HTTP2 "http-push2" // URL (iSpindle format)
@ -109,6 +112,10 @@ class Config {
float tempSensorAdj; // This value will be added to the read sensor value
int sleepInterval;
// Wifi Config
String wifiSSID;
String wifiPASS;
// Push target settings
String brewfatherPushUrl; // URL For brewfather
@ -143,6 +150,11 @@ class Config {
void setOtaURL( String s ) { otaURL = s; saveNeeded = true; }
bool isOtaActive() { return otaURL.length()?true:false; }
const char* getWifiSSID() { return wifiSSID.c_str(); }
void setWifiSSID( String s ) { wifiSSID = s; saveNeeded = true; }
const char* getWifiPass() { return wifiPASS.c_str(); }
void setWifiPass( String s ) { wifiPASS = s; saveNeeded = true; }
// Brewfather
const char* getBrewfatherPushUrl() { return brewfatherPushUrl.c_str(); }
void setBrewfatherPushUrl( String s ) { brewfatherPushUrl = s; saveNeeded = true; }

View File

@ -226,6 +226,8 @@ bool GyroSensor::read() {
#if LOG_LEVEL==6
Log.verbose(F("GYRO: Getting new gyro position." CR) );
#endif
if( !sensorConnected )
return false;
readSensor( lastGyroData, SENSOR_READ_COUNT, SENSOR_READ_DELAY ); // Last param is unused if GYRO_USE_INTERRUPT is defined.

View File

@ -114,20 +114,11 @@ void setup() {
ESP.wdtDisable();
ESP.wdtEnable( interval*2 );
LOG_PERF_START("main-temp-setup");
myTempSensor.setup();
LOG_PERF_STOP("main-temp-setup");
if( dt ) {
Log.notice(F("Main: Detected doubletap on reset. Reset reason=%s" CR), ESP.getResetReason().c_str());
}
// Setup Gyro
//LOG_PERF_START("main-gyro-setup"); // Takes less than 5ms, so skip this measurment
if( !myGyro.setup() )
Log.error(F("Main: Failed to initialize the gyro." CR));
//LOG_PERF_STOP("main-gyro-setup");
if( dt )
Log.notice(F("Main: Detected doubletap on reset." CR));
#ifdef DEACTIVATE_SLEEPMODE
#ifdef SKIP_SLEEPMODE
// If we are running in debug more we skip this part. makes is hard to debug in case of crash/watchdog reset
dt = false;
#endif
@ -136,6 +127,15 @@ void setup() {
myWifi.connect( dt ); // This will return false if unable to connect to wifi, will be handled in loop()
LOG_PERF_STOP("main-wifi-connect");
LOG_PERF_START("main-temp-setup");
myTempSensor.setup();
LOG_PERF_STOP("main-temp-setup");
//LOG_PERF_START("main-gyro-setup"); // Takes less than 5ms, so skip this measurment
if( !myGyro.setup() )
Log.error(F("Main: Failed to initialize the gyro." CR));
//LOG_PERF_STOP("main-gyro-setup");
LOG_PERF_START("main-gyro-read");
myGyro.read();
LOG_PERF_STOP("main-gyro-read");
@ -278,7 +278,7 @@ void loop() {
//#endif
}
if( myWifi.isConnected() )
//if( myWifi.isConnected() )
myWebServer.loop();
}

View File

@ -28,34 +28,16 @@ SOFTWARE.
#include "calc.h"
#include "tempsensor.h"
#include <ArduinoJson.h>
#include <incbin.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <LittleFS.h>
// Binary resouces
#if defined( EMBED_HTML )
INCBIN_EXTERN(IndexHtm);
INCBIN_EXTERN(DeviceHtm);
INCBIN_EXTERN(ConfigHtm);
INCBIN_EXTERN(CalibrationHtm);
INCBIN_EXTERN(AboutHtm);
#else
INCBIN_EXTERN(UploadHtm);
#endif
WebServer myWebServer; // My wrapper class fr webserver functions
ESP8266WebServer server(80);
int lastFormulaCreateError = 0;
extern bool sleepModeActive;
extern bool sleepModeAlwaysSkip;
//
// Callback from webServer when / has been accessed.
//
void webHandleDevice() {
void WebServer::webHandleDevice() {
LOG_PERF_START("webserver-api-device");
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/config." CR));
@ -71,14 +53,14 @@ void webHandleDevice() {
#endif
String out;
serializeJson(doc, out);
server.send(200, "application/json", out.c_str() );
server->send(200, "application/json", out.c_str() );
LOG_PERF_STOP("webserver-api-device");
}
//
// Callback from webServer when / has been accessed.
//
void webHandleConfig() {
void WebServer::webHandleConfig() {
LOG_PERF_START("webserver-api-config");
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/config." CR));
@ -103,14 +85,14 @@ void webHandleConfig() {
#endif
String out;
serializeJson(doc, out);
server.send(200, "application/json", out.c_str() );
server->send(200, "application/json", out.c_str() );
LOG_PERF_STOP("webserver-api-config");
}
//
// Callback from webServer when / has been accessed.
//
void webHandleUpload() {
void WebServer::webHandleUpload() {
LOG_PERF_START("webserver-api-upload");
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/upload." CR));
@ -130,21 +112,19 @@ void webHandleUpload() {
#endif
String out;
serializeJson(doc, out);
server.send(200, "application/json", out.c_str() );
server->send(200, "application/json", out.c_str() );
LOG_PERF_STOP("webserver-api-upload");
}
//
// Callback from webServer when / has been accessed.
//
File uploadFile;
void webHandleUploadFile() {
void WebServer::webHandleUploadFile() {
LOG_PERF_START("webserver-api-upload-file");
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/upload/file." CR));
#endif
HTTPUpload& upload = server.upload();
HTTPUpload& upload = server->upload();
String f = upload.filename;
bool validFilename = false;
@ -169,10 +149,10 @@ void webHandleUploadFile() {
uploadFile.close();
Log.notice(F("WEB : File uploaded %d bytes." CR), upload.totalSize);
}
server.sendHeader("Location","/");
server.send(303);
server->sendHeader("Location","/");
server->send(303);
} else {
server.send(500, "text/plain", "Couldn't create file.");
server->send(500, "text/plain", "Couldn't create file.");
}
LOG_PERF_STOP("webserver-api-upload-file");
}
@ -180,46 +160,46 @@ void webHandleUploadFile() {
//
// Callback from webServer when / has been accessed.
//
void webHandleCalibrate() {
void WebServer::webHandleCalibrate() {
LOG_PERF_START("webserver-api-calibrate");
String id = server.arg( CFG_PARAM_ID );
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/calibrate." CR));
#endif
if( !id.equalsIgnoreCase( myConfig.getID() ) ) {
Log.error(F("WEB : Wrong ID received %s, expected %s" CR), id.c_str(), myConfig.getID());
server.send(400, "text/plain", "Invalid ID.");
server->send(400, "text/plain", "Invalid ID.");
LOG_PERF_STOP("webserver-api-calibrate");
return;
}
myGyro.calibrateSensor();
server.send(200, "text/plain", "Device calibrated" );
server->send(200, "text/plain", "Device calibrated" );
LOG_PERF_STOP("webserver-api-calibrate");
}
//
// Callback from webServer when / has been accessed.
//
void webHandleFactoryReset() {
String id = server.arg( CFG_PARAM_ID );
void WebServer::webHandleFactoryReset() {
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/factory." CR));
#endif
if( !id.compareTo( myConfig.getID() ) ) {
server.send(200, "text/plain", "Doing reset...");
server->send(200, "text/plain", "Doing reset...");
LittleFS.remove(CFG_FILENAME);
LittleFS.end();
delay(500);
ESP.reset();
} else {
server.send(400, "text/plain", "Unknown ID.");
server->send(400, "text/plain", "Unknown ID.");
}
}
//
// Callback from webServer when / has been accessed.
//
void webHandleStatus() {
void WebServer::webHandleStatus() {
LOG_PERF_START("webserver-api-status");
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/status." CR));
@ -248,173 +228,173 @@ void webHandleStatus() {
#endif
String out;
serializeJson(doc, out);
server.send(200, "application/json", out.c_str() );
server->send(200, "application/json", out.c_str() );
LOG_PERF_STOP("webserver-api-status");
}
//
// Callback from webServer when / has been accessed.
//
void webHandleClearWIFI() {
String id = server.arg( CFG_PARAM_ID );
void WebServer::webHandleClearWIFI() {
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/clearwifi." CR));
#endif
if( !id.compareTo( myConfig.getID() ) ) {
server.send(200, "text/plain", "Clearing WIFI credentials and doing reset...");
server->send(200, "text/plain", "Clearing WIFI credentials and doing reset...");
delay(1000);
WiFi.disconnect(); // Clear credentials
ESP.reset();
} else {
server.send(400, "text/plain", "Unknown ID.");
server->send(400, "text/plain", "Unknown ID.");
}
}
//
// Used to force the device to never sleep.
//
void webHandleStatusSleepmode() {
void WebServer::webHandleStatusSleepmode() {
LOG_PERF_START("webserver-api-sleepmode");
String id = server.arg( CFG_PARAM_ID );
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/status/sleepmode." CR) );
#endif
if( !id.equalsIgnoreCase( myConfig.getID() ) ) {
Log.error(F("WEB : Wrong ID received %s, expected %s" CR), id.c_str(), myConfig.getID());
server.send(400, "text/plain", "Invalid ID.");
server->send(400, "text/plain", "Invalid ID.");
LOG_PERF_STOP("webserver-api-sleepmode");
return;
}
#if LOG_LEVEL==6
Log.verbose(F("WEB : sleep-mode=%s." CR), server.arg( CFG_PARAM_SLEEP_MODE ).c_str() );
Log.verbose(F("WEB : sleep-mode=%s." CR), server->arg( CFG_PARAM_SLEEP_MODE ).c_str() );
#endif
if( server.arg( CFG_PARAM_SLEEP_MODE ).equalsIgnoreCase( "true" ) )
if( server->arg( CFG_PARAM_SLEEP_MODE ).equalsIgnoreCase( "true" ) )
sleepModeAlwaysSkip = true;
else
sleepModeAlwaysSkip = false;
server.send(200, "text/plain", "Sleep mode updated" );
server->send(200, "text/plain", "Sleep mode updated" );
LOG_PERF_STOP("webserver-api-sleepmode");
}
//
// Update device settings.
//
void webHandleConfigDevice() {
void WebServer::webHandleConfigDevice() {
LOG_PERF_START("webserver-api-config-device");
String id = server.arg( CFG_PARAM_ID );
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/config/device." CR) );
#endif
if( !id.equalsIgnoreCase( myConfig.getID() ) ) {
Log.error(F("WEB : Wrong ID received %s, expected %s" CR), id.c_str(), myConfig.getID());
server.send(400, "text/plain", "Invalid ID.");
server->send(400, "text/plain", "Invalid ID.");
LOG_PERF_STOP("webserver-api-config-device");
return;
}
#if LOG_LEVEL==6
Log.verbose(F("WEB : mdns=%s, temp-format=%s." CR), server.arg( CFG_PARAM_MDNS ).c_str(), server.arg( CFG_PARAM_TEMPFORMAT ).c_str() );
Log.verbose(F("WEB : mdns=%s, temp-format=%s." CR), server->arg( CFG_PARAM_MDNS ).c_str(), server->arg( CFG_PARAM_TEMPFORMAT ).c_str() );
#endif
myConfig.setMDNS( server.arg( CFG_PARAM_MDNS ).c_str() );
myConfig.setTempFormat( server.arg( CFG_PARAM_TEMPFORMAT ).charAt(0) );
myConfig.setSleepInterval( server.arg( CFG_PARAM_SLEEP_INTERVAL ).c_str() );
myConfig.setMDNS( server->arg( CFG_PARAM_MDNS ).c_str() );
myConfig.setTempFormat( server->arg( CFG_PARAM_TEMPFORMAT ).charAt(0) );
myConfig.setSleepInterval( server->arg( CFG_PARAM_SLEEP_INTERVAL ).c_str() );
myConfig.saveFile();
server.sendHeader("Location", "/config.htm#collapseOne", true);
server.send(302, "text/plain", "Device config updated" );
server->sendHeader("Location", "/config.htm#collapseOne", true);
server->send(302, "text/plain", "Device config updated" );
LOG_PERF_STOP("webserver-api-config-device");
}
//
// Update push settings.
//
void webHandleConfigPush() {
void WebServer::webHandleConfigPush() {
LOG_PERF_START("webserver-api-config-push");
String id = server.arg( CFG_PARAM_ID );
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/config/push." CR) );
#endif
if( !id.equalsIgnoreCase( myConfig.getID() ) ) {
Log.error(F("WEB : Wrong ID received %s, expected %s" CR), id.c_str(), myConfig.getID());
server.send(400, "text/plain", "Invalid ID.");
server->send(400, "text/plain", "Invalid ID.");
LOG_PERF_STOP("webserver-api-config-push");
return;
}
#if LOG_LEVEL==6
Log.verbose(F("WEB : http=%s,%s, bf=%s influx2=%s, %s, %s, %s." CR), server.arg( CFG_PARAM_PUSH_HTTP ).c_str(),
server.arg( CFG_PARAM_PUSH_HTTP2 ).c_str(), server.arg( CFG_PARAM_PUSH_BREWFATHER ).c_str(),
server.arg( CFG_PARAM_PUSH_INFLUXDB2 ).c_str(), server.arg( CFG_PARAM_PUSH_INFLUXDB2_ORG ).c_str(),
server.arg( CFG_PARAM_PUSH_INFLUXDB2_BUCKET ).c_str(), server.arg( CFG_PARAM_PUSH_INFLUXDB2_AUTH ).c_str()
Log.verbose(F("WEB : http=%s,%s, bf=%s influx2=%s, %s, %s, %s." CR), server->arg( CFG_PARAM_PUSH_HTTP ).c_str(),
server->arg( CFG_PARAM_PUSH_HTTP2 ).c_str(), server->arg( CFG_PARAM_PUSH_BREWFATHER ).c_str(),
server->arg( CFG_PARAM_PUSH_INFLUXDB2 ).c_str(), server->arg( CFG_PARAM_PUSH_INFLUXDB2_ORG ).c_str(),
server->arg( CFG_PARAM_PUSH_INFLUXDB2_BUCKET ).c_str(), server->arg( CFG_PARAM_PUSH_INFLUXDB2_AUTH ).c_str()
);
#endif
myConfig.setHttpPushUrl( server.arg( CFG_PARAM_PUSH_HTTP ).c_str() );
myConfig.setHttpPushUrl2( server.arg( CFG_PARAM_PUSH_HTTP2 ).c_str() );
myConfig.setBrewfatherPushUrl( server.arg( CFG_PARAM_PUSH_BREWFATHER ).c_str() );
myConfig.setInfluxDb2PushUrl( server.arg( CFG_PARAM_PUSH_INFLUXDB2 ).c_str() );
myConfig.setInfluxDb2PushOrg( server.arg( CFG_PARAM_PUSH_INFLUXDB2_ORG ).c_str() );
myConfig.setInfluxDb2PushBucket( server.arg( CFG_PARAM_PUSH_INFLUXDB2_BUCKET ).c_str() );
myConfig.setInfluxDb2PushToken( server.arg( CFG_PARAM_PUSH_INFLUXDB2_AUTH ).c_str() );
myConfig.setHttpPushUrl( server->arg( CFG_PARAM_PUSH_HTTP ).c_str() );
myConfig.setHttpPushUrl2( server->arg( CFG_PARAM_PUSH_HTTP2 ).c_str() );
myConfig.setBrewfatherPushUrl( server->arg( CFG_PARAM_PUSH_BREWFATHER ).c_str() );
myConfig.setInfluxDb2PushUrl( server->arg( CFG_PARAM_PUSH_INFLUXDB2 ).c_str() );
myConfig.setInfluxDb2PushOrg( server->arg( CFG_PARAM_PUSH_INFLUXDB2_ORG ).c_str() );
myConfig.setInfluxDb2PushBucket( server->arg( CFG_PARAM_PUSH_INFLUXDB2_BUCKET ).c_str() );
myConfig.setInfluxDb2PushToken( server->arg( CFG_PARAM_PUSH_INFLUXDB2_AUTH ).c_str() );
myConfig.saveFile();
server.sendHeader("Location", "/config.htm#collapseTwo", true);
server.send(302, "text/plain", "Push config updated" );
server->sendHeader("Location", "/config.htm#collapseTwo", true);
server->send(302, "text/plain", "Push config updated" );
LOG_PERF_STOP("webserver-api-config-push");
}
//
// Update gravity settings.
//
void webHandleConfigGravity() {
void WebServer::webHandleConfigGravity() {
LOG_PERF_START("webserver-api-config-gravity");
String id = server.arg( CFG_PARAM_ID );
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/config/gravity." CR) );
#endif
if( !id.equalsIgnoreCase( myConfig.getID() ) ) {
Log.error(F("WEB : Wrong ID received %s, expected %s" CR), id.c_str(), myConfig.getID());
server.send(400, "text/plain", "Invalid ID.");
server->send(400, "text/plain", "Invalid ID.");
LOG_PERF_STOP("webserver-api-config-gravity");
return;
}
#if LOG_LEVEL==6
Log.verbose(F("WEB : formula=%s, temp-corr=%s." CR), server.arg( CFG_PARAM_GRAVITY_FORMULA ).c_str(), server.arg( CFG_PARAM_GRAVITY_TEMP_ADJ ).c_str() );
Log.verbose(F("WEB : formula=%s, temp-corr=%s." CR), server->arg( CFG_PARAM_GRAVITY_FORMULA ).c_str(), server->arg( CFG_PARAM_GRAVITY_TEMP_ADJ ).c_str() );
#endif
myConfig.setGravityFormula( server.arg( CFG_PARAM_GRAVITY_FORMULA ).c_str() );
myConfig.setGravityTempAdj( server.arg( CFG_PARAM_GRAVITY_TEMP_ADJ ).equalsIgnoreCase( "on" ) ? true:false);
myConfig.setGravityFormula( server->arg( CFG_PARAM_GRAVITY_FORMULA ).c_str() );
myConfig.setGravityTempAdj( server->arg( CFG_PARAM_GRAVITY_TEMP_ADJ ).equalsIgnoreCase( "on" ) ? true:false);
myConfig.saveFile();
server.sendHeader("Location", "/config.htm#collapseThree", true);
server.send(302, "text/plain", "Gravity config updated" );
server->sendHeader("Location", "/config.htm#collapseThree", true);
server->send(302, "text/plain", "Gravity config updated" );
LOG_PERF_STOP("webserver-api-config-gravity");
}
//
// Update hardware settings.
//
void webHandleConfigHardware() {
void WebServer::webHandleConfigHardware() {
LOG_PERF_START("webserver-api-config-hardware");
String id = server.arg( CFG_PARAM_ID );
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/config/hardware." CR) );
#endif
if( !id.equalsIgnoreCase( myConfig.getID() ) ) {
Log.error(F("WEB : Wrong ID received %s, expected %s" CR), id.c_str(), myConfig.getID());
server.send(400, "text/plain", "Invalid ID.");
server->send(400, "text/plain", "Invalid ID.");
LOG_PERF_STOP("webserver-api-config-hardware");
return;
}
#if LOG_LEVEL==6
Log.verbose(F("WEB : vf=%s, tempadj=%s, ota=%s." CR), server.arg( CFG_PARAM_VOLTAGEFACTOR ).c_str(), server.arg( CFG_PARAM_TEMP_ADJ ).c_str(), server.arg( CFG_PARAM_OTA ).c_str() );
Log.verbose(F("WEB : vf=%s, tempadj=%s, ota=%s." CR), server->arg( CFG_PARAM_VOLTAGEFACTOR ).c_str(), server->arg( CFG_PARAM_TEMP_ADJ ).c_str(), server->arg( CFG_PARAM_OTA ).c_str() );
#endif
myConfig.setVoltageFactor( server.arg( CFG_PARAM_VOLTAGEFACTOR ).toFloat() );
myConfig.setTempSensorAdj( server.arg( CFG_PARAM_TEMP_ADJ ).toFloat() );
myConfig.setOtaURL( server.arg( CFG_PARAM_OTA ).c_str() );
myConfig.setVoltageFactor( server->arg( CFG_PARAM_VOLTAGEFACTOR ).toFloat() );
myConfig.setTempSensorAdj( server->arg( CFG_PARAM_TEMP_ADJ ).toFloat() );
myConfig.setOtaURL( server->arg( CFG_PARAM_OTA ).c_str() );
myConfig.saveFile();
server.sendHeader("Location", "/config.htm#collapseFour", true);
server.send(302, "text/plain", "Hardware config updated" );
server->sendHeader("Location", "/config.htm#collapseFour", true);
server->send(302, "text/plain", "Hardware config updated" );
LOG_PERF_STOP("webserver-api-config-hardware");
}
//
// Callback from webServer when / has been accessed.
//
void webHandleFormulaRead() {
void WebServer::webHandleFormulaRead() {
LOG_PERF_START("webserver-api-formula-read");
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/formula/get." CR));
@ -463,61 +443,61 @@ void webHandleFormulaRead() {
#endif
String out;
serializeJson(doc, out);
server.send(200, "application/json", out.c_str() );
server->send(200, "application/json", out.c_str() );
LOG_PERF_STOP("webserver-api-formula-read");
}
//
// Update hardware settings.
//
void webHandleFormulaWrite() {
void WebServer::webHandleFormulaWrite() {
LOG_PERF_START("webserver-api-formula-write");
String id = server.arg( CFG_PARAM_ID );
String id = server->arg( CFG_PARAM_ID );
#if LOG_LEVEL==6
Log.verbose(F("WEB : webServer callback for /api/formula/post." CR) );
#endif
if( !id.equalsIgnoreCase( myConfig.getID() ) ) {
Log.error(F("WEB : Wrong ID received %s, expected %s" CR), id.c_str(), myConfig.getID());
server.send(400, "text/plain", "Invalid ID.");
server->send(400, "text/plain", "Invalid ID.");
LOG_PERF_STOP("webserver-api-formula-write");
return;
}
#if LOG_LEVEL==6
Log.verbose(F("WEB : angles=%F,%F,%F,%F,%F." CR), server.arg( "a1" ).toFloat(), server.arg( "a2" ).toFloat(), server.arg( "a3" ).toFloat(), server.arg( "a4" ).toFloat(), server.arg( "a5" ).toFloat() );
Log.verbose(F("WEB : gravity=%F,%F,%F,%F,%F." CR), server.arg( "g1" ).toFloat(), server.arg( "g2" ).toFloat(), server.arg( "g3" ).toFloat(), server.arg( "g4" ).toFloat(), server.arg( "g5" ).toFloat() );
Log.verbose(F("WEB : angles=%F,%F,%F,%F,%F." CR), server->arg( "a1" ).toFloat(), server->arg( "a2" ).toFloat(), server->arg( "a3" ).toFloat(), server->arg( "a4" ).toFloat(), server->arg( "a5" ).toFloat() );
Log.verbose(F("WEB : gravity=%F,%F,%F,%F,%F." CR), server->arg( "g1" ).toFloat(), server->arg( "g2" ).toFloat(), server->arg( "g3" ).toFloat(), server->arg( "g4" ).toFloat(), server->arg( "g5" ).toFloat() );
#endif
RawFormulaData fd;
fd.a[0] = server.arg( "a1" ).toDouble();
fd.a[1] = server.arg( "a2" ).toDouble();
fd.a[2] = server.arg( "a3" ).toDouble();
fd.a[3] = server.arg( "a4" ).toDouble();
fd.a[4] = server.arg( "a5" ).toDouble();
fd.g[0] = server.arg( "g1" ).toDouble();
fd.g[1] = server.arg( "g2" ).toDouble();
fd.g[2] = server.arg( "g3" ).toDouble();
fd.g[3] = server.arg( "g4" ).toDouble();
fd.g[4] = server.arg( "g5" ).toDouble();
fd.a[0] = server->arg( "a1" ).toDouble();
fd.a[1] = server->arg( "a2" ).toDouble();
fd.a[2] = server->arg( "a3" ).toDouble();
fd.a[3] = server->arg( "a4" ).toDouble();
fd.a[4] = server->arg( "a5" ).toDouble();
fd.g[0] = server->arg( "g1" ).toDouble();
fd.g[1] = server->arg( "g2" ).toDouble();
fd.g[2] = server->arg( "g3" ).toDouble();
fd.g[3] = server->arg( "g4" ).toDouble();
fd.g[4] = server->arg( "g5" ).toDouble();
myConfig.setFormulaData( fd );
int e;
char buf[100];
e = createFormula( fd, &buf[0], 4 );
e = createFormula( fd, &buf[0], 2 );
if( e ) {
// If we fail with order=4 try with 3
Log.warning(F("WEB : Failed to find formula with order 4." CR), e );
// If we fail with order=2 try with 3
Log.warning(F("WEB : Failed to find formula with order 3." CR), e );
e = createFormula( fd, &buf[0], 3 );
}
if( e ) {
// If we fail with order=3 try with 2
Log.warning(F("WEB : Failed to find formula with order 3." CR), e );
e = createFormula( fd, &buf[0], 2 );
// If we fail with order=3 try with 4
Log.warning(F("WEB : Failed to find formula with order 4." CR), e );
e = createFormula( fd, &buf[0], 4 );
}
if( e ) {
// If we fail with order=2 then we mark it as failed
// If we fail with order=4 then we mark it as failed
Log.error(F("WEB : Unable to find formula based on provided values err=%d." CR), e );
lastFormulaCreateError = e;
} else {
@ -528,8 +508,8 @@ void webHandleFormulaWrite() {
}
myConfig.saveFile();
server.sendHeader("Location", "/calibration.htm", true);
server.send(302, "text/plain", "Formula updated" );
server->sendHeader("Location", "/calibration.htm", true);
server->send(302, "text/plain", "Formula updated" );
LOG_PERF_STOP("webserver-api-formula-write");
}
//
@ -570,35 +550,34 @@ bool WebServer::checkHtmlFile( HtmlFile item ) {
return LittleFS.exists( fn );
}
//
// Handler for page not found
//
void WebServer::webHandlePageNotFound()
{
Log.error(F("WEB : URL not found %s received." CR), server->uri().c_str());
server->send(404, "text/plain", F("URL not found") );
}
//
// Setup the Web Server callbacks and start it
//
bool WebServer::setupWebServer() {
Log.notice(F("WEB : Configuring web server." CR));
server = new ESP8266WebServer();
MDNS.begin( myConfig.getMDNS() );
MDNS.addService("http", "tcp", 80);
// Static content
#if defined( EMBED_HTML )
server.on("/",[]() {
server.send_P(200, "text/html", (const char*) gIndexHtmData, gIndexHtmSize );
} );
server.on("/index.htm",[]() {
server.send_P(200, "text/html", (const char*) gIndexHtmData, gIndexHtmSize );
} );
server.on("/device.htm",[]() {
server.send_P(200, "text/html", (const char*) gDeviceHtmData, gDeviceHtmSize );
} );
server.on("/config.htm",[]() {
server.send_P(200, "text/html", (const char*) gConfigHtmData, gConfigHtmSize );
} );
server.on("/calibration.htm",[]() {
server.send_P(200, "text/html", (const char*) gCalibrationHtmData, gCalibrationHtmSize );
} );
server.on("/about.htm",[]() {
server.send_P(200, "text/html", (const char*) gAboutHtmData, gAboutHtmSize );
} );
server->on("/", std::bind(&WebServer::webReturnIndexHtm, this) );
server->on("/index.htm", std::bind(&WebServer::webReturnIndexHtm, this) );
server->on("/device.htm", std::bind(&WebServer::webReturnDeviceHtm, this) );
server->on("/config.htm", std::bind(&WebServer::webReturnConfigHtm, this) );
server->on("/calibration.htm", std::bind(&WebServer::webReturnCalibrationHtm, this) );
server->on("/about.htm", std::bind(&WebServer::webReturnAboutHtm, this) );
#else
// Show files in the filessytem at startup
@ -614,50 +593,41 @@ bool WebServer::setupWebServer() {
if( checkHtmlFile( HTML_INDEX ) && checkHtmlFile( HTML_DEVICE ) && checkHtmlFile( HTML_CONFIG ) && checkHtmlFile( HTML_ABOUT ) ) {
Log.notice(F("WEB : All html files exist, starting in normal mode." CR));
server.serveStatic("/", LittleFS, "/index.min.htm" );
server.serveStatic("/index.htm", LittleFS, "/index.min.htm" );
server.serveStatic("/device.htm", LittleFS, "/device.min.htm" );
server.serveStatic("/config.htm", LittleFS, "/config.min.htm" );
server.serveStatic("/about.htm", LittleFS, "/about.min.htm" );
server.serveStatic("/calibration.htm", LittleFS, "/calibration.min.htm" );
server->serveStatic("/", LittleFS, "/index.min.htm" );
server->serveStatic("/index.htm", LittleFS, "/index.min.htm" );
server->serveStatic("/device.htm", LittleFS, "/device.min.htm" );
server->serveStatic("/config.htm", LittleFS, "/config.min.htm" );
server->serveStatic("/about.htm", LittleFS, "/about.min.htm" );
server->serveStatic("/calibration.htm", LittleFS, "/calibration.min.htm" );
// Also add the static upload view in case we we have issues that needs to be fixed.
server.on("/upload.htm",[]() {
server.send_P(200, "text/html", (const char*) gUploadHtmData, gUploadHtmSize );
} );
server->on("/upload.htm", std::bind(&WebServer::webReturnUploadHtm, this) );
} else {
Log.error(F("WEB : Missing html files, starting with upload UI." CR));
server.on("/",[]() {
server.send_P(200, "text/html", (const char*) gUploadHtmData, gUploadHtmSize );
} );
server->on("/", std::bind(&WebServer::webReturnUploadHtm, this) );
}
#endif
// Dynamic content
server.on("/api/config", HTTP_GET, webHandleConfig); // Get config.json
server.on("/api/device", HTTP_GET, webHandleDevice); // Get device.json
server.on("/api/formula", HTTP_GET, webHandleFormulaRead); // Get formula.json (calibration page)
server.on("/api/formula", HTTP_POST, webHandleFormulaWrite); // Get formula.json (calibration page)
server.on("/api/calibrate", HTTP_POST, webHandleCalibrate); // Run calibration routine (param id)
server.on("/api/factory", HTTP_GET, webHandleFactoryReset); // Reset the device
server.on("/api/status", HTTP_GET, webHandleStatus); // Get the status.json
server.on("/api/clearwifi", HTTP_GET, webHandleClearWIFI); // Clear wifi settings
server.on("/api/upload", HTTP_GET, webHandleUpload); // Get upload.json
server->on("/api/config", HTTP_GET, std::bind(&WebServer::webHandleConfig, this) ); // Get config.json
server->on("/api/device", HTTP_GET, std::bind(&WebServer::webHandleDevice, this)); // Get device.json
server->on("/api/formula", HTTP_GET, std::bind(&WebServer::webHandleFormulaRead, this)); // Get formula.json (calibration page)
server->on("/api/formula", HTTP_POST, std::bind(&WebServer::webHandleFormulaWrite, this)); // Get formula.json (calibration page)
server->on("/api/calibrate", HTTP_POST, std::bind(&WebServer::webHandleCalibrate, this)); // Run calibration routine (param id)
server->on("/api/factory", HTTP_GET, std::bind(&WebServer::webHandleFactoryReset, this)); // Reset the device
server->on("/api/status", HTTP_GET, std::bind(&WebServer::webHandleStatus, this)); // Get the status.json
server->on("/api/clearwifi", HTTP_GET, std::bind(&WebServer::webHandleClearWIFI, this)); // Clear wifi settings
server->on("/api/upload", HTTP_GET, std::bind(&WebServer::webHandleUpload, this)); // Get upload.json
server.on("/api/upload", HTTP_POST, [](){ server.send(200); }, webHandleUploadFile); // File upload data
server.on("/api/status/sleepmode", HTTP_POST, webHandleStatusSleepmode); // Change sleep mode
server.on("/api/config/device", HTTP_POST, webHandleConfigDevice); // Change device settings
server.on("/api/config/push", HTTP_POST, webHandleConfigPush); // Change push settings
server.on("/api/config/gravity", HTTP_POST, webHandleConfigGravity); // Change gravity settings
server.on("/api/config/hardware", HTTP_POST, webHandleConfigHardware); // Change hardware settings
server->on("/api/upload", HTTP_POST, std::bind(&WebServer::webReturnOK, this), std::bind(&WebServer::webHandleUploadFile, this)); // File upload data
server->on("/api/status/sleepmode", HTTP_POST, std::bind(&WebServer::webHandleStatusSleepmode, this)); // Change sleep mode
server->on("/api/config/device", HTTP_POST, std::bind(&WebServer::webHandleConfigDevice, this)); // Change device settings
server->on("/api/config/push", HTTP_POST, std::bind(&WebServer::webHandleConfigPush, this)); // Change push settings
server->on("/api/config/gravity", HTTP_POST, std::bind(&WebServer::webHandleConfigGravity, this)); // Change gravity settings
server->on("/api/config/hardware", HTTP_POST, std::bind(&WebServer::webHandleConfigHardware, this)); // Change hardware settings
server.onNotFound( []() {
Log.error(F("WEB : URL not found %s received." CR), server.uri().c_str());
server.send(404, "text/plain", F("URL not found") );
} );
server.begin();
server->onNotFound( std::bind(&WebServer::webHandlePageNotFound, this));
server->begin();
Log.notice(F("WEB : Web server started." CR));
return true;
}
@ -667,7 +637,7 @@ bool WebServer::setupWebServer() {
//
void WebServer::loop() {
// Dont put serial debug output in this call
server.handleClient();
server->handleClient();
MDNS.update();
}

View File

@ -25,9 +25,58 @@ SOFTWARE.
#define _WEBSERVER_H
// Include
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <incbin.h>
// Binary resouces
#if defined( EMBED_HTML )
INCBIN_EXTERN(IndexHtm);
INCBIN_EXTERN(DeviceHtm);
INCBIN_EXTERN(ConfigHtm);
INCBIN_EXTERN(CalibrationHtm);
INCBIN_EXTERN(AboutHtm);
#else
INCBIN_EXTERN(UploadHtm);
#endif
// classes
class WebServer {
private:
ESP8266WebServer *server = 0;
File uploadFile;
int lastFormulaCreateError = 0;
void webHandleConfig();
void webHandleFormulaWrite();
void webHandleFormulaRead();
void webHandleConfigHardware();
void webHandleConfigGravity();
void webHandleConfigPush();
void webHandleConfigDevice();
void webHandleStatusSleepmode();
void webHandleClearWIFI();
void webHandleStatus();
void webHandleFactoryReset();
void webHandleCalibrate();
void webHandleUploadFile();
void webHandleUpload();
void webHandleDevice();
void webHandlePageNotFound();
// Inline functions.
void webReturnOK() { server->send(200); }
#if defined( EMBED_HTML )
void webReturnIndexHtm() { server->send_P(200, "text/html", (const char*) gIndexHtmData, gIndexHtmSize ); }
void webReturnDeviceHtm() { server->send_P(200, "text/html", (const char*) gDeviceHtmData, gDeviceHtmSize ); }
void webReturnConfigHtm() { server->send_P(200, "text/html", (const char*) gConfigHtmData, gConfigHtmSize ); }
void webReturnCalibrationHtm() { server->send_P(200, "text/html", (const char*) gCalibrationHtmData, gCalibrationHtmSize ); }
void webReturnAboutHtm() { server->send_P(200, "text/html", (const char*) gAboutHtmData, gAboutHtmSize ); }
#else
void webReturnUploadHtm() { server->send_P(200, "text/html", (const char*) gUploadHtmData, gUploadHtmSize ); }
#endif
public:
enum HtmlFile {
HTML_INDEX = 0,

View File

@ -45,49 +45,63 @@ const char* userPWD = USER_SSID_PWD;
//
bool Wifi::connect( bool showPortal ) {
WiFi.persistent( true );
WiFi.mode(WIFI_STA);
WiFiManager myWifiManager;
if( myWifiManager.getWiFiSSID().length()==0 ) {
if( !strlen( myConfig.getWifiSSID() ) ) {
Log.info(F("WIFI: No SSID seams to be stored, forcing portal to start." CR));
showPortal = true;
} else {
Log.info(F("WIFI: Using SSID=%s and %s." CR), myConfig.getWifiSSID(), myConfig.getWifiPass() );
}
if( strlen(userSSID)==0 && showPortal ) {
#if LOG_LEVEL==6
Log.verbose(F("WIFI: Connecting to WIFI via connection manager (portal=%s)." CR), showPortal?"true":"false");
myWifiManager.setDebugOutput(true);
#endif
if( strlen(userSSID)==0 && showPortal ) {
WiFiManager myWifiManager;
Log.notice(F("WIFI: Starting wifi portal." CR));
myWifiManager.setDebugOutput(true);
myWifiManager.setClass("invert");
myWifiManager.setConfigPortalTimeout( 120 ); // Keep it open for 120 seconds
myWifiManager.startConfigPortal( WIFI_DEFAULT_SSID, WIFI_DEFAULT_PWD );
bool f = myWifiManager.startConfigPortal( WIFI_DEFAULT_SSID, WIFI_DEFAULT_PWD );
if( f ) {
Log.notice(F("WIFI: Success got values from WIFI portal=%s,%s." CR), myWifiManager.getWiFiSSID(), myWifiManager.getWiFiPass() );
myConfig.setWifiSSID( myWifiManager.getWiFiSSID() );
myConfig.setWifiPass( myWifiManager.getWiFiPass() );
myConfig.saveFile();
} else {
Log.notice(F("WIFI: Failure from WIFI portal, rebooting." CR) );
delay(200);
ESP.reset();
}
}
// Connect to wifi
int i = 0;
Log.notice(F("WIFI: Connecting to WIFI." CR));
Log.notice(F("WIFI: Connecting to WIFI, mode=%d,persistent=%d,fhy=%d ." CR), WiFi.getMode(), WiFi.getPersistent(), WiFi.getPhyMode() );
WiFi.mode(WIFI_STA);
if( strlen(userSSID) ) {
Log.notice(F("WIFI: Connecting to wifi using predefined settings %s." CR), userSSID);
WiFi.begin( userSSID, userPWD );
} else {
WiFi.begin();
#if LOG_LEVEL==6
Log.verbose(F("WIFI: Using SSID=%s, KEY=%s." CR), WiFi.SSID().c_str(), WiFi.psk().c_str() );
#endif
Log.notice(F("WIFI: Connecting to wifi using stored settings. %s." CR), myConfig.getWifiSSID());
WiFi.begin(myConfig.getWifiSSID(), myConfig.getWifiPass());
}
WiFi.printDiag(Serial);
while( WiFi.status() != WL_CONNECTED ) {
yield();
delay(100);
Serial.print( "." );
if( i++ > 200 ) { // Try for 20 seconds.
Log.error(F("WIFI: Failed to connect to wifi %d, aborting." CR), WiFi.status() );
WiFi.disconnect();
/*if( i++ > 200 ) { // Try for 20 seconds.
Log.error(F("WIFI: Failed to connect to wifi %d, aborting %s." CR), WiFi.status(), getIPAddress().c_str() );
//WiFi.disconnect();
return connectedFlag; // Return to main that we have failed to connect.
}
}*/
}
Serial.print( CR );
connectedFlag = true;