ropg / ezTime

ezTime — pronounced "Easy Time" — is a very easy to use Arduino time and date library that provides NTP network time lookups, extensive timezone support, formatted time and date strings, user events, millisecond precision and more.
MIT License
327 stars 92 forks source link

Picking up on an event #13

Closed malbrook closed 5 years ago

malbrook commented 5 years ago

I am using EZTime together with a DS3231 RTC so that the clock will operate correctly even if there is no network connection. For instances where a network connection is available is there any way to pick up on the event that occurs when an NTP update completes so I can use the new time setting to correct the RTC if necessary.

I currently have the RTC periodically updating the local clock but would like to correct the RTC if a new time is received from the NTP. Using the DEBUG setting I can see the messages Querying pool.ntp.org ... success (round trip 46 ms) Received time: Friday, 02-Nov-18 20:32:29.319 UTC (internal clock was 1237 ms fast) from the DEBUG but I am not sure how to pick up on the events completion.

Hardware is an ESP WROOM 32 module on a custom PCB with DS3231 chip, using the rtc_by_manuka library for the DS3231.

ropg commented 5 years ago

I guess you could turn off NTP updates with setInterval(0) and then from your own event call queryNTP (which doesn't actually set the time) and then setTime and whatever else you want to do. How about something like this. (Untested...)

[...]

void setup() {
    [...]
    setInterval(0);
    timeSyncEvent();
}

void timeSyncEvent() {
    time_t t;
    unsigned long measured_at;
    if (queryNTP("pool.ntp.org", t, measured_at)) {
        setTime(t, millis() - measured_at);

        // Insert whatever you want to with the received time here

        // run again in an hour
        UTC.setEvent(timeSyncEvent, now() + 3600;
    } else {
        UTC.setEvent(timeSyncEvent, now() + 5;
    }
}

 

I do plan for some future version to make the time updates such that time only goes forward (monotonous time) and corrections are done by adding or subtracting a few milliseconds here or there.

I'll also think about how to support RTC clocks, GPS receivers and the like.

malbrook commented 5 years ago

Thanks for the ideas, excellent software library.