diff --git a/src/ble.cpp b/src/ble.cpp index 2af4bfc..a70ce3a 100644 --- a/src/ble.cpp +++ b/src/ble.cpp @@ -24,11 +24,12 @@ SOFTWARE. #if defined(ESP32) #include +#include // Tilt UUID variants and data format, based on tilt-sim // // https://github.com/spouliot/tilt-sim -// +// // Tilt data format is described here. Only SG and Temp is transmitted over BLE. // https://kvurd.com/blog/tilt-hydrometer-ibeacon-data-format/ @@ -38,10 +39,11 @@ SOFTWARE. BleSender::BleSender(const char* color) { BLEDevice::init(""); - // boost power to maximum, these might be changed once battery life using BLE has been tested. + // boost power to maximum, these might be changed once battery life using BLE + // has been tested. esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_DEFAULT, ESP_PWR_LVL_P9); esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_ADV, ESP_PWR_LVL_P9); - esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_SCAN ,ESP_PWR_LVL_P9); + esp_ble_tx_power_set(ESP_BLE_PWR_TYPE_SCAN, ESP_PWR_LVL_P9); _advertising = BLEDevice::getAdvertising(); _color = color; @@ -60,7 +62,7 @@ BleSender::BleSender(const char* color) { _uuid = BLEUUID::fromString("A495BB60-C5B1-4B44-B512-1370F02D74DE"); else if (!_color.compareTo("yellow")) _uuid = BLEUUID::fromString("A495BB70-C5B1-4B44-B512-1370F02D74DE"); - else // if (_color.compareTo("pink")) + else // if (_color.compareTo("pink")) _uuid = BLEUUID::fromString("A495BB80-C5B1-4B44-B512-1370F02D74DE"); } @@ -68,26 +70,27 @@ BleSender::BleSender(const char* color) { // Send temp and gravity via BLE // void BleSender::sendData(float tempF, float gravSG) { - uint16_t gravity = gravSG*1000; // SG * 1000 or SG * 10000 for Tilt Pro/HD - uint16_t temperature = tempF; // Deg F _or_ Deg F * 10 for Tilt Pro/HD + uint16_t gravity = gravSG * 1000; // SG * 1000 or SG * 10000 for Tilt Pro/HD + uint16_t temperature = tempF; // Deg F _or_ Deg F * 10 for Tilt Pro/HD BLEBeacon oBeacon = BLEBeacon(); - oBeacon.setManufacturerId(0x4C00); // fake Apple 0x004C LSB (ENDIAN_CHANGE_U16!) + oBeacon.setManufacturerId( + 0x4C00); // fake Apple 0x004C LSB (ENDIAN_CHANGE_U16!) oBeacon.setProximityUUID(_uuid); oBeacon.setMajor(temperature); - oBeacon.setMinor(gravity); + oBeacon.setMinor(gravity); std::string strServiceData = ""; - strServiceData += (char)26; // Len - strServiceData += (char)0xFF; // Type - strServiceData += oBeacon.getData(); + strServiceData += static_cast(26); // Len + strServiceData += static_cast(0xFF); // Type + strServiceData += oBeacon.getData(); BLEAdvertisementData oAdvertisementData = BLEAdvertisementData(); - oAdvertisementData.setFlags(0x04); // BR_EDR_NOT_SUPPORTED 0x04 + oAdvertisementData.setFlags(0x04); // BR_EDR_NOT_SUPPORTED 0x04 oAdvertisementData.addData(strServiceData); BLEAdvertisementData oScanResponseData = BLEAdvertisementData(); _advertising->setAdvertisementData(oAdvertisementData); - _advertising->setScanResponseData(oScanResponseData); + _advertising->setScanResponseData(oScanResponseData); _advertising->setAdvertisementType(BLE_GAP_CONN_MODE_NON); _advertising->start(); @@ -96,4 +99,4 @@ void BleSender::sendData(float tempF, float gravSG) { delay(100); } -#endif // ESP32 \ No newline at end of file +#endif // ESP32 diff --git a/src/ble.hpp b/src/ble.hpp index ade8cf9..57d1657 100644 --- a/src/ble.hpp +++ b/src/ble.hpp @@ -24,25 +24,24 @@ SOFTWARE. #ifndef SRC_BLE_HPP_ #define SRC_BLE_HPP_ -#if defined (ESP32) +#if defined(ESP32) -#include #include -#include +#include + #include +#include class BleSender { private: - BLEAdvertising *_advertising; + BLEAdvertising* _advertising; String _color; BLEUUID _uuid; public: - BleSender(const char* color); + explicit BleSender(const char* color); void sendData(float tempF, float gravSG); }; -#endif // ESP32 -#endif // SRC_BLE_HPP_ - -// EOF \ No newline at end of file +#endif // ESP32 +#endif // SRC_BLE_HPP_ diff --git a/src/config.cpp b/src/config.cpp index e6fd4c7..68f4841 100644 --- a/src/config.cpp +++ b/src/config.cpp @@ -65,7 +65,7 @@ Config::Config() { // void Config::createJson(DynamicJsonDocument& doc) { doc[PARAM_MDNS] = getMDNS(); - //doc[PARAM_CONFIG_VER] = getConfigVersion(); + // doc[PARAM_CONFIG_VER] = getConfigVersion(); doc[PARAM_ID] = getID(); doc[PARAM_OTA] = getOtaURL(); doc[PARAM_SSID] = getWifiSSID(); @@ -300,10 +300,11 @@ bool Config::loadFile() { _formulaData.g[4] = doc[PARAM_FORMULA_DATA]["g5"].as(); /*if( doc[PARAM_CONFIG_VER].isNull() ) { - // If this parameter is missing we need to reset the gyrocalibaration due to bug #29 - _gyroCalibration.ax = _gyroCalibration.ay = _gyroCalibration.az = 0; - _gyroCalibration.gx = _gyroCalibration.gy = _gyroCalibration.gz = 0; - Log.warning(F("CFG : Old configuration format, clearing gyro calibration." CR)); + // If this parameter is missing we need to reset the gyrocalibaration due to + bug #29 _gyroCalibration.ax = _gyroCalibration.ay = _gyroCalibration.az = 0; + _gyroCalibration.gx = _gyroCalibration.gy = _gyroCalibration.gz = 0; + Log.warning(F("CFG : Old configuration format, clearing gyro calibration." + CR)); }*/ _saveNeeded = false; // Reset save flag diff --git a/src/config.hpp b/src/config.hpp index 68486a1..29e580a 100644 --- a/src/config.hpp +++ b/src/config.hpp @@ -60,7 +60,7 @@ class HardwareConfig { int _gyroSensorMovingThreashold = 500; int _gyroReadCount = 50; int _gyroReadDelay = 3150; // us, empirical, to hold sampling to 200 Hz - int _pushTimeout = 10; // seconds + int _pushTimeout = 10; // seconds public: int getWifiPortalTimeout() { return _wifiPortalTimeout; } @@ -133,7 +133,7 @@ class Config { char _gravityFormat = 'G'; // BLE (ESP32 only) - String _colorBLE; + String _colorBLE; // Gyro calibration and formula calculation data RawGyroData _gyroCalibration = {0, 0, 0, 0, 0, 0}; @@ -360,7 +360,10 @@ class Config { } bool isBLEActive() { return _colorBLE.length() ? true : false; } bool isWifiPushActive() { - return (isHttpActive() || isHttp2Active() || isHttp3Active() || isBrewfatherActive() || isInfluxDb2Active() || isMqttActive()) ? true : false; + return (isHttpActive() || isHttp2Active() || isHttp3Active() || + isBrewfatherActive() || isInfluxDb2Active() || isMqttActive()) + ? true + : false; } const RawGyroData& getGyroCalibration() { return _gyroCalibration; } diff --git a/src/gyro.cpp b/src/gyro.cpp index 7aa374e..b49ade3 100644 --- a/src/gyro.cpp +++ b/src/gyro.cpp @@ -197,12 +197,13 @@ float GyroSensor::calculateAngle(RawGyroData &raw) { // Source: https://www.nxp.com/docs/en/application-note/AN3461.pdf float vY = (acos(abs(ay) / sqrt(ax * ax + ay * ay + az * az)) * 180.0 / PI); - //float vZ = (acos(abs(az) / sqrt(ax * ax + ay * ay + az * az)) * 180.0 / PI); - //float vX = (acos(abs(ax) / sqrt(ax * ax + ay * ay + az * az)) * 180.0 / PI); + // float vZ = (acos(abs(az) / sqrt(ax * ax + ay * ay + az * az)) * 180.0 / + // PI); float vX = (acos(abs(ax) / sqrt(ax * ax + ay * ay + az * az)) * 180.0 + // / PI); #if LOG_LEVEL == 6 && !defined(GYRO_DISABLE_LOGGING) - //Log.notice(F("GYRO: angleX= %F." CR), vX); + // Log.notice(F("GYRO: angleX= %F." CR), vX); Log.notice(F("GYRO: angleY= %F." CR), vY); - //Log.notice(F("GYRO: angleZ= %F." CR), vZ); + // Log.notice(F("GYRO: angleZ= %F." CR), vZ); #endif return vY; } diff --git a/src/helper.cpp b/src/helper.cpp index 68d0b36..7fba565 100644 --- a/src/helper.cpp +++ b/src/helper.cpp @@ -50,9 +50,8 @@ void tcp_cleanup() { // // Convert sg to plato // -double convertToPlato(double sg) { - if (sg) - return 259 - (259 / sg); +double convertToPlato(double sg) { + if (sg) return 259 - (259 / sg); return 0; } @@ -357,20 +356,25 @@ void PerfLogging::pushInflux() { snprintf(&buf[0], sizeof(buf), "\ndebug,host=%s,device=%s ", myConfig.getMDNS(), myConfig.getID()); body += &buf[0]; -#if defined (ESP8266) - snprintf( - &buf[0], sizeof(buf), - "angle=%.4f,gyro-ax=%d,gyro-ay=%d,gyro-az=%d,gyro-temp=%.2f,ds-temp=%.2f,heap=%d,heap-frag=%d,heap-max=%d,stack=%d", - myGyro.getAngle(), myGyro.getLastGyroData().ax, - myGyro.getLastGyroData().ay, myGyro.getLastGyroData().az, - myGyro.getSensorTempC(), myTempSensor.getTempC(myConfig.isGyroTemp()), ESP.getFreeHeap(), ESP.getHeapFragmentation(), ESP.getMaxFreeBlockSize(), ESP.getFreeContStack()); -#else // defined (ESP32) - snprintf( - &buf[0], sizeof(buf), - "angle=%.4f,gyro-ax=%d,gyro-ay=%d,gyro-az=%d,gyro-temp=%.2f,ds-temp=%.2f,heap=%d,heap-frag=%d,heap-max=%d", - myGyro.getAngle(), myGyro.getLastGyroData().ax, - myGyro.getLastGyroData().ay, myGyro.getLastGyroData().az, - myGyro.getSensorTempC(), myTempSensor.getTempC(myConfig.isGyroTemp()), ESP.getFreeHeap(), 0, ESP.getMaxAllocHeap()); +#if defined(ESP8266) + snprintf(&buf[0], sizeof(buf), + "angle=%.4f,gyro-ax=%d,gyro-ay=%d,gyro-az=%d,gyro-temp=%.2f,ds-temp=" + "%.2f,heap=%d,heap-frag=%d,heap-max=%d,stack=%d", + myGyro.getAngle(), myGyro.getLastGyroData().ax, + myGyro.getLastGyroData().ay, myGyro.getLastGyroData().az, + myGyro.getSensorTempC(), + myTempSensor.getTempC(myConfig.isGyroTemp()), ESP.getFreeHeap(), + ESP.getHeapFragmentation(), ESP.getMaxFreeBlockSize(), + ESP.getFreeContStack()); +#else // defined (ESP32) + snprintf(&buf[0], sizeof(buf), + "angle=%.4f,gyro-ax=%d,gyro-ay=%d,gyro-az=%d,gyro-temp=%.2f,ds-temp=" + "%.2f,heap=%d,heap-frag=%d,heap-max=%d", + myGyro.getAngle(), myGyro.getLastGyroData().ax, + myGyro.getLastGyroData().ay, myGyro.getLastGyroData().az, + myGyro.getSensorTempC(), + myTempSensor.getTempC(myConfig.isGyroTemp()), ESP.getFreeHeap(), 0, + ESP.getMaxAllocHeap()); #endif body += &buf[0]; @@ -429,7 +433,7 @@ float reduceFloatPrecision(float f, int dec) { // String urlencode(String str) { String encodedString; - encodedString.reserve(str.length()*2); + encodedString.reserve(str.length() * 2); encodedString = ""; char c; char code0; diff --git a/src/main.cpp b/src/main.cpp index 5805fda..af69136 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -21,6 +21,7 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +#include #include #include #include @@ -30,7 +31,6 @@ SOFTWARE. #include #include #include -#include // Define constats for this program #ifdef DEACTIVATE_SLEEPMODE @@ -161,7 +161,8 @@ void setup() { runMode = RunMode::wifiSetupMode; } - bool needWifi = true; // Under ESP32 we dont need wifi if only BLE is active in gravityMode + bool needWifi = true; // Under ESP32 we dont need wifi if only BLE is active + // in gravityMode // Do this setup for all modes exect wifi setup switch (runMode) { @@ -183,9 +184,11 @@ void setup() { myBatteryVoltage.read(); checkSleepMode(myGyro.getAngle(), myBatteryVoltage.getVoltage()); -#if defined (ESP32) +#if defined(ESP32) if (!myConfig.isWifiPushActive() && runMode == RunMode::gravityMode) { - Log.notice(F("Main: Wifi is not needed in gravity mode, skipping connection." CR)); + Log.notice( + F("Main: Wifi is not needed in gravity mode, skipping " + "connection." CR)); needWifi = false; } #endif @@ -269,18 +272,19 @@ bool loopReadGravity() { pushMillis = millis(); LOG_PERF_START("loop-push"); -#if defined (ESP32) +#if defined(ESP32) if (myConfig.isBLEActive()) { BleSender ble(myConfig.getColorBLE()); - ble.sendData( convertCtoF(tempC), gravitySG); + ble.sendData(convertCtoF(tempC), gravitySG); Log.notice(F("MAIN: Broadcast data over bluetooth." CR)); } -#endif +#endif - if (myWifi.isConnected()) { // no need to try if there is no wifi connection. + if (myWifi.isConnected()) { // no need to try if there is no wifi + // connection. PushTarget push; push.sendAll(angle, gravitySG, corrGravitySG, tempC, - (millis() - runtimeMillis) / 1000); + (millis() - runtimeMillis) / 1000); } LOG_PERF_STOP("loop-push"); @@ -356,7 +360,9 @@ void loop() { case RunMode::gravityMode: // If we didnt get a wifi connection, we enter sleep for a short time to // conserve battery. - if (!myWifi.isConnected() && myConfig.isWifiPushActive()) { // no connection to wifi and we have defined push targets. + if (!myWifi.isConnected() && + myConfig.isWifiPushActive()) { // no connection to wifi and we have + // defined push targets. Log.notice( F("MAIN: No connection to wifi established, sleeping for 60s." CR)); myWifi.stopDoubleReset(); diff --git a/src/main.hpp b/src/main.hpp index cbd5cac..0a87558 100644 --- a/src/main.hpp +++ b/src/main.hpp @@ -29,16 +29,16 @@ SOFTWARE. #include #include -#if defined (ESP8266) +#if defined(ESP8266) #include #define ESP_RESET ESP.reset #define PIN_SDA D3 #define PIN_SCL D4 #define PIN_DS D6 #define PIN_LED 2 -//#define PIN_A0 A0 -#else // defined (ESP32) -#if defined (ESPRESSIF32_20) +// #define PIN_A0 A0 +#else // defined (ESP32) +#if defined(ESPRESSIF32_20) #include #else #include diff --git a/src/pushtarget.cpp b/src/pushtarget.cpp index cd917a0..9cf045c 100644 --- a/src/pushtarget.cpp +++ b/src/pushtarget.cpp @@ -36,7 +36,7 @@ SOFTWARE. // Send the data to targets // void PushTarget::sendAll(float angle, float gravitySG, float corrGravitySG, - float tempC, float runTime) { + float tempC, float runTime) { printHeap("PUSH"); _http.setReuse(false); _httpSecure.setReuse(false); @@ -111,12 +111,10 @@ void PushTarget::sendInfluxDb2(TemplatingEngine& engine) { if (_lastCode == 204) { _lastSuccess = true; - Log.notice(F("PUSH: InfluxDB2 push successful, response=%d" CR), - _lastCode); + Log.notice(F("PUSH: InfluxDB2 push successful, response=%d" CR), _lastCode); } else { ErrorFileLog errLog; - errLog.addEntry("PUSH: Influxdb push failed response=" + - String(_lastCode)); + errLog.addEntry("PUSH: Influxdb push failed response=" + String(_lastCode)); } _http.end(); @@ -186,7 +184,8 @@ void PushTarget::addHttpHeader(HTTPClient& http, String header) { // // Send data to http target using POST // -void PushTarget::sendHttpPost(TemplatingEngine& engine, bool isSecure, int index) { +void PushTarget::sendHttpPost(TemplatingEngine& engine, bool isSecure, + int index) { #if !defined(PUSH_DISABLE_LOGGING) Log.notice(F("PUSH: Sending values to http (%s)" CR), index ? "http2" : "http"); @@ -213,11 +212,12 @@ void PushTarget::sendHttpPost(TemplatingEngine& engine, bool isSecure, int index Log.notice(F("PUSH: HTTP, SSL enabled without validation." CR)); _wifiSecure.setInsecure(); -#if defined (ESP8266) - String host = serverPath.substring(8); // remove the prefix or the probe will fail, it needs a pure host name. +#if defined(ESP8266) + String host = + serverPath.substring(8); // remove the prefix or the probe will fail, + // it needs a pure host name. int idx = host.indexOf("/"); - if (idx!=-1) - host = host.substring(0, idx); + if (idx != -1) host = host.substring(0, idx); if (_wifiSecure.probeMaxFragmentLength(host, 443, 512)) { Log.notice(F("PUSH: HTTP server supports smaller SSL buffer." CR)); @@ -254,13 +254,11 @@ void PushTarget::sendHttpPost(TemplatingEngine& engine, bool isSecure, int index if (_lastCode == 200) { _lastSuccess = true; - Log.notice(F("PUSH: HTTP post successful, response=%d" CR), - _lastCode); + Log.notice(F("PUSH: HTTP post successful, response=%d" CR), _lastCode); } else { ErrorFileLog errLog; - errLog.addEntry( - "PUSH: HTTP post failed response=" + String(_lastCode) + - String(index == 0 ? " (http)" : " (http2)")); + errLog.addEntry("PUSH: HTTP post failed response=" + String(_lastCode) + + String(index == 0 ? " (http)" : " (http2)")); } if (isSecure) { @@ -296,11 +294,12 @@ void PushTarget::sendHttpGet(TemplatingEngine& engine, bool isSecure) { Log.notice(F("PUSH: HTTP, SSL enabled without validation." CR)); _wifiSecure.setInsecure(); -#if defined (ESP8266) - String host = serverPath.substring(8); // remove the prefix or the probe will fail, it needs a pure host name. +#if defined(ESP8266) + String host = + serverPath.substring(8); // remove the prefix or the probe will fail, + // it needs a pure host name. int idx = host.indexOf("/"); - if (idx!=-1) - host = host.substring(0, idx); + if (idx != -1) host = host.substring(0, idx); if (_wifiSecure.probeMaxFragmentLength(host, 443, 512)) { Log.notice(F("PUSH: HTTP server supports smaller SSL buffer." CR)); @@ -310,7 +309,7 @@ void PushTarget::sendHttpGet(TemplatingEngine& engine, bool isSecure) { _httpSecure.begin(_wifiSecure, serverPath); _httpSecure.setTimeout(myHardwareConfig.getPushTimeout() * 1000); - _lastCode = _httpSecure.GET(); + _lastCode = _httpSecure.GET(); } else { _http.begin(_wifi, serverPath); _http.setTimeout(myHardwareConfig.getPushTimeout() * 1000); @@ -319,12 +318,10 @@ void PushTarget::sendHttpGet(TemplatingEngine& engine, bool isSecure) { if (_lastCode == 200) { _lastSuccess = true; - Log.notice(F("PUSH: HTTP get successful, response=%d" CR), - _lastCode); + Log.notice(F("PUSH: HTTP get successful, response=%d" CR), _lastCode); } else { ErrorFileLog errLog; - errLog.addEntry( - "PUSH: HTTP get failed response=" + String(_lastCode)); + errLog.addEntry("PUSH: HTTP get failed response=" + String(_lastCode)); } if (isSecure) { @@ -356,7 +353,7 @@ void PushTarget::sendMqtt(TemplatingEngine& engine, bool isSecure) { Log.notice(F("PUSH: MQTT, SSL enabled without validation." CR)); _wifiSecure.setInsecure(); -#if defined (ESP8266) +#if defined(ESP8266) if (_wifiSecure.probeMaxFragmentLength(host, port, 512)) { Log.notice(F("PUSH: MQTT server supports smaller SSL buffer." CR)); _wifiSecure.setBufferSizes(512, 512); diff --git a/src/pushtarget.hpp b/src/pushtarget.hpp index 2c237c2..8bc8337 100644 --- a/src/pushtarget.hpp +++ b/src/pushtarget.hpp @@ -48,12 +48,18 @@ class PushTarget { public: void sendAll(float angle, float gravitySG, float corrGravitySG, float tempC, - float runTime); + float runTime); void sendBrewfather(TemplatingEngine& engine); - void sendHttp1(TemplatingEngine& engine, bool isSecure) { sendHttpPost(engine, isSecure, 0); } - void sendHttp2(TemplatingEngine& engine, bool isSecure) { sendHttpPost(engine, isSecure, 1); } - void sendHttp3(TemplatingEngine& engine, bool isSecure) { sendHttpGet(engine, isSecure); } + void sendHttp1(TemplatingEngine& engine, bool isSecure) { + sendHttpPost(engine, isSecure, 0); + } + void sendHttp2(TemplatingEngine& engine, bool isSecure) { + sendHttpPost(engine, isSecure, 1); + } + void sendHttp3(TemplatingEngine& engine, bool isSecure) { + sendHttpGet(engine, isSecure); + } void sendInfluxDb2(TemplatingEngine& engine); void sendMqtt(TemplatingEngine& engine, bool isSecure); int getLastCode() { return _lastCode; } diff --git a/src/resources.cpp b/src/resources.cpp index 3520037..f57792c 100644 --- a/src/resources.cpp +++ b/src/resources.cpp @@ -21,7 +21,7 @@ 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. */ -#if defined (ESP8266) +#if defined(ESP8266) #define INCBIN_OUTPUT_SECTION ".irom.text" #endif #include @@ -42,5 +42,4 @@ INCBIN(UploadHtm, "data/upload.min.htm"); #endif INCBIN(FirmwareHtm, "data/firmware.min.htm"); - // EOF diff --git a/src/templating.cpp b/src/templating.cpp index b5ac231..3cb47dd 100644 --- a/src/templating.cpp +++ b/src/templating.cpp @@ -21,51 +21,51 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -#include #include +#include -#if defined (ESP8266) +#if defined(ESP8266) #include -#else // defined (ESP32) +#else // defined (ESP32) #include #endif // Use iSpindle format for compatibility, HTTP POST -const char iSpindleFormat[] PROGMEM = - "{" +const char iSpindleFormat[] PROGMEM = + "{" "\"name\" : \"${mdns}\", " - "\"ID\": \"${id}\", " - "\"token\" : \"${token}\", " - "\"interval\": ${sleep-interval}, " - "\"temperature\": ${temp}, " - "\"temp_units\": \"${temp-unit}\", " - "\"gravity\": ${gravity}, " - "\"angle\": ${angle}, " - "\"battery\": ${battery}, " - "\"rssi\": ${rssi}, " - "\"corr-gravity\": ${corr-gravity}, " - "\"gravity-unit\": \"${gravity-unit}\", " - "\"run-time\": ${run-time} " - "}"; + "\"ID\": \"${id}\", " + "\"token\" : \"${token}\", " + "\"interval\": ${sleep-interval}, " + "\"temperature\": ${temp}, " + "\"temp_units\": \"${temp-unit}\", " + "\"gravity\": ${gravity}, " + "\"angle\": ${angle}, " + "\"battery\": ${battery}, " + "\"rssi\": ${rssi}, " + "\"corr-gravity\": ${corr-gravity}, " + "\"gravity-unit\": \"${gravity-unit}\", " + "\"run-time\": ${run-time} " + "}"; // Format for an HTTP GET -const char iHttpGetFormat[] PROGMEM = - "?name=${mdns}" - "&id=${id}" - "&token=${token2}" - "&interval=${sleep-interval}" - "&temperature=${temp}" - "&temp-units=${temp-unit}" - "&gravity=${gravity}" - "&angle=${angle}" - "&battery=${battery}" - "&rssi=${rssi}" - "&corr-gravity=${corr-gravity}" - "&gravity-unit=${gravity-unit}" - "&run-time=${run-time}"; +const char iHttpGetFormat[] PROGMEM = + "?name=${mdns}" + "&id=${id}" + "&token=${token2}" + "&interval=${sleep-interval}" + "&temperature=${temp}" + "&temp-units=${temp-unit}" + "&gravity=${gravity}" + "&angle=${angle}" + "&battery=${battery}" + "&rssi=${rssi}" + "&corr-gravity=${corr-gravity}" + "&gravity-unit=${gravity-unit}" + "&run-time=${run-time}"; -const char brewfatherFormat[] PROGMEM = - "{" +const char brewfatherFormat[] PROGMEM = + "{" "\"name\": \"${mdns}\"," "\"temp\": ${temp}, " "\"aux_temp\": 0, " @@ -80,27 +80,30 @@ const char brewfatherFormat[] PROGMEM = "\"comment\": \"\", " "\"beer\": \"\", " "\"battery\": ${battery}" - "}"; + "}"; -const char influxDbFormat[] PROGMEM = - "measurement,host=${mdns},device=${id},temp-format=${temp-unit},gravity-format=${gravity-unit} " - "gravity=${gravity},corr-gravity=${corr-gravity},angle=${angle},temp=${temp},battery=${battery}," - "rssi=${rssi}\n"; +const char influxDbFormat[] PROGMEM = + "measurement,host=${mdns},device=${id},temp-format=${temp-unit},gravity-" + "format=${gravity-unit} " + "gravity=${gravity},corr-gravity=${corr-gravity},angle=${angle},temp=${" + "temp},battery=${battery}," + "rssi=${rssi}\n"; -const char mqttFormat[] PROGMEM = - "ispindel/${mdns}/tilt:${angle}|" - "ispindel/${mdns}/temperature:${temp}|" - "ispindel/${mdns}/temp_units:${temp-unit}|" - "ispindel/${mdns}/battery:${battery}|" - "ispindel/${mdns}/gravity:${gravity}|" - "ispindel/${mdns}/interval:${sleep-interval}|" - "ispindel/${mdns}/RSSI:${rssi}|"; +const char mqttFormat[] PROGMEM = + "ispindel/${mdns}/tilt:${angle}|" + "ispindel/${mdns}/temperature:${temp}|" + "ispindel/${mdns}/temp_units:${temp-unit}|" + "ispindel/${mdns}/battery:${battery}|" + "ispindel/${mdns}/gravity:${gravity}|" + "ispindel/${mdns}/interval:${sleep-interval}|" + "ispindel/${mdns}/RSSI:${rssi}|"; // // Initialize the variables // -void TemplatingEngine::initialize(float angle, float gravitySG, float corrGravitySG, float tempC, float runTime) { - +void TemplatingEngine::initialize(float angle, float gravitySG, + float corrGravitySG, float tempC, + float runTime) { // Names setVal(TPL_MDNS, myConfig.getMDNS()); setVal(TPL_ID, myConfig.getID()); @@ -134,8 +137,7 @@ void TemplatingEngine::initialize(float angle, float gravitySG, float corrGravit if (myConfig.isGravitySG()) { setVal(TPL_GRAVITY, gravitySG, 4); setVal(TPL_GRAVITY_CORR, corrGravitySG, 4); - } - else { + } else { setVal(TPL_GRAVITY, convertToPlato(gravitySG), 1); setVal(TPL_GRAVITY_CORR, convertToPlato(corrGravitySG), 1); } @@ -163,34 +165,34 @@ const String& TemplatingEngine::create(TemplatingEngine::Templates idx) { case TEMPLATE_HTTP1: baseTemplate = String(iSpindleFormat); fname = TPL_FNAME_HTTP1; - break; + break; case TEMPLATE_HTTP2: baseTemplate = String(iSpindleFormat); fname = TPL_FNAME_HTTP2; - break; + break; case TEMPLATE_HTTP3: baseTemplate = String(iHttpGetFormat); fname = TPL_FNAME_HTTP3; - break; + break; case TEMPLATE_BREWFATHER: baseTemplate = String(brewfatherFormat); - //fname = TPL_FNAME_BREWFATHER; - break; + // fname = TPL_FNAME_BREWFATHER; + break; case TEMPLATE_INFLUX: baseTemplate = String(influxDbFormat); fname = TPL_FNAME_INFLUXDB; - break; + break; case TEMPLATE_MQTT: baseTemplate = String(mqttFormat); fname = TPL_FNAME_MQTT; - break; + break; } // TODO: Add code to load templates from disk if they exist. File file = LittleFS.open(fname, "r"); if (file) { - char buf[file.size()+1]; - memset(&buf[0], 0, file.size()+1); + char buf[file.size() + 1]; + memset(&buf[0], 0, file.size() + 1); file.readBytes(&buf[0], file.size()); baseTemplate = String(&buf[0]); file.close(); @@ -198,14 +200,14 @@ const String& TemplatingEngine::create(TemplatingEngine::Templates idx) { } #if LOG_LEVEL == 6 - //Log.verbose(F("TPL : Base '%s'." CR), baseTemplate.c_str()); + // Log.verbose(F("TPL : Base '%s'." CR), baseTemplate.c_str()); #endif // Insert data into template. transform(baseTemplate); #if LOG_LEVEL == 6 - //Log.verbose(F("TPL : Transformed '%s'." CR), baseTemplate.c_str()); + // Log.verbose(F("TPL : Transformed '%s'." CR), baseTemplate.c_str()); #endif return baseTemplate; diff --git a/src/templating.hpp b/src/templating.hpp index 5a40ceb..4800fa8 100644 --- a/src/templating.hpp +++ b/src/templating.hpp @@ -85,7 +85,7 @@ class TemplatingEngine { {TPL_GRAVITY_P, ""}, {TPL_GRAVITY_CORR, ""}, {TPL_GRAVITY_CORR_G, ""}, {TPL_GRAVITY_CORR_P, ""}, {TPL_GRAVITY_UNIT, ""}, {TPL_TOKEN, ""}, - {TPL_TOKEN2, ""} }; + {TPL_TOKEN2, ""}}; char buffer[20]; String baseTemplate; diff --git a/src/webserver.cpp b/src/webserver.cpp index d333827..3184ddf 100644 --- a/src/webserver.cpp +++ b/src/webserver.cpp @@ -26,10 +26,10 @@ SOFTWARE. #include #include #include +#include #include #include #include -#include #include #include @@ -51,9 +51,8 @@ void WebServerHandler::webHandleConfig() { double angle = 0; - if (myGyro.hasValue()) - angle = myGyro.getAngle(); - + if (myGyro.hasValue()) angle = myGyro.getAngle(); + double tempC = myTempSensor.getTempC(myConfig.isGyroTemp()); double gravity = calculateGravity(angle, tempC); @@ -61,8 +60,9 @@ void WebServerHandler::webHandleConfig() { doc[PARAM_GRAVITY_FORMAT] = String(myConfig.getGravityFormat()); // Format the adjustment so we get rid of rounding errors - if (myConfig.isTempF()) - doc[PARAM_TEMP_ADJ] = reduceFloatPrecision(convertCtoF(myConfig.getTempSensorAdjC()), 1); + if (myConfig.isTempF()) + doc[PARAM_TEMP_ADJ] = + reduceFloatPrecision(convertCtoF(myConfig.getTempSensorAdjC()), 1); else doc[PARAM_TEMP_ADJ] = reduceFloatPrecision(myConfig.getTempSensorAdjC(), 1); @@ -128,13 +128,13 @@ void WebServerHandler::webHandleUpload() { obj[PARAM_FILE_NAME] = dir.fileName(); obj[PARAM_FILE_SIZE] = dir.fileSize(); } -#else // defined(ESP32) +#else // defined(ESP32) JsonArray files = doc.createNestedArray(PARAM_FILES); File dir = LittleFS.open("/"); while (true) { - File entry = dir.openNextFile(); + File entry = dir.openNextFile(); if (!entry) { // no more files break; @@ -188,43 +188,51 @@ void WebServerHandler::webHandleUploadFile() { } #if LOG_LEVEL == 6 && !defined(WEB_DISABLE_LOGGING) - Log.verbose(F("WEB : webServer callback for /api/upload, receiving file %s, %d(%d) " - "valid=%s, firmware=%s." CR), - f.c_str(), upload.currentSize, upload.totalSize, validFilename ? "yes" : "no", firmware ? "yes" : "no"); + Log.verbose( + F("WEB : webServer callback for /api/upload, receiving file %s, %d(%d) " + "valid=%s, firmware=%s." CR), + f.c_str(), upload.currentSize, upload.totalSize, + validFilename ? "yes" : "no", firmware ? "yes" : "no"); #endif if (firmware) { - // Handle firmware update - uint32_t maxSketchSpace = 1044464; //(ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; + // Handle firmware update, hardcode since function return wrong value. + uint32_t maxSketchSpace = + 1044464; // (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000; if (upload.status == UPLOAD_FILE_START) { _uploadReturn = 200; - Log.notice(F("WEB : Start firmware upload, max sketch size %d kb." CR), maxSketchSpace/1024); + Log.notice(F("WEB : Start firmware upload, max sketch size %d kb." CR), + maxSketchSpace / 1024); - if (!Update.begin(maxSketchSpace, U_FLASH, PIN_LED)){ + if (!Update.begin(maxSketchSpace, U_FLASH, PIN_LED)) { ErrorFileLog errLog; - errLog.addEntry(F("WEB : Not enough space to store for this firmware.")); + errLog.addEntry( + F("WEB : Not enough space to store for this firmware.")); _uploadReturn = 500; - } + } } else if (upload.status == UPLOAD_FILE_WRITE) { - Log.notice(F("WEB : Writing firmware upload %d (%d)." CR), upload.totalSize, maxSketchSpace); + Log.notice(F("WEB : Writing firmware upload %d (%d)." CR), + upload.totalSize, maxSketchSpace); if (upload.totalSize > maxSketchSpace) { Log.error(F("WEB : Firmware file is to large." CR)); _uploadReturn = 500; - } else if (Update.write(upload.buf, upload.currentSize) != upload.currentSize){ + } else if (Update.write(upload.buf, upload.currentSize) != + upload.currentSize) { Log.warning(F("WEB : Firmware write was unsuccessful." CR)); _uploadReturn = 500; } } else if (upload.status == UPLOAD_FILE_END) { Log.notice(F("WEB : Finish firmware upload." CR)); - if(Update.end(true)) { + if (Update.end(true)) { _server->send(200); delay(500); ESP_RESET(); } else { ErrorFileLog errLog; - errLog.addEntry(F("WEB : Failed to finish firmware flashing error=") + String(Update.getError())); + errLog.addEntry(F("WEB : Failed to finish firmware flashing error=") + + String(Update.getError())); _uploadReturn = 500; } } else { @@ -244,15 +252,13 @@ void WebServerHandler::webHandleUploadFile() { if (validFilename) _uploadFile = LittleFS.open(f, "w"); } else if (upload.status == UPLOAD_FILE_WRITE) { Log.notice(F("WEB : Writing html upload." CR)); - if (_uploadFile) - _uploadFile.write( - upload.buf, - upload.currentSize); + if (_uploadFile) _uploadFile.write(upload.buf, upload.currentSize); } else if (upload.status == UPLOAD_FILE_END) { Log.notice(F("WEB : Finish html upload." CR)); if (_uploadFile) { _uploadFile.close(); - Log.notice(F("WEB : Html file uploaded %d bytes." CR), upload.totalSize); + Log.notice(F("WEB : Html file uploaded %d bytes." CR), + upload.totalSize); } _server->sendHeader("Location", "/"); _server->send(303); @@ -321,8 +327,7 @@ void WebServerHandler::webHandleStatus() { double angle = 0; - if (myGyro.hasValue()) - angle = myGyro.getAngle(); + if (myGyro.hasValue()) angle = myGyro.getAngle(); double tempC = myTempSensor.getTempC(myConfig.isGyroTemp()); double gravity = calculateGravity(angle, tempC); @@ -833,10 +838,11 @@ void WebServerHandler::webHandleTestPush() { PushTarget push; bool enabled = false; - if (!type.compareTo(PARAM_FORMAT_BREWFATHER) && myConfig.isBrewfatherActive()) { + if (!type.compareTo(PARAM_FORMAT_BREWFATHER) && + myConfig.isBrewfatherActive()) { push.sendBrewfather(engine); enabled = true; - } else if (!type.compareTo(PARAM_FORMAT_HTTP1) && myConfig.isHttpActive()) { + } else if (!type.compareTo(PARAM_FORMAT_HTTP1) && myConfig.isHttpActive()) { push.sendHttp1(engine, myConfig.isHttpSSL()); enabled = true; } else if (!type.compareTo(PARAM_FORMAT_HTTP2) && myConfig.isHttp2Active()) { @@ -845,7 +851,8 @@ void WebServerHandler::webHandleTestPush() { } else if (!type.compareTo(PARAM_FORMAT_HTTP3) && myConfig.isHttp3Active()) { push.sendHttp3(engine, myConfig.isHttp3SSL()); enabled = true; - } else if (!type.compareTo(PARAM_FORMAT_INFLUXDB) && myConfig.isInfluxDb2Active()) { + } else if (!type.compareTo(PARAM_FORMAT_INFLUXDB) && + myConfig.isInfluxDb2Active()) { push.sendInfluxDb2(engine); enabled = true; } else if (!type.compareTo(PARAM_FORMAT_MQTT) && myConfig.isMqttActive()) { @@ -1143,9 +1150,9 @@ bool WebServerHandler::setupWebServer() { // Check if the html files exist, if so serve them, else show the static // upload page. - if (checkHtmlFile(HTML_INDEX) && checkHtmlFile(HTML_CONFIG) && - checkHtmlFile(HTML_CALIBRATION) && checkHtmlFile(HTML_FORMAT) && - checkHtmlFile(HTML_ABOUT) && checkHtmlFile(HTML_TEST) ) { + if (checkHtmlFile(HTML_INDEX) && checkHtmlFile(HTML_CONFIG) && + checkHtmlFile(HTML_CALIBRATION) && checkHtmlFile(HTML_FORMAT) && + checkHtmlFile(HTML_ABOUT) && checkHtmlFile(HTML_TEST)) { Log.notice(F("WEB : All html files exist, starting in normal mode." CR)); _server->serveStatic("/", LittleFS, "/index.min.htm"); @@ -1166,7 +1173,7 @@ bool WebServerHandler::setupWebServer() { } #endif _server->on("/firmware.htm", - std::bind(&WebServerHandler::webReturnFirmwareHtm, this)); + std::bind(&WebServerHandler::webReturnFirmwareHtm, this)); _server->serveStatic("/log", LittleFS, ERR_FILENAME); _server->serveStatic("/runtime", LittleFS, RUNTIME_FILENAME); @@ -1226,7 +1233,7 @@ bool WebServerHandler::setupWebServer() { this)); // Change device params _server->on("/api/test/push", HTTP_GET, std::bind(&WebServerHandler::webHandleTestPush, - this)); // + this)); // _server->onNotFound( std::bind(&WebServerHandler::webHandlePageNotFound, this)); diff --git a/src/webserver.hpp b/src/webserver.hpp index 3969a92..d8a8b92 100644 --- a/src/webserver.hpp +++ b/src/webserver.hpp @@ -24,14 +24,14 @@ SOFTWARE. #ifndef SRC_WEBSERVER_HPP_ #define SRC_WEBSERVER_HPP_ -#if defined (ESP8266) +#if defined(ESP8266) #include #include #include -#else // defined (ESP32) +#else // defined (ESP32) +#include #include #include -#include #endif #include @@ -103,8 +103,7 @@ class WebServerHandler { gAboutHtmSize); } void webReturnTestHtm() { - _server->send_P(200, "text/html", (const char*)gTestHtmData, - gTestHtmSize); + _server->send_P(200, "text/html", (const char*)gTestHtmData, gTestHtmSize); } #else void webReturnUploadHtm() { diff --git a/src/wifi.cpp b/src/wifi.cpp index d5c8640..34f629d 100644 --- a/src/wifi.cpp +++ b/src/wifi.cpp @@ -138,7 +138,7 @@ void WifiConnection::startPortal() { String mdns("

