/
esp8266-fastled-webserver.ino
1693 lines (1403 loc) · 53.7 KB
/
esp8266-fastled-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) 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/>.
*/
#include "common.h"
WiFiManager wifiManager;
ESP8266WebServer webServer(80);
//WebSocketsServer webSocketsServer = WebSocketsServer(81);
ESP8266HTTPUpdateServer httpUpdateServer;
int utcOffsetInSeconds = -6 * 60 * 60;
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org", utcOffsetInSeconds, NTP_UPDATE_THROTTLE_MILLLISECONDS);
String nameString;
CRGB leds[NUM_PIXELS];
const uint8_t brightnessCount = 5;
const uint8_t brightnessMap[brightnessCount] = { 16, 32, 64, 128, 255 };
uint8_t brightnessIndex = DEFAULT_BRIGHTNESS_INDEX;
// 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 = 49;
// 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 = 60;
uint8_t speed = 30;
///////////////////////////////////////////////////////////////////////
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 = DEFAULT_PATTERN_INDEX; // Index number of which pattern is current
uint8_t autoplay = 0;
uint8_t autoplayDuration = 10;
unsigned long autoPlayTimeout = 0;
uint8_t showClock = 0;
uint8_t clockBackgroundFade = 160;
uint8_t utcOffsetIndex = 24; // map(-6, -12, 14, 0, 104); -12 to 14 in 15 minute increments, mapped to 0 to 104
uint8_t currentPaletteIndex = 0;
uint8_t gHue = 0; // rotating "base color" used by many of the patterns
CRGB solidColor = CRGB::Blue;
// scale the brightness of all pixels down
void dimAll(byte value)
{
for (auto led : leds) {
led.nscale8(value);
}
}
// List of patterns to cycle through. Each is defined as a separate function below.
// NOTE: IS_FIBONACCI implies HAS_COORDINATE_MAP
const PatternAndName patterns[] = {
{ pride, "Pride" },
#if IS_FIBONACCI
{ prideFibonacci, "Pride Fibonacci" },
#endif
{ colorWaves, "Color Waves" },
#if IS_FIBONACCI
{ colorWavesFibonacci, "Color Waves Fibonacci" },
#endif
{ pridePlayground, "Pride Playground" },
#if IS_FIBONACCI
{ pridePlaygroundFibonacci, "Pride Playground Fibonacci" },
#endif
{ colorWavesPlayground, "Color Waves Playground" },
#if IS_FIBONACCI
{ colorWavesPlaygroundFibonacci, "Color Waves Playground Fibonacci" },
#endif
#if defined(PRODUCT_HEXRINGS228)
{ ringSnake, "Ring Snake" },
{ ringSnakes, "Ring Snakes" },
{ ringSnakes3, "Ring Snakes 3" },
{ ringSnakes4, "Ring Snakes 4" },
{ ringSnakes5, "Ring Snakes 5" },
{ ringSnakes6, "Ring Snakes 6" },
{ ringSnakes7, "Ring Snakes 7" },
{ ringSnakes8, "Ring Snakes 8" },
{ ringGradientPalette, "Ring Gradient Palette" },
{ ringAngleGradientPalette, "Ring Angle Gradient Palette" },
#endif
{ wheel, "Wheel" },
{ pacifica_loop, "Pacifica" },
#if IS_FIBONACCI
{ swirlFibonacci, "Swirl Fibonacci"},
{ fireFibonacci, "Fire Fibonacci" },
{ waterFibonacci, "Water Fibonacci" },
{ emitterFibonacci, "Emitter Fibonacci" },
{ pacifica_fibonacci_loop, "Pacifica Fibonacci" },
{ fibonacciStars, "Fibonacci Stars" },
#endif
#if HAS_COORDINATE_MAP // really a wrong name... and likely doing way more computation than necessary
{ radarSweepPalette, "Radar Sweep Palette" },
#endif
#if HAS_COORDINATE_MAP
// matrix patterns
{ anglePalette, "Angle Palette" },
{ radiusPalette, "Radius Palette" },
{ xPalette, "X Axis Palette" },
{ yPalette, "Y Axis Palette" },
{ xyPalette, "XY Axis Palette" },
{ angleGradientPalette, "Angle Gradient Palette" },
{ radiusGradientPalette, "Radius Gradient Palette" },
{ xGradientPalette, "X Axis Gradient Palette" },
{ yGradientPalette, "Y Axis Gradient Palette" },
{ xyGradientPalette, "XY Axis Gradient Palette" },
// noise patterns
{ gradientPalettePolarNoise, "Gradient Palette Polar Noise" },
{ palettePolarNoise, "Palette Polar Noise" },
{ firePolarNoise, "Fire Polar Noise" },
{ firePolarNoise2, "Fire Polar Noise 2" },
{ lavaPolarNoise, "Lava Polar Noise" },
{ rainbowPolarNoise, "Rainbow Polar Noise" },
{ rainbowStripePolarNoise, "Rainbow Stripe Polar Noise" },
{ partyPolarNoise, "Party Polar Noise" },
{ forestPolarNoise, "Forest Polar Noise" },
{ cloudPolarNoise, "Cloud Polar Noise" },
{ oceanPolarNoise, "Ocean Polar Noise" },
{ blackAndWhitePolarNoise, "Black & White Polar Noise" },
{ blackAndBluePolarNoise, "Black & Blue Polar Noise" },
{ gradientPaletteNoise, "Gradient Palette Noise" },
{ paletteNoise, "Palette Noise" },
{ fireNoise, "Fire Noise" },
{ fireNoise2, "Fire Noise 2" },
{ lavaNoise, "Lava Noise" },
{ rainbowNoise, "Rainbow Noise" },
{ rainbowStripeNoise, "Rainbow Stripe Noise" },
{ partyNoise, "Party Noise" },
{ forestNoise, "Forest Noise" },
{ cloudNoise, "Cloud Noise" },
{ oceanNoise, "Ocean Noise" },
{ blackAndWhiteNoise, "Black & White Noise" },
{ blackAndBlueNoise, "Black & Blue Noise" },
{ drawAnalogClock, "Analog Clock" },
#endif
#if IS_FIBONACCI
{ drawSpiralAnalogClock13, "Spiral Analog Clock 13" },
{ drawSpiralAnalogClock21, "Spiral Analog Clock 21" },
{ drawSpiralAnalogClock34, "Spiral Analog Clock 34" },
{ drawSpiralAnalogClock55, "Spiral Analog Clock 55" },
{ drawSpiralAnalogClock89, "Spiral Analog Clock 89" },
{ drawSpiralAnalogClock21and34, "Spiral Analog Clock 21 & 34"},
{ drawSpiralAnalogClock13_21_and_34, "Spiral Analog Clock 13, 21 & 34"},
{ drawSpiralAnalogClock34_21_and_13, "Spiral Analog Clock 34, 21 & 13"},
#endif
#if defined(PRODUCT_KRAKEN64)
// Kraken patterns ... these use body[], which is also used as a proxy for radius...
{ radiusPalette, "Kraken Palette" },
{ radiusGradientPalette, "Kraken Gradient Palette" },
#endif
// twinkle patterns
{ rainbowTwinkles, "Rainbow Twinkles" },
{ snowTwinkles, "Snow Twinkles" },
{ cloudTwinkles, "Cloud Twinkles" },
{ incandescentTwinkles, "Incandescent Twinkles" },
// TwinkleFOX patterns
{ retroC9Twinkles, "Retro C9 Twinkles" },
{ redWhiteTwinkles, "Red & White Twinkles" },
{ blueWhiteTwinkles, "Blue & White Twinkles" },
{ redGreenWhiteTwinkles, "Red, Green & White Twinkles" },
{ fairyLightTwinkles, "Fairy Light Twinkles" },
{ snow2Twinkles, "Snow 2 Twinkles" },
{ hollyTwinkles, "Holly Twinkles" },
{ iceTwinkles, "Ice Twinkles" },
{ partyTwinkles, "Party Twinkles" },
{ forestTwinkles, "Forest Twinkles" },
{ lavaTwinkles, "Lava Twinkles" },
{ fireTwinkles, "Fire Twinkles" },
{ cloud2Twinkles, "Cloud 2 Twinkles" },
{ oceanTwinkles, "Ocean Twinkles" },
{ rainbow, "Rainbow" },
{ rainbowWithGlitter, "Rainbow With Glitter" },
{ rainbowSolid, "Solid Rainbow" },
{ confetti, "Confetti" },
{ sinelon, "Sinelon" },
{ bpm, "Beat" },
{ juggle, "Juggle" },
{ fire, "Fire" },
{ water, "Water" },
{ strandTest, "Strand Test" },
#if (PARALLEL_OUTPUT_CHANNELS > 1)
{ multi_test, "Multi Test" },
#endif
{ showSolidColor, "Solid Color" } // This *must* be the last pattern
};
const uint8_t patternCount = ARRAY_SIZE2(patterns);
const CRGBPalette16 palettes[] = {
RainbowColors_p,
RainbowStripeColors_p,
CloudColors_p,
LavaColors_p,
OceanColors_p,
ForestColors_p,
PartyColors_p,
HeatColors_p
};
const uint8_t paletteCount = ARRAY_SIZE2(palettes);
const String paletteNames[paletteCount] = {
"Rainbow",
"Rainbow Stripe",
"Cloud",
"Lava",
"Ocean",
"Forest",
"Party",
"Heat",
};
// TODO / BUGBUG -- should this be ESP8266-specific? Is this only for when IR enabled ???
// FIB128 did not have this...
#if defined(PRODUCT_FIBONACCI256)
ADC_MODE(ADC_VCC);
#endif
void setup() {
WiFi.mode(WIFI_STA); // explicitly set mode, esp defaults to STA+AP
WiFi.setSleepMode(WIFI_NONE_SLEEP);
Serial.begin(115200);
Serial.setDebugOutput(true);
uint16_t milliAmps = (AVAILABLE_MILLI_AMPS < MAX_MILLI_AMPS) ? AVAILABLE_MILLI_AMPS : MAX_MILLI_AMPS;
#if PARALLEL_OUTPUT_CHANNELS == 1
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, NUM_PIXELS); // for WS2812 (Neopixel)
#else
#if PARALLEL_OUTPUT_CHANNELS >= 2
FastLED.addLeds<LED_TYPE, DATA_PIN, COLOR_ORDER>(leds, LedOffset<1>(), LedCount<1>());
FastLED.addLeds<LED_TYPE, DATA_PIN_2, COLOR_ORDER>(leds, LedOffset<2>(), LedCount<2>());
#endif
#if PARALLEL_OUTPUT_CHANNELS >= 3
FastLED.addLeds<LED_TYPE, DATA_PIN_3, COLOR_ORDER>(leds, LedOffset<3>(), LedCount<3>());
#endif
#if PARALLEL_OUTPUT_CHANNELS >= 4
FastLED.addLeds<LED_TYPE, DATA_PIN_4, COLOR_ORDER>(leds, LedOffset<4>(), LedCount<4>());
#endif
#if PARALLEL_OUTPUT_CHANNELS >= 5
FastLED.addLeds<LED_TYPE, DATA_PIN_5, COLOR_ORDER>(leds, LedOffset<5>(), LedCount<4>());
#endif
#if PARALLEL_OUTPUT_CHANNELS >= 6
FastLED.addLeds<LED_TYPE, DATA_PIN_6, COLOR_ORDER>(leds, LedOffset<6>(), LedCount<4>());
#endif
#endif // PARALLEL_OUTPUT_CHANNELS
//FastLED.addLeds<LED_TYPE,DATA_PIN,CLK_PIN,COLOR_ORDER>(leds, NUM_PIXELS); // for APA102 (Dotstar)
FastLED.setDither(false);
FastLED.setCorrection(TypicalLEDStrip);
FastLED.setBrightness(brightness);
FastLED.setMaxPowerInVoltsAndMilliamps(5, milliAmps);
fill_solid(leds, NUM_PIXELS, CRGB::Black);
FastLED.show();
EEPROM.begin(512); // TODO: move settings (currently EEPROM) to fields.hpp/.cpp
readSettings();
FastLED.setBrightness(brightness);
#if defined(ENABLE_IR)
irReceiver.enableIRIn(); // Start the receiver
#endif
Serial.println();
Serial.println(F("System Info:"));
Serial.print( F("Max mA: ") ); Serial.println(milliAmps);
Serial.print( F("Heap: ") ); Serial.println(system_get_free_heap_size());
Serial.print( F("Boot Vers: ") ); Serial.println(system_get_boot_version());
Serial.print( F("CPU: ") ); Serial.println(system_get_cpu_freq());
Serial.print( F("SDK: ") ); Serial.println(system_get_sdk_version());
Serial.print( F("Chip ID: ") ); Serial.println(system_get_chip_id());
Serial.print( F("Flash ID: ") ); Serial.println(spi_flash_get_id());
Serial.print( F("Flash Size: ") ); Serial.println(ESP.getFlashChipRealSize());
Serial.print( F("Vcc: ") ); Serial.println(ESP.getVcc());
Serial.print( F("MAC Address: ") ); Serial.println(WiFi.macAddress());
Serial.println();
Serial.println(F("Settings: "));
Serial.print(F("brightness: ")); Serial.println(brightness);
Serial.print(F("currentPatternIndex: ")); Serial.println(currentPatternIndex);
Serial.print(F("solidColor.r: ")); Serial.println(solidColor.r);
Serial.print(F("solidColor.g: ")); Serial.println(solidColor.g);
Serial.print(F("solidColor.b: ")); Serial.println(solidColor.b);
Serial.print(F("power: ")); Serial.println(power);
Serial.print(F("autoplay: ")); Serial.println(autoplay);
Serial.print(F("autoplayDuration: ")); Serial.println(autoplayDuration);
Serial.print(F("currentPaletteIndex: ")); Serial.println(currentPaletteIndex);
Serial.print(F("showClock: ")); Serial.println(showClock);
Serial.print(F("clockBackgroundFade: ")); Serial.println(clockBackgroundFade);
Serial.print(F("utcOffsetIndex: ")); Serial.println(utcOffsetIndex);
Serial.print(F("utcOffsetInSeconds: ")); Serial.println(utcOffsetInSeconds);
Serial.println();
if (!MYFS.begin()) {
Serial.println(F("An error occurred when attempting to mount the flash file system"));
} else {
Serial.println("FS contents:");
Dir dir = MYFS.openDir("/");
while (dir.next()) {
String fileName = dir.fileName();
size_t fileSize = dir.fileSize();
Serial.printf("FS File: %s, size: %s\n", fileName.c_str(), String(fileSize).c_str());
}
Serial.printf("\n");
}
// Do a little work to get a unique-ish name. Get the
// last two bytes of the MAC (HEX'd)":
// copy the mac address to a byte array
uint8_t mac[WL_MAC_ADDR_LENGTH];
WiFi.softAPmacAddress(mac);
// format the last two digits to hex character array, like 0A0B
char macID[5];
sprintf(macID, "%02X%02X", mac[WL_MAC_ADDR_LENGTH - 2], mac[WL_MAC_ADDR_LENGTH - 1]);
// convert the character array to a string
String macIdString = macID;
macIdString.toUpperCase();
nameString = NAME_PREFIX + macIdString;
// Allocation of variable-sized arrays on the stack is a GCC extension.
// Converting this to be compile-time evaluated is possible:
// nameString.length() === strlen(NAME_PREFIX) + strlen(maxIdString)
// strlen(NAME_PREFIX) is compile-time constexpr (but changes per NAME_PREFIX)
// strlen(macIdString) is always 4
// Therefore, can use the following to ensure statically evaluated at compile-time,
// and avoid use of GCC extensions, with no performance loss.
const size_t nameCharCount = static_eval<size_t, constexpr_strlen(NAME_PREFIX) + 4>::value;
const size_t nameBufferSize = static_eval<size_t, nameCharCount+1>::value;
char nameChar[nameBufferSize];
memset(nameChar, 0, nameBufferSize);
// Technically, this should *NEVER* need to check the nameString length.
// However, I prefer to code defensively, since no static_assert() can detect this.
size_t loopUntil = (nameCharCount <= nameString.length() ? nameCharCount : nameString.length());
for (size_t i = 0; i < loopUntil; i++) {
nameChar[i] = nameString.charAt(i);
}
Serial.printf("Name: %s\n", nameChar );
// reset settings - wipe credentials for testing
// wifiManager.resetSettings();
wifiManager.setConfigPortalBlocking(false);
//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("Wi-Fi connected");
}
else {
Serial.println("Wi-Fi manager portal running");
}
httpUpdateServer.setup(&webServer);
webServer.on("/all", HTTP_GET, []() {
String json = getFieldsJson();
webServer.send(200, "application/json", json);
});
webServer.on("/fieldsWithoutOptions", HTTP_GET, []() {
String json = getFieldsWithoutOptionsJson();
webServer.send(200, "application/json", json);
});
webServer.on("/patternOptions", HTTP_GET, []() {
String json = getPatternsJson();
webServer.send(200, "application/json", json);
});
webServer.on("/paletteOptions", HTTP_GET, []() {
String json = getPalettesJson();
webServer.send(200, "application/json", json);
});
webServer.on("/product", HTTP_GET, []() {
String json = "{\"productName\":\"" PRODUCT_FRIENDLY_NAME "\"}";
webServer.send(200, "application/json", json);
});
webServer.on("/info", HTTP_GET, []() {
String json = getInfoJson();
webServer.send(200, "application/json", json);
});
webServer.on("/fieldValue", HTTP_GET, []() {
String name = webServer.arg("name");
String value = getFieldValue(name);
webServer.send(200, "text/json", value);
});
webServer.on("/fieldValue", HTTP_POST, []() {
String name = webServer.arg("name");
String value = webServer.arg("value");
String newValue = setFieldValue(name, value);
webServer.send(200, "text/json", newValue);
});
webServer.on("/power", HTTP_POST, []() {
String value = webServer.arg("value");
setPower(value.toInt());
sendInt(power);
});
webServer.on("/cooling", HTTP_POST, []() {
String value = webServer.arg("value");
cooling = value.toInt();
broadcastInt("cooling", cooling);
sendInt(cooling);
});
webServer.on("/sparking", HTTP_POST, []() {
String value = webServer.arg("value");
sparking = value.toInt();
broadcastInt("sparking", sparking);
sendInt(sparking);
});
webServer.on("/speed", HTTP_POST, []() {
String value = webServer.arg("value");
speed = value.toInt();
broadcastInt("speed", speed);
sendInt(speed);
});
webServer.on("/twinkleSpeed", HTTP_POST, []() {
String value = webServer.arg("value");
long tmp = value.toInt();
if (tmp < 0) {
tmp = 0;
} else if (tmp > 8) {
tmp = 8;
}
twinkleSpeed = (uint8_t)tmp;
writeAndCommitSettings();
broadcastInt("twinkleSpeed", twinkleSpeed);
sendInt(twinkleSpeed);
});
webServer.on("/twinkleDensity", HTTP_POST, []() {
String value = webServer.arg("value");
long tmp = value.toInt();
if (tmp < 0) {
tmp = 0;
} else if (tmp > 8) {
tmp = 8;
}
twinkleDensity = tmp;
writeAndCommitSettings();
broadcastInt("twinkleDensity", twinkleDensity);
sendInt(twinkleDensity);
});
webServer.on("/coolLikeIncandescent", HTTP_POST, []() {
String value = webServer.arg("value");
long tmp = value.toInt();
if (tmp < 0) {
tmp = 0;
} else if (tmp > 1) {
tmp = 1;
}
coolLikeIncandescent = tmp;
writeAndCommitSettings();
broadcastInt("coolLikeIncandescent", coolLikeIncandescent);
sendInt(coolLikeIncandescent);
});
webServer.on("/solidColor", HTTP_POST, []() {
String r = webServer.arg("r");
String g = webServer.arg("g");
String b = webServer.arg("b");
setSolidColor(r.toInt(), g.toInt(), b.toInt());
sendString(String(solidColor.r) + "," + String(solidColor.g) + "," + String(solidColor.b));
});
webServer.on("/pattern", HTTP_POST, []() {
String value = webServer.arg("value");
setPattern(value.toInt());
sendInt(currentPatternIndex);
});
webServer.on("/patternName", HTTP_POST, []() {
String value = webServer.arg("value");
setPatternName(value);
sendInt(currentPatternIndex);
});
webServer.on("/palette", HTTP_POST, []() {
String value = webServer.arg("value");
setPalette(value.toInt());
sendInt(currentPaletteIndex);
});
webServer.on("/paletteName", HTTP_POST, []() {
String value = webServer.arg("value");
setPaletteName(value);
sendInt(currentPaletteIndex);
});
webServer.on("/brightness", HTTP_POST, []() {
String value = webServer.arg("value");
setBrightness(value.toInt());
sendInt(brightness);
});
webServer.on("/autoplay", HTTP_POST, []() {
String value = webServer.arg("value");
setAutoplay(value.toInt());
sendInt(autoplay);
});
webServer.on("/autoplayDuration", HTTP_POST, []() {
String value = webServer.arg("value");
setAutoplayDuration(value.toInt());
sendInt(autoplayDuration);
});
webServer.on("/showClock", HTTP_POST, []() {
String value = webServer.arg("value");
long tmp = value.toInt();
if (tmp < 0) {
tmp = 0;
} else if (tmp > 1) {
tmp = 1;
}
setShowClock(tmp);
sendInt(showClock);
});
webServer.on("/clockBackgroundFade", HTTP_POST, []() {
String value = webServer.arg("value");
long tmp = value.toInt();
if (tmp < 0) {
tmp = 0;
} else if (tmp > 255) {
tmp = 255;
}
setClockBackgroundFade(tmp);
sendInt(clockBackgroundFade);
});
//list directory
webServer.on("/list", HTTP_GET, handleFileList);
//load editor
webServer.on("/edit", HTTP_GET, []() {
if (!handleFileRead("/edit.htm")) webServer.send(404, "text/plain", "FileNotFound");
});
//create file
webServer.on("/edit", HTTP_PUT, handleFileCreate);
//delete file
webServer.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
webServer.on("/edit", HTTP_POST, []() {
webServer.send(200, "text/plain", "");
}, handleFileUpload);
webServer.enableCORS(true);
webServer.serveStatic("/", LittleFS, "/", "max-age=86400");
MDNS.begin(nameChar);
MDNS.setHostname(nameChar);
webServer.begin();
Serial.println("HTTP web server started");
// webSocketsServer.begin();
// webSocketsServer.onEvent(webSocketEvent);
// Serial.println("Web socket server started");
autoPlayTimeout = millis() + (autoplayDuration * 1000);
timeClient.begin();
}
void sendInt(uint8_t value)
{
sendString(String(value));
}
void sendString(String value)
{
webServer.send(200, "text/plain", value);
}
void broadcastInt(String name, uint8_t value)
{
String json = "{\"name\":\"" + name + "\",\"value\":" + String(value) + "}";
// webSocketsServer.broadcastTXT(json);
}
void broadcastString(String name, String value)
{
String json = "{\"name\":\"" + name + "\",\"value\":\"" + String(value) + "\"}";
// webSocketsServer.broadcastTXT(json);
}
// TODO: Add board-specific entropy sources
// e.g., using `uint32_t esp_random()`, if exposed in Arduino ESP32 / ESP8266 BSPs
// e.g., directly reading from 0x3FF20E44 on ESP8266 (dangerous! no entropy validation, whitening)
// e.g., directly reading from 0x3FF75144 on ESP32 (dangerous! no entropy validation, whitening)
// e.g., directly reading from RANDOM_REG32 (dangerous! no entropy validation, whitening)
// e.g., using a library, such as https://github.com/marvinroger/ESP8266TrueRandom/blob/master/ESP8266TrueRandom.cpp (less dangerous?)
// e.g., directly reading REG_READ(WDEV_RND_REG) (dangerous! no check for sufficient clock cycles passed for entropy)
void loop() {
// Modify random number generator seed; we use a lot of it. (Note: this is still deterministic)
random16_add_entropy(random(65535));
// webSocketsServer.loop();
wifiManager.process();
webServer.handleClient();
MDNS.update();
static bool hasConnected = false;
EVERY_N_SECONDS(1) {
if (WiFi.status() != WL_CONNECTED) {
// Serial.printf("Connecting to %s\n", ssid);
hasConnected = false;
}
else if (!hasConnected) {
hasConnected = true;
MDNS.begin(nameString);
MDNS.setHostname(nameString);
webServer.begin();
Serial.println("HTTP web server started");
Serial.print("Connected! Open http://");
Serial.print(WiFi.localIP());
Serial.print(" or http://");
Serial.print(nameString);
Serial.println(".local in your browser");
} else {
timeClient.update(); // NTPClient has throttling built-in
}
}
checkPingTimer();
handleIrInput(); // empty function when ENABLE_IR is not defined
if (power == 0) {
fill_solid(leds, NUM_PIXELS, CRGB::Black);
FastLED.delay(1000 / FRAMES_PER_SECOND); // this function calls FastLED.show() at least once
return;
}
// EVERY_N_SECONDS(10) {
// Serial.print( F("Heap: ") ); Serial.println(system_get_free_heap_size());
// }
// change to a new cpt-city gradient palette
EVERY_N_SECONDS( secondsPerPalette ) {
gCurrentPaletteNumber = addmod8( gCurrentPaletteNumber, 1, gGradientPaletteCount);
gTargetPalette = gGradientPalettes[ gCurrentPaletteNumber ];
}
EVERY_N_MILLISECONDS(40) {
// slowly blend the current palette to the next
nblendPaletteTowardPalette( gCurrentPalette, gTargetPalette, 8);
gHue++; // slowly cycle the "base color" through the rainbow
}
if (autoplay && (millis() > autoPlayTimeout)) {
adjustPattern(true);
autoPlayTimeout = millis() + (autoplayDuration * 1000);
}
// Call the current pattern function once, updating the 'leds' array
patterns[currentPatternIndex].pattern();
#if HAS_COORDINATE_MAP
if (showClock) drawAnalogClock();
#endif
// insert a delay to keep the framerate modest ... this is guaranteed to call FastLED.show() at least once
FastLED.delay(1000 / FRAMES_PER_SECOND);
}
//void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t length) {
//
// switch (type) {
// case WStype_DISCONNECTED:
// Serial.printf("[%u] Disconnected!\n", num);
// break;
//
// case WStype_CONNECTED:
// {
// IPAddress ip = webSocketsServer.remoteIP(num);
// Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload);
//
// // send message to client
// // webSocketsServer.sendTXT(num, "Connected");
// }
// break;
//
// case WStype_TEXT:
// Serial.printf("[%u] get Text: %s\n", num, payload);
//
// // send message to client
// // webSocketsServer.sendTXT(num, "message here");
//
// // send data to all connected clients
// // webSocketsServer.broadcastTXT("message here");
// break;
//
// case WStype_BIN:
// Serial.printf("[%u] get binary length: %u\n", num, length);
// hexdump(payload, length);
//
// // send message to client
// // webSocketsServer.sendBIN(num, payload, lenght);
// break;
// }
//}
// TODO: Save settings in file system, not EEPROM!
const uint8_t SETTINGS_MAGIC_BYTE = 0x96;
void readSettings()
{
// check for "magic number" so we know settings have been written to EEPROM
// and it's not just full of random bytes
if (EEPROM.read(511) != SETTINGS_MAGIC_BYTE) {
return;
}
brightness = EEPROM.read(0);
currentPatternIndex = EEPROM.read(1);
if (currentPatternIndex >= patternCount) {
currentPatternIndex = patternCount - 1;
}
byte r = EEPROM.read(2);
byte g = EEPROM.read(3);
byte b = EEPROM.read(4);
if (r == 0 && g == 0 && b == 0)
{
}
else
{
solidColor = CRGB(r, g, b);
}
power = EEPROM.read(5);
autoplay = EEPROM.read(6);
autoplayDuration = EEPROM.read(7);
currentPaletteIndex = EEPROM.read(8);
if (currentPaletteIndex >= paletteCount) {
currentPaletteIndex = paletteCount - 1;
}
twinkleSpeed = EEPROM.read(9);
twinkleDensity = EEPROM.read(10);
cooling = EEPROM.read(11);
sparking = EEPROM.read(12);
coolLikeIncandescent = EEPROM.read(13);
showClock = EEPROM.read(14);
clockBackgroundFade = EEPROM.read(15);
utcOffsetIndex = EEPROM.read(16);
setUtcOffsetIndex(utcOffsetIndex);
}
void writeAndCommitSettings() {
EEPROM.write(0, brightness);
EEPROM.write(1, currentPatternIndex);
EEPROM.write(2, solidColor.r);
EEPROM.write(3, solidColor.g);
EEPROM.write(4, solidColor.b);
EEPROM.write(5, power);
EEPROM.write(6, autoplay);
EEPROM.write(7, autoplayDuration);
EEPROM.write(8, currentPaletteIndex);
EEPROM.write(9, twinkleSpeed);
EEPROM.write(10, twinkleDensity);
EEPROM.write(11, cooling);
EEPROM.write(12, sparking);
EEPROM.write(13, coolLikeIncandescent);
EEPROM.write(14, showClock);
EEPROM.write(15, clockBackgroundFade);
EEPROM.write(16, utcOffsetIndex);
EEPROM.write(511, SETTINGS_MAGIC_BYTE);
EEPROM.commit();
}
void setPower(uint8_t value)
{
power = value == 0 ? 0 : 1;
writeAndCommitSettings();
broadcastInt("power", value);
}
void setAutoplay(uint8_t value)
{
autoplay = value == 0 ? 0 : 1;
writeAndCommitSettings();
broadcastInt("autoplay", autoplay);
}
void setAutoplayDuration(uint8_t value)
{
autoplayDuration = value;
writeAndCommitSettings();
autoPlayTimeout = millis() + (autoplayDuration * 1000);
broadcastInt("autoplayDuration", autoplayDuration);
}
void setSolidColor(CRGB color)
{
setSolidColor(color.r, color.g, color.b);
}
void setSolidColor(uint8_t r, uint8_t g, uint8_t b)
{
solidColor = CRGB(r, g, b);
writeAndCommitSettings();
setPattern(patternCount - 1);
broadcastString("color", String(solidColor.r) + "," + String(solidColor.g) + "," + String(solidColor.b));
}
// increase or decrease the current pattern number, and wrap around at the ends
void adjustPattern(bool up)
{
if (up)
currentPatternIndex++;
else
currentPatternIndex--;
// wrap around at the end
if (currentPatternIndex >= patternCount) {
currentPatternIndex = 0;
}
if (autoplay == 0) {
writeAndCommitSettings();
}
broadcastInt("pattern", currentPatternIndex);
}
void setPattern(uint8_t value)
{
if (value >= patternCount)
value = patternCount - 1;
currentPatternIndex = value;
if (autoplay == 0) {
writeAndCommitSettings();
}
broadcastInt("pattern", currentPatternIndex);
}
void setPatternName(String name)
{
for (uint8_t i = 0; i < patternCount; i++) {
if (patterns[i].name == name) {
setPattern(i);
break;
}
}
}
void setPalette(uint8_t value)
{
if (value >= paletteCount)
value = paletteCount - 1;
currentPaletteIndex = value;
writeAndCommitSettings();
broadcastInt("palette", currentPaletteIndex);
}
void setPaletteName(String name)
{
for (uint8_t i = 0; i < paletteCount; i++) {
if (paletteNames[i] == name) {
setPalette(i);
break;
}
}
}
void adjustBrightness(bool up)
{
if (up && brightnessIndex < brightnessCount - 1)
brightnessIndex++;
else if (!up && brightnessIndex > 0)
brightnessIndex--;
brightness = brightnessMap[brightnessIndex];
FastLED.setBrightness(brightness);
writeAndCommitSettings();
broadcastInt("brightness", brightness);
}
void setBrightness(uint8_t value)
{
brightness = value;
FastLED.setBrightness(brightness);
writeAndCommitSettings();
broadcastInt("brightness", brightness);
}
void strandTest()
{
static size_t i = 0;
EVERY_N_SECONDS(1)
{
i++;
if (i >= NUM_PIXELS)
i = 0;
}
fill_solid(leds, NUM_PIXELS, CRGB::Black);
leds[i] = solidColor;
}