-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathh801-mqtt-json.ino
1277 lines (1107 loc) · 38.5 KB
/
h801-mqtt-json.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 H801 5 channel LED dimmer
// based on https://github.com/open-homeautomation/h801/blob/master/mqtt/mqtt.ino
// and https://github.com/bruhautomation/ESP-MQTT-JSON-Digital-LEDs/blob/master/ESP_MQTT_Digital_LEDs/ESP_MQTT_Digital_LEDs.ino
//
//IMPORTANT!!!!!!!!!!!!
// inside PubSubClient.h the folloing needs to be changed on line 26:
// PubSubClient.h is inside documents/Arduino/libraries/PubSubclient/src/PubSubClient.h
// #define MQTT_MAX_PACKET_SIZE 128 --> #define MQTT_MAX_PACKET_SIZE 800
#define MQTT_MAX_PACKET_SIZE 800
#define FIRMWARE_VERSION "2.0.3"
#define MANUFACTURER "Huacanxing"
#include <string>
#include <ESP8266WiFi.h>
#include <PubSubClient.h> // MQTT client
#include <WiFiUDP.h> // UDP
#include <ESP8266WebServer.h> // OTA
#include <ESP8266mDNS.h> // OTA
#include <ESP8266HTTPUpdateServer.h> // OTA
#include <ArduinoJson.h>
#include "Config.h"
#define DEVELOPMENT
// Get settings from config.h
const char* mqtt_server = mqtt_server_conf;
const char* mqtt_user = mqtt_user_conf;
const char* mqtt_password = mqtt_password_conf;
// Initial setup
WiFiClient wifiClient;
PubSubClient client(wifiClient);
WiFiUDP Udp;
ESP8266WebServer httpServer(OTA_port);
ESP8266HTTPUpdateServer httpUpdater;
/********************************** program variables *****************************************/
char chip_id[9] = "00000000";
char myhostname[] = "esp00000000";
IPAddress ip;
uint8_t reconnect_N = 0;
unsigned long last_publish_ms = 0;
// transitioning variables
float transition_time_s_standard = transition_time_s_conf;
float transition_time_s = transition_time_s_conf;
unsigned long last_transition_publish = 0;
unsigned long start_transition_loop_ms = 0;
unsigned long transition_ms = 0;
uint8_t transition_increment = 1;
int rest_step[5] = {0};
float step_time_ms[5] = {1};
int n_step[5] = {0};
uint16_t transitionStepCount[5] = {0};
boolean transitioning = false;
uint8_t t_red_begin = 255;
uint8_t t_green_begin = 255;
uint8_t t_blue_begin = 255;
uint8_t t_rgb_brightness_begin = 255;
uint8_t t_white_brightness_begin = 255;
uint8_t t_w1_begin = 255;
uint8_t t_w2_begin = 255;
boolean t_rgb_state_begin = false;
boolean t_white_state_begin = false;
uint8_t targetR = 255;
uint8_t targetG = 255;
uint8_t targetB = 255;
uint8_t targetW1 = 255;
uint8_t targetW2 = 255;
// UDP/HDMI variables
boolean UDP_stream = false;
boolean UDP_stream_begin = false;
uint16_t UDP_packetSize = 0;
// buffer used to send/receive data with MQTT
#define JSON_BUFFER_SIZE 800
#define MQTT_UP_online "online"
#define MQTT_UP_offline "offline"
/********************************** Light variables *****************************************/
// the payload that represents enabled/disabled state, by default
const char* LIGHT_ON = "ON";
const char* LIGHT_OFF = "OFF";
#define RGB_LIGHT_RED_PIN 15
#define RGB_LIGHT_GREEN_PIN 13
#define RGB_LIGHT_BLUE_PIN 12
#define W1_PIN 14
#define W2_PIN 4
#define GREEN_PIN 1
#define RED_PIN 5
// store the state of the rgb LED strip (colors, brightness, ...)
boolean m_rgb_state = false;
uint8_t m_rgb_brightness = 255;
uint8_t m_rgb_red = 255;
uint8_t m_rgb_green = 255;
uint8_t m_rgb_blue = 255;
// store the state of the white LED strip (colors, brightness, ...)
boolean m_white_state = false;
uint8_t m_white_brightness = 255;
uint16_t m_color_temp = max_color_temp;
uint8_t m_w1 = 255;
uint8_t m_w2 = 255;
// store aditional states for combined RGB White light
uint8_t m_combined_brightness = 255;
boolean m_white_mode = true;
String m_effect = "white_mode";
String m_color_mode = "color_temp";
// store state during transitioning
uint8_t transition_red = 255;
uint8_t transition_green = 255;
uint8_t transition_blue = 255;
uint8_t transition_w1 = 255;
uint8_t transition_w2 = 255;
/********************************** Setup *****************************************/
void setup()
{
pinMode(RGB_LIGHT_RED_PIN, OUTPUT);
pinMode(RGB_LIGHT_GREEN_PIN, OUTPUT);
pinMode(RGB_LIGHT_BLUE_PIN, OUTPUT);
analogWriteRange(255);
setRGB(0, 0, 0);
pinMode(W1_PIN, OUTPUT);
setW1(0);
pinMode(W2_PIN, OUTPUT);
setW2(0);
pinMode(GREEN_PIN, OUTPUT);
pinMode(RED_PIN, OUTPUT);
digitalWrite(RED_PIN, 0);
digitalWrite(GREEN_PIN, 1);
convert_color_temp();
sprintf(chip_id, "%08X", ESP.getChipId());
sprintf(myhostname, "esp%08X", ESP.getChipId());
// Setup console
Serial1.begin(115200);
delay(10);
Serial1.println();
Serial1.println();
// Setup WIFI
WiFi.mode(WIFI_STA);
WiFi.begin(wifi_ssid_conf, wifi_password_conf);
while (WiFi.waitForConnectResult() != WL_CONNECTED) {
Serial1.println("Connection Failed! Rebooting...");
Serial1.print(".");
delay(30000);
ESP.restart();
}
Serial1.println("");
ip = WiFi.localIP();
if (WiFi.status() == WL_CONNECTED) {
Serial1.println("");
Serial1.print("Connected to ");
Serial1.println(wifi_ssid_conf);
Serial1.print("IP address: ");
Serial1.println(ip);
}
// init the MQTT connection
client.setBufferSize(MQTT_MAX_PACKET_SIZE);
client.setServer(mqtt_server, 1883);
client.setCallback(callback);
// OTA
// do not start OTA server if no password has been set
if (OTA_password != "") {
MDNS.begin(OTA_hostname);
httpUpdater.setup(&httpServer, OTA_update_path, OTA_username, OTA_password);
httpServer.begin();
MDNS.addService("http", "tcp", OTA_port);
Serial.printf("HTTPUpdateServer ready! Open http://%s.local%s in your browser and login", OTA_hostname, OTA_update_path);
}
digitalWrite(RED_PIN, 1);
}
/********************************** LED strip control *****************************************/
void setRGB(uint8_t p_red, uint8_t p_green, uint8_t p_blue) {
analogWrite(RGB_LIGHT_RED_PIN, map(p_red, 0, 255, 0, RGB_mixing[0]));
analogWrite(RGB_LIGHT_GREEN_PIN, map(p_green, 0, 255, 0, RGB_mixing[1]));
analogWrite(RGB_LIGHT_BLUE_PIN, map(p_blue, 0, 255, 0, RGB_mixing[2]));
}
void setColor(void) {
if (m_rgb_state) {
setRGB(map(m_rgb_red, 0, 255, 0, m_rgb_brightness), map(m_rgb_green, 0, 255, 0, m_rgb_brightness), map(m_rgb_blue, 0, 255, 0, m_rgb_brightness));
} else {
setRGB(0, 0, 0);
}
}
void convert_color_temp(void) {
float temp_unit = 2*(float(m_color_temp) - min_color_temp)/(max_color_temp - min_color_temp) - 1;
if (temp_unit == 0){
m_w1 = 255;
m_w2 = 255;
} else if (temp_unit > 0) {
m_w1 = int(round((1.0-temp_unit)*255));
m_w2 = 255;
} else if (temp_unit < 0){
m_w1 = 255;
m_w2 = int(round((1.0+temp_unit)*255));
} else {
return;
}
}
void setW1(uint8_t brightness) {
// convert the brightness in % (0-100%) into a digital value (0-255)
analogWrite(W1_PIN, brightness);
}
void setW2(uint8_t brightness) {
// convert the brightness in % (0-100%) into a digital value (0-255)
analogWrite(W2_PIN, brightness);
}
void setWhite(void) {
if (m_white_state) {
uint8_t w1_brightness = map(m_w1, 0, 255, 0, m_white_brightness);
uint8_t w2_brightness = map(m_w2, 0, 255, 0, m_white_brightness);
setW1(w1_brightness);
setW2(w2_brightness);
} else {
setW1(0);
setW2(0);
}
}
void setLEDpin(int LED_pin, uint8_t LED_value){
// map the color value from (0-255) to the value range (0-RGB_mixing)
if (LED_pin == RGB_LIGHT_RED_PIN) {
LED_value = map(LED_value, 0, 255, 0, RGB_mixing[0]);
} else if (LED_pin == RGB_LIGHT_GREEN_PIN) {
LED_value = map(LED_value, 0, 255, 0, RGB_mixing[1]);
} else if (LED_pin == RGB_LIGHT_BLUE_PIN) {
LED_value = map(LED_value, 0, 255, 0, RGB_mixing[2]);
}
analogWrite(LED_pin, LED_value);
}
/********************************** Publish states *****************************************/
void publishRGBJsonState() {
if (transitioning) {
return; // let the transition publish intermediate states
}
publishRGBJsonStateVal(m_rgb_state, m_rgb_red, m_rgb_green, m_rgb_blue, m_rgb_brightness);
}
void publishRGBJsonStateVal(boolean p_rgb_state, uint8_t p_rgb_red, uint8_t p_rgb_green, uint8_t p_rgb_blue, uint8_t p_rgb_brightness) {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
root["state"] = (p_rgb_state) ? LIGHT_ON : LIGHT_OFF;
JsonObject color = root.createNestedObject("color");
color["r"] = p_rgb_red;
color["g"] = p_rgb_green;
color["b"] = p_rgb_blue;
root["color_mode"] = "rgb";
root["brightness"] = p_rgb_brightness;
if (UDP_stream) {
m_effect = "HDMI";
root["state"] = LIGHT_ON;
} else {
m_effect = "color_mode";
}
root["effect"] = m_effect.c_str();
char buffer[measureJson(root) + 1];
serializeJson(root, buffer, sizeof(buffer));
client.publish(MQTT_JSON_LIGHT_RGB_STATE_TOPIC, buffer, true);
}
void publishWhiteJsonState() {
if (transitioning) {
return; // let the transition publish intermediate states
}
publishWhiteJsonStateVal(m_white_state, m_w1, m_w2, m_white_brightness);
}
void publishWhiteJsonStateVal(boolean p_white_state, uint8_t p_w1, uint8_t p_w2, uint8_t p_white_brightness) {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
root["state"] = (p_white_state) ? LIGHT_ON : LIGHT_OFF;
m_color_temp = int(round((float(p_w2)/510 - float(p_w1)/510 + 0.5)*(max_color_temp - min_color_temp)) + min_color_temp);
root["color_temp"] = m_color_temp;
root["color_mode"] = "color_temp";
root["brightness"] = p_white_brightness;
char buffer[measureJson(root) + 1];
serializeJson(root, buffer, sizeof(buffer));
client.publish(MQTT_JSON_LIGHT_WHITE_STATE_TOPIC, buffer, true);
}
void publishCombinedJsonState() {
if (transitioning) {
return; // let the transition publish intermediate states
}
publishCombinedJsonStateVal(m_white_state, m_w1, m_w2, m_rgb_state, m_rgb_red, m_rgb_green, m_rgb_blue, m_combined_brightness);
}
void publishCombinedJsonStateVal(boolean p_white_state, uint8_t p_w1, uint8_t p_w2, boolean p_rgb_state, uint8_t p_rgb_red, uint8_t p_rgb_green, uint8_t p_rgb_blue, uint8_t p_combined_brightness) {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
root["state"] = (p_white_state || p_rgb_state) ? LIGHT_ON : LIGHT_OFF;
m_color_temp = int(round((float(p_w2)/510 - float(p_w1)/510 + 0.5)*(max_color_temp - min_color_temp)) + min_color_temp);
root["color_temp"] = m_color_temp;
root["brightness"] = p_combined_brightness;
JsonObject color = root.createNestedObject("color");
if (p_white_state && !p_rgb_state) {
color["r"] = 255;
color["g"] = 255;
color["b"] = 255;
} else {
color["r"] = p_rgb_red;
color["g"] = p_rgb_green;
color["b"] = p_rgb_blue;
}
if (UDP_stream) {
m_effect = "HDMI";
m_color_mode = "rgb";
root["state"] = LIGHT_ON;
} else if (p_white_state && !p_rgb_state) {
m_effect = "white_mode";
m_color_mode = "color_temp";
} else if (!p_white_state && p_rgb_state) {
m_effect = "color_mode";
m_color_mode = "rgb";
} else if (p_white_state && p_rgb_state) {
m_effect = "both_mode";
m_color_mode = "rgb";
}
root["effect"] = m_effect.c_str();
root["color_mode"] = m_color_mode.c_str();
char buffer[measureJson(root) + 1];
serializeJson(root, buffer, sizeof(buffer));
client.publish(MQTT_JSON_LIGHT_COMBINED_STATE_TOPIC, buffer, true);
}
void publishJsonSettings() {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
root["transition_time_s_standard"] = transition_time_s_standard;
JsonObject rgb_mix = root.createNestedObject("RGB_mixing");
rgb_mix["r"] = RGB_mixing[0];
rgb_mix["g"] = RGB_mixing[1];
rgb_mix["b"] = RGB_mixing[2];
root["chip_id"] = myhostname;
root["IP"] = ip.toString();
char buffer[measureJson(root) + 1];
serializeJson(root, buffer, sizeof(buffer));
client.publish(MQTT_JSON_LIGHT_SETTINGS_STATE_TOPIC, buffer, true);
}
void publishJsonDiscovery() {
publishJsonDiscovery_entity("combined", "combined", true, true);
publishJsonDiscovery_entity("rgb", "rgb", false, true);
publishJsonDiscovery_entity("white", "white", true, false);
publishJsonDiscovery_entity("white_single", "white", false, false);
}
void publishJsonDiscovery_entity(const char type[], const char type_topic[], bool sup_color_temp, bool sup_rgb) {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
char idendifier[15] = "H801_";
strcat(idendifier, chip_id);
char unique_id[27] = "H801_";
strcat(unique_id, chip_id);
strcat(unique_id, "_");
strcat(unique_id, type);
char conf_url[strlen(OTA_update_path)+25] = "http://";
strcat(conf_url, ip.toString().c_str());
strcat(conf_url, OTA_update_path);
char entity_name[14] = "";
strcat(entity_name, type);
char stat_t[27] = "~/";
strcat(stat_t, type_topic);
strcat(stat_t, "/json_status");
char cmd_t[27] = "~/";
strcat(cmd_t, type);
strcat(cmd_t, "/json_set");
root["~"] = Mqtt_Base_Topic;
root["name"] = entity_name;
root["unique_id"] = unique_id;
root["schema"] = "json";
root["stat_t"] = stat_t;
root["cmd_t"] = cmd_t;
root["avty_t"] = "~/active";
root["brightness"] = true;
JsonArray sup_col_modes;
if(sup_color_temp | sup_rgb) {
sup_col_modes = root.createNestedArray("supported_color_modes");
}
if(sup_color_temp) {
sup_col_modes.add("color_temp");
root["min_mireds"] = min_color_temp;
root["max_mireds"] = max_color_temp;
}
if(sup_rgb) {
sup_col_modes.add("rgb");
root["effect"] = true;
JsonArray effect_list = root.createNestedArray("effect_list");
if(sup_color_temp) {
effect_list.add("white_mode");
}
effect_list.add("color_mode");
if(sup_color_temp) {
effect_list.add("both_mode");
}
if (UDP_Port != 0) {
effect_list.add("HDMI");
}
}
root["optimistic"] = false;
JsonObject device = root.createNestedObject("device");
device["configuration_url"] = conf_url;
JsonArray identifier_arr = device.createNestedArray("identifiers");
identifier_arr.add(idendifier);
device["model"] = "H801";
device["manufacturer"] = MANUFACTURER;
device["name"] = Module_Name;
device["sw_version"] = FIRMWARE_VERSION;
char buffer[measureJson(root) + 1];
serializeJson(root, buffer, sizeof(buffer));
char mqtt_discovery_topic[strlen(MQTT_HOMEASSISTANT_DISCOVERY_PREFIX) + 45] = MQTT_HOMEASSISTANT_DISCOVERY_PREFIX;
strcat(mqtt_discovery_topic, "/light/H801_");
strcat(mqtt_discovery_topic, chip_id);
strcat(mqtt_discovery_topic, "/");
strcat(mqtt_discovery_topic, type);
strcat(mqtt_discovery_topic, "/config");
client.publish(mqtt_discovery_topic, buffer, true);
}
/********************************** MQTT calback *****************************************/
// function called when a MQTT message arrived
void callback(char* p_topic, byte* p_payload, unsigned int p_length) {
// Parse received message
char message[p_length + 1];
for (int i = 0; i < p_length; i++) {
message[i] = (char)p_payload[i];
}
message[p_length] = '\0';
// Save RGB begin state
t_rgb_state_begin = m_rgb_state;
t_rgb_brightness_begin = m_rgb_brightness;
t_red_begin = m_rgb_red;
t_green_begin = m_rgb_green;
t_blue_begin = m_rgb_blue;
// Save White begin state
t_white_state_begin = m_white_state;
t_white_brightness_begin = m_white_brightness;
t_w1_begin = m_w1;
t_w2_begin = m_w2;
// Save UDP begin state
UDP_stream_begin = UDP_stream;
// Handle RGB commands
if (String(MQTT_JSON_LIGHT_RGB_COMMAND_TOPIC).equals(p_topic)) {
if (!processRGBJson(message)) {
return;
}
if (transition_time_s <= 0) {
setColor();
} else {
Transition();
}
publishRGBJsonState();
}
// Handle White commands
if (String(MQTT_JSON_LIGHT_WHITE_COMMAND_TOPIC).equals(p_topic)) {
if (!processWhiteJson(message)) {
return;
}
if (transition_time_s <= 0) {
setWhite();
} else {
Transition();
}
publishWhiteJsonState();
}
// Handle White single commands
if (String(MQTT_JSON_LIGHT_WHITE_SINGLE_COMMAND_TOPIC).equals(p_topic)) {
if (!processWhiteJson(message)) {
return;
}
m_color_temp = max_color_temp;
convert_color_temp();
if (transition_time_s <= 0) {
setWhite();
} else {
Transition();
}
publishWhiteJsonState();
}
// Handle combined commands
if (String(MQTT_JSON_LIGHT_COMBINED_COMMAND_TOPIC).equals(p_topic)) {
if (!processCombinedJson(message)) {
return;
}
if (transition_time_s <= 0) {
setWhite();
setColor();
} else {
Transition();
}
publishCombinedJsonState();
}
// Handle settings commands
if (String(MQTT_JSON_LIGHT_SETTINGS_COMMAND_TOPIC).equals(p_topic)) {
if (!processJsonSettings(message)) {
return;
}
publishJsonSettings();
}
// Reset the transition time for the next transition
transition_time_s = transition_time_s_standard;
// Apply UDP stream changes
UDP_start_stop();
// Flash green LED
digitalWrite(GREEN_PIN, 0);
delay(1);
digitalWrite(GREEN_PIN, 1);
}
/********************************** JSON processing *****************************************/
bool processRGBJson(char* message) {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
DeserializationError error = deserializeJson(root, message);
if (error) {
Serial1.println("deserializeJson() failed");
return false;
}
// Turn RGB "ON" or "OFF"
if (root.containsKey("state")) {
if (strcmp(root["state"], LIGHT_ON) == 0) {
m_rgb_state = true;
//check brightness and color not to be 0
if (m_rgb_brightness == 0) {
m_rgb_brightness = 255;
}
if (m_rgb_red == 0 && m_rgb_green == 0 && m_rgb_blue == 0) {
m_rgb_red = 255;
m_rgb_green = 255;
m_rgb_blue = 255;
}
}
else if (strcmp(root["state"], LIGHT_OFF) == 0) {
m_rgb_state = false;
}
}
// Change RGB brightness
if (root.containsKey("brightness")) {
uint8_t brightness = int(root["brightness"]);
if (brightness < 0 || brightness > 255) {
Serial1.println("Invalid brightness");
return false;
} else {
m_rgb_brightness = brightness;
}
}
// Change RGB color
if (root.containsKey("color")) {
uint8_t rgb_red = int(root["color"]["r"]);
if (rgb_red < 0 || rgb_red > 255) {
Serial1.println("Invalid red color value");
return false;
} else {
m_rgb_red = rgb_red;
}
uint8_t rgb_green = int(root["color"]["g"]);
if (rgb_green < 0 || rgb_green > 255) {
Serial1.println("Invalid green color value");
return false;
} else {
m_rgb_green = rgb_green;
}
uint8_t rgb_blue = int(root["color"]["b"]);
if (rgb_blue < 0 || rgb_blue > 255) {
Serial1.println("Invalid blue color value");
return false;
} else {
m_rgb_blue = rgb_blue;
}
}
// Change LED strip mode
if (root.containsKey("effect")) {
const char* effect = root["effect"];
m_effect = effect;
if (m_effect == "UDP" || m_effect == "HDMI") {
UDP_stream = true;
} else {
UDP_stream = false;
}
} else {
UDP_stream = false;
}
// Check transition time
if (root.containsKey("transition")) {
float trans_time = float(root["transition"]);
if (trans_time > 0) {
transition_time_s = trans_time;
} else {
transition_time_s = 0;
}
}
return true;
}
bool processWhiteJson(char* message) {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
DeserializationError error = deserializeJson(root, message);
if (error) {
Serial1.println("deserializeJson() failed");
return false;
}
// Turn White "ON" or "OFF"
if (root.containsKey("state")) {
if (strcmp(root["state"], LIGHT_ON) == 0) {
m_white_state = true;
//check brightness not to be 0
if (m_white_brightness == 0) {
m_white_brightness = 255;
}
}
else if (strcmp(root["state"], LIGHT_OFF) == 0) {
m_white_state = false;
}
}
// Change White brightness
if (root.containsKey("brightness")) {
uint8_t brightness = int(root["brightness"]);
if (brightness < 0 || brightness > 255) {
Serial1.println("Invalid brightness");
return false;
} else {
m_white_brightness = brightness;
}
}
// Change White color temperature
if (root.containsKey("color_temp")) {
uint16_t color_temp = int(root["color_temp"]);
if (color_temp < min_color_temp || color_temp > max_color_temp) {
Serial1.println("Invalid color temperature");
return false;
} else {
m_color_temp = color_temp;
convert_color_temp();
}
}
// Check transition time
if (root.containsKey("transition")) {
float trans_time = float(root["transition"]);
if (trans_time > 0) {
transition_time_s = trans_time;
} else {
transition_time_s = 0;
}
}
return true;
}
bool processCombinedJson(char* message) {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
DeserializationError error = deserializeJson(root, message);
if (error) {
Serial1.println("deserializeJson() failed");
return false;
}
// Turn LED strip "ON" or "OFF"
if (root.containsKey("state")) {
if (strcmp(root["state"], LIGHT_ON) == 0) {
if (m_white_mode) {
m_white_state = true;
m_rgb_state = false;
} else {
m_white_state = false;
m_rgb_state = true;
}
//check brightness and color not to be 0
if (m_rgb_brightness == 0) {
m_rgb_brightness = 255;
}
if (m_white_brightness == 0) {
m_white_brightness = 255;
}
if (m_combined_brightness == 0) {
m_combined_brightness = 255;
}
if (m_rgb_red == 0 && m_rgb_green == 0 && m_rgb_blue == 0) {
m_rgb_red = 255;
m_rgb_green = 255;
m_rgb_blue = 255;
}
}
else if (strcmp(root["state"], LIGHT_OFF) == 0) {
if (m_white_state) {
m_white_mode = true;
} else if (m_rgb_state) {
m_white_mode = false;
}
m_rgb_state = false;
m_white_state = false;
}
}
// Change LED strip brightness
if (root.containsKey("brightness")) {
uint8_t brightness = int(root["brightness"]);
if (brightness < 0 || brightness > 255) {
Serial1.println("Invalid brightness");
return false;
} else {
m_rgb_brightness = brightness;
m_white_brightness = brightness;
m_combined_brightness = brightness;
}
}
// Change LED strip color
if (root.containsKey("color")) {
uint8_t rgb_red = int(root["color"]["r"]);
if (rgb_red < 0 || rgb_red > 255) {
Serial1.println("Invalid red color value");
return false;
} else {
m_rgb_red = rgb_red;
}
uint8_t rgb_green = int(root["color"]["g"]);
if (rgb_green < 0 || rgb_green > 255) {
Serial1.println("Invalid green color value");
return false;
} else {
m_rgb_green = rgb_green;
}
uint8_t rgb_blue = int(root["color"]["b"]);
if (rgb_blue < 0 || rgb_blue > 255) {
Serial1.println("Invalid blue color value");
return false;
} else {
m_rgb_blue = rgb_blue;
}
m_rgb_state = true;
m_white_state = false;
m_white_mode = false;
}
// Change LED strip color temperature
if (root.containsKey("color_temp")) {
uint16_t color_temp = int(root["color_temp"]);
if (color_temp < min_color_temp || color_temp > max_color_temp) {
Serial1.println("Invalid color temperature");
return false;
} else {
m_color_temp = color_temp;
convert_color_temp();
}
m_white_state = true;
m_rgb_state = false;
m_white_mode = true;
}
// Change LED strip mode
if (root.containsKey("effect")) {
const char* effect = root["effect"];
m_effect = effect;
if (m_effect == "white_mode") {
m_white_state = true;
m_rgb_state = false;
m_white_mode = true;
UDP_stream = false;
} else if (m_effect == "color_mode") {
m_white_state = false;
m_rgb_state = true;
m_white_mode = false;
UDP_stream = false;
} else if (m_effect == "UDP" || m_effect == "HDMI") {
UDP_stream = true;
} else {
UDP_stream = false;
}
} else {
UDP_stream = false;
}
// Check transition time
if (root.containsKey("transition")) {
float trans_time = float(root["transition"]);
if (trans_time > 0) {
transition_time_s = trans_time;
} else {
transition_time_s = 0;
}
}
return true;
}
bool processJsonSettings(char* message) {
StaticJsonDocument<JSON_BUFFER_SIZE> root;
DeserializationError error = deserializeJson(root, message);
if (error) {
Serial1.println("deserializeJson() failed");
return false;
}
// Check transition time
if (root.containsKey("transition_time_s")) {
float trans_time = float(root["transition_time_s"]);
if (trans_time > 0) {
transition_time_s_standard = trans_time;
} else {
transition_time_s_standard = 0;
}
}
// Check RGB_mixing
if (root.containsKey("RGB_mixing")) {
uint8_t mixing_red = int(root["RGB_mixing"]["r"]);
if (mixing_red < 0 || mixing_red > 255) {
Serial1.println("Invalid red mixing value");
return false;
} else {
RGB_mixing[0] = mixing_red;
}
uint8_t mixing_green = int(root["RGB_mixing"]["g"]);
if (mixing_green < 0 || mixing_green > 255) {
Serial1.println("Invalid green mixing value");
return false;
} else {
RGB_mixing[1] = mixing_green;
}
uint8_t mixing_blue = int(root["RGB_mixing"]["b"]);
if (mixing_blue < 0 || mixing_blue > 255) {
Serial1.println("Invalid blue mixing value");
return false;
} else {
RGB_mixing[2] = mixing_blue;
}
}
return true;
}
/********************************** MQTT connection *****************************************/
void reconnect() {
// Loop until we're reconnected
reconnect_N = 0;
while (!client.connected()) {
Serial1.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect(chip_id, mqtt_user, mqtt_password, MQTT_UP, 2, true, MQTT_UP_offline)) {
Serial1.println("connected");
// blink 10 times green LED for success connected
for (int x=0; x < 10; x++){
delay(100);
digitalWrite(GREEN_PIN, 0);
delay(100);
digitalWrite(GREEN_PIN, 1);
}
ip = WiFi.localIP();
client.publish(MQTT_UP, MQTT_UP_online, true);
// Once connected, publish an announcement...
// publish the initial values
publishCombinedJsonState();
publishRGBJsonState();
publishWhiteJsonState();
publishJsonSettings();
publishJsonDiscovery();
// ... and resubscribe
client.subscribe(MQTT_JSON_LIGHT_RGB_COMMAND_TOPIC);
client.subscribe(MQTT_JSON_LIGHT_WHITE_COMMAND_TOPIC);
client.subscribe(MQTT_JSON_LIGHT_WHITE_SINGLE_COMMAND_TOPIC);
client.subscribe(MQTT_JSON_LIGHT_COMBINED_COMMAND_TOPIC);
client.subscribe(MQTT_JSON_LIGHT_SETTINGS_COMMAND_TOPIC);
} else {
Serial1.print("failed, rc=");
Serial1.print(client.state());
Serial1.print(", mqtt_ip=");
Serial1.print(mqtt_server);
Serial1.println(" try again in 5 seconds");
reconnect_N = reconnect_N + 1;
// Wait about 5 seconds (10 x 500ms) before retrying
for (int x=0; x < 10; x++){
delay(400);
digitalWrite(RED_PIN, 0);
delay(100);
digitalWrite(RED_PIN, 1);
}
if (reconnect_N > 60) {
// exit after 5 minutes, go back to the main loop
return;
}
}
}
}
/********************************** Main Loop *****************************************/
void loop()
{
if (WiFi.status() == WL_CONNECTED) {
//Confirm that still connected to MQTT broker
if (!client.connected()) {
Serial1.println("Reconnecting to MQTT Broker");
reconnect();
}
} else {
digitalWrite(RED_PIN, 0);
// Wait 5 seconds before retrying loop if their is no WIFI connection
delay(5000);
digitalWrite(RED_PIN, 1);
return;
}
client.loop();
// process OTA updates