ESP8266 NTP Sync Slowing Secure Device Connection

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?

Hi @Michael_Long,

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.

Thank you,
Heath

Hi Heath,

Yes, you are correct. They will connect immediately if insecure. It is just that the 30sec or so clock sync is required before a secure connection.

We are using the Expressif ESP 12-S Microcontroller Module.

Thanks,

Michael

Hi @Michael_Long,

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.

Thank you,
Heath

Hi Heath,

Thanks for the workaround suggestion. That allows a somewhat secure connection without the 30sec clock sync wait. I tried it and it works.

Thank you,

Michael

1 Like