Default mDNS name is: http://"); mdns += myConfig.getMDNS(); - mdns += ".local

"; + mdns += ".local

"; ESP_WMParameter deviceName(mdns.c_str()); myWifiManager->addParameter(&deviceName); @@ -244,9 +244,9 @@ bool WifiConnection::updateFirmware() { WiFiClientSecure wifiSecure; HTTPUpdateResult ret; String serverPath = myConfig.getOtaURL(); -#if defined (ESP8266) +#if defined(ESP8266) serverPath += "firmware.bin"; -#else // defined (ESP32) +#else // defined (ESP32) serverPath += "firmware32.bin"; #endif @@ -280,7 +280,7 @@ bool WifiConnection::updateFirmware() { // // Download and save file // -void WifiConnection::downloadFile(HTTPClient& http, String& fname) { +void WifiConnection::downloadFile(HTTPClient &http, String &fname) { #if LOG_LEVEL == 6 && !defined(WIFI_DISABLE_LOGGING) Log.verbose(F("WIFI: Download file %s." CR), fname); #endif @@ -357,14 +357,15 @@ bool WifiConnection::checkFirmwareVersion() { _newFirmware = true; // Compare patch version else if (newVer[0] == curVer[0] && newVer[1] == curVer[1] && - newVer[2] > curVer[2]) + newVer[2] > curVer[2]) _newFirmware = true; } } // Download new html files to filesystem if they are present. if (!ver["html"].isNull() && _newFirmware) { - Log.notice(F("WIFI: OTA checking if html files should be downloaded." CR)); + Log.notice( + F("WIFI: OTA checking if html files should be downloaded." CR)); JsonArray htmlFiles = ver["html"].as(); for (JsonVariant v : htmlFiles) { String s = v;