-
-
Notifications
You must be signed in to change notification settings - Fork 55
/
d1-template.ino
383 lines (314 loc) · 8.72 KB
/
d1-template.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
//
// This is a simple template-project which does the minimal
// kind of thing that any of my projects tend to do:
//
// * Handle the setup of WiFi.
//
// * Handle OTA - no password.
//
// * Get the time/date via NTP.
//
// * Launch a simple HTTP-server.
//
// Steve
// --
//
//
// WiFi manager library, for working as an access-point, etc.
//
#include "WiFiManager.h"
//
// WiFi & over the air updates
//
#include <ESP8266WiFi.h>
#include <ArduinoOTA.h>
//
// For dealing with NTP & the clock.
//
#include "NTPClient.h"
//
// Debug messages over the serial console.
//
#include "debug.h"
//
// The name of this project.
//
// Used for the Access-Point name, and for OTA-identification.
//
#define PROJECT_NAME "TEMPLATE"
//
// The NTP-client object.
//
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
//
// Timezone offset from GMT
//
int time_zone_offset = 0;
//
// The HTTP-server we present runs on port 80.
//
WiFiServer server(80);
//
// This function is called when the device is powered-on.
//
void setup()
{
//
// Enable our serial port.
//
#ifdef DEBUG
Serial.begin(115200);
#endif
//
// Handle Connection.
//
WiFiManager wifiManager;
wifiManager.setAPCallback(access_point_callback);
wifiManager.autoConnect(PROJECT_NAME);
//
// Now we're connected show the local IP address.
//
DEBUG_LOG("\nWiFi Connected with IP %s\n",
WiFi.localIP().toString().c_str());
//
// Ensure our NTP-client is ready.
//
timeClient.begin();
//
// Configure the NTP-callbacks
//
timeClient.on_before_update(on_before_ntp);
timeClient.on_after_update(on_after_ntp);
//
// Setup the timezone & update-interval.
//
timeClient.setTimeOffset(time_zone_offset * (60 * 60));
timeClient.setUpdateInterval(300 * 1000);
//
// Now we can start our HTTP server
//
server.begin();
DEBUG_LOG("HTTP-Server started on http://%s\n",
WiFi.localIP().toString().c_str());
//
// Allow over the air updates
//
// This is documented here:
// https://randomnerdtutorials.com/esp8266-ota-updates-with-arduino-ide-over-the-air/
//
// Hostname defaults to esp8266-[ChipID]
//
ArduinoOTA.setHostname(PROJECT_NAME);
ArduinoOTA.onStart([]()
{
DEBUG_LOG("OTA Started:");
});
ArduinoOTA.onEnd([]()
{
DEBUG_LOG("OTA Ended.");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total)
{
char buf[64];
memset(buf, '\0', sizeof(buf));
snprintf(buf, sizeof(buf) - 1, "Upgrade - %02u%%", (progress / (total / 100)));
DEBUG_LOG(buf);
});
ArduinoOTA.onError([](ota_error_t error)
{
if (error == OTA_AUTH_ERROR)
DEBUG_LOG("\tAuth Failed\n");
else if (error == OTA_BEGIN_ERROR)
DEBUG_LOG("\tBegin Failed\n");
else if (error == OTA_CONNECT_ERROR)
DEBUG_LOG("\tConnect Failed\n");
else if (error == OTA_RECEIVE_ERROR)
DEBUG_LOG("\tReceive Failed\n");
else if (error == OTA_END_ERROR)
DEBUG_LOG("\tEnd Failed\n");
});
//
// Ensure the OTA process is running & listening.
//
ArduinoOTA.begin();
}
//
// Called just before the date/time is updated via NTP
//
void on_before_ntp()
{
DEBUG_LOG("Updating date & time:\n");
}
//
// Called just after the date/time is updated via NTP
//
void on_after_ntp()
{
DEBUG_LOG("\tUpdated date & time\n");
}
//
// If we're unconfigured we run an access-point.
//
// Show that, explicitly.
//
void access_point_callback(WiFiManager* myWiFiManager)
{
DEBUG_LOG("AccessPoint Mode Enabled.\n");
}
//
// This function is called continously.
//
void loop()
{
//
// Keep the previous time, to avoid needless re-draws
//
static char prev_time[40] = { '\0'};
//
// The current time.
//
// We'll format stuff here, and if the value are different
// from the previous-time we'll know we should output it.
//
char curr_time[40] = { '\0'};
//
// Handle any pending over the air updates.
//
ArduinoOTA.handle();
//
// Resync the clock?
//
timeClient.update();
//
// Get the current time.
//
int hour = timeClient.getHours();
int min = timeClient.getMinutes();
int sec = timeClient.getSeconds();
int year = timeClient.getYear();
//
// Along with names for things.
//
String d_name = timeClient.getWeekDay();
String m_name = timeClient.getMonth();
int day = timeClient.getDayOfMonth();
//
// Format the time & date.
//
snprintf(curr_time, sizeof(curr_time) - 1,
"%02d:%02d:%02d %s %02d %s %04d\n",
hour, min, sec, d_name.c_str(), day, m_name.c_str(), year);
//
// Output to the serial-console if the time
// has changed - i.e. once per second.
//
if (strcmp(curr_time , prev_time) != 0)
{
DEBUG_LOG(curr_time);
//
// Record the current time.
//
strcpy(prev_time, curr_time);
}
//
// Check if a client has connected to our HTTP-server.
//
// If so handle it.
//
WiFiClient client = server.available();
if (client)
processHTTPRequest(client);
//
// Now sleep a little.
//
delay(20);
}
//
// Serve a redirect to the server-root
//
void redirectIndex(WiFiClient client)
{
client.println("HTTP/1.1 302 Found");
client.print("Location: http://");
client.print(WiFi.localIP().toString().c_str());
client.println("/");
}
//
// This is a bit horrid.
//
// Serve a HTML-page to any clients who connect, via a browser.
//
void serveHTML(WiFiClient client)
{
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println("");
client.println("<!DOCTYPE html>");
client.println("<html lang=\"en\">");
client.println("<head>");
client.println("<title>Template Project</title>");
client.println("<meta charset=\"utf-8\">");
client.println("<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">");
client.println("<link href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u\" crossorigin=\"anonymous\">");
client.println("<script src=\"https://code.jquery.com/jquery-1.12.4.min.js\" integrity=\"sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=\" crossorigin=\"anonymous\"></script>");
client.println("<script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\" integrity=\"sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa\" crossorigin=\"anonymous\"></script>");
client.println("</head>");
client.println("<body>");
client.println("<nav id=\"nav\" class = \"navbar navbar-default\" style=\"padding-left:50px; padding-right:50px;\">");
client.println("<div class = \"navbar-header\">");
client.println("<h1 class=\"banner\"><a href=\"/\">Template Project</a> - <small>by Steve</small></h1>");
client.println("</div>");
client.println("<ul class=\"nav navbar-nav navbar-right\">");
client.println("<li><a href=\"https://steve.fi/Hardware/\">Steve's Projects</a></li>");
client.println("</ul>");
client.println("</nav>");
client.println("<div class=\"container-fluid\">");
// Start of body
// Row
client.println("<div class=\"row\">");
client.println("<div class=\"col-md-3\"></div>");
client.println("<div class=\"col-md-9\"><h1>Template Project</h1><p> </p></div>");
client.println("</div>");
client.println("<div class=\"row\">");
client.println("<div class=\"col-md-4\"></div>");
client.println("<div class=\"col-md-4\">");
client.println("<p>This is a template project. Update as you wish.</p>");
client.println("</div>");
client.println("<div class=\"col-md-4\"></div>");
client.println("</div>");
// End of body
client.println("</div>");
client.println("</body>");
client.println("</html>");
}
//
// Process an incoming HTTP-request.
//
void processHTTPRequest(WiFiClient client)
{
// Wait until the client sends some data
while (client.connected() && !client.available())
delay(1);
// Read the first line of the request
String request = client.readStringUntil('\r');
client.flush();
#if 0
//
// Sample of how to handle a particular request
//
if (request.indexOf("/ON") != -1)
{
//
// Do stuff here.
//
//
// Redirect to the server-root
//
redirectIndex(client);
return;
}
#endif
// Return a simple response
serveHTML(client);
}