-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathITS1A.ino
1117 lines (951 loc) · 33 KB
/
ITS1A.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
//#define DEBUG_ITS1A
//#define DEBUG_ALT
#define OTA
#define SYNC_BUS
#if defined DEBUG_ITS1A //|| defined DEBUG_ALT
#define DEBUG(...) { Serial.println(__VA_ARGS__); }
Print *debugPrint = &Serial;
#else
#define DEBUG(...) { }
#endif
//#define ALEXA
// Not enough space in ESP01 for SPIFFS, the app and an upload space.
//#define OTA
#include "Arduino.h"
#include "ConfigItem.h" // https://github.com/judge2005/Configs
#include "EEPROMConfig.h" // "
#ifdef OTA
#include "ASyncOTAWebUpdate.h" // https://github.com/judge2005/ASyncOTAWebUpdate
#endif
#include <EEPROM.h>
#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include <ESP8266mDNS.h>
#include <ESPAsyncTCP.h> // https://github.com/me-no-dev/ESPAsyncTCP
#include <ESPAsyncWebServer.h> // https://github.com/me-no-dev/ESPAsyncWebServer
#include <AsyncJson.h> // "
#ifdef USE_EADNS
#include <ESPAsyncDNSServer.h> // https://github.com/devyte/ESPAsyncDNSServer
#endif
#include <AsyncWiFiManager.h> // https://github.com/judge2005/AsyncWiFiManager
#include <DNSServer.h>
#include <NeoPixelBus.h> // https://github.com/Makuna/NeoPixelBus
#include <EspSNTPTimeSync.h> // https://github.com/judge2005/TimeSync
#ifdef ALEXA
#include <fauxmoESP.h> // https://bitbucket.org/judge2005/fauxmoesp
#include <HueColorUtils.h> // "
#endif
#include <ITS1ANixieDriver.h> // https://github.com/judge2005/NixieDriver
#include <SixNixieClock.h> // https://github.com/judge2005/OneNixieClock
#include <SoftMSTimer.h> // https://github.com/judge2005/NixieMisc
#include <MovementSensor.h> // "
#include <WSHandler.h> // https://github.com/judge2005/NixieMisc
#include <WSMenuHandler.h> // "
#include <WSConfigHandler.h> // "
#include <WSGlobalConfigHandler.h> // "
#include <WSPresetValuesHandler.h> // "
#include <WSPresetNamesHandler.h> // "
#include <WSInfoHandler.h> // "
#ifdef DEBUG_ALT
const byte MovPin = 13; // PIR/Radar etc.
#else
const byte MovPin = 3; // PIR/Radar etc.
#endif
unsigned long nowMs = 0;
char *revision="$Rev: 634 $";
String chipId = String(ESP.getChipId(), HEX);
String ssid = "STC-";
StringConfigItem hostName("hostname", 63, "ITS1AClock");
AsyncWebServer server(80);
AsyncWebSocket ws("/ws"); // access at ws://[esp ip]/ws
#ifdef USE_EADNS
AsyncDNSServer dns;
#else
DNSServer dns;
#endif
AsyncWiFiManager wifiManager(&server,&dns);
TimeSync *timeSync;
#ifdef SYNC_BUS
WiFiUDP syncBus;
#endif
#ifdef OTA
ASyncOTAWebUpdate otaUpdater(Update, "update", "secretsauce");
#endif
#ifdef ALEXA
fauxmoESP fauxmo;
#endif
ITS1ANixieDriver nixieDriver(6);
NixieDriver *pDriver = &nixieDriver;
SixNixieClock sixNixieClock(pDriver);
NixieClock *pNixieClock = &sixNixieClock;
class Configurator {
public:
virtual void configure() = 0;
};
void infoCallback();
namespace ConfigSet1 {
#include <ITS1AConfigSet1.h>
}
namespace ConfigSet2 {
#include <ITS1AConfigSet2.h>
} // End namespace
namespace ConfigSet3 {
#include <ITS1AConfigSet3.h>
} // End namespace
namespace ConfigSet4 {
#include <ITS1AConfigSet4.h>
} // End namespace
namespace ConfigSet5 {
#include <ITS1AConfigSet5.h>
} // End namespace
StringConfigItem set1Name("set1_name", 12, "24 Hour");
StringConfigItem set2Name("set2_name", 12, "12 Hour");
StringConfigItem set3Name("set3_name", 12, "Fast Clock");
StringConfigItem set4Name("set4_name", 12, "Test");
StringConfigItem set5Name("set5_name", 12, "Manual");
BaseConfigItem *configSetPresetNames[] = {
&set1Name,
&set2Name,
&set3Name,
&set4Name,
&set5Name,
0
};
CompositeConfigItem presetNamesConfig("preset_names", 0, configSetPresetNames);
StringConfigItem currentSet("current_set", 4, "set1");
// Alexa config values
StringConfigItem date_name("date_name", 20, String("date"));
StringConfigItem backlight_name("backlight_name", 20, String("backlight"));
StringConfigItem underlight_name("underlight_name", 20, String("underlight"));
StringConfigItem clock_name("clock_name", 20, String("clock"));
StringConfigItem test_name("test_name", 20, String("test"));
StringConfigItem cycling_name("cycling_name", 20, String("hue cycling"));
StringConfigItem twelve_hour_name("twelve_hour_name", 20, String("12 hour"));
StringConfigItem zero_name("zero_name", 20, String("leading zero"));
BaseConfigItem *alexaSet[] = {
// Alexa
&date_name,
&backlight_name,
&underlight_name,
&clock_name,
&test_name,
&cycling_name,
&twelve_hour_name,
&zero_name,
0
};
CompositeConfigItem alexaConfig("alexa", 0, alexaSet);
BaseConfigItem *configSetGlobal[] = {
&hostName,
¤tSet,
&alexaConfig,
0
};
CompositeConfigItem globalConfig("global", 0, configSetGlobal);
BaseConfigItem *configSetRoot[] = {
&globalConfig,
&presetNamesConfig,
&ConfigSet1::config,
&ConfigSet2::config,
&ConfigSet3::config,
&ConfigSet4::config,
&ConfigSet5::config,
0
};
CompositeConfigItem rootConfig("root", 0, configSetRoot);
EEPROMConfig config(rootConfig);
void infoCallback();
String wifiCallback();
namespace CurrentConfig {
String name("set1");
CompositeConfigItem *config = &ConfigSet1::config;
// Clock config values
BooleanConfigItem *time_or_date = &ConfigSet1::time_or_date;
ByteConfigItem *date_format = &ConfigSet1::date_format;
BooleanConfigItem *hour_format = &ConfigSet1::hour_format;
BooleanConfigItem *leading_zero = &ConfigSet1::leading_zero;
ByteConfigItem *fading = &ConfigSet1::fading;
ByteConfigItem *colons = &ConfigSet1::colons;
ByteConfigItem *display_on = &ConfigSet1::display_on;
ByteConfigItem *display_off = &ConfigSet1::display_off;
StringConfigItem *time_url = &ConfigSet1::time_url;
// LED config values
ByteConfigItem *hue = &ConfigSet1::hue;
ByteConfigItem *saturation = &ConfigSet1::saturation;
BooleanConfigItem *backlight = &ConfigSet1::backlight;
BooleanConfigItem *underlight = &ConfigSet1::underlight;
BooleanConfigItem *hue_cycling = &ConfigSet1::hue_cycling;
ByteConfigItem *led_scale = &ConfigSet1::led_scale;
ByteConfigItem *underlight_scale = &ConfigSet1::underlight_scale;
IntConfigItem *cycle_time = &ConfigSet1::cycle_time;
// Extra config values
ByteConfigItem *show_date = &ConfigSet1::show_date;
ByteConfigItem *out_effect = &ConfigSet1::out_effect;
ByteConfigItem *in_effect = &ConfigSet1::in_effect;
BooleanConfigItem *display = &ConfigSet1::display;
ByteConfigItem *test_speed = &ConfigSet1::test_speed;
IntConfigItem *reset_time = &ConfigSet1::reset_time;
IntConfigItem *set_time = &ConfigSet1::set_time;
BooleanConfigItem *hv = &ConfigSet1::hv;
ByteConfigItem *mov_delay = &ConfigSet1::mov_delay;
ByteConfigItem *mov_src = &ConfigSet1::mov_src;
// Alexa config values
StringConfigItem *date_name = &::date_name;
StringConfigItem *backlight_name = &::backlight_name;
StringConfigItem *underlight_name = &::underlight_name;
StringConfigItem *clock_name = &::clock_name;
StringConfigItem *test_name = &::test_name;
StringConfigItem *cycling_name = &::cycling_name;
StringConfigItem *twelve_hour_name = &::twelve_hour_name;
StringConfigItem *zero_name = &::zero_name;
// Sync config values
IntConfigItem *sync_port = &ConfigSet1::sync_port;
ByteConfigItem *sync_role = &ConfigSet1::sync_role;
void setCurrent(const String &name) {
if (CurrentConfig::name == name) {
return; // Already set to this
}
BaseConfigItem *newConfig = rootConfig.get(name.c_str());
if (newConfig) {
DEBUG("Changing preset to:");
DEBUG(name);
CurrentConfig::name = name;
config = static_cast<CompositeConfigItem*>(newConfig);
/*
* I hate doing this.
*/
// Clock config values
time_or_date = static_cast<BooleanConfigItem*>(config->get("time_or_date"));
date_format = static_cast<ByteConfigItem*>(config->get("date_format"));
hour_format = static_cast<BooleanConfigItem*>(config->get("hour_format"));
leading_zero = static_cast<BooleanConfigItem*>(config->get("leading_zero"));
fading = static_cast<ByteConfigItem*>(config->get("fading"));
colons = static_cast<ByteConfigItem*>(config->get("colons"));
display_on = static_cast<ByteConfigItem*>(config->get("display_on"));
display_off = static_cast<ByteConfigItem*>(config->get("display_off"));
time_url = static_cast<StringConfigItem*>(config->get("time_url"));
// LED config values
hue = static_cast<ByteConfigItem*>(config->get("hue"));
saturation = static_cast<ByteConfigItem*>(config->get("saturation"));
backlight = static_cast<BooleanConfigItem*>(config->get("backlight"));
underlight = static_cast<BooleanConfigItem*>(config->get("underlight"));
hue_cycling = static_cast<BooleanConfigItem*>(config->get("hue_cycling"));
led_scale = static_cast<ByteConfigItem*>(config->get("led_scale"));
underlight_scale = static_cast<ByteConfigItem*>(config->get("underlight_scale"));
cycle_time = static_cast<IntConfigItem*>(config->get("cycle_time"));
// Extra config values
show_date = static_cast<ByteConfigItem*>(config->get("show_date"));
out_effect = static_cast<ByteConfigItem*>(config->get("out_effect"));
in_effect = static_cast<ByteConfigItem*>(config->get("in_effect"));
display = static_cast<BooleanConfigItem*>(config->get("display"));
test_speed = static_cast<ByteConfigItem*>(config->get("test_speed"));
reset_time = static_cast<IntConfigItem*>(config->get("reset_time"));
set_time = static_cast<IntConfigItem*>(config->get("set_time"));
hv = static_cast<BooleanConfigItem*>(config->get("hv"));
mov_delay = static_cast<ByteConfigItem*>(config->get("mov_delay"));
mov_src = static_cast<ByteConfigItem*>(config->get("mov_src"));
// Sync config values
sync_port = static_cast<IntConfigItem*>(config->get("sync_port"));
sync_role = static_cast<ByteConfigItem*>(config->get("sync_role"));
BaseConfigItem *currentSetName = rootConfig.get("current_set");
currentSetName->fromString(name);
currentSetName->put();
}
}
}
MovementSensor mov(MovPin);
BlankTimeMonitor blankingMonitor;
class ITS1ANixieDriverConfigurator : Configurator {
public:
ITS1ANixieDriverConfigurator(ITS1ANixieDriver &driver) : driver(driver) {
}
virtual void configure() {
driver.setIndicator(*CurrentConfig::colons);
driver.setResetTime(*CurrentConfig::reset_time);
driver.setSetTime(*CurrentConfig::set_time);
}
private:
ITS1ANixieDriver &driver;
};
class SixNixieClockConfigurator : Configurator {
public:
SixNixieClockConfigurator(SixNixieClock &clock) : clock(clock) {
}
virtual void configure() {
if (timeSync->initialized() || !*CurrentConfig::display) {
clock.setClockMode(*CurrentConfig::display);
clock.setCountSpeed(*CurrentConfig::test_speed);
} else {
clock.setClockMode(false);
clock.setCountSpeed(60);
}
clock.setHV(*CurrentConfig::hv);
clock.setMov(mov.isOn());
clock.setFadeMode(*CurrentConfig::fading);
clock.setTimeMode(*CurrentConfig::time_or_date);
clock.setDateFormat(*CurrentConfig::date_format);
clock.set12hour(*CurrentConfig::hour_format);
clock.setLeadingZero(*CurrentConfig::leading_zero);
clock.setOnOff(*CurrentConfig::display_on, *CurrentConfig::display_off);
clock.setAlternateInterval(*CurrentConfig::show_date);
clock.setOutEffect(*CurrentConfig::out_effect);
clock.setInEffect(*CurrentConfig::in_effect);
}
private:
SixNixieClock &clock;
};
ITS1ANixieDriverConfigurator driverConfigurator(nixieDriver);
SixNixieClockConfigurator clockConfigurator(sixNixieClock);
#ifdef SYNC_BUS
void writeSyncBus(char msg[]) {
IPAddress broadcastIP(~((uint32_t)WiFi.subnetMask()) | ((uint32_t)WiFi.gatewayIP()));
syncBus.beginPacket(broadcastIP, *CurrentConfig::sync_port);
syncBus.write(msg);
syncBus.endPacket();
}
void sendSyncMsg() {
static char syncMsg[10] = "sync:";
if (*CurrentConfig::sync_role == 1) {
itoa(*CurrentConfig::hue, &syncMsg[5], 10);
writeSyncBus(syncMsg);
pNixieClock->syncDisplay();
// *CurrentConfig::digit = pNixieClock->getNixieDigit();
}
}
void sendMovMsg() {
static char syncMsg[10] = "mov";
static unsigned long lastSend = 0;
// send at most 10 notifications/sec
if (*CurrentConfig::sync_role == 1 && (nowMs - lastSend >= 100)) {
lastSend = nowMs;
writeSyncBus(syncMsg);
}
}
void announceSlave() {
static char syncMsg[] = "slave";
if (*CurrentConfig::sync_role == 2) {
writeSyncBus(syncMsg);
}
}
void readSyncBus() {
static char incomingMsg[10];
int size = syncBus.parsePacket();
if (size) {
int len = syncBus.read(incomingMsg, 9);
if (len > 0 && len < 10) {
incomingMsg[len] = 0;
if (strncmp("sync", incomingMsg, 4) == 0) {
if (strlen(incomingMsg) > 5) {
byte hue = atoi(&incomingMsg[5]);
*CurrentConfig::hue = hue;
}
pNixieClock->syncDisplay();
// *CurrentConfig::digit = pNixieClock->getNixieDigit();
return;
}
if (strncmp("mov", incomingMsg, 3) == 0) {
mov.trigger();
}
if (*CurrentConfig::sync_role == 1 && strcmp("slave", incomingMsg) == 0) {
// A new slave just joined, broadcast a sync message
sendSyncMsg();
}
}
}
}
void syncBusLoop() {
static byte currentRole = 255;
if (*CurrentConfig::sync_role != 0) {
// We are a master or slave
// If port has changed, set new port and announce status
if (syncBus.localPort() != *CurrentConfig::sync_port) {
syncBus.begin(*CurrentConfig::sync_port);
currentRole = 255;
}
} else {
// We aren't in a sync group
currentRole = 0;
syncBus.stop();
}
if (currentRole != *CurrentConfig::sync_role) {
currentRole = *CurrentConfig::sync_role;
if (currentRole == 1) {
sendSyncMsg();
} else if (currentRole == 2) {
announceSlave();
}
}
readSyncBus();
}
#endif
void initClock() {
pDriver->init();
pNixieClock->setTimeSync(timeSync);
pNixieClock->setNixieDriver(pDriver);
pNixieClock->init();
}
void ledTimerHandler();
SoftMSTimer::TimerInfo ledTimer = {
60000,
0,
false,
ledTimerHandler
};
SoftMSTimer::TimerInfo eepromUpdateTimer = {
60000,
0,
true,
eepromUpdate
};
#if defined DEBUG_ITS1A //|| defined DEBUG_ALT
SoftMSTimer::TimerInfo memoryDumpTimer = {
5000,
0,
true,
memoryDumpHandler
};
#endif
void memoryDumpHandler() {
DEBUG(ESP.getFreeHeap());
}
void timeHandler(AsyncWebServerRequest *request) {
DEBUG("Got time request")
String wifiTime = request->getParam("time", true, false)->value();
timeSync->setTime(wifiTime);
request->send(SPIFFS, "/time.html");
}
const byte numLEDs = 10;
NeoPixelBus <NeoGrbFeature, NeoEsp8266Uart0800KbpsMethod> leds(numLEDs);
void ledDisplay(bool backLight=true, bool underLight=true) {
uint8_t scale = *CurrentConfig::led_scale;
if (!backLight) {
scale = 0;
}
HsbColor color((byte)(*CurrentConfig::hue)/256.0, (byte)(*CurrentConfig::saturation)/256.0, scale/256.0);
for (int i=0; i<6; i++) {
leds.SetPixelColor(i, color);
}
scale = *CurrentConfig::underlight_scale;
if (!underLight) {
scale = 0;
}
color = HsbColor((byte)(*CurrentConfig::hue)/256.0, (byte)(*CurrentConfig::saturation)/256.0, scale/256.0);
for (int i=6; i<10; i++) {
leds.SetPixelColor(i, color);
}
#ifndef DEBUG_ITS1A
leds.Show();
#endif
}
void ledTimerHandler() {
ledDisplay(*CurrentConfig::backlight, *CurrentConfig::underlight);
if (*CurrentConfig::hue_cycling) {
broadcastUpdate(*CurrentConfig::hue);
*CurrentConfig::hue = (*CurrentConfig::hue + 1) % 256;
}
}
AsyncWiFiManagerParameter *hostnameParam;
void initFromEEPROM() {
// config.setDebugPrint(debugPrint);
config.init();
// rootConfig.debug(debugPrint);
DEBUG(hostName);
rootConfig.get(); // Read all of the config values from EEPROM
String currentSetName = currentSet;
CurrentConfig::setCurrent(currentSetName);
DEBUG(hostName);
hostnameParam = new AsyncWiFiManagerParameter("Hostname", "clock host name", hostName.value.c_str(), 63);
}
void createSSID() {
// Create a unique SSID that includes the hostname. Max SSID length is 32!
ssid = (chipId + hostName).substring(0, 31);
}
void setWiFiAP(bool on) {
if (on) {
wifiManager.startConfigPortal();
} else {
wifiManager.stopConfigPortal();
}
}
void mainHandler(AsyncWebServerRequest *request) {
DEBUG("Got request")
request->send(SPIFFS, "/index.html");
}
void sendFavicon(AsyncWebServerRequest *request) {
DEBUG("Got favicon request")
request->send(SPIFFS, "/assets/favicon-32x32.png", "image/png");
}
void broadcastUpdate(const BaseConfigItem& item) {
const size_t bufferSize = JSON_OBJECT_SIZE(2) + JSON_OBJECT_SIZE(20); // 20 should be plenty
#ifdef JSON5
DynamicJsonBuffer jsonBuffer(bufferSize);
JsonObject& root = jsonBuffer.createObject();
root["type"] = "sv.update";
JsonObject &value = root.createNestedObject("value");
String rawJSON = item.toJSON(); // This object needs to hang around until we are done serializing.
value[item.name] = ArduinoJson::RawJson(rawJSON.c_str());
size_t len = root.measureLength();
AsyncWebSocketMessageBuffer * buffer = ws.makeBuffer(len); // creates a buffer (len + 1) for you.
if (buffer) {
root.printTo((char *)buffer->get(), len + 1);
ws.textAll(buffer);
}
#else
DynamicJsonDocument doc(bufferSize);
JsonObject root = doc.to<JsonObject>();
root["type"] = "sv.update";
JsonVariant value = root.createNestedObject("value");
String rawJSON = item.toJSON(); // This object needs to hang around until we are done serializing.
value[item.name] = serialized(rawJSON.c_str());
size_t len = measureJson(root);
AsyncWebSocketMessageBuffer * buffer = ws.makeBuffer(len); // creates a buffer (len + 1) for you.
if (buffer) {
serializeJson(root, (char *)buffer->get(), len + 1);
ws.textAll(buffer);
}
#endif
#ifdef ALEXA
updateFauxMoValues();
#endif
}
WSConfigHandler wsClockHandler(rootConfig, "clock");
WSConfigHandler wsLEDHandler(rootConfig, "leds");
WSConfigHandler wsExtraHandler(rootConfig, "extra");
WSGlobalConfigHandler wsAlexaHandler(rootConfig, "alexa");
WSPresetValuesHandler wsPresetValuesHandler(rootConfig);
WSInfoHandler wsInfoHandler(infoCallback);
WSPresetNamesHandler wsPresetNamesHandler(rootConfig);
WSConfigHandler wsSyncHandler(rootConfig, "sync");
void infoCallback() {
wsInfoHandler.setSsid(ssid);
wsInfoHandler.setBlankingMonitor(&blankingMonitor);
wsInfoHandler.setRevision(revision);
TimeSync::SyncStats &syncStats = timeSync->getStats();
wsInfoHandler.setFailedCount(syncStats.failedCount);
wsInfoHandler.setLastFailedMessage(syncStats.lastFailedMessage);
wsInfoHandler.setLastUpdateTime(syncStats.lastUpdateTime);
}
String *items[] = {
&WSMenuHandler::clockMenu,
&WSMenuHandler::ledsMenu,
&WSMenuHandler::extraMenu,
#ifdef SYNC_BUS
&WSMenuHandler::syncMenu,
#endif
#ifdef ALEXA
&WSMenuHandler::alexaMenu,
#endif
&WSMenuHandler::presetsMenu,
&WSMenuHandler::infoMenu,
&WSMenuHandler::presetNamesMenu,
0
};
WSMenuHandler wsMenuHandler(items);
// Order of this needs to match the numbers in WSMenuHandler.cpp
WSHandler *wsHandlers[] = {
&wsMenuHandler,
&wsClockHandler,
&wsLEDHandler,
&wsExtraHandler,
&wsPresetValuesHandler,
&wsInfoHandler,
&wsPresetNamesHandler,
&wsAlexaHandler,
&wsSyncHandler
};
void updateValue(int screen, String pair) {
int index = pair.indexOf(':');
DEBUG(pair)
// _key has to hang around because key points to an internal data structure
String _key = pair.substring(0, index);
const char* key = _key.c_str();
String value = pair.substring(index+1);
if (screen == 4) { // Presets
CurrentConfig::setCurrent(value);
StringConfigItem temp(key, 10, value);
broadcastUpdate(temp);
} else if (screen == 6) { // Preset names
BaseConfigItem *item = rootConfig.get(key);
if (item != 0) {
item->fromString(value);
item->put();
broadcastUpdate(*item);
}
} else if (screen == 7) { // Alexa switch names
BaseConfigItem *item = rootConfig.get(key);
if (item != 0) {
#ifdef ALEXA
StringConfigItem *sItem = static_cast<StringConfigItem*>(item);
int deviceId = fauxmo.getDeviceId(sItem->value.c_str());
if (deviceId > 0) {
fauxmo.renameDevice(deviceId, value.c_str());
}
item->fromString(value);
item->put();
broadcastUpdate(*item);
#endif
}
} else {
BaseConfigItem *item = CurrentConfig::config->get(key);
if (item != 0) {
item->fromString(value);
item->put();
// Shouldn't special case this stuff. Should attach listeners to the config value!
// TODO: This won't work if we just switch change sets instead!
if (strcmp(key, CurrentConfig::time_url->name) == 0) {
timeSync->setTz(value);
timeSync->sync();
}
broadcastUpdate(*item);
} else if (_key == "sync_do") {
sendSyncMsg();
announceSlave();
} else if (_key == "wifi_ap") {
setWiFiAP(value == "true" ? true : false);
}
}
}
/*
* Handle application protocol
*/
void handleWSMsg(AsyncWebSocketClient *client, char *data) {
String wholeMsg(data);
int code = wholeMsg.substring(0, wholeMsg.indexOf(':')).toInt();
if (code < 9) {
wsHandlers[code]->handle(client, data);
} else {
String message = wholeMsg.substring(wholeMsg.indexOf(':')+1);
int screen = message.substring(0, message.indexOf(':')).toInt();
String pair = message.substring(message.indexOf(':')+1);
updateValue(screen, pair);
}
}
/*
* Handle transport protocol
*/
void wsHandler(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) {
//Handle WebSocket event
switch (type) {
case WS_EVT_CONNECT:
DEBUG("WS connected")
;
break;
case WS_EVT_DISCONNECT:
DEBUG("WS disconnected")
;
break;
case WS_EVT_ERROR:
DEBUG("WS error")
;
DEBUG((char* )data)
;
break;
case WS_EVT_PONG:
DEBUG("WS pong")
;
break;
case WS_EVT_DATA: // Yay we got something!
DEBUG("WS data")
;
AwsFrameInfo * info = (AwsFrameInfo*) arg;
if (info->final && info->index == 0 && info->len == len) {
//the whole message is in a single frame and we got all of it's data
if (info->opcode == WS_TEXT) {
DEBUG("WS text data");
data[len] = 0;
handleWSMsg(client, (char *) data);
} else {
DEBUG("WS binary data");
}
} else {
DEBUG("WS data was split up!");
}
break;
}
}
#ifdef OTA
void sendUpdateForm(AsyncWebServerRequest *request) {
request->send(SPIFFS, "/update.html");
}
void sendUpdatingInfo(AsyncResponseStream *response, boolean hasError) {
response->print("<html><head><meta http-equiv=\"refresh\" content=\"10; url=/\"></head><body>");
hasError ?
response->print("Update failed: please wait while the device reboots") :
response->print("Update OK: please wait while the device reboots");
response->print("</body></html>");
}
#endif
void eepromUpdate() {
config.commit();
}
void snoozeUpdate();
#ifdef ALEXA
void updateFauxMoValues() {
fauxmo.setState((unsigned char)0, !(*CurrentConfig::time_or_date), *CurrentConfig::time_or_date ? 0 : 255, 0, 0);
XYPoint xy = HueColorUtils::HSToXY(
round(((int)(*CurrentConfig::hue)) * 360.0 / 255.0),
((double)(*CurrentConfig::saturation)) / 255.0,
0
);
fauxmo.setState(1, *CurrentConfig::backlight, *CurrentConfig::led_scale, xy.x, xy.y);
fauxmo.setState(2, *CurrentConfig::underlight, *CurrentConfig::underlight_scale, xy.x, xy.y);
fauxmo.setState(3, *CurrentConfig::hv, *CurrentConfig::hv ? 255 : 0, 0, 0);
fauxmo.setState(4, !(*CurrentConfig::display), !(*CurrentConfig::display) ? 0 : 255, 0, 0);
fauxmo.setState(5, *CurrentConfig::hue_cycling, *CurrentConfig::hue_cycling ? 255 : 0, 0, 0);
fauxmo.setState(6, *CurrentConfig::hour_format, *CurrentConfig::hour_format ? 255 : 0, 0, 0);
fauxmo.setState(7, *CurrentConfig::leading_zero, *CurrentConfig::leading_zero ? 255 : 0, 0, 0);
}
void startFauxMo() {
fauxmo.createServer(false);
fauxmo.setPort(80); // This is required for gen3 devices
// You have to call enable(true) once you have a WiFi connection
// You can enable or disable the library at any moment
// Disabling it will prevent the devices from being discovered and switched
fauxmo.enable(true);
fauxmo.addDevice(CurrentConfig::date_name->value.c_str(), "Dimmable Light", "LOM001");
fauxmo.addDevice(CurrentConfig::backlight_name->value.c_str(), "Extended Color light", "LCT015");
fauxmo.addDevice(CurrentConfig::underlight_name->value.c_str(), "Extended Color light", "LCT015");
fauxmo.addDevice(CurrentConfig::clock_name->value.c_str(), "Dimmable Light", "LOM001");
fauxmo.addDevice(CurrentConfig::test_name->value.c_str(), "Dimmable Light", "LWB004");
fauxmo.addDevice(CurrentConfig::cycling_name->value.c_str(), "Dimmable Light", "LOM001");
fauxmo.addDevice(CurrentConfig::twelve_hour_name->value.c_str(), "Dimmable Light", "LOM001");
fauxmo.addDevice(CurrentConfig::zero_name->value.c_str(), "Dimmable Light", "LOM001");
updateFauxMoValues();
// These two callbacks are required for gen1 and gen3 compatibility
server.onRequestBody([](AsyncWebServerRequest *request, uint8_t *data, size_t len, size_t index, size_t total) {
if (fauxmo.process(request->client(), request->method() == HTTP_GET, request->url(), String((char *)data))) {
return;
}
// Handle any other body request here...
DEBUG("Passing on: ");
DEBUG(request->host());
DEBUG(request->url());
});
server.onNotFound([](AsyncWebServerRequest *request) {
String body = (request->hasParam("body", true)) ? request->getParam("body", true)->value() : String();
if (!fauxmo.process(request->client(), request->method() == HTTP_GET, request->url(), body)) {
// re-direct to root, i.e. brute force the captive portal if in AP mode.
if (!request->host().equals(request->client()->localIP().toString())) {
DEBUG(String("Redirecting: ") + request->client()->localIP().toString());
DEBUG(request->host());
DEBUG(request->url());
AsyncWebServerResponse *response = request->beginResponse(302,"text/plain","");
response->addHeader("Location", String("http://") + request->client()->localIP().toString());
response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response->addHeader("Pragma", "no-cache");
response->addHeader("Expires", "-1");
request->send ( response);
} else {
DEBUG("Sending not found");
AsyncWebServerResponse *response = request->beginResponse(404,"text/plain","Not found");
response->addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
response->addHeader("Pragma", "no-cache");
response->addHeader("Expires", "-1");
request->send (response );
}
}
});
fauxmo.onSetState([](unsigned char device_id, const char * device_name, bool state, unsigned char value, float x, float y) {
BooleanConfigItem *item = 0;
ByteConfigItem *valueItem = 0;
ByteConfigItem *hueItem = 0;
ByteConfigItem *saturationItem = 0;
switch (device_id) {
case 0:
item = &(*CurrentConfig::time_or_date = !state);
break;
case 1:
{
item = &(*CurrentConfig::backlight = state);
HS hs = HueColorUtils::XYToHS(x, y, 0);
hueItem = &(*CurrentConfig::hue = (byte)round(hs.h * 255.0 / 360.0));
saturationItem = &(*CurrentConfig::saturation = (byte)round(hs.s * 255));
valueItem = &(*CurrentConfig::led_scale = value);
}
break;
case 2:
{
item = &(*CurrentConfig::underlight = state);
HS hs = HueColorUtils::XYToHS(x, y, 0);
hueItem = &(*CurrentConfig::hue = (byte)round(hs.h * 255.0 / 360.0));
saturationItem = &(*CurrentConfig::saturation = (byte)round(hs.s * 255));
valueItem = &(*CurrentConfig::underlight_scale = value);
}
break;
case 3:
item = &(*CurrentConfig::hv = state);
break;
case 4:
item = &(*CurrentConfig::display = !state);
break;
case 5:
item = &(*CurrentConfig::hue_cycling = state);
break;
case 6:
item = &(*CurrentConfig::hour_format = state);
break;
case 7:
item = &(*CurrentConfig::leading_zero = state);
break;
}
if (item != 0) {
item->put();
broadcastUpdate(*item);
}
if (hueItem != 0) {
hueItem->put();
broadcastUpdate(*hueItem);
}
if (saturationItem != 0) {
saturationItem->put();
broadcastUpdate(*saturationItem);
}
if (valueItem != 0) {
valueItem->put();
broadcastUpdate(*valueItem);
}
});
}
#endif
void SetupServer() {
DEBUG("SetupServer()");
hostName = String(hostnameParam->getValue());
hostName.put();
config.commit();
createSSID();
wifiManager.setAPCredentials(ssid.c_str(), "secretsauce");
DEBUG(hostName.value);
MDNS.begin(hostName.value.c_str());
MDNS.addService("http", "tcp", 80);
if (!timeSync->initialized()) {
timeSync->init();
}
}
SoftMSTimer::TimerInfo *infos[] = {
&ledTimer,
&eepromUpdateTimer,
#if defined DEBUG_ITS1A //|| defined DEBUG_ALT
&memoryDumpTimer,
#endif
0
};
SoftMSTimer timedFunctions(infos);
void connectedHandler() {
// MDNS listens for an IP address from WiFi
DEBUG("WiFi connected");
MDNS.begin(hostName.value.c_str());
MDNS.addService("http", "tcp", 80);
if (!timeSync->initialized()) {
timeSync->init();
}
}
void apChange(AsyncWiFiManager *wifiManager) {
DEBUG("apChange()");
DEBUG(wifiManager->isAP());
// broadcastUpdate(wifiCallback());
}
void setup()
{
#if !defined DEBUG_ITS1A && !defined DEBUG_ALT
pinMode(MovPin, FUNCTION_3);
// pinMode(LED_PIN, FUNCTION_3);
#endif
#ifndef DEBUG_ITS1A
pinMode(MovPin, INPUT_PULLUP);
#endif
chipId.toUpperCase();
// Serial.begin(921600);