-
Notifications
You must be signed in to change notification settings - Fork 5
/
httpledstripe_esp.cpp
2168 lines (1952 loc) · 59.8 KB
/
httpledstripe_esp.cpp
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
/**************************************************************
This work is based on many others.
If published then under whatever licence free to be used,
distibuted, changed and whatsoever.
This Work is based on many others
and heavily modified for my personal use.
It is basically based on the following great developments:
- Adafruit Neopixel https://github.com/adafruit/Adafruit_NeoPixel
- WS2812FX library https://github.com/kitesurfer1404/WS2812FX
- fhem esp8266 implementation - Idea from https://github.com/sw-home/FHEM-LEDStripe
- FastLED library - see http://www.fastLed.io
- ESPWebserver - see https://github.com/jasoncoon/esp8266-fastled-webserver
My GIT source code storage
https://github.com/tobi01001/LED_Stripe_Dynamic_web_conf
Done by tobi01001
**************************************************************
MIT License
Copyright (c) 2018 tobi01001
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
**************************************************************/
#include <FS.h>
#include <Arduino.h>
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <WebSocketsServer.h>
#include <WiFiManager.h>
#include <ArduinoOTA.h>
#include <EEPROM.h>
#define FASTLED_ESP8266_RAW_PIN_ORDER
#define FASTLED_ESP8266_DMA
#define FASTLED_USE_PROGMEM 1
#include "debug_help.h"
#include "defaults.h"
extern "C"
{
#include "user_interface.h"
}
// new approach starts here:
#include "led_strip.h"
// The delay being used for several init phases.
#ifdef DEBUG
#define INITDELAY 500
#else
#define INITDELAY 2
#endif
// TODO: Implement and use a "defaults.h" to enable specific defaults?
/* use build flags to define these */
#ifndef LED_NAME
#error "You need to give your LED a Name (build flag e.g. '-DLED_NAME=\"My LED\"')!"
#endif
#define BUILD_VERSION ("0.9_Segs_")
#ifndef BUILD_VERSION
#error "We need a SW Version and Build Version!"
#endif
#ifdef DEBUG
String build_version = BUILD_VERSION + String("DEBUG ") + String(__TIMESTAMP__);
#else
String build_version = BUILD_VERSION + String(__TIMESTAMP__);
#endif
#ifndef LED_COUNT
#error "You need to define the number of Leds by LED_COUNT (build flag e.g. -DLED_COUNT=50)"
#endif
/* Definitions for network usage */
/* maybe move all wifi stuff to separate files.... */
#define WIFI_TIMEOUT 5000
ESP8266WebServer server(80);
WebSocketsServer *webSocketsServer; // webSocketsServer = WebSocketsServer(81);
String AP_SSID = LED_NAME + String(ESP.getChipId());
/* END Network Definitions */
//flag for saving data
bool shouldSaveRuntime = false;
WS2812FX::segment seg;
#include "FSBrowser.h"
// function Definitions
void saveEEPROMData(void),
initOverTheAirUpdate(void),
setupWiFi(void),
handleSet(void),
handleNotFound(void),
handleGetModes(void),
handleStatus(void),
factoryReset(void),
handleResetRequest(void),
setupWebServer(void),
showInitColor(CRGB Color),
sendInt(String name, uint16_t value),
sendString(String name, String value),
sendAnswer(String jsonAnswer),
broadcastInt(String name, uint16_t value),
broadcastString(String name, String value),
webSocketEvent(uint8_t num, WStype_t type, uint8_t *payload, size_t length),
checkSegmentChanges(void),
clearEEPROM(void);
const String
pals_setup(void);
uint32
getResetReason(void);
// used to send an answer as INT to the calling http request
// TODO: Use one answer function with parameters being overloaded
void sendInt(String name, uint16_t value)
{
String answer = F("{ ");
answer += F("\"currentState\" : { \"");
answer += name;
answer += F("\": ");
answer += value;
answer += " } }";
DEBUGPRNT("Send HTML respone 200, application/json with value: " + answer);
server.send(200, "application/json", answer);
}
// used to send an answer as String to the calling http request
// TODO: Use one answer function with parameters being overloaded
void sendString(String name, String value)
{
String answer = F("{ ");
answer += F("\"currentState\" : { \"");
answer += name;
answer += F("\": \"");
answer += value;
answer += "\" } }";
DEBUGPRNT("Send HTML respone 200, application/json with value: " + answer);
server.send(200, "application/json", answer);
}
// used to send an answer as JSONString to the calling http request
// send answer can embed a complete json string instead of a single name / value pair.
void sendAnswer(String jsonAnswer)
{
String answer = "{ \"currentState\": { " + jsonAnswer + "} }";
server.send(200, "application/json", answer);
}
// broadcasts the name and value to all websocket clients
void broadcastInt(String name, uint16_t value)
{
String json = "{\"name\":\"" + name + "\",\"value\":" + String(value) + "}";
DEBUGPRNT("Send websocket broadcast with value: " + json);
webSocketsServer->broadcastTXT(json);
}
// broadcasts the name and value to all websocket clients
// TODO: One function with parameters being overloaded.
void broadcastString(String name, String value)
{
String json = "{\"name\":\"" + name + "\",\"value\":\"" + String(value) + "\"}";
DEBUGPRNT("Send websocket broadcast with value: " + json);
webSocketsServer->broadcastTXT(json);
}
// calculates a simple CRC over the given buffer and length
unsigned int calc_CRC16(unsigned int crc, unsigned char *buf, int len)
{
for (int pos = 0; pos < len; pos++)
{
crc ^= (unsigned int)buf[pos]; // XOR byte into least sig. byte of crc
for (int i = 8; i != 0; i--)
{ // Loop over each bit
if ((crc & 0x0001) != 0)
{ // If the LSB is set
crc >>= 1; // Shift right and XOR 0xA001
crc ^= 0xA001;
}
else // Else LSB is not set
crc >>= 1; // Just shift right
}
}
return crc;
}
void checkSegmentChanges(void) {
if(seg.power != strip->getPower()) {
seg.power = strip->getPower();
broadcastInt("power", seg.power);
shouldSaveRuntime = true;
}
if(seg.isRunning != strip->isRunning()) {
seg.isRunning = strip->isRunning();
broadcastInt("isRunning", seg.isRunning);
shouldSaveRuntime = true;
}
if(seg.targetBrightness != strip->getTargetBrightness()) {
seg.targetBrightness = strip->getTargetBrightness();
broadcastInt("br", seg.targetBrightness);
shouldSaveRuntime = true;
}
if(seg.mode != strip->getMode()){
seg.mode = strip->getMode();
broadcastInt("mo", seg.mode);
shouldSaveRuntime = true;
}
if(seg.targetPaletteNum != strip->getTargetPaletteNumber()) {
seg.targetPaletteNum = strip->getTargetPaletteNumber();
broadcastInt("pa", seg.targetPaletteNum);
shouldSaveRuntime = true;
}
if(seg.beat88 != strip->getBeat88()) {
seg.beat88 = strip->getBeat88();
broadcastInt("sp", seg.beat88);
shouldSaveRuntime = true;
}
if(seg.blendType != strip->getBlendType()) {
seg.blendType = strip->getBlendType();
broadcastInt("blendType", seg.blendType);
shouldSaveRuntime = true;
}
if(seg.colorTemp != strip->getColorTemperature())
{
seg.colorTemp = strip->getColorTemperature();
broadcastInt("ColorTemperature", strip->getColorTemp());
shouldSaveRuntime = true;
}
if(seg.blur != strip->getBlurValue())
{
seg.blur = strip->getBlurValue();
broadcastInt("LEDblur", seg.blur);
shouldSaveRuntime = true;
}
if(seg.reverse != strip->getReverse())
{
seg.reverse = strip->getReverse();
broadcastInt("reverse", seg.reverse);
shouldSaveRuntime = true;
}
if(seg.segments != strip->getSegments())
{
seg.segments = strip->getSegments();
broadcastInt("segments", seg.segments);
shouldSaveRuntime = true;
}
if(seg.mirror != strip->getMirror())
{
seg.mirror = strip->getMirror();
broadcastInt("mirror", seg.mirror);
shouldSaveRuntime = true;
}
if(seg.inverse != strip->getInverse())
{
seg.inverse = strip->getInverse();
broadcastInt("inverse",seg.inverse);
shouldSaveRuntime = true;
}
if(seg.hueTime != strip->getHueTime())
{
seg.hueTime = strip->getHueTime();
broadcastInt("huetime", seg.hueTime);
shouldSaveRuntime = true;
}
if(seg.deltaHue != strip->getDeltaHue())
{
seg.deltaHue = strip->getDeltaHue();
broadcastInt("deltahue", seg.deltaHue);
shouldSaveRuntime = true;
}
if(seg.autoplay != strip->getAutoplay())
{
seg.autoplay = strip->getAutoplay();
broadcastInt("autoplay", seg.autoplay);
shouldSaveRuntime = true;
}
if(seg.autoplayDuration != strip->getAutoplayDuration())
{
seg.autoplayDuration = strip->getAutoplayDuration();
broadcastInt("autoplayDuration", seg.autoplayDuration);
shouldSaveRuntime = true;
}
if(seg.autoPal != strip->getAutopal())
{
seg.autoPal = strip->getAutopal();
broadcastInt("autopal", seg.autoPal);
shouldSaveRuntime = true;
}
if(seg.autoPalDuration != strip->getAutopalDuration())
{
seg.autoPalDuration = strip->getAutopalDuration();
broadcastInt("autopalDuration", seg.autoPalDuration);
shouldSaveRuntime = true;
}
/*
"solidColor" -> currently not possible to save?
--> for this to work we need to add 32bit color to the structure
and to "set" this including palette creation...
...and the palette creation depends on the current palette number?
*/
if(seg.cooling != strip->getCooling())
{
seg.cooling = strip->getCooling();
broadcastInt("cooling", seg.cooling);
shouldSaveRuntime = true;
}
if(seg.sparking != strip->getSparking())
{
seg.sparking = strip->getSparking();
broadcastInt("sparking", seg.sparking);
shouldSaveRuntime = true;
}
if(seg.twinkleSpeed != strip->getTwinkleSpeed())
{
seg.twinkleSpeed = strip->getTwinkleSpeed();
broadcastInt("twinkleSpeed", seg.twinkleSpeed);
shouldSaveRuntime = true;
}
if(seg.twinkleDensity != strip->getTwinkleDensity())
{
seg.twinkleDensity = strip->getTwinkleDensity();
broadcastInt("twinkleDensity", seg.twinkleDensity);
shouldSaveRuntime = true;
}
if(seg.numBars != strip->getNumBars())
{
seg.numBars = strip->getNumBars();
broadcastInt("numBars", seg.numBars);
shouldSaveRuntime = true;
}
if(seg.damping != strip->getDamping())
{
seg.damping = strip->getDamping();
broadcastInt("damping", seg.damping);
shouldSaveRuntime = true;
}
if(seg.sunrisetime != strip->getSunriseTime())
{
seg.sunrisetime = strip->getSunriseTime();
broadcastInt("sunriseset", seg.sunrisetime);
shouldSaveRuntime = true;
}
if(seg.milliamps != strip->getMilliamps())
{
seg.milliamps = strip->getMilliamps();
broadcastInt("current", seg.milliamps);
shouldSaveRuntime = true;
}
if(seg.fps != strip->getMaxFPS())
{
seg.fps = strip->getMaxFPS();
broadcastInt("fps", seg.fps);
shouldSaveRuntime = true;
}
if(seg.dithering != strip->getDithering())
{
seg.dithering = strip->getDithering();
broadcastInt("dithering", seg.dithering);
shouldSaveRuntime = true;
}
}
void print_segment(WS2812FX::segment * s) {
DEBUGPRNT("Printing segment content");
#ifdef DEBUG
Serial.println("\t\tCRC:\t" + String(s->CRC));
Serial.println("\t\tisRunning:\t" + String(s->isRunning));
Serial.println("\t\tReverse:\t" + String(s->reverse));
Serial.println("\t\tInverse:\t" + String(s->inverse));
Serial.println("\t\tMirror:\t" + String(s->mirror));
Serial.println("\t\tAutoplay:\t" + String(s->autoplay));
Serial.println("\t\tAutopal:\t" + String(s->autoPal));
Serial.println("\t\tbeat88:\t" + String(s->beat88));
Serial.println("\t\thueTime:\t" + String(s->hueTime));
Serial.println("\t\tmilliamps:\t" + String(s->milliamps));
Serial.println("\t\tautoplayduration:\t" + String(s->autoplayDuration));
Serial.println("\t\tautopalduration:\t" + String(s->autoPalDuration));
Serial.println("\t\tsegements:\t" + String(s->segments));
Serial.println("\t\tcooling:\t" + String(s->cooling));
Serial.println("\t\tsparking:\t" + String(s->sparking));
Serial.println("\t\ttwinkleSpeed:\t" + String(s->twinkleSpeed));
Serial.println("\t\ttwinkleDensity:\t" + String(s->twinkleDensity));
Serial.println("\t\tnumBars:\t" + String(s->numBars));
Serial.println("\t\tmode:\t" + String(s->mode));
Serial.println("\t\tfps:\t" + String(s->fps));
Serial.println("\t\tdeltaHue:\t" + String(s->deltaHue));
Serial.println("\t\tblur:\t" + String(s->blur));
Serial.println("\t\tdamping:\t" + String(s->damping));
Serial.println("\t\tdithering:\t" + String(s->dithering));
Serial.println("\t\tsunrisetime:\t" + String(s->sunrisetime));
Serial.println("\t\ttargetBrightness:\t" + String(s->targetBrightness));
Serial.println("\t\ttargetPaletteNum:\t" + String(s->targetPaletteNum));
Serial.println("\t\tcurrentPaletteNum:\t" + String(s->currentPaletteNum));
Serial.println("\t\tblendType:\t" + String(s->blendType));
Serial.println("\t\tcolorTemp:\t" + String(s->colorTemp));
#endif
DEBUGPRNT("done");
}
// write runtime data to EEPROM (when required by "shouldSave Runtime")
void saveEEPROMData(void)
{
if (!shouldSaveRuntime)
return;
shouldSaveRuntime = false;
DEBUGPRNT("\tGoing to store runtime on EEPROM...");
// we will store the complete segment data
//now in "checkSegment"
//WS2812FX::segment seg = *strip->getSegment();
DEBUGPRNT("WS2812 segment:");
print_segment(strip->getSegment());
DEBUGPRNT("copied segment:");
print_segment(&seg);
seg.CRC = (uint16_t)calc_CRC16(0x5a5a,(unsigned char *)&seg + 2, sizeof(seg) - 2);
strip->setCRC(seg.CRC);
DEBUGPRNT("\tSegment size: " + String(strip->getSegmentSize())+ "\tCRC size: " + String(strip->getCRCsize()));
DEBUGPRNT("\tCRC calculated " + String(seg.CRC) + "\tCRC stored " + String(strip->getCRC()));
DEBUGPRNT("WS2812 segment with new CRC:");
print_segment(strip->getSegment());
// write the data to the EEPROM
EEPROM.put(0, seg);
// as we work on ESP, we also need to commit the written data.
EEPROM.commit();
DEBUGPRNT("EEPROM write finished...");
}
// reads the stored runtime data from EEPROM
// must be called after everything else is already setup to be working
// otherwise this may terribly fail and could override what was read already
void readRuntimeDataEEPROM(void)
{
DEBUGPRNT("\tReading Config From EEPROM...");
// copy segment...
// now separate global....
//WS2812FX::segment seg;
//read the configuration from EEPROM into RAM
EEPROM.get(0, seg);
DEBUGPRNT("Segment after Reading:");
print_segment(&seg);
// calculate the CRC over the data being stored in the EEPROM (except the CRC itself)
uint16_t mCRC = (uint16_t)calc_CRC16(0x5a5a, (unsigned char *)&seg + 2, sizeof(seg) - 2);
DEBUGPRNT("\tCRC calculated " + String(mCRC) + "\tCRC stored " + String(seg.CRC));
// we have a matching CRC, so we update the runtime data.
if (seg.CRC == mCRC)
{
DEBUGPRNT("\tWe got a CRC match!...");
(*strip->getSegment()) = seg;
strip->init();
}
else // load defaults
{
DEBUGPRNT("\tWe got NO NO NO CRC match!!!");
DEBUGPRNT("Loading default Data...");
strip->resetDefaults();
}
memset(&seg, 0, sizeof(seg));
checkSegmentChanges();
// no need to save right now. next save should be after /set?....
shouldSaveRuntime = false;
strip->setTransition();
}
// we do not want anything to distrub the OTA
// therefore there is a flag which could be used to prevent from that...
// However, seems that a connection being active via websocket interrupts
// even if the web socket server is stopped??
bool OTAisRunning = false;
void initOverTheAirUpdate(void)
{
DEBUGPRNT("Initializing OTA capabilities....");
showInitColor(CRGB::Blue);
delay(INITDELAY);
/* init OTA */
// Port defaults to 8266
ArduinoOTA.setPort(8266);
ArduinoOTA.setRebootOnSuccess(true);
// TODO: Implement Hostname in config and WIFI Settings?
// Hostname defaults to esp8266-[ChipID]
// ArduinoOTA.setHostname("esp8266Toby01");
// No authentication by default
// ArduinoOTA.setPassword((const char *)"123");
ArduinoOTA.onStart([]() {
DEBUGPRNT("OTA start");
strip->setIsRunning(false);
strip->setPower(false);
// the following is just to visually indicate the OTA start
// which is done by blinking the complete stripe in different colors from yellow to green
uint8_t factor = 85;
for (uint8_t c = 0; c < 4; c++)
{
for (uint16_t i = 0; i < strip->getStripLength(); i++)
{
uint8_t r = 256 - (c * factor);
uint8_t g = c > 0 ? (c * factor - 1) : (c * factor);
//strip.setPixelColor(i, r, g, 0);
strip->leds[i] = CRGB(strip_color32(r, g, 0));
}
strip->show();
delay(250);
for (uint16_t i = 0; i < strip->getStripLength(); i++)
{
strip->leds[i] = CRGB::Black;
}
strip->show();
delay(500);
}
// we need to delete the websocket server in order to have OTA correctly running.
delete webSocketsServer;
// we stop the webserver to not get interrupted....
server.stop();
// we indicate our sktch that OTA is currently running (should actually not be required)
OTAisRunning = true;
});
// what to do if OTA is finished...
ArduinoOTA.onEnd([]() {
DEBUGPRNT("OTA end");
// OTA finished.
// We fade out the green Leds being activated during OTA.
for (uint8_t i = strip->leds[0].green; i > 0; i--)
{
for (uint16_t p = 0; p < strip->getStripLength(); p++)
{
strip->leds[p].subtractFromRGB(2);
//strip.setPixelColor(p, 0, i-1 ,0);
}
strip->show();
delay(2);
}
// indicate that OTA is no longer running.
OTAisRunning = false;
// no need to reset ESP as this is done by the OTA handler by default
});
// show the progress on the strips as well to be informed if anything gets stuck...
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
DEBUGPRNT("Progress: " + String((progress / (total / 100))));
// OTA Update will show increasing green LEDs during progress:
uint16_t progress_value = progress * 100 / (total / strip->getStripLength());
uint16_t pixel = (uint16_t)(progress_value / 100);
uint16_t temp_color = progress_value - (pixel * 100);
if (temp_color > 255)
temp_color = 255;
strip->leds[pixel] = strip_color32(0, (uint8_t)temp_color, 0);
strip->show();
});
// something went wrong, we gonna show an error "message" via LEDs.
ArduinoOTA.onError([](ota_error_t error) {
DEBUGPRNT("Error[%u]: " + String(error));
if (error == OTA_AUTH_ERROR) {
DEBUGPRNT("Auth Failed");
}
else if (error == OTA_BEGIN_ERROR) {
DEBUGPRNT("Begin Failed");
}
else if (error == OTA_CONNECT_ERROR) {
DEBUGPRNT("Connect Failed");
}
else if (error == OTA_RECEIVE_ERROR) {
DEBUGPRNT("Receive Failed");
}
else if (error == OTA_END_ERROR) {
DEBUGPRNT("End Failed");
}
// something went wrong during OTA.
// We will fade in to red...
for (uint16_t c = 0; c < 256; c++)
{
for (uint16_t i = 0; i < strip->getStripLength(); i++)
{
//strip.setPixelColor(i,(uint8_t)c,0,0);
strip->leds[i] = strip_color32((uint8_t)c, 0, 0);
}
strip->show();
delay(2);
}
// We wait 10 seconds and then restart the ESP...
delay(10000);
ESP.restart();
});
// start the service
ArduinoOTA.begin();
DEBUGPRNT("OTA capabilities initialized....");
showInitColor(CRGB::Green);
delay(INITDELAY);
showInitColor(CRGB::Black);
delay(INITDELAY);
}
// for DEBUG purpose without Serial connection...
void showInitColor(CRGB Color)
{
#ifdef DEBUG
FastLED.showColor(Color);
#endif
}
// setup the Wifi connection with Wifi Manager...
void setupWiFi(void)
{
showInitColor(CRGB::Blue);
delay(INITDELAY);
WiFi.hostname(LED_NAME + String(ESP.getChipId()));
WiFiManager wifiManager;
// 4 Minutes should be sufficient.
// Especially in case of WiFi loss...
wifiManager.setConfigPortalTimeout(240);
//tries to connect to last known settings
//if it does not connect it starts an access point with the specified name
//here "AutoConnectAP" with password "password"
//and goes into a blocking loop awaiting configuration
DEBUGPRNT("Going to autoconnect and/or Start AP");
if (!wifiManager.autoConnect(AP_SSID.c_str()))
{
DEBUGPRNT("failed to connect, we should reset as see if it connects");
showInitColor(CRGB::Yellow);
delay(3000);
showInitColor(CRGB::Red);
ESP.restart();
delay(5000);
}
//if we get here we have connected to the WiFi
DEBUGPRNT("local ip: ");
DEBUGPRNT(WiFi.localIP());
showInitColor(CRGB::Green);
delay(INITDELAY);
showInitColor(CRGB::Black);
}
// helper function to change an 8bit value by the given percentage
// TODO: we could use 8bit fractions for performance
uint8_t changebypercentage(uint8_t value, uint8_t percentage)
{
uint16_t ret = max((value * percentage) / 100, 10);
if (ret > 255)
ret = 255;
return (uint8_t)ret;
}
// if /set was called
void handleSet(void)
{
bool sendStatus = false;
// Debug only
#ifdef DEBUG
DEBUGPRNT("<Begin>Server Args:");
for (uint8_t i = 0; i < server.args(); i++)
{
DEBUGPRNT(server.argName(i) + "\t" + server.arg(i));
}
DEBUGPRNT("<End> Server Args");
#endif
// to be completed in general
// TODO: question: is there enough memory to store color and "timing" per pixel?
// i.e. uint32_t onColor, OffColor, uint16_t ontime, offtime
// = 12 * 300 = 3600 byte...???
// this will be a new branch possibly....
// The following list is unfortunately not complete....
// mo = mode set (eihter +, - or value)
// br = brightness (eihter +, - or value)
// co = color (32 bit unsigned color)
// re = red value of color (eihter +, - or value)
// gr = green value of color (eihter +, - or value)
// bl = blue value of color (eihter +, - or value)
// sp = speed (eihter +, - or value)
// sec = sunrise / sunset time in seconds....
// min = sunrise/ sunset time in minutes
// pi = pixel to be set (clears others?)
// rnS = Range start Pixel;
// rnE = Range end Pixel;
// here we set a new mode if we have the argument mode
if (server.hasArg("mo"))
{
// flag to decide if this is an library effect
bool isWS2812FX = false;
// current library effect number
uint8_t effect = strip->getMode();
DEBUGPRNT("got Argument mo....");
// just switch to the next if we get an "u" for up
if (server.arg("mo")[0] == 'u')
{
DEBUGPRNT("got Argument mode up....");
//effect = effect + 1;
isWS2812FX = true;
effect = strip->nextMode(AUTO_MODE_UP);
}
// switch to the previous one if we get a "d" for down
else if (server.arg("mo")[0] == 'd')
{
DEBUGPRNT("got Argument mode down....");
//effect = effect - 1;
isWS2812FX = true;
effect = strip->nextMode(AUTO_MODE_DOWN);
}
// if we get an "o" for off, we switch off
else if (server.arg("mo")[0] == 'o')
{
DEBUGPRNT("got Argument mode Off....");
strip->setPower(false);
sendString("state", "off");
//broadcastInt("power", false);
}
// for backward compatibility and FHEM:
// --> activate fire flicker
else if (server.arg("mo")[0] == 'f')
{
DEBUGPRNT("got Argument fire....");
effect = FX_MODE_FIRE_FLICKER;
isWS2812FX = true;
}
// for backward compatibility and FHEM:
// --> activate rainbow effect
else if (server.arg("mo")[0] == 'r')
{
DEBUGPRNT("got Argument mode rainbow cycle....");
effect = FX_MODE_RAINBOW_CYCLE;
isWS2812FX = true;
}
// for backward compatibility and FHEM:
// --> activate the K.I.T.T. (larson scanner)
else if (server.arg("mo")[0] == 'k')
{
DEBUGPRNT("got Argument mode KITT....");
effect = FX_MODE_LARSON_SCANNER;
isWS2812FX = true;
}
// for backward compatibility and FHEM:
// --> activate Twinkle Fox
else if (server.arg("mo")[0] == 's')
{
DEBUGPRNT("got Argument mode Twinkle Fox....");
effect = FX_MODE_TWINKLE_FOX;
isWS2812FX = true;
}
// for backward compatibility and FHEM:
// --> activate Twinkle Fox in white...
else if (server.arg("mo")[0] == 'w')
{
DEBUGPRNT("got Argument mode White Twinkle....");
strip->setColor(CRGBPalette16(CRGB::White));
effect = FX_MODE_TWINKLE_FOX;
isWS2812FX = true;
}
// sunrise effect
else if (server.arg("mo") == "Sunrise")
{
DEBUGPRNT("got Argument mode sunrise....");
// sunrise time in seconds
if (server.hasArg("sec"))
{
DEBUGPRNT("got Argument sec....");
strip->setSunriseTime(((uint16_t)strtoul(&server.arg("sec")[0], NULL, 10)) / 60);
}
// sunrise time in minutes
else if (server.hasArg("min"))
{
DEBUGPRNT("got Argument min....");
strip->setSunriseTime(((uint16_t)strtoul(&server.arg("sec")[0], NULL, 10)));
}
isWS2812FX = true;
effect = FX_MODE_SUNRISE;
strip->setTransition();
//broadcastInt("sunriseset", strip->getSunriseTime());
//sendStatus = true;
}
// the same for sunset....
else if (server.arg("mo") == "Sunset")
{
DEBUGPRNT("got Argument mode sunset....");
// sunrise time in seconds
if (server.hasArg("sec"))
{
DEBUGPRNT("got Argument sec....");
strip->setSunriseTime(((uint16_t)strtoul(&server.arg("sec")[0], NULL, 10)) / 60);
}
// sunrise time in minutes
else if (server.hasArg("min"))
{
DEBUGPRNT("got Argument min....");
strip->setSunriseTime( ((uint16_t)strtoul(&server.arg("min")[0], NULL, 10)));
}
// answer for the "calling" party
isWS2812FX = true;
effect = FX_MODE_SUNSET;
strip->setTransition();
//broadcastInt("sunriseset", strip->getSunriseTime());
//sendStatus = true;
}
// finally - if nothing matched before - we switch to the effect being provided.
// we don't care if its actually an int or not
// because it will be zero anyway if not.
else
{
DEBUGPRNT("got Argument mode and seems to be an Effect....");
effect = (uint8_t)strtoul(&server.arg("mo")[0], NULL, 10);
isWS2812FX = true;
}
// sanity only, actually handled in the library...
if (effect >= strip->getModeCount())
{
DEBUGPRNT("Effect to high....");
effect = 0;
}
// activate the effect...
if (isWS2812FX)
{
strip->setMode(effect);
// in case it was stopped before
// seems to be obsolete but does not hurt anyway...
strip->start();
DEBUGPRNT("gonna send mo response....");
//broadcastInt("power", true);
}
}
// global on/off
if (server.hasArg("power"))
{
DEBUGPRNT("got Argument power....");
if (server.arg("power")[0] == '0')
{
strip->setPower(false);
}
else
{
strip->setPower(true);
strip->setMode(strip->getMode());
}
sendString("state", strip->getPower() ? "on" : "off");
//broadcastInt("power", strip->getPower());
}
if(server.hasArg("isRunning"))
{
DEBUGPRNT("got Argument \"isRunning\"....");
if (server.arg("isRunning")[0] == '0')
{
strip->setIsRunning(false);
}
else
{
strip->setIsRunning(true);
}
sendString("state", strip->isRunning() ? "on" : "off");
//broadcastInt("power", strip->isRunning());
}
// if we got a palette change
if (server.hasArg("pa"))
{
// TODO: Possibility to setColors and new Palettes...
uint8_t pal = (uint8_t)strtoul(&server.arg("pa")[0], NULL, 10);
DEBUGPRNT("New palette with value: " + String(pal));
strip->setTargetPalette(pal);
// sendAnswer( "\"palette\": " + String(pal) + ", \"palette name\": \"" +
// (String)strip->getPalName(pal) + "\"");
// broadcastInt("pa", pal);
}
// if we got a new brightness value
if (server.hasArg("br"))
{
DEBUGPRNT("got Argument brightness....");
uint8_t brightness = strip->getBrightness();
if (server.arg("br")[0] == 'u')
{
brightness = changebypercentage(brightness, 110);
}
else if (server.arg("br")[0] == 'd')
{
brightness = changebypercentage(brightness, 90);
}
else
{
brightness = constrain((uint8_t)strtoul(&server.arg("br")[0], NULL, 10), BRIGHTNESS_MIN, BRIGHTNESS_MAX);
}
strip->setBrightness(brightness);
sendInt("brightness", brightness);
//broadcastInt("br", strip->getBrightness());
}
// if we got a speed value
// for backward compatibility.
// is beat88 value anyway
if (server.hasArg("sp"))
{
#ifdef DEBUG
DEBUGPRNT("got Argument speed....");
#endif
uint16_t speed = strip->getBeat88();
if (server.arg("sp")[0] == 'u')
{
uint16_t ret = max((speed * 115) / 100, 10);
if (ret > BEAT88_MAX)
ret = BEAT88_MAX;
speed = ret;
}
else if (server.arg("sp")[0] == 'd')
{
uint16_t ret = max((speed * 80) / 100, 10);
if (ret > BEAT88_MAX)
ret = BEAT88_MAX;
speed = ret;
}
else
{
speed = constrain((uint16_t)strtoul(&server.arg("sp")[0], NULL, 10), BEAT88_MIN, BEAT88_MAX);
}
strip->setSpeed(speed);
strip->show();
sendAnswer("\"speed\": " + String(speed) + ", \"beat88\": \"" + String(speed));
//broadcastInt("sp", strip->getBeat88());
strip->setTransition();
}
// if we got a speed value (as beat88)
if (server.hasArg("be"))
{
#ifdef DEBUG
DEBUGPRNT("got Argument speed (beat)....");
#endif
uint16_t speed = strip->getBeat88();