From baf8a45bcff1505d1296467a48faf1e8ac00aa67 Mon Sep 17 00:00:00 2001 From: Shahram <71178922+Nourbakhsh-Rad@users.noreply.github.com> Date: Wed, 22 Dec 2021 11:43:29 +0330 Subject: [PATCH 01/14] Update ESPNtpClient.cpp --- src/ESPNtpClient.cpp | 37 ++++++++++++++++++++++++++++--------- 1 file changed, 28 insertions(+), 9 deletions(-) diff --git a/src/ESPNtpClient.cpp b/src/ESPNtpClient.cpp index 55b7e57..d372780 100644 --- a/src/ESPNtpClient.cpp +++ b/src/ESPNtpClient.cpp @@ -178,14 +178,14 @@ bool NTPClient::begin (const char* ntpServerName) { } DEBUGLOGI ("NTP socket created"); - if (WiFi.isConnected ()) { + if (connectionStatus ()) { ip_addr_t localAddress; #ifdef ESP32 - localAddress.u_addr.ip4.addr = WiFi.localIP (); + localAddress.u_addr.ip4.addr = getDeviceIP (); localAddress.type = IPADDR_TYPE_V4; DEBUGLOGI ("Bind UDP port %d to %s", DEFAULT_NTP_PORT, IPAddress (localAddress.u_addr.ip4.addr).toString ().c_str ()); #else - localAddress.addr = WiFi.localIP (); + localAddress.addr = getDeviceIP (); DEBUGLOGI ("Bind UDP port %d to %s", DEFAULT_NTP_PORT, IPAddress (localAddress.addr).toString ().c_str ()); #endif result = udp_bind (udp, /*IP_ADDR_ANY*/ &localAddress, DEFAULT_NTP_PORT); @@ -520,7 +520,7 @@ void NTPClient::s_getTimeloop (void* arg) { lastGotTime = ::millis (); DEBUGLOGI ("Periodic loop. Millis = %d", lastGotTime); if (self->isConnected) { - if (WiFi.isConnected ()) { + if (connectionStatus ()) { self->getTime (); } else { DEBUGLOGE ("DISCONNECTED"); @@ -532,7 +532,7 @@ void NTPClient::s_getTimeloop (void* arg) { self->isConnected = false; } } else { - if (WiFi.isConnected ()) { + if (connectionStatus ()) { DEBUGLOGD ("CONNECTED. Binding"); if (self->udp) { udp_disconnect (self->udp); @@ -548,10 +548,10 @@ void NTPClient::s_getTimeloop (void* arg) { ip_addr_t localAddress; #ifdef ESP32 - localAddress.u_addr.ip4.addr = WiFi.localIP (); + localAddress.u_addr.ip4.addr = getDeviceIP (); localAddress.type = IPADDR_TYPE_V4; #else // ESP8266 - localAddress.addr = WiFi.localIP (); + localAddress.addr = getDeviceIP (); #endif // ESP32 err_t result = udp_bind (self->udp, /*IP_ADDR_ANY*/ &localAddress, DEFAULT_NTP_PORT); DEBUGLOGI ("Bind UDP port"); @@ -607,8 +607,8 @@ void NTPClient::getTime () { } if (dnsErrors >= 3) { dnsErrors = 0; - DEBUGLOGW ("Reconnecting WiFi"); - WiFi.reconnect (); + DEBUGLOGW ("Reconnecting WiFi/Ethernet"); + connectionReconnect (); } return; } else { @@ -1191,3 +1191,22 @@ char* NTPClient::ntpEvent2str (NTPEvent_t e) { return result; } + +/// weak functions to get connection status, reconnect and IP address of device +extern "C" +{ + bool connectionStatus() __attribute__ ((weak, alias("__connectionStatus"))); + bool __connectionStatus() { + //***** + } + + bool connectionReconnect() __attribute__ ((weak, alias("__connectionReconnect"))); + bool __connectionReconnect() { + //***** + } + + IPAddress getDeviceIP() __attribute__ ((weak, alias("__getDeviceIP"))); + IPAddress __getDeviceIP() { + //***** + } +} From 874e6b0eac7962f377eed96042f81abb300a5ff9 Mon Sep 17 00:00:00 2001 From: Shahram <71178922+Nourbakhsh-Rad@users.noreply.github.com> Date: Wed, 22 Dec 2021 11:52:01 +0330 Subject: [PATCH 02/14] Update ESPNtpClient.h --- src/ESPNtpClient.h | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/ESPNtpClient.h b/src/ESPNtpClient.h index 1789e72..6e749c3 100644 --- a/src/ESPNtpClient.h +++ b/src/ESPNtpClient.h @@ -236,6 +236,14 @@ typedef std::function onSyncEvent_t; ///< @brief Event notifi static char strBuffer[35]; ///< @brief Temporary buffer for time and date strings +/// weak functions to get connection status, reconnect and IP address of device +extern "C" +{ + bool connectionStatus(); + bool connectionReconnect(); + IPAddress getDeviceIP(); +} + /** * @brief NTPClient class */ From 65690994e4e613893e7c48b8ab71acc6a8f9ac18 Mon Sep 17 00:00:00 2001 From: Shahram <71178922+Nourbakhsh-Rad@users.noreply.github.com> Date: Wed, 22 Dec 2021 12:00:48 +0330 Subject: [PATCH 03/14] Update advancedExample.ino --- examples/advancedExample/advancedExample.ino | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/examples/advancedExample/advancedExample.ino b/examples/advancedExample/advancedExample.ino index cd3ef97..05940bf 100644 --- a/examples/advancedExample/advancedExample.ino +++ b/examples/advancedExample/advancedExample.ino @@ -29,6 +29,17 @@ NTPEvent_t ntpEvent; // Last triggered event double offset; double timedelay; +// weak functions to get connection status, reconnect and IP address of device +bool connectionStatus() { + return WiFi.isConnected (); +} +bool connectionReconnect() { + return WiFi.reconnect (); +} +IPAddress getDeviceIP() { + return WiFi.localIP (); +} + #ifdef ESP32 void onWifiEvent (system_event_id_t event, system_event_info_t info) { #else @@ -138,4 +149,4 @@ void loop() { i++; } delay (0); -} \ No newline at end of file +} From c4f8c7147aa9ec4b989dc8229ed5f2afb751aa0c Mon Sep 17 00:00:00 2001 From: Shahram <71178922+Nourbakhsh-Rad@users.noreply.github.com> Date: Wed, 22 Dec 2021 12:01:45 +0330 Subject: [PATCH 04/14] Update ledFlasher.ino --- examples/ledFlasher/ledFlasher.ino | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/examples/ledFlasher/ledFlasher.ino b/examples/ledFlasher/ledFlasher.ino index 82046ff..75d6b8f 100644 --- a/examples/ledFlasher/ledFlasher.ino +++ b/examples/ledFlasher/ledFlasher.ino @@ -27,6 +27,16 @@ void processSyncEvent (NTPEvent_t ntpEvent) { Serial.printf ("[NTP-event] %s\n", NTP.ntpEvent2str(ntpEvent)); } +// weak functions to get connection status, reconnect and IP address of device +bool connectionStatus() { + return WiFi.isConnected (); +} +bool connectionReconnect() { + return WiFi.reconnect (); +} +IPAddress getDeviceIP() { + return WiFi.localIP (); +} void setup () { Serial.begin (115200); From 92b8ffcb76e102231d8bb3118b771190668213f8 Mon Sep 17 00:00:00 2001 From: Shahram <71178922+Nourbakhsh-Rad@users.noreply.github.com> Date: Wed, 22 Dec 2021 12:03:37 +0330 Subject: [PATCH 05/14] Update basicExample.ino --- examples/basicExample/basicExample.ino | 46 ++++++++++++++++++++++++-- 1 file changed, 44 insertions(+), 2 deletions(-) diff --git a/examples/basicExample/basicExample.ino b/examples/basicExample/basicExample.ino index f6355f6..0559fef 100644 --- a/examples/basicExample/basicExample.ino +++ b/examples/basicExample/basicExample.ino @@ -2,11 +2,21 @@ //#include "WifiConfig.h" +#define USE_ETHERNET true /* false: WiFi or true: lwIP_Etherner */ + #include #ifdef ESP32 #include #else #include + +#if (USE_ETHERNET) + #include + #include + + #define ETH_SS_PIN 4 + ENC28J60lwIP eth(ETH_SS_PIN); +#endif #endif #ifndef WIFI_CONFIG_H @@ -16,10 +26,42 @@ #define SHOW_TIME_PERIOD 1000 +// weak functions to get connection status, reconnect and IP address of device +bool connectionStatus() { + #if (USE_ETHERNET) + return eth.connected (); + #else + return WiFi.isConnected (); + #endif +} +bool connectionReconnect() { + #if (USE_ETHERNET) + return true; + #else + return WiFi.reconnect (); + #endif +} +IPAddress getDeviceIP() { + #if (USE_ETHERNET) + return eth.localIP (); + #else + return WiFi.localIP (); + #endif +} + void setup() { Serial.begin (115200); Serial.println (); - WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); + + #if (USE_ETHERNET) + SPI.begin(); + + eth.setDefault(); // use ethernet for default route + eth.begin(); + #else + WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); + #endif + NTP.setTimeZone (TZ_Etc_UTC); NTP.begin (); } @@ -31,4 +73,4 @@ void loop() { last = millis (); Serial.println (NTP.getTimeDateStringUs ()); } -} \ No newline at end of file +} From c5e8d70eedcc7d5c272c29172f6efde9a937a597 Mon Sep 17 00:00:00 2001 From: Shahram Date: Thu, 23 Dec 2021 17:46:29 +0330 Subject: [PATCH 06/14] Update advancedExample.ino --- examples/advancedExample/advancedExample.ino | 240 ++++++++++++++----- 1 file changed, 175 insertions(+), 65 deletions(-) diff --git a/examples/advancedExample/advancedExample.ino b/examples/advancedExample/advancedExample.ino index 05940bf..9074725 100644 --- a/examples/advancedExample/advancedExample.ino +++ b/examples/advancedExample/advancedExample.ino @@ -1,28 +1,54 @@ #include //#include "WifiConfig.h" +#define USE_ETHERNET false /* false: WiFi or true: lwIP_Etherner */ +#define USE_STATIC false /* false: DHCP or true: STATIC */ + #include + #ifdef ESP32 -#include + #include + + #undef USE_ETHERNET + #define USE_ETHERNET false #else -#include -#endif + #include + + #if (USE_ETHERNET) + #include + #include + + #define ETH_SS_PIN 4 + ENC28J60lwIP eth(ETH_SS_PIN); + #endif +#endif //ESP32 #ifndef WIFI_CONFIG_H -#define YOUR_WIFI_SSID "YOUR_WIFI_SSID" -#define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD" + #define YOUR_WIFI_SSID "YOUR_WIFI_SSID" + #define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD" + + // YOUR_ROUTER_SETTINGS + #if (USE_STATIC) + IPAddress apIP(192, 168, 1, 10); + IPAddress gwIP(192, 168, 1, 1); + IPAddress snIP(255, 255, 255, 0); + IPAddress dnIP1(192, 168, 1, 1); + IPAddress dnIP2( 8, 8, 8, 8); + #endif #endif // !WIFI_CONFIG_H #ifdef ESP32 -#define ONBOARDLED 5 // Built in LED on some ESP-32 boards + #define ONBOARDLED 5 // Built in LED on some ESP-32 boards #else -#define ONBOARDLED 2 // Built in LED on ESP-12/ESP-07 + #define ONBOARDLED 2 // Built in LED on ESP-12/ESP-07 #endif + #define SHOW_TIME_PERIOD 1000 #define NTP_TIMEOUT 5000 const PROGMEM char* ntpServer = "pool.ntp.org"; -bool wifiFirstConnected = false; +bool conFirstConnected = false; +bool conLastStatus = false; boolean syncEventTriggered = false; // True if a time even has been triggered NTPEvent_t ntpEvent; // Last triggered event @@ -31,62 +57,79 @@ double timedelay; // weak functions to get connection status, reconnect and IP address of device bool connectionStatus() { - return WiFi.isConnected (); + #if (USE_ETHERNET) + return eth.connected (); + #else + return WiFi.isConnected (); + #endif } + bool connectionReconnect() { - return WiFi.reconnect (); + #if (USE_ETHERNET) + return true; + #else + return WiFi.reconnect (); + #endif } + IPAddress getDeviceIP() { - return WiFi.localIP (); + #if (USE_ETHERNET) + return eth.localIP (); + #else + return WiFi.localIP (); + #endif } -#ifdef ESP32 -void onWifiEvent (system_event_id_t event, system_event_info_t info) { -#else -void onWifiEvent (WiFiEvent_t event) { -#endif - Serial.printf ("[WiFi-event] event: %d\n", event); +#if (!USE_ETHERNET) + #ifdef ESP32 + void onWifiEvent (system_event_id_t event, system_event_info_t info) { + #else + void onWifiEvent (WiFiEvent_t event) { + #endif + Serial.printf ("[WiFi-event] event: %d\n", event); + + switch (event) { + #ifdef ESP32 + case SYSTEM_EVENT_STA_CONNECTED: + Serial.printf ("Connected to %s. Asking for IP address.\r\n", info.connected.ssid); + break; + case SYSTEM_EVENT_STA_GOT_IP: + Serial.printf ("Got IP: %s\r\n", IPAddress (info.got_ip.ip_info.ip.addr).toString ().c_str ()); + Serial.printf ("Connected: %s\r\n", WiFi.status () == WL_CONNECTED ? "yes" : "no"); + digitalWrite (ONBOARDLED, LOW); // Turn on LED + conFirstConnected = true; + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + Serial.printf ("Disconnected from SSID: %s\n", info.disconnected.ssid); + Serial.printf ("Reason: %d\n", info.disconnected.reason); + digitalWrite (ONBOARDLED, HIGH); // Turn off LED + //NTP.stop(); // NTP sync can be disabled to avoid sync errors + WiFi.reconnect (); + break; + #else + case WIFI_EVENT_STAMODE_CONNECTED: + Serial.printf ("Connected to %s. Asking for IP address.\r\n", WiFi.BSSIDstr().c_str()); + break; + case WIFI_EVENT_STAMODE_GOT_IP: + Serial.printf ("Got IP: %s\r\n", WiFi.localIP().toString().c_str ()); + Serial.printf ("Connected: %s\r\n", WiFi.status () == WL_CONNECTED ? "yes" : "no"); + digitalWrite (ONBOARDLED, LOW); // Turn on LED + conFirstConnected = true; + break; + case WIFI_EVENT_STAMODE_DISCONNECTED: + Serial.printf ("Disconnected from SSID: %s\n", WiFi.BSSIDstr ().c_str ()); + //Serial.printf ("Reason: %d\n", info.disconnected.reason); + digitalWrite (ONBOARDLED, HIGH); // Turn off LED + //NTP.stop(); // NTP sync can be disabled to avoid sync errors + WiFi.reconnect (); + break; + #endif + default: + break; + } + } - switch (event) { -#ifdef ESP32 - case SYSTEM_EVENT_STA_CONNECTED: - Serial.printf ("Connected to %s. Asking for IP address.\r\n", info.connected.ssid); - break; - case SYSTEM_EVENT_STA_GOT_IP: - Serial.printf ("Got IP: %s\r\n", IPAddress (info.got_ip.ip_info.ip.addr).toString ().c_str ()); - Serial.printf ("Connected: %s\r\n", WiFi.status () == WL_CONNECTED ? "yes" : "no"); - digitalWrite (ONBOARDLED, LOW); // Turn on LED - wifiFirstConnected = true; - break; - case SYSTEM_EVENT_STA_DISCONNECTED: - Serial.printf ("Disconnected from SSID: %s\n", info.disconnected.ssid); - Serial.printf ("Reason: %d\n", info.disconnected.reason); - digitalWrite (ONBOARDLED, HIGH); // Turn off LED - //NTP.stop(); // NTP sync can be disabled to avoid sync errors - WiFi.reconnect (); - break; -#else - case WIFI_EVENT_STAMODE_CONNECTED: - Serial.printf ("Connected to %s. Asking for IP address.\r\n", WiFi.BSSIDstr().c_str()); - break; - case WIFI_EVENT_STAMODE_GOT_IP: - Serial.printf ("Got IP: %s\r\n", WiFi.localIP().toString().c_str ()); - Serial.printf ("Connected: %s\r\n", WiFi.status () == WL_CONNECTED ? "yes" : "no"); - digitalWrite (ONBOARDLED, LOW); // Turn on LED - wifiFirstConnected = true; - break; - case WIFI_EVENT_STAMODE_DISCONNECTED: - Serial.printf ("Disconnected from SSID: %s\n", WiFi.BSSIDstr ().c_str ()); - //Serial.printf ("Reason: %d\n", info.disconnected.reason); - digitalWrite (ONBOARDLED, HIGH); // Turn off LED - //NTP.stop(); // NTP sync can be disabled to avoid sync errors - WiFi.reconnect (); - break; -#endif - default: - break; - } -} +#endif //!USE_ETHERNET void processSyncEvent (NTPEvent_t ntpEvent) { switch (ntpEvent.event) { @@ -103,9 +146,29 @@ void processSyncEvent (NTPEvent_t ntpEvent) { void setup() { Serial.begin (115200); - Serial.println (); - WiFi.mode (WIFI_STA); - WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); + Serial.println ("\r\n"); + + #if (USE_ETHERNET) + SPI.begin(); + + eth.setDefault(); // use ethernet for default route + + #if (USE_STATIC) + eth.config(apIP, gwIP, snIP, dnIP1, dnIP2); + #endif + + eth.begin(); + + #else + WiFi.mode (WIFI_STA); + + #if (USE_STATIC) + WiFi.config(apIP, gwIP, snIP, dnIP1, dnIP2); + #endif + + WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); + + #endif //USE_ETHERNET pinMode (ONBOARDLED, OUTPUT); // Onboard LED digitalWrite (ONBOARDLED, HIGH); // Switch off LED @@ -114,15 +177,21 @@ void setup() { ntpEvent = event; syncEventTriggered = true; }); - WiFi.onEvent (onWifiEvent); + + #if (USE_ETHERNET) + conLastStatus = !eth.connected (); + + #else + WiFi.onEvent (onWifiEvent); + #endif } void loop() { static int i = 0; static int last = 0; - if (wifiFirstConnected) { - wifiFirstConnected = false; + if (conFirstConnected) { + conFirstConnected = false; NTP.setTimeZone (TZ_Europe_Madrid); NTP.setInterval (600); NTP.setNTPTimeout (NTP_TIMEOUT); @@ -140,8 +209,49 @@ void loop() { last = millis (); Serial.print (i); Serial.print (" "); Serial.print (NTP.getTimeDateStringUs ()); Serial.print (" "); - Serial.print ("WiFi is "); - Serial.print (WiFi.isConnected () ? "connected" : "not connected"); Serial.print (". "); + + #if (USE_ETHERNET) + if(conLastStatus != eth.connected ()) + { + conLastStatus = eth.connected (); + + if(conLastStatus) + { + Serial.printf ("\r\nGot IP: %s\r\n", eth.localIP().toString().c_str ()); + + #if (USE_STATIC) + Serial.println ("Ethernet is connected [STATIC]"); + #else + Serial.println ("Ethernet is connected [DHCP]"); + #endif + + digitalWrite (ONBOARDLED, LOW); // Turn on LED + conFirstConnected = true; + } + else + { + #if (USE_STATIC) + Serial.println ("Ethernet is not connected [STATIC]"); + #else + Serial.println ("Ethernet is not connected [DHCP]"); + #endif + + digitalWrite (ONBOARDLED, HIGH); // Turn off LED + } + } + + #else + Serial.print ("WiFi is "); + Serial.print (WiFi.isConnected () ? "connected " : "not connected "); + + #if (USE_STATIC) + Serial.println ("[STATIC]"); + #else + Serial.println ("[DHCP]"); + #endif + + #endif //USE_ETHERNET + Serial.print ("Uptime: "); Serial.print (NTP.getUptimeString ()); Serial.print (" since "); Serial.println (NTP.getTimeDateString (NTP.getFirstSyncUs ())); From 3cc73dca852cf84cd08a85d2c8773e4a6c352c8b Mon Sep 17 00:00:00 2001 From: Shahram Date: Thu, 23 Dec 2021 17:53:15 +0330 Subject: [PATCH 07/14] Update basicExample.ino --- examples/basicExample/basicExample.ino | 58 +++++++++++++++++++------- 1 file changed, 43 insertions(+), 15 deletions(-) diff --git a/examples/basicExample/basicExample.ino b/examples/basicExample/basicExample.ino index 0559fef..1b33933 100644 --- a/examples/basicExample/basicExample.ino +++ b/examples/basicExample/basicExample.ino @@ -1,27 +1,40 @@ #include //#include "WifiConfig.h" - -#define USE_ETHERNET true /* false: WiFi or true: lwIP_Etherner */ +#define USE_ETHERNET false /* false: WiFi or true: lwIP_Etherner */ +#define USE_STATIC false /* false: DHCP or true: STATIC */ #include + #ifdef ESP32 -#include -#else -#include + #include -#if (USE_ETHERNET) - #include - #include + #undef USE_ETHERNET + #define USE_ETHERNET false +#else + #include - #define ETH_SS_PIN 4 - ENC28J60lwIP eth(ETH_SS_PIN); -#endif -#endif + #if (USE_ETHERNET) + #include + #include + + #define ETH_SS_PIN 4 + ENC28J60lwIP eth(ETH_SS_PIN); + #endif +#endif //ESP32 #ifndef WIFI_CONFIG_H -#define YOUR_WIFI_SSID "YOUR_WIFI_SSID" -#define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD" + #define YOUR_WIFI_SSID "YOUR_WIFI_SSID" + #define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD" + + // YOUR_ROUTER_SETTINGS + #if (USE_STATIC) + IPAddress apIP(192, 168, 1, 10); + IPAddress gwIP(192, 168, 1, 1); + IPAddress snIP(255, 255, 255, 0); + IPAddress dnIP1(192, 168, 1, 1); + IPAddress dnIP2( 8, 8, 8, 8); + #endif #endif // !WIFI_CONFIG_H #define SHOW_TIME_PERIOD 1000 @@ -34,6 +47,7 @@ bool connectionStatus() { return WiFi.isConnected (); #endif } + bool connectionReconnect() { #if (USE_ETHERNET) return true; @@ -41,6 +55,7 @@ bool connectionReconnect() { return WiFi.reconnect (); #endif } + IPAddress getDeviceIP() { #if (USE_ETHERNET) return eth.localIP (); @@ -57,10 +72,23 @@ void setup() { SPI.begin(); eth.setDefault(); // use ethernet for default route + + #if (USE_STATIC) + eth.config(apIP, gwIP, snIP, dnIP1, dnIP2); + #endif + eth.begin(); + #else + WiFi.mode (WIFI_STA); + + #if (USE_STATIC) + WiFi.config(apIP, gwIP, snIP, dnIP1, dnIP2); + #endif + WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); - #endif + + #endif //USE_ETHERNET NTP.setTimeZone (TZ_Etc_UTC); NTP.begin (); From 38f57b08382d575e7722dcb43f612a6d3ef1c3b7 Mon Sep 17 00:00:00 2001 From: Shahram Date: Sun, 26 Dec 2021 13:22:17 +0330 Subject: [PATCH 08/14] Update ESPNtpClient.cpp --- src/ESPNtpClient.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/ESPNtpClient.cpp b/src/ESPNtpClient.cpp index d372780..b906c0a 100644 --- a/src/ESPNtpClient.cpp +++ b/src/ESPNtpClient.cpp @@ -1197,16 +1197,16 @@ extern "C" { bool connectionStatus() __attribute__ ((weak, alias("__connectionStatus"))); bool __connectionStatus() { - //***** + return WiFi.isConnected (); } bool connectionReconnect() __attribute__ ((weak, alias("__connectionReconnect"))); bool __connectionReconnect() { - //***** + return WiFi.reconnect (); } IPAddress getDeviceIP() __attribute__ ((weak, alias("__getDeviceIP"))); IPAddress __getDeviceIP() { - //***** + return WiFi.localIP (); } } From ad0ac6cdb16c77389d4fe3e813c14a9c8a5a2b8f Mon Sep 17 00:00:00 2001 From: Shahram Date: Sun, 26 Dec 2021 13:26:27 +0330 Subject: [PATCH 09/14] Update advancedExample.ino --- examples/advancedExample/advancedExample.ino | 30 +++++++------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/examples/advancedExample/advancedExample.ino b/examples/advancedExample/advancedExample.ino index 9074725..c7a3806 100644 --- a/examples/advancedExample/advancedExample.ino +++ b/examples/advancedExample/advancedExample.ino @@ -56,29 +56,19 @@ double offset; double timedelay; // weak functions to get connection status, reconnect and IP address of device -bool connectionStatus() { - #if (USE_ETHERNET) +#if (USE_ETHERNET) + bool connectionStatus() { return eth.connected (); - #else - return WiFi.isConnected (); - #endif -} - -bool connectionReconnect() { - #if (USE_ETHERNET) + } + + bool connectionReconnect() { return true; - #else - return WiFi.reconnect (); - #endif -} - -IPAddress getDeviceIP() { - #if (USE_ETHERNET) + } + + IPAddress getDeviceIP() { return eth.localIP (); - #else - return WiFi.localIP (); - #endif -} + } +#endif //USE_ETHERNET #if (!USE_ETHERNET) #ifdef ESP32 From a66e24e1f8f845ae12424d00d34b5f89df8f5068 Mon Sep 17 00:00:00 2001 From: Shahram Date: Sun, 26 Dec 2021 13:28:25 +0330 Subject: [PATCH 10/14] Update basicExample.ino --- examples/basicExample/basicExample.ino | 30 +++++++++----------------- 1 file changed, 10 insertions(+), 20 deletions(-) diff --git a/examples/basicExample/basicExample.ino b/examples/basicExample/basicExample.ino index 1b33933..e0fdbad 100644 --- a/examples/basicExample/basicExample.ino +++ b/examples/basicExample/basicExample.ino @@ -40,29 +40,19 @@ #define SHOW_TIME_PERIOD 1000 // weak functions to get connection status, reconnect and IP address of device -bool connectionStatus() { - #if (USE_ETHERNET) +#if (USE_ETHERNET) + bool connectionStatus() { return eth.connected (); - #else - return WiFi.isConnected (); - #endif -} - -bool connectionReconnect() { - #if (USE_ETHERNET) + } + + bool connectionReconnect() { return true; - #else - return WiFi.reconnect (); - #endif -} - -IPAddress getDeviceIP() { - #if (USE_ETHERNET) + } + + IPAddress getDeviceIP() { return eth.localIP (); - #else - return WiFi.localIP (); - #endif -} + } +#endif //USE_ETHERNET void setup() { Serial.begin (115200); From 3f8b85dbbebb0e65b4307b1fc193cd2a7ab73124 Mon Sep 17 00:00:00 2001 From: Shahram Date: Sun, 26 Dec 2021 13:29:44 +0330 Subject: [PATCH 11/14] Update ledFlasher.ino --- examples/ledFlasher/ledFlasher.ino | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/examples/ledFlasher/ledFlasher.ino b/examples/ledFlasher/ledFlasher.ino index 75d6b8f..e90f5a5 100644 --- a/examples/ledFlasher/ledFlasher.ino +++ b/examples/ledFlasher/ledFlasher.ino @@ -27,17 +27,6 @@ void processSyncEvent (NTPEvent_t ntpEvent) { Serial.printf ("[NTP-event] %s\n", NTP.ntpEvent2str(ntpEvent)); } -// weak functions to get connection status, reconnect and IP address of device -bool connectionStatus() { - return WiFi.isConnected (); -} -bool connectionReconnect() { - return WiFi.reconnect (); -} -IPAddress getDeviceIP() { - return WiFi.localIP (); -} - void setup () { Serial.begin (115200); Serial.println (); From 19a4a5dd14cfbc6aa10932832df5183e025a9385 Mon Sep 17 00:00:00 2001 From: Shahram Date: Tue, 4 Jan 2022 08:20:23 +0330 Subject: [PATCH 12/14] Update ESPNtpClient.cpp --- src/ESPNtpClient.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/ESPNtpClient.cpp b/src/ESPNtpClient.cpp index b906c0a..aa5b1bd 100644 --- a/src/ESPNtpClient.cpp +++ b/src/ESPNtpClient.cpp @@ -607,8 +607,10 @@ void NTPClient::getTime () { } if (dnsErrors >= 3) { dnsErrors = 0; - DEBUGLOGW ("Reconnecting WiFi/Ethernet"); - connectionReconnect (); + if (manageWifi) { + DEBUGLOGW ("Reconnecting WiFi/Ethernet"); + connectionReconnect (); + } } return; } else { From 2f277401350a7332ff338d9beded44be03ac2d80 Mon Sep 17 00:00:00 2001 From: Shahram Date: Tue, 4 Jan 2022 09:09:55 +0330 Subject: [PATCH 13/14] Update ESPNtpClient.cpp --- src/ESPNtpClient.cpp | 68 +++++++++++++++++++++++++------------------- 1 file changed, 38 insertions(+), 30 deletions(-) diff --git a/src/ESPNtpClient.cpp b/src/ESPNtpClient.cpp index aa5b1bd..5e39f13 100644 --- a/src/ESPNtpClient.cpp +++ b/src/ESPNtpClient.cpp @@ -112,7 +112,7 @@ int32_t flipInt32 (int32_t number) { } //DEBUGLOGV ("Output number %08X", *(int32_t*)output); - int32_t *result = (int32_t*)output; + int32_t* result = (int32_t*)output; return *result; } @@ -154,14 +154,22 @@ char* dumpNTPPacket (char* data, size_t length, char* buffer, int len) { return buffer; } -bool NTPClient::begin (const char* ntpServerName) { +bool NTPClient::begin (const char* ntpServerName, bool manageWifi) { err_t result; - - if (!setNtpServerName (ntpServerName) || !strnlen (ntpServerName, SERVER_NAME_LENGTH)) { - DEBUGLOGE ("Invalid NTP server name"); - return false; + + this->manageWifi = manageWifi; + + if (ntpServerName) { + if (!setNtpServerName (ntpServerName) || !strnlen (ntpServerName, SERVER_NAME_LENGTH)) { + DEBUGLOGE ("Invalid NTP server name"); + return false; + } + DEBUGLOGI ("Got server name"); + } else { + if (!strnlen (this->ntpServerName, SERVER_NAME_LENGTH)) { + setNtpServerName (DEFAULT_NTP_SERVER); + } } - DEBUGLOGI ("Got server name"); if (udp) { DEBUGLOGI ("Remove UDP connection"); @@ -172,7 +180,7 @@ bool NTPClient::begin (const char* ntpServerName) { udp = udp_new (); - if (!udp){ + if (!udp) { DEBUGLOGE ("Failed to create NTP socket"); return false; } @@ -294,8 +302,8 @@ void NTPClient::processPacket (struct pbuf* packet) { } responseTimer.detach (); - - if (!decodeNtpMessage ((uint8_t*)packet->payload, packet->len, &ntpPacket)){ + + if (!decodeNtpMessage ((uint8_t*)packet->payload, packet->len, &ntpPacket)) { DEBUGLOGE ("Null pointer packet"); return; } @@ -326,7 +334,7 @@ void NTPClient::processPacket (struct pbuf* packet) { actualInterval = longInterval; numSyncRetry = 0; DEBUGLOGI ("Offset %0.3f ms is under threshold %ld. Not updating", offsetAve / 1000.0, timeSyncThreshold); - if (wasPartial){ + if (wasPartial) { wasPartial = false; if (onSyncEvent) { NTPEvent_t event; @@ -413,7 +421,7 @@ void NTPClient::processPacket (struct pbuf* packet) { DEBUGLOGI ("Next sync programmed for %d seconds", getLongInterval ()); status = syncd; numSyncRetry = 0; - if (wasPartial){ + if (wasPartial) { offsetApplied = true; } //Serial.printf ("Status: %d wasPartial: %d offsetApplied %d Offset %0.3f\n", status, wasPartial, offsetApplied, ((float)tvOffset.tv_sec + (float)tvOffset.tv_usec / 1000000.0) * 1000); @@ -432,7 +440,7 @@ void NTPClient::processPacket (struct pbuf* packet) { } if (offsetApplied && onSyncEvent) { NTPEvent_t event; - if (status == partialSync){ + if (status == partialSync) { event.event = partlySync; event.info.retrials = numSyncRetry; //event.info.offset = offset; @@ -459,7 +467,7 @@ void NTPClient::s_recvPacket (void* arg, struct udp_pcb* pcb, struct pbuf* p, self->responsePacketValid = true; } -void NTPClient::s_receiverTask (void* arg){ +void NTPClient::s_receiverTask (void* arg) { NTPClient* self = reinterpret_cast(arg); #ifdef ESP32 for (;;) { @@ -521,7 +529,7 @@ void NTPClient::s_getTimeloop (void* arg) { DEBUGLOGI ("Periodic loop. Millis = %d", lastGotTime); if (self->isConnected) { if (connectionStatus ()) { - self->getTime (); + self->getTime (); } else { DEBUGLOGE ("DISCONNECTED"); if (self->udp) { @@ -591,7 +599,7 @@ void NTPClient::s_getTimeloop (void* arg) { void NTPClient::getTime () { err_t result; - static uint dnsErrors = 0; + static unsigned int dnsErrors = 0; result = WiFi.hostByName (getNtpServerName (), ntpServerIPAddress); if (!result) { @@ -603,21 +611,21 @@ void NTPClient::getTime () { event.info.serverAddress = ntpServerIPAddress; event.info.port = DEFAULT_NTP_PORT; - onSyncEvent (event); + onSyncEvent (event); } if (dnsErrors >= 3) { dnsErrors = 0; if (manageWifi) { - DEBUGLOGW ("Reconnecting WiFi/Ethernet"); - connectionReconnect (); + DEBUGLOGW ("Reconnecting WiFi"); + connectionReconnect (); } } return; } else { - DEBUGLOGI ("NTP server address resolved to %s", ntpServerIPAddress.toString ().c_str ()); + DEBUGLOGI ("NTP server address %s resolved to %s", ntpServerName, ntpServerIPAddress.toString ().c_str ()); } dnsErrors = 0; - if (ntpServerIPAddress == IPAddress(INADDR_NONE)) { + if (ntpServerIPAddress == IPAddress (INADDR_NONE)) { DEBUGLOGE ("IP address unset. Aborting"); actualInterval = ntpTimeout + 500; DEBUGLOGI ("Set interval to = %d", actualInterval); @@ -698,7 +706,7 @@ boolean NTPClient::sendNTPpacket () { pbuf* buffer; NTPUndecodedPacket_t packet; buffer = pbuf_alloc (PBUF_TRANSPORT, sizeof (NTPUndecodedPacket_t), PBUF_RAM); - if (!buffer){ + if (!buffer) { DEBUGLOGE ("Cannot allocate UDP packet buffer"); return false; } @@ -839,10 +847,10 @@ bool NTPClient::setInterval (int shortInterval, int longInterval) { DEBUGLOGI ("Interval set to = %d", actualInterval); DEBUGLOGI ("Short sync interval set to %d s", shortInterval); DEBUGLOGI ("Long sync interval set to %d s", longInterval); -return true; + return true; } else { DEBUGLOGW ("Too low interval values"); - return false; + return false; } } @@ -909,10 +917,10 @@ NTPPacket_t* NTPClient::decodeNtpMessage (uint8_t* messageBuffer, size_t length, decPacket->peerStratum = recPacket.peerStratum; DEBUGLOGD ("Peer Stratum = %u", decPacket->peerStratum); - decPacket->pollingInterval = pow(2, recPacket.pollingInterval); + decPacket->pollingInterval = pow (2, recPacket.pollingInterval); DEBUGLOGD ("Polling Interval = %u", decPacket->pollingInterval); - decPacket->clockPrecission = pow(2,recPacket.clockPrecission); + decPacket->clockPrecission = pow (2, recPacket.clockPrecission); DEBUGLOGD ("Clock Precission = %0.3f us", decPacket->clockPrecission * 1000000); int16_t ts16_s = flipInt16 (recPacket.rootDelay.secondsOffset); @@ -998,7 +1006,7 @@ NTPPacket_t* NTPClient::decodeNtpMessage (uint8_t* messageBuffer, size_t length, bool NTPClient::checkNTPresponse (NTPPacket_t* ntpPacket, int64_t offsetUs) { //dumpNtpPacketInfo (ntpPacket); - if (ntpPacket->flags.li!=0){ + if (ntpPacket->flags.li != 0) { DEBUGLOGE ("Leap indicator error: %d", ntpPacket->flags.li); return false; } @@ -1028,10 +1036,10 @@ bool NTPClient::checkNTPresponse (NTPPacket_t* ntpPacket, int64_t offsetUs) { //Serial.printf ("Dispersion: %0.6f s\n", ntpPacket->dispersion); //Serial.printf ("Offset: %0.6f s\n", offsetUs / 1000000.0); - if (ntpPacket->dispersion > abs(offsetUs / 1000000.0) || ntpPacket->dispersion == 0.0) { + if (ntpPacket->dispersion > abs (offsetUs / 1000000.0) || ntpPacket->dispersion == 0.0) { DEBUGLOGE ("Dispersion error: %0.3f ms > Offset: %0.3f ms", ntpPacket->dispersion * 1000.0, (float)(offsetUs / 1000.0)); return false; - } + } } return true; @@ -1095,7 +1103,7 @@ bool NTPClient::adjustOffset (timeval* offset) { // timersub (¤ttime, &_offset, &newtime); // } - if (settimeofday (&newtime, NULL)) { // hard adjustment + if (settimeofday (&newtime, (timezone*)NULL)) { // hard adjustment return false; } //Serial.printf ("millis() offset 1: %lld\n", currenttime_us / 1000 - millis ()); From 95f42f04567bbcf92e4549e26c37b3c376aa6dba Mon Sep 17 00:00:00 2001 From: Shahram Date: Tue, 4 Jan 2022 09:16:36 +0330 Subject: [PATCH 14/14] Update ESPNtpClient.h --- src/ESPNtpClient.h | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/src/ESPNtpClient.h b/src/ESPNtpClient.h index 6e749c3..ff9e088 100644 --- a/src/ESPNtpClient.h +++ b/src/ESPNtpClient.h @@ -1,7 +1,7 @@ /** * @file ESPNtpClient.h - * @version 0.2.5 - * @date 16/03/2021 + * @version 0.2.6 + * @date 29/12/2021 * @author German Martin * @brief Library to get system sync from a NTP server with microseconds accuracy in ESP8266 and ESP32 */ @@ -16,8 +16,8 @@ #endif #include -using namespace std; -using namespace placeholders; +//using namespace std; +//using namespace placeholders; extern "C" { #include "lwip/init.h" @@ -261,16 +261,17 @@ class NTPClient { onSyncEvent_t onSyncEvent; ///< @brief Event handler callback uint16_t ntpTimeout = DEFAULT_NTP_TIMEOUT; ///< @brief Response timeout for NTP requests long minSyncAccuracyUs = DEFAULT_MIN_SYNC_ACCURACY_US; ///< @brief DEfault minimum offset value to consider a good sync - uint maxNumSyncRetry = DEFAULT_MAX_RESYNC_RETRY; ///< @brief Number of resync repetitions if minimum accuracy has not been reached - uint numSyncRetry; ///< @brief Current resync repetition - uint maxDispersionErrors = DEFAULT_MAX_RESYNC_RETRY; ///< @brief Number of resync repetitions if server has a dispersion value bigger than offset absolute value - uint numDispersionErrors; + unsigned int maxNumSyncRetry = DEFAULT_MAX_RESYNC_RETRY; ///< @brief Number of resync repetitions if minimum accuracy has not been reached + unsigned int numSyncRetry; ///< @brief Current resync repetition + unsigned int maxDispersionErrors = DEFAULT_MAX_RESYNC_RETRY; ///< @brief Number of resync repetitions if server has a dispersion value bigger than offset absolute value + unsigned int numDispersionErrors; long timeSyncThreshold = DEFAULT_TIME_SYNC_THRESHOLD; ///< @brief If calculated offset is below this threshold it will not be applied. // This is to avoid continious innecesary glitches in clock - uint numTimeouts = 0; ///< @brief After this number of timeout responses ntp sync time is increased + unsigned int numTimeouts = 0; ///< @brief After this number of timeout responses ntp sync time is increased NTPStatus_t status = unsyncd; ///< @brief Sync status char ntpServerName[SERVER_NAME_LENGTH]; ///< @brief of NTP server on Internet or LAN IPAddress ntpServerIPAddress; ///< @brief IP address of NTP server on Internet or LAN + bool manageWifi = true; ///< @brief Enables this library to manage wifi reconnection. True by default public: #ifdef ESP32 //bool terminateTasks = false; @@ -290,8 +291,8 @@ class NTPClient { int64_t offsetSum; ///< @brief Sum of offsets for average calculation int64_t offsetAve; ///< @brief Average calculated value - uint round = 0; ///< @brief Number of offset values added during last sync - uint numAveRounds = DEFAULT_NUM_OFFSET_AVE_ROUNDS; ///< @brief Number of request to be done to calculate average. + unsigned int round = 0; ///< @brief Number of offset values added during last sync + unsigned int numAveRounds = DEFAULT_NUM_OFFSET_AVE_ROUNDS; ///< @brief Number of request to be done to calculate average. pbuf* lastNtpResponsePacket; ///< @brief Last response packet to be processed by receiver task bool responsePacketValid = false; ///< @brief Is `lastNtpResponsePacket` already processed? @@ -427,9 +428,10 @@ class NTPClient { /** * @brief Starts time synchronization * @param ntpServerName NTP server name as String + * @param manageWifi `true` if WiFi should be managed by library * @return `true` if everything went ok */ - bool begin (const char* ntpServerName = DEFAULT_NTP_SERVER); + bool begin (const char* ntpServerName = NULL, bool manageWifi = true); /** * @brief Sets NTP server name @@ -562,7 +564,7 @@ class NTPClient { * @return String built from given time */ char* getTimeStr (timeval moment) { - tm* local_tm = localtime ((time_t*)&moment.tv_usec); + tm* local_tm = localtime (&moment.tv_sec); size_t index = strftime (strBuffer, sizeof (strBuffer), "%H:%M:%S", local_tm); snprintf (strBuffer + index, sizeof (strBuffer) - index, ".%06ld", moment.tv_usec); return strBuffer; @@ -767,7 +769,7 @@ class NTPClient { * @brief Gets the number of sync attempts to calculate average offset * @return Number of average rounds 1.. MAX_OFFSET_AVERAGE_ROUNDS */ - uint getnumAveRounds () { + unsigned int getnumAveRounds () { return numAveRounds; }