From 654558abcd0ff1bf5089ff7b1ec07d850012f95b Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Tue, 28 Dec 2021 19:24:10 -0800 Subject: [PATCH 01/20] Partial work for NTP client --- platformio.ini | 9 +++++---- src/gps/RTC.h | 5 ++++- src/mesh/http/WiFiAPClient.cpp | 33 +++++++++++++++++++++++++++------ 3 files changed, 36 insertions(+), 11 deletions(-) diff --git a/platformio.ini b/platformio.ini index 1d35ddeb96..3e1056b7dc 100644 --- a/platformio.ini +++ b/platformio.ini @@ -9,10 +9,10 @@ ; https://docs.platformio.org/page/projectconf.html [platformio] -default_envs = tbeam +;default_envs = tbeam ;default_envs = tbeam0.7 ;default_envs = heltec-v2.0 -;default_envs = tlora-v1 +default_envs = tlora-v1 ;default_envs = tlora_v1_3 ;default_envs = tlora-v2 ;default_envs = lora-relay-v1 # nrf board @@ -114,6 +114,7 @@ lib_deps = paulstoffregen/OneWire@^2.3.5 robtillaart/DS18B20@^0.1.11 h2zero/NimBLE-Arduino@1.3.1 + arduino-libraries/NTPClient#531eff39d9fbc831f3d03f706a161739203fbe2a # Hmm - this doesn't work yet # board_build.ldscript = linker/esp32.extram.bss.ld lib_ignore = @@ -127,8 +128,8 @@ platform_packages = ;upload_port = /dev/ttyUSB0 ;monitor_port = /dev/ttyUSB0 -;upload_port = /dev/cu.SLAB_USBtoUART -;monitor_port = /dev/cu.SLAB_USBtoUART +upload_port = /dev/cu.SLAB_USBtoUART +monitor_port = /dev/cu.SLAB_USBtoUART ; customize the partition table ; http://docs.platformio.org/en/latest/platforms/espressif32.html#partition-tables diff --git a/src/gps/RTC.h b/src/gps/RTC.h index 3a89d98104..730d1914ef 100644 --- a/src/gps/RTC.h +++ b/src/gps/RTC.h @@ -11,8 +11,11 @@ enum RTCQuality { /// Some other node gave us a time we can use RTCQualityFromNet = 1, + /// Our time is based on NTP + RTCQualityNTP= 2, + /// Our time is based on our own GPS - RTCQualityGPS = 2 + RTCQualityGPS = 3 }; RTCQuality getRTCQuality(); diff --git a/src/mesh/http/WiFiAPClient.cpp b/src/mesh/http/WiFiAPClient.cpp index 91892b5de7..b1d1ba9170 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -3,13 +3,15 @@ #include "concurrency/Periodic.h" #include "configuration.h" #include "main.h" -#include "mqtt/MQTT.h" #include "mesh/http/WebServer.h" #include "mesh/wifi/WiFiServerAPI.h" +#include "mqtt/MQTT.h" #include "target_specific.h" #include #include #include +#include +#include using namespace concurrency; @@ -18,6 +20,10 @@ static void WiFiEvent(WiFiEvent_t event); // DNS Server for the Captive Portal DNSServer dnsServer; +// NTP +WiFiUDP ntpUDP; +NTPClient timeClient(ntpUDP, "0.pool.ntp.org"); + uint8_t wifiDisconnectReason = 0; // Stores our hostname @@ -46,10 +52,11 @@ static WifiSleepObserver wifiSleepObserver; static int32_t reconnectWiFi() { + const char *wifiName = radioConfig.preferences.wifi_ssid; + const char *wifiPsw = radioConfig.preferences.wifi_password; + if (radioConfig.has_preferences && needReconnect) { - const char *wifiName = radioConfig.preferences.wifi_ssid; - const char *wifiPsw = radioConfig.preferences.wifi_password; if (!*wifiPsw) // Treat empty password as no password wifiPsw = NULL; @@ -60,9 +67,21 @@ static int32_t reconnectWiFi() DEBUG_MSG("... Reconnecting to WiFi access point\n"); WiFi.mode(WIFI_MODE_STA); WiFi.begin(wifiName, wifiPsw); + + // Starting timeClient; + + } } + if (*wifiName) { + DEBUG_MSG("Updating NTP time\n"); + timeClient.update(); + + Serial.println(timeClient.getFormattedTime()); + Serial.println(timeClient.getEpochTime()); + } + return 30 * 1000; // every 30 seconds } @@ -128,14 +147,17 @@ static void onNetworkConnected() MDNS.addService("https", "tcp", 443); } + DEBUG_MSG("Starting NTP time client\n"); + timeClient.begin(); + initWebServer(); initApiServer(); APStartupComplete = true; - } + } // FIXME this is kinda yucky, instead we should just have an observable for 'wifireconnected' - if(mqtt) + if (mqtt) mqtt->reconnect(); } @@ -176,7 +198,6 @@ bool initWifi(bool forceSoftAP) } else { DEBUG_MSG("Starting WIFI AP: ssid=%s, ok=%d\n", wifiName, WiFi.softAP(wifiName, wifiPsw)); - } WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); From c531ea86014a7e88cdf0f0bdcca6a56f8e855ebb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 30 Dec 2021 22:16:46 +0100 Subject: [PATCH 02/20] new Configuration section --- src/configuration.h | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/configuration.h b/src/configuration.h index 597f60094b..473a92114e 100644 --- a/src/configuration.h +++ b/src/configuration.h @@ -323,6 +323,41 @@ along with this program. If not, see . #endif +#elif defined(ARDUINO_HELTEC_WIFI_LORA_32) + +// the default ESP32 Pin of 15 is the Oled SCL, set to 36 and 37 and works fine. +// Tested on Neo6m module. +#undef GPS_RX_PIN +#undef GPS_TX_PIN +#define GPS_RX_PIN 36 +#define GPS_TX_PIN 37 + +#ifndef USE_JTAG // gpio15 is TDO for JTAG, so no I2C on this board while doing jtag +#define I2C_SDA 4 // I2C pins for this board +#define I2C_SCL 15 +#endif + +#define RESET_OLED 16 // If defined, this pin will be used to reset the display controller + +#define LED_PIN 25 // If defined we will blink this LED +#define BUTTON_PIN 0 // If defined, this will be used for user button presses + +#define USE_RF95 +#define LORA_DIO0 26 // a No connect on the SX1262 module +#ifndef USE_JTAG +#define LORA_RESET 14 +#endif +#define LORA_DIO1 33 // Not really used +#define LORA_DIO2 32 // Not really used + +// ratio of voltage divider = 3.20 (R1=100k, R2=220k) +#define ADC_MULTIPLIER 3.2 + +// This string must exactly match the case used in release file names or the android updater won't work +#define HW_VENDOR HardwareModel_HELTEC_V1 + +#define BATTERY_PIN 13 // A battery voltage measurement pin, voltage divider connected here to measure battery voltage + #elif defined(TLORA_V1) // This string must exactly match the case used in release file names or the android updater won't work #define HW_VENDOR HardwareModel_TLORA_V1 From 9c7121df3e9f05e97ec0e2607ef26ce810574ad6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 30 Dec 2021 22:18:08 +0100 Subject: [PATCH 03/20] Update platformio.ini add new board to platform.io definition --- platformio.ini | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/platformio.ini b/platformio.ini index 1d35ddeb96..9c301ea337 100644 --- a/platformio.ini +++ b/platformio.ini @@ -12,6 +12,7 @@ default_envs = tbeam ;default_envs = tbeam0.7 ;default_envs = heltec-v2.0 +;default_envs = heltec-v1 ;default_envs = tlora-v1 ;default_envs = tlora_v1_3 ;default_envs = tlora-v2 @@ -158,6 +159,13 @@ board = ttgo-t-beam build_flags = ${esp32_base.build_flags} -D TBEAM_V07 +[env:heltec-v1] +;build_type = debug ; to make it possible to step through our jtag debugger +extends = esp32_base +board = heltec_wifi_lora_32 +build_flags = + ${esp32_base.build_flags} -D HELTEC_V1 + [env:heltec-v2.0] ;build_type = debug ; to make it possible to step through our jtag debugger extends = esp32_base From e24a2116d836c0dd2c5fdb9d0ac6ae139072c2d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 30 Dec 2021 22:19:04 +0100 Subject: [PATCH 04/20] build the new board with build_all --- bin/build-all.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/bin/build-all.sh b/bin/build-all.sh index 922fd4b7d3..1cf83c62ff 100755 --- a/bin/build-all.sh +++ b/bin/build-all.sh @@ -5,7 +5,7 @@ set -e VERSION=`bin/buildinfo.py long` SHORT_VERSION=`bin/buildinfo.py short` -BOARDS_ESP32="tlora-v2 tlora-v1 tlora_v1_3 tlora-v2-1-1.6 tbeam heltec-v2.0 heltec-v2.1 tbeam0.7 meshtastic-diy-v1" +BOARDS_ESP32="tlora-v2 tlora-v1 tlora_v1_3 tlora-v2-1-1.6 tbeam heltec-v1 heltec-v2.0 heltec-v2.1 tbeam0.7 meshtastic-diy-v1" #BOARDS_ESP32=tbeam # FIXME note nrf52840dk build is for some reason only generating a BIN file but not a HEX file nrf52840dk-geeksville is fine From 20497335c27983a78cf3e829ce2452e3df88879a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Thu, 30 Dec 2021 22:20:15 +0100 Subject: [PATCH 05/20] stop old chip from crashing --- src/sleep.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/sleep.cpp b/src/sleep.cpp index 558dbf1d4e..998645dcd9 100644 --- a/src/sleep.cpp +++ b/src/sleep.cpp @@ -65,7 +65,11 @@ void setCPUFast(bool on) return; } - setCpuFrequencyMhz(on ? 240 : 80); + // The Heltec LORA32 V1 runs at 26 MHz base frequency and doesn't react well to switching to 80 MHz... + #ifndef ARDUINO_HELTEC_WIFI_LORA_32 + setCpuFrequencyMhz(on ? 240 : 80); + #endif + #endif } From a16dcbe9d0256f7681f233ab09d36f4b8dbfd9b5 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Thu, 30 Dec 2021 14:24:44 -0800 Subject: [PATCH 06/20] Don't let S&F send payloads if channel utilization is > 50% --- src/plugins/esp32/StoreForwardPlugin.cpp | 30 ++++++++++++++++-------- 1 file changed, 20 insertions(+), 10 deletions(-) diff --git a/src/plugins/esp32/StoreForwardPlugin.cpp b/src/plugins/esp32/StoreForwardPlugin.cpp index 10dedda410..4b8152a084 100644 --- a/src/plugins/esp32/StoreForwardPlugin.cpp +++ b/src/plugins/esp32/StoreForwardPlugin.cpp @@ -3,6 +3,7 @@ #include "NodeDB.h" #include "RTC.h" #include "Router.h" +#include "airtime.h" #include "configuration.h" #include "mesh-pb-constants.h" #include "mesh/generated/storeforward.pb.h" @@ -22,20 +23,29 @@ int32_t StoreForwardPlugin::runOnce() if (radioConfig.preferences.is_router) { + // Send out the message queue. if (this->busy) { - // Send out the message queue. + - // DEBUG_MSG("--- --- --- In busy loop 1 %d\n", this->packetHistoryTXQueue_index); - storeForwardPlugin->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); + // Only send packets if the channel is less than 50% utilized. + if (airTime->channelUtilizationPercent() < 50) { - if (this->packetHistoryTXQueue_index == packetHistoryTXQueue_size) { - strcpy(this->routerMessage, "** S&F - Done"); - storeForwardPlugin->sendMessage(this->busyTo, this->routerMessage); - // DEBUG_MSG("--- --- --- In busy loop - Done \n"); - this->packetHistoryTXQueue_index = 0; - this->busy = false; + // DEBUG_MSG("--- --- --- In busy loop 1 %d\n", this->packetHistoryTXQueue_index); + storeForwardPlugin->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); + + if (this->packetHistoryTXQueue_index == packetHistoryTXQueue_size) { + strcpy(this->routerMessage, "** S&F - Done"); + storeForwardPlugin->sendMessage(this->busyTo, this->routerMessage); + + // DEBUG_MSG("--- --- --- In busy loop - Done \n"); + this->packetHistoryTXQueue_index = 0; + this->busy = false; + } else { + this->packetHistoryTXQueue_index++; + } + } else { - this->packetHistoryTXQueue_index++; + DEBUG_MSG("Channel utilization is too high. Skipping this oppurtunity to send and will retry later.\n"); } } DEBUG_MSG("SF myNodeInfo.bitrate = %f bytes / sec\n", myNodeInfo.bitrate); From 8bbdfe45387246b20e2de0b815d2c0bc2368dd69 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Thu, 30 Dec 2021 15:01:19 -0800 Subject: [PATCH 07/20] Fix typo --- src/plugins/esp32/StoreForwardPlugin.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/plugins/esp32/StoreForwardPlugin.cpp b/src/plugins/esp32/StoreForwardPlugin.cpp index 4b8152a084..f8194563ed 100644 --- a/src/plugins/esp32/StoreForwardPlugin.cpp +++ b/src/plugins/esp32/StoreForwardPlugin.cpp @@ -45,7 +45,7 @@ int32_t StoreForwardPlugin::runOnce() } } else { - DEBUG_MSG("Channel utilization is too high. Skipping this oppurtunity to send and will retry later.\n"); + DEBUG_MSG("Channel utilization is too high. Skipping this opportunity to send and will retry later.\n"); } } DEBUG_MSG("SF myNodeInfo.bitrate = %f bytes / sec\n", myNodeInfo.bitrate); From c8aec324f527ec2367c091657f442a613bec3d50 Mon Sep 17 00:00:00 2001 From: Balazs Kelemen Date: Sat, 1 Jan 2022 11:33:17 +0100 Subject: [PATCH 08/20] Channel-binding filter accepts empty channel names. --- src/mesh/MeshPlugin.cpp | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/src/mesh/MeshPlugin.cpp b/src/mesh/MeshPlugin.cpp index f801682d12..85988ec7b0 100644 --- a/src/mesh/MeshPlugin.cpp +++ b/src/mesh/MeshPlugin.cpp @@ -96,7 +96,7 @@ void MeshPlugin::callPlugins(const MeshPacket &mp, RxSource src) assert(!pi.myReply); // If it is !null it means we have a bug, because it should have been sent the previous time if (wantsPacket) { - DEBUG_MSG("Plugin %s wantsPacket=%d\n", pi.name, wantsPacket); + DEBUG_MSG("Plugin '%s' wantsPacket=%d\n", pi.name, wantsPacket); pluginFound = true; @@ -109,7 +109,10 @@ void MeshPlugin::callPlugins(const MeshPacket &mp, RxSource src) /// Also: if a packet comes in on the local PC interface, we don't check for bound channels, because it is TRUSTED and it needs to /// to be able to fetch the initial admin packets without yet knowing any channels. - bool rxChannelOk = !pi.boundChannel || (mp.from == 0) || (ch && (strcmp(ch->settings.name, pi.boundChannel) == 0)); + bool rxChannelOk = !pi.boundChannel || (mp.from == 0) || + !ch || + strlen(ch->settings.name) > 0 || + strcmp(ch->settings.name, pi.boundChannel); if (!rxChannelOk) { // no one should have already replied! @@ -134,9 +137,9 @@ void MeshPlugin::callPlugins(const MeshPacket &mp, RxSource src) // any other node. if (mp.decoded.want_response && toUs && (getFrom(&mp) != ourNodeNum || mp.to == ourNodeNum) && !currentReply) { pi.sendResponse(mp); - DEBUG_MSG("Plugin %s sent a response\n", pi.name); + DEBUG_MSG("Plugin '%s' sent a response\n", pi.name); } else { - DEBUG_MSG("Plugin %s considered\n", pi.name); + DEBUG_MSG("Plugin '%s' considered\n", pi.name); } // If the requester didn't ask for a response we might need to discard unused replies to prevent memory leaks @@ -147,7 +150,7 @@ void MeshPlugin::callPlugins(const MeshPacket &mp, RxSource src) } if (handled == ProcessMessage::STOP) { - DEBUG_MSG("Plugin %s handled and skipped other processing\n", pi.name); + DEBUG_MSG("Plugin '%s' handled and skipped other processing\n", pi.name); break; } } From 333b19580428f403a336b4a50529e2d0f0fb7ec2 Mon Sep 17 00:00:00 2001 From: linagee Date: Sat, 1 Jan 2022 13:00:32 -0700 Subject: [PATCH 09/20] Don't commit vim swap files to repo (#1051) --- .gitignore | 3 +++ bin/.promote-release.sh.swp | Bin 12288 -> 0 bytes 2 files changed, 3 insertions(+) delete mode 100644 bin/.promote-release.sh.swp diff --git a/.gitignore b/.gitignore index 40bba6f697..3d181a39a9 100644 --- a/.gitignore +++ b/.gitignore @@ -23,3 +23,6 @@ flash.uf2 cmake-build* __pycache__ +*.swp +*.swo +*~ diff --git a/bin/.promote-release.sh.swp b/bin/.promote-release.sh.swp deleted file mode 100644 index 0dddde02b17cd4bae1d425c6efcf64ae2f262208..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 12288 zcmeI&ON$dh5CGtcSMh=Vfif$IxXC2ZgBKA*(cnhKN6yWoe32?g%@aySUb#Qb5Uru^(v@BGp$)~AZ zZT8^B_>QrKo{T2r9Sc8f4$L09qFs`WA$x4%lQz$m6m(P}nqr_ymD%iUT++%El;y@| zjdx2IY2c|Q6=)drj%+d|0wS<2Z~<;l#-sGzUjG_iz4B&zT1Fxu0wN#+A|L`HAOa#F z0{^u@YFO z^#A|n_y6}x0N*%1b9~}39Gc@k$4!o(y#7bG&!@f8L_h>YKmYKmV?Bc>Ue{(aTrU=g;0_(*{i?Mu(M&y3O~y9#s*IvjKy4ZC#>u$Cwl5t*J|6 zD~y`3^lA}t^C%o~xDKv*uz;HB5JiFR5-`R)54sjOp(v5$aiG`bd}yaOb^++>o44}ImO!9 z>JXq~(S~a+ylEoxCui$ZTsV*X3Z81$kPmpwe9F_NmZV^bRT4?s(WM+B&K%#Z4QW&9 R?2X9l*mzxgpojxP_ziF4!36*S From 924069f9ad285e4b09b3406fe5059654ad4e3113 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sat, 1 Jan 2022 19:54:49 -0800 Subject: [PATCH 10/20] S&F - Only TX if utilization is below 25% --- src/plugins/esp32/StoreForwardPlugin.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/plugins/esp32/StoreForwardPlugin.cpp b/src/plugins/esp32/StoreForwardPlugin.cpp index f8194563ed..f613fc7c05 100644 --- a/src/plugins/esp32/StoreForwardPlugin.cpp +++ b/src/plugins/esp32/StoreForwardPlugin.cpp @@ -27,8 +27,8 @@ int32_t StoreForwardPlugin::runOnce() if (this->busy) { - // Only send packets if the channel is less than 50% utilized. - if (airTime->channelUtilizationPercent() < 50) { + // Only send packets if the channel is less than 25% utilized. + if (airTime->channelUtilizationPercent() < 25) { // DEBUG_MSG("--- --- --- In busy loop 1 %d\n", this->packetHistoryTXQueue_index); storeForwardPlugin->sendPayload(this->busyTo, this->packetHistoryTXQueue_index); @@ -424,9 +424,6 @@ StoreForwardPlugin::StoreForwardPlugin() // Popupate PSRAM with our data structures. this->populatePSRAM(); - // this->packetTimeMax = 2000; - // DEBUG_MSG("SF Time to Transmit maxPacketSize (%d bytes) %d ms\n", maxPacketSize, this->packetTimeMax); - } else { DEBUG_MSG("Device has less than 1M of PSRAM free. Aborting startup.\n"); DEBUG_MSG("Store & Forward Plugin - Aborting Startup.\n"); From 749d127281f851e357a763f30a7e9c4687634875 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sat, 1 Jan 2022 23:10:37 -0800 Subject: [PATCH 11/20] Return an informative message if web content files are unavailable. --- src/mesh/http/ContentHandler.cpp | 12 ++++++++++-- src/mesh/http/WiFiAPClient.cpp | 23 +++++++++++------------ 2 files changed, 21 insertions(+), 14 deletions(-) diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index c1fced6dea..9a655839f3 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -297,14 +297,21 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) file = SPIFFS.open(filenameGzip.c_str()); res->setHeader("Content-Encoding", "gzip"); if (!file.available()) { - DEBUG_MSG("File not available\n"); + DEBUG_MSG("File not available - %s\n", filenameGzip.c_str()); } } else { has_set_content_type = true; filenameGzip = "/static/index.html.gz"; file = SPIFFS.open(filenameGzip.c_str()); - res->setHeader("Content-Encoding", "gzip"); res->setHeader("Content-Type", "text/html"); + if (!file.available()) { + DEBUG_MSG("File not available - %s\n", filenameGzip.c_str()); + res->println("Web server is running.

