NTPClient.cpp 8.57 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
 * The MIT License (MIT)
 * Copyright (c) 2015 by Fabrice Weinberg
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "NTPClient.h"

NTPClient::NTPClient(UDP& udp) {
  this->_udp            = &udp;
}

Eric Duminil's avatar
Eric Duminil committed
28
NTPClient::NTPClient(UDP& udp, long timeOffset) {
29
30
31
32
33
34
35
36
37
  this->_udp            = &udp;
  this->_timeOffset     = timeOffset;
}

NTPClient::NTPClient(UDP& udp, const char* poolServerName) {
  this->_udp            = &udp;
  this->_poolServerName = poolServerName;
}

Eric Duminil's avatar
Eric Duminil committed
38
39
40
41
42
43
44
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP) {
  this->_udp            = &udp;
  this->_poolServerIP   = poolServerIP;
  this->_poolServerName = NULL;
}

NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset) {
45
46
47
48
49
  this->_udp            = &udp;
  this->_timeOffset     = timeOffset;
  this->_poolServerName = poolServerName;
}

Eric Duminil's avatar
Eric Duminil committed
50
51
52
53
54
55
56
57
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset){
  this->_udp            = &udp;
  this->_timeOffset     = timeOffset;
  this->_poolServerIP   = poolServerIP;
  this->_poolServerName = NULL;
}

NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval) {
58
59
60
61
62
63
  this->_udp            = &udp;
  this->_timeOffset     = timeOffset;
  this->_poolServerName = poolServerName;
  this->_updateInterval = updateInterval;
}

Eric Duminil's avatar
Eric Duminil committed
64
65
66
67
68
69
70
71
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset, unsigned long updateInterval) {
  this->_udp            = &udp;
  this->_timeOffset     = timeOffset;
  this->_poolServerIP   = poolServerIP;
  this->_poolServerName = NULL;
  this->_updateInterval = updateInterval;
}

72
73
74
75
void NTPClient::begin() {
  this->begin(NTP_DEFAULT_LOCAL_PORT);
}

Eric Duminil's avatar
Eric Duminil committed
76
void NTPClient::begin(unsigned int port) {
77
78
79
80
81
82
83
84
85
86
87
  this->_port = port;

  this->_udp->begin(this->_port);

  this->_udpSetup = true;
}

bool NTPClient::forceUpdate() {
  #ifdef DEBUG_NTPClient
    Serial.println("Update from NTP Server");
  #endif
Eric Duminil's avatar
Eric Duminil committed
88

89
90
91
  // flush any existing packets
  while(this->_udp->parsePacket() != 0)
    this->_udp->flush();
Eric Duminil's avatar
Eric Duminil committed
92

93
94
95
96
97
98
99
100
101
102
103
104
105
106
  this->sendNTPPacket();

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

  this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time

Eric Duminil's avatar
Eric Duminil committed
107
108
  this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);

109
110
111
112
113
114
115
116
  unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
  unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
  // combine the four bytes (two words) into a long integer
  // this is NTP time (seconds since Jan 1 1900):
  unsigned long secsSince1900 = highWord << 16 | lowWord;

  this->_currentEpoc = secsSince1900 - SEVENZYYEARS;

Eric Duminil's avatar
Eric Duminil committed
117
  return true;  // return true after successful update
118
119
120
121
122
}

bool NTPClient::update() {
  if ((millis() - this->_lastUpdate >= this->_updateInterval)     // Update after _updateInterval
    || this->_lastUpdate == 0) {                                // Update if there was no update yet.
Eric Duminil's avatar
Eric Duminil committed
123
    if (!this->_udpSetup || this->_port != NTP_DEFAULT_LOCAL_PORT) this->begin(this->_port); // setup the UDP client if needed
124
125
    return this->forceUpdate();
  }
Eric Duminil's avatar
Eric Duminil committed
126
127
128
129
130
  return false;   // return false if update does not occur
}

bool NTPClient::isTimeSet() const {
  return (this->_lastUpdate != 0); // returns true if the time has been set, else false
131
132
}

Eric Duminil's avatar
Eric Duminil committed
133
unsigned long NTPClient::getEpochTime() const {
134
  return this->_timeOffset + // User offset
Eric Duminil's avatar
Eric Duminil committed
135
         this->_currentEpoc + // Epoch returned by the NTP server
136
137
138
         ((millis() - this->_lastUpdate) / 1000); // Time since last update
}

Eric Duminil's avatar
Eric Duminil committed
139
int NTPClient::getDay() const {
140
141
  return (((this->getEpochTime()  / 86400L) + 4 ) % 7); //0 is Sunday
}
Eric Duminil's avatar
Eric Duminil committed
142
int NTPClient::getHours() const {
143
144
  return ((this->getEpochTime()  % 86400L) / 3600);
}
Eric Duminil's avatar
Eric Duminil committed
145
int NTPClient::getMinutes() const {
146
147
  return ((this->getEpochTime() % 3600) / 60);
}
Eric Duminil's avatar
Eric Duminil committed
148
int NTPClient::getSeconds() const {
149
150
151
  return (this->getEpochTime() % 60);
}

