-
Notifications
You must be signed in to change notification settings - Fork 33
/
Arilux_AL-LC0X.ino
1049 lines (951 loc) · 32.1 KB
/
Arilux_AL-LC0X.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
/*
Alternative firmware for Arilux AL-LC0X series of ESP8266 based RGB LED controllers.
See the README at https://github.com/mertenats/Arilux_AL-LC0X for more information.
Licensed under the MIT license.
*/
#include "config.h"
#include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient - v2.7
#ifdef IR_REMOTE
#include <IRremoteESP8266.h> // https://github.com/markszabo/IRremoteESP8266 - v2.5.4
#include <IRrecv.h>
#include <IRutils.h>
#endif
#ifdef RF_REMOTE
#include <RCSwitch.h> // https://github.com/sui77/rc-switch
#endif
#include <ArduinoOTA.h>
#if defined(HOME_ASSISTANT_MQTT_DISCOVERY) || defined(HOME_ASSISTANT_MQTT_ATTRIBUTES) || defined (JSON)
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson - Version 6.9.1
#endif
#include "Arilux.h"
// in a terminal: telnet arilux.local
#ifdef DEBUG_TELNET
WiFiServer telnetServer(23);
WiFiClient telnetClient;
#endif
// Macros for debugging
#ifdef DEBUG_TELNET
#define DEBUG_PRINT(x) telnetClient.print(x)
#define DEBUG_PRINT_WITH_FMT(x, fmt) telnetClient.print(x, fmt)
#define DEBUG_PRINTLN(x) telnetClient.println(x)
#define DEBUG_PRINTLN_WITH_FMT(x, fmt) telnetClient.println(x, fmt)
#else
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINT_WITH_FMT(x, fmt) Serial.print(x, fmt)
#define DEBUG_PRINTLN(x) Serial.println(x)
#define DEBUG_PRINTLN_WITH_FMT(x, fmt) Serial.println(x, fmt)
#endif
char chipid[12];
char MQTT_CLIENT_ID[32];
char MQTT_TOPIC_PREFIX[32];
// MQTT topics
char ARILUX_MQTT_STATUS_TOPIC[44];
#ifdef HOME_ASSISTANT_MQTT_ATTRIBUTES
char HOME_ASSISTANT_MQTT_ATTRIBUTES_TOPIC[44];
#endif
#ifdef HOME_ASSISTANT_MQTT_DISCOVERY
char HOME_ASSISTANT_MQTT_DISCOVERY_TOPIC[56];
#endif
#ifdef JSON
char ARILUX_MQTT_JSON_STATE_TOPIC[44];
char ARILUX_MQTT_JSON_COMMAND_TOPIC[44];
#else
char ARILUX_MQTT_STATE_STATE_TOPIC[44];
char ARILUX_MQTT_STATE_COMMAND_TOPIC[44];
char ARILUX_MQTT_BRIGHTNESS_STATE_TOPIC[44];
char ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC[44];
char ARILUX_MQTT_COLOR_STATE_TOPIC[44];
char ARILUX_MQTT_COLOR_COMMAND_TOPIC[44];
#if defined(RGBW) || defined (RGBWW)
char ARILUX_MQTT_WHITE_STATE_TOPIC[44];
char ARILUX_MQTT_WHITE_COMMAND_TOPIC[44];
#endif
#endif
// MQTT buffer
char msgBuffer[32];
char friendlyName[64];
volatile uint8_t cmd = ARILUX_CMD_NOT_DEFINED;
Arilux arilux;
#ifdef IR_REMOTE
IRrecv irRecv(ARILUX_IR_PIN);
#endif
#ifdef RF_REMOTE
RCSwitch rcSwitch = RCSwitch();
#endif
#ifdef TLS
WiFiClientSecure wifiClient;
#else
WiFiClient wifiClient;
#endif
PubSubClient mqttClient(wifiClient);
// Real values to write to the LEDs (ex. including brightness and state)
byte realRed = 0;
byte realGreen = 0;
byte realBlue = 0;
// Globals for fade/transitions
bool startFade = false;
unsigned long lastLoop = 0;
int transitionTime = 0;
bool inFade = false;
int loopCount = 0;
int stepR, stepG, stepB;
int redVal, grnVal, bluVal;
// Globals for flash
bool flash = false;
bool startFlash = false;
int flashLength = 0;
unsigned long flashStartTime = 0;
byte flashRed = 0;
byte flashGreen = 0;
byte flashBlue = 0;
byte flashBrightness = 0;
///////////////////////////////////////////////////////////////////////////
// SSL/TLS
///////////////////////////////////////////////////////////////////////////
/*
Function called to verify the fingerprint of the MQTT server certificate
*/
#ifdef TLS
void verifyFingerprint() {
DEBUG_PRINT(F("INFO: Connecting to "));
DEBUG_PRINTLN(MQTT_SERVER);
if (!wifiClient.connect(MQTT_SERVER, MQTT_PORT)) {
DEBUG_PRINTLN(F("ERROR: Connection failed. Halting execution"));
delay(1000);
ESP.reset();
}
if (wifiClient.verify(TLS_FINGERPRINT, MQTT_SERVER)) {
DEBUG_PRINTLN(F("INFO: Connection secure"));
} else {
DEBUG_PRINTLN(F("ERROR: Connection insecure! Halting execution"));
delay(1000);
ESP.reset();
}
}
#endif
///////////////////////////////////////////////////////////////////////////
// Utilities
///////////////////////////////////////////////////////////////////////////
/*
Helper function to subscribe to a MQTT topic
*/
void subscribeToMQTTTopic(const char* topic) {
if (mqttClient.subscribe(topic)) {
DEBUG_PRINT(F("INFO: Sending the MQTT subscribe succeeded for topic: "));
DEBUG_PRINTLN(topic);
} else {
DEBUG_PRINT(F("ERROR: Sending the MQTT subscribe failed for topic: "));
DEBUG_PRINTLN(topic);
}
}
/*
Helper function to publish to a MQTT topic with the given payload
*/
void publishToMQTT(const char* topic, const char* payload) {
if (mqttClient.publish(topic, payload, true)) {
DEBUG_PRINT(F("INFO: MQTT message publish succeeded. Topic: "));
DEBUG_PRINT(topic);
DEBUG_PRINT(F(". Payload: "));
DEBUG_PRINTLN(payload);
} else {
DEBUG_PRINTLN(F("ERROR: MQTT message publish failed, either connection lost, or message too large"));
}
}
#ifdef HOME_ASSISTANT_MQTT_ATTRIBUTES
void publishAttributes(void) {
StaticJsonDocument<512> root;
root["BSSID"] = WiFi.BSSIDstr();
root["Chip ID"] = chipid;
root["Hostname"] = MQTT_CLIENT_ID;
root["IP Address"] = WiFi.localIP().toString();
root["LED Strip Type"] = arilux.getColorString();
root["MAC Address"] = WiFi.macAddress();
root["Model"] = DEVICE_MODEL;
root["Remote Type"] = "None";
#if defined(IR_REMOTE)
root["Remote Type"] = "Infrared (IR)";
#elif defined(RF_REMOTE)
root["Remote Type"] = "Radio Frequency (RF)";
#endif
root["RSSI"] = WiFi.RSSI();
root["SSID"] = WiFi.SSID();
root["Telnet Logging Enabled"] = false;
#if defined(DEBUG_TELNET)
root["Telnet Logging Enabled"] = true;
#endif
char outgoingJsonBuffer[512];
serializeJson(root, outgoingJsonBuffer);
publishToMQTT(HOME_ASSISTANT_MQTT_ATTRIBUTES_TOPIC, outgoingJsonBuffer);
}
#endif
#ifdef HOME_ASSISTANT_MQTT_DISCOVERY
void publishDiscovery(void) {
StaticJsonDocument<512> root;
root["name"] = friendlyName;
root["availability_topic"] = ARILUX_MQTT_STATUS_TOPIC;
#ifdef HOME_ASSISTANT_MQTT_ATTRIBUTES
root["json_attributes_topic"] = HOME_ASSISTANT_MQTT_ATTRIBUTES_TOPIC;
#endif
#ifdef JSON
root["brightness"] = true;
root["command_topic"] = ARILUX_MQTT_JSON_COMMAND_TOPIC;
root["rgb"] = true;
root["schema"] = "json";
root["state_topic"] = ARILUX_MQTT_JSON_STATE_TOPIC;
#if defined(RGBW) || defined (RGBWW)
root["white_value"] = true;
#endif
#else
root["brightness_command_topic"] = ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC;
root["brightness_state_topic"] = ARILUX_MQTT_BRIGHTNESS_STATE_TOPIC;
root["command_topic"] = ARILUX_MQTT_STATE_COMMAND_TOPIC;
root["payload_off"] = MQTT_STATE_OFF_PAYLOAD;
root["payload_on"] = MQTT_STATE_ON_PAYLOAD;
root["rgb_command_topic"] = ARILUX_MQTT_COLOR_COMMAND_TOPIC;
root["rgb_state_topic"] = ARILUX_MQTT_COLOR_STATE_TOPIC;
root["state_topic"] = ARILUX_MQTT_STATE_STATE_TOPIC;
#endif
char outgoingJsonBuffer[1024];
serializeJson(root, outgoingJsonBuffer);
publishToMQTT(HOME_ASSISTANT_MQTT_DISCOVERY_TOPIC, outgoingJsonBuffer);
}
#endif
#ifndef JSON
void publishStateChange(void) {
publishToMQTT(ARILUX_MQTT_STATE_STATE_TOPIC, (arilux.getState() ? MQTT_STATE_ON_PAYLOAD : MQTT_STATE_OFF_PAYLOAD));
}
void publishBrightnessChange(void) {
snprintf(msgBuffer, sizeof(msgBuffer), "%d", arilux.getBrightness());
publishToMQTT(ARILUX_MQTT_BRIGHTNESS_STATE_TOPIC, msgBuffer);
}
void publishColorChange(void) {
snprintf(msgBuffer, sizeof(msgBuffer), "%d,%d,%d", arilux.getRedValue(), arilux.getGreenValue(), arilux.getBlueValue());
publishToMQTT(ARILUX_MQTT_COLOR_STATE_TOPIC, msgBuffer);
}
#if defined(RGBW) || defined (RGBWW)
void publishWhiteChange(void) {
snprintf(msgBuffer, sizeof(msgBuffer), "%d,%d", arilux.getWhite1Value(), arilux.getWhite2Value());
publishToMQTT(ARILUX_MQTT_WHITE_STATE_TOPIC, msgBuffer);
}
#endif
#endif
///////////////////////////////////////////////////////////////////////////
// Effects
///////////////////////////////////////////////////////////////////////////
// From https://www.arduino.cc/en/Tutorial/ColorCrossfader
/* BELOW THIS LINE IS THE MATH -- YOU SHOULDN'T NEED TO CHANGE THIS FOR THE BASICS
*
* The program works like this:
* Imagine a crossfade that moves the red LED from 0-10,
* the green from 0-5, and the blue from 10 to 7, in
* ten steps.
* We'd want to count the 10 steps and increase or
* decrease color values in evenly stepped increments.
* Imagine a + indicates raising a value by 1, and a -
* equals lowering it. Our 10 step fade would look like:
*
* 1 2 3 4 5 6 7 8 9 10
* R + + + + + + + + + +
* G + + + + +
* B - - -
*
* The red rises from 0 to 10 in ten steps, the green from
* 0-5 in 5 steps, and the blue falls from 10 to 7 in three steps.
*
* In the real program, the color percentages are converted to
* 0-255 values, and there are 1020 steps (255*4).
*
* To figure out how big a step there should be between one up- or
* down-tick of one of the LED values, we call calculateStep(),
* which calculates the absolute gap between the start and end values,
* and then divides that gap by 1020 to determine the size of the step
* between adjustments in the value.
*/
int calculateStep(int prevValue, int endValue) {
int step = endValue - prevValue; // What's the overall gap?
if (step) { // If its non-zero,
step = 1020/step; // divide by 1020
}
return step;
}
/* The next function is calculateVal. When the loop value, i,
* reaches the step size appropriate for one of the
* colors, it increases or decreases the value of that color by 1.
* (R, G, and B are each calculated separately.)
*/
int calculateVal(int step, int val, int i) {
if ((step) && i % step == 0) { // If step is non-zero and its time to change a value,
if (step > 0) { // increment the value if step is positive...
val += 1;
}
else if (step < 0) { // ...or decrement it if step is negative
val -= 1;
}
}
// Defensive driving: make sure val stays in the range 0-255
if (val > 255) {
val = 255;
}
else if (val < 0) {
val = 0;
}
return val;
}
void flashSuccess(bool success) {
flashLength = 5000;
flashBrightness = 255;
if(success) {
flashRed = 0;
flashGreen = 255;
} else {
flashRed = 255;
flashGreen = 0;
}
flashBlue = 0;
flashRed = map(flashRed, 0, 255, 0, flashBrightness);
flashGreen = map(flashGreen, 0, 255, 0, flashBrightness);
flashBlue = map(flashBlue, 0, 255, 0, flashBrightness);
flash = true;
startFlash = true;
}
void handleEffects(void) {
if (flash) {
if (startFlash) {
startFlash = false;
flashStartTime = millis();
arilux.setWhite(0, 0);
}
if ((millis() - flashStartTime) <= flashLength) {
if ((millis() - flashStartTime) % 1000 <= 500) {
arilux.setColor(flashRed, flashGreen, flashBlue);
} else {
arilux.setColor(0, 0, 0);
// If you'd prefer the flashing to happen "on top of"
// the current color, uncomment the next line.
// arilux.setColor(realRed, realGreen, realBlue);
}
} else {
flash = false;
arilux.setColor(realRed, realGreen, realBlue);
}
}
if (startFade) {
// If we don't want to fade, skip it.
if (transitionTime == 0) {
arilux.setColor(realRed, realGreen, realBlue);
redVal = realRed;
grnVal = realGreen;
bluVal = realBlue;
startFade = false;
} else {
loopCount = 0;
stepR = calculateStep(redVal, realRed);
stepG = calculateStep(grnVal, realGreen);
stepB = calculateStep(bluVal, realBlue);
arilux.setFadeToColor(realRed, realGreen, realBlue);
inFade = true;
}
}
if (inFade) {
startFade = false;
unsigned long now = millis();
if (now - lastLoop > transitionTime) {
if (loopCount <= 1020) {
lastLoop = now;
redVal = calculateVal(stepR, redVal, loopCount);
grnVal = calculateVal(stepG, grnVal, loopCount);
bluVal = calculateVal(stepB, bluVal, loopCount);
arilux.setFadeColor(redVal, grnVal, bluVal); // Write current values to LED pins
DEBUG_PRINT("Fade Loop count: ");
DEBUG_PRINTLN(loopCount);
loopCount++;
} else {
inFade = false;
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// MQTT
///////////////////////////////////////////////////////////////////////////
/*
Function called when a MQTT message arrived
@param p_topic The topic of the MQTT message
@param p_payload The payload of the MQTT message
@param p_length The length of the payload
*/
void callback(char* p_topic, byte* p_payload, unsigned int p_length) {
// Concatenate the payload into a string
String payload;
for (uint8_t i = 0; i < p_length; i++) {
payload.concat((char)p_payload[i]);
}
// Handle the MQTT topic of the received message
#ifdef JSON
if (String(ARILUX_MQTT_JSON_COMMAND_TOPIC).equals(p_topic)) {
StaticJsonDocument<512> doc;
auto error = deserializeJson(doc, payload);
if (error) {
DEBUG_PRINT(F("parseObject() failed with code "));
DEBUG_PRINTLN(error.c_str());
return;
}
JsonObject root = doc.as<JsonObject>();
if (root.containsKey("color")) {
startFade = true;
inFade = false; // Kill the current fade
int red_color = root["color"]["r"];
int green_color = root["color"]["g"];
int blue_color = root["color"]["b"];
realRed = red_color;
realGreen = green_color;
realBlue = blue_color;
} else {
realRed = arilux.getRedValue();
realGreen = arilux.getGreenValue();
realBlue = arilux.getBlueValue();
}
if (root.containsKey("flash")) {
startFade = true;
inFade = false; // Kill the current fade
flashLength = (int)root["flash"] * 1000;
if (root.containsKey("brightness")) {
flashBrightness = root["brightness"];
} else {
flashBrightness = arilux.getBrightness();
}
if (root.containsKey("color")) {
flashRed = root["color"]["r"];
flashGreen = root["color"]["g"];
flashBlue = root["color"]["b"];
} else {
flashRed = arilux.getRedValue();
flashGreen = arilux.getGreenValue();
flashBlue = arilux.getBlueValue();
}
flashRed = map(flashRed, 0, 255, 0, flashBrightness);
flashGreen = map(flashGreen, 0, 255, 0, flashBrightness);
flashBlue = map(flashBlue, 0, 255, 0, flashBrightness);
flash = true;
startFlash = true;
} else { // Not flashing
flash = false;
if (root.containsKey("state")) {
if (strcmp(root["state"], "ON") == 0) {
arilux.turnOn();
} else if (strcmp(root["state"], "OFF") == 0) {
startFade = false;
startFlash = false;
inFade = false; // Kill the current fade
arilux.turnOff();
}
}
if (root.containsKey("transition")) {
transitionTime = root["transition"];
} else {
transitionTime = 0;
}
if (root.containsKey("brightness")) {
int brightness = root["brightness"];
arilux.setBrightness(brightness);
}
if (root.containsKey("white_value")) {
int white_value = root["white_value"];
arilux.setWhite(white_value, white_value);
}
}
cmd = ARILUX_CMD_JSON;
}
#else
if (String(ARILUX_MQTT_STATE_COMMAND_TOPIC).equals(p_topic)) {
if (payload.equals(String(MQTT_STATE_ON_PAYLOAD))) {
if (arilux.turnOn())
cmd = ARILUX_CMD_STATE_CHANGED;
} else if (payload.equals(String(MQTT_STATE_OFF_PAYLOAD))) {
if (arilux.turnOff())
cmd = ARILUX_CMD_STATE_CHANGED;
}
} else if (String(ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC).equals(p_topic)) {
if (arilux.setBrightness(payload.toInt()))
cmd = ARILUX_CMD_BRIGHTNESS_CHANGED;
} else if (String(ARILUX_MQTT_COLOR_COMMAND_TOPIC).equals(p_topic)) {
// Get the position of the first and second commas
int commaIndex = payload.indexOf(',');
// Search for the next comma just after the first
int secondCommaIndex = payload.indexOf(',', commaIndex + 1);
String firstValue = payload.substring(0, commaIndex);
String secondValue = payload.substring(commaIndex + 1, secondCommaIndex);
String thirdValue = payload.substring(secondCommaIndex + 1); // To the end of the string
int r = firstValue.toInt();
int g = secondValue.toInt();
int b = thirdValue.toInt();
if (arilux.setColor(r, g, b))
cmd = ARILUX_CMD_COLOR_CHANGED;
}
#if defined(RGBW) || defined (RGBWW)
if (String(ARILUX_MQTT_WHITE_COMMAND_TOPIC).equals(p_topic)) {
uint8_t firstIndex = payload.indexOf(',');
if (arilux.setWhite(payload.substring(0, firstIndex).toInt(), payload.substring(firstIndex + 1).toInt()))
cmd = ARILUX_CMD_WHITE_CHANGED;
}
#endif
#endif
}
/*
Function called to connect/reconnect to the MQTT broker
*/
volatile unsigned long lastmqttreconnect = 0;
void connectMQTT(void) {
if (!mqttClient.connected()) {
if (lastmqttreconnect + 1000 < millis()) {
if (mqttClient.connect(MQTT_CLIENT_ID, MQTT_USER, MQTT_PASS, ARILUX_MQTT_STATUS_TOPIC, 0, 1, "offline")) {
DEBUG_PRINTLN(F("INFO: The client is successfully connected to the MQTT broker"));
publishToMQTT(ARILUX_MQTT_STATUS_TOPIC, "online");
#ifdef HOME_ASSISTANT_MQTT_ATTRIBUTES
publishAttributes();
#endif
#ifdef HOME_ASSISTANT_MQTT_DISCOVERY
publishDiscovery();
#endif
flashSuccess(true);
} else {
DEBUG_PRINTLN(F("ERROR: The connection to the MQTT broker failed"));
DEBUG_PRINT(F("Username: "));
DEBUG_PRINTLN(MQTT_USER);
DEBUG_PRINT(F("Password: "));
DEBUG_PRINTLN(MQTT_PASS);
DEBUG_PRINT(F("Broker: "));
DEBUG_PRINTLN(MQTT_SERVER);
DEBUG_PRINT(F("Port: "));
DEBUG_PRINTLN(MQTT_PORT);
flashSuccess(false);
}
#ifdef JSON
subscribeToMQTTTopic(ARILUX_MQTT_JSON_COMMAND_TOPIC);
#else
subscribeToMQTTTopic(ARILUX_MQTT_STATE_COMMAND_TOPIC);
subscribeToMQTTTopic(ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC);
subscribeToMQTTTopic(ARILUX_MQTT_COLOR_COMMAND_TOPIC);
#if defined(RGBW) || defined (RGBWW)
subscribeToMQTTTopic(ARILUX_MQTT_WHITE_COMMAND_TOPIC);
#endif
#endif
lastmqttreconnect = millis();
}
}
}
///////////////////////////////////////////////////////////////////////////
// TELNET
///////////////////////////////////////////////////////////////////////////
/*
Function called to handle Telnet clients
https://www.youtube.com/watch?v=j9yW10OcahI
*/
#ifdef DEBUG_TELNET
void handleTelnet(void) {
if (telnetServer.hasClient()) {
if (!telnetClient || !telnetClient.connected()) {
if (telnetClient) {
telnetClient.stop();
}
telnetClient = telnetServer.available();
} else {
telnetServer.available().stop();
}
}
}
#endif
///////////////////////////////////////////////////////////////////////////
// IR REMOTE
///////////////////////////////////////////////////////////////////////////
/*
Function called to handle received IR codes from the remote
*/
#ifdef IR_REMOTE
void handleIRRemote(void) {
decode_results results;
if (irRecv.decode(&results)) {
switch (results.value) {
case ARILUX_IR_CODE_KEY_UP:
if (arilux.increaseBrightness())
cmd = ARILUX_CMD_BRIGHTNESS_CHANGED;
break;
case ARILUX_IR_CODE_KEY_DOWN:
if (arilux.decreaseBrightness())
cmd = ARILUX_CMD_BRIGHTNESS_CHANGED;
break;
case ARILUX_IR_CODE_KEY_OFF:
if (arilux.turnOff())
cmd = ARILUX_CMD_STATE_CHANGED;
break;
case ARILUX_IR_CODE_KEY_ON:
if (arilux.turnOn())
cmd = ARILUX_CMD_STATE_CHANGED;
break;
case ARILUX_IR_CODE_KEY_R:
if (arilux.setColor(255, 0, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_G:
if (arilux.setColor(0, 255, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_B:
if (arilux.setColor(0, 0, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_W:
if (arilux.setColor(255, 255, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_1:
if (arilux.setColor(255, 51, 51))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_2:
if (arilux.setColor(102, 204, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_3:
if (arilux.setColor(0, 102, 204))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_FLASH:
// TODO
DEBUG_PRINTLN(F("INFO: IR_CODE_KEY_FLASH"));
break;
case ARILUX_IR_CODE_KEY_4:
if (arilux.setColor(255, 102, 102))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_5:
if (arilux.setColor(0, 255, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_6:
if (arilux.setColor(153, 0, 153))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_STROBE:
// TODO
DEBUG_PRINTLN(F("INFO: IR_CODE_KEY_STROBE"));
break;
case ARILUX_IR_CODE_KEY_7:
if (arilux.setColor(255, 255, 102))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_8:
if (arilux.setColor(51, 153, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_9:
if (arilux.setColor(255, 0, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_FADE:
// TODO
DEBUG_PRINTLN(F("INFO: IR_CODE_KEY_FADE"));
break;
case ARILUX_IR_CODE_KEY_10:
if (arilux.setColor(255, 255, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_11:
if (arilux.setColor(0, 128, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_12:
if (arilux.setColor(255, 102, 178))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_IR_CODE_KEY_SMOOTH:
// TODO
DEBUG_PRINTLN(F("INFO: IR_CODE_KEY_SMOOTH"));
break;
default:
DEBUG_PRINT(F("ERROR: IR code not defined: "));
DEBUG_PRINTLN(uint64ToString(results.value, HEX));
break;
}
irRecv.resume();
}
}
#endif
///////////////////////////////////////////////////////////////////////////
// RF REMOTE
///////////////////////////////////////////////////////////////////////////
/*
Function called to handle received RF codes from the remote
*/
#ifdef RF_REMOTE
void handleRFRemote(void) {
if (rcSwitch.available()) {
int value = rcSwitch.getReceivedValue();
switch (value) {
case ARILUX_RF_CODE_KEY_BRIGHT_PLUS:
if (arilux.increaseBrightness())
cmd = ARILUX_CMD_BRIGHTNESS_CHANGED;
break;
case ARILUX_RF_CODE_KEY_BRIGHT_MINUS:
if (arilux.decreaseBrightness())
cmd = ARILUX_CMD_BRIGHTNESS_CHANGED;
break;
case ARILUX_RF_CODE_KEY_OFF:
if (arilux.turnOff())
cmd = ARILUX_CMD_STATE_CHANGED;
break;
case ARILUX_RF_CODE_KEY_ON:
if (arilux.turnOn())
cmd = ARILUX_CMD_STATE_CHANGED;
break;
case ARILUX_RF_CODE_KEY_RED:
if (arilux.setColor(255, 0, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_GREEN:
if (arilux.setColor(0, 255, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_BLUE:
if (arilux.setColor(0, 0, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_WHITE:
if (arilux.setColor(255, 255, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_ORANGE:
if (arilux.setColor(255, 165, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_LTGRN:
if (arilux.setColor(144, 238, 144))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_LTBLUE:
if (arilux.setColor(173, 216, 230))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_AMBER:
if (arilux.setColor(255, 194, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_CYAN:
if (arilux.setColor(0, 255, 255))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_PURPLE:
if (arilux.setColor(128, 0, 128))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_YELLOW:
if (arilux.setColor(255, 255, 0))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_PINK:
if (arilux.setColor(255, 192, 203))
cmd = ARILUX_CMD_COLOR_CHANGED;
break;
case ARILUX_RF_CODE_KEY_TOGGLE:
// TODO
DEBUG_PRINTLN(F("INFO: ARILUX_RF_CODE_KEY_TOGGLE"));
break;
case ARILUX_RF_CODE_KEY_SPEED_PLUS:
// TODO
DEBUG_PRINTLN(F("INFO: ARILUX_RF_CODE_KEY_SPEED_PLUS"));
break;
case ARILUX_RF_CODE_KEY_MODE_PLUS:
// TODO
DEBUG_PRINTLN(F("INFO: ARILUX_RF_CODE_KEY_MODE_PLUS"));
break;
case ARILUX_RF_CODE_KEY_SPEED_MINUS:
// TODO
DEBUG_PRINTLN(F("INFO: ARILUX_RF_CODE_KEY_SPEED_MINUS"));
break;
case ARILUX_RF_CODE_KEY_MODE_MINUS:
// TODO
DEBUG_PRINTLN(F("INFO: ARILUX_RF_CODE_KEY_MODE_MINUS"));
break;
default:
DEBUG_PRINTLN(F("ERROR: RF code not defined"));
break;
}
rcSwitch.resetAvailable();
}
}
#endif
///////////////////////////////////////////////////////////////////////////
// CMD
///////////////////////////////////////////////////////////////////////////
/*
Function called to handle commands due to changes
*/
void handleCMD(void) {
#ifdef JSON
if (cmd != ARILUX_CMD_NOT_DEFINED) {
StaticJsonDocument<512> root;
String stringState = arilux.getState() ? "ON" : "OFF";
root["state"] = stringState;
root["brightness"] = arilux.getBrightness();
// root["transition"] =
root["white_value"] = arilux.getWhite1Value();
JsonObject color = root.createNestedObject("color");
color["r"] = arilux.getRedValue();
color["g"] = arilux.getGreenValue();
color["b"] = arilux.getBlueValue();
char outgoingJsonBuffer[512];
serializeJson(root, outgoingJsonBuffer);
publishToMQTT(ARILUX_MQTT_JSON_STATE_TOPIC, outgoingJsonBuffer);
};
#else
switch (cmd) {
case ARILUX_CMD_NOT_DEFINED:
break;
case ARILUX_CMD_STATE_CHANGED:
publishStateChange();
break;
case ARILUX_CMD_BRIGHTNESS_CHANGED:
publishBrightnessChange();
publishStateChange();
break;
case ARILUX_CMD_COLOR_CHANGED:
publishColorChange();
publishStateChange();
break;
#if defined(RGBW) || defined (RGBWW)
case ARILUX_CMD_WHITE_CHANGED:
publishWhiteChange();
publishStateChange();
break;
#endif
default:
break;
}
#endif
cmd = ARILUX_CMD_NOT_DEFINED;
}
///////////////////////////////////////////////////////////////////////////
// WiFi
///////////////////////////////////////////////////////////////////////////
/*
Function called to setup the connection to the WiFi AP
*/
void setupWiFi() {
delay(10);
DEBUG_PRINT(F("INFO: Connecting to: "));
DEBUG_PRINTLN(WIFI_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
DEBUG_PRINT(".");
}
randomSeed(micros());
DEBUG_PRINTLN();
DEBUG_PRINTLN(F("INFO: WiFi connected"));
DEBUG_PRINT(F("INFO: IP address: "));
DEBUG_PRINTLN(WiFi.localIP());
}
///////////////////////////////////////////////////////////////////////////
// SETUP() AND LOOP()
///////////////////////////////////////////////////////////////////////////
void setup() {
Serial.begin(115200);
delay(500);
#ifdef DEBUG_TELNET
// Start the Telnet server
telnetServer.begin();
telnetServer.setNoDelay(true);
#endif
sprintf(chipid, "%08X", ESP.getChipId());
sprintf(MQTT_CLIENT_ID, HOST, chipid);
sprintf(friendlyName, "Arilux %s %s LED Controller (%s)", DEVICE_MODEL, arilux.getColorString(), chipid);
DEBUG_PRINT("Hostname:");
DEBUG_PRINTLN(MQTT_CLIENT_ID);
WiFi.hostname(MQTT_CLIENT_ID);
// Setup Wi-Fi
setupWiFi();
// Init the Arilux LED controller
if (arilux.init())
cmd = ARILUX_CMD_STATE_CHANGED;
#ifdef IR_REMOTE
// Start the IR receiver
irRecv.enableIRIn();
#endif
#ifdef RF_REMOTE
// Start the RF receiver
rcSwitch.enableReceive(ARILUX_RF_PIN);
#endif
#ifdef TLS
// Check the fingerprint of CloudMQTT's SSL cert
verifyFingerprint();
#endif
sprintf(MQTT_TOPIC_PREFIX, MQTT_TOPIC_PREFIX_TEMPLATE, arilux.getColorString(), chipid);
sprintf(ARILUX_MQTT_STATUS_TOPIC, MQTT_STATUS_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
#ifdef HOME_ASSISTANT_MQTT_ATTRIBUTES
sprintf(HOME_ASSISTANT_MQTT_ATTRIBUTES_TOPIC, HOME_ASSISTANT_MQTT_ATTRIBUTES_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
#endif
#ifdef HOME_ASSISTANT_MQTT_DISCOVERY
sprintf(HOME_ASSISTANT_MQTT_DISCOVERY_TOPIC, "%s/light/ARILUX_%s_%s_%s/config", HOME_ASSISTANT_MQTT_DISCOVERY_PREFIX, DEVICE_MODEL, arilux.getColorString(), chipid);
#endif
#ifdef JSON
sprintf(ARILUX_MQTT_JSON_STATE_TOPIC, MQTT_JSON_STATE_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
sprintf(ARILUX_MQTT_JSON_COMMAND_TOPIC, MQTT_JSON_COMMAND_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
#else
sprintf(ARILUX_MQTT_STATE_STATE_TOPIC, MQTT_STATE_STATE_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
sprintf(ARILUX_MQTT_STATE_COMMAND_TOPIC, MQTT_STATE_COMMAND_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
sprintf(ARILUX_MQTT_BRIGHTNESS_STATE_TOPIC, MQTT_BRIGHTNESS_STATE_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
sprintf(ARILUX_MQTT_BRIGHTNESS_COMMAND_TOPIC, MQTT_BRIGHTNESS_COMMAND_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
sprintf(ARILUX_MQTT_COLOR_STATE_TOPIC, MQTT_COLOR_STATE_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
sprintf(ARILUX_MQTT_COLOR_COMMAND_TOPIC, MQTT_COLOR_COMMAND_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
#if defined(RGBW) || defined (RGBWW)
sprintf(ARILUX_MQTT_WHITE_STATE_TOPIC, MQTT_WHITE_STATE_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
sprintf(ARILUX_MQTT_WHITE_COMMAND_TOPIC, MQTT_WHITE_COMMAND_TOPIC_TEMPLATE, MQTT_TOPIC_PREFIX);
#endif
#endif
mqttClient.setServer(MQTT_SERVER, MQTT_PORT);