The content you are looking for can't be found. Please see: FAQ.

stats"); + } else { + res->setHeader("Content-Encoding", "gzip"); + } } res->setHeader("Content-Length", httpsserver::intToString(file.size())); @@ -576,6 +583,7 @@ void handleReport(HTTPRequest *req, HTTPResponse *res) res->println("},"); res->println("\"device\": {"); + res->printf("\"channel_utilization\": %3.2f%,\n", airTime->channelUtilizationPercent()); res->printf("\"reboot_counter\": %d\n", myNodeInfo.reboot_count); res->println("},"); diff --git a/src/mesh/http/WiFiAPClient.cpp b/src/mesh/http/WiFiAPClient.cpp index 91892b5de7..c5cbe9c93b 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -3,9 +3,9 @@ #include "concurrency/Periodic.h" #include "configuration.h" #include "main.h" -#include "mqtt/MQTT.h" #include "mesh/http/WebServer.h" #include "mesh/wifi/WiFiServerAPI.h" +#include "mqtt/MQTT.h" #include "target_specific.h" #include #include @@ -132,30 +132,30 @@ static void onNetworkConnected() initApiServer(); APStartupComplete = true; - } + } // FIXME this is kinda yucky, instead we should just have an observable for 'wifireconnected' - if(mqtt) + if (mqtt) mqtt->reconnect(); } // Startup WiFi bool initWifi(bool forceSoftAP) { - if (forceSoftAP) { - DEBUG_MSG("WiFi ... Forced AP Mode\n"); - } else if (radioConfig.preferences.wifi_ap_mode) { - DEBUG_MSG("WiFi ... AP Mode\n"); - } else { - DEBUG_MSG("WiFi ... Client Mode\n"); - } - forcedSoftAP = forceSoftAP; if ((radioConfig.has_preferences && radioConfig.preferences.wifi_ssid[0]) || forceSoftAP) { const char *wifiName = radioConfig.preferences.wifi_ssid; const char *wifiPsw = radioConfig.preferences.wifi_password; + if (forceSoftAP) { + DEBUG_MSG("WiFi ... Forced AP Mode\n"); + } else if (radioConfig.preferences.wifi_ap_mode) { + DEBUG_MSG("WiFi ... AP Mode\n"); + } else { + DEBUG_MSG("WiFi ... Client Mode\n"); + } + createSSLCert(); if (!*wifiPsw) // Treat empty password as no password @@ -176,7 +176,6 @@ bool initWifi(bool forceSoftAP) } else { DEBUG_MSG("Starting WIFI AP: ssid=%s, ok=%d\n", wifiName, WiFi.softAP(wifiName, wifiPsw)); - } WiFi.softAPConfig(apIP, apIP, IPAddress(255, 255, 255, 0)); From 5d4f039b3e8b04736a9fecd2c91ef719775e33f7 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sat, 1 Jan 2022 23:25:20 -0800 Subject: [PATCH 12/20] updating proto submodule to latest --- proto | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/proto b/proto index 4a64080d16..7b80bde421 160000 --- a/proto +++ b/proto @@ -1 +1 @@ -Subproject commit 4a64080d160f9219768a4126414d41dc82a3d63c +Subproject commit 7b80bde4213c530ab3d85a19d1795025299d4633 From 3857dd7e5228d45953ce648b7df7edd2accee67c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Thomas=20G=C3=B6ttgens?= Date: Sun, 2 Jan 2022 14:41:41 +0100 Subject: [PATCH 13/20] regen protobuf headers --- src/mesh/generated/mesh.pb.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/mesh/generated/mesh.pb.h b/src/mesh/generated/mesh.pb.h index 27e7d53cd3..c5c980a353 100644 --- a/src/mesh/generated/mesh.pb.h +++ b/src/mesh/generated/mesh.pb.h @@ -23,6 +23,7 @@ typedef enum _HardwareModel { HardwareModel_TLORA_V1_1p3 = 8, HardwareModel_RAK4631 = 9, HardwareModel_HELTEC_V2_1 = 10, + HardwareModel_HELTEC_V1 = 11, HardwareModel_LORA_RELAY_V1 = 32, HardwareModel_NRF52840DK = 33, HardwareModel_PPR = 34, From 9a87ec73536e9791b0f982e3cbe1a9a249b3cca3 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sun, 2 Jan 2022 11:05:32 -0800 Subject: [PATCH 14/20] Count tx airtime only after it's sent by the radio --- src/mesh/RadioLibInterface.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/mesh/RadioLibInterface.cpp b/src/mesh/RadioLibInterface.cpp index cb77d9ec3d..4455b971cf 100644 --- a/src/mesh/RadioLibInterface.cpp +++ b/src/mesh/RadioLibInterface.cpp @@ -101,7 +101,6 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) // Sometimes when testing it is useful to be able to never turn on the xmitter #ifndef LORA_DISABLE_SENDING printPacket("enqueuing for send", p); - uint32_t xmitMsec = getPacketTime(p); DEBUG_MSG("txGood=%d,rxGood=%d,rxBad=%d\n", txGood, rxGood, rxBad); ErrorCode res = txQueue.enqueue(p) ? ERRNO_OK : ERRNO_UNKNOWN; @@ -111,10 +110,6 @@ ErrorCode RadioLibInterface::send(MeshPacket *p) return res; } - // Count the packet toward our TX airtime utilization. - // We only count it if it can be added to the TX queue. - airTime->logAirtime(TX_LOG, xmitMsec); - // We want all sending/receiving to be done by our daemon thread, We use a delay here because this packet might have been sent // in response to a packet we just received. So we want to make sure the other side has had a chance to reconfigure its radio startTransmitTimer(true); @@ -188,6 +183,10 @@ void RadioLibInterface::onNotify(uint32_t notification) MeshPacket *txp = txQueue.dequeue(); assert(txp); startSend(txp); + + // Packet has been sent, count it toward our TX airtime utilization. + uint32_t xmitMsec = getPacketTime(txp); + airTime->logAirtime(TX_LOG, xmitMsec); } } else { // DEBUG_MSG("done with txqueue\n"); From 4d82a0146b3913141ef8f8f796b980802f62162b Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sun, 2 Jan 2022 19:50:43 -0800 Subject: [PATCH 15/20] Initial checkin of Online OTA SPIFFS update --- platformio.ini | 1 + src/mesh/RadioLibInterface.h | 1 + src/mesh/http/ContentHandler.cpp | 137 ++++++++++++++++++++++++++++++- src/mesh/http/ContentHandler.h | 5 +- 4 files changed, 139 insertions(+), 5 deletions(-) diff --git a/platformio.ini b/platformio.ini index 9c301ea337..155460b1ce 100644 --- a/platformio.ini +++ b/platformio.ini @@ -115,6 +115,7 @@ lib_deps = paulstoffregen/OneWire@^2.3.5 robtillaart/DS18B20@^0.1.11 h2zero/NimBLE-Arduino@1.3.1 + tobozo/ESP32-targz@^1.1.4 # Hmm - this doesn't work yet # board_build.ldscript = linker/esp32.extram.bss.ld lib_ignore = diff --git a/src/mesh/RadioLibInterface.h b/src/mesh/RadioLibInterface.h index 54d9e67441..de3505524c 100644 --- a/src/mesh/RadioLibInterface.h +++ b/src/mesh/RadioLibInterface.h @@ -8,6 +8,7 @@ #define RADIOLIB_SOFTWARE_SERIAL_UNSUPPORTED #endif +#define RADIOLIB_EXCLUDE_HTTP #include // ESP32 has special rules about ISR code diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index 9a655839f3..38fab48487 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -41,6 +41,13 @@ using namespace httpsserver; #include "mesh/http/ContentHandler.h" +#include +#include +HTTPClient http; + +#define DEST_FS_USES_SPIFFS +#include + // We need to specify some content-type mapping, so the resources get delivered with the // right content type and are displayed correctly in the browser char contentTypes[][2][32] = {{".txt", "text/plain"}, {".html", "text/html"}, @@ -50,9 +57,58 @@ char contentTypes[][2][32] = {{".txt", "text/plain"}, {".html", "text/html"} {".css", "text/css"}, {".ico", "image/vnd.microsoft.icon"}, {".svg", "image/svg+xml"}, {"", ""}}; +const char *tarURL = "https://www.casler.org/temp/meshtastic-web.tar"; +const char *certificate = NULL; // change this as needed, leave as is for no TLS check (yolo security) + // Our API to handle messages to and from the radio. HttpAPI webAPI; +WiFiClient *getTarHTTPClientPtr(WiFiClientSecure *client, const char *url, const char *cert = NULL) +{ + if (cert == NULL) { + // New versions don't have setInsecure + // client->setInsecure(); + } else { + client->setCACert(cert); + } + const char *UserAgent = "ESP32-HTTP-GzUpdater-Client"; + http.setReuse(true); // handle 301 redirects gracefully + http.setUserAgent(UserAgent); + http.setConnectTimeout(10000); // 10s timeout = 10000 + if (!http.begin(*client, url)) { + log_e("Can't open url %s", url); + return nullptr; + } + const char *headerKeys[] = {"location", "redirect", "Content-Type", "Content-Length", "Content-Disposition"}; + const size_t numberOfHeaders = 5; + http.collectHeaders(headerKeys, numberOfHeaders); + int httpCode = http.GET(); + // file found at server + if (httpCode == HTTP_CODE_FOUND || httpCode == HTTP_CODE_MOVED_PERMANENTLY) { + String newlocation = ""; + String headerLocation = http.header("location"); + String headerRedirect = http.header("redirect"); + if (headerLocation != "") { + newlocation = headerLocation; + Serial.printf("302 (location): %s => %s\n", url, headerLocation.c_str()); + } else if (headerRedirect != "") { + Serial.printf("301 (redirect): %s => %s\n", url, headerLocation.c_str()); + newlocation = headerRedirect; + } + http.end(); + if (newlocation != "") { + log_w("Found 302/301 location header: %s", newlocation.c_str()); + return getTarHTTPClientPtr(client, newlocation.c_str(), cert); + } else { + log_e("Empty redirect !!"); + return nullptr; + } + } + if (httpCode != 200) + return nullptr; + return http.getStreamPtr(); +} + void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer) { @@ -66,6 +122,8 @@ void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer) ResourceNode *nodeHotspotApple = new ResourceNode("/hotspot-detect.html", "GET", &handleHotspot); ResourceNode *nodeHotspotAndroid = new ResourceNode("/generate_204", "GET", &handleHotspot); + ResourceNode *nodeUpdateSPIFFS = new ResourceNode("/update", "GET", &handleUpdateSPIFFS); + ResourceNode *nodeRestart = new ResourceNode("/restart", "POST", &handleRestart); ResourceNode *nodeFormUpload = new ResourceNode("/upload", "POST", &handleFormUpload); @@ -90,7 +148,8 @@ void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer) secureServer->registerNode(nodeJsonSpiffsBrowseStatic); secureServer->registerNode(nodeJsonDelete); secureServer->registerNode(nodeJsonReport); - secureServer->registerNode(nodeRoot); + secureServer->registerNode(nodeUpdateSPIFFS); + secureServer->registerNode(nodeRoot); // This has to be last // Insecure nodes insecureServer->registerNode(nodeAPIv1ToRadioOptions); @@ -105,7 +164,8 @@ void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer) insecureServer->registerNode(nodeJsonSpiffsBrowseStatic); insecureServer->registerNode(nodeJsonDelete); insecureServer->registerNode(nodeJsonReport); - insecureServer->registerNode(nodeRoot); + insecureServer->registerNode(nodeUpdateSPIFFS); + insecureServer->registerNode(nodeRoot); // This has to be last } void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) @@ -620,6 +680,79 @@ void handleHotspot(HTTPRequest *req, HTTPResponse *res) res->println("\n"); } +void handleUpdateSPIFFS(HTTPRequest *req, HTTPResponse *res) +{ + res->setHeader("Content-Type", "text/html"); + res->setHeader("Access-Control-Allow-Origin", "*"); + res->setHeader("Access-Control-Allow-Methods", "GET"); + + res->println("Updating. Don't leave this page!"); + + DEBUG_MSG("hi!\n"); + + File root = SPIFFS.open("/"); + File file = root.openNextFile(); + + DEBUG_MSG("Deleting files from /static\n"); + + while (file) { + String filePath = String(file.name()); + if (filePath.indexOf("/static") == 0) { + DEBUG_MSG("%s\n", file.name()); + SPIFFS.remove(file.name()); + } + file = root.openNextFile(); + } + + // return; + + WiFiClientSecure *client = new WiFiClientSecure; + Stream *streamptr = getTarHTTPClientPtr(client, tarURL, certificate); + + if (streamptr != nullptr) { + + TarUnpacker *TARUnpacker = new TarUnpacker(); + TARUnpacker->haltOnError(true); // stop on fail (manual restart/reset required) + TARUnpacker->setTarVerify(true); // true = enables health checks but slows down the overall process + TARUnpacker->setupFSCallbacks(targzTotalBytesFn, targzFreeBytesFn); // prevent the partition from exploding, recommended + TARUnpacker->setLoggerCallback(BaseUnpacker::targzPrintLoggerCallback); // gz log verbosity + TARUnpacker->setTarProgressCallback( + BaseUnpacker::defaultProgressCallback); // prints the untarring progress for each individual file + TARUnpacker->setTarStatusProgressCallback( + BaseUnpacker::defaultTarStatusProgressCallback); // print the filenames as they're expanded + TARUnpacker->setTarMessageCallback(BaseUnpacker::targzPrintLoggerCallback); // tar log verbosity + + String contentLengthStr = http.header("Content-Length"); + contentLengthStr.trim(); + int64_t streamSize = -1; + if (contentLengthStr != "") { + streamSize = atoi(contentLengthStr.c_str()); + Serial.printf("Stream size %d\n", streamSize); + res->printf("Stream size %d\n", streamSize); + } + + if (!TARUnpacker->tarStreamExpander(streamptr, streamSize, SPIFFS, "/static")) { + Serial.printf("tarStreamExpander failed with return code #%d\n", TARUnpacker->tarGzGetError()); + } else { + // print leftover bytes if any (probably zero-fill from the server) + while (http.connected()) { + size_t streamSize = streamptr->available(); + if (streamSize) { + Serial.printf("%02x ", streamptr->read()); + } else + break; + } + + res->println("Done"); + } + + } else { + Serial.println("Failed to establish http connection"); + } + + res->println("Done"); +} + void handleRestart(HTTPRequest *req, HTTPResponse *res) { res->setHeader("Content-Type", "text/html"); diff --git a/src/mesh/http/ContentHandler.h b/src/mesh/http/ContentHandler.h index cc07cb8337..f456d0a1f0 100644 --- a/src/mesh/http/ContentHandler.h +++ b/src/mesh/http/ContentHandler.h @@ -1,5 +1,6 @@ #pragma once + void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer); // Declare some handler functions for the various URLs on the server @@ -14,9 +15,7 @@ void handleSpiffsBrowseStatic(HTTPRequest *req, HTTPResponse *res); void handleSpiffsDeleteStatic(HTTPRequest *req, HTTPResponse *res); void handleBlinkLED(HTTPRequest *req, HTTPResponse *res); void handleReport(HTTPRequest *req, HTTPResponse *res); - -void middlewareSpeedUp240(HTTPRequest *req, HTTPResponse *res, std::function next); -void middlewareSpeedUp160(HTTPRequest *req, HTTPResponse *res, std::function next); +void handleUpdateSPIFFS(HTTPRequest *req, HTTPResponse *res); // Interface to the PhoneAPI to access the protobufs with messages class HttpAPI : public PhoneAPI From 893472e36a671047006e5f32dbdf0a62e35ed428 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sun, 2 Jan 2022 20:05:13 -0800 Subject: [PATCH 16/20] Update text and tar URL --- src/mesh/http/ContentHandler.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index 38fab48487..737335b839 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -57,7 +57,7 @@ char contentTypes[][2][32] = {{".txt", "text/plain"}, {".html", "text/html"} {".css", "text/css"}, {".ico", "image/vnd.microsoft.icon"}, {".svg", "image/svg+xml"}, {"", ""}}; -const char *tarURL = "https://www.casler.org/temp/meshtastic-web.tar"; +const char *tarURL = "https://github.com/meshtastic/meshtastic-web/releases/download/latest/build.tar"; const char *certificate = NULL; // change this as needed, leave as is for no TLS check (yolo security) // Our API to handle messages to and from the radio. @@ -368,7 +368,7 @@ void handleStatic(HTTPRequest *req, HTTPResponse *res) DEBUG_MSG("File not available - %s\n", filenameGzip.c_str()); res->println("Web server is running.