Eric Duminil's avatar
Eric Duminil committed
152
153
154
155
156
157
158
159
160
161
String NTPClient::getFormattedTime() const {
  unsigned long rawTime = this->getEpochTime();
  unsigned long hours = (rawTime % 86400L) / 3600;
  String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);

  unsigned long minutes = (rawTime % 3600) / 60;
  String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);

  unsigned long seconds = rawTime % 60;
  String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);
162

Eric Duminil's avatar
Eric Duminil committed
163
  return hoursStr + ":" + minuteStr + ":" + secondStr;
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
}

void NTPClient::end() {
  this->_udp->stop();

  this->_udpSetup = false;
}

void NTPClient::setTimeOffset(int timeOffset) {
  this->_timeOffset     = timeOffset;
}

void NTPClient::setUpdateInterval(unsigned long updateInterval) {
  this->_updateInterval = updateInterval;
}

Eric Duminil's avatar
Eric Duminil committed
180
181
182
183
void NTPClient::setPoolServerName(const char* poolServerName) {
    this->_poolServerName = poolServerName;
}

184
185
186
187
188
189
190
191
192
void NTPClient::sendNTPPacket() {
  // set all bytes in the buffer to 0
  memset(this->_packetBuffer, 0, NTP_PACKET_SIZE);
  // Initialize values needed to form NTP request
  this->_packetBuffer[0] = 0b11100011;   // LI, Version, Mode
  this->_packetBuffer[1] = 0;     // Stratum, or type of clock
  this->_packetBuffer[2] = 6;     // Polling Interval
  this->_packetBuffer[3] = 0xEC;  // Peer Clock Precision
  // 8 bytes of zero for Root Delay & Root Dispersion
Eric Duminil's avatar
Eric Duminil committed
193
  this->_packetBuffer[12]  = 49;
194
  this->_packetBuffer[13]  = 0x4E;
Eric Duminil's avatar
Eric Duminil committed
195
196
  this->_packetBuffer[14]  = 49;
  this->_packetBuffer[15]  = 52;
197
198
199

  // all NTP fields have been given values, now
  // you can send a packet requesting a timestamp:
Eric Duminil's avatar
Eric Duminil committed
200
201
202
203
204
  if  (this->_poolServerName) {
    this->_udp->beginPacket(this->_poolServerName, 123);
  } else {
    this->_udp->beginPacket(this->_poolServerIP, 123);
  }
205
206
207
208
  this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
  this->_udp->endPacket();
}

Eric Duminil's avatar
Eric Duminil committed
209
210
211
void NTPClient::setRandomPort(unsigned int minValue, unsigned int maxValue) {
  randomSeed(analogRead(0));
  this->_port = random(minValue, maxValue);
212
}
Eric Duminil's avatar
Eric Duminil committed
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259


/*** Custom code for ampel-firmware ***/
void NTPClient::getFormattedTime(char *formatted_time, unsigned long secs) {
  unsigned long rawTime = secs ? secs : this->getEpochTime();
  unsigned int hours = (rawTime % 86400L) / 3600;
  unsigned int minutes = (rawTime % 3600) / 60;
  unsigned int seconds = rawTime % 60;

  snprintf(formatted_time, 9, "%02d:%02d:%02d", hours, minutes, seconds);
}

#define LEAP_YEAR(Y)     ( (Y>0) && !(Y%4) && ( (Y%100) || !(Y%400) ) )

// Based on https://github.com/PaulStoffregen/Time/blob/master/Time.cpp
void NTPClient::getFormattedDate(char *formatted_date, unsigned long secs) {
  unsigned long rawTime = (secs ? secs : this->getEpochTime()) / 86400L;  // in days
  unsigned long days = 0, year = 1970;
  uint8_t month;
  static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31};

  while((days += (LEAP_YEAR(year) ? 366 : 365)) <= rawTime)
    year++;
  rawTime -= days - (LEAP_YEAR(year) ? 366 : 365); // now it is days in this year, starting at 0
  days=0;
  for (month=0; month<12; month++) {
    uint8_t monthLength;
    if (month==1) { // february
      monthLength = LEAP_YEAR(year) ? 29 : 28;
    } else {
      monthLength = monthDays[month];
    }
    if (rawTime < monthLength) break;
    rawTime -= monthLength;
  }
  month++; // jan is month 1
  rawTime++; // first day is day 1

  char formatted_time[9];
  this->getFormattedTime(formatted_time, secs);
  snprintf(formatted_date, 23, "%4lu-%02d-%02lu %s%+03d", year, month, rawTime, formatted_time, this->_timeOffset / 3600);
}

void NTPClient::setEpochTime(unsigned long secs) {
  this->_currentEpoc = secs;
}
/**************************************************************/