Git Product home page Git Product logo

ntpclient's Issues

NTP returns erroneous times

Running the NTP Basic example gave me the following values:

07:00:14
07:00:15
07:00:16
07:00:17
07:00:18
07:00:19
07:00:20
07:00:21
07:00:22
06:59:43 <---- What is happening here?
06:59:44
06:59:45
06:59:46
06:59:47
06:59:48
06:59:49
06:59:50
06:59:51
06:59:52
06:59:53
06:59:54
06:59:55
06:59:56
06:59:57
06:59:58
06:59:59
07:00:00
07:00:01

And this is the NTP Basic example I used:

#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

const char *ssid     = "xxxxx";
const char *password = "xxxxx";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);

void setup(){
  Serial.begin(115200);

  WiFi.begin(ssid, password);

  while ( WiFi.status() != WL_CONNECTED ) {
    delay ( 500 );
    Serial.print ( "." );
  }

  timeClient.begin();
}

void loop() {
  timeClient.update();

  Serial.println(timeClient.getFormattedTime());

  delay(1000);
}

NTPC: how to obtain "getHours" in 24 hrs format?

Please let me know if is it possible to get NTC timeClient.getHours() in 24hrs format?
Always getting 12 hr format.

My piece of Arduino code:
Updating RTC chip with NTF time, if current time is 11PM then i got "11" but need "23":
rtc.adjust(DateTime(YEAR, MONTH, DAY, timeClient.getHours(), timeClient.getMinutes(), SE));

BTW I know there is a way to use different approach e.g. epoch time or parse getFormattedTime etc...

getEpochTime should optionally accept timezone offset

use case: applications requires both UTC (for data logging) and time display in localtime (for dashboard or displays). I'm currently using setTimeOffset method for this, which requires 2 calls, before and after getEpochTime. This is acceptable but an getEpochTime offset parameter is preferred. Thanks.

Can you please create a new release

PlatformIO is currently pulling release 3.1.0 - and that does not have the setPoolServerName function. Please create a new release from the master so that the libraries can be updated in PlatformIO

setPoolServerName

hello,
I loaded today the NTPClient by the IDE Arduino

1/ Not colored word :
setTimeOffset
setUpdateInterval
setPoolServerName
Cause : It's missing ! I send the pull request for added in keywords.txt

2/ compilation error :
344: timeClient.setPoolServerName("europe.pool.ntp.org");
'class NTPClient' has no member named 'setPoolServerName'
Cause: setPoolServerName is missing in the cpp file of the library

weird because setPoolServerName is present here in the cpp file !

NTPClient object sets time to 2036-02-07

I'm using the NTPClient in an arduino project.

Yesterday right after 19:40:53 CET the clock jumped to 2036-02-07 07:28:16. The object continued from this date on for about 2 more minutes until 2036-02-07 07:29:38 then it came back again to current time: 2019-12-04 19:42:18.

Does anyone know what might be the issue?

Based on this thread, which is quite related to this problem but with a different library, seems to be an internet connectivity issue. However why does the clock go to the future?

I am wondering if there has been done a patch for NTPClient.h

Additional context

Additional reports

NTPClient.getEpochTime() jumps an hour

I am using the NTPClient on a Wemos D1 Mini (ESP8266). On occasion, my code is detecting that the return from NTPClient.update() then NTPClient.getEpochTime() has jumped an hour.
I have tested with different NTP server pools (time.nist.gov and pool.ntp.org). The occurrence of the jump is not consistent. I've recorded it in teh morning, event, and over night.

I'm looking for debugging suggestions.

I have the following code fragment (with some gorpy calculations removed):

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", 0, 3600000); // interval is 1 hour
...
timeClient.begin();
...
... define and initialize some globals
...
void clock_loop() {
    current_ticks = millis();
    if (next_update < current_ticks) {
        if (timeClient.update()) {
            ... save values from previous iteration as last_epoc, last_hour, last_minute
            cur_epoch = timeClient.getEpochTime();
            ... fetch cur_hour and cur_minute and calc next_update
            Serial.printf("Clock updated: %02d, %02d (%lu  %lu)\n", cur_hour, cur_minute, cur_epoch);
        } else {
            // we will assume one minute has passed
            ... compute cur__hour and cur_minute and calc next_update (to be on a minute boundary)
            Serial.printf("Clock update failed: %02d:%02d\n", cur_hour, cur_minute);
        }
        if (ABS(COMBINE(_hours, _minutes) - COMBINE(last_hour, last_minute)) > 2) {
            // more than two minutes have elapsed. something went wrong
            Serial.printf("Clock jumped: from %02d:%02d to %02d:%02d\n", 
                        last_hour, last_minute, cur_hour, cur_minute);
        }
    }
}