The content you are looking for can't be found. Please see: FAQ.

stats"); + "href=/json/report>stats

Experemntal Web Content OTA Update"); } else { res->setHeader("Content-Encoding", "gzip"); } @@ -742,8 +742,6 @@ void handleUpdateSPIFFS(HTTPRequest *req, HTTPResponse *res) } else break; } - - res->println("Done"); } } else { From b2011a1889e585f62332b4b308475e3f158e6ad9 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sun, 2 Jan 2022 20:37:52 -0800 Subject: [PATCH 17/20] Switching url to casler.org. github has too many redirections. --- src/mesh/http/ContentHandler.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index 737335b839..3f622b65c8 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -57,7 +57,8 @@ char contentTypes[][2][32] = {{".txt", "text/plain"}, {".html", "text/html"} {".css", "text/css"}, {".ico", "image/vnd.microsoft.icon"}, {".svg", "image/svg+xml"}, {"", ""}}; -const char *tarURL = "https://github.com/meshtastic/meshtastic-web/releases/download/latest/build.tar"; +//const char *tarURL = "https://github.com/meshtastic/meshtastic-web/releases/download/latest/build.tar"; +const char *tarURL = "https://www.casler.org/temp/meshtastic-web.tar"; const char *certificate = NULL; // change this as needed, leave as is for no TLS check (yolo security) // Our API to handle messages to and from the radio. From 6d0368b13d421331a434714d7f88a9fc6a996d5b Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sun, 2 Jan 2022 22:10:55 -0800 Subject: [PATCH 18/20] Update URL to proper meshtastic web download location & disable halting --- src/mesh/http/ContentHandler.cpp | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index 3f622b65c8..3e35ee5fd5 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -57,8 +57,8 @@ char contentTypes[][2][32] = {{".txt", "text/plain"}, {".html", "text/html"} {".css", "text/css"}, {".ico", "image/vnd.microsoft.icon"}, {".svg", "image/svg+xml"}, {"", ""}}; -//const char *tarURL = "https://github.com/meshtastic/meshtastic-web/releases/download/latest/build.tar"; -const char *tarURL = "https://www.casler.org/temp/meshtastic-web.tar"; +//const char *tarURL = "https://www.casler.org/temp/meshtastic-web.tar"; +const char *tarURL = "https://api-production-871d.up.railway.app/mirror/webui"; const char *certificate = NULL; // change this as needed, leave as is for no TLS check (yolo security) // Our API to handle messages to and from the radio. @@ -687,9 +687,7 @@ void handleUpdateSPIFFS(HTTPRequest *req, HTTPResponse *res) res->setHeader("Access-Control-Allow-Origin", "*"); res->setHeader("Access-Control-Allow-Methods", "GET"); - res->println("Updating. Don't leave this page!"); - - DEBUG_MSG("hi!\n"); + res->println("Downloading Meshtastic Web Content..."); File root = SPIFFS.open("/"); File file = root.openNextFile(); @@ -713,8 +711,8 @@ void handleUpdateSPIFFS(HTTPRequest *req, HTTPResponse *res) if (streamptr != nullptr) { TarUnpacker *TARUnpacker = new TarUnpacker(); - TARUnpacker->haltOnError(true); // stop on fail (manual restart/reset required) - TARUnpacker->setTarVerify(true); // true = enables health checks but slows down the overall process + TARUnpacker->haltOnError(false); // stop on fail (manual restart/reset required) + TARUnpacker->setTarVerify(false); // true = enables health checks but slows down the overall process TARUnpacker->setupFSCallbacks(targzTotalBytesFn, targzFreeBytesFn); // prevent the partition from exploding, recommended TARUnpacker->setLoggerCallback(BaseUnpacker::targzPrintLoggerCallback); // gz log verbosity TARUnpacker->setTarProgressCallback( From 063d7a7d8117271b084f18f925143d723381cf78 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Sun, 2 Jan 2022 22:17:26 -0800 Subject: [PATCH 19/20] Cleanup API endpoint debug output --- src/mesh/http/ContentHandler.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/mesh/http/ContentHandler.cpp b/src/mesh/http/ContentHandler.cpp index 3e35ee5fd5..c051e0cda8 100644 --- a/src/mesh/http/ContentHandler.cpp +++ b/src/mesh/http/ContentHandler.cpp @@ -172,7 +172,7 @@ void registerHandlers(HTTPServer *insecureServer, HTTPSServer *secureServer) void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) { - DEBUG_MSG("+++++++++++++++ webAPI handleAPIv1FromRadio\n"); + DEBUG_MSG("webAPI handleAPIv1FromRadio\n"); /* For documentation, see: @@ -217,12 +217,12 @@ void handleAPIv1FromRadio(HTTPRequest *req, HTTPResponse *res) res->write(txBuf, len); } - DEBUG_MSG("--------------- webAPI handleAPIv1FromRadio, len %d\n", len); + DEBUG_MSG("webAPI handleAPIv1FromRadio, len %d\n", len); } void handleAPIv1ToRadio(HTTPRequest *req, HTTPResponse *res) { - DEBUG_MSG("+++++++++++++++ webAPI handleAPIv1ToRadio\n"); + DEBUG_MSG("webAPI handleAPIv1ToRadio\n"); /* For documentation, see: @@ -249,7 +249,7 @@ void handleAPIv1ToRadio(HTTPRequest *req, HTTPResponse *res) webAPI.handleToRadio(buffer, s); res->write(buffer, s); - DEBUG_MSG("--------------- webAPI handleAPIv1ToRadio\n"); + DEBUG_MSG("webAPI handleAPIv1ToRadio\n"); } void handleSpiffsBrowseStatic(HTTPRequest *req, HTTPResponse *res) From 38baebe48f34d8c9ba846f299e183d26ff37cc91 Mon Sep 17 00:00:00 2001 From: Jm Casler Date: Mon, 3 Jan 2022 17:35:20 -0800 Subject: [PATCH 20/20] Use NTP time if connected to wifi --- src/mesh/http/WiFiAPClient.cpp | 27 ++++++++++++++++++--------- 1 file changed, 18 insertions(+), 9 deletions(-) diff --git a/src/mesh/http/WiFiAPClient.cpp b/src/mesh/http/WiFiAPClient.cpp index 2037d06eb9..1101ad1cd9 100644 --- a/src/mesh/http/WiFiAPClient.cpp +++ b/src/mesh/http/WiFiAPClient.cpp @@ -1,5 +1,6 @@ #include "mesh/http/WiFiAPClient.h" #include "NodeDB.h" +#include "RTC.h" #include "concurrency/Periodic.h" #include "configuration.h" #include "main.h" @@ -9,9 +10,9 @@ #include "target_specific.h" #include #include +#include #include #include -#include using namespace concurrency; @@ -55,8 +56,7 @@ static int32_t reconnectWiFi() const char *wifiName = radioConfig.preferences.wifi_ssid; const char *wifiPsw = radioConfig.preferences.wifi_password; - if (radioConfig.has_preferences && needReconnect) { - + if (radioConfig.has_preferences && needReconnect && !WiFi.isConnected()) { if (!*wifiPsw) // Treat empty password as no password wifiPsw = NULL; @@ -67,19 +67,27 @@ static int32_t reconnectWiFi() DEBUG_MSG("... Reconnecting to WiFi access point\n"); WiFi.mode(WIFI_MODE_STA); WiFi.begin(wifiName, wifiPsw); + // Starting timeClient; - - } } - if (*wifiName) { + //if (*wifiName) { + if (WiFi.isConnected()) { DEBUG_MSG("Updating NTP time\n"); - timeClient.update(); + if (timeClient.update()) { + DEBUG_MSG("NTP Request Success - Setting RTCQualityNTP if needed\n"); + + struct timeval tv; + tv.tv_sec = timeClient.getEpochTime(); + tv.tv_usec = 0; + + perhapsSetRTC(RTCQualityNTP, &tv); - Serial.println(timeClient.getFormattedTime()); - Serial.println(timeClient.getEpochTime()); + } else { + DEBUG_MSG("NTP Update failed\n"); + } } return 30 * 1000; // every 30 seconds @@ -149,6 +157,7 @@ static void onNetworkConnected() DEBUG_MSG("Starting NTP time client\n"); timeClient.begin(); + timeClient.setUpdateInterval(60*60); // Update once an hour initWebServer(); initApiServer();