forked from forkineye/ESPixelStick
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWNRF.ino
1492 lines (1272 loc) · 48 KB
/
WNRF.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
/*
WNRF.ino
Project: WNRF - An ESP8266, E1.31, and NRF24L01 based pixel driver
Copyright (c) 2022 Andrew Williams
http://www.ratsnest.ca
Based on..
Project: ESPixelStick - An ESP8266 and E1.31 based pixel driver
Copyright (c) 2016 Shelby Merrick
http://www.forkineye.com
This program is provided free for you to use in any way that you wish,
subject to the laws and regulations where you are using it. Due diligence
is strongly suggested before using this code. Please give credit where due.
The Author makes no warranty of any kind, express or implied, with regard
to this program or the documentation contained in this document. The
Author shall not be liable in any event for incidental or consequential
damages in connection with, or arising out of, the furnishing, performance
or use of these programs.
*/
/*****************************************/
/* BEGIN - Configuration */
/*****************************************/
/* Fallback configuration if config.json is empty or fails */
const char ssid[] = "";
const char passphrase[] = "";
/*****************************************/
/* END - Configuration */
/*****************************************/
#include <ESPAsyncE131.h>
#include "ESPAsyncZCPP.h"
#include "ESPAsyncDDP.h"
#include <Hash.h>
#include <SPI.h>
#include "WNRF.h"
#include "FPPDiscovery.h"
#include "EFUpdate.h"
#include "wshandler.h"
extern "C" {
#include <user_interface.h>
}
// Debugging support
#if defined(DEBUG)
extern "C" void system_set_os_print(uint8 onoff);
extern "C" void ets_install_putc1(void* routine);
static void _u0_putc(char c) {
while (((U0S >> USTXC) & 0x7F) == 0x7F);
U0F = c;
}
#endif
/////////////////////////////////////////////////////////
//
// Globals
//
/////////////////////////////////////////////////////////
// MQTT State
const char MQTT_SET_COMMAND_TOPIC[] = "/set";
// MQTT Payloads by default (on/off)
const char LIGHT_ON[] = "ON";
const char LIGHT_OFF[] = "OFF";
// Configuration file
const char CONFIG_FILE[] = "/config.json";
ESPAsyncE131 e131(10); // ESPAsyncE131 with X buffers
ESPAsyncZCPP zcpp(5); // ESPAsyncZCPP with X buffers
ESPAsyncDDP ddp(5); // ESPAsyncDDP with X buffers
FPPDiscovery fppDiscovery(VERSION); // FPP Discovery Listener
config_t config; // Current configuration
uint32_t *seqError; // Sequence error tracking for each universe
uint32_t *seqZCPPError; // Sequence error tracking for each universe
uint16_t lastZCPPConfig; // last config we saw
uint8_t seqZCPPTracker; // sequence number of zcpp frames
uint16_t uniLast = 1; // Last Universe to listen for
bool reboot = false; // Reboot flag
AsyncWebServer web(HTTP_PORT); // Web Server
AsyncWebSocket ws("/ws"); // Web Socket Plugin
uint8_t *seqTracker; // Current sequence numbers for each Universe */
uint32_t lastUpdate; // Update timeout tracker
WiFiEventHandler wifiConnectHandler; // WiFi connect handler
WiFiEventHandler wifiDisconnectHandler; // WiFi disconnect handler
Ticker wifiTicker; // Ticker to handle WiFi
Ticker idleTicker; // Ticker for effect on idle
#ifdef MQTT
AsyncMqttClient mqtt; // MQTT object
Ticker mqttTicker; // Ticker to handle MQTT
#endif
EffectEngine effects; // Effects Engine
IPAddress ourLocalIP;
IPAddress ourSubnetMask;
// Output Drivers
#if defined(ESPS_MODE_WNRF)
WnrfDriver out_driver;
#else
#error "No valid output mode defined."
#endif
#define LED_WIFI 2
// LED_NRF comes from WnrfDriver.h
#define LED_OFF 0x0000
#define BLINK_1HZ 0xFF00
#define BLINK_2HZ 0xF0F0
#define BEAT ~(0x0033)
#define FLICKER ~(0x3030)
// Avoid using this, so that we have visual that the main loop is operational
#define SOLID 0xFFFF
#ifdef LED_WIFI
uint16_t led_state_wifi=LED_OFF;
uint32_t led_timeout =0;
uint16_t led_mask = 0x0001;
#endif
/////////////////////////////////////////////////////////
//
// Forward Declarations
//
/////////////////////////////////////////////////////////
void loadConfig();
void initWifi();
void initWeb();
void updateConfig();
// Radio config
RF_PRE_INIT() {
//wifi_set_phy_mode(PHY_MODE_11G); // Force 802.11g mode
system_phy_set_powerup_option(31); // Do full RF calibration on power-up
system_phy_set_max_tpw(82); // Set max TX power
}
void ZCPPSub(); // Forward declaration
void setup() {
// Configure SDK params
wifi_set_sleep_type(NONE_SLEEP_T);
#if defined (DATA_PIN)
// Initial pin states
pinMode(DATA_PIN, OUTPUT);
digitalWrite(DATA_PIN, LOW);
#endif
#if defined (LED_WIFI)
pinMode(LED_WIFI,OUTPUT);
digitalWrite(LED_WIFI, HIGH);
#endif
#if defined (LED_NRF)
pinMode(LED_NRF, OUTPUT);
digitalWrite(LED_NRF, LOW);
#endif
// Setup serial log port
LOG_PORT.begin(115200);
delay(10);
#if defined(DEBUG)
ets_install_putc1((void *) &_u0_putc);
system_set_os_print(1);
#endif
// Set default data source to E131
config.ds = DataSource::E131;
LOG_PORT.println("");
LOG_PORT.print(F("WNRF v"));
for (uint8_t i = 0; i < strlen_P(VERSION); i++)
LOG_PORT.print((char)(pgm_read_byte(VERSION + i)));
LOG_PORT.print(F(" ("));
for (uint8_t i = 0; i < strlen_P(BUILD_DATE); i++)
LOG_PORT.print((char)(pgm_read_byte(BUILD_DATE + i)));
LOG_PORT.println(")");
LOG_PORT.println(ESP.getFullVersion());
// Enable SPIFFS
if (!SPIFFS.begin())
{
LOG_PORT.println("File system did not initialise correctly");
}
else
{
LOG_PORT.println("File system initialised");
}
FSInfo fs_info;
if (SPIFFS.info(fs_info))
{
LOG_PORT.print("Total bytes in file system: ");
LOG_PORT.println(fs_info.usedBytes);
LOG_PORT.print("Space:");
LOG_PORT.println(fs_info.totalBytes - fs_info.usedBytes);
Dir dir = SPIFFS.openDir("/");
while (dir.next()) {
LOG_PORT.print(dir.fileName());
File f = dir.openFile("r");
LOG_PORT.println(f.size());
}
}
else
{
LOG_PORT.println("Failed to read file system details");
}
// Load configuration from SPIFFS and set Hostname
loadConfig();
if (config.hostname)
WiFi.hostname(config.hostname);
#if defined (DATA_PIN)
out_driver.setPin(DATA_PIN);
#endif
updateConfig();
// Do one effects cycle as early as possible
if (config.ds == DataSource::WEB) {
effects.run();
}
// set the effect idle timer
idleTicker.attach(config.effect_idletimeout, idleTimeout);
out_driver.show();
// Setup WiFi Handlers
wifiConnectHandler = WiFi.onStationModeGotIP(onWifiConnect);
#ifdef MQTT
// Setup MQTT Handlers
if (config.mqtt) {
mqtt.onConnect(onMqttConnect);
mqtt.onDisconnect(onMqttDisconnect);
mqtt.onMessage(onMqttMessage);
mqtt.setServer(config.mqtt_ip.c_str(), config.mqtt_port);
// Unset clean session (defaults to true) so we get retained messages of QoS > 0
mqtt.setCleanSession(config.mqtt_clean);
if (config.mqtt_user.length() > 0)
mqtt.setCredentials(config.mqtt_user.c_str(), config.mqtt_password.c_str());
}
#endif
// Fallback to default SSID and passphrase if we fail to connect
initWifi();
if (WiFi.status() != WL_CONNECTED) {
LOG_PORT.println(F("*** Timeout - Reverting to default SSID ***"));
config.ssid = ssid;
config.passphrase = passphrase;
initWifi();
#if defined(LED_WIFI)
led_state_wifi = BLINK_1HZ;
#endif
}
// If we fail again, go SoftAP or reboot
if (WiFi.status() != WL_CONNECTED) {
if (config.ap_fallback) {
LOG_PORT.println(F("*** FAILED TO ASSOCIATE WITH AP, GOING SOFTAP ***"));
WiFi.mode(WIFI_AP);
String ssid = "WNRF " + String(config.hostname);
WiFi.softAP(ssid.c_str());
ourLocalIP = WiFi.softAPIP();
ourSubnetMask = IPAddress(255,255,255,0);
#if defined(LED_WIFI)
led_state_wifi = BEAT;
#endif
} else {
LOG_PORT.println(F("*** FAILED TO ASSOCIATE WITH AP, REBOOTING ***"));
ESP.restart();
}
}
#if defined(LED_WIFI)
//digitalWrite(LED_WIFI, LOW);
#endif
wifiDisconnectHandler = WiFi.onStationModeDisconnected(onWiFiDisconnect);
LOG_PORT.print("IP : ");
LOG_PORT.println(ourLocalIP);
LOG_PORT.print("Subnet mask : ");
LOG_PORT.println(ourSubnetMask);
// Configure and start the web server
initWeb();
// Setup E1.31
if (config.multicast) {
if (e131.begin(E131_MULTICAST, config.universe,
uniLast - config.universe + 1)) {
LOG_PORT.println(F("- E131 Multicast Enabled"));
} else {
LOG_PORT.println(F("*** E131 MULTICAST INIT FAILED ****"));
}
} else {
if (e131.begin(E131_UNICAST)) {
LOG_PORT.print(F("- E131 Unicast port: "));
LOG_PORT.println(E131_DEFAULT_PORT);
} else {
LOG_PORT.println(F("*** E131 UNICAST INIT FAILED ****"));
}
}
fppDiscovery.begin();
if (ddp.begin(ourLocalIP)) {
LOG_PORT.println(F("- DDP Enabled"));
} else {
LOG_PORT.println(F("*** DDP INIT FAILED ****"));
}
lastZCPPConfig = -1;
if (zcpp.begin(ourLocalIP)) {
LOG_PORT.println(F("- ZCPP Enabled"));
ZCPPSub();
} else {
LOG_PORT.println(F("*** ZCPP INIT FAILED ****"));
}
}
/////////////////////////////////////////////////////////
//
// WiFi Section
//
/////////////////////////////////////////////////////////
void initWifi() {
// Switch to station mode and disconnect just in case
WiFi.mode(WIFI_STA);
WiFi.disconnect();
if (!config.ssid.isEmpty()) {
connectWifi();
uint32_t timeout = millis();
while (WiFi.status() != WL_CONNECTED) {
LOG_PORT.print(".");
delay(500);
if (millis() - timeout > (1000 * config.sta_timeout) ) {
LOG_PORT.println("");
LOG_PORT.println(F("*** Failed to connect ***"));
break;
}
}
}
}
void reconnectWifi() {
WiFi.reconnect();
}
void connectWifi() {
delay(secureRandom(100, 500));
LOG_PORT.println("");
LOG_PORT.print(F("Connecting to "));
LOG_PORT.print(config.ssid);
LOG_PORT.print(F(" as "));
LOG_PORT.println(config.hostname);
WiFi.begin(config.ssid.c_str(), config.passphrase.c_str());
if (config.dhcp) {
LOG_PORT.print(F("Connecting with DHCP"));
} else {
// We don't use DNS, so just set it to our gateway
WiFi.config(IPAddress(config.ip[0], config.ip[1], config.ip[2], config.ip[3]),
IPAddress(config.gateway[0], config.gateway[1], config.gateway[2], config.gateway[3]),
IPAddress(config.netmask[0], config.netmask[1], config.netmask[2], config.netmask[3]),
IPAddress(config.gateway[0], config.gateway[1], config.gateway[2], config.gateway[3])
);
LOG_PORT.print(F("Connecting with Static IP"));
}
}
void onWifiConnect(const WiFiEventStationModeGotIP &event) {
LOG_PORT.println("");
LOG_PORT.print(F("Connected with IP: "));
LOG_PORT.println(WiFi.localIP());
ourLocalIP = WiFi.localIP();
ourSubnetMask = WiFi.subnetMask();
#ifdef MQTT
// Setup MQTT connection if enabled
if (config.mqtt)
connectToMqtt();
#endif
// Setup mDNS / DNS-SD
//TODO: Reboot or restart mdns when config.id is changed?
String chipId = String(ESP.getChipId(), HEX);
MDNS.setInstanceName(String(config.id + " (" + chipId + ")").c_str());
if (MDNS.begin(config.hostname.c_str())) {
MDNS.addService("http", "tcp", HTTP_PORT);
MDNS.addService("zcpp", "udp", ZCPP_PORT);
MDNS.addService("ddp", "udp", DDP_PORT);
MDNS.addService("e131", "udp", E131_DEFAULT_PORT);
MDNS.addServiceTxt("e131", "udp", "TxtVers", String(RDMNET_DNSSD_TXTVERS));
MDNS.addServiceTxt("e131", "udp", "ConfScope", RDMNET_DEFAULT_SCOPE);
MDNS.addServiceTxt("e131", "udp", "E133Vers", String(RDMNET_DNSSD_E133VERS));
MDNS.addServiceTxt("e131", "udp", "CID", chipId);
MDNS.addServiceTxt("e131", "udp", "Model", "WNRF");
MDNS.addServiceTxt("e131", "udp", "Manuf", "LabRat");
} else {
LOG_PORT.println(F("*** Error setting up mDNS responder ***"));
}
}
void onWiFiDisconnect(const WiFiEventStationModeDisconnected &event) {
LOG_PORT.println(F("*** WiFi Disconnected ***"));
#ifdef MQTT
// Pause MQTT reconnect while WiFi is reconnecting
mqttTicker.detach();
#endif
wifiTicker.once(2, reconnectWifi);
}
// Subscribe to "n" universes, starting at "universe"
void multiSub() {
uint8_t count;
ip_addr_t ifaddr;
ip_addr_t multicast_addr;
count = uniLast - config.universe + 1;
ifaddr.addr = static_cast<uint32_t>(WiFi.localIP());
for (uint8_t i = 0; i < count; i++) {
multicast_addr.addr = static_cast<uint32_t>(IPAddress(239, 255,
(((config.universe + i) >> 8) & 0xff),
(((config.universe + i) >> 0) & 0xff)));
igmp_joingroup(&ifaddr, &multicast_addr);
}
}
void ZCPPSub() {
ip_addr_t ifaddr;
ifaddr.addr = static_cast<uint32_t>(ourLocalIP);
ip_addr_t multicast_addr;
multicast_addr.addr = static_cast<uint32_t>(IPAddress(224, 0, 30, 5));
igmp_joingroup(&ifaddr, &multicast_addr);
LOG_PORT.println(F("- ZCPP Subscribed to multicast 224.0.30.5"));
}
/////////////////////////////////////////////////////////
//
// MQTT Section
//
/////////////////////////////////////////////////////////
#ifdef MQTT
void connectToMqtt() {
LOG_PORT.print(F("- Connecting to MQTT Broker "));
LOG_PORT.println(config.mqtt_ip);
mqtt.connect();
}
void onMqttConnect(bool sessionPresent) {
LOG_PORT.println(F("- MQTT Connected"));
// Get retained MQTT state
mqtt.subscribe(config.mqtt_topic.c_str(), 0);
mqtt.unsubscribe(config.mqtt_topic.c_str());
// Setup subscriptions
mqtt.subscribe(String(config.mqtt_topic + MQTT_SET_COMMAND_TOPIC).c_str(), 0);
// Publish state
publishState();
// Publish discovery
publishHA(config.mqtt_hadisco);
}
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason) {
LOG_PORT.println(F("- MQTT Disconnected"));
if (WiFi.isConnected()) {
mqttTicker.once(2, connectToMqtt);
}
}
void onMqttMessage(char* topic, char* payload,
AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total) {
DynamicJsonDocument r(1024);
DeserializationError error = deserializeJson(r, payload);
if (error) {
LOG_PORT.println("MQTT: Parsing failed");
return;
}
JsonObject root = r.as<JsonObject>();
// if its a retained message and we want clean session, ignore it
if ( properties.retain && config.mqtt_clean ) {
return;
}
bool stateOn = false;
if (root.containsKey("state")) {
if (strcmp(root["state"], LIGHT_ON) == 0) {
stateOn = true;
} else if (strcmp(root["state"], LIGHT_OFF) == 0) {
stateOn = false;
}
}
if (root.containsKey("brightness")) {
effects.setBrightness((float)root["brightness"] / 255.0);
}
if (root.containsKey("speed")) {
effects.setSpeed(root["speed"]);
}
if (root.containsKey("color")) {
effects.setColor({
root["color"]["r"],
root["color"]["g"],
root["color"]["b"]
});
}
if (root.containsKey("effect")) {
// Set the explict effect provided by the MQTT client
effects.setEffect(root["effect"]);
}
if (root.containsKey("reverse")) {
effects.setReverse(root["reverse"]);
}
if (root.containsKey("mirror")) {
effects.setMirror(root["mirror"]);
}
if (root.containsKey("allleds")) {
effects.setAllLeds(root["allleds"]);
}
// Set data source based on state - Fall back to E131 when off
if (stateOn) {
if (effects.getEffect().equalsIgnoreCase("Disabled"))
effects.setEffect("Solid");
config.ds = DataSource::MQTT;
} else {
config.ds = DataSource::E131;
effects.clearAll();
}
publishState();
}
void publishHA(bool join) {
// Setup HA discovery
String ha_config = config.mqtt_haprefix + "/light/" + String(ESP.getChipId(), HEX) + "/config";
if (join) {
DynamicJsonDocument root(1024);
root["name"] = config.id;
root["schema"] = "json";
root["state_topic"] = config.mqtt_topic;
root["command_topic"] = config.mqtt_topic + "/set";
root["rgb"] = "true";
root["brightness"] = "true";
root["effect"] = "true";
// Populate the effect list
JsonArray effect_list = root.createNestedArray("effect_list");
// effect[0] is 'disabled', skip it
for (uint8_t i = 1; i < effects.getEffectCount(); i++) {
effect_list.add(effects.getEffectInfo(i)->name);
}
// Register the attributes topic
root["json_attributes_topic"] = config.mqtt_topic + "/attributes";
// Create a unique id using the chip id, and fill in the device properties
// to enable integration support in HomeAssistant.
root["unique_id"] = "WNRF_" + String(ESP.getChipId(), HEX);
JsonObject device = root.createNestedObject("device");
device["identifiers"] = WiFi.macAddress();
device["manufacturer"] = "WNRF";
device["model"] = String(config.channel_count / 3) + " Pixel Controller";
device["name"] = config.id;
device["sw_version"] = "WNRF v" + String(VERSION);
char buffer[measureJson(root) + 1];
serializeJson(root, buffer, sizeof(buffer));
mqtt.publish(ha_config.c_str(), 0, true, buffer);
publishAttributes();
} else {
mqtt.publish(ha_config.c_str(), 0, true, "");
}
}
void publishState() {
DynamicJsonDocument root(1024);
if ((config.ds != DataSource::E131 && config.ds != DataSource::ZCPP) && (!effects.getEffect().equalsIgnoreCase("Disabled")))
root["state"] = LIGHT_ON;
else
root["state"] = LIGHT_OFF;
JsonObject color = root.createNestedObject("color");
color["r"] = effects.getColor().r;
color["g"] = effects.getColor().g;
color["b"] = effects.getColor().b;
root["brightness"] = effects.getBrightness() * 255;
root["speed"] = effects.getSpeed();
if (!effects.getEffect().equalsIgnoreCase("Disabled")) {
root["effect"] = effects.getEffect();
}
root["reverse"] = effects.getReverse();
root["mirror"] = effects.getMirror();
root["allleds"] = effects.getAllLeds();
char buffer[measureJson(root) + 1];
serializeJson(root, buffer, sizeof(buffer));
mqtt.publish(config.mqtt_topic.c_str(), 0, true, buffer);
}
void publishAttributes() {
String topic = config.mqtt_topic + "/attributes";
DynamicJsonDocument root(1024);
// Publish the e131 attributes=
root["universe"] = config.universe;
root["universe_limit"] = config.universe_limit;
root["channel_start"] = config.channel_start;
root["channel_count"] = config.channel_count;
root["multicast"] = config.multicast;
char buffer[measureJson(root) + 1];
serializeJson(root, buffer, sizeof(buffer));
mqtt.publish(topic.c_str(), 0, true, buffer);
}
#endif
/////////////////////////////////////////////////////////
//
// Web Section
//
/////////////////////////////////////////////////////////
File file; // Watch the spelling
char fw_name[40];
int getFWName(void) {
Dir dir = SPIFFS.openDir("/16f/");
if (dir.next()) {
snprintf(fw_name,40,"%s",dir.fileName().c_str());
return 1;
} else {
sprintf(fw_name,"");
return 0;
}
}
void handleUpload(AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){
if(!index){
LOG_PORT.print(F("UploadStart: "));
LOG_PORT.println(filename.c_str());
// Delete any existing files
Dir dir = SPIFFS.openDir("/16f/");
while (dir.next()) {
LOG_PORT.print("Removing (");
LOG_PORT.print(dir.fileName());
SPIFFS.remove(dir.fileName());
File f = dir.openFile("r");
LOG_PORT.println(")");
}
file = SPIFFS.open("/16f/"+filename,"w");
}
if (!file) {
// Something went wrong - invalid file handle
request->send(500, "text/plain", "File Creation Error: " );
cb_upload_reply(500, (char *) filename.c_str());
}
if (len) {
file.write(data,len);
}
if(final){
file.close();
LOG_PORT.print(F("\nUploadEnded: "));
LOG_PORT.print(filename.c_str());
LOG_PORT.print(", ");
LOG_PORT.println(index+len);
request->send(200, "text/plain", "File Upload Completed: " );
// Update filename
getFWName();
LOG_PORT.print(F("FILENAME:"));
LOG_PORT.print(fw_name);
LOG_PORT.print(".\n");
cb_upload_reply(200, fw_name);
}
}
// Configure and start the web server
void initWeb() {
// Handle OTA update from asynchronous callbacks
Update.runAsync(true);
// Add header for SVG plot support?
DefaultHeaders::Instance().addHeader("Access-Control-Allow-Origin", "*");
// Setup WebSockets
ws.onEvent(wsEvent);
web.addHandler(&ws);
// Heap status handler
web.on("/heap", HTTP_GET, [](AsyncWebServerRequest * request) {
request->send(200, "text/plain", String(ESP.getFreeHeap()));
});
// JSON Config Handler
web.on("/conf", HTTP_GET, [](AsyncWebServerRequest * request) {
String jsonString;
serializeConfig(jsonString, true);
request->send(200, "text/json", jsonString);
});
// Firmware upload handler - only in station mode
web.on("/updatefw", HTTP_POST, [](AsyncWebServerRequest * request) {
ws.textAll("X6");
}, handle_fw_upload).setFilter(ON_STA_FILTER);
// File Upload Handler
web.on("/wnrfu", HTTP_POST, [](AsyncWebServerRequest *request) {},
[](AsyncWebServerRequest *request, const String& filename, size_t index, uint8_t *data,
size_t len, bool final) {handleUpload(request, filename, index, data, len, final);}
);
// Static Handler
web.serveStatic("/", SPIFFS, "/www/").setDefaultFile("index.html");
// Raw config file Handler - but only on station
// web.serveStatic("/config.json", SPIFFS, "/config.json").setFilter(ON_STA_FILTER);
web.onNotFound([](AsyncWebServerRequest * request) {
request->send(404, "text/plain", "Page not found");
});
DefaultHeaders::Instance().addHeader(F("Access-Control-Allow-Origin"), "*");
// Config file upload handler - only in station mode
web.on("/config", HTTP_POST, [](AsyncWebServerRequest * request) {
ws.textAll("X6");
}, handle_config_upload).setFilter(ON_STA_FILTER);
web.begin();
LOG_PORT.print(F("- Web Server started on port "));
LOG_PORT.println(HTTP_PORT);
}
/////////////////////////////////////////////////////////
//
// JSON / Configuration Section
//
/////////////////////////////////////////////////////////
// Configuration Validations
void validateConfig() {
// E1.31 Limits
if (config.universe < 1)
config.universe = 1;
if (config.universe_limit > UNIVERSE_MAX || config.universe_limit < 1)
config.universe_limit = UNIVERSE_MAX;
if (config.channel_start < 1)
config.channel_start = 1;
else if (config.channel_start > config.universe_limit)
config.channel_start = config.universe_limit;
#ifdef MQTT
// Set default MQTT port if missing
if (config.mqtt_port == 0)
config.mqtt_port = MQTT_PORT;
// Generate default MQTT topic if blank
if (!config.mqtt_topic.length()) {
config.mqtt_topic = "diy/esps/" + String(ESP.getChipId(), HEX);
}
// Set default Home Assistant Discovery prefix if blank
if (!config.mqtt_haprefix.length()) {
config.mqtt_haprefix = "homeassistant";
}
#endif
#if defined(ESPS_MODE_WNRF)
// Set Mode
config.devmode = MODE_NRF;
if (config.nrf_legacy)
config.channel_count = 32;
else
config.channel_count = 512;
#endif
if (config.effect_speed < 1)
config.effect_speed = 1;
if (config.effect_speed > 10)
config.effect_speed = 10;
if (config.effect_brightness > 1.0)
config.effect_brightness = 1.0;
if (config.effect_brightness < 0.0)
config.effect_brightness = 0.0;
if (config.effect_idletimeout == 0) {
config.effect_idletimeout = 10;
config.effect_idleenabled = false;
}
if (config.effect_startenabled) {
if (effects.isValidEffect(config.effect_name)) {
effects.setEffect(config.effect_name);
if ( !config.effect_name.equalsIgnoreCase("disabled")
&& !config.effect_name.equalsIgnoreCase("view") ) {
config.ds = DataSource::WEB;
}
}
}
}
void updateConfig() {
// Validate first
validateConfig();
// Find the last universe we should listen for
uint16_t span = config.channel_start + config.channel_count - 1;
if (span % config.universe_limit)
uniLast = config.universe + span / config.universe_limit;
else
uniLast = config.universe + span / config.universe_limit - 1;
// Setup the sequence error tracker
uint8_t uniTotal = (uniLast + 1) - config.universe;
if (seqTracker) free(seqTracker);
if ((seqTracker = static_cast<uint8_t *>(malloc(uniTotal))))
memset(seqTracker, 0x00, uniTotal);
seqZCPPTracker = 0;
if (seqError) free(seqError);
if ((seqError = static_cast<uint32_t *>(malloc(uniTotal * 4))))
memset(seqError, 0x00, uniTotal * 4);
seqZCPPError = 0;
// Zero out packet stats
e131.stats.num_packets = 0;
zcpp.stats.num_packets = 0;
// Initialize for our pixel type
#if defined(ESPS_MODE_WNRF)
out_driver.begin(config.nrf_baud, config.nrf_chan, config.channel_count);
effects.begin(&out_driver, config.channel_count / 3 );
register_nrf_callbacks(); // Allow NRF driver to send ASYNC responses to WEB client
#endif
LOG_PORT.print(F("- Listening for "));
LOG_PORT.print(config.channel_count);
LOG_PORT.print(F(" channels, from Universe "));
LOG_PORT.print(config.universe);
LOG_PORT.print(F(" to "));
LOG_PORT.println(uniLast);
// Setup IGMP subscriptions if multicast is enabled
if (config.multicast)
multiSub();
#ifdef MQTT
// Update Home Assistant Discovery if enabled
if (config.mqtt) {
publishHA(config.mqtt_hadisco);
publishState();
}
#endif
}
// De-Serialize Network config
void dsNetworkConfig(const JsonObject &json) {
if (json.containsKey("network")) {
JsonObject networkJson = json["network"];
// Fallback to embedded ssid and passphrase if null in config
config.ssid = networkJson["ssid"].as<String>();
if (!config.ssid.length())
config.ssid = ssid;
config.passphrase = networkJson["passphrase"].as<String>();
if (!config.passphrase.length())
config.passphrase = passphrase;
// Network
for (int i = 0; i < 4; i++) {
config.ip[i] = networkJson["ip"][i];
config.netmask[i] = networkJson["netmask"][i];
config.gateway[i] = networkJson["gateway"][i];
}
config.dhcp = networkJson["dhcp"];
config.sta_timeout = networkJson["sta_timeout"] | CLIENT_TIMEOUT;
if (config.sta_timeout < 5) {
config.sta_timeout = 5;
}
config.ap_fallback = networkJson["ap_fallback"];
config.ap_timeout = networkJson["ap_timeout"] | AP_TIMEOUT;
if (config.ap_timeout < 15) {
config.ap_timeout = 15;
}
// Generate default hostname if needed
config.hostname = networkJson["hostname"].as<String>();
}
else {
LOG_PORT.println("No network settings found.");
}
if (!config.hostname.length()) {
config.hostname = "esps-" + String(ESP.getChipId(), HEX);
}
}
// De-serialize Effect Config
void dsEffectConfig(const JsonObject &json) {
// Effects
if (json.containsKey("effects")) {
JsonObject effectsJson = json["effects"];
config.effect_name = effectsJson["name"].as<String>();
config.effect_mirror = effectsJson["mirror"];
config.effect_allleds = effectsJson["allleds"];
config.effect_reverse = effectsJson["reverse"];
if (effectsJson.containsKey("speed"))
config.effect_speed = effectsJson["speed"];
config.effect_color = { effectsJson["r"], effectsJson["g"], effectsJson["b"] };
if (effectsJson.containsKey("brightness"))
config.effect_brightness = effectsJson["brightness"];
config.effect_startenabled = effectsJson["startenabled"];
config.effect_idleenabled = effectsJson["idleenabled"];
config.effect_idletimeout = effectsJson["idletimeout"];
}
else
{
LOG_PORT.println("No effect settings found.");
}
}
// De-serialize Device Config
void dsDeviceConfig(const JsonObject &json) {
// Device
if (json.containsKey("device")) {
config.id = json["device"]["id"].as<String>();
}
else
{
LOG_PORT.println("No device settings found.");
}
// E131
if (json.containsKey("e131")) {
config.universe = json["e131"]["universe"];
config.universe_limit = json["e131"]["universe_limit"];
config.channel_start = json["e131"]["channel_start"];
config.channel_count = json["e131"]["channel_count"];
config.multicast = json["e131"]["multicast"];
}
else
{
LOG_PORT.println("No e131 settings found.");
}
#ifdef MQTT
// MQTT
if (json.containsKey("mqtt")) {
JsonObject mqttJson = json["mqtt"];
config.mqtt = mqttJson["enabled"];
config.mqtt_ip = mqttJson["ip"].as<String>();
config.mqtt_port = mqttJson["port"];
config.mqtt_user = mqttJson["user"].as<String>();
config.mqtt_password = mqttJson["password"].as<String>();