This repository was archived by the owner on Jun 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathAI-Thinker_RGBW_Bulb.ino
More file actions
608 lines (521 loc) · 17.2 KB
/
Copy pathAI-Thinker_RGBW_Bulb.ino
File metadata and controls
608 lines (521 loc) · 17.2 KB
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
/*
Alternative firmware for AI Thinker RGBW bulbs, based on ESP8266.
See the README at https://github.com/mertenats/AI-Thinker_RGBW_Bulb for more information.
Licensed under the MIT license.
Demonstration at https://www.youtube.com/watch?v=xIR5uHMbAZ4
If you like the content of this repo, please add a star! Thank you!
Samuel Mertenat
04-05.2017
*/
#include <ESP8266WiFi.h> // https://github.com/esp8266/Arduino
#include <PubSubClient.h> // https://github.com/knolleary/pubsubclient
#include <ArduinoJson.h> // https://github.com/bblanchon/ArduinoJson
#include <ArduinoOTA.h>
#include "AI-Thinker_RGBW_Bulb.h"
#if defined(DEBUG_TELNET)
WiFiServer telnetServer(DEBUG_TELNET_PORT);
WiFiClient telnetClient;
#define DEBUG_PRINT(x) telnetClient.print(x)
#define DEBUG_PRINTLN(x) telnetClient.println(x)
#elif defined(DEBUG_SERIAL)
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif
StaticJsonBuffer<256> staticJsonBuffer;
char jsonBuffer[256] = {0};
volatile uint8_t cmd = CMD_NOT_DEFINED;
AIRGBWBulb bulb;
#if defined(TLS)
WiFiClientSecure wifiClient;
#else
WiFiClient wifiClient;
#endif
PubSubClient mqttClient(wifiClient);
///////////////////////////////////////////////////////////////////////////
// TELNET
///////////////////////////////////////////////////////////////////////////
/*
Function called to handle Telnet clients
https://www.youtube.com/watch?v=j9yW10OcahI
*/
#if defined(DEBUG_TELNET)
void handleTelnet(void) {
if (telnetServer.hasClient()) {
if (!telnetClient || !telnetClient.connected()) {
if (telnetClient) {
telnetClient.stop();
}
telnetClient = telnetServer.available();
} else {
telnetServer.available().stop();
}
}
}
#endif
///////////////////////////////////////////////////////////////////////////
// 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_SERVER_PORT)) {
DEBUG_PRINTLN(F("ERROR: Connection failed. Halting execution"));
delay(1000);
ESP.reset();
/*
TODO: Doing something smarter than rebooting the device
*/
}
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();
/*
TODO: Doing something smarter than rebooting the device
*/
}
}
#endif
///////////////////////////////////////////////////////////////////////////
// SAVE/LOAD SAVED CONFIGURATION
///////////////////////////////////////////////////////////////////////////
#if defined(SAVE_STATE)
bool loadConfig() {
if (!SPIFFS.exists("/config.json")) {
bulb.init();
} else {
File configFile = SPIFFS.open("/config.json", "r");
if (!configFile) {
DEBUG_PRINTLN(F("ERROR: Failed to open config file"));
return false;
}
size_t size = configFile.size();
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonBuffer dynamicJsonBuffer;
JsonObject& root = dynamicJsonBuffer.parseObject(buf.get());
if (!root.success()) {
DEBUG_PRINTLN(F("ERROR: parseObject() failed"));
return false;
}
bool state;
if (strcmp(root["state"], MQTT_STATE_ON_PAYLOAD) == 0) {
state = true;
} else if (strcmp(root["state"], MQTT_STATE_OFF_PAYLOAD) == 0) {
state = false;
}
uint8_t red = root["color"]["r"];
uint8_t green = root["color"]["g"];
uint8_t blue = root["color"]["b"];
uint8_t white = root["white_value"];
if (white != 0) {
bulb.setWhite(white);
} else {
bulb.setColor(red, green, blue);
}
uint8_t brightness = root["brightness"];
bulb.setBrightness(brightness);
bool isDiscovered = root["isDiscovered"];
bulb.isDiscovered(isDiscovered);
bool isGammaCorrectionEnabled = root["isGammaCorrectionEnabled"];
bulb.isGammaCorrectionEnabled(isGammaCorrectionEnabled);
bulb.setState(state);
return true;
}
}
bool saveConfig() {
DynamicJsonBuffer dynamicJsonBuffer;
JsonObject& root = dynamicJsonBuffer.createObject();
root["state"] = bulb.getState() ? MQTT_STATE_ON_PAYLOAD : MQTT_STATE_OFF_PAYLOAD;
root["brightness"] = bulb.getBrightness();
JsonObject& color = root.createNestedObject("color");
color["r"] = bulb.getColor().red;
color["g"] = bulb.getColor().green;
color["b"] = bulb.getColor().blue;
root["white_value"] = bulb.getColor().white;
root["isDiscovered"] = bulb.isDiscovered();
root["isGammaCorrectionEnabled"] = bulb.isGammaCorrectionEnabled();
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
DEBUG_PRINTLN(F("ERROR: Failed to open config file for writing"));
return false;
}
root.printTo(configFile);
return true;
}
#endif
///////////////////////////////////////////////////////////////////////////
// WiFi
///////////////////////////////////////////////////////////////////////////
/*
Function called to handle WiFi events
*/
void handleWiFiEvent(WiFiEvent_t event) {
switch (event) {
case WIFI_EVENT_STAMODE_GOT_IP:
DEBUG_PRINTLN(F("INFO: WiFi connected"));
DEBUG_PRINT(F("INFO: IP address: "));
DEBUG_PRINTLN(WiFi.localIP());
break;
case WIFI_EVENT_STAMODE_DISCONNECTED:
DEBUG_PRINTLN(F("ERROR: WiFi losts connection"));
/*
TODO: Doing something smarter than rebooting the device
*/
delay(5000);
ESP.restart();
break;
default:
DEBUG_PRINT(F("INFO: WiFi event: "));
DEBUG_PRINTLN(event);
break;
}
}
/*
Function called to setup the connection to the WiFi AP
*/
void setupWiFi() {
DEBUG_PRINT(F("INFO: WiFi connecting to: "));
DEBUG_PRINTLN(WIFI_SSID);
delay(10);
WiFi.mode(WIFI_STA);
WiFi.onEvent(handleWiFiEvent);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
randomSeed(micros());
}
///////////////////////////////////////////////////////////////////////////
// OTA
///////////////////////////////////////////////////////////////////////////
#if defined(OTA)
/*
Function called to setup OTA updates
*/
void setupOTA() {
#if defined(OTA_HOSTNAME)
ArduinoOTA.setHostname(OTA_HOSTNAME);
DEBUG_PRINT(F("INFO: OTA hostname sets to: "));
DEBUG_PRINTLN(OTA_HOSTNAME);
#endif
#if defined(OTA_PORT)
ArduinoOTA.setPort(OTA_PORT);
DEBUG_PRINT(F("INFO: OTA port sets to: "));
DEBUG_PRINTLN(OTA_PORT);
#endif
#if defined(OTA_PASSWORD)
ArduinoOTA.setPassword((const char *)OTA_PASSWORD);
DEBUG_PRINT(F("INFO: OTA password sets to: "));
DEBUG_PRINTLN(OTA_PASSWORD);
#endif
ArduinoOTA.onStart([]() {
DEBUG_PRINTLN(F("INFO: OTA starts"));
});
ArduinoOTA.onEnd([]() {
DEBUG_PRINTLN(F("INFO: OTA ends"));
});
ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {
DEBUG_PRINT(F("INFO: OTA progresses: "));
DEBUG_PRINT(progress / (total / 100));
DEBUG_PRINTLN(F("%"));
});
ArduinoOTA.onError([](ota_error_t error) {
DEBUG_PRINT(F("ERROR: OTA error: "));
DEBUG_PRINTLN(error);
if (error == OTA_AUTH_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA auth failed"));
else if (error == OTA_BEGIN_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA begin failed"));
else if (error == OTA_CONNECT_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA connect failed"));
else if (error == OTA_RECEIVE_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA receive failed"));
else if (error == OTA_END_ERROR)
DEBUG_PRINTLN(F("ERROR: OTA end failed"));
});
ArduinoOTA.begin();
}
/*
Function called to handle OTA updates
*/
void handleOTA() {
ArduinoOTA.handle();
}
#endif
///////////////////////////////////////////////////////////////////////////
// MQTT
///////////////////////////////////////////////////////////////////////////
char MQTT_CLIENT_ID[7] = {0};
#if defined(MQTT_HOME_ASSISTANT_SUPPORT)
char MQTT_CONFIG_TOPIC[sizeof(MQTT_HOME_ASSISTANT_DISCOVERY_PREFIX) + sizeof(MQTT_CLIENT_ID) + sizeof(MQTT_CONFIG_TOPIC_TEMPLATE) - 4] = {0};
#endif
char MQTT_STATE_TOPIC[sizeof(MQTT_CLIENT_ID) + sizeof(MQTT_STATE_TOPIC_TEMPLATE) - 2] = {0};
char MQTT_COMMAND_TOPIC[sizeof(MQTT_CLIENT_ID) + sizeof(MQTT_COMMAND_TOPIC_TEMPLATE) - 2] = {0};
char MQTT_STATUS_TOPIC[sizeof(MQTT_CLIENT_ID) + sizeof(MQTT_STATUS_TOPIC_TEMPLATE) - 2] = {0};
volatile unsigned long lastMQTTConnection = MQTT_CONNECTION_TIMEOUT;
/*
Function called when a MQTT message has 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 handleMQTTMessage(char* p_topic, byte* p_payload, unsigned int p_length) {
// concatenates the payload into a string
String payload;
for (uint8_t i = 0; i < p_length; i++) {
payload.concat((char)p_payload[i]);
}
DEBUG_PRINTLN(F("INFO: New MQTT message received"));
DEBUG_PRINT(F("INFO: MQTT topic: "));
DEBUG_PRINTLN(p_topic);
DEBUG_PRINT(F("INFO: MQTT payload: "));
DEBUG_PRINTLN(payload);
if (String(MQTT_COMMAND_TOPIC).equals(p_topic)) {
DynamicJsonBuffer dynamicJsonBuffer;
JsonObject& root = dynamicJsonBuffer.parseObject(p_payload);
if (!root.success()) {
DEBUG_PRINTLN(F("ERROR: parseObject() failed"));
return;
}
if (root.containsKey("state")) {
if (strcmp(root["state"], MQTT_STATE_ON_PAYLOAD) == 0) {
if (bulb.setState(true)) {
DEBUG_PRINT(F("INFO: State changed to: "));
DEBUG_PRINTLN(bulb.getState());
cmd = CMD_STATE_CHANGED;
}
} else if (strcmp(root["state"], MQTT_STATE_OFF_PAYLOAD) == 0) {
// stops the possible current effect
bulb.setEffect(EFFECT_NOT_DEFINED_NAME);
if (bulb.setState(false)) {
DEBUG_PRINT(F("INFO: State changed to: "));
DEBUG_PRINTLN(bulb.getState());
cmd = CMD_STATE_CHANGED;
}
}
}
if (root.containsKey("color")) {
// stops the possible current effect
bulb.setEffect(EFFECT_NOT_DEFINED_NAME);
uint8_t r = root["color"]["r"];
uint8_t g = root["color"]["g"];
uint8_t b = root["color"]["b"];
if (bulb.setColor(r, g, b)) {
DEBUG_PRINT(F("INFO: Color changed to: "));
DEBUG_PRINT(bulb.getColor().red);
DEBUG_PRINT(F(", "));
DEBUG_PRINT(bulb.getColor().green);
DEBUG_PRINT(F(", "));
DEBUG_PRINTLN(bulb.getColor().blue);
cmd = CMD_STATE_CHANGED;
}
}
if (root.containsKey("brightness")) {
if (bulb.setBrightness(root["brightness"])) {
DEBUG_PRINT(F("INFO: Brightness changed to: "));
DEBUG_PRINTLN(bulb.getBrightness());
cmd = CMD_STATE_CHANGED;
}
}
if (root.containsKey("white_value")) {
// stops the possible current effect
bulb.setEffect(EFFECT_NOT_DEFINED_NAME);
if (bulb.setWhite(root["white_value"])) {
DEBUG_PRINT(F("INFO: White changed to: "));
DEBUG_PRINTLN(bulb.getColor().white);
cmd = CMD_STATE_CHANGED;
}
}
if (root.containsKey("color_temp")) {
// stops the possible current effect
bulb.setEffect(EFFECT_NOT_DEFINED_NAME);
if (bulb.setColorTemperature(root["color_temp"])) {
DEBUG_PRINT(F("INFO: Color temperature changed to: "));
DEBUG_PRINTLN(bulb.getColorTemperature());
cmd = CMD_STATE_CHANGED;
}
}
if (root.containsKey("effect")) {
const char* effect = root["effect"];
if (bulb.setEffect(effect)) {
DEBUG_PRINTLN(F("INFO: Effect started"));
cmd = CMD_NOT_DEFINED;
}
}
}
}
/*
Function called to subscribe to a MQTT topic
*/
void subscribeToMQTT(char* p_topic) {
if (mqttClient.subscribe(p_topic)) {
DEBUG_PRINT(F("INFO: Sending the MQTT subscribe succeeded for topic: "));
DEBUG_PRINTLN(p_topic);
} else {
DEBUG_PRINT(F("ERROR: Sending the MQTT subscribe failed for topic: "));
DEBUG_PRINTLN(p_topic);
}
}
/*
Function called to publish to a MQTT topic with the given payload
*/
void publishToMQTT(char* p_topic, char* p_payload) {
if (mqttClient.publish(p_topic, p_payload, true)) {
DEBUG_PRINT(F("INFO: MQTT message published successfully, topic: "));
DEBUG_PRINT(p_topic);
DEBUG_PRINT(F(", payload: "));
DEBUG_PRINTLN(p_payload);
} else {
DEBUG_PRINTLN(F("ERROR: MQTT message not published, either connection lost, or message too large. Topic: "));
DEBUG_PRINT(p_topic);
DEBUG_PRINT(F(" , payload: "));
DEBUG_PRINTLN(p_payload);
}
}
/*
Function called to connect/reconnect to the MQTT broker
*/
void connectToMQTT() {
if (!mqttClient.connected()) {
if (lastMQTTConnection + MQTT_CONNECTION_TIMEOUT < millis()) {
if (mqttClient.connect(MQTT_CLIENT_ID, MQTT_USERNAME, MQTT_PASSWORD, MQTT_STATUS_TOPIC, 0, 1, "dead")) {
DEBUG_PRINTLN(F("INFO: The client is successfully connected to the MQTT broker"));
publishToMQTT(MQTT_STATUS_TOPIC, "alive");
#if defined(MQTT_HOME_ASSISTANT_SUPPORT)
if (!bulb.isDiscovered()) {
bulb.isDiscovered(true);
// MQTT discovery for Home Assistant
JsonObject& root = staticJsonBuffer.createObject();
root["name"] = FRIENDLY_NAME;
root["platform"] = "mqtt_json";
root["state_topic"] = MQTT_STATE_TOPIC;
root["command_topic"] = MQTT_COMMAND_TOPIC;
root["brightness"] = true;
root["rgb"] = true;
root["white_value"] = true;
root["color_temp"] = true;
root["effect"] = true;
JsonArray& effect_list = root.createNestedArray("effect_list");
effect_list.add(EFFECT_NOT_DEFINED_NAME);
effect_list.add(EFFECT_RAINBOW_NAME);
effect_list.add(EFFECT_BLINK_NAME);
root.printTo(jsonBuffer, sizeof(jsonBuffer));
publishToMQTT(MQTT_CONFIG_TOPIC, jsonBuffer);
}
#endif
subscribeToMQTT(MQTT_COMMAND_TOPIC);
} else {
DEBUG_PRINTLN(F("ERROR: The connection to the MQTT broker failed"));
DEBUG_PRINT(F("INFO: MQTT username: "));
DEBUG_PRINTLN(MQTT_USERNAME);
DEBUG_PRINT(F("INFO: MQTT password: "));
DEBUG_PRINTLN(MQTT_PASSWORD);
DEBUG_PRINT(F("INFO: MQTT broker: "));
DEBUG_PRINTLN(MQTT_SERVER);
}
lastMQTTConnection = millis();
}
}
}
///////////////////////////////////////////////////////////////////////////
// CMD
///////////////////////////////////////////////////////////////////////////
void handleCMD() {
switch (cmd) {
case CMD_NOT_DEFINED:
break;
#if defined(SAVE_STATE)
case CMD_SAVE_STATE:
cmd = CMD_NOT_DEFINED;
saveConfig();
break;
#endif
case CMD_STATE_CHANGED:
#if defined(SAVE_STATE)
cmd = CMD_SAVE_STATE;
#else
cmd = CMD_NOT_DEFINED;
#endif
DynamicJsonBuffer dynamicJsonBuffer;
JsonObject& root = dynamicJsonBuffer.createObject();
root["state"] = bulb.getState() ? MQTT_STATE_ON_PAYLOAD : MQTT_STATE_OFF_PAYLOAD;
root["brightness"] = bulb.getBrightness();
JsonObject& color = root.createNestedObject("color");
color["r"] = bulb.getColor().red;
color["g"] = bulb.getColor().green;
color["b"] = bulb.getColor().blue;
root["white_value"] = bulb.getColor().white;
root["color_temp"] = bulb.getColorTemperature();
root.printTo(jsonBuffer, sizeof(jsonBuffer));
publishToMQTT(MQTT_STATE_TOPIC, jsonBuffer);
break;
}
}
///////////////////////////////////////////////////////////////////////////
// SETUP() AND LOOP()
///////////////////////////////////////////////////////////////////////////
void setup() {
#if defined(DEBUG_SERIAL)
Serial.begin(115200);
#elif defined(DEBUG_TELNET)
telnetServer.begin();
telnetServer.setNoDelay(true);
#endif
#if defined(SAVE_STATE)
SPIFFS.begin();
//SPIFFS.format(); // remove config
loadConfig();
#else
bulb.init();
#endif
setupWiFi();
#if defined(TLS)
verifyFingerprint();
#endif
sprintf(MQTT_CLIENT_ID, "%06X", ESP.getChipId());
#if defined(MQTT_HOME_ASSISTANT_SUPPORT)
sprintf(MQTT_CONFIG_TOPIC, MQTT_CONFIG_TOPIC_TEMPLATE, MQTT_HOME_ASSISTANT_DISCOVERY_PREFIX, MQTT_CLIENT_ID);
DEBUG_PRINT(F("INFO: MQTT config topic: "));
DEBUG_PRINTLN(MQTT_CONFIG_TOPIC);
#endif
sprintf(MQTT_STATE_TOPIC, MQTT_STATE_TOPIC_TEMPLATE, MQTT_CLIENT_ID);
sprintf(MQTT_COMMAND_TOPIC, MQTT_COMMAND_TOPIC_TEMPLATE, MQTT_CLIENT_ID);
sprintf(MQTT_STATUS_TOPIC, MQTT_STATUS_TOPIC_TEMPLATE, MQTT_CLIENT_ID);
DEBUG_PRINT(F("INFO: MQTT state topic: "));
DEBUG_PRINTLN(MQTT_STATE_TOPIC);
DEBUG_PRINT(F("INFO: MQTT command topic: "));
DEBUG_PRINTLN(MQTT_COMMAND_TOPIC);
DEBUG_PRINT(F("INFO: MQTT status topic: "));
DEBUG_PRINTLN(MQTT_STATUS_TOPIC);
mqttClient.setServer(MQTT_SERVER, MQTT_SERVER_PORT);
mqttClient.setCallback(handleMQTTMessage);
connectToMQTT();
#if defined(OTA)
setupOTA();
#endif
cmd = CMD_STATE_CHANGED;
}
void loop() {
#if defined(DEBUG_TELNET)
// handle the Telnet connection
handleTelnet();
#endif
yield();
#if defined(OTA)
handleOTA();
#endif
yield();
connectToMQTT();
mqttClient.loop();
yield();
handleCMD();
yield();
bulb.loop();
}