Here is a snippet of my logging:

lock updated: 07:05  (1533798300 )
Clock updated: 07:06  (1533798360 )
Clock updated: 07:07  (1533798420 )
Clock updated: 07:08  (1533798480 )
Clock updated: 07:09  (1533798540 )
Clock updated: 07:10  (1533798600 )
Clock updated: 06:11  (1533795061 )
Clock jumped: from 07:10 to 06:11
Clock updated: 06:11  (1533795119 )
Clock updated: 06:12  (1533795120 )
Clock updated: 06:13  (1533795180 )
Clock updated: 06:14  (1533795240 )
Clock updated: 06:15  (1533795300 )

NTPClient can't connect

Hi

I've used the library with an ESP32 DevKit V1 and with the sample code it didn't work .
I just update the line NTPClient timeClient(ntpUDP) by a more suitable for my case NTPClient timeClient(ntpUDP, "ntp.unice.fr"); from my university or fos-dca-01.av.si-aceralia.

Same result, didn't work

Could you help me ?
Regards

Document getEpochTime()

going through the readme and even the .h file I was at a loss as to why there was no date functionality. Only by going through the .cpp did I find getEpochTime() - arguably the most important function in the library! Having this in the README would help newcomers.

Wrong Time when using static IP

I figured out that when using a static IP, the time returned is wrong.

Running the basic sample: everything is fine.

But when I included the code in a different project (using static IP) is returned wrong data.

To reproduce the issue:

Define following
IPAddress staticIP(192, 168, 20, 11);
IPAddress gateway(192, 168, 20, 1);
IPAddress subnet(255, 255, 255, 0);

and add line

WiFi.config(staticIP, subnet, gateway);

right before the Wifi.begin();

not working with static IP on esp8266

Thanks for this library, unfortunately I cant get it to work when i have a static IP assigned (in the script) to my ESP8266. Is there something I'm doing wrong or an easy way around this (other than setting the IP on the router).
Any help appreciated
thanks

Day of week

I believe that it is importand have a getWeekDay() method for retrieve the day of week.
It is enougth receive simply a number, from 1 to 7, that represent monday-->sunday

random library folder name

When I install this library it is located in the libraries folder in a subfolder named "arduino_[random-six-digit-number]" instead of the name of the library like with other libraries. Anyone know what's going on here?

how to retrieve dayOfWeek, day, month, year?

how to retrieve dayOfWeek, day, month, year?
(either using Unix time string or via extra functions, feat time zone offsets)
an example sketch shipping with this lib would be highly appreciated!

Clock is randomly delayed

Hello,
I do not understand why the clock is randomly delayed, but the interesting thing is that it delay exactly the time set in the variable "updateInterval" or the function "setUpdateInterval ()", I already did several tests but I can not find this bug.

Anyone have any idea where this problem is?

Using an IP address for NTP connections

I've modified NTPClient() to accept an IP address as an alternative to the usual server name. This often speeds up an NTP fetch by avoiding the DNS lookup step.

NTPClient.h:

const char*   _poolServerName = "time.nist.gov"; // Default time server
IPAddress     _poolServerIP;

NTPClient(UDP& udp, int timeOffset);
NTPClient(UDP& udp, IPAddress poolServerIP);
NTPClient(UDP& udp, const char* poolServerName);

NTPClient.cpp:

NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP) {
  this->_udp            = &udp;
  this->_poolServerIP = poolServerIP;
  this->_poolServerName = NULL;
}


  // you can send a packet requesting a timestamp:
  if (this->_poolServerName) this->_udp->beginPacket(this->_poolServerName, 123); // NTP requests are to port 123
    else this->_udp->beginPacket(this->_poolServerIP, 123);
  this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);

NTPClient library - How does timeClient.update() work

Using a ESP8266-12E I've been trying the Network Time Protocol (NTP) but have discover an unexplained issue as follows:

