forked from isparkes/ArdunixNix6
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWifiTimeProviderESP8266.ino
869 lines (739 loc) · 24.9 KB
/
WifiTimeProviderESP8266.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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
/*
ESP8266 Webserver for the Arduino Nixie clock
Starts the ESP8266 as an access point and provides a web interface to configure WiFi credentials
Go to http://192.168.4.1 in a web browser connected to this access point to see it
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <Wire.h>
#include <EEPROM.h>
#include <WiFiUdp.h>
#include <time.h>
#define DEBUG_OFF // DEBUG or DEBUG_OFF
#define AP_USE_PASSWORD_OFF // AP_USE_PASSWORD or AP_USE_PASSWORD_OFF
// Access point credentials
const char *ap_ssid = "NixieTimeModule";
#ifdef AP_USE_PASSWORD
const char *ap_password = "thereisnospoon";
#endif
#define blueLedPin 1
boolean blueLedState = true;
long lastMillis = 0;
long lastI2CUpdateTime = -60000;
String timeServerURL = "";
#define I2C_SLAVE_ADDR 0x68
#define I2C_TIME_UPDATE 0x00
ESP8266WebServer server(80);
// ----------------------------------------------------------------------------------------------------
// ---------------------------------------------- Set up --------------------------------------------
// ----------------------------------------------------------------------------------------------------
void setup()
{
#ifdef DEBUG
Serial.begin(115200);
Serial.println();
Serial.println("Configuring access point...");
#else
pinMode(blueLedPin, OUTPUT);
#endif
// Set that we are using all the 512 bytes of EEPROM
EEPROM.begin(512);
delay(10);
// You can add the password parameter if you want the AP to be password protected
#ifdef AP_USE_PASSWORD
Wifi.softAP(ssid, password);
#else
WiFi.softAP(ap_ssid);
#endif
// read eeprom for ssid and pass
String esid = getSSIDFromEEPROM();
String epass = getPasswordFromEEPROM();
timeServerURL = getTimeServerURLFromEEPROM();
// Connect
int connectResult = connectToWLAN(esid.c_str(), epass.c_str());
if (connectResult != 0) {
clearCredentialsFromEEPROM();
}
IPAddress apIP = WiFi.softAPIP();
IPAddress myIP = WiFi.localIP();
#ifdef DEBUG
Serial.print("AP IP address: ");
Serial.println(apIP);
Serial.print("IP address: ");
Serial.println(myIP);
#endif
Wire.begin(0, 2); // SDA = 0, SCL = 2
#ifdef DEBUG
Serial.println("I2C master started");
#endif
/* Set page handler functions */
server.on("/", rootPageHandler);
server.on("/wlan_config", wlanPageHandler);
server.on("/scan_i2c", i2cScanPageHandler);
server.on("/ntp", ntpPageHandler);
server.on("/info", infoPageHandler);
server.on("/time", timeServerPageHandler);
server.on("/reset", resetPageHandler);
server.on("/updatetime", updateTimePageHandler);
server.onNotFound(handleNotFound);
server.begin();
#ifdef DEBUG
Serial.println("HTTP server started");
#endif
}
// ----------------------------------------------------------------------------------------------------
// --------------------------------------------- Main Loop --------------------------------------------
// ----------------------------------------------------------------------------------------------------
void loop()
{
server.handleClient();
// Only works if we are not using the serial interface
if ((millis() - lastMillis) > 1000) {
lastMillis = millis();
// See if it is time to update the Clock
if ((millis() - lastI2CUpdateTime) > 60000) {
// Send the time to the I2C client
int result = sendTimeToI2C(getTimeFromTimeZoneServer());
if(result == 0) {
lastI2CUpdateTime = millis();
}
}
#ifndef DEBUG
toggleBlueLED();
#endif
}
}
// ----------------------------------------------------------------------------------------------------
// ------------------------------------------- Page Handlers ------------------------------------------
// ----------------------------------------------------------------------------------------------------
/**
Root page for the webserver
*/
void rootPageHandler()
{
String response_message = "<html><head><title>Arduino Nixie Clock Time Module</title></head>";
response_message += "<body style=\"background-color:PaleGoldenRod\"><h1><center>Arduino Nixie Clock Time Module</center></h1>";
if (WiFi.status() == WL_CONNECTED)
{
IPAddress ip = WiFi.localIP();
String ipStr = String(ip[0]) + '.' + String(ip[1]) + '.' + String(ip[2]) + '.' + String(ip[3]);
IPAddress softapip = WiFi.softAPIP();
String ipStr1 = String(softapip[0]) + '.' + String(softapip[1]) + '.' + String(softapip[2]) + '.' + String(softapip[3]);
response_message += "<center>WLAN Status: Connected<br>";
response_message += "WLAN IP: ";
response_message += ipStr;
response_message += "<br>";
response_message += "AP IP: ";
response_message += ipStr1;
response_message += "<br>";
response_message += "WLAN SSID: ";
response_message += WiFi.SSID();
response_message += "<br>";
response_message += "<br>";
response_message += "Time server URL: ";
response_message += timeServerURL;
response_message += "<br>";
response_message += "Time according to time server: ";
response_message += getTimeFromTimeZoneServer();
response_message += "<br>";
response_message += "</center><br>";
}
else
{
IPAddress softapip = WiFi.softAPIP();
String ipStr1 = String(softapip[0]) + '.' + String(softapip[1]) + '.' + String(softapip[2]) + '.' + String(softapip[3]);
response_message += "<center>WLAN Status: Disconnected<br>";
response_message += "AP IP: ";
response_message += ipStr1;
response_message += "<br>";
response_message += "</center><br>";
}
// Make the uptime readable
long upSecs = millis() / 1000;
long upDays = upSecs / 86400;
long upHours = (upSecs - (upDays * 86400)) / 3600;
long upMins = (upSecs - (upDays * 86400) - (upHours * 3600)) / 60;
response_message += "<center>Uptime: ";
response_message += upDays;
response_message += " days, ";
response_message += upHours;
response_message += " hours, ";
response_message += upMins;
response_message += " mins</center><br>";
response_message += "<ul><li><a href=\"/wlan_config\">Configure WLAN settings</a></li>";
response_message += "<li><a href=\"/time\">Configure Time Server</a></li>";
response_message += "<li><a href=\"/scan_i2c\">Scan I2C</h4></li>";
response_message += "<li><a href=\"/ntp\">Get NTP time</h4></li>";
response_message += "<li><a href=\"/info\">Show Information about the ESP8266</h4></li>";
response_message += "<li><a href=\"/updatetime\">Update the time now</h4></li></ul>";
response_message += "</body></html>";
server.send(200, "text/html", response_message);
}
/**
WLAN page allows users to set the WiFi credentials
*/
void wlanPageHandler()
{
// Check if there are any GET parameters, if there are, we are configuring
if (server.hasArg("ssid"))
{
if (server.hasArg("password"))
{
WiFi.begin(server.arg("ssid").c_str(), server.arg("password").c_str());
}
else
{
WiFi.begin(server.arg("ssid").c_str());
}
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
#ifdef DEBUG
Serial.print(".");
#endif
}
storeWLANCredentialsInEEPROM(server.arg("ssid"), server.arg("password"));
#ifdef DEBUG
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("SoftAP IP address: ");
Serial.println(WiFi.softAPIP());
#endif
}
String response_message = "";
response_message += "<html>";
response_message += "<head><title>Arduino Nixie Clock Time Module</title></head>";
response_message += "<body style=\"background-color:PaleGoldenRod\"><h1><center>WLAN Settings</center></h1>";
if (WiFi.status() == WL_CONNECTED)
{
response_message += "Status: Connected<br>";
}
else
{
response_message += "Status: Disconnected<br>";
}
response_message += "<p>To connect to a WiFi network, please select a network...</p>";
// Get number of visible access points
int ap_count = WiFi.scanNetworks();
if (ap_count == 0)
{
response_message += "No access points found.<br>";
}
else
{
response_message += "<form method=\"get\">";
// Show access points
for (uint8_t ap_idx = 0; ap_idx < ap_count; ap_idx++)
{
response_message += "<input type=\"radio\" name=\"ssid\" value=\"" + String(WiFi.SSID(ap_idx)) + "\">";
response_message += String(WiFi.SSID(ap_idx)) + " (RSSI: " + WiFi.RSSI(ap_idx) + ")";
(WiFi.encryptionType(ap_idx) == ENC_TYPE_NONE) ? response_message += " " : response_message += "*";
response_message += "<br><br>";
}
response_message += "WiFi password (if required):<br>";
response_message += "<input type=\"text\" name=\"password\"><br>";
response_message += "<input type=\"submit\" value=\"Connect\">";
response_message += "</form>";
}
response_message += "<a href=\"/\">Go back to main page</a>";
response_message += "</body></html>";
server.send(200, "text/html", response_message);
}
/**
Scan the I2C bus - master mode looking for slaves
*/
void i2cScanPageHandler()
{
String response_message = "<html><head><title>Arduino Nixie Clock Time Module</title></head>";
response_message += "<body style=\"background-color:PaleGoldenRod\"><h1><center>Arduino Nixie Clock Time Module</center></h1>";
for (int idx = 0 ; idx < 128 ; idx++)
{
Wire.beginTransmission(idx);
int error = Wire.endTransmission();
if (error == 0) {
response_message += "<center>Found I2C slave at ";
response_message += idx;
response_message += "</center><br>";
} else {
response_message += ".";
}
}
response_message += "<br>";
response_message += "<a href=\"/\">Go back to main page</a>";
response_message += "</body></html>";
server.send(200, "text/html", response_message);
}
/**
Get the NTP time
*/
void ntpPageHandler()
{
long epoch = getNTPTime();
String response_message = "<html><head><title>Arduino Nixie Clock Time Module</title></head>";
response_message += "<body style=\"background-color:PaleGoldenRod\"><h1><center>NTP Status</center></h1>";
response_message += "<center>got epoch ";
response_message += epoch;
response_message += "</center><br>";
response_message += "<a href=\"/\">Go back to main page</a>";
response_message += "</body></html>";
server.send(200, "text/html", response_message);
}
/**
Get the local time from the time server, and modify the time server URL if needed
*/
void timeServerPageHandler()
{
// Check if there are any GET parameters, if there are, we are configuring
if (server.hasArg("timeserverurl"))
{
if (strlen(server.arg("timeserverurl").c_str()) > 4) {
timeServerURL = server.arg("timeserverurl").c_str();
storeTimeServerURLInEEPROM(timeServerURL);
}
}
String timeString = getTimeFromTimeZoneServer();
String response_message = "<html><head><title>Arduino Nixie Clock Time Module</title></head>";
response_message += "<body style=\"background-color:PaleGoldenRod\"><h1><center>Time Status</center></h1>";
response_message += "<center>got time string ";
response_message += timeString;
response_message += "</center><br>";
response_message += "<form method=\"get\">";
response_message += "Time Server URL:<br>";
response_message += "<input type=\"text\" name=\"timeserverurl\" value=\"";
response_message += timeServerURL;
response_message += "\"><br>";
response_message += "<input type=\"submit\" value=\"Set\">";
response_message += "</form>";
response_message += "<a href=\"/\">Go back to main page</a>";
response_message += "</body></html>";
server.send(200, "text/html", response_message);
}
/**
Get the local time from the time server, and send it via I2C right now
*/
void updateTimePageHandler()
{
String timeString = getTimeFromTimeZoneServer();
int result = sendTimeToI2C(timeString);
String response_message = "<html><head><title>Arduino Nixie Clock Time Module</title></head>";
response_message += "<body style=\"background-color:PaleGoldenRod\"><h1><center>Time Status</center></h1>";
response_message += "<center>got time string ";
response_message += timeString;
response_message += "</center><br>";
response_message += "<center>update result ";
response_message += result;
response_message += "</center><br>";
response_message += "<a href=\"/\">Go back to main page</a>";
response_message += "</body></html>";
server.send(200, "text/html", response_message);
}
/**
Give info about the ESP8266
*/
void infoPageHandler() {
String response_message = "<html><head><title>Arduino Nixie Clock Time Module</title></head>";
response_message += "<body style=\"background-color:PaleGoldenRod\"><h1><center>ESP8266 Status</center></h1>";
response_message += "<center>Sketch size: ";
response_message += ESP.getSketchSize();
response_message += "<center>Free sketch size: ";
response_message += ESP.getFreeSketchSpace();
response_message += "<center>Free heap: ";
response_message += ESP.getFreeHeap();
response_message += "<center>Boot version: ";
response_message += ESP.getBootVersion();
response_message += "<center>CPU Freq: ";
response_message += ESP.getCpuFreqMHz();
response_message += "<center>SDK version: ";
response_message += ESP.getSdkVersion();
response_message += "<center>Chip ID: ";
response_message += ESP.getChipId();
response_message += "<center>Flash Chip ID: ";
response_message += ESP.getFlashChipId();
response_message += "<center>Flash size: ";
response_message += ESP.getFlashChipRealSize();
response_message += "<center>Vcc: ";
response_message += ESP.getVcc();
response_message += "</center><br>";
response_message += "<a href=\"/\">Go back to main page</a>";
response_message += "</body></html>";
server.send(200, "text/html", response_message);
}
/**
Reset the EEPROM and stored values
*/
void resetPageHandler() {
clearCredentialsFromEEPROM();
clearTimeServerURLFromEEPROM();
String response_message = "<html><head><title>Arduino Nixie Clock Time Module</title></head>";
response_message += "<body style=\"background-color:PaleGoldenRod\"><h1><center>Reset</center></h1>";
response_message += "<center>Reset done</center><br>";
response_message += "<a href=\"/\">Go back to main page</a>";
response_message += "</body></html>";
server.send(200, "text/html", response_message);
}
/* Called if requested page is not found */
void handleNotFound()
{
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++)
{
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------- Network handling -----------------------------------------
// ----------------------------------------------------------------------------------------------------
/**
Try to connect to the WiFi with the given credentials. Give up after 10 seconds
if we can't get in.
*/
int connectToWLAN(const char* ssid, const char* password) {
int retries = 0;
#ifdef DEBUG
Serial.println("Connecting to WLAN");
#endif
if (password && strlen(password) > 0 ) {
WiFi.begin(ssid, password);
} else {
WiFi.begin(ssid);
}
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
#ifdef DEBUG
Serial.print(".");
#endif
retries++;
if (retries > 20) {
return 1;
}
}
return 0;
}
// send an NTP request to the time server at the given address
unsigned long getNTPTime()
{
unsigned int localPort = 2390; // local port to listen for UDP packets
IPAddress timeServerIP; // time.nist.gov NTP server address
const char* ntpServerName = "time.nist.gov";
const int NTP_PACKET_SIZE = 48; // NTP time stamp is in the first 48 bytes of the message
byte packetBuffer[ NTP_PACKET_SIZE]; //buffer to hold incoming and outgoing packets
// A UDP instance to let us send and receive packets over UDP
WiFiUDP udp;
udp.begin(localPort);
#ifdef DEBUG
Serial.print("UDP Local port: ");
Serial.println(udp.localPort());
#endif
//get a random server from the pool
WiFi.hostByName(ntpServerName, timeServerIP);
#ifdef DEBUG
Serial.print("Got target IP: ");
Serial.println(timeServerIP);
Serial.println("sending NTP packet...");
#endif
memset(packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
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
// 8 bytes of zero for Root Delay & Root Dispersion
packetBuffer[12] = 49;
packetBuffer[13] = 0x4E;
packetBuffer[14] = 49;
packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
udp.beginPacket(timeServerIP, 123); //NTP requests are to port 123
udp.write(packetBuffer, NTP_PACKET_SIZE);
udp.endPacket();
// Try for 10 seconds to get a packet
delay(1000);
int loopCounter = 0;
while (loopCounter < 100) {
loopCounter++;
int cb = udp.parsePacket();
if (!cb) {
#ifdef DEBUG
Serial.println("no packet yet");
#endif
} else {
#ifdef DEBUG
Serial.print("packet received, length=");
Serial.println(cb);
#endif
// We've received a packet, read the data from it
udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer
//the timestamp starts at byte 40 of the received packet and is four bytes,
// or two words, long. First, esxtract the two words:
unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
unsigned long lowWord = word(packetBuffer[42], 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;
#ifdef DEBUG
Serial.print("Seconds since Jan 1 1900 = " );
Serial.println(secsSince1900);
// now convert NTP time into everyday time:
Serial.print("Unix time = ");
#endif
// Unix time starts on Jan 1 1970. In seconds, that's 2208988800:
const unsigned long seventyYears = 2208988800UL;
// subtract seventy years:
unsigned long epoch = secsSince1900 - seventyYears;
#ifdef DEBUG
// print Unix time:
Serial.println(epoch);
#endif
byte hours = (epoch % 86400L) / 3600;
byte mins = (epoch % 3600) / 60;
byte secs = (epoch % 60);
#ifdef DEBUG
// print the hour, minute and second:
Serial.print("The UTC time is "); // UTC is the time at Greenwich Meridian (GMT)
Serial.print(hours); // print the hour (86400 equals secs per day)
Serial.print(':');
if (mins < 10 ) {
// In the first 10 minutes of each hour, we'll want a leading '0'
Serial.print('0');
}
Serial.print(mins); // print the minute (3600 equals secs per minute)
Serial.print(':');
if ( secs < 10 ) {
// In the first 10 seconds of each minute, we'll want a leading '0'
Serial.print('0');
}
Serial.println(secs); // print the second
#endif
time_t def_time = epoch;
struct tm *a_tim = localtime(&def_time);
Serial.print("Local hours: ");
Serial.println(a_tim->tm_hour);
return epoch;
}
delay(100);
}
// no result in the time
return 0;
}
/**
Get the local time from the time zone server. Return "ERROR" if something went wrong.
Uses the global variable timeServerURL.
*/
String getTimeFromTimeZoneServer() {
HTTPClient http;
String payload = "ERROR";
http.begin(timeServerURL);
int httpCode = http.GET();
if (httpCode > 0) {
// file found at server
if (httpCode == HTTP_CODE_OK) {
payload = http.getString();
}
} else {
#ifdef DEBUG
Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
#endif
}
http.end();
return payload;
}
// ----------------------------------------------------------------------------------------------------
// ------------------------------------------ EEPROM functions ----------------------------------------
// ----------------------------------------------------------------------------------------------------
String getSSIDFromEEPROM() {
#ifdef DEBUG
Serial.println("Reading EEPROM ssid");
#endif
String esid = "";
for (int i = 0; i < 32; i++)
{
byte readByte = EEPROM.read(i);
if (readByte == 0) {
break;
}
esid += char(readByte);
}
#ifdef DEBUG
Serial.print("Recovered SSID: ");
Serial.println(esid);
#endif
return esid;
}
String getPasswordFromEEPROM() {
#ifdef DEBUG
Serial.println("Reading EEPROM password");
#endif
String epass = "";
for (int i = 32; i < 96; i++)
{
byte readByte = EEPROM.read(i);
if (readByte == 0) {
break;
}
epass += char(EEPROM.read(i));
}
#ifdef DEBUG
Serial.print("Recovered password: ");
Serial.println(epass);
#endif
return epass;
}
void storeWLANCredentialsInEEPROM(String qsid, String qpass) {
#ifdef DEBUG
Serial.print("writing eeprom ssid, length ");
Serial.println(qsid.length());
#endif
for (int i = 0; i < 32; i++)
{
if (i < qsid.length()) {
EEPROM.write(i, qsid[i]);
#ifdef DEBUG
Serial.print("Wrote: ");
Serial.println(qsid[i]);
#endif
} else {
EEPROM.write(i, 0);
}
}
#ifdef DEBUG
Serial.print("writing eeprom pass, length ");
Serial.println(qpass.length());
#endif
for (int i = 0; i < 96; i++)
{
if ( i < qpass.length()) {
EEPROM.write(32 + i, qpass[i]);
#ifdef DEBUG
Serial.print("Wrote: ");
Serial.println(qpass[i]);
#endif
} else {
EEPROM.write(32 + i, 0);
}
}
EEPROM.commit();
}
void clearCredentialsFromEEPROM() {
#ifdef DEBUG
Serial.println("clearing credentials from eeprom");
#endif
for (int i = 0; i < (96); i++) {
EEPROM.write(i, 0);
}
EEPROM.commit();
}
String getTimeServerURLFromEEPROM() {
#ifdef DEBUG
Serial.println("Reading time server URL");
#endif
String eurl = "";
for (int i = 96; i < (96 + 256); i++)
{
byte readByte = EEPROM.read(i);
if (readByte != 0) {
eurl += char(readByte);
}
}
#ifdef DEBUG
Serial.print("Recovered time server URL: ");
Serial.println(eurl);
Serial.println(eurl.length());
#endif
return eurl;
}
void storeTimeServerURLInEEPROM(String timeServerURL) {
#ifdef DEBUG
Serial.print("writing time server URL, length ");
Serial.println(timeServerURL.length());
#endif
for (int i = 0; i < 256; i++)
{
if (i < timeServerURL.length()) {
EEPROM.write(96 + i, timeServerURL[i]);
#ifdef DEBUG
Serial.print("Wrote: ");
Serial.println(timeServerURL[i]);
#endif
} else {
EEPROM.write(96 + i, 0);
}
}
EEPROM.commit();
}
void clearTimeServerURLFromEEPROM() {
#ifdef DEBUG
Serial.println("clearing time server URL from eeprom");
#endif
for (int i = 96; i < (96 + 256); i++) {
EEPROM.write(i, 0);
}
EEPROM.commit();
}
// ----------------------------------------------------------------------------------------------------
// ----------------------------------------- Utility functions ----------------------------------------
// ----------------------------------------------------------------------------------------------------
/**
Switch the state of the blue LED and send it to the GPIO. Used in normal "heartbeat" processing and to show processing.
*/
void toggleBlueLED() {
blueLedState = ! blueLedState;
digitalWrite(blueLedPin, blueLedState);
}
/**
Send the time to the I2C slave.
*/
int sendTimeToI2C(String timeString) {
int year = getIntValue(timeString, ',', 0);
byte month = getIntValue(timeString, ',', 1);
byte day = getIntValue(timeString, ',', 2);
byte hour = getIntValue(timeString, ',', 3);
byte minute = getIntValue(timeString, ',', 4);
byte sec = getIntValue(timeString, ',', 5);
byte yearAdjusted = (year - 2000);
Wire.beginTransmission(I2C_SLAVE_ADDR);
Wire.write(I2C_TIME_UPDATE); // Command
Wire.write(yearAdjusted);
Wire.write(month);
Wire.write(day);
Wire.write(hour);
Wire.write(minute);
Wire.write(sec);
int error = Wire.endTransmission();
return error;
}
/**
Split a string based on a separator, get the element given by index
*/
String getValue(String data, char separator, int index)
{
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length() - 1;
for (int i = 0; i <= maxIndex && found <= index; i++) {
if (data.charAt(i) == separator || i == maxIndex) {
found++;
strIndex[0] = strIndex[1] + 1;
strIndex[1] = (i == maxIndex) ? i + 1 : i;
}
}
return found > index ? data.substring(strIndex[0], strIndex[1]) : "";
}
int getIntValue(String data, char separator, int index) {
String result = getValue(data, separator, index);
return atoi(result.c_str());
}