forked from NimmLor/esp8266-fastled-iot-webserver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
esp8266-fastled-iot-webserver.ino
4947 lines (4321 loc) · 164 KB
/
esp8266-fastled-iot-webserver.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
/*
ESP8266 FastLED WebServer: https://github.com/jasoncoon/esp8266-fastled-webserver
Copyright (C) 2015-2018 Jason Coon
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define FASTLED_INTERRUPT_RETRY_COUNT 1
//#define FASTLED_ALLOW_INTERRUPTS 0
#include <FastLED.h>
FASTLED_USING_NAMESPACE
#include <FS.h>
#ifdef ESP8266
extern "C" {
#include "user_interface.h"
}
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#elif defined(ESP32)
#include <WiFi.h>
#include <SPIFFS.h>
#endif
#include <EEPROM.h>
#include "GradientPalettes.h"
#include "Field.h"
/*
______ _____ ____ ____ ___ _____ _____
/ ____// ___/ / __ \ ( __ )|__ \ / ___/ / ___/
/ __/ \__ \ / /_/ // __ |__/ // __ \ / __ \
/ /___ ___/ // ____// /_/ // __// /_/ // /_/ /
/_____/ /____//_/ \____//____/\____/ \____/
______ ___ _____ ______ __ ______ ____
/ ____// | / ___//_ __// / / ____// __ \
/ /_ / /| | \__ \ / / / / / __/ / / / /
/ __/ / ___ | ___/ / / / / /___ / /___ / /_/ /
/_/ /_/ |_|/____/ /_/ /_____//_____//_____/
____ ____ ______
/ _// __ \/_ __/
/ / / / / / / /
_/ / / /_/ / / /
/___/ \____/ /_/
_ __ ______ ____ _____ ______ ____ _ __ ______ ____
| | / // ____// __ )/ ___/ / ____// __ \| | / // ____// __ \
| | /| / // __/ / __ |\__ \ / __/ / /_/ /| | / // __/ / /_/ /
| |/ |/ // /___ / /_/ /___/ // /___ / _, _/ | |/ // /___ / _, _/
|__/|__//_____//_____//____//_____//_/ |_| |___//_____//_/ |_|
*/
/*######################## MAIN CONFIG ########################*/
#define LED_TYPE WS2812B // You might also use a WS2811 or any other strip that is Fastled compatible
#define DATA_PIN D3 // Be aware: the pin mapping might be different on boards like the NodeMCU
//#define CLK_PIN D5 // Only required when using 4-pin SPI-based LEDs
#define CORRECTION UncorrectedColor // If colors are weird use TypicalLEDStrip
#define COLOR_ORDER GRB // Change this if colors are swapped (in my case, red was swapped with green)
#define MILLI_AMPS 10000 // IMPORTANT: set the max milli-Amps of your power supply (4A = 4000mA)
#define VOLTS 5 // Voltage of the Power Supply
#define LED_DEBUG 0 // enable debug messages on serial console, set to 0 to disable debugging
#define DEFAULT_HOSTNAME "LEDs" // Name that appears in your network, don't use whitespaces, use "-" instead
#define LED_DEVICE_TYPE 0 // The following types are available
/*
0: Generic LED-Strip: a regular LED-Strip without any special arrangement (and Infinity Mirror + Bottle Lighting Pad)
* Easiest: 5V WS2812B LED-Strip: https://s.click.aliexpress.com/e/_dZ1hCJ7
* (Long Ranges) 12V WS2811 LED-Strip: https://s.click.aliexpress.com/e/_d7Ehe3L
* (High-Speed) 5V SK9822 LED-Strip: https://s.click.aliexpress.com/e/_d8pzc89
* (Expensive) 5V APA102 LED-Strip: https://s.click.aliexpress.com/e/_Bf9wVZUD
* (Flexible) 5V WS2812 S LED-Strip: https://s.click.aliexpress.com/e/_d6XxPOH
* Wemos D1 Mini: https://s.click.aliexpress.com/e/_dTVGMGl
* 5V Power Supply: https://s.click.aliexpress.com/e/_dY5zCWt
* Solderless LED-Connector: https://s.click.aliexpress.com/e/_dV4rsjF
* 3D-Printed Wemos-D1 case: https://www.thingiverse.com/thing:3544576
1: LED-Matrix: With a flexible LED-Matrix you can display the audio like a Audio Visualizer
* Flexible WS2812 Matrix: https://s.click.aliexpress.com/e/_d84R5kp
* Wemos D1 Mini: https://s.click.aliexpress.com/e/_dTVGMGl
* 5V Power Supply: https://s.click.aliexpress.com/e/_dY5zCWt
2: 3D-Printed 7-Segment Clock, display the time in a cool 7-segment style, syncs with a ntp of your choice
* unfortunatly the "thing's" description isn't updated yet to the new standalone system
* Project link, small version: https://www.thingiverse.com/thing:3117494
* Project link, large version: https://www.thingiverse.com/thing:2968056
3: 3D-Printed Desk Lamp, a Lamp that reacts to sound for your desk
* Project link, twisted version: https://www.thingiverse.com/thing:4129249
* Project link, round version: https://www.thingiverse.com/thing:3676533
4: 3D-Printed Nanoleafs, a Nanoleaf clone that can be made for cheap
* Project link: https://www.thingiverse.com/thing:3354082
5: 3D-Printed Animated RGB Logos
* Project link, Twenty-One-Pilots: https://www.thingiverse.com/thing:3523487
* Project link, Thingiverse: https://www.thingiverse.com/thing:3531086
*/
//---------------------------------------------------------------------------------------------------------//
// Device Configuration:
//---------------------------------------------------------------------------------------------------------//
#if LED_DEVICE_TYPE == 0 // Generic LED-Strip
#define NUM_LEDS 24
//#define NUM_LEDS 33
//#define NUM_LEDS 183
#define BAND_GROUPING 1 // Groups part of the band to save performance and network traffic
#elif LED_DEVICE_TYPE == 1 // LED MATRIX
#define LENGTH 32
#define HEIGHT 8
//#define AddLogoVisualizers // (only 32x8) Adds Visualization patterns with logo (currently only HBz)
#elif LED_DEVICE_TYPE == 2 // 7-Segment Clock
#define NTP_REFRESH_INTERVAL_SECONDS 600 // 10 minutes
const char* ntpServerName = "at.pool.ntp.org"; // Austrian ntp-timeserver
int t_offset = 1; // offset added to the time from the ntp server
bool updateColorsEverySecond = false; // if set to false it will update colors every minute (time patterns only)
const int NTP_PACKET_SIZE = 48;
bool switchedTimePattern = true;
#define NUM_LEDS 30
#define Digit1 0
#define Digit2 7
#define Digit3 16
#define Digit4 23
// Values for the Big Clock: 58, 0, 14, 30, 44
#elif LED_DEVICE_TYPE == 3 // Desk Lamp
#define LINE_COUNT 8 // Amount of led strip pieces
#define LEDS_PER_LINE 10 // Amount of led pixel per single led strip piece
#elif LED_DEVICE_TYPE == 4 // Nanoleafs
#define LEAFCOUNT 12 // Amount of triangles
#define PIXELS_PER_LEAF 12 // Amount of LEDs inside 1x Tringle
#elif LED_DEVICE_TYPE == 5 // Animated Logos
// Choose your logo below, remove the comment in front of your design
// Important: see "LOGO CONFIG" below
#define TWENTYONEPILOTS
//#define THINGIVERSE // FIXME: THIS IS BROKEN
#endif
//---------------------------------------------------------------------------------------------------------//
// Feature Configuration: Enabled by removing the "//" in front of the define statements
//---------------------------------------------------------------------------------------------------------//
//#define ENABLE_OTA_SUPPORT // requires ArduinoOTA - library, not working on esp's with 1MB memory (esp-01, Wemos D1 lite ...)
//#define OTA_PASSWORD "passwd123" // password that is required to update the esp's firmware wireless
#define ENABLE_MULTICAST_DNS // allows to access the UI via "http://<HOSTNAME>.local/", implemented by GitHub/WarDrake
#define RANDOM_AUTOPLAY_PATTERN // if enabled the next pattern for autoplay is choosen at random
#define AUTOPLAY_IGNORE_UDP_PATTERNS // remove visualization patterns from autoplay
//#define ENABLE_ALEXA_SUPPORT // Espalexa library required
//#define SOUND_SENSOR_SUPPORT // allows to control the leds using a physical sound-sensor, configuration below
//#define ENABLE_SERIAL_AMBILIGHT // allows to function as an ambilight behind a monitor by using data from usb-serial (integration of adalight)
//#define ENABLE_MQTT_SUPPORT // allows integration in homeassistant/googlehome/mqtt
// mqtt server required, see MQTT Configuration for more, implemented by GitHub/WarDrake
//#define ENABLE_UDP_VISUALIZATION // allows to sync the LEDs with pc-music using https://github.com/NimmLor/IoT-Audio-Visualization-Center
//#define ENABLE_HOMEY_SUPPORT // Add support for Homey integration (Athom Homey library required)
//---------------------------------------------------------------------------------------------------------//
/*############ Alexa Configuration ############*/
/* This part configures the devices that can be detected,
* by your Amazon Alexa device. In order to Connect the device,
* open http://ip_of_the_esp8266/alexa in your browser. Or click
* the alexa button in the navbar.
* Afterwards tell say "Alexa, discover devices" to your device,
* after around 30 seconds it should respond with the new devices
* it has detected.
*
* In order to be able to control mutliple parameters of the strip,
* the code must create multiple alexa devices. However you can
* use
*
* To add those extra devices remove the two "//" in front of the,
* defines below.
*
* The Devices with specific pattern, require the corresponding SpecificPatternX
* statement, as argument you have to provide the zero-based index of the `patterns`
* array below. (Hint: CTRL + F -> "patterns =")
*
*/
#ifdef ENABLE_ALEXA_SUPPORT
//#define ALEXA_DEVICE_NAME DEFAULT_HOSTNAME
//#define AddAutoplayDevice ((String)DEFAULT_HOSTNAME + (String)" Autoplay")
//#define AddStrobeDevice ((String)DEFAULT_HOSTNAME + (String)" Strobe")
//#define AddSpecificPatternDeviceA ((String)DEFAULT_HOSTNAME + (String)" Party")
//#define AddSpecificPatternDeviceB ((String)DEFAULT_HOSTNAME + (String)" Chill")
//#define AddSpecificPatternDeviceC ((String)DEFAULT_HOSTNAME + (String)" Rainbow")
//#define AddAudioDevice ((String)DEFAULT_HOSTNAME + (String)" Audio")
//#define SpecificPatternA 37 // Parameter defines what pattern gets executed
//#define SpecificPatternB 12 // Parameter defines what pattern gets executed
//#define SpecificPatternC 0 // Parameter defines what pattern gets executed
//#define AudioPattern 44 // Parameter defines what pattern gets executed
#endif // ENABLE_ALEXA_SUPPORT
/*########## Alexa Configuration END ##########*/
/*######################## ANIMATED RGB LOGO CONFIG ########################*/
#ifdef TWENTYONEPILOTS
#define RING_LENGTH 24 // amount of pixels for the Ring (should be 24)
#define DOUBLE_STRIP_LENGTH 2 // amount of pixels used for the straight double line
#define DOT_LENGTH 1 // amount of pixels used for the dot
#define ITALIC_STRIP_LENGTH 2 // amount of pixels used for the
#define ANIMATION_NAME "Twenty One Pilots - Animated" // name for the Logo animation, displayed on the webserver
#define ANIMATION_NAME_STATIC "Twenty One Pilots - Static" // logo for the static logo, displayed on the webserver
#define ANIMATION_RING_DURATION 30 // longer values result into a longer loop duration
#define STATIC_RING_COLOR CRGB(222,255,5) // Color for the outer ring in static mode
#define STATIC_LOGO_COLOR CRGB(150,240,3) // Color for the inner logo in static mode
/*
Wiring order:
The array below will determine the order of the wiring,
the first value is for the ring, I've hooked it up after the inner part,
so it's the start value is the total length of all other pixels (2+1+2)
the second one is for the vertical double line
in my case it was the first one that is connected to the esp8266,
the third one is for the dot and the fourth one for the angled double line
if you have connected the ring first it should look like this: const int twpOffsets[] = { 0,24,26,27 };
*/
// Syntax: { <RING>, <VERTICAL>, <HORIZONTAL_DOT>, <ANGLED> };
// The values represent the zero-based index on the strip of the element
const int twpOffsets[] = { 5,0,2,3 };
#endif // TWENTYONEPILOTS
#ifdef THINGIVERSE
#define RING_LENGTH 24 // amount of pixels for the Ring (should be 24)
#define HORIZONTAL_LENGTH 3 // amount of pixels used for the straight double line
#define VERTICAL_LENGTH 2 // amount of pixels used for the straight double line
#define ANIMATION_NAME "Thingiverse - Animated" // name for the Logo animation, displayed on the webserver
#define ANIMATION_NAME_STATIC "Thingiverse - Static" // logo for the static logo, displayed on the webserver
#define ANIMATION_RING_DURATION 30 // longer values result into a longer loop duration
#define STATIC_RING_COLOR CRGB(0,149,255) // Color for the outer ring in static mode
#define STATIC_LOGO_COLOR CRGB(0,149,255) // Color for the inner logo in static mode
#define RINGFIRST false // change this to <true> if you have wired the ring first
#define HORIZONTAL_BEFORE_VERTICAL true // change this to <true> if you have wired the horizontal strip before the vertical
#endif // THINGIVERSE
/*###################### ANIMATED RGB LOGO CONFIG END ######################*/
/*-------- SOUND SENSOR (LEGACY) --------*/
#ifdef SOUND_SENSOR_SUPPORT
#define SOUND_SENSOR_PIN A0 // An Analog sensor should be connected to an analog pin
#define SENSOR_TYPE 1 // 0: Dumb Sensors, 1: MAX4466 Sound Sensor, 2: MAX9814 Sound Sensor
// Values for MAX44666:
int16_t audioMinVol = 135; // minimal Voltage from Mic, higher Value = less sensitive
int16_t audioMaxVol = 145; // maximal Voltage from Mic, lower Value = more LED on with lower Volume
#endif
/*------ SOUND SENSOR (LEGACY) END ------*/
/*######################## MQTT Configuration ########################*/
#ifdef ENABLE_MQTT_SUPPORT
// these are deafault settings which can be changed in the web interface "settings" page
#define MQTT_ENABLED 0
#define MQTT_HOSTNAME "homeassistant.local"
#define MQTT_PORT 1883
#define MQTT_USER "MyUserName"
#define MQTT_PASS ""
#define MQTT_TOPIC_SET "/set" // MQTT Topic to subscribe to for changes(Home Assistant)
#if LED_DEVICE_TYPE == 0
#define MQTT_TOPIC "homeassistant/light/ledstrip" // MQTT Topic to Publish to for state and config (Home Assistant)
#define MQTT_DEVICE_NAME "Ledstrip"
#elif LED_DEVICE_TYPE == 1
#define MQTT_TOPIC "homeassistant/light/ledmatrix" // MQTT Topic to Publish to for state and config (Home Assistant)
#define MQTT_DEVICE_NAME "Led Matrix"
#elif LED_DEVICE_TYPE == 2
#define MQTT_TOPIC "homeassistant/light/7-segment-clock" // MQTT Topic to Publish to for state and config (Home Assistant)
#define MQTT_DEVICE_NAME "7 Segment Clock"
#elif LED_DEVICE_TYPE == 3
#define MQTT_TOPIC "homeassistant/light/desklamp" // MQTT Topic to Publish to for state and config (Home Assistant)
#define MQTT_DEVICE_NAME "Led Desk Lamp"
#elif LED_DEVICE_TYPE == 4
#define MQTT_TOPIC "homeassistant/light/nanoleafs" // MQTT Topic to Publish to for state and config (Home Assistant)
#define MQTT_DEVICE_NAME "Nanoleafs"
#elif LED_DEVICE_TYPE == 5
#define MQTT_TOPIC "homeassistant/light/ledlogo" // MQTT Topic to Publish to for state and config (Home Assistant)
#define MQTT_DEVICE_NAME "Animated Logo"
#endif
#define MQTT_UNIQUE_IDENTIFIER WiFi.macAddress() // A Unique Identifier for the device in Homeassistant (MAC Address used by default)
#define MQTT_MAX_PACKET_SIZE 1024
#define MQTT_MAX_TRANSFER_SIZE 1024
#include <PubSubClient.h> // Include the MQTT Library, must be installed via the library manager
#include <ArduinoJson.h>
WiFiClient espClient;
PubSubClient mqttClient(espClient);
#endif
/*###################### MQTT Configuration END ######################*/
/*#########################################################################################################//
-----------------------------------------------------------------------------------------------------------//
_____ ____ _ __ ____ ____ _____ ____ _ __ ___
/ ___// __ \ / |/ // __// _// ___/ / __// |/ // _ \
/ /__ / /_/ // // _/ _/ / / (_ / / _/ / // // /
\___/ \____//_/|_//_/ /___/ \___/ /___//_/|_//____/
-----------------------------------------------------------------------------------------------------------//
###########################################################################################################*/
#define VERSION "4.5"
#define VERSION_DATE "2020-02-14"
// define debugging MACROS
#if LED_DEBUG != 0
#define SERIAL_DEBUG_ADD(s) Serial.print(s);
#define SERIAL_DEBUG_ADDF(format, ...) Serial.printf(format, __VA_ARGS__);
#define SERIAL_DEBUG_EOL Serial.print("\n");
#define SERIAL_DEBUG_BOL Serial.printf("DEBUG [%lu]: ", millis());
#define SERIAL_DEBUG_LN(s) SERIAL_DEBUG_BOL SERIAL_DEBUG_ADD(s) SERIAL_DEBUG_EOL
#define SERIAL_DEBUG_LNF(format, ...) SERIAL_DEBUG_BOL SERIAL_DEBUG_ADDF(format, __VA_ARGS__) SERIAL_DEBUG_EOL
#else
#define SERIAL_DEBUG_ADD(s) do{}while(0);
#define SERIAL_DEBUG_ADDF(format, ...) do{}while(0);
#define SERIAL_DEBUG_EOL do{}while(0);
#define SERIAL_DEBUG_BOL do{}while(0);
#define SERIAL_DEBUG_LN(s) do{}while(0);
#define SERIAL_DEBUG_LNF(format, ...) do{}while(0);
#endif
#ifdef LED_DEVICE_TYPE
#include <WiFiUdp.h>
#if LED_DEVICE_TYPE == 1
#define PACKET_LENGTH LENGTH
#define NUM_LEDS (HEIGHT * LENGTH)
#define PACKET_LENGTH LENGTH
#define BAND_GROUPING 1
#elif LED_DEVICE_TYPE == 2
#define PACKET_LENGTH NUM_LEDS
#define BAND_GROUPING 1
IPAddress timeServerIP;
WiFiUDP udpTime;
byte packetBuffer[NTP_PACKET_SIZE];
int hours = 0; int mins = 0; int secs = 0;
unsigned int localPortTime = 2390;
unsigned long update_timestamp = 0;
unsigned long last_diff = 0;
unsigned long ntp_timestamp = 0;
#elif LED_DEVICE_TYPE == 3
#define NUM_LEDS (LINE_COUNT * LEDS_PER_LINE)
#define PACKET_LENGTH LEDS_PER_LINE
#define BAND_GROUPING 1
#elif LED_DEVICE_TYPE == 4
#define NUM_LEDS (PIXELS_PER_LEAF * LEAFCOUNT)
#define PACKET_LENGTH (LEAFCOUNT * 3)
#define BAND_GROUPING 1
#elif LED_DEVICE_TYPE == 5
#define BAND_GROUPING 1
#ifdef TWENTYONEPILOTS
#define NUM_LEDS (RING_LENGTH+DOT_LENGTH+DOUBLE_STRIP_LENGTH+ITALIC_STRIP_LENGTH)
#endif
#ifdef THINGIVERSE
#define NUM_LEDS (RING_LENGTH+HORIZONTAL_LENGTH+VERTICAL_LENGTH)
#endif
#define PACKET_LENGTH NUM_LEDS
#else
#ifdef BAND_GROUPING
#define PACKET_LENGTH (int)((NUM_LEDS/BAND_GROUPING))
#else
#define PACKET_LENGTH NUM_LEDS
#endif
#endif
// wifi definition
#include <WiFiManager.h> // https://github.com/tzapu/WiFiManager/tree/development
WiFiManager wifiManager;
bool wifiMangerPortalRunning = false;
bool wifiConnected = false;
// Misc Params
#define AVG_ARRAY_SIZE 10
#define BAND_START 0
#define BAND_END 3 // can be increased when working with bigger spectrums (40+)
#define UDP_PORT 4210 // used for UDP visualization
WiFiUDP Udp; // used for NTP and visualization
unsigned int localUdpPort = UDP_PORT; // local port to listen on
uint8_t incomingPacket[PACKET_LENGTH + 1];
#endif
// include config management
#include "config.h"
#ifdef ESP8266
ESP8266WebServer webServer(80);
#elif defined(ESP32)
WebServer webServer(80);
#endif
// #include "FSBrowser.h" currently not used
#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0]))
#define FRAMES_PER_SECOND 120 // here you can control the speed. With the Access Point / Web Server the animations run a bit slower.
#define SOUND_REACTIVE_FPS FRAMES_PER_SECOND
#ifdef ENABLE_OTA_SUPPORT
#include <ArduinoOTA.h>
#endif
#ifdef ENABLE_ALEXA_SUPPORT
#if LED_DEBUG != 0
#define ESPALEXA_DEBUG
#endif
#include <Espalexa.h>
void mainAlexaEvent(EspalexaDevice*);
Espalexa espalexa;
#ifdef ESP8266
ESP8266WebServer webServer2(80);
#elif defined(ESP32)
WebServer webServer2(80);
#endif
EspalexaDevice* alexa_main;
#endif // ENABLE_ALEXA_SUPPORT
#ifdef ENABLE_MULTICAST_DNS
#ifdef ESP8266
#include <ESP8266mDNS.h>
#elif defined(ESP32)
#include <ESPmDNS.h>
#endif //ESP32
#endif // ENABLE_MULTICAST_DNS
#ifdef ENABLE_HOMEY_SUPPORT
#include <Homey.h> //Athom Homey library
#endif
CRGB leds[NUM_LEDS];
const uint8_t brightnessCount = 5;
uint8_t brightnessMap[brightnessCount] = { 5, 32, 64, 128, 255 };
uint8_t brightnessIndex = 3;
// ten seconds per color palette makes a good demo
// 20-120 is better for deployment
uint8_t secondsPerPalette = 10;
// COOLING: How much does the air cool as it rises?
// Less cooling = taller flames. More cooling = shorter flames.
// Default 50, suggested range 20-100
uint8_t cooling = 3;
// SPARKING: What chance (out of 255) is there that a new spark will be lit?
// Higher chance = more roaring fire. Lower chance = more flickery fire.
// Default 120, suggested range 50-200.
uint8_t sparking = 50;
uint8_t speed = 70;
///////////////////////////////////////////////////////////////////////
// Forward declarations of an array of cpt-city gradient palettes, and
// a count of how many there are. The actual color palette definitions
// are at the bottom of this file.
extern const TProgmemRGBGradientPalettePtr gGradientPalettes[];
uint8_t gCurrentPaletteNumber = 0;
CRGBPalette16 gCurrentPalette(CRGB::Black);
CRGBPalette16 gTargetPalette(gGradientPalettes[0]);
CRGBPalette16 IceColors_p = CRGBPalette16(CRGB::Black, CRGB::Blue, CRGB::Aqua, CRGB::White);
uint8_t currentPatternIndex = 2; // Index number of which pattern is current
uint8_t previousPatternIndex = 2; // Index number of last pattern
uint8_t autoplay = 0;
uint8_t autoplayDuration = 10;
unsigned long autoPlayTimeout = 0;
uint8_t currentPaletteIndex = 0;
uint8_t gHue = 0; // rotating "base color" used by many of the patterns
uint8_t slowHue = 0; // slower gHue
uint8_t verySlowHue = 0; // very slow gHue
CRGB solidColor = CRGB::Blue;
typedef struct {
CRGBPalette16 palette;
String name;
} PaletteAndName;
typedef PaletteAndName PaletteAndNameList[];
const CRGBPalette16 palettes[] = {
RainbowColors_p,
RainbowStripeColors_p,
CloudColors_p,
LavaColors_p,
OceanColors_p,
ForestColors_p,
PartyColors_p,
HeatColors_p
};
const uint8_t paletteCount = ARRAY_SIZE(palettes);
const String paletteNames[paletteCount] = {
"Rainbow",
"Rainbow Stripe",
"Cloud",
"Lava",
"Ocean",
"Forest",
"Party",
"Heat",
};
// I just don't know why. Anyone an idea?
void IfThisIsRemovedTheScatchWillFailToBuild(void) {};
typedef void(*Pattern)();
typedef Pattern PatternList[];
typedef struct {
Pattern pattern;
String name;
// these settings decide if certain controls/fields are displayed in the web interface
bool show_palette;
bool show_speed;
bool show_color_picker;
bool show_cooling_sparking;
bool show_twinkle;
} PatternAndName;
typedef PatternAndName PatternAndNameList[];
#include "TwinkleFOX.h"
#include "Twinkles.h"
// List of patterns to cycle through. Each is defined as a separate function below.
PatternAndNameList patterns = {
// Time patterns
#if LED_DEVICE_TYPE == 2 // palet speed color spark twinkle
{ displayTimeStatic, "Time", true, true, true, false, false},
{ displayTimeColorful, "Time Colorful", true, true, false, false, false},
{ displayTimeGradient, "Time Gradient", true, true, false, false, false},
{ displayTimeGradientLarge, "Time Gradient large", true, true, false, false, false},
{ displayTimeRainbow, "Time Rainbow", true, true, false, false, false},
#endif
#if LED_DEVICE_TYPE == 3 // palet speed color spark twinkle
{ pride_Waves, "Pride Waves", true, true, false, false, false},
{ pride_Rings, "Pride Rings", true, true, false, false, false},
{ colorWaves_hori, "Vertical Waves", true, true, false, false, false},
{ colorWaves_vert, "Color Rings", true, true, false, false, false},
{ rainbow_vert, "Vertical Rainbow", true, true, false, false, false},
#endif
// animation patterns // palet speed color spark twinkle
{ pride, "Pride", false, false, false, false, false},
{ colorWaves, "Color Waves", false, false, false, false, false},
{ rainbow, "Horizontal Rainbow", false, true, false, false, false},
{ rainbowSolid, "Solid Rainbow", false, true, false, false, false},
{ confetti, "Confetti", false, true, false, false, false},
{ sinelon, "Sinelon", true, true, false, false, false},
{ bpm, "Beat", true, true, false, false, false},
{ juggle, "Juggle", false, true, false, false, false},
{ fire, "Fire", false, true, false, true, false},
{ water, "Water", false, true, false, true, false},
{ solid_strobe, "Strobe", false, true, true, false, false},
{ rainbow_strobe, "Rainbow Strobe", false, true, false, false, false},
{ smooth_rainbow_strobe, "Smooth Rainbow Strobe", false, true, false, false, false},
// DigitalJohnson patterns // palet speed color spark twinkle
{ rainbowRoll, "Rainbow Roll", false, true, false, false, false},
{ rainbowBeat, "Rainbow Beat", false, true, false, false, false},
{ randomPaletteFades, "Palette Fades", true, true, false, false, false},
{ rainbowChase, "Rainbow Chase", false, true, false, false, false},
{ randomDots, "Rainbow Dots", false, true, false, false, false},
{ randomFades, "Rainbow Fades", false, true, false, false, false},
{ policeLights, "Police Lights", false, true, false, false, false},
{ glitter, "Glitter", false, true, false, false, false},
{ snowFlakes, "Snow Flakes", false, true, false, false, false},
{ lightning, "Lightning", false, false, false, false, false},
// twinkle patterns // palet speed color spark twinkle
{ paletteTwinkles, "Palette Twinkles", true, true, false, false, true},
{ snowTwinkles, "Snow Twinkles", false, true, false, false, true},
{ incandescentTwinkles, "Incandescent Twinkles", false, true, false, false, true},
// TwinkleFOX patterns // palet speed color spark twinkle
{ retroC9Twinkles, "Retro C9 Twinkles", false, true, false, false, true},
{ redWhiteTwinkles, "Red & White Twinkles", false, true, false, false, true},
{ blueWhiteTwinkles, "Blue & White Twinkles", false, true, false, false, true},
{ redGreenWhiteTwinkles, "Red, Green & White Twinkles", false, true, false, false, true},
{ fairyLightTwinkles, "Fairy Light Twinkles", false, true, false, false, true},
{ snow2Twinkles, "Snow 2 Twinkles", false, true, false, false, true},
{ hollyTwinkles, "Holly Twinkles", false, true, false, false, true},
{ iceTwinkles, "Ice Twinkles", false, true, false, false, true},
{ partyTwinkles, "Party Twinkles", false, true, false, false, true},
{ forestTwinkles, "Forest Twinkles", false, true, false, false, true},
{ lavaTwinkles, "Lava Twinkles", false, true, false, false, true},
{ fireTwinkles, "Fire Twinkles", false, true, false, false, true},
{ cloud2Twinkles, "Cloud 2 Twinkles", false, true, false, false, true},
{ oceanTwinkles, "Ocean Twinkles", false, true, false, false, true},
#ifdef ENABLE_UDP_VISUALIZATION
// Visualization Patterns
#if LED_DEVICE_TYPE == 1 // Matrix // palet speed color spark twinkle
{ RainbowVisualizer, "Rainbow Visualization", true, true, false, false, false},
{ SingleColorVisualizer, "Single Color Visualization", true, true, true, false, false},
{ RainbowVisualizerDoubleSided, "Rainbow Visualization Outside", true, true, false, false, false},
{ SingleColorVisualizerDoubleSided, "Single Color Visualization Outside" true, true, true, false, false},
#ifdef AddLogoVisualizers
#if LENGTH == 32 && HEIGHT == 8 // Logo Visualizers
{ HbzVisualizerRainbow, "Hbz Visualizer Spectrum", true, true, false, false, false},
{ HbzVisualizerWhite, "Hbz Visualizer", true, true, false, false, false},
#endif
#endif
#endif
#ifdef LED_DEVICE_TYPE // Generic Visualization Patterns // palet speed color spark twinkle
{ vuMeterSolid, "Solid Volume Visualizer", true, true, false, false, false},
{ vuMeterStaticRainbow, "Static Rainbow Volume Visualizer", true, true, false, false, false},
{ vuMeterRainbow, "Flowing Rainbow Volume Visualizer", true, true, false, false, false},
{ vuMeterTriColor, "Tri-Color Volume Visualizer", true, true, false, false, false},
{ RefreshingVisualizer, "Wave Visualizer", true, true, false, false, false},
{ CentralVisualizer, "Center Visualizer", true, true, false, false, false},
{ SolidColorDualTone, "Solid-Color Pair Bullet Visualizer", true, true, true, false, false},
{ SolidColorComplementary, "Solid-Color Complementary Bullet Visualizer", true, true, true, false, false},
{ BluePurpleBullets, "Blue/Purple Bullet Visualizer", true, true, false, false, false},
{ BulletVisualizer, "Beat-Bullet Visualization", true, true, false, false, false},
//{ RainbowPeaks, "Rainbow Peak Visualizer"}, // broken
{ RainbowBassRings, "Bass Ring Visualizer", true, true, false, false, false},
{ RainbowKickRings, "Kick Ring Visualizer", true, true, false, false, false},
//{ TrailingBulletsVisualizer, "Trailing Bullet Visualization"}, // obsolete
//{ BrightnessVisualizer, "Brightness Visualizer"}, // broken
{ RainbowBandVisualizer, "Rainbow Band Visualizer", true, true, false, false, false},
{ SingleColorBandVisualizer, "Single Color Band Visualizer", true, true, true, false, false},
#endif
#if LED_DEVICE_TYPE == 4 // palet speed color spark twinkle
{ NanoleafWaves, "Nanoleaf Wave Visualizer", true, true, false, false, false},
{ NanoleafBand, "Nanoleaf Rainbow Band Visualizer", true, true, false, false, false},
{ NanoleafSingleBand, "Nanoleaf Solid Color Band Visualizer", true, true, true, false, false},
#endif
#endif // ENABLE_UDP_VISUALIZATION
#ifdef ENABLE_SERIAL_AMBILIGHT // palet speed color spark twinkle
{ ambilight, "⋆Serial Ambilight", true, true, false, false, false},
#endif // ENABLE_SERIAL_AMBILIGHT
#ifdef SOUND_SENSOR_SUPPORT
{ soundReactive, "Sound Reactive", true, true, false, false, false},
#endif
{ showSolidColor, "Solid Color", false, false, true, false, false}
};
const uint8_t patternCount = ARRAY_SIZE(patterns);
#include "Fields.h"
// ######################## define setup() and loop() ####################
void setup() {
#ifdef ESP8266
WiFi.setSleepMode(WIFI_NONE_SLEEP);
#endif
WiFi.mode(WIFI_STA); // avoid creating a seperate AP
Serial.begin(115200);
delay(100);
Serial.print("\n\n");
#if LED_TYPE == WS2812 || LED_TYPE == WS2812B || LED_TYPE == WS2811 || LED_TYPE == WS2813 || LED_TYPE == NEOPIXEL
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); // WS2812 (Neopixel)
#elif defined CLK_PIN
FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_LEDS); // for APA102 (Dotstar)
#else
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_LEDS); // misc. 3-pin
#endif
FastLED.setDither(false);
FastLED.setCorrection(CORRECTION);
FastLED.setBrightness(brightness);
FastLED.setMaxPowerInVoltsAndMilliamps(VOLTS, MILLI_AMPS);
fill_solid(leds, NUM_LEDS, CRGB::Black);
FastLED.show();
// set a default config to be used on config reset
default_cfg.brightness = brightness;
default_cfg.currentPatternIndex = currentPatternIndex;
default_cfg.power = power;
default_cfg.autoplay = autoplay;
default_cfg.autoplayDuration = autoplayDuration;
default_cfg.currentPaletteIndex = currentPaletteIndex;
default_cfg.speed = speed;
loadConfig();
FastLED.setBrightness(brightness);
// irReceiver.enableIRIn(); // Start the receiver
SERIAL_DEBUG_EOL
SERIAL_DEBUG_LN(F("System Information:"))
SERIAL_DEBUG_LNF("Version: %s (%s)", VERSION, VERSION_DATE)
SERIAL_DEBUG_LNF("Heap: %d", system_get_free_heap_size())
SERIAL_DEBUG_LNF("SDK: %s", system_get_sdk_version())
#ifdef ESP8266
SERIAL_DEBUG_LNF("Boot Vers: %d", system_get_boot_version())
SERIAL_DEBUG_LNF("CPU Speed: %d MHz", system_get_cpu_freq())
SERIAL_DEBUG_LNF("Chip ID: %d", system_get_chip_id())
SERIAL_DEBUG_LNF("Flash ID: %d", spi_flash_get_id())
SERIAL_DEBUG_LNF("Flash Size: %dKB", ESP.getFlashChipRealSize())
SERIAL_DEBUG_LNF("Vcc: %d", ESP.getVcc())
#elif defined(ESP32)
SERIAL_DEBUG_LNF("CPU Speed: %d MHz", ESP.getCpuFreqMHz())
SERIAL_DEBUG_LNF("Flash Size: %dKB", ESP.getFlashChipSize())
#endif
SERIAL_DEBUG_LNF("MAC address: %s", WiFi.macAddress().c_str())
SERIAL_DEBUG_EOL
#ifdef SOUND_REACTIVE
#if SENSOR_TYPE == 0
pinMode(SOUND_SENSOR_PIN, INPUT);
#endif
#endif // SOUND_REACTIVE
// starting file system
if (!SPIFFS.begin ()) {
Serial.println(F("An Error has occurred while mounting SPIFFS"));
return;
}
// setting up Wifi
String macID = WiFi.macAddress().substring(12, 14) +
WiFi.macAddress().substring(15, 17);
macID.toUpperCase();
String nameString = String(cfg.hostname) + String(" - ") + macID;
char nameChar[nameString.length() + 1];
nameString.toCharArray(nameChar, sizeof(nameChar));
// setup wifiManager
wifiManager.setHostname(cfg.hostname); // set hostname
wifiManager.setConfigPortalBlocking(false); // config portal is not blocking (LEDs light up in AP mode)
wifiManager.setSaveConfigCallback(handleReboot); // after the wireless settings have been saved a reboot will be performed
#if LED_DEBUG != 0
wifiManager.setDebugOutput(true);
#else
wifiManager.setDebugOutput(false);
#endif
//automatically connect using saved credentials if they exist
//If connection fails it starts an access point with the specified name
if (wifiManager.autoConnect(nameChar)) {
Serial.println("INFO: Wi-Fi connected");
} else {
Serial.printf("INFO: Wi-Fi manager portal running. Connect to the Wi-Fi AP '%s' to configure your wireless connection\n", nameChar);
wifiMangerPortalRunning = true;
}
// FS debug information
// THIS NEEDS TO BE PAST THE WIFI SETUP!! OTHERWISE WIFI SETUP WILL BE DELAYED
#if LED_DEBUG != 0
SERIAL_DEBUG_LN(F("SPIFFS contents:"))
#ifdef ESP8266
Dir dir = SPIFFS.openDir("/");
while (dir.next()) {
SERIAL_DEBUG_LNF("FS File: %s, size: %lu", dir.fileName().c_str(), dir.fileSize())
}
SERIAL_DEBUG_EOL
FSInfo fs_info;
SPIFFS.info(fs_info);
unsigned int totalBytes = fs_info.totalBytes;
unsigned int usedBytes = fs_info.usedBytes;
#elif defined(ESP32)
File root = SPIFFS.open("/");
File file = root.openNextFile();
while (file) {
SERIAL_DEBUG_LNF("FS File: %s, size: %lu", file.name(), file.size())
file = root.openNextFile();
}
SERIAL_DEBUG_EOL
unsigned int totalBytes = SPIFFS.totalBytes();
unsigned int usedBytes = SPIFFS.usedBytes();
#endif
if (usedBytes == 0) {
SERIAL_DEBUG_LN(F("NO WEB SERVER FILES PRESENT! SEE: https://github.com/NimmLor/esp8266-fastled-iot-webserver/blob/master/Software_Installation.md#32-sketch-data-upload\n"))
}
SERIAL_DEBUG_LNF("FS Size: %luKB, used: %luKB, %0.2f%%", \
totalBytes, usedBytes, \
(float) 100 / totalBytes * usedBytes)
SERIAL_DEBUG_EOL
#endif
// print setup details
#ifdef ESP8266
SERIAL_DEBUG_LNF("Arduino Core Version: %s", ARDUINO_ESP8266_RELEASE)
#elif defined(ESP32) && defined(ARDUINO_ESP32_RELEASE)
SERIAL_DEBUG_LNF("Arduino Core Version: %s", ARDUINO_ESP32_RELEASE)
#endif
SERIAL_DEBUG_LN(F("Enabled Features:"))
#ifdef ENABLE_MULTICAST_DNS
SERIAL_DEBUG_LN(F("Feature: mDNS support enabled"))
#endif
#ifdef ENABLE_OTA_SUPPORT
SERIAL_DEBUG_LN(F("Feature: OTA support enabled"))
#endif
#ifdef ENABLE_ALEXA_SUPPORT
SERIAL_DEBUG_LN(F("Feature: Alexa support enabled"))
#endif
#ifdef SOUND_SENSOR_SUPPORT
SERIAL_DEBUG_LN(F("Feature: Sound sensor support enabled"))
#endif
#ifdef ENABLE_MQTT_SUPPORT
SERIAL_DEBUG_LNF("Feature: MQTT support enabled (mqtt version: %s)", String(MQTT_VERSION).c_str())
#endif
#ifdef ENABLE_SERIAL_AMBILIGHT
SERIAL_DEBUG_LN(F("Feature: Serial ambilight support enabled"))
#endif
#ifdef ENABLE_UDP_VISUALIZATION
SERIAL_DEBUG_LN(F("Feature: UDP visualization support enabled"))
#endif
#ifdef ENABLE_HOMEY_SUPPORT
SERIAL_DEBUG_LNF("Feature: Homey support enabled (version: %s)", HOMEYDUINO_VERSION)
#endif
SERIAL_DEBUG_EOL
switch(LED_DEVICE_TYPE) {
case 0: SERIAL_DEBUG_LN("Configured device type: LED strip (0)") break;
case 1: SERIAL_DEBUG_LN("Configured device type: LED MATRIX (1)") break;
case 2: SERIAL_DEBUG_LN("Configured device type: 7-Segment Clock (2)") break;
case 3: SERIAL_DEBUG_LN("Configured device type: Desk Lamp (3)") break;
case 4: SERIAL_DEBUG_LN("Configured device type: Nanoleafs (4)") break;
case 5: SERIAL_DEBUG_LN("Configured device type: Animated Logos (5)") break;
}
SERIAL_DEBUG_LNF("NUM_LEDS: %d", NUM_LEDS)
SERIAL_DEBUG_LNF("BAND_GROUPING: %d", BAND_GROUPING)
SERIAL_DEBUG_LNF("PACKET_LENGTH: %d", PACKET_LENGTH)
#ifdef ENABLE_HOMEY_SUPPORT
//Start Homey library
Homey.begin(cfg.hostname);
Homey.setClass("light");
Homey.addCapability("onoff", homeyLightOnoff); //boolean
Homey.addCapability("dim", homeyLightDim); //number 0.00 - 1.00
Homey.addCapability("light_hue", homeyLightHue); //number 0.00 - 1.00
Homey.addCapability("light_saturation", homeyLightSaturation); //number 0.00 - 1.00
Homey.addCapability("speaker_next", homeyNext); //boolean
Homey.addCapability("speaker_prev", homeyPrev); //boolean
Homey.setCapabilityValue("onoff", cfg.power); //Set initial value
Homey.setCapabilityValue("dim", getBrightnessMapped(0.0f, 1.0f)); //Set initial value
Homey.setCapabilityValue("light_hue", getHueMapped(0.0f, 1.0f)); //Set initial value
Homey.setCapabilityValue("light_saturation", getSatMapped(0.0f, 1.0f)); //Set initial value
#endif
#ifdef ENABLE_OTA_SUPPORT
webServer.on("/ota", HTTP_GET, []() {
IPAddress ip = WiFi.localIP();
String h = "<font face='arial'><h1> OTA Update Mode</h1>";
h += "<h2>Procedure: </h3>";
h += "The UI won't be available until reset.<br>";
h += "<b>Open your Arduino IDE and select the new PORT in Tools menu and upload the code!</b>";
h += "<br>Exit OTA mode: <a href=\"http://" + ip.toString() + "/reboot\"); ' value='Reboot'>Reboot</a>";
h += "</font>";
webServer.send(200, "text/html", h);
delay(100);
ArduinoOTA.setHostname(cfg.hostname);
#ifdef OTA_PASSWORD
ArduinoOTA.setPassword(OTA_PASSWORD);
#endif
ArduinoOTA.onStart([]() {
SPIFFS.end();
if (ArduinoOTA.getCommand() == U_FLASH) {
Serial.println("Start updating sketch");
} else { // U_FS
Serial.println("Start updating filesystem");
}
// NOTE: if updating FS this would be the place to unmount FS using FS.end()
});
ArduinoOTA.onEnd([]() {
Serial.println("\nFinished OTA Update\nRebooting");
delay(500);
ESP.restart();
});
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");
}
});
ArduinoOTA.begin();
delay(100);
while (1) {
ArduinoOTA.handle();
delay(1);
webServer.handleClient();
delay(1);
}
}); // GET /ota
#endif
#ifdef ENABLE_ALEXA_SUPPORT
#ifdef ALEXA_DEVICE_NAME
alexa_main = new EspalexaDevice(ALEXA_DEVICE_NAME, mainAlexaEvent, EspalexaDeviceType::color);
#else
alexa_main = new EspalexaDevice(cfg.hostname, mainAlexaEvent, EspalexaDeviceType::color);
#endif
espalexa.addDevice(alexa_main);
#ifdef AddAutoplayDevice
espalexa.addDevice(AddAutoplayDevice, AlexaAutoplayEvent, EspalexaDeviceType::onoff); //non-dimmable device
#endif
#ifdef AddStrobeDevice
espalexa.addDevice(AddStrobeDevice, AlexaStrobeEvent, EspalexaDeviceType::color); //non-dimmable device
#endif
#ifdef AddSpecificPatternDeviceA
espalexa.addDevice(AddSpecificPatternDeviceA, AlexaSpecificEventA, EspalexaDeviceType::onoff); //non-dimmable device
#endif
#ifdef AddSpecificPatternDeviceB
espalexa.addDevice(AddSpecificPatternDeviceB, AlexaSpecificEventB, EspalexaDeviceType::onoff); //non-dimmable device
#endif
#ifdef AddSpecificPatternDeviceC
espalexa.addDevice(AddSpecificPatternDeviceC, AlexaSpecificEventC, EspalexaDeviceType::onoff); //non-dimmable device
#endif
#ifdef AddAudioDevice
espalexa.addDevice(AddAudioDevice, AlexaAudioEvent, EspalexaDeviceType::onoff); //non-dimmable device
#endif
webServer.onNotFound([]() {
if (!espalexa.handleAlexaApiCall(webServer.uri(), webServer.arg(0))) //if you don't know the URI, ask espalexa whether it is an Alexa control request
{
//whatever you want to do with 404s
webServer.send(404, "text/plain", "Not found");
}
});
addRebootPage(0);
webServer.on("/alexa", HTTP_GET, []() {
IPAddress ip = WiFi.localIP();
String h = "<font face='arial'><h1> Alexa pairing mode</h1>";
h += "<h2>Procedure: </h3>";
h += "The webserver will reboot and the UI won't be available.<br>";
h += "<b>Now. Say to Alexa: 'Alexa, discover devices'.<b><br><br>";
h += "Alexa should tell you that it found a new device, if it did reset the esp8266 to return to the normal mode.";
h += "<br>Exit pairing mode: <a href=\"http://" + ip.toString() + "/reboot\"); ' value='Reboot'>Reboot</a>";
h += "</font>";
webServer.send(200, "text/html", h);
webServer2.on("/alexa", [&]() {webServer2.send(200, "text/html", h); });
delay(100);
webServer.stop();
delay(500);
webServer.close();
delay(500);
webServer2.onNotFound([]() {
if (!espalexa.handleAlexaApiCall(webServer2.uri(), webServer2.arg(0))) //if you don't know the URI, ask espalexa whether it is an Alexa control request
{
//whatever you want to do with 404s
webServer2.send(404, "text/plain", "Not found");
}
});
addRebootPage(2);
delay(100);