-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathenLIGHTen-LED-Clock.ino
1284 lines (1132 loc) · 41.9 KB
/
enLIGHTen-LED-Clock.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
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "definitions.h"
#include "version.h"
// ***************************************************************************
// Load libraries for: WebServer / WiFiManager / WebSockets
// ***************************************************************************
#include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino
#include <NtpClientLib.h>
// needed for library WiFiManager
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //https://github.com/tzapu/WiFiManager
#include <WiFiClient.h>
#include <ESP8266mDNS.h>
#include <FS.h>
#include <EEPROM.h>
#include <Timezone.h>
#include <WebSockets.h> //https://github.com/Links2004/arduinoWebSockets
#include <WebSocketsServer.h>
TimeChangeRule myDST = {"EDT", Second, Sun, Mar, 2, 0}; // Daylight time = UTC - 4 hours
TimeChangeRule mySTD = {"EST", First, Sun, Nov, 2, -60}; // Standard time = UTC - 5 hours
Timezone myTZ(myDST, mySTD);
TimeChangeRule *tcr;
int hour_hand = 3, timezflag, minute_hand, second_hand, previous_second, previous_minute, previous_hour, looptimer, flourishtime = 10, timezone = -5, hoursmall = 0, hourtall = 0;
int clockmode = 2, timerflag = 99, interuptflag = 1, hourchanged = 0, minchanged = 0, secchanged = 0, secondhandstate = 1;
int playground = 0, decayline = 120, nightlevel = 20;
int ipint = 0;
int stripoffset = 100;
char ipstring[20];
uint8_t LEDr, LEDg, LEDb;
// OTA
#ifdef ENABLE_OTA
#include <WiFiUdp.h>
#include <ArduinoOTA.h>
#endif
//SPIFFS Save
#if !defined(ENABLE_HOMEASSISTANT) and defined(ENABLE_STATE_SAVE_SPIFFS)
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#endif
// MQTT
#ifdef ENABLE_MQTT
#include <PubSubClient.h>
#ifdef ENABLE_HOMEASSISTANT
#include <ArduinoJson.h> //https://github.com/bblanchon/ArduinoJson
#endif
WiFiClient espClient;
PubSubClient mqtt_client(espClient);
#endif
#ifdef ENABLE_AMQTT
#include <AsyncMqttClient.h> //https://github.com/marvinroger/async-mqtt-client
//https://github.com/me-no-dev/ESPAsyncTCP
#ifdef ENABLE_HOMEASSISTANT
#include <ArduinoJson.h>
#endif
AsyncMqttClient amqttClient;
WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
#endif
// ***************************************************************************
// Instanciate HTTP(80) / WebSockets(81) Server
// ***************************************************************************
ESP8266WebServer server(80);
WebSocketsServer webSocket = WebSocketsServer(81);
#ifdef HTTP_OTA
#include <ESP8266HTTPUpdateServer.h>
ESP8266HTTPUpdateServer httpUpdater;
#endif
#ifdef USE_NEOANIMATIONFX
// ***************************************************************************
// Load libraries / Instanciate NeoAnimationFX library
// ***************************************************************************
// https://github.com/debsahu/NeoAnimationFX
#include "NeoAnimationFX.h"
#define NEOMETHOD NeoPBBGRB800
NEOMETHOD neoStrip(220);
NeoAnimationFX<NEOMETHOD> strip(neoStrip);
// Uses Pin RX / GPIO3 (Only pin that is supported, due to hardware limitations)
// NEOMETHOD NeoPBBGRB800 uses GRB config 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEOMETHOD NeoPBBGRB400 uses GRB config 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEOMETHOD NeoPBBRGB800 uses RGB config 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEOMETHOD NeoPBBRGB400 uses RGB config 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// Uses Pin D4 / GPIO2 (Only pin that is supported, due to hardware limitations)
// NEOMETHOD NeoPBBGRBU800 uses GRB config 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEOMETHOD NeoPBBGRBU400 uses GRB config 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEOMETHOD NeoPBBRGBU800 uses RGB config 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEOMETHOD NeoPBBRGBU400 uses RGB config 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
#endif
#ifdef USE_WS2812FX
// ***************************************************************************
// Load libraries / Instanciate WS2812FX library
// ***************************************************************************
// https://github.com/kitesurfer1404/WS2812FX
#include <WS2812FX.h>
WS2812FX strip = WS2812FX(NUMLEDS, PIN, NEO_GRB + NEO_KHZ800);
// Parameter 1 = number of pixels in strip
// Parameter 2 = Arduino pin number (most are valid)
// Parameter 3 = pixel type flags, add together as needed:
// NEO_KHZ800 800 KHz bitstream (most NeoPixel products w/WS2812 LEDs)
// NEO_KHZ400 400 KHz (classic 'v1' (not v2) FLORA pixels, WS2811 drivers)
// NEO_GRB Pixels are wired for GRB bitstream (most NeoPixel products)
// NEO_RGB Pixels are wired for RGB bitstream (v1 FLORA pixels, not v2)
// IMPORTANT: To reduce NeoPixel burnout risk, add 1000 uF capacitor across
// pixel power leads, add 300 - 500 Ohm resistor on first pixel's data input
// and minimize distance between Arduino and first pixel. Avoid connecting
// on a live circuit...if you must, connect GND first.
#endif
// ***************************************************************************
// Load library "ticker" for blinking status led
// ***************************************************************************
#include <Ticker.h>
Ticker ticker;
#ifdef ENABLE_HOMEASSISTANT
Ticker ha_send_data;
#endif
#ifdef ENABLE_AMQTT
Ticker mqttReconnectTimer;
Ticker wifiReconnectTimer;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
Ticker spiffs_save_state;
#endif
void tick()
{
//toggle state
int state = digitalRead(BUILTIN_LED); // get the current state of GPIO1 pin
digitalWrite(BUILTIN_LED, !state); // set pin to the opposite state
}
#ifdef ENABLE_STATE_SAVE_EEPROM
// ***************************************************************************
// EEPROM helper
// ***************************************************************************
String readEEPROM(int offset, int len) {
String res = "";
for (int i = 0; i < len; ++i)
{
res += char(EEPROM.read(i + offset));
//DBG_OUTPUT_PORT.println(char(EEPROM.read(i + offset)));
}
DBG_OUTPUT_PORT.printf("readEEPROM(): %s\n", res.c_str());
return res;
}
void writeEEPROM(int offset, int len, String value) {
DBG_OUTPUT_PORT.printf("writeEEPROM(): %s\n", value.c_str());
for (int i = 0; i < len; ++i)
{
if (i < value.length()) {
EEPROM.write(i + offset, value[i]);
} else {
EEPROM.write(i + offset, NULL);
}
}
}
#endif
// ***************************************************************************
// Saved state handling
// ***************************************************************************
// https://stackoverflow.com/questions/9072320/split-string-into-string-array
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]) : "";
}
// ***************************************************************************
// Callback for WiFiManager library when config mode is entered
// ***************************************************************************
//gets called when WiFiManager enters configuration mode
void configModeCallback (WiFiManager *myWiFiManager) {
DBG_OUTPUT_PORT.println("Entered config mode");
DBG_OUTPUT_PORT.println(WiFi.softAPIP());
//if you used auto generated SSID, print it
DBG_OUTPUT_PORT.println(myWiFiManager->getConfigPortalSSID());
//entered config mode, make led toggle faster
ticker.attach(0.2, tick);
uint16_t i;
for (i = 0; i < 220; i++) {
strip.setPixelColor(i, 0, 0, 255);
}
strip.show();
}
//callback notifying us of the need to save config
void saveConfigCallback () {
DBG_OUTPUT_PORT.println("Should save config");
shouldSaveConfig = true;
}
// ***************************************************************************
// Include: Webserver
// ***************************************************************************
#include "spiffs_webserver.h"
// ***************************************************************************
// Include: Request handlers
// ***************************************************************************
#include "request_handlers.h"
// ***************************************************************************
// Include: Color modes
// ***************************************************************************
#ifdef ENABLE_LEGACY_ANIMATIONS
#include "colormodes.h"
#endif
// ***************************************************************************
// MAIN
// ***************************************************************************
void setup() {
// system_update_cpu_freq(160);
NTP.begin("es.pool.ntp.org", 0 , true); // get time from NTP server pool.
NTP.setInterval(63);
setTime(myTZ.toUTC(compileTime()));
DBG_OUTPUT_PORT.begin(115200);
EEPROM.begin(512);
// set builtin led pin as output
pinMode(BUILTIN_LED, OUTPUT);
// button pin setup
#ifdef ENABLE_BUTTON
pinMode(BUTTON,INPUT_PULLUP);
#endif
// start ticker with 0.5 because we start in AP mode and try to connect
ticker.attach(0.5, tick);
// ***************************************************************************
// Setup: SPIFFS
// ***************************************************************************
SPIFFS.begin();
{
Dir dir = SPIFFS.openDir("/");
while (dir.next()) {
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
DBG_OUTPUT_PORT.printf("FS File: %s, size: %s\n", fileName.c_str(), formatBytes(fileSize).c_str());
}
FSInfo fs_info;
SPIFFS.info(fs_info);
DBG_OUTPUT_PORT.printf("FS Usage: %d/%d bytes\n\n", fs_info.usedBytes, fs_info.totalBytes);
}
wifi_station_set_hostname(const_cast<char*>(HOSTNAME));
// ***************************************************************************
// Setup: Neopixel
// ***************************************************************************
strip.init();
strip.setBrightness(brightness);
strip.setSpeed(convertSpeed(ws2812fx_speed));
//strip.setMode(FX_MODE_RAINBOW_CYCLE);
strip.setColor(main_color.red, main_color.green, main_color.blue);
strip.start();
// ***************************************************************************
// Setup: WiFiManager
// ***************************************************************************
// The extra parameters to be configured (can be either global or just in the setup)
// After connecting, parameter.getValue() will get you the configured value
// id/name placeholder/prompt default length
#if defined(ENABLE_MQTT) or defined(ENABLE_AMQTT)
#if defined(ENABLE_STATE_SAVE_SPIFFS) and (defined(ENABLE_MQTT) or defined(ENABLE_AMQTT))
(readConfigFS()) ? DBG_OUTPUT_PORT.println("WiFiManager config FS Read success!"): DBG_OUTPUT_PORT.println("WiFiManager config FS Read failure!");
#else
String settings_available = readEEPROM(134, 1);
if (settings_available == "1") {
readEEPROM(0, 64).toCharArray(mqtt_host, 64); // 0-63
readEEPROM(64, 6).toCharArray(mqtt_port, 6); // 64-69
readEEPROM(70, 32).toCharArray(mqtt_user, 32); // 70-101
readEEPROM(102, 32).toCharArray(mqtt_pass, 32); // 102-133
DBG_OUTPUT_PORT.printf("MQTT host: %s\n", mqtt_host);
DBG_OUTPUT_PORT.printf("MQTT port: %s\n", mqtt_port);
DBG_OUTPUT_PORT.printf("MQTT user: %s\n", mqtt_user);
DBG_OUTPUT_PORT.printf("MQTT pass: %s\n", mqtt_pass);
}
#endif
WiFiManagerParameter custom_mqtt_host("host", "MQTT hostname", mqtt_host, 64);
WiFiManagerParameter custom_mqtt_port("port", "MQTT port", mqtt_port, 6);
WiFiManagerParameter custom_mqtt_user("user", "MQTT user", mqtt_user, 32);
WiFiManagerParameter custom_mqtt_pass("pass", "MQTT pass", mqtt_pass, 32);
#endif
//Local intialization. Once its business is done, there is no need to keep it around
WiFiManager wifiManager;
//reset settings - for testing
//wifiManager.resetSettings();
//set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode
wifiManager.setAPCallback(configModeCallback);
#if defined(ENABLE_MQTT) or defined(ENABLE_AMQTT)
//set config save notify callback
wifiManager.setSaveConfigCallback(saveConfigCallback);
//add all your parameters here
wifiManager.addParameter(&custom_mqtt_host);
wifiManager.addParameter(&custom_mqtt_port);
wifiManager.addParameter(&custom_mqtt_user);
wifiManager.addParameter(&custom_mqtt_pass);
#endif
WiFi.setSleepMode(WIFI_NONE_SLEEP);
// Uncomment if you want to restart ESP8266 if it cannot connect to WiFi.
// Value in brackets is in seconds that WiFiManger waits until restart
//wifiManager.setConfigPortalTimeout(180);
// Uncomment if you want to set static IP
// Order is: IP, Gateway and Subnet
//wifiManager.setSTAStaticIPConfig(IPAddress(192,168,0,128), IPAddress(192,168,0,1), IPAddress(255,255,255,0));
//fetches ssid and pass and tries to connect
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP"
//and goes into a blocking loop awaiting configuration
if (!wifiManager.autoConnect(HOSTNAME)) {
DBG_OUTPUT_PORT.println("failed to connect and hit timeout");
//reset and try again, or maybe put it to deep sleep
ESP.reset(); //Will be removed when upgrading to standalone offline McLightingUI version
delay(1000); //Will be removed when upgrading to standalone offline McLightingUI version
}
#if defined(ENABLE_MQTT) or defined(ENABLE_AMQTT)
//read updated parameters
strcpy(mqtt_host, custom_mqtt_host.getValue());
strcpy(mqtt_port, custom_mqtt_port.getValue());
strcpy(mqtt_user, custom_mqtt_user.getValue());
strcpy(mqtt_pass, custom_mqtt_pass.getValue());
//save the custom parameters to FS
#if defined(ENABLE_STATE_SAVE_SPIFFS) and (defined(ENABLE_MQTT) or defined(ENABLE_AMQTT))
(writeConfigFS(shouldSaveConfig)) ? DBG_OUTPUT_PORT.println("WiFiManager config FS Save success!"): DBG_OUTPUT_PORT.println("WiFiManager config FS Save failure!");
#else if defined(ENABLE_STATE_SAVE_EEPROM)
if (shouldSaveConfig) {
DBG_OUTPUT_PORT.println("Saving WiFiManager config");
writeEEPROM(0, 64, mqtt_host); // 0-63
writeEEPROM(64, 6, mqtt_port); // 64-69
writeEEPROM(70, 32, mqtt_user); // 70-101
writeEEPROM(102, 32, mqtt_pass); // 102-133
writeEEPROM(134, 1, "1"); // 134 --> always "1"
EEPROM.commit();
}
#endif
#endif
#ifdef ENABLE_AMQTT
wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWifiDisconnect);
#endif
//if you get here you have connected to the WiFi
DBG_OUTPUT_PORT.println("connected...yeey :)");
ticker.detach();
//keep LED on
digitalWrite(BUILTIN_LED, LOW);
// ***************************************************************************
// Configure OTA
// ***************************************************************************
#ifdef ENABLE_OTA
DBG_OUTPUT_PORT.println("Arduino OTA activated.");
// Port defaults to 8266
ArduinoOTA.setPort(8266);
// Hostname defaults to esp8266-[ChipID]
ArduinoOTA.setHostname(HOSTNAME);
// No authentication by default
// ArduinoOTA.setPassword("admin");
// Password can be set with it's md5 value as well
// MD5(admin) = 21232f297a57a5a743894a0e4a801fc3
// ArduinoOTA.setPasswordHash("21232f297a57a5a743894a0e4a801fc3");
ArduinoOTA.onStart([]() {
DBG_OUTPUT_PORT.println("Arduino OTA: Start updating");
});
ArduinoOTA.onEnd([]() {
DBG_OUTPUT_PORT.println("Arduino OTA: End");
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
DBG_OUTPUT_PORT.printf("Arduino OTA Progress: %u%%\r", (progress / (total / 100)));
});
ArduinoOTA.onError([](ota_error_t error) {
DBG_OUTPUT_PORT.printf("Arduino OTA Error[%u]: ", error);
if (error == OTA_AUTH_ERROR) DBG_OUTPUT_PORT.println("Arduino OTA: Auth Failed");
else if (error == OTA_BEGIN_ERROR) DBG_OUTPUT_PORT.println("Arduino OTA: Begin Failed");
else if (error == OTA_CONNECT_ERROR) DBG_OUTPUT_PORT.println("Arduino OTA: Connect Failed");
else if (error == OTA_RECEIVE_ERROR) DBG_OUTPUT_PORT.println("Arduino OTA: Receive Failed");
else if (error == OTA_END_ERROR) DBG_OUTPUT_PORT.println("Arduino OTA: End Failed");
});
ArduinoOTA.begin();
DBG_OUTPUT_PORT.println("");
#endif
// ***************************************************************************
// Configure MQTT
// ***************************************************************************
#ifdef ENABLE_MQTT
if (mqtt_host != "" && atoi(mqtt_port) > 0) {
snprintf(mqtt_intopic, sizeof mqtt_intopic, "%s/in", HOSTNAME);
snprintf(mqtt_outtopic, sizeof mqtt_outtopic, "%s/out", HOSTNAME);
DBG_OUTPUT_PORT.printf("MQTT active: %s:%d\n", mqtt_host, String(mqtt_port).toInt());
mqtt_client.setServer(mqtt_host, atoi(mqtt_port));
mqtt_client.setCallback(mqtt_callback);
}
#endif
#ifdef ENABLE_AMQTT
if (mqtt_host != "" && atoi(mqtt_port) > 0) {
amqttClient.onConnect(onMqttConnect);
amqttClient.onDisconnect(onMqttDisconnect);
amqttClient.onMessage(onMqttMessage);
amqttClient.setServer(mqtt_host, atoi(mqtt_port));
if (mqtt_user != "" or mqtt_pass != "") amqttClient.setCredentials(mqtt_user, mqtt_pass);
amqttClient.setClientId(mqtt_clientid);
connectToMqtt();
}
#endif
// #ifdef ENABLE_HOMEASSISTANT
// ha_send_data.attach(5, tickerSendState); // Send HA data back only every 5 sec
// #endif
// ***************************************************************************
// Setup: MDNS responder
// ***************************************************************************
bool mdns_result = MDNS.begin(HOSTNAME);
DBG_OUTPUT_PORT.print("Open http://");
DBG_OUTPUT_PORT.print(WiFi.localIP());
DBG_OUTPUT_PORT.println("/ to open McLighting.");
DBG_OUTPUT_PORT.print("Use http://");
DBG_OUTPUT_PORT.print(HOSTNAME);
DBG_OUTPUT_PORT.println(".local/ when you have Bonjour installed.");
DBG_OUTPUT_PORT.print("New users: Open http://");
DBG_OUTPUT_PORT.print(WiFi.localIP());
DBG_OUTPUT_PORT.println("/upload to upload the webpages first.");
DBG_OUTPUT_PORT.println("");
char buffer[100];
sprintf(buffer, WiFi.localIP().toString().c_str());
DBG_OUTPUT_PORT.print(buffer);
int rcol = -80;
int gcol = 0;
int bcol = 0;
for (int z=0; z<15; z++){ //output ip address so users know where to connect.
DBG_OUTPUT_PORT.println("");
DBG_OUTPUT_PORT.println(buffer[z]);
delay(300);
for (byte i = 0; i <= NUMLEDSECS; i++) {
strip.setPixelColor(i+stripoffset, 0, 0, 0);
}
delay(0);
strip.show();
clearNumbers();
delay(300);
rcol = rcol + 90;
gcol = gcol + 50;
bcol = bcol + 137;
if(rcol > 250){
rcol = rcol - 250;
}
if(gcol > 250){
gcol = gcol -250;
}
if(bcol > 250){
bcol = bcol - 250;
}
main_color.red=rcol;
main_color.green =gcol;
main_color.blue = bcol;
if(buffer[z]=='1'){
one();
}
if(buffer[z]=='2'){
two();
}
if(buffer[z]=='3'){
three();
}
if(buffer[z]=='4'){
four();
}
if(buffer[z]=='5'){
five();
}
if(buffer[z]=='6'){
six();
}
if(buffer[z]=='7'){
seven();
}
if(buffer[z]=='8'){
eight();
}
if(buffer[z]=='9'){
nine();
}
if(buffer[z]=='0'){
zero();
}
if(buffer[z]=='.'){
dot();
}
}
// ***************************************************************************
// Setup: WebSocket server
// ***************************************************************************
webSocket.begin();
webSocket.onEvent(webSocketEvent);
// ***************************************************************************
// Setup: SPIFFS Webserver handler
// ***************************************************************************
//list directory
server.on("/list", HTTP_GET, handleFileList);
//load editor
server.on("/edit", HTTP_GET, []() {
if (!handleFileRead("/edit.htm")) server.send(404, "text/plain", "FileNotFound");
});
//create file
server.on("/edit", HTTP_PUT, handleFileCreate);
//delete file
server.on("/edit", HTTP_DELETE, handleFileDelete);
//first callback is called after the request has ended with all parsed arguments
//second callback handles file uploads at that location
server.on("/edit", HTTP_POST, []() {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", "");
}, handleFileUpload);
//get heap status, analog input value and all GPIO statuses in one json call
server.on("/esp_status", HTTP_GET, []() {
DynamicJsonDocument jsonBuffer;
JsonObject json = jsonBuffer.to<JsonObject>();
json["HOSTNAME"] = HOSTNAME;
json["version"] = SKETCH_VERSION;
json["heap"] = ESP.getFreeHeap();
json["sketch_size"] = ESP.getSketchSize();
json["free_sketch_space"] = ESP.getFreeSketchSpace();
json["flash_chip_size"] = ESP.getFlashChipSize();
json["flash_chip_real_size"] = ESP.getFlashChipRealSize();
json["flash_chip_speed"] = ESP.getFlashChipSpeed();
json["sdk_version"] = ESP.getSdkVersion();
json["core_version"] = ESP.getCoreVersion();
json["cpu_freq"] = ESP.getCpuFreqMHz();
json["chip_id"] = ESP.getFlashChipId();
#ifndef USE_NEOANIMATIONFX
json["animation_lib"] = "WS2812FX";
json["pin"] = PIN;
#else
json["animation_lib"] = "NeoAnimationFX";
json["pin"] = "Ignored, check NEOMETHOD";
#endif
json["number_leds"] = NUMLEDS;
#ifdef ENABLE_BUTTON
json["button_mode"] = "ON";
#else
json["button_mode"] = "OFF";
#endif
#ifdef ENABLE_AMQTT
json["amqtt"] = "ON";
#endif
#ifdef ENABLE_MQTT
json["mqtt"] = "ON";
#endif
#ifdef ENABLE_HOMEASSISTANT
json["home_assistant"] = "ON";
#else
json["home_assistant"] = "OFF";
#endif
#ifdef ENABLE_LEGACY_ANIMATIONS
json["legacy_animations"] = "ON";
#else
json["legacy_animations"] = "OFF";
#endif
#ifdef HTTP_OTA
json["esp8266_http_updateserver"] = "ON";
#endif
#ifdef ENABLE_OTA
json["arduino_ota"] = "ON";
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
json["state_save"] = "SPIFFS";
#endif
#ifdef ENABLE_STATE_SAVE_EEPROM
json["state_save"] = "EEPROM";
#endif
String json_str;
serializeJson(json, json_str);
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "application/json", json_str);
});
//called when the url is not defined here
//use it to load content from SPIFFS
server.onNotFound([]() {
if (!handleFileRead(server.uri()))
handleNotFound();
});
server.on("/upload", handleMinimalUpload);
server.on("/restart", []() {
DBG_OUTPUT_PORT.printf("/restart\n");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", "restarting..." );
ESP.restart();
});
server.on("/reset_wlan", []() {
DBG_OUTPUT_PORT.printf("/reset_wlan\n");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", "Resetting WLAN and restarting..." );
WiFiManager wifiManager;
wifiManager.resetSettings();
ESP.restart();
});
server.on("/start_config_ap", []() {
DBG_OUTPUT_PORT.printf("/start_config_ap\n");
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", "Starting config AP ..." );
WiFiManager wifiManager;
wifiManager.startConfigPortal(HOSTNAME);
});
// ***************************************************************************
// Setup: SPIFFS Webserver handler
// ***************************************************************************
server.on("/set_brightness", []() {
getArgs();
mode = BRIGHTNESS;
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String(String("OK %") + String(brightness)).c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String(String("OK %") + String(brightness)).c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
if(!ha_send_data.active()) ha_send_data.once(5, tickerSendState);
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
getStatusJSON();
});
server.on("/get_brightness", []() {
String str_brightness = String((int) (brightness / 2.55));
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", str_brightness );
DBG_OUTPUT_PORT.print("/get_brightness: ");
DBG_OUTPUT_PORT.println(str_brightness);
});
server.on("/set_speed", []() {
if (server.arg("d").toInt() >= 0) {
ws2812fx_speed = server.arg("d").toInt();
ws2812fx_speed = constrain(ws2812fx_speed, 0, 255);
strip.setSpeed(convertSpeed(ws2812fx_speed));
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String(String("OK ?") + String(ws2812fx_speed)).c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String(String("OK ?") + String(ws2812fx_speed)).c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
if(!ha_send_data.active()) ha_send_data.once(5, tickerSendState);
#endif
}
getStatusJSON();
});
server.on("/get_speed", []() {
String str_speed = String(ws2812fx_speed);
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", str_speed );
DBG_OUTPUT_PORT.print("/get_speed: ");
DBG_OUTPUT_PORT.println(str_speed);
});
server.on("/get_switch", []() {
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", (mode == OFF) ? "0" : "1" );
DBG_OUTPUT_PORT.printf("/get_switch: %s\n", (mode == OFF) ? "0" : "1");
});
server.on("/get_color", []() {
char rgbcolor[7];
snprintf(rgbcolor, sizeof(rgbcolor), "%02X%02X%02X", main_color.red, main_color.green, main_color.blue);
server.sendHeader("Access-Control-Allow-Origin", "*");
server.send(200, "text/plain", rgbcolor );
DBG_OUTPUT_PORT.print("/get_color: ");
DBG_OUTPUT_PORT.println(rgbcolor);
});
server.on("/status", []() {
getStatusJSON();
});
server.on("/off", []() {
#ifdef ENABLE_LEGACY_ANIMATIONS
exit_func = true;
#endif
mode = OFF;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =off").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =off").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = false;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
server.on("/all", []() {
#ifdef ENABLE_LEGACY_ANIMATIONS
exit_func = true;
#endif
ws2812fx_mode = FX_MODE_STATIC;
mode = SET_MODE;
//mode = ALL;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =all").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =all").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
#ifdef ENABLE_LEGACY_ANIMATIONS
server.on("/wipe", []() {
exit_func = true;
mode = WIPE;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =wipe").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =wipe").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
server.on("/rainbow", []() {
exit_func = true;
mode = RAINBOW;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =rainbow").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =rainbow").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
server.on("/rainbowCycle", []() {
exit_func = true;
mode = RAINBOWCYCLE;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =rainbowCycle").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =rainbowCycle").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
server.on("/theaterchase", []() {
exit_func = true;
mode = THEATERCHASE;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =theaterchase").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =theaterchase").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
server.on("/twinkleRandom", []() {
exit_func = true;
mode = TWINKLERANDOM;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =twinkleRandom").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =twinkleRandom").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
server.on("/theaterchaseRainbow", []() {
exit_func = true;
mode = THEATERCHASERAINBOW;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =theaterchaseRainbow").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =theaterchaseRainbow").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
server.on("/tv", []() {
exit_func = true;
mode = TV;
getArgs();
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String("OK =tv").c_str());
#endif
#ifdef ENABLE_AMQTT
amqttClient.publish(mqtt_outtopic.c_str(), qospub, false, String("OK =tv").c_str());
#endif
#ifdef ENABLE_HOMEASSISTANT
stateOn = true;
#endif
#ifdef ENABLE_STATE_SAVE_SPIFFS
if(!spiffs_save_state.active()) spiffs_save_state.once(3, tickerSpiffsSaveState);
#endif
});
#endif
server.on("/get_dimflag", []() {
String str_dimflag = "[";
str_dimflag += "{\"mode\":";
str_dimflag += String ((int) strip.getMode());
str_dimflag += ", \"name\":\"";
str_dimflag += "clockmode";
str_dimflag += "\"},";
str_dimflag += "{\"mode\":";
str_dimflag += String ((int)(clockmode));
str_dimflag += ", \"name\":\"";
str_dimflag += "ringmode";
str_dimflag += "\"},";
str_dimflag += "{\"mode\":";
str_dimflag += String ((int) (ws2812fx_speed));
str_dimflag += ", \"name\":\"";
str_dimflag += "speed";
str_dimflag += "\"},";
str_dimflag += "{\"mode\":";
str_dimflag += String ((int) (brightness));
str_dimflag += ", \"name\":\"";
str_dimflag += "brightness";
str_dimflag += "\"},";
str_dimflag += "{\"mode\":";
str_dimflag += String((int) (dimflag));
str_dimflag += ", \"name\":\"";
str_dimflag += "dimflag";
str_dimflag += "\"},";
str_dimflag += "{\"mode\":";
str_dimflag += String ((int) (arcflag));
str_dimflag += ", \"name\":\"";
str_dimflag += "arcflag";
str_dimflag += "\"},";
str_dimflag += "{\"mode\":";
str_dimflag += String ((int) (secondhandstate));
str_dimflag += ", \"name\":\"";
str_dimflag += "secondhandstate";
str_dimflag += "\"},";
str_dimflag += "{\"mode\":";
str_dimflag += String ((int) (dayflag));
str_dimflag += ", \"name\":\"";
str_dimflag += "dayflag";
str_dimflag += "\"},";
str_dimflag += "{}]";
// String str_dimflag = String ((int) strip.getMode()) + "," + String ((int) (ws2812fx_speed)) + "," + String ((int) (brightness)) + "," + String ((int) (clockmode)) + "," + String((int) (dimflag)) + "," + String ((int) (arcflag)) + "," + String ((int) (secondhandstate)) + "," + String ((int) (dayflag));
server.send(200, "application/json", str_dimflag );
});
server.on("/get_modes", []() {
getModesJSON();
});
server.on("/set_mode", []() {
getArgs();
mode = SET_MODE;
getStatusJSON();
#ifdef ENABLE_MQTT
mqtt_client.publish(mqtt_outtopic, String(String("OK /") + String(ws2812fx_mode)).c_str());