Using say the "Basic" example sketch that comes with the library, I find the time displayed updates even when I shut down my Wi-Fi as follows:

void loop() {
  timeClient.update();
  Serial.println(timeClient.getFormattedTime());
  delay(1000);
}

My expectation is that timeClient.update() should fail but the sketch seems to keep accumulating/updating and displaying time by itself.

I've been unable to find a manual/instructions for library NTPClient.

Assistance / comments welcome.

timeOffset doesn't look correct

I'm in Los Angeles CA, so my time offset is UTC-8 Hrs or 28800 seconds .

Right now the time is 8:20 pm, but with timeoffset = 28800, timeClient.getFormattedTime() gives me 22:28:40.

What am I doing wrong?

Using getFormattedTime() to format a given time

I've adjusted getFormattedTime() to take an (optional) 'secs' argument, so that the same formatting code can be used to format any given time, while still formatting the NTP time if the argument is left out. This is similar to time conversion functions in other languages, and might avoid the need to include a dedicated time/date library in some projects.

NTPClient.h:

/**
 * @return secs argument (or 0 for current time) formatted like `hh:mm:ss`
 */
String getFormattedTime(unsigned long secs = 0);

NTPClient.cpp:

String NTPClient::getFormattedTime(unsigned long secs) {
  unsigned long rawTime = secs ? secs : this->getEpochTime();

Changes for 3.0.0

I just merged #8 which sets the basis for 3.0.0. Are there any other things we need to change for this release. We can change the API as we like because we are doing a major version bump, so getting the API straight is important.

AU (GMT+10)+ : Any offset over 32767 did not work - fix included

Time offset for Australia GMT +10 is 36,000 (plus 10 hours), however the datatype for offset in my library was int. The current code it is a long, and a long has a maximum value of 32,767. If you need a higher offset, ie, in Australia +10, etc, you need to modify the datatype to unsigned long, in the following locations:

NTPClient.h
line 18: unsigned long _timeOffset = 0;
lines 31-44:
NTPClient(UDP& udp, unsigned long timeOffset); NTPClient(UDP& udp, const char* poolServerName); NTPClient(UDP& udp, const char* poolServerName, unsigned long timeOffset); NTPClient(UDP& udp, const char* poolServerName, unsigned long timeOffset, int updateInterval);

line 69: void setTimeOffset(unsigned long timeOffset);

NTPClient.cpp

line 28: NTPClient::NTPClient(UDP& udp, unsigned long timeOffset) {
line 38: NTPClient::NTPClient(UDP& udp, const char* poolServerName, unsigned long timeOffset) {
line 44: NTPClient::NTPClient(UDP& udp, const char* poolServerName, unsigned long timeOffset, int updateInterval) {
line 143: void NTPClient::setTimeOffset(unsigned long timeOffset) {

Just incase you're from Australia and scratching your head like I'd been doing for an hour or so. Enjoy :)

ESP8266 returning wrong hour en minutes values

I'm using the library for setting the time to be used on a clock.
This is a real clock for in the living room, problem happens on different clocks on different locations exactly at the same time ! The value returned is always 19 for the hours() and 29 for the minutes(). It does this about once a day at a random time, but mostly in the evenings. So it must be code related.

Details for the bits that matter for this problem, very straightforward I thought..

#include <NTPClient.h>
#include <WiFiUdp.h>

WiFiUDP ntpUDP;
//First number is timeoffset (1 uur), second is updateinterval (4 uur)
NTPClient timeClient(ntpUDP, "nl.pool.ntp.org", 3600, 14400);

void setup(){
timeClient.begin();
}

Void loop(){
timeClient.update();
}

int minuten = timeClient.getMinutes();
int uur = timeClient.getHours();

Any help in any direction is very appreciated !!

.getEpochTime rollover?

I've been trying to use this library to monitor uptime on my esp projects. Basically, I have an unsigned long (startEpoch) that I populate in startup block. Every 60 seconds thereafter, I populate a local variable (currentEpoch) with timeclient.getEpochTime(). Next I subtract startEpoch from currentEpoch and get uptime in seconds. This works great for about 47 days 17 hours and 2 minutes... roughly. Then I see that currentEpoch jumps backwards to the same epoch of startEpoch. It suggests there is some millis overflow issue given the elapsed time. I have studied my code and cannot see anything in my code that would cause this but I'm amateur at best so I could be wrong. I have included the abridged version below.

I set the sketch to publish currentEpoch, startEpoch as well as strUptime to 3 mqtt topics which I logged. My timestamp log only shows changes and startEpoch didn't change which can be seen by subscribing via mosquitto_sub and it is still broadcasting the may 22 startEpoch:

uptime/state 00:00:10
debug/StartEpoch 1527022364
debug/CurrentEpoch 1527023000
2018-07-11 09:52:36.984  CurrentEpoch changed from 1531317120 to 1531317181
2018-07-11 09:53:36.982  Uptime changed from 49:17:00 to 49:17:01
2018-07-11 09:53:37.482  CurrentEpoch changed from 1531317181 to 1531317241
2018-07-11 09:54:37.482  Uptime changed from 49:17:01 to 49:17:02
2018-07-11 09:54:37.983  CurrentEpoch changed from 1531317241 to 1531317302
2018-07-11 09:55:37.983  Uptime changed from 49:17:02 to 00:00:00
2018-07-11 09:55:38.486  CurrentEpoch changed from 1531317302 to 1527022395
2018-07-11 09:56:38.484  Uptime changed from 00:00:00 to 00:00:01
2018-07-11 09:56:38.986  CurrentEpoch changed from 1527022395 to 1527022455
2018-07-11 09:57:38.986  Uptime changed from 00:00:01 to 00:00:02
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <NTPClient.h>

unsigned long uptimeMillis = 0; //holds millis for uptime processing
unsigned long startEpoch = 0; //holds starting time epoch

WiFiUDP ntpUDP;
WiFiClient espClient;
NTPClient timeClient(ntpUDP, "us.pool.ntp.org");


void setup() {
  timeClient.begin(); //start NTP, update and get start epoch
  timeClient.update();
  startEpoch = timeClient.getEpochTime();  


void loop() {

//BEGIN UPTIME---------------------------------------------------
  if ((unsigned long)(millis() - uptimeMillis) >= 60000 || uptimeMillis ==0)
  {

    unsigned long uptime = 0; //holds differential epoch
    unsigned long currentepoch = timeClient.getEpochTime();  //this is for testing purposes
    String strDays = "00"; //strings for time bits
    String strHours = "00";
    String strMinutes = "00";
    
    uptime = timeClient.getEpochTime() - startEpoch;
  
    int days = uptime / 60 / 60 / 24;
    int hours = (uptime / 60 / 60) % 24;
    int minutes = (uptime / 60) % 60;
  
    if (days < 10) 
    {
      strDays = "0" + String(days);
    } else {
      strDays = String(days);
    }
    if (hours < 10) 
    {
      strHours = "0" + String(hours);
    } else {
      strHours = String(hours);
    }
    if (minutes < 10) 
    {
      strMinutes = "0" + String(minutes);
    } else {
      strMinutes = String(minutes);
    }
    String strUptime = strDays + ":" + strHours + ":" + strMinutes;
    
    uptimeMillis = millis(); //reset count
  }
  //END UPTIME------------------------------------------------------
}

compiler error after version 3_2_0

used:
Arduinoboard MKR WiFi 1010, Windows 10, create.arduino IOT cloud

Here the compiler error:
/home/builder/opt/libraries/latest/ntpclient_3_2_0/NTPClient.h:7:25: error: expected unqualified-id before numeric constant

#define NTP_PACKET_SIZE 48

Also:
inside the examples "basic" and "advanced" it is not mentioned, which libraries to include for MKR-WiFi-1010

NTP client crashes if you pass an ntp server that the dns does not resolve

I am using the library with ESP32 and I found that if you put an incorrect ntp server (I assume it happens even if the connection to the internet is absent) the esp 32 restarts.
What I found is that in NTPClient :: sendNTPPacket () the packet is sent to the ntp server but it is not checked whether this -> _ udp-> beginPacket (this -> _ poolServerName, 123)) was successful.
Even if beginPacket () fails immediately after you try to send the package with the request that causes the reboot.

Since

    // Start building up a packet to send to the remote host specific in host and port
    // Returns 1 if successful, 0 if there was a problem resolving the hostname or port
    virtual int beginPacket(const char *host, uint16_t port) =0;

I'd suggest checking this -> _ udp-> beginPacket (....).

// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
if (this->_udp->beginPacket(this->_poolServerName, 123)) {  //NTP requests are to port 123
    this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
    this->_udp->endPacket();
}

SIM800 GSM

Hello! Please help!
Im using SIM800 GSM via TinyGSMclient library, but no examples of code how use NTPClient in my case. Im search a lot but not found how tu use udp: Reference to an UDP object with TinyGSMclient.h.
Is exist many examples of ethernet or wi-fi but none of GSM.

wrong time occasionally

Hi,
I'm using the library (great job by the way) with an ESP-12 and I'm publishing some data to MQTT server, including time, then shutting down for 2 min's (Deep sleep) then starting again.

sometimes the time returned is 00:00:12 ~(the seconds vary) mostly the time returned is correct.

Is there a minimum time for the server to respond, is the 00:00:12 time returned because the server has not responded in time?

Any thoughts?

Allow selecting time format

Today i needed formatted result only on HHmm, so i modified the get formatted metodhs.
So if you agree it is a good idea create a new constructor whit a new argument passed for select some formatted result:

  • HHmm
  • HHmmss
  • Etc.

Basic example not compile

You ned pass a value on costructor inizialization in the sketch, or if you prefer, you can add an empty constructor to the library

Check if NTP update is successfull by comparing the new time with time at last NTP Update + time gone since then

Hello,
is it possible to add a feature where the new NTP time from the NTP server is checked to be valid by comparing the new time with the old time + time between the updates?
Since normal uC are not very precise maybe by adding a tolerance of x% for the time between the updates?

I sometimes get a single wrong update.

Another possibility would be to compare the result of x UDP requests with each other to be certain, the update is succesfull.

Greetings Michael

Can we have a setEpochTime() method?

Could we have a way of manually setting the internal time stored by NTPClient please? e.g., a setEpochTime(t) to match the existing getEpochTime().

My use case is reading the NTP time over the network no more than once a day, between which the ESP8266 spends much of its time in deep sleep mode, so I'm storing the predicted wake time/date in RTC memory, and I'd like to write that into NTPClient when REASON_DEEP_SLEEP_AWAKE (but not for other reset methods like power on).

Thanks

updateInterval variable type problem between int and unsigned int

The internal _updateInterval is an 'unsigned int' (0-65535), which allows a maximum of 65 seconds between updates when calling 'bool update()'. It is initialized to 60000 (60 seconds) by default.

The constructor of NTPClient() takes it as parameter so a user can modify it, but the parameter is declared as 'int' (32 seconds max interval) instead of 'unsigned int'.

The constructor should be also 'unsigned int' as the internal private variable _updateInterval.

Even more, I suggest to modify them both to unsigned long, to be able to set more than only 65 seconds interval update.

getEpochTime with timeOffset?

Unix time (also known as POSIX time or epoch time) is a system for describing instants in time, defined as the number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, 1 January 1970 - Wikipedia

So, I understand that timeOffset is used to set timezone to get correct "local" time. But method getEpochTime() should return as it's name says - a Unix time in UTC regardless of "local" timezone. So looks like this->_timeOffset should not be added to this->_currentEpoc in NTPClient::getEpochTime()

First NTP time retrive fail

if you decrease the delay in the loop, example at 500ms, the time that is printed is 00.00.00
Only after one minute (the standard resync time) it will be corrected.

Give access to _lastUpdate would let users deal with better accuracy requirements

I'm working on an application that is time sensitive, at least in a relative way.
I don't need exact microsecond precision of the returned time, but I need a more or less reliable way to determine at the millisecond where I'm standing compared to the epoch.

Simply giving access to _lastUpdate does the job I think, as I can now get a string representing a ms epoch that way :

unsigned long seconds = timeClient.getEpochTime();
unsigned long ms = (millis() - timeClient.getLastUpdate()) % 1000;
char ms_char[12];
sprintf(ms_char,"%lu%03lu",seconds,ms);

Now I don't know what the best design is for this library :

  • Propose a getMillisecondString()
  • Simply let use deal with a public getLastUpdate() like I did
  • Deal with 64bit to return a ms epoch as a number...

Malformed NTP request

FYI, the following is perhaps intended to spell "INIT" code but unfortunately without the "0x" prefix some values are unintended decimal representation resulting in the nonsensical ASCII code "1N14".

packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.