PaulStoffregen / Time

Time library for Arduino
http://playground.arduino.cc/code/time
1.25k stars 666 forks source link

Non-blocking SyncProvider function. #129

Closed gfvalvo closed 5 years ago

gfvalvo commented 5 years ago

The proposed changes will allow for low-latency, non-blocking code to be used in the user’s SyncProvider function. The specific application in mind is when the sync is provided via NTP since there's an unknown and variable delay between sending the NTP request and getting a response.

Two optional parameters are added to the setSyncProvider function prototype:

void setSyncProvider(getExternalTime getTimeFunction, bool immedRetry = false, bool wait = false);

immedRetry -- when true, instructs the ‘now()’ function not to update ‘nextSyncTime’ if the user’s SyncProvider function returns ‘0’.

wait -- when, true forces the ‘setSyncProvider()’ to wait for valid synchronization.

The idea is that when immedRetry is as true, now() will continue to call the user’s SyncProvider function until a valid time is returned (assuming the nextSyncTime condition is satisfied). So (when using NTP) the first call to the SyncProvider function will send the UDP request packet and immediately return ‘0’. Because a 0 was returned, each subsequent call to now() will therefore call the SyncProvider function again. In turn, it will do one of three things:

  1. Receive a valid NTP packet, reset itself to send another UDP request packet the next time it is called, and return the time.

  2. Recognize that a packet has not yet been received and immediately return ‘0’.

  3. Time out, reset itself to send another UDP request packet the next time it is called, and return ‘0’.

Only when Case #1 happens will now() update the time for its next sync request to be syncInterval seconds in the future.

To maintain backwards compatibility for existing applications the immedRetry and wait arguments can be omitted from the call to setSyncProvider(). In this case, the library will behave exactly the same as before.

An updated 'TimeNTP_ESP8266WiFi.ino' example is included to demonstrate the new technique.

gfvalvo commented 5 years ago

Cancel this request. Will re-submitt.