-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfw1906_generic_ok.ino
1135 lines (1018 loc) · 68.8 KB
/
fw1906_generic_ok.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
// Creates a single length diyHue Strip Light which can be divided into several sections.
// Each section will be exposed as a single "light" entity in DIYhue dashboard.
// Default 3 sections, can be set to less or more. Can be set to 1 section.
// Each section does NOT have to be same number of pixels. (section 1 can be 10 pixels, section 2 can be 99 pixeles ect)
// Changing number of sections will require deleting/adding the light(s) in DIYhue dashboard. super easy!
//
// After flashing first time, or after erasing flash, connect to DIY hue wifi Access Point, go to webpage 192.168.4.1 to configure wifi.
// enter device IP address into browser to configure LED sections, LED pixel count (save & reboot), and set Static IP (save & reboot)
// then add device to DIYhue dashboard via STATIC IP address.
#include <FS.h>
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <WiFiUdp.h>
#include <ESP8266HTTPUpdateServer.h>
#include <ESP8266WebServer.h>
#include <NeoPixelBus.h>
#include <WiFiManager.h>
#include <ArduinoJson.h>
IPAddress address ( 192, 168, 0, 95); // choose an unique IP Adress
IPAddress gateway ( 192, 168, 0, 1); // Router IP
IPAddress submask(255, 255, 255, 0);
#define LIGHT_VERSION 3.1
#define LIGHT_NAME_MAX_LENGTH 32 // Longer name will get stripped
#define ENTERTAINMENT_TIMEOUT 1500 // millis
#define POWER_MOSFET_PIN 13 // By installing a MOSFET it will cut the power to the leds when lights ore off.
// Warm White (2000K)
const uint8_t WWHITE_CT_R = 255;
const uint8_t WWHITE_CT_G = 138;
const uint8_t WWHITE_CT_B = 18;
// Cool White (6500K)
const uint8_t CWHITE_CT_R = 255;
const uint8_t CWHITE_CT_G = 249;
const uint8_t CWHITE_CT_B = 253;
float covertedColor[5];
struct state {
uint8_t colors[5], bri = 100, sat = 254, colorMode = 2;
bool lightState;
int ct = 200, hue;
float stepLevel[5], currentColors[5], x, y;
};
state lights[10];
bool inTransition, entertainmentRun, mosftetState, useDhcp = true;
byte mac[6], packetBuffer[46];
unsigned long lastEPMillis;
//settings
char lightName[LIGHT_NAME_MAX_LENGTH] = "Hue fw1906 strip";
uint8_t scene, startup, onPin = 4, offPin = 5;
int RgbAdditionalPct = 0;
int CtBlendRgbPctW = 0;
int CtBlendRgbPctC = 0;
bool hwSwitch = false;
uint8_t rgb_multiplier[] = {100, 100, 100}; // light multiplier in percentage /R, G, B/
bool rgbctswitch = false;
bool ctblendswitch = false;
uint8_t lightsCount = 3;
uint16_t dividedLightsArray[30];
uint16_t pixelCount = 60;
uint8_t transitionLeds = 6; // pixelCount must be divisible by this value
ESP8266WebServer server(80);
WiFiUDP Udp;
ESP8266HTTPUpdateServer httpUpdateServer;
RgbwwColor red = RgbwwColor(255, 0, 0, 0, 0);
RgbwwColor green = RgbwwColor(0, 255, 0, 0, 0);
RgbwwColor white = RgbwwColor(0,0,0,127,127);
RgbwwColor black = RgbwwColor(0);
//NeoPixelBus<NeoGrbcwxFeature, Neo800KbpsMethod>* strip = NULL;
NeoPixelBus<NeoGrbcwxFeature, NeoWs2812xMethod>* strip = NULL;
void convertHue(uint8_t light) // convert hue / sat values from HUE API to RGB
{
double hh, p, q, t, ff, s, v;
long i;
s = lights[light].sat / 255.0;
v = lights[light].bri / 255.0;
if (s <= 0.0) { // < is bogus, just shuts up warnings
lights[light].colors[0] = v;
lights[light].colors[1] = v;
lights[light].colors[2] = v;
return;
}
hh = lights[light].hue;
if (hh >= 65535.0) hh = 0.0;
hh /= 11850, 0;
i = (long)hh;
ff = hh - i;
p = v * (1.0 - s);
q = v * (1.0 - (s * ff));
t = v * (1.0 - (s * (1.0 - ff)));
switch (i) {
case 0:
lights[light].colors[0] = v * 255.0;
lights[light].colors[1] = t * 255.0;
lights[light].colors[2] = p * 255.0;
lights[light].colors[3] = 0;
lights[light].colors[4] = 0;
break;
case 1:
lights[light].colors[0] = q * 255.0;
lights[light].colors[1] = v * 255.0;
lights[light].colors[2] = p * 255.0;
lights[light].colors[3] = 0;
lights[light].colors[4] = 0;
break;
case 2:
lights[light].colors[0] = p * 255.0;
lights[light].colors[1] = v * 255.0;
lights[light].colors[2] = t * 255.0;
lights[light].colors[3] = 0;
lights[light].colors[4] = 0;
break;
case 3:
lights[light].colors[0] = p * 255.0;
lights[light].colors[1] = q * 255.0;
lights[light].colors[2] = v * 255.0;
lights[light].colors[3] = 0;
lights[light].colors[4] = 0;
break;
case 4:
lights[light].colors[0] = t * 255.0;
lights[light].colors[1] = p * 255.0;
lights[light].colors[2] = v * 255.0;
lights[light].colors[3] = 0;
lights[light].colors[4] = 0;
break;
case 5:
default:
lights[light].colors[0] = v * 255.0;
lights[light].colors[1] = p * 255.0;
lights[light].colors[2] = q * 255.0;
lights[light].colors[3] = 0;
lights[light].colors[4] = 0;
break;
}
convertRgbToRgbwc(light);
}
void convertXy(uint8_t light) // convert CIE xy values from HUE API to RGB
{
int optimal_bri = lights[light].bri;
if (optimal_bri < 5) {
optimal_bri = 5;
}
float Y = lights[light].y;
float X = lights[light].x;
float Z = 1.0f - lights[light].x - lights[light].y;
// sRGB D65 conversion
float r = X * 3.2406f - Y * 1.5372f - Z * 0.4986f;
float g = -X * 0.9689f + Y * 1.8758f + Z * 0.0415f;
float b = X * 0.0557f - Y * 0.2040f + Z * 1.0570f;
// Apply gamma correction
r = r <= 0.0031308f ? 12.92f * r : (1.0f + 0.055f) * pow(r, (1.0f / 2.4f)) - 0.055f;
g = g <= 0.0031308f ? 12.92f * g : (1.0f + 0.055f) * pow(g, (1.0f / 2.4f)) - 0.055f;
b = b <= 0.0031308f ? 12.92f * b : (1.0f + 0.055f) * pow(b, (1.0f / 2.4f)) - 0.055f;
// Apply multiplier for white correction
r = r * rgb_multiplier[0] / 100;
g = g * rgb_multiplier[1] / 100;
b = b * rgb_multiplier[2] / 100;
if (r > b && r > g) {
// red is biggest
if (r > 1.0f) {
g = g / r;
b = b / r;
r = 1.0f;
}
}
else if (g > b && g > r) {
// green is biggest
if (g > 1.0f) {
r = r / g;
b = b / g;
g = 1.0f;
}
}
else if (b > r && b > g) {
// blue is biggest
if (b > 1.0f) {
r = r / b;
g = g / b;
b = 1.0f;
}
}
r = r < 0 ? 0 : r;
g = g < 0 ? 0 : g;
b = b < 0 ? 0 : b;
lights[light].colors[0] = (int) (r * optimal_bri); lights[light].colors[1] = (int) (g * optimal_bri); lights[light].colors[2] = (int) (b * optimal_bri); lights[light].colors[3] = 0; lights[light].colors[4] = 0;
convertRgbToRgbwc(light);
}
void convertCt(uint8_t light) // convert ct (color temperature) value from HUE API to RGB
{
int hectemp = 10000 / lights[light].ct;
int optimal_bri = int(3 + lights[light].bri / 1.01);
int optimal_bri_rgb = int(optimal_bri * RgbAdditionalPct / 100);
int r, g, b;
if (hectemp <= 66) {
r = 255;
g = 99.4708025861 * log(hectemp) - 161.1195681661;
b = hectemp <= 19 ? 0 : (138.5177312231 * log(hectemp - 10) - 305.0447927307);
} else {
r = 329.698727446 * pow(hectemp - 60, -0.1332047592);
g = 288.1221695283 * pow(hectemp - 60, -0.0755148492);
b = 255;
}
r = r > 255 ? 255 : r;
g = g > 255 ? 255 : g;
b = b > 255 ? 255 : b;
// Apply multiplier for white correction
r = r * rgb_multiplier[0] / 100;
g = g * rgb_multiplier[1] / 100;
b = b * rgb_multiplier[2] / 100;
lights[light].colors[0] = r * (optimal_bri_rgb / 255.0f); lights[light].colors[1] = g * (optimal_bri_rgb / 255.0f); lights[light].colors[2] = b * (optimal_bri_rgb / 255.0f);
uint8 percent_warm = ((lights[light].ct - 150) * 100) / 350;
lights[light].colors[3] = (optimal_bri * percent_warm) / 100;
lights[light].colors[4] = (optimal_bri * (100 - percent_warm)) / 100;
}
void convertRgbToRgbwc(uint8_t light) {
uint8_t r = lights[light].colors[0];
uint8_t g = lights[light].colors[1];
uint8_t b = lights[light].colors[2];
convertColorRgbToRgbwc(r, g, b);
for (uint8_t k = 0; k < 5; k++) { //loop with every RGB channel
lights[light].colors[k] = covertedColor[k];
}
}
void convertColorRgbToRgbwc(uint8_t r, uint8_t g, uint8_t b) {
uint8_t r0 = r;
uint8_t g0 = g;
uint8_t b0 = b;
// get highest replacement by warm white
float wwhiteValueForRed = r0 * 255.0 / WWHITE_CT_R;
float wwhiteValueForGreen = g0 * 255.0 / WWHITE_CT_G;
float wwhiteValueForBlue = b0 * 255.0 / WWHITE_CT_B;
float minWWhiteValue = min(wwhiteValueForRed,
min(wwhiteValueForGreen,
wwhiteValueForBlue)) * CtBlendRgbPctW / 100;
// get highest replacement by cold white
float cwhiteValueForRed = r0 * 255.0 / CWHITE_CT_R;
float cwhiteValueForGreen = g0 * 255.0 / CWHITE_CT_G;
float cwhiteValueForBlue = b0 * 255.0 / CWHITE_CT_B;
float minCWhiteValue = min(cwhiteValueForRed,
min(cwhiteValueForGreen,
cwhiteValueForBlue)) * CtBlendRgbPctC / 100;
// balance warm and cold white replacement
float Wtot = (minCWhiteValue + minWWhiteValue);
float CWpct = (Wtot != 0 ? minCWhiteValue / Wtot : 0);
float WWpct = (Wtot != 0 ? minWWhiteValue / Wtot : 0);
minCWhiteValue = minCWhiteValue * CWpct;
minWWhiteValue = minWWhiteValue * WWpct;
uint8_t CW = (minCWhiteValue <= 255 ? (uint8_t) minCWhiteValue : 255);
uint8_t WW = (minWWhiteValue <= 255 ? (uint8_t) minWWhiteValue : 255);
//subtract warm white on rgb channels
uint8_t r1 = (uint8_t)(r0 - minWWhiteValue * WWHITE_CT_R / 255);
uint8_t g1 = (uint8_t)(g0 - minWWhiteValue * WWHITE_CT_G / 255);
uint8_t b1 = (uint8_t)(b0 - minWWhiteValue * WWHITE_CT_B / 255);
//subtract cold white on rgb channels
uint8_t r2 = (uint8_t)(r1- minCWhiteValue * WWHITE_CT_R / 255);
uint8_t g2 = (uint8_t)(g1 - minCWhiteValue * WWHITE_CT_G / 255);
uint8_t b2 = (uint8_t)(b1 - minCWhiteValue * WWHITE_CT_B / 255);
//result
covertedColor[0] = r2;
covertedColor[1] = g2;
covertedColor[2] = b2;
covertedColor[3] = WW;
covertedColor[4] = CW;
}
void handleNotFound() { // default webserver response for unknow requests
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET) ? "GET" : "POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i = 0; i < server.args(); i++) {
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void infoLight(RgbwwColor color) { // boot animation for leds count and wifi test
// Flash the strip in the selected color. White = booted, green = WLAN connected, red = WLAN could not connect
for (int i = 0; i < pixelCount; i++)
{
strip->SetPixelColor(i, color);
strip->Show();
delay(10);
strip->SetPixelColor(i, black);
strip->Show();
}
}
void apply_scene(uint8_t new_scene) { // these are internal scenes store in light firmware that can be applied on boot and manually from light web interface
for (uint8_t light = 0; light < lightsCount; light++) {
if ( new_scene == 1) {
lights[light].bri = 254; lights[light].ct = 346; lights[light].colorMode = 2; convertCt(light);
} else if ( new_scene == 2) {
lights[light].bri = 254; lights[light].ct = 233; lights[light].colorMode = 2; convertCt(light);
} else if ( new_scene == 3) {
lights[light].bri = 254; lights[light].ct = 156; lights[light].colorMode = 2; convertCt(light);
} else if ( new_scene == 4) {
lights[light].bri = 77; lights[light].ct = 367; lights[light].colorMode = 2; convertCt(light);
} else if ( new_scene == 5) {
lights[light].bri = 254; lights[light].ct = 447; lights[light].colorMode = 2; convertCt(light);
} else if ( new_scene == 6) {
lights[light].bri = 1; lights[light].x = 0.561; lights[light].y = 0.4042; lights[light].colorMode = 1; convertXy(light);
} else if ( new_scene == 7) {
lights[light].bri = 203; lights[light].x = 0.380328; lights[light].y = 0.39986; lights[light].colorMode = 1; convertXy(light);
} else if ( new_scene == 8) {
lights[light].bri = 112; lights[light].x = 0.359168; lights[light].y = 0.28807; lights[light].colorMode = 1; convertXy(light);
} else if ( new_scene == 9) {
lights[light].bri = 142; lights[light].x = 0.267102; lights[light].y = 0.23755; lights[light].colorMode = 1; convertXy(light);
} else if ( new_scene == 10) {
lights[light].bri = 216; lights[light].x = 0.393209; lights[light].y = 0.29961; lights[light].colorMode = 1; convertXy(light);
} else {
lights[light].bri = 144; lights[light].ct = 447; lights[light].colorMode = 2; convertCt(light);
}
}
}
void processLightdata(uint8_t light, float transitiontime) { // calculate the step level of every RGB channel for a smooth transition in requested transition time
transitiontime *= 17 - (pixelCount / 40); //every extra led add a small delay that need to be counted for transition time match
if (lights[light].colorMode == 1 && lights[light].lightState == true) {
convertXy(light);
} else if (lights[light].colorMode == 2 && lights[light].lightState == true) {
convertCt(light);
} else if (lights[light].colorMode == 3 && lights[light].lightState == true) {
convertHue(light);
}
for (uint8_t i = 0; i < 5; i++) {
if (lights[light].lightState) {
lights[light].stepLevel[i] = ((float)lights[light].colors[i] - lights[light].currentColors[i]) / transitiontime;
} else {
lights[light].stepLevel[i] = lights[light].currentColors[i] / transitiontime;
}
}
}
RgbwwColor blending(float left[5], float right[5], uint8_t pixel) { // return RgbwwColor based on neighbour leds
uint8_t result[5];
for (uint8_t i = 0; i < 5; i++) {
float percent = (float) pixel / (float) (transitionLeds + 1);
result[i] = (left[i] * (1.0f - percent) + right[i] * percent);
}
return RgbwwColor((uint8_t)result[0], (uint8_t)result[1], (uint8_t)result[2], (uint8_t)result[3], (uint8_t)result[4]);
}
RgbwwColor convFloat(float color[5]) { // return RgbwwColor from float
return RgbwwColor((uint8_t)color[0], (uint8_t)color[1], (uint8_t)color[2], (uint8_t)color[3], (uint8_t)color[4]);
}
void cutPower() {
bool any_on = false;
for (int light = 0; light < lightsCount; light++) {
if (lights[light].lightState) {
any_on = true;
}
}
if (!any_on && !inTransition && mosftetState) {
digitalWrite(POWER_MOSFET_PIN, LOW);
mosftetState = false;
} else if (any_on && !mosftetState){
digitalWrite(POWER_MOSFET_PIN, HIGH);
mosftetState = true;
}
}
void lightEngine() { // core function executed in loop()
for (int light = 0; light < lightsCount; light++) { // loop with every virtual light
if (lights[light].lightState) { // if light in on
if (lights[light].colors[0] != lights[light].currentColors[0] || lights[light].colors[1] != lights[light].currentColors[1] || lights[light].colors[2] != lights[light].currentColors[2] || lights[light].colors[3] != lights[light].currentColors[3] || lights[light].colors[4] != lights[light].currentColors[4]) { // if not all RGB channels of the light are at desired level
inTransition = true;
for (uint8_t k = 0; k < 5; k++) { // loop with every RGB channel of the light
if (lights[light].colors[k] != lights[light].currentColors[k]) lights[light].currentColors[k] += lights[light].stepLevel[k]; // move RGB channel on step closer to desired level
if ((lights[light].stepLevel[k] > 0.0 && lights[light].currentColors[k] > lights[light].colors[k]) || (lights[light].stepLevel[k] < 0.0 && lights[light].currentColors[k] < lights[light].colors[k])) lights[light].currentColors[k] = lights[light].colors[k]; // if the current level go below desired level apply directly the desired level.
}
if (lightsCount > 1) { // if are more then 1 virtual light we need to apply transition leds (set in the web interface)
if (light == 0) { // if is the first light we must not have transition leds at the beginning
for (int pixel = 0; pixel < dividedLightsArray[0]; pixel++) // loop with all leds of the light (declared in web interface)
{
if (pixel < dividedLightsArray[0] - transitionLeds / 2) { // apply raw color if we are outside transition leds
strip->SetPixelColor(pixel, convFloat(lights[light].currentColors));
} else {
strip->SetPixelColor(pixel, blending(lights[0].currentColors, lights[1].currentColors, pixel + 1 - (dividedLightsArray[0] - transitionLeds / 2 ))); // calculate the transition led color
}
}
}
else { // is not the first virtual light
for (int pixel = 0; pixel < dividedLightsArray[light]; pixel++) // loop with all leds of the light
{
long pixelSum;
for (int value = 0; value < light; value++)
{
if (value + 1 == light) {
pixelSum += dividedLightsArray[value] - transitionLeds;
}
else {
pixelSum += dividedLightsArray[value];
}
}
if (pixel < transitionLeds / 2) { // beginning transition leds
strip->SetPixelColor(pixel + pixelSum + transitionLeds, blending( lights[light - 1].currentColors, lights[light].currentColors, pixel + 1));
}
else if (pixel > dividedLightsArray[light] - transitionLeds / 2 - 1) { // end of transition leds
//Serial.println(String(pixel));
strip->SetPixelColor(pixel + pixelSum + transitionLeds, blending( lights[light].currentColors, lights[light + 1].currentColors, pixel + transitionLeds / 2 - dividedLightsArray[light]));
}
else { // outside transition leds (apply raw color)
strip->SetPixelColor(pixel + pixelSum + transitionLeds, convFloat(lights[light].currentColors));
}
pixelSum = 0;
}
}
} else { // strip has only one virtual light so apply raw color to entire strip
strip->ClearTo(convFloat(lights[light].currentColors), 0, pixelCount - 1);
}
strip->Show(); //show what was calculated previously
}
} else { // if light in off, calculate the dimming effect only
if (lights[light].currentColors[0] != 0 || lights[light].currentColors[1] != 0 || lights[light].currentColors[2] != 0 || lights[light].currentColors[3] != 0 || lights[light].currentColors[4] != 0) { // proceed forward only in case not all RGB channels are zero
inTransition = true;
for (uint8_t k = 0; k < 5; k++) { //loop with every RGB channel
if (lights[light].currentColors[k] != 0) lights[light].currentColors[k] -= lights[light].stepLevel[k]; // remove one step level
if (lights[light].currentColors[k] < 0) lights[light].currentColors[k] = 0; // save condition, if level go below zero set it to zero
}
if (lightsCount > 1) { // if the strip has more than one light
if (light == 0) { // if is the first light of the strip
for (int pixel = 0; pixel < dividedLightsArray[0]; pixel++) // loop with every led of the virtual light
{
if (pixel < dividedLightsArray[0] - transitionLeds / 2) { // leds until transition zone apply raw color
strip->SetPixelColor(pixel, convFloat(lights[light].currentColors));
} else { // leds in transition zone apply the transition color
strip->SetPixelColor(pixel, blending(lights[0].currentColors, lights[1].currentColors, pixel + 1 - (dividedLightsArray[0] - transitionLeds / 2 )));
}
}
}
else { // is not the first light
for (int pixel = 0; pixel < dividedLightsArray[light]; pixel++) // loop with every led
{
long pixelSum;
for (int value = 0; value < light; value++)
{
if (value + 1 == light) {
pixelSum += dividedLightsArray[value] - transitionLeds;
}
else {
pixelSum += dividedLightsArray[value];
}
}
if (pixel < transitionLeds / 2) { // leds in beginning of transition zone must apply blending
strip->SetPixelColor(pixel + pixelSum + transitionLeds, blending( lights[light - 1].currentColors, lights[light].currentColors, pixel + 1));
}
else if (pixel > dividedLightsArray[light] - transitionLeds / 2 - 1) { // leds in the end of transition zone must apply blending
//Serial.println(String(pixel));
strip->SetPixelColor(pixel + pixelSum + transitionLeds, blending( lights[light].currentColors, lights[light + 1].currentColors, pixel + transitionLeds / 2 - dividedLightsArray[light]));
}
else { // leds outside transition zone apply raw color
strip->SetPixelColor(pixel + pixelSum + transitionLeds, convFloat(lights[light].currentColors));
}
pixelSum = 0;
}
}
} else { // is just one virtual light declared, apply raw color to all leds
strip->ClearTo(convFloat(lights[light].currentColors), 0, pixelCount - 1);
}
strip->Show();
}
}
}
cutPower(); // if all lights are off GPIO12 can cut the power to the strip using a powerful P-Channel MOSFET
if (inTransition) { // wait 6ms for a nice transition effect
delay(6);
inTransition = false; // set inTransition bash to false (will be set bach to true on next level execution if desired state is not reached)
} else if (hwSwitch == true) { // if you want to use some GPIO's for on/off and brightness controll
if (digitalRead(onPin) == HIGH) { // on button pressed
int i = 0;
while (digitalRead(onPin) == HIGH && i < 30) { // count how log is the button pressed
delay(20);
i++;
}
for (int light = 0; light < lightsCount; light++) {
if (i < 30) { // there was a short press
lights[light].lightState = true;
}
else { // there was a long press
lights[light].bri += 56;
if (lights[light].bri > 255) {
// don't increase the brightness more then maximum value
lights[light].bri = 255;
}
}
}
} else if (digitalRead(offPin) == HIGH) { // off button pressed
int i = 0;
while (digitalRead(offPin) == HIGH && i < 30) {
delay(20);
i++;
}
for (int light = 0; light < lightsCount; light++) {
if (i < 30) {
// there was a short press
lights[light].lightState = false;
}
else {
// there was a long press
lights[light].bri -= 56;
if (lights[light].bri < 1) {
// don't decrease the brightness less than minimum value.
lights[light].bri = 1;
}
}
}
}
}
}
void saveState() { // save the lights state on SPIFFS partition in JSON format
DynamicJsonDocument json(1024);
for (uint8_t i = 0; i < lightsCount; i++) {
JsonObject light = json.createNestedObject((String)i);
light["on"] = lights[i].lightState;
light["bri"] = lights[i].bri;
if (lights[i].colorMode == 1) {
light["x"] = lights[i].x;
light["y"] = lights[i].y;
} else if (lights[i].colorMode == 2) {
light["ct"] = lights[i].ct;
} else if (lights[i].colorMode == 3) {
light["hue"] = lights[i].hue;
light["sat"] = lights[i].sat;
}
}
File stateFile = SPIFFS.open("/state.json", "w");
serializeJson(json, stateFile);
}
void restoreState() { // restore the lights state from SPIFFS partition
File stateFile = SPIFFS.open("/state.json", "r");
if (!stateFile) {
saveState();
return;
}
DynamicJsonDocument json(1024);
DeserializationError error = deserializeJson(json, stateFile.readString());
if (error) {
//Serial.println("Failed to parse config file");
return;
}
for (JsonPair state : json.as<JsonObject>()) {
const char* key = state.key().c_str();
int lightId = atoi(key);
JsonObject values = state.value();
lights[lightId].lightState = values["on"];
lights[lightId].bri = (uint8_t)values["bri"];
if (values.containsKey("x")) {
lights[lightId].x = values["x"];
lights[lightId].y = values["y"];
lights[lightId].colorMode = 1;
} else if (values.containsKey("ct")) {
lights[lightId].ct = values["ct"];
lights[lightId].colorMode = 2;
} else {
if (values.containsKey("hue")) {
lights[lightId].hue = values["hue"];
lights[lightId].colorMode = 3;
}
if (values.containsKey("sat")) {
lights[lightId].sat = (uint8_t) values["sat"];
lights[lightId].colorMode = 3;
}
}
}
}
bool saveConfig() { // save config in SPIFFS partition in JSON file
DynamicJsonDocument json(1024);
json["name"] = lightName;
json["startup"] = startup;
json["scene"] = scene;
json["on"] = onPin;
json["off"] = offPin;
json["hw"] = hwSwitch;
json["dhcp"] = useDhcp;
json["lightsCount"] = lightsCount;
json["rgbct"] = rgbctswitch;
json["ctblend"] = ctblendswitch;
json["rgbctpct"] = RgbAdditionalPct;
json["ctblendpctc"] = CtBlendRgbPctC;
json["ctblendpctw"] = CtBlendRgbPctW;
for (uint16_t i = 0; i < lightsCount; i++) {
json["dividedLight_" + String(i)] = dividedLightsArray[i];
}
json["pixelCount"] = pixelCount;
json["transLeds"] = transitionLeds;
json["rpct"] = rgb_multiplier[0];
json["gpct"] = rgb_multiplier[1];
json["bpct"] = rgb_multiplier[2];
JsonArray addr = json.createNestedArray("addr");
addr.add(address[0]);
addr.add(address[1]);
addr.add(address[2]);
addr.add(address[3]);
JsonArray gw = json.createNestedArray("gw");
gw.add(gateway[0]);
gw.add(gateway[1]);
gw.add(gateway[2]);
gw.add(gateway[3]);
JsonArray mask = json.createNestedArray("mask");
mask.add(submask[0]);
mask.add(submask[1]);
mask.add(submask[2]);
mask.add(submask[3]);
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
//Serial.println("Failed to open config file for writing");
return false;
}
serializeJson(json, configFile);
return true;
}
bool loadConfig() { // load the configuration from SPIFFS partition
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
//Serial.println("Create new file with default values");
return saveConfig();
}
size_t size = configFile.size();
if (size > 1024) {
//Serial.println("Config file size is too large");
return false;
}
if (configFile.size() > 1024) {
//Serial.println("Config file size is too large");
return false;
}
DynamicJsonDocument json(1024);
DeserializationError error = deserializeJson(json, configFile.readString());
if (error) {
//Serial.println("Failed to parse config file");
return false;
}
strcpy(lightName, json["name"]);
startup = (uint8_t) json["startup"];
scene = (uint8_t) json["scene"];
onPin = (uint8_t) json["on"];
offPin = (uint8_t) json["off"];
hwSwitch = json["hw"];
lightsCount = (uint16_t) json["lightsCount"];
rgbctswitch = json["rgbct"];
RgbAdditionalPct = json["rgbctpct"];
ctblendswitch = json["ctblend"];
CtBlendRgbPctC = json["ctblendpctc"];
CtBlendRgbPctW = json["ctblendpctw"];
for (uint16_t i = 0; i < lightsCount; i++) {
dividedLightsArray[i] = (uint16_t) json["dividedLight_" + String(i)];
}
pixelCount = (uint16_t) json["pixelCount"];
transitionLeds = (uint8_t) json["transLeds"];
if (json.containsKey("rpct")) {
rgb_multiplier[0] = (uint8_t) json["rpct"];
rgb_multiplier[1] = (uint8_t) json["gpct"];
rgb_multiplier[2] = (uint8_t) json["bpct"];
}
useDhcp = json["dhcp"];
address = {json["addr"][0], json["addr"][1], json["addr"][2], json["addr"][3]};
submask = {json["mask"][0], json["mask"][1], json["mask"][2], json["mask"][3]};
gateway = {json["gw"][0], json["gw"][1], json["gw"][2], json["gw"][3]};
return true;
}
void ChangeNeoPixels(uint16_t newCount) {// this set the number of leds of the strip based on web configuration
if (strip != NULL) {
delete strip; // delete the previous dynamically created strip
}
//strip = new NeoPixelBus<NeoGrbcwxFeature, Neo800KbpsMethod>(newCount); // and recreate with new count
strip = new NeoPixelBus<NeoGrbcwxFeature, NeoWs2812xMethod>(newCount); // and recreate with new count
strip->Begin();
}
void setup() {
Serial.begin(115200);
Serial.println();
delay(1000);
pinMode(POWER_MOSFET_PIN, OUTPUT);
digitalWrite(POWER_MOSFET_PIN, HIGH); mosftetState = true; // reuired if HIGH logic power the strip, otherwise must be commented.
Serial.println("mounting FS...");
if (!SPIFFS.begin()) {
//Serial.println("Failed to mount file system");
return;
}
if (!loadConfig()) {
//Serial.println("Failed to load config");
} else {
////Serial.println("Config loaded");
}
dividedLightsArray[lightsCount];
ChangeNeoPixels(pixelCount);
if (startup == 1) {
for (uint8_t i = 0; i < lightsCount; i++) {
lights[i].lightState = true;
}
}
if (startup == 0) {
restoreState();
} else {
apply_scene(scene);
}
for (uint8_t i = 0; i < lightsCount; i++) {
processLightdata(i, 4);
}
if (lights[0].lightState) {
for (uint8_t i = 0; i < 200; i++) {
lightEngine();
}
}
WiFi.mode(WIFI_STA);
WiFiManager wifiManager; // wifimanager will start the configuration SSID if wifi connection is not succesfully
if (!useDhcp) {
wifiManager.setSTAStaticIPConfig(address, gateway, submask);
}
if (!wifiManager.autoConnect(lightName)) { // light was not connected to wifi and not configured so reset.
delay(3000);
ESP.reset();
delay(5000);
}
if (useDhcp) {
address = WiFi.localIP();
gateway = WiFi.gatewayIP();
submask = WiFi.subnetMask();
}
if (! lights[0].lightState) { // test if light zero (must be at last one light) is not set to ON
infoLight(white); // play white anymation
while (WiFi.status() != WL_CONNECTED) { // connection to wifi still not ready
infoLight(red); // play red animation
delay(500);
}
// Show that we are connected
infoLight(green); // connected, play green animation
}
String hostname = lightName;
hostname.replace(" ", "-");
WiFi.hostname("hue-" + hostname);
WiFi.macAddress(mac);
httpUpdateServer.setup(&server); // start http server
Udp.begin(2100); // start entertainment UDP server
if (hwSwitch == true) { // set buttons pins mode in case are used
pinMode(onPin, INPUT);
pinMode(offPin, INPUT);
}
server.on("/state", HTTP_PUT, []() { // HTTP PUT request used to set a new light state
bool stateSave = false;
DynamicJsonDocument root(1024);
DeserializationError error = deserializeJson(root, server.arg("plain"));
if (error) {
server.send(404, "text/plain", "FAIL. " + server.arg("plain"));
} else {
for (JsonPair state : root.as<JsonObject>()) {
const char* key = state.key().c_str();
int light = atoi(key) - 1;
JsonObject values = state.value();
int transitiontime = 4;
if (values.containsKey("xy")) {
lights[light].x = values["xy"][0];
lights[light].y = values["xy"][1];
lights[light].colorMode = 1;
} else if (values.containsKey("ct")) {
lights[light].ct = values["ct"];
lights[light].colorMode = 2;
} else {
if (values.containsKey("hue")) {
lights[light].hue = values["hue"];
lights[light].colorMode = 3;
}
if (values.containsKey("sat")) {
lights[light].sat = values["sat"];
lights[light].colorMode = 3;
}
}
if (values.containsKey("on")) {
if (values["on"]) {
lights[light].lightState = true;
} else {
lights[light].lightState = false;
}
if (startup == 0) {
stateSave = true;
}
}
if (values.containsKey("bri")) {
lights[light].bri = values["bri"];
}
if (values.containsKey("bri_inc")) {
lights[light].bri += (int) values["bri_inc"];
if (lights[light].bri > 255) lights[light].bri = 255;
else if (lights[light].bri < 1) lights[light].bri = 1;
}
if (values.containsKey("transitiontime")) {
transitiontime = values["transitiontime"];
}
if (values.containsKey("alert") && values["alert"] == "select") {
if (lights[light].lightState) {
lights[light].currentColors[0] = 0; lights[light].currentColors[1] = 0; lights[light].currentColors[2] = 0; lights[light].currentColors[3] = 0; lights[light].currentColors[4] = 0;
} else {
lights[light].currentColors[1] = 126; lights[light].currentColors[2] = 126;
}
}
processLightdata(light, transitiontime);
}
String output;
serializeJson(root, output);
server.send(200, "text/plain", output);
if (stateSave) {
saveState();
}
}
});
server.on("/state", HTTP_GET, []() { // HTTP GET request used to fetch current light state
uint8_t light = server.arg("light").toInt() - 1;
DynamicJsonDocument root(1024);
root["on"] = lights[light].lightState;
root["bri"] = lights[light].bri;
JsonArray xy = root.createNestedArray("xy");
xy.add(lights[light].x);
xy.add(lights[light].y);
root["ct"] = lights[light].ct;
root["hue"] = lights[light].hue;
root["sat"] = lights[light].sat;
if (lights[light].colorMode == 1)
root["colormode"] = "xy";
else if (lights[light].colorMode == 2)
root["colormode"] = "ct";
else if (lights[light].colorMode == 3)
root["colormode"] = "hs";
String output;
serializeJson(root, output);
server.send(200, "text/plain", output);
});
server.on("/detect", []() { // HTTP GET request used to discover the light type
char macString[32] = {0};
sprintf(macString, "%02X:%02X:%02X:%02X:%02X:%02X", mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
DynamicJsonDocument root(1024);
root["name"] = lightName;
root["lights"] = lightsCount;
root["protocol"] = "native_multi";
root["modelid"] = "LST002";
root["type"] = "fw1906_strip";
root["mac"] = String(macString);
root["version"] = LIGHT_VERSION;
String output;
serializeJson(root, output);
server.send(200, "text/plain", output);
});
server.on("/config", []() { // used by light web interface to get current configuration
DynamicJsonDocument root(1024);
root["name"] = lightName;
root["scene"] = scene;
root["startup"] = startup;
root["hw"] = hwSwitch;
root["on"] = onPin;
root["off"] = offPin;
root["rgbct"] = rgbctswitch;
root["ctblend"] = ctblendswitch;
root["hwswitch"] = (int)hwSwitch;
root["rgbctswitch"] = (int)rgbctswitch;
root["ctblendswitch"] = (int)ctblendswitch;
root["lightscount"] = lightsCount;
root["rgbctpct"] = RgbAdditionalPct;
root["ctblendpctc"] = CtBlendRgbPctC;
root["ctblendpctw"] = CtBlendRgbPctW;
for (uint8_t i = 0; i < lightsCount; i++) {
root["dividedLight_" + String(i)] = (int)dividedLightsArray[i];
}
root["pixelcount"] = pixelCount;
root["transitionleds"] = transitionLeds;
root["rpct"] = rgb_multiplier[0];
root["gpct"] = rgb_multiplier[1];
root["bpct"] = rgb_multiplier[2];
root["disdhcp"] = (int)!useDhcp;
root["addr"] = (String)address[0] + "." + (String)address[1] + "." + (String)address[2] + "." + (String)address[3];
root["gw"] = (String)gateway[0] + "." + (String)gateway[1] + "." + (String)gateway[2] + "." + (String)gateway[3];
root["sm"] = (String)submask[0] + "." + (String)submask[1] + "." + (String)submask[2] + "." + (String)submask[3];
String output;
serializeJson(root, output);
server.send(200, "text/plain", output);
});
server.on("/", []() { // light http web interface
if (server.arg("section").toInt() == 1) {
server.arg("name").toCharArray(lightName, LIGHT_NAME_MAX_LENGTH);
startup = server.arg("startup").toInt();
scene = server.arg("scene").toInt();
lightsCount = server.arg("lightscount").toInt();
pixelCount = server.arg("pixelcount").toInt();
transitionLeds = server.arg("transitionleds").toInt();
rgb_multiplier[0] = server.arg("rpct").toInt();
rgb_multiplier[1] = server.arg("gpct").toInt();
rgb_multiplier[2] = server.arg("bpct").toInt();
for (uint16_t i = 0; i < lightsCount; i++) {
dividedLightsArray[i] = server.arg("dividedLight_" + String(i)).toInt();
}
hwSwitch = server.hasArg("hwswitch") ? server.arg("hwswitch").toInt() : 0;
if (server.hasArg("hwswitch")) {
onPin = server.arg("on").toInt();
offPin = server.arg("off").toInt();
}
rgbctswitch = server.hasArg("rgbctswitch") ? server.arg("rgbctswitch").toInt() : 0;
if (server.hasArg("rgbctswitch")) {
RgbAdditionalPct = server.arg("rgbctpct").toInt();
} else {
RgbAdditionalPct = 0;
}