When I connect my ESP8266 based devices (which are in different cities with totally different internet connections) to Losant securely I see it often takes up to 30 seconds using this code.
However, when I have them connect over an insecure channel it happens within a second or so consistently. The secure connection uses this NTP sync routine that is the slow part:
// Set time via NTP, as required for x.509 validation
void setClock() {
configTime(3 * 3600, 0, "pool.ntp.org", "time.nist.gov");
time_t now = time(nullptr);
while (now < 8 * 3600 * 2) { // ***** this takes up to 30 seconds to complete
delay(500);
now = time(nullptr);
}
struct tm timeinfo;
gmtime_r(&now, &timeinfo);
}
Is this expected behavior? Are others experiencing these long secure connection times? Any thoughts on what might be the root cause or fix to speed it up? Any better ways to more quickly sync the clock?
Just to make sure, your devices are successfully connecting with the example code in our repo, but the issue you are facing now is that the clock sync takes up to 30 seconds to complete?
Would you be able to share the exact ESP8266 devices you are experiencing this on?
In the meantime, I’ll take a deeper look to see if I can find something for you.
The difference between connect and connectSecure is that connect is connecting to port 1883 of our MQTT broker, which does not have TLS enabled. connectSecure on the other hand is connecting via port 8883, which does have TLS Enabled.
By default, when connecting securely to our broker, the certificate is verified, which requires the clock to be synced, which is why the NTP Sync would occur in the first place.
I don’t have a good answer for why your specific device is taking some extra time to sync the clock, I apologize. But, one option you do have is to remove the NTP Sync altogether (the setClock function), and add:
wifiClient.setInsecure();
This still uses TLS encryption, but won’t verify the server certificate. Now, this option is less secure than verifying the server certificate but far more secure than no encryption at all.