-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathESP8266-MyWidget-Demo.ino
785 lines (694 loc) · 26.6 KB
/
ESP8266-MyWidget-Demo.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
/*
MIT License
ESP8266-MyWidget-Demo.ino
Copyright (c) 2021 Tony Keith
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.
Version: 1.1.3
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266mDNS.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoOTA.h>
#include <LittleFS.h>
#include <PangolinMQTT.h>
#include <Ticker.h>
#include <ESP8266TimerInterrupt.h>
#include <ESP8266_ISR_Timer.h>
#define LIBRARY "PangolinMQTT "PANGO_VERSION
// MQTT Delay
#define RECONNECT_DELAY_M 3
// WIFI Delay
#define RECONNECT_DELAY_W 5
// MQTT Port
#define MQTT_PORT 1883
#define START_WITH_CLEAN_SESSION true
// 1uS * 10000 = 10mS
#define HW_TIMER_INTERVAL 10000
// define timer dividers for onboard LED flash speed
#define INT_SLOW 1000 // 1hz
#define INT_MED 500 // 5 hz
#define INT_FAST 100 // 10 hz
#define INT_FASTEST 50 // 20 hz
// Your ssid and password here
const char* ssid = "YOUR-SSID";
const char* password = "YOUR-SSID-PASSWORD";
// Your MQTT broker address here
#define MQTT_HOST IPAddress(192, 168, 0, 100)
// host name
const char* host = "mywidget";
// global LED state
bool ledState1 = 0;
// global MQTT publish counter
int counter = 1;
// interrupt variables
volatile unsigned long interruptCounter1 = 0;
volatile unsigned long interruptCounter2 = 0;
volatile unsigned long interruptCounter3 = 0;
// timer intervals
unsigned long interruptInterval1 = INT_SLOW;
unsigned long interruptInterval2 = INT_FAST;
unsigned long interruptInterval3 = INT_FASTEST;
// interrupt interval index for changeInterval()
int timer1_idx=0; // ledTimerISR()
int timer2_idx=0; // counterTimer1ISR()
int timer3_idx=0; // counterTimer2ISR()
// init ESP8266 timer
ESP8266Timer ITimer;
ESP8266_ISR_Timer ISR_Timer;
// interrupt timer handler
void ICACHE_RAM_ATTR timerHandler() {
ISR_Timer.run();
} // timerHandler()
// interrupt handler to Toggle LED
void ICACHE_RAM_ATTR ledTimerISR() {
// Toggle LED Pin
digitalWrite(LED_BUILTIN,!(digitalRead(LED_BUILTIN)));
// inc counter
interruptCounter1++;
} // ledTimerISR()
// interrupt handler to increment counter
void ICACHE_RAM_ATTR counterTimer1ISR() {
// inc counter
interruptCounter2++;
} // counterTimer1ISR()
// interrupt handler to increment counter
void ICACHE_RAM_ATTR counterTimer2ISR() {
// inc counter
interruptCounter3++;
} // counterTimer2ISR()
// file system structure
FSInfo fs_info;
PangolinMQTT mqttClient;
Ticker mqttReconnectTimer,wifiReconnectTimer;
WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
AsyncWebServer webServer(80);
AsyncWebSocket webSocket("/ws");
void handleWebSocketMessage(AsyncWebSocket *server, AsyncWebSocketClient *client, void *arg, uint8_t *data, size_t len) {
AwsFrameInfo *info = (AwsFrameInfo*)arg;
if (info->final && info->index == 0 && info->len == len) {
if(info->opcode == WS_TEXT) {
char buffer[100];
memcpy(buffer, data, len);
buffer[len] = 0;
Serial.printf("Handle WS: %s - len: %d\n", buffer, len);
char *token = strtok(buffer, ":");
if(!strcmp("cmd", token)) {
// Serial.println("cmd");
token = strtok(NULL, ":");
if (!strcmp("get", token)) {
// GET ACTIONS
// Serial.println("get");
token = strtok(NULL, ":");
// Serial.println(token);
if (!strcmp("uptime", token)) {
// uptime
Serial.println("uptime:" + String(millis()));
client->text("cmd:get:uptime:" + String(millis()));
} else if (!strcmp("status", token)) {
// status
client->text("cmd:get:status:" + String(ledState1));
} else if (!strcmp("speed", token)) {
String speed = "1";
// speed - cmd:get:speed:interrupt:speed
char *intNum = strtok(NULL, ":");
Serial.println("interrupt:" + String(intNum));
if(intNum[0] == '1') {
// interrupt - 1
if(interruptInterval1 == INT_SLOW)
speed = "1";
else if(interruptInterval1 == INT_MED)
speed = "2";
else if(interruptInterval1 == INT_FAST)
speed = "3";
else if(interruptInterval1 == INT_FASTEST)
speed = "4";
} else if(intNum[0] == '2') {
// interrupt - 2
if(interruptInterval2 == INT_SLOW)
speed = "1";
else if(interruptInterval2 == INT_MED)
speed = "2";
else if(interruptInterval2 == INT_FAST)
speed = "3";
else if(interruptInterval2 == INT_FASTEST)
speed = "4";
} else if(intNum[0] == '3') {
// interrupt - 3
if(interruptInterval3 == INT_SLOW)
speed = "1";
else if(interruptInterval3 == INT_MED)
speed = "2";
else if(interruptInterval3 == INT_FAST)
speed = "3";
else if(interruptInterval3 == INT_FASTEST)
speed = "4";
}
client->text("cmd:get:speed:" + String(intNum) + ":" + String(speed));
} else if (!strcmp("config", token)) {
// config
String fileData;
File f = LittleFS.open("/cfg.txt", "r");
if (!f) {
Serial.println("file open failed");
} else {
f.seek (0, SeekSet);
fileData = f.readString ();
f.close ();
}
client->text("cmd:get:config:" + fileData);
} else {
Serial.println("Unknown get action");
client->text("Unknown get action");
}
} else if (!strcmp("set", token)) {
// SET ACTIONS
// Serial.println("set");
token = strtok(NULL, ":");
// Serial.println(token);
if (!strcmp("toggle", token)) {
// toggle
ledState1 = !ledState1;
client->text("cmd:set:toggle:" + String(ledState1));
} else if (!strcmp("speed", token)) {
// default to slow
unsigned long tmpSpeed = INT_SLOW;
// speed - cmd:set:speed:interrupt:speed
char *intNum = strtok(NULL, ":");
Serial.println("interrupt:" + String(intNum));
char *speed = strtok(NULL, ":");
Serial.println("speed:" + String(speed));
if(strlen(speed) == 1) {
if(speed[0] == '1')
tmpSpeed = INT_SLOW;
else if (speed[0] == '2')
tmpSpeed = INT_MED;
else if (speed[0] == '3')
tmpSpeed = INT_FAST;
else if (speed[0] == '4')
tmpSpeed = INT_FASTEST;
}
if(intNum[0] == '1') {
// interrupt - 1
if(tmpSpeed != interruptInterval1) {
interruptInterval1 = tmpSpeed;
// update the interval
ISR_Timer.changeInterval(timer1_idx, interruptInterval1);
}
} else if(intNum[0] == '2') {
// interrupt - 2
if(tmpSpeed != interruptInterval2) {
interruptInterval2 = tmpSpeed;
// update the interval
ISR_Timer.changeInterval(timer2_idx, interruptInterval2);
}
} else if(intNum[0] == '3') {
// interrupt - 3
if(tmpSpeed != interruptInterval2) {
interruptInterval3 = tmpSpeed;
// update the interval
ISR_Timer.changeInterval(timer3_idx, interruptInterval3);
}
}
client->text("cmd:set:speed:" + String(intNum) + ":" + String(speed));
} else if (!strcmp("config", token)) {
String(buf);
// config
// channels:ports:user1:user2
char *channels = strtok(NULL, ":");
Serial.println(channels);
char *ports = strtok(NULL, ":");
Serial.println(ports);
char *user1 = strtok(NULL, ":");
Serial.println(user1);
char *user2 = strtok(NULL, ":");
Serial.println(user2);
// channels:ports:user1:user2
buf += String(channels) + ":" + String(ports) + ":" + String(user1) + ":" + String(user2);
Serial.println(buf);
File f = LittleFS.open("/cfg.txt", "w");
if (!f) {
Serial.println("file open failed");
} else {
f.seek (0, SeekSet);
f.print (buf);
f.close ();
Serial.println("Config File Saved");
}
client->text("cmd:set:config:" + String(buf));
} else {
Serial.println("Unknown set action");
client->text("Unknown set action");
}
} else {
Serial.println("Unknown request");
client->text("Unknown request");
} // get cmd
} else {
Serial.println("Unknown cmd");
client->text("Unknown cmd");
} // cmd
} else {
client->binary("I got your binary message");
}
} else {
// message is comprised of multiple frames or the frame is split into multiple packets
if(info->index == 0){
if(info->num == 0)
Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");
Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len);
}
Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT)?"text":"binary", info->index, info->index + len);
if(info->message_opcode == WS_TEXT){
data[len] = 0;
Serial.printf("%s\n", (char*)data);
} else {
for(size_t i=0; i < len; i++) {
Serial.printf("%02x ", data[i]);
}
Serial.printf("\n");
}
if((info->index + len) == info->len) {
Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len);
if(info->final) {
Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT)?"text":"binary");
if(info->message_opcode == WS_TEXT)
client->text("I got your text message");
else
client->binary("I got your binary message");
}
}
}
} // handleWebSocketMessage()
void onMqttConnect(bool sessionPresent) {
Serial.printf("Connected to MQTT session=%d max payload size=%d\n", sessionPresent,mqttClient.getMaxPayloadSize());
Serial.println("Subscribing at QoS 2");
mqttClient.subscribe("esp32/get/uptime", 2);
mqttClient.subscribe("esp32/get/heap", 2);
mqttClient.subscribe("esp32/get/counter", 2);
mqttClient.subscribe("esp32/set/counter", 2);
} // onMqttConnect()
void onMqttMessage(const char* topic, const uint8_t* payload, size_t len,uint8_t qos,bool retain,bool dup) {
Serial.printf("\nH=%u Message %s qos%d dup=%d retain=%d len=%d\n",ESP.getFreeHeap(),topic,qos,dup,retain,len);
PANGO::dumphex(payload,len,16);
if(!strcmp(topic,"esp32/get/uptime") ) {
Serial.println("esp32/get/uptime");
mqttClient.publish("esp32/uptime", millis(),"%u");
} else if (!strcmp(topic,"esp32/get/heap")) {
Serial.println("esp32/get/heap");
mqttClient.publish("esp32/heap", ESP.getFreeHeap(),"%u");
} else if (!strcmp(topic,"esp32/get/counter")) {
Serial.println("esp32/get/counter");
mqttClient.publish("esp32/counter", counter, "%u");
if(++counter > 9999)
counter=1;
} else if (!strcmp(topic,"esp32/set/counter")) {
if(len > 0 && len < 6) {
char buf[6];
memcpy(buf, payload, len);
buf[len] = 0;
counter = atoi(buf);
}
Serial.println("esp32/set/counter");
mqttClient.publish("esp32/counter", counter, "%u");
}
} // onMqttMessage()
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type,
void *arg, uint8_t *data, size_t len) {
switch (type) {
case WS_EVT_CONNECT:
Serial.printf("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
break;
case WS_EVT_DISCONNECT:
Serial.printf("WebSocket client #%u disconnected\n", client->id());
break;
case WS_EVT_DATA:
handleWebSocketMessage(server, client, arg, data, len);
break;
case WS_EVT_PONG:
Serial.println("ping");
break;
case WS_EVT_ERROR:
Serial.println("error");
break;
}
} // onEvent()
//
// Based on args, return status of network, signal, chipInfo, heap, filesystem (fs) in JSON format
//
void handleStatusJson(AsyncWebServerRequest* request)
{
String json = "{";
bool n = false;
Serial.println("GET status-json");
if (request->arg("network") == "true") {
// Serial.println("network");
if(n) json += ",";
json += "\"network\":{";
json += "\"ssid\":\"" + String(ssid) + "\"";
json += ",\"hostname\":\"" + String(host) + "\"";
json += ",\"ip\":\"" + WiFi.localIP().toString() + "\"";
json += ",\"gateway\":\"" + WiFi.gatewayIP().toString() + "\"";
json += ",\"netmask\":\"" + WiFi.subnetMask().toString() + "\"";
json += "}";
n = true;
}
if (request->arg("signal")== "true") {
// Serial.println("signal");
if(n) json += ",";
json += "\"signal\":{";
json += "\"strength\":\"" + String(WiFi.RSSI()) + "\"";
json += "}";
n = true;
}
if (request->arg("chipInfo")== "true") {
// Serial.println("chipInfo");
if(n) json += ",";
json += "\"chipInfo\":{";
json += "\"chipId\":\"" + String(ESP.getChipId()) + "\"";
json += ",\"flashChipId\":\"" + String(ESP.getFlashChipId()) + "\"";
json += ",\"flashChipSize\":\"" + String(ESP.getFlashChipSize()) + "\"";
json += ",\"flashChipRealSize\":\"" + String(ESP.getFlashChipRealSize()) + "\"";
json += "}";
n = true;
}
if (request->arg("heap")== "true") {
// Serial.println("heap");
if(n) json += ",";
json += "\"heap\":{";
json += "\"freeHeap\":\"" + String(ESP.getFreeHeap()) + "\"";
json += "}";
n = true;
}
if (request->arg("fs")== "true") {
// Serial.println("fs");
if(n) json += ",";
json += "\"fs\":{";
json += "\"totalBytes\":\"" + String(fs_info.totalBytes) + "\"";
json += ",\"usedBytes\":\"" + String(fs_info.usedBytes) + "\"";
json += "}";
n = true;
}
json += "}";
request->send(200, "application/json", json);
} // handleStatusJson()
//
// Based on args, return interrupt counters
//
void handleIntCounter(AsyncWebServerRequest* request)
{
String buf;
Serial.println("GET intcount");
if(request->params() != 0) {
if (request->arg("1") == "true") {
Serial.println("intcount1");
buf += ":intcount1=" + String(interruptCounter1);
}
if (request->arg("2") == "true") {
Serial.println("intcount2");
buf += ":intcount2=" + String(interruptCounter2);
}
if (request->arg("3") == "true") {
Serial.println("intcount3");
buf += ":intcount3=" + String(interruptCounter3);
}
} else {
buf += ":intcount1=" + String(interruptCounter1);
}
request->send(200, "text/plain", buf);
} // handleIntCounter()
void handleStatus(AsyncWebServerRequest* request)
{
String buf;
Serial.println("GET status");
// not necessary - just additional info
int params = request->params();
for(int i=0;i<params;i++) {
AsyncWebParameter* p = request->getParam(i);
Serial.printf("_GET[%s]: %s\n", p->name().c_str(), p->value().c_str());
}
if (request->arg("network") == "true") {
// Serial.println("network");
buf += ":network=true";
buf += ":ssid=" + String(ssid);
buf += ":hostname=" + String(host);
buf += ":ip=" + WiFi.localIP().toString();
buf += ":gateway=" + WiFi.gatewayIP().toString();
buf += ":netmask=" + WiFi.subnetMask().toString();
}
if (request->arg("signal")== "true") {
// Serial.println("signal");
buf += ":signal=true";
buf += ":strength=" + String(WiFi.RSSI());
}
if (request->arg("chipInfo")== "true") {
// Serial.println("chipInfo");
buf += ":chipInfo=true";
buf += ":chipId=" + String(ESP.getChipId());
buf += ":flashChipId=" + String(ESP.getFlashChipId());
buf += ":flashChipSize=" + String(ESP.getFlashChipSize());
buf += ":flashChipRealSize=" + String(ESP.getFlashChipRealSize());
}
if (request->arg("heap")== "true") {
// Serial.println("heap");
buf += ":heap=true";
buf += ":freeHeap=" + String(ESP.getFreeHeap());
}
if (request->arg("fs")== "true") {
// Serial.println("fs");
buf += ":fs=true";
buf += ":totalBytes=" + String(fs_info.totalBytes);
buf += ":usedBytes=" + String(fs_info.usedBytes);
}
request->send(200, "text/plain", buf);
} // handleStatus()
void initWeb() {
webSocket.onEvent(onEvent);
webServer.addHandler(&webSocket);
// get heap (TEXT response)
webServer.on("/heap", HTTP_GET, [](AsyncWebServerRequest *request) {
Serial.println("GET heap");
request->send(200, "text/plain", "freeHeap=" + String(ESP.getFreeHeap()));
});
// get intcount with optional parameters (TEXT response)
webServer.on("/intcount", HTTP_GET, [](AsyncWebServerRequest *request) {
handleIntCounter(request);
});
// get intcount2 (TEXT response)
webServer.on("/intcount2", HTTP_GET, [](AsyncWebServerRequest *request) {
Serial.println("GET intcount2");
request->send(200, "text/plain", ":intcount2=" + String(interruptCounter2));
});
// get intcount3 (TEXT response)
webServer.on("/intcount3", HTTP_GET, [](AsyncWebServerRequest *request) {
Serial.println("GET intcount3");
request->send(200, "text/plain", ":intcount3=" + String(interruptCounter3));
});
// get status (TEXT response)
webServer.on("/status", HTTP_GET, [](AsyncWebServerRequest* request) {
handleStatus(request);
});
// get status (JSON response)
webServer.on("/status-json", HTTP_GET, [](AsyncWebServerRequest* request) {
handleStatusJson(request);
});
// post counter (TEXT response)
webServer.on("/counter", HTTP_POST, [](AsyncWebServerRequest *request){
String message;
Serial.println("POST:counter");
int i=0;
// counter must be in request
if (request->hasParam("counter", true)) {
message = request->getParam("counter", true)->value();
i = atoi(String(message).c_str());
if(i>0 && i<=9999)
counter = i;
}
request->send(200, "text/plain", "POST: Counter set to: " + String(i));
});
// page not found message
webServer.onNotFound([](AsyncWebServerRequest *request) {
request->send(404, "text/plain", "Page not found");
});
// default to index page
webServer.serveStatic("/", LittleFS, "/").setDefaultFile("index.html");
// serve up image
webServer.on("/cplusplus", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(LittleFS, "/cplusplus.png", "image/png");
});
webServer.begin();
Serial.println("WebServer Started");
} // initWeb()
void connectToMqtt() {
Serial.println("Connecting to MQTT...");
mqttClient.connect();
} // connectToMqtt()
void connectToWifi() {
if(!WiFi.isConnected()) {
Serial.printf("Connecting to Wi-Fi... SSID=%s\n", ssid);
WiFi.begin(ssid, password);
} else {
Serial.printf("Already connected\n");
}
} // connectToWifi()
void onWifiConnect(const WiFiEventStationModeGotIP& event) {
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
if (MDNS.begin(host)) {
Serial.printf("Open http://%s", host);
Serial.println(".local to open ESP8266-MyWidget-Demo");
} else {
Serial.println("Error setting up MDNS responder!");
}
MDNS.addService("http", "tcp", 80);
ArduinoOTA.onStart([]() {
Serial.println("Start");
});
ArduinoOTA.onEnd([]() {
Serial.println("\nEnd");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
Serial.printf("Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
Serial.printf("Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed");
else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed");
else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed");
else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed");
else if (error == OTA_END_ERROR) Serial.println("End Failed");
});
initWeb();
ArduinoOTA.begin();
connectToMqtt();
} // onWifiConnect()
void onWifiDisconnect(const WiFiEventStationModeDisconnected& event) {
Serial.printf("Disconnected from Wi-Fi event=%d\n",event.reason);
mqttReconnectTimer.detach(); // ensure we don't reconnect to MQTT while reconnecting to Wi-Fi
wifiReconnectTimer.once(RECONNECT_DELAY_W, connectToWifi);
} // onWifiDisconnect()
void setup() {
Serial.begin(115200);
wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);
mqttClient.onConnect(onMqttConnect);
mqttClient.onDisconnect(onMqttDisconnect);
mqttClient.onMessage(onMqttMessage);
mqttClient.setServer(MQTT_HOST, MQTT_PORT);
mqttClient.setWill("DIED",2,false,"probably still some bugs");
mqttClient.onError(onMqttError);
mqttClient.setCleanSession(START_WITH_CLEAN_SESSION);
mqttClient.setKeepAlive(RECONNECT_DELAY_M *3);
connectToWifi();
LittleFS.begin();
if(LittleFS.info(fs_info)) {
Serial.printf("LittleFS File System Size: ");
Serial.println(fs_info.totalBytes);
Serial.printf("Used: ");
Serial.println(fs_info.usedBytes);
}
Serial.println("LittlFS started. Contents:");
Dir dir = LittleFS.openDir("/");
while (dir.next()) {
Serial.printf("%s - %d bytes\n", dir.fileName().c_str(), dir.fileSize());
}
dir = LittleFS.openDir("/css");
while (dir.next()) {
Serial.printf("%s - %d bytes\n", dir.fileName().c_str(), dir.fileSize());
}
dir = LittleFS.openDir("/js");
while (dir.next()) {
Serial.printf("%s - %d bytes\n", dir.fileName().c_str(), dir.fileSize());
}
// Initialize the LED_BUILTIN pin as an output
pinMode(LED_BUILTIN, OUTPUT);
// set timer to 100000/100 = 1000 hz
if (! ITimer.attachInterruptInterval(HW_TIMER_INTERVAL, timerHandler)) {
Serial.println("Can't set ITimer correctly. Select another freq. or interval");
}
// The timers of the RTC are not affected by the CPU speed setting.
// A given timer divisor produces the same rate of change of the RTC timer's COUNT register with both speed settings.
// 100 = 1 hz (SLOW)
// 50 = 5 hz (MEDIUM)
// 10 = 10 hz (FAST)
// 5 = 20 hz (FASTEST)
timer1_idx = ISR_Timer.setInterval(interruptInterval1, ledTimerISR);
timer2_idx = ISR_Timer.setInterval(interruptInterval2, counterTimer1ISR);
timer3_idx = ISR_Timer.setInterval(interruptInterval3, counterTimer2ISR);
Serial.printf("Timer1 Index=%d\n",timer1_idx);
Serial.printf("Timer2 Index=%d\n",timer2_idx);
Serial.printf("Timer3 Index=%d\n",timer3_idx);
} // setup()
void onMqttDisconnect(int8_t reason) {
Serial.printf("Disconnected from MQTT reason=%d\n",reason);
mqttReconnectTimer.once(RECONNECT_DELAY_M, connectToMqtt);
} // onMqttDisconnect()
void onMqttError(uint8_t e,uint32_t info) {
switch(e) {
case TCP_DISCONNECTED:
// usually because your structure is wrong and you called a function before onMqttConnect
Serial.printf("ERROR: NOT CONNECTED info=%d\n",info);
break;
case MQTT_SERVER_UNAVAILABLE:
// server has gone away - network problem? server crash?
Serial.printf("ERROR: MQTT_SERVER_UNAVAILABLE info=%d\n",info);
break;
case UNRECOVERABLE_CONNECT_FAIL:
// there is something wrong with your connection parameters? IP:port incorrect? user credentials typo'd?
Serial.printf("ERROR: UNRECOVERABLE_CONNECT_FAIL info=%d\n",info);
break;
case TLS_BAD_FINGERPRINT:
Serial.printf("ERROR: TLS_BAD_FINGERPRINT info=%d\n",info);
break;
case SUBSCRIBE_FAIL:
// you tried to subscribe to an invalid topic
Serial.printf("ERROR: SUBSCRIBE_FAIL info=%d\n",info);
break;
case INBOUND_QOS_ACK_FAIL:
Serial.printf("ERROR: OUTBOUND_QOS_ACK_FAIL id=%d\n",info);
break;
case OUTBOUND_QOS_ACK_FAIL:
Serial.printf("ERROR: OUTBOUND_QOS_ACK_FAIL id=%d\n",info);
break;
case INBOUND_PUB_TOO_BIG:
// someone sent you a p[acket that this MCU does not have enough FLASH to handle
Serial.printf("ERROR: INBOUND_PUB_TOO_BIG size=%d Max=%d\n",e,mqttClient.getMaxPayloadSize());
break;
case OUTBOUND_PUB_TOO_BIG:
// you tried to send a packet that this MCU does not have enough FLASH to handle
Serial.printf("ERROR: OUTBOUND_PUB_TOO_BIG size=%d Max=%d\n",e,mqttClient.getMaxPayloadSize());
break;
case BOGUS_PACKET: // Your server sent a control packet type unknown to MQTT 3.1.1
// 99.99% unlikely to ever happen, but this message is better than a crash, non?
Serial.printf("ERROR: BOGUS_PACKET TYPE=%02x\n",e,info);
break;
case X_INVALID_LENGTH: // An x function rcvd a msg with an unexpected length: probale data corruption or malicious msg
// 99.99% unlikely to ever happen, but this message is better than a crash, non?
Serial.printf("ERROR: X_INVALID_LENGTH TYPE=%02x\n",e,info);
break;
default:
Serial.printf("UNKNOWN ERROR: %u extra info %d",e,info);
break;
}
} // onMqttError()
void loop() {
MDNS.update();
ArduinoOTA.handle();
} // loop()
// End of File