-
Notifications
You must be signed in to change notification settings - Fork 3
/
Time.ino
388 lines (358 loc) · 12.5 KB
/
Time.ino
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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
Messung Dauer in Millisekunden einer Ausführung
//vor Beginn einfügen:
unsigned long start = millis();
//nach Ende einfügen
unsigned long dauer = millis() - start;
Serial.print(F("Dauer: "));
Serial.print(dauer);
Serial.println(F(" mS"));
Messung Dauer in Mikrosekunden einer Ausführung
//vor Beginn einfügen:
unsigned long start = micros();
//nach Ende einfügen
unsigned long dauer = micros() - start;
Serial.print(F("Dauer: "));
Serial.print(dauer);
Serial.println(F(" µS"));
*/
// Messung Dauer in Millisekunden einer Ausführung
//unsigned long startOperation = millis(); // benötigte Rechenzeit für Operation ermitteln (vor Beginn einfügen)
//TimeOfOperation(startOperation); // benötigte Rechenzeit für Operation (nach Ende einfügen)
//#if DEBUG_OUTPUT_SERIAL
//void TimeOfOperation(unsigned long startOperation) {
// String logText = F("Time for operation: ");
// logText += millis() - startOperation;
// logText += F(" mSec");
// Serial.println(logText);
// appendLogFile(logText);
//}
//#endif
void DS1307_setTime() {
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write((byte)0); // start at location 0
Wire.write(bin2bcd(second()));
Wire.write(bin2bcd(minute()));
Wire.write(bin2bcd(hour()));
Wire.write(weekday());
Wire.write(bin2bcd(day()));
Wire.write(bin2bcd(month()));
Wire.write(bin2bcd(year() - 2000));
Wire.endTransmission();
}
void DS1307_getTime() { // get date and time from DS1307
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(DS1307_ADDRESS, 7);
uint8_t se = bcd2bin(Wire.read() & 0x7F); // Bit 7 (CH) auf 0 setzen
uint8_t mi = bcd2bin(Wire.read());
uint8_t ho = bcd2bin(Wire.read());
Wire.read(); // weekday
uint8_t da = bcd2bin(Wire.read());
uint8_t mo = bcd2bin(Wire.read());
uint16_t ye = bcd2bin(Wire.read()) + 2000;
setTime(ho, mi, se, da, mo, ye);
}
uint8_t DS1307_isrunning(void) {
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(DS1307_ADDRESS, 1);
uint8_t ss = Wire.read();
return !(ss >> 7);
}
long DS1307_read_long(byte address) {
//Read the 4 bytes from the DS1307 memory.
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(address);
Wire.endTransmission();
Wire.requestFrom(DS1307_ADDRESS, 4);
long byte1 = Wire.read();
long byte2 = Wire.read();
long byte3 = Wire.read();
long byte4 = Wire.read();
//Return the recomposed long by using bitshift.
return (byte4 & 0xFF) + ((byte3 << 8) & 0xFFFF) + ((byte2 << 16) & 0xFFFFFF) + ((byte1 << 24) & 0xFFFFFFFF);
}
void DS1307_write_long(byte address, long value) {
#if defined DEBUG_OUTPUT_SERIAL_DS1307
Serial.print(F("DS1307 write long at address: "));
Serial.print(address);
Serial.print(F(" - "));
Serial.println(value);
#endif
//Decomposition from a long to 4 bytes by using bitshift.
//Byte1 = Most significant -> Byte4 = Least significant byte
byte byte1 = ((value >> 24) & 0xFF);
byte byte2 = ((value >> 16) & 0xFF);
byte byte3 = ((value >> 8) & 0xFF);
byte byte4 = (value & 0xFF);
//Write the 4 bytes into the DS1307 memory.
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(address); // register address
Wire.write(byte1);
Wire.write(byte2);
Wire.write(byte3);
Wire.write(byte4);
Wire.endTransmission();
}
#if defined DEBUG_OUTPUT_SERIAL_DS1307
void DS1307_read_table() {
SerialPrintLine(); // Trennlinie seriell ausgeben
Serial.println(F("DS1307 read all bytes"));
int bytesPerRow = 16;
int i = 0;
int j = 0;
byte b = 0;
char buf[10];
Serial.print(F("Addr. "));
for (i = 0; i < bytesPerRow; i++) {
sprintf(buf, "%02X ", i);
Serial.print(buf);
}
Serial.println();
SerialPrintLine(); // Trennlinie seriell ausgeben
Wire.beginTransmission(DS1307_ADDRESS);
Wire.write(0x00); // Address
Wire.endTransmission();
for (i = 0; i < 64; i++) {
if (j == 0) {
sprintf(buf, "%04X: ", i);
Serial.print(buf);
}
//The Wire library has a buffer of 32 bytes!!!
Wire.requestFrom(DS1307_ADDRESS, 1); // maximal 32 Byte !!!
if (Wire.available()) {
b = Wire.read();
};
sprintf(buf, "%02X ", b);
j++;
if (j == bytesPerRow) {
j = 0;
Serial.println(buf);
} else Serial.print(buf);
}
SerialPrintLine(); // Trennlinie seriell ausgeben
}
#endif
void DS1307_clear_ram() {
#if defined DEBUG_OUTPUT_SERIAL_DS1307
Serial.println(F("DS1307 clear RAM"));
#endif
for (int x = 8; x < 64; x++) {
//The Wire library has a buffer of 32 bytes!!!
Wire.beginTransmission (DS1307_ADDRESS);
Wire.write(x); // Address
Wire.write (0xFF);
Wire.endTransmission ();
}
// scheibt maximal 32 Byte
// Wire.beginTransmission(DS1307_ADDRESS);
// Wire.write(0x08);
// for (uint8_t pos = 0; pos < 56; ++pos) {
// Wire.write(0x02);
// delay(1);
// }
// Wire.endTransmission();
}
////////////////////////////////////////////////////////////////////////////////
// utility code, some of this could be exposed in the DateTime API if needed
uint8_t bcd2bin (uint8_t val) {
return val - 6 * (val >> 4);
}
uint8_t bin2bcd (uint8_t val) {
return val + 6 * (val / 10);
}
/********************************************************************************************\
Time stuff
\*********************************************************************************************/
//void convcompileDate(char const *cdate, char *buff) {
// int vmonth, vday, vyear;
// static const char month_names[] = "JanFebMarAprMayJunJulAugSepOctNovDec";
// sscanf(cdate, "%s %d %d", buff, &vday, &vyear);
// vmonth = (strstr(month_names, buff)-month_names)/3+1;
// sprintf(buff, "%d%02d%02dt", vyear, vmonth, vday);
//}
// return Uptime String from Timestamp (t is time in seconds)
String UpTimeToString(unsigned long t) {
char str[11];
if (t < 86400) {
sprintf(str, "%02d:%02d:%02d", hour(t), minute(t), second(t));
} else if (t < 172800) {
int d = t / 86400;
sprintf(str, "%d Tag", d);
} else {
int d = t / 86400;
sprintf(str, "%d Tage", d);
}
return str;
}
// return Time String from Timestamp (t is time in seconds)
String TimeToString(unsigned long t) {
char str[9];
sprintf(str, "%02d:%02d:%02d", hour(t), minute(t), second(t));
return str;
}
// return Time String from Timestamp (t is time in seconds)
String TimeToStringHM(unsigned long t) {
char str[6];
sprintf(str, "%02d:%02d", hour(t), minute(t));
return str;
}
// return Date String from Timestamp (t is time in seconds)
String DateToString(unsigned long t) {
char str[11];
sprintf(str, "%02d.%02d.%04d", day(t), month(t), year(t));
return str;
}
// return Date and Time String from Timestamp (t is time in seconds)
String DateTimeToString(unsigned long t) {
char str[20];
sprintf(str, "%02d.%02d.%04d %02d:%02d:%02d", day(t), month(t), year(t), hour(t), minute(t), second(t));
return str;
}
// return Anzahl Tage im Monat
int LastDayOfMonth (int monat, int jahr) {
int daysInMonth[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// Check if it is a leap year, this is confusing business
// See: https://support.microsoft.com/en-us/kb/214019
if (jahr % 4 == 0) {
if (jahr % 100 != 0) {
daysInMonth[2] = 29;
}
else {
if (jahr % 400 == 0) {
daysInMonth[2] = 29;
}
}
}
return daysInMonth[monat];
}
void checkDst() {
// check the beginn of daylight saving time
if (weekday() == 1 && month() == 3 && day() >= 25 && day() <= 31 && hour() == 2 && DST == false) {
// setclockto 3 am;
adjustTime(3600); // Adjust system time by adding the adjustment value
numberLogLinesDay = 23;
DST = true;
EEPROM_write_boolean(EEPROM_ADDR_DST, DST); // write boolean at address
DS1307_setTime(); // set date and time to DS1307
appendLogFile(F("Summertime"));
if (SerialOutput == 1) { // serielle Ausgabe eingeschaltet
Serial.println(F("Switch to summertime!"));
}
}
// check the end of daylight saving time
if (weekday() == 1 && month() == 10 && day() >= 25 && day() <= 31 && hour() == 3 && DST == true) {
// setclockto 2 am;
adjustTime(-3600); // Adjust system time by adding the adjustment value
numberLogLinesDay = 25;
DST = false;
EEPROM_write_boolean(EEPROM_ADDR_DST, DST); // write boolean at address
DS1307_setTime(); // set date and time to DS1307
appendLogFile(F("Normaltime"));
if (SerialOutput == 1) { // serielle Ausgabe eingeschaltet
Serial.println(F("It is Normaltime!"));
}
}
}
boolean setTimeNtp() {
unsigned long t = getNtpTime();
if (t != 0) {
if (DST) {
t += 3600; // add one hour if DST active
}
ntpSyncTimeDeviation = now() - t; // Abweichung Uhrzeit
#ifdef DEBUG_OUTPUT_SERIAL_WIFI
Serial.print(F("Systime: "));
Serial.print(now());
Serial.println(F(" Seconds since 01.01.1970"));
#endif
setTime(t); // Set Time
DS1307_setTime(); // set date and time to DS1307
lastSetTime = now();
#ifdef DEBUG_OUTPUT_SERIAL_WIFI
Serial.print(F("NTPtime: "));
Serial.print(t);
Serial.println(F(" Seconds since 01.01.1970"));
Serial.print(F("Deviation: "));
Serial.print(ntpSyncTimeDeviation);
Serial.println(F(" Seconds"));
Serial.print(F("Date: "));
Serial.println(DateToString(now())); // return Date String from Timestamp
Serial.print(F("Day of week: "));
Serial.println(weekday()); // Day of the week, Sunday is day 1
Serial.print(F("Time: "));
Serial.println(TimeToString(now())); // return Time String from Timestamp
#endif
// ntpSyncInterval = 7200; // 2 Stunden
// ntpSyncInterval = 21600; // 6 Stunden
ntpSyncInterval = 86400; // 24 Stunden
String logtext = F("NTP time sync OK (");
logtext += (ntpSyncTimeDeviation);
logtext += F(" Sek)");
appendLogFile(logtext);
return 1;
} else {
ntpSyncInterval = 3600; // 60 Minuten
appendLogFile(F("NTP time sync Error"));
return 0;
}
}
unsigned long getNtpTime() {
WiFiUDP udp;
udp.begin(123);
//String log = F("NTP: NTP sync requested");
//addLog(LOG_LEVEL_DEBUG_MORE, log);
#ifdef DEBUG_OUTPUT_SERIAL_WIFI
Serial.println(F("NTP: sync requested"));
#endif
const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message
byte packetBuffer[NTP_PACKET_SIZE]; //buffer to hold incoming & outgoing packets
IPAddress timeServerIP;
WiFi.hostByName(ntpServerName[ntpServerNr].c_str(), timeServerIP);
char host[20];
sprintf_P(host, PSTR("%u.%u.%u.%u"), timeServerIP[0], timeServerIP[1], timeServerIP[2], timeServerIP[3]);
//log = F("NTP: NTP send to ");
//log += host;
//addLog(LOG_LEVEL_DEBUG_MORE, log);
#ifdef DEBUG_OUTPUT_SERIAL_WIFI
Serial.print(F("NTP: send to "));
Serial.println(host);
#endif
while (udp.parsePacket() > 0) ; // discard any previously received packets
memset(packetBuffer, 0, NTP_PACKET_SIZE);
packetBuffer[0] = 0b11100011; // LI, Version, Mode
packetBuffer[1] = 0; // Stratum, or type of clock
packetBuffer[2] = 6; // Polling Interval
packetBuffer[3] = 0xEC; // Peer Clock Precision
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
udp.beginPacket(timeServerIP, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
uint32_t beginWait = millis();
while (millis() - beginWait < 1500) {
int size = udp.parsePacket();
if (size >= NTP_PACKET_SIZE) {
udp.read(packetBuffer, NTP_PACKET_SIZE); // read packet into the buffer
unsigned long secsSince1900;
// convert four bytes starting at location 40 to a long integer
secsSince1900 = (unsigned long)packetBuffer[40] << 24;
secsSince1900 |= (unsigned long)packetBuffer[41] << 16;
secsSince1900 |= (unsigned long)packetBuffer[42] << 8;
secsSince1900 |= (unsigned long)packetBuffer[43];
#ifdef DEBUG_OUTPUT_SERIAL_WIFI
Serial.println(F("NTP: replied!"));
#endif
return secsSince1900 - 2208988800UL + TimeZone * 3600;
}
}
#ifdef DEBUG_OUTPUT_SERIAL_WIFI
Serial.println(F("NTP: no reply"));
#endif
return 0;
}