Azure / azure-sdk-for-c

This repository is for active development of the Azure SDK for Embedded C. For consumers of the SDK we recommend visiting our versioned developer docs at https://azure.github.io/azure-sdk-for-c.
MIT License
224 stars 120 forks source link

DEVICE STUCK AS CONNECTING TO SNTP SERVER #2705

Closed Yhaw closed 9 months ago

Yhaw commented 9 months ago

After inserting the keys and the device Id with all necessary information in the IoT hub or Central example for ESP32, once I upload the to esp32 board, it asks to sync the board with an SNTP server but after going through this process for sometime , it gets stuck in a loop.

The log output I get is "SETTING TIME SNTP .........................................................................."

once the board gets started and connects with the wifi, it trys connect to the server and this happens.

I am assuming the problem is the domain to the SNTP servers, they may not be working or so.

define NTP_SERVERS "pool.ntp.org", "time.nist.gov"

issue

But I found a way around! So I decide to use a different sntp server api, do a little changes to the initialize time function and it worked this is the code

this is the new changes

define NTP_SERVERS "http://worldtimeapi.org/api/timezone/Etc/UTC"

static void initializeTime() {

Logger.Info("Setting time using Time API");

HTTPClient http; http.begin(NTP_SERVERS); int httpCode = http.GET();

if (httpCode == HTTP_CODE_OK) { String payload = http.getString();

dateTimeString = payload.substring(payload.indexOf("datetime\":\"") + 11, payload.indexOf("Z"));
struct tm tm;
strptime(dateTimeString.c_str(), "%Y-%m-%dT%H:%M:%S", &tm);

time_t t = mktime(&tm);

if (t != -1)
{
  struct timeval tv;
  tv.tv_sec = t;
  tv.tv_usec = 0;
  settimeofday(&tv, nullptr);
  Serial.println("Time updated successfully.");
}
else
{
  Serial.println("Failed to parse time.");
}

} else { Serial.print("HTTP error code: "); Serial.println(httpCode); }

http.end();

delay(1000); }

And this worked for me.

Screenshot from 2023-12-02 09-29-58

Thank you

ericwolz commented 9 months ago

The ESP32 platform API configTime() will periodically sync the internal clock with the STNP server. Unless you use an external crystal, the, the build in oscillator is not very accurate and will cause a clock drift.

Your implementation would need to be periodically call a STNP server to keep the clock in sync.