arduino-libraries / NTPClient

Connect to a NTP server
533 stars 366 forks source link

Add set function to define the response timeout #189

Open CNSNGopenSourceProjects opened 1 year ago

CNSNGopenSourceProjects commented 1 year ago

I like very much you library, but the 1000ms timeout (on forceUpdate) is too short some time. I would like to make a suggestion to create a function to allow the definition of the response timeout to be used on forceUpdate(). The default value will be 1000ms, but it can be increased if necessary.

Just for reference, I did the following changes on my implementation for Arduino + ESP32: On NTPClient.h:

::::::::::::::::::
    unsigned long _responceTimeout = 1000;  // In ms        // <--FC
::::::::::::::::::
    /**
     * Changes the response timeout. Cannot be lower than 1000ms.
     */
    void setTimeResponse(unsigned long timeResponse);   // <- FC
::::::::::::::::::

On NTPClient.cpp:

::::::::::::::::::
bool NTPClient::forceUpdate() {
::::::::::::::::::  // Wait till data is there or timeout...
  // byte timeout = 0;              // <--FC
  unsigned long timeout = 0;        // <--FC
  int cb = 0;
  do {
    delay ( 10 );
    cb = this->_udp->parsePacket();
    //if (timeout > 100) return false; // timeout after 1000 ms     // <--FC
    if (timeout > this->_responceTimeout) return false; // timeout  // <--FC
    //timeout++;                    // <--FC
    timeout+=10;                    // <--FC
  } while (cb == 0);

  //this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time   // <--FC
  this->_lastUpdate = millis() - timeout + 10; // Account for delay in reading the time         // <--FC
::::::::::::::::::
void NTPClient::setTimeResponse(unsigned long timeResponse) {                   // <- FC
  this->_responceTimeout     = (timeResponse <= 1000) ? 1000 : timeResponse;    // <- FC
}                                   
::::::::::::::::::

Best regards,

Fernando