-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPowerManager.cpp
More file actions
1694 lines (1539 loc) · 72.7 KB
/
Copy pathPowerManager.cpp
File metadata and controls
1694 lines (1539 loc) · 72.7 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
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
#include "wled.h"
#define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x])))))
// external usermod: this ID is not present in WLED's const.h (overridable in case of a clash)
#ifndef USERMOD_ID_POWERMANAGER
#define USERMOD_ID_POWERMANAGER 200
#endif
#ifndef POWERMANAGER_MAX_RELAYS
#define POWERMANAGER_MAX_RELAYS 4
#else
#if POWERMANAGER_MAX_RELAYS>16
#undef POWERMANAGER_MAX_RELAYS
#define POWERMANAGER_MAX_RELAYS 16
#warning Maximum relays set to 16
#endif
#endif
#ifndef POWERMANAGER_PINS
#define POWERMANAGER_PINS -1
#define POWERMANAGER_ENABLED false
#else
#define POWERMANAGER_ENABLED true
#endif
#ifndef POWERMANAGER_HA_DISCOVERY
#define POWERMANAGER_HA_DISCOVERY false
#endif
#ifndef POWERMANAGER_DELAYS
#define POWERMANAGER_DELAYS 0
#endif
#ifndef POWERMANAGER_EXTERNALS
#define POWERMANAGER_EXTERNALS false
#endif
#ifndef POWERMANAGER_INVERTS
#define POWERMANAGER_INVERTS false
#endif
#ifndef POWERMANAGER_SEGMENTS
#define POWERMANAGER_SEGMENTS -1
#endif
#ifndef POWERMANAGER_STABILIZE
#define POWERMANAGER_STABILIZE 1
#endif
// relay 0 doubles as the dedicated "Master AC relay" (e.g. the AC-side trigger of the main PSU):
// when enabled it is on while any segment is on. Only relay 0 can take this role.
#ifndef POWERMANAGER_MASTER
#define POWERMANAGER_MASTER false
#endif
// sync main power with the Master AC relay: when it cuts because every segment was switched off,
// main power is switched off too (UI/MQTT/HA show off); switching a segment on restores it
#ifndef POWERMANAGER_MASTER_MAIN_SYNC
#define POWERMANAGER_MASTER_MAIN_SYNC false
#endif
// take over all relays: unconfigured relays (pin set, but no segment link and not externally
// controlled) stay off until they are given a role, instead of following main power (default WLED
// behavior). Avoids surprises once part of the relays is segment-coupled.
#ifndef POWERMANAGER_TAKEOVER
#define POWERMANAGER_TAKEOVER false
#endif
// special relay_t.segment value: relay is on while *any* segment is on (master PSU mode)
#define POWERMANAGER_SEG_ANY 99
#ifndef POWERMANAGER_NAMES
#define POWERMANAGER_NAMES ""
#endif
#ifndef POWERMANAGER_NAME_LEN
#define POWERMANAGER_NAME_LEN 33 // max relay name length including terminator
#endif
// anti-flash blackout around segment power-on: black frames sent before / kept up after switching the port
#ifndef POWERMANAGER_BLACK_PRE_MS
#define POWERMANAGER_BLACK_PRE_MS 200
#endif
#ifndef POWERMANAGER_BLACK_POST_MS
#define POWERMANAGER_BLACK_POST_MS 200
#endif
// minimum time a port stays off before it may be re-energised: lets the LED strip's capacitors
// discharge so the chips reset properly (re-powering a half-discharged strip can latch a white
// flash no matter what data is streaming)
#ifndef POWERMANAGER_MIN_OFF_MS
#define POWERMANAGER_MIN_OFF_MS 2000
#endif
// power-on blackout phases (relay_t.boPhase)
#define BO_NONE 0
#define BO_PRE 1 // sending black frames, port still off
#define BO_POST 2 // port energised, still sending black frames
#define BO_FADE 3 // still black; cancelled stale transition is being destroyed, clean fade starts next frame
#define BO_FADE_TIMEOUT_MS 250 // max wait in BO_FADE for a cancelled transition to be destroyed
#define POWERMANAGER_FADE_GRACE_MS 1000 // extra wait for a lingering fade-out before cutting power anyway
#define WLED_DEBOUNCE_THRESHOLD 50 //only consider button input of at least 50ms as valid (debouncing)
#define ON true
#define OFF false
// I2C port expander types
#define EXPANDER_NONE 0
#define EXPANDER_PCF8574 1
#define EXPANDER_AW9523 2
#if defined(USERMOD_USE_PCF8574) && defined(USERMOD_USE_AW9523)
#error "PowerManager: define either USERMOD_USE_PCF8574 or USERMOD_USE_AW9523, not both"
#endif
#if defined(USERMOD_USE_PCF8574)
#define POWERMANAGER_EXPANDER EXPANDER_PCF8574
#elif defined(USERMOD_USE_AW9523)
#define POWERMANAGER_EXPANDER EXPANDER_AW9523
#else
#ifndef POWERMANAGER_EXPANDER
#define POWERMANAGER_EXPANDER EXPANDER_NONE
#endif
#endif
#ifndef PCF8574_ADDRESS
#define PCF8574_ADDRESS 0x20 // some may start at 0x38
#endif
#ifndef AW9523_ADDRESS
#define AW9523_ADDRESS 0x58 // AD1=AD0=GND; 0x58-0x5B depending on AD1/AD0 straps
#endif
#ifndef AW9523_P0_PUSHPULL
#define AW9523_P0_PUSHPULL true // P0_x port drive mode: push-pull (recommended for relays), false = open-drain
#endif
#if POWERMANAGER_EXPANDER == EXPANDER_AW9523
#define POWERMANAGER_EXPANDER_ADDR AW9523_ADDRESS
#else
#define POWERMANAGER_EXPANDER_ADDR PCF8574_ADDRESS
#endif
// AW9523(B) register map (registers 0x03, 0x05, 0x07 and 0x13 are the P1 counterparts of P0 at 0x02, 0x04, 0x06 and 0x12)
#define AW9523_REG_IN0 0x00 // input state (read-only)
#define AW9523_REG_OUT0 0x02 // output state: 0=low, 1=high
#define AW9523_REG_CFG0 0x04 // direction: 0=output, 1=input
#define AW9523_REG_INT0 0x06 // interrupt: 0=enabled, 1=disabled
#define AW9523_REG_ID 0x10 // read-only, returns 0x23
#define AW9523_REG_GCR 0x11 // global control: bit4 P0 push-pull, bits 0-1 LED current range
#define AW9523_REG_MODE0 0x12 // port mode: 0=LED, 1=GPIO
#define AW9523_ID_VALUE 0x23
#define AW9523_GCR_GPOMD 0x10 // GCR bit4: P0 port push-pull when set
/*
* Power Manager usermod
*
* Handles multiple relay/MOSFET power outputs (direct GPIO or PCF8574/AW9523 I2C expanders).
* Relays can be named and coupled to segments: a coupled relay follows its segment's on/off
* state to cut the actual supply power of individual LED sections, with anti-flash power
* sequencing, PSU stabilization and a dedicated Master AC relay (relay 0) that is always the
* last to cut and can mirror WLED's main power state.
* See readme.md and the "Segment coupling & power sequencing" section below for details.
*
* This usermod grew out of WLED's built-in multi_relay usermod:
* multi_relay written and maintained by @blazoncek (with contributions noted in its history)
* power sequencing / segment coupling extensions and rename by @Quindor (intermit.tech)
* Settings saved by multi_relay are migrated automatically (see readFromConfig()).
*/
typedef struct relay_t {
int8_t pin;
struct { // reduces memory footprint
bool active : 1; // is the relay waiting to be switched
bool invert : 1; // does On mean 1 or 0
bool state : 1; // 1 relay is On, 0 relay is Off
bool external : 1; // is the relay externally controlled
int8_t button : 4; // which button triggers relay
bool segSeen : 1; // segment coupling: linked segment observed active this session (guards deletion detection against boot races)
uint8_t boPhase : 2; // power-on blackout phase (BO_NONE/BO_PRE/BO_POST/BO_FADE)
};
uint16_t delayOn; // seconds to wait before switching the relay on
uint16_t delayOff; // seconds to wait before switching the relay off
int8_t segment; // segment this relay follows: -1 = not coupled, 0..MAX_NUM_SEGMENTS-1 = segment id, 99 = any segment on
char name[POWERMANAGER_NAME_LEN]; // user-friendly name (e.g. physical output port), shown in UI/Info/HA
} Relay;
class PowerManager : public Usermod {
private:
// array of relays
Relay _relay[POWERMANAGER_MAX_RELAYS];
uint32_t _switchTimerStart; // switch timer start time
// segment coupling & power sequencing state (see section comment in the implementation)
uint32_t _pendingSince[POWERMANAGER_MAX_RELAYS]; // start of a pending delayed switch (0 = nothing pending)
uint32_t _boStart[POWERMANAGER_MAX_RELAYS]; // start of the current blackout phase
uint32_t _onAt[POWERMANAGER_MAX_RELAYS]; // last switch-on time (master stabilization window)
uint32_t _offAt[POWERMANAGER_MAX_RELAYS]; // last switch-off time (minimum off-time gate)
bool _oldMode; // old brightness
bool enabled; // usermod enabled
bool initDone; // status of initialisation
uint8_t expanderType; // I2C port expander type (EXPANDER_NONE/EXPANDER_PCF8574/EXPANDER_AW9523)
uint8_t expanderAddr; // I2C address of port expander
bool awP0PushPull; // AW9523: drive P0_x port in push-pull mode (instead of open-drain)
bool awFound; // AW9523: chip detected on I2C bus (ID register check)
uint16_t awOutputState; // AW9523: shadow of output registers (bit n = port n; 0-7 = P0_x, 8-15 = P1_x)
uint16_t boPreMs; // blackout: black frames before segment power-on (0 with boPostMs 0 = disabled)
uint16_t boPostMs; // blackout: keep sending black frames this long after power-on
uint16_t stabilizeSec; // PSU stabilization (seconds): after the Master AC relay powers on,
// the strip stays black and dependent coupled relays wait this long
uint16_t minOffMs; // minimum port off-time before re-energising (LED capacitor discharge)
bool masterEnabled; // relay 0 acts as the Master AC relay (segment = POWERMANAGER_SEG_ANY)
bool masterMainSync; // main power follows the Master AC relay (off when it cuts, back on with a segment)
bool _autoMainOff; // this usermod switched main power off (a segment turning on restores it)
bool takeOverRelays; // unconfigured relays stay off instead of following main power
bool HAautodiscovery;
uint16_t periodicBroadcastSec;
unsigned long lastBroadcast;
// strings to reduce flash memory usage (used more than twice)
static const char _name[];
static const char _legacyName[];
static const char _enabled[];
static const char _relay_str[];
static const char _delay_str[];
static const char _activeHigh[];
static const char _external[];
static const char _button[];
static const char _broadcast[];
static const char _HAautodiscovery[];
static const char _pcf8574[];
static const char _pcfAddress[];
static const char _expander[];
static const char _expanderAddr[];
static const char _pushPull[];
static const char _switch[];
static const char _toggle[];
static const char _Command[];
static const char _segment_str[];
static const char _delayOn_str[];
static const char _delayOff_str[];
static const char _stabilize_str[];
static const char _blackPre[];
static const char _blackPost[];
static const char _minOff[];
static const char _master[];
static const char _mainSync[];
static const char _takeOver[];
void handleOffTimer();
void handleSegmentCoupling();
void handleBlackout();
void beginFadePhase(uint8_t r);
void restartSegmentFade(uint8_t r);
void cancelSegTransitions(uint8_t r);
bool isSegFading(uint8_t r);
bool masterHoldsOn();
bool dependentsStillOn();
void setSegmentLink(uint8_t relay, int seg, bool persist = true);
void InitHtmlAPIHandle();
int getValue(String data, char separator, int index);
uint8_t getActiveRelayCount();
// number of output ports the configured expander provides (expander pins are 100 .. 100+count-1)
inline uint8_t expanderPortCount() { return expanderType == EXPANDER_AW9523 ? 16 : 8; }
// relay is coupled to a segment (exclusively segment-driven, no external/button control)
inline bool isCoupled(uint8_t r) { return _relay[r].segment >= 0; }
// invoke fn(Segment&) for every active segment the relay is coupled to
// (its own segment, or all of them for an "any segment" master relay)
template<typename FN> void forOwnedSegments(uint8_t r, FN fn) {
if (_relay[r].segment == POWERMANAGER_SEG_ANY) {
for (unsigned s = 0; s < strip.getSegmentsNum(); s++) {
Segment &seg = strip.getSegment(s);
if (seg.isActive()) fn(seg);
}
} else if ((uint8_t)_relay[r].segment < strip.getSegmentsNum()) {
Segment &seg = strip.getSegment(_relay[r].segment);
if (seg.isActive()) fn(seg);
}
}
byte IOexpanderWrite(byte address, byte _data);
byte IOexpanderRead(int address);
// AW9523 register access (byte pairs use the chip's auto-incrementing register pointer)
byte awRegWrite8(uint8_t reg, uint8_t value);
byte awRegWrite16(uint8_t reg, uint16_t value);
int16_t awRegRead8(uint8_t reg); // returns -1 on I2C error
void initAW9523(uint16_t state, uint16_t used);
void publishMqtt(int relay);
#ifndef WLED_DISABLE_MQTT
void publishHomeAssistantAutodiscovery();
#endif
public:
/**
* constructor
*/
PowerManager();
/**
* desctructor
*/
//~PowerManager() {}
/**
* Enable/Disable the usermod
*/
inline void enable(bool enable) { enabled = enable; }
/**
* Get usermod enabled/disabled state
*/
inline bool isEnabled() { return enabled; }
/**
* getId() allows you to optionally give your V2 usermod an unique ID (please define it in const.h!).
* This could be used in the future for the system to determine whether your usermod is installed.
*/
inline uint16_t getId() override { return USERMOD_ID_POWERMANAGER; }
/**
* switch relay on/off
*/
void switchRelay(uint8_t relay, bool mode);
/**
* toggle relay
*/
inline void toggleRelay(uint8_t relay) {
switchRelay(relay, !_relay[relay].state);
}
/**
* setup() is called once at boot. WiFi is not yet connected at this point.
* You can use it to initialize variables, sensors or similar.
*/
void setup() override;
/**
* connected() is called every time the WiFi is (re)connected
* Use it to initialize network interfaces
*/
inline void connected() override { InitHtmlAPIHandle(); }
/**
* loop() is called continuously. Here you can check for events, read sensors, etc.
*/
void loop() override;
/**
* called after effects are rendered, just before strip.show();
* paints segments in a power-on blackout window black
*/
void handleOverlayDraw() override;
/**
* streams the JavaScript that injects the segment-card "Power relays" menu into the
* main web UI (served at /um.js; the UI runs it after every state render)
*/
#ifdef WLED_ENABLE_UM_UI_INJECT // WLED base includes the usermod web-UI injection mechanism
void addUIInjectCode(Print &dest) override;
#endif
#ifndef WLED_DISABLE_MQTT
bool onMqttMessage(char* topic, char* payload) override;
void onMqttConnect(bool sessionPresent) override;
#endif
/**
* handleButton() can be used to override default button behaviour. Returning true
* will prevent button working in a default way.
* Replicating button.cpp
*/
bool handleButton(uint8_t b) override;
/**
* addToJsonInfo() can be used to add custom entries to the /json/info part of the JSON API.
*/
void addToJsonInfo(JsonObject &root) override;
/**
* addToJsonState() can be used to add custom entries to the /json/state part of the JSON API (state object).
* Values in the state object may be modified by connected clients
*/
void addToJsonState(JsonObject &root) override;
/**
* readFromJsonState() can be used to receive data clients send to the /json/state part of the JSON API (state object).
* Values in the state object may be modified by connected clients
*/
void readFromJsonState(JsonObject &root) override;
/**
* provide the changeable values
*/
void addToConfig(JsonObject &root) override;
void appendConfigData() override;
/**
* restore the changeable values
* readFromConfig() is called before setup() to populate properties from values stored in cfg.json
*
* The function should return true if configuration was successfully loaded or false if there was no configuration.
*/
bool readFromConfig(JsonObject &root) override;
};
// class implementation
void PowerManager::publishMqtt(int relay) {
#ifndef WLED_DISABLE_MQTT
//Check if MQTT Connected, otherwise it will crash the 8266
if (WLED_MQTT_CONNECTED){
char subuf[64];
sprintf_P(subuf, PSTR("%s/relay/%d"), mqttDeviceTopic, relay);
mqtt->publish(subuf, 0, false, _relay[relay].state ? "on" : "off");
}
#endif
}
/**
* switch off the strip if the delay has elapsed
*/
void PowerManager::handleOffTimer() {
unsigned long now = millis();
bool activeRelays = false;
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
if (_relay[i].active && _switchTimerStart > 0 && now - _switchTimerStart > (unsigned long)(offMode ? _relay[i].delayOff : _relay[i].delayOn)*1000) {
if (!_relay[i].external) switchRelay(i, !offMode);
_relay[i].active = false;
} else if (periodicBroadcastSec && now - lastBroadcast > (periodicBroadcastSec*1000)) {
if (_relay[i].pin>=0) publishMqtt(i);
}
activeRelays = activeRelays || _relay[i].active;
}
if (!activeRelays) _switchTimerStart = 0;
if (periodicBroadcastSec && now - lastBroadcast > (periodicBroadcastSec*1000)) lastBroadcast = now;
}
/**
* HTTP API handler
* borrowed from:
* https://github.com/gsieben/WLED/blob/master/usermods/GeoGab-Relays/usermod_GeoGab.h
*/
#define GEOGABVERSION "0.1.3"
void PowerManager::InitHtmlAPIHandle() { // https://github.com/me-no-dev/ESPAsyncWebServer
DEBUG_PRINTLN(F("Relays: Initialize HTML API"));
server.on(F("/relays"), HTTP_GET, [this](AsyncWebServerRequest *request) {
DEBUG_PRINTLN(F("Relays: HTML API"));
String janswer;
String error = "";
//int params = request->params();
janswer = F("{\"NoOfRelays\":");
janswer += String(POWERMANAGER_MAX_RELAYS) + ",";
if (getActiveRelayCount()) {
// Commands
if (request->hasParam(FPSTR(_switch))) {
/**** Switch ****/
AsyncWebParameter* p = request->getParam(FPSTR(_switch));
// Get Values
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
int value = getValue(p->value(), ',', i);
if (value==-1) {
error = F("There must be as many arguments as relays");
} else {
// Switch
if (_relay[i].external) switchRelay(i, (bool)value);
}
}
} else if (request->hasParam(FPSTR(_toggle))) {
/**** Toggle ****/
AsyncWebParameter* p = request->getParam(FPSTR(_toggle));
// Get Values
for (int i=0;i<POWERMANAGER_MAX_RELAYS;i++) {
int value = getValue(p->value(), ',', i);
if (value==-1) {
error = F("There must be as many arguments as relays");
} else {
// Toggle
if (value && _relay[i].external) toggleRelay(i);
}
}
} else {
error = F("No valid command found");
}
} else {
error = F("No active relays");
}
// Status response
char sbuf[16];
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
sprintf_P(sbuf, PSTR("\"%d\":%d,"), i, (_relay[i].pin<0 ? -1 : (int)_relay[i].state));
janswer += sbuf;
}
janswer += F("\"error\":\"");
janswer += error;
janswer += F("\",");
janswer += F("\"SW Version\":\"");
janswer += String(F(GEOGABVERSION));
janswer += F("\"}");
request->send(200, "application/json", janswer);
});
}
int PowerManager::getValue(String data, char separator, int index) {
int found = 0;
int strIndex[] = {0, -1};
int maxIndex = data.length()-1;
for(int i=0; i<=maxIndex && found<=index; i++){
if(data.charAt(i)==separator || i==maxIndex){
found++;
strIndex[0] = strIndex[1]+1;
strIndex[1] = (i == maxIndex) ? i+1 : i;
}
}
return found>index ? data.substring(strIndex[0], strIndex[1]).toInt() : -1;
}
//Write a byte to the IO expander
byte PowerManager::IOexpanderWrite(byte address, byte _data ) {
Wire.beginTransmission(address);
Wire.write(_data);
return Wire.endTransmission();
}
//Read a byte from the IO expander
byte PowerManager::IOexpanderRead(int address) {
byte _data = 0;
Wire.requestFrom(address, 1);
if (Wire.available()) {
_data = Wire.read();
}
return _data;
}
//Write a byte to an AW9523 register
byte PowerManager::awRegWrite8(uint8_t reg, uint8_t value) {
Wire.beginTransmission(expanderAddr);
Wire.write(reg);
Wire.write(value);
return Wire.endTransmission();
}
//Write two consecutive AW9523 registers (low byte to reg, high byte to reg+1) in one transaction
byte PowerManager::awRegWrite16(uint8_t reg, uint16_t value) {
Wire.beginTransmission(expanderAddr);
Wire.write(reg);
Wire.write((uint8_t)(value & 0xFF));
Wire.write((uint8_t)(value >> 8));
return Wire.endTransmission();
}
//Read a byte from an AW9523 register, -1 on I2C error
int16_t PowerManager::awRegRead8(uint8_t reg) {
Wire.beginTransmission(expanderAddr);
Wire.write(reg);
if (Wire.endTransmission(false) != 0) return -1; // repeated start
if (Wire.requestFrom(expanderAddr, (uint8_t)1) != 1) return -1;
return Wire.read();
}
/**
* initialise AW9523: verify chip ID, then configure only the ports used by relays
* (GPIO mode, output direction, interrupts masked) without disturbing other ports.
* state = desired output level per port (invert already applied), used = ports owned by relays
*/
void PowerManager::initAW9523(uint16_t state, uint16_t used) {
awFound = (awRegRead8(AW9523_REG_ID) == AW9523_ID_VALUE);
if (!awFound) {
DEBUG_PRINTLN(F("AW9523 not found."));
return;
}
// merge relay states into shadow of output registers so unrelated ports keep their level
int16_t lo = awRegRead8(AW9523_REG_OUT0);
int16_t hi = awRegRead8(AW9523_REG_OUT0+1);
awOutputState = (lo < 0 || hi < 0) ? 0 : ((uint16_t)hi << 8) | (uint8_t)lo;
awOutputState = (awOutputState & ~used) | (state & used);
awRegWrite16(AW9523_REG_OUT0, awOutputState); // set levels before flipping direction to avoid glitches
// P0 port drive mode; keep LED current bits, reserved bits must be written 0
int16_t gcr = awRegRead8(AW9523_REG_GCR);
awRegWrite8(AW9523_REG_GCR, ((gcr < 0 ? 0 : gcr) & 0x03) | (awP0PushPull ? AW9523_GCR_GPOMD : 0));
for (int p = 0; p < 2; p++) { // p=0: P0_x registers, p=1: P1_x registers
uint8_t mask = used >> (8*p);
if (!mask) continue;
int16_t v;
v = awRegRead8(AW9523_REG_MODE0+p); if (v >= 0) awRegWrite8(AW9523_REG_MODE0+p, v | mask); // GPIO mode
v = awRegRead8(AW9523_REG_CFG0+p); if (v >= 0) awRegWrite8(AW9523_REG_CFG0+p, v & ~mask); // output direction
v = awRegRead8(AW9523_REG_INT0+p); if (v >= 0) awRegWrite8(AW9523_REG_INT0+p, v | mask); // interrupts off
}
DEBUG_PRINTLN(F("AW9523 inited."));
}
// public methods
PowerManager::PowerManager()
: _switchTimerStart(0)
, enabled(POWERMANAGER_ENABLED)
, initDone(false)
, expanderType(POWERMANAGER_EXPANDER)
, expanderAddr(POWERMANAGER_EXPANDER_ADDR)
, awP0PushPull(AW9523_P0_PUSHPULL)
, awFound(false)
, awOutputState(0)
, boPreMs(POWERMANAGER_BLACK_PRE_MS)
, boPostMs(POWERMANAGER_BLACK_POST_MS)
, stabilizeSec(POWERMANAGER_STABILIZE)
, minOffMs(POWERMANAGER_MIN_OFF_MS)
, masterEnabled(POWERMANAGER_MASTER)
, masterMainSync(POWERMANAGER_MASTER_MAIN_SYNC)
, _autoMainOff(false)
, takeOverRelays(POWERMANAGER_TAKEOVER)
, HAautodiscovery(POWERMANAGER_HA_DISCOVERY)
, periodicBroadcastSec(60)
, lastBroadcast(0)
{
const int8_t defPins[] = {POWERMANAGER_PINS};
const int8_t relayDelays[] = {POWERMANAGER_DELAYS};
const bool relayExternals[] = {POWERMANAGER_EXTERNALS};
const bool relayInverts[] = {POWERMANAGER_INVERTS};
const int8_t relaySegments[] = {POWERMANAGER_SEGMENTS};
const char* const relayNames[] = {POWERMANAGER_NAMES};
for (size_t i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
_relay[i].pin = i < COUNT_OF(defPins) ? defPins[i] : -1;
_relay[i].delayOn = i < COUNT_OF(relayDelays) ? relayDelays[i] : 0;
_relay[i].delayOff = i < COUNT_OF(relayDelays) ? relayDelays[i] : 0;
_relay[i].invert = i < COUNT_OF(relayInverts) ? relayInverts[i] : false;
_relay[i].active = false;
_relay[i].state = false;
_relay[i].external = i < COUNT_OF(relayExternals) ? relayExternals[i] : false;
_relay[i].button = -1;
_relay[i].segment = i < COUNT_OF(relaySegments) ? relaySegments[i] : -1;
_relay[i].segSeen = false;
_relay[i].boPhase = BO_NONE;
_pendingSince[i] = 0;
_boStart[i] = 0;
_onAt[i] = 0;
_offAt[i] = 0;
strlcpy(_relay[i].name, i < COUNT_OF(relayNames) ? relayNames[i] : "", POWERMANAGER_NAME_LEN);
}
// relay 0 is the dedicated Master AC relay slot; only it may follow all segments
if (masterEnabled) {
_relay[0].segment = POWERMANAGER_SEG_ANY;
if (_relay[0].delayOff == 0) _relay[0].delayOff = 5; // default PSU anti-cycling hold (config overrides)
}
for (size_t i=1; i<POWERMANAGER_MAX_RELAYS; i++)
if (_relay[i].segment == POWERMANAGER_SEG_ANY) _relay[i].segment = -1;
}
/**
* switch relay on/off
*/
void PowerManager::switchRelay(uint8_t relay, bool mode) {
if (relay>=POWERMANAGER_MAX_RELAYS || _relay[relay].pin<0) return;
if (_relay[relay].state != mode) { // timestamps drive the stabilization and minimum off-time windows
if (mode) _onAt[relay] = millis();
else _offAt[relay] = millis();
}
_relay[relay].state = mode;
if (expanderType == EXPANDER_PCF8574 && _relay[relay].pin >= 100) {
// we need to send all outputs at the same time
uint8_t state = 0;
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
if (_relay[i].pin < 100) continue;
uint8_t pin = _relay[i].pin - 100;
state |= (_relay[i].invert ? !_relay[i].state : _relay[i].state) << pin; // fill relay states for all pins
}
IOexpanderWrite(expanderAddr, state);
DEBUG_PRINT(F("Writing to PCF8574: ")); DEBUG_PRINTLN(state);
} else if (expanderType == EXPANDER_AW9523 && _relay[relay].pin >= 100) {
// shadow register lets us switch a single port without touching the others
uint8_t port = _relay[relay].pin - 100;
bitWrite(awOutputState, port, _relay[relay].invert ? !mode : mode);
awRegWrite16(AW9523_REG_OUT0, awOutputState);
DEBUG_PRINT(F("Writing to AW9523: ")); DEBUG_PRINTLN(awOutputState);
} else if (_relay[relay].pin < 100) {
pinMode(_relay[relay].pin, OUTPUT);
digitalWrite(_relay[relay].pin, _relay[relay].invert ? !_relay[relay].state : _relay[relay].state);
} else return;
publishMqtt(relay);
}
uint8_t PowerManager::getActiveRelayCount() {
uint8_t count = 0;
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) if (_relay[i].pin>=0) count++;
return count;
}
/**
* couple/decouple a relay to a segment (-1 = none, 0..n = segment id).
* persist=false applies the link without writing cfg.json - used by preset-carried links
* ("save":false) so switching presets does not wear flash; the configured links then
* remain the boot baseline. The Master AC relay role (segment 99) is configured via
* settings only, not via this API.
*/
void PowerManager::setSegmentLink(uint8_t relay, int seg, bool persist) {
if (relay >= POWERMANAGER_MAX_RELAYS) return;
if (relay == 0 && masterEnabled) return; // Master AC relay is not re-linkable
if (seg < -1 || seg >= (int)strip.getMaxSegments()) seg = -1;
if (_relay[relay].segment == seg) return;
_relay[relay].segment = seg;
_relay[relay].segSeen = false;
_relay[relay].boPhase = BO_NONE;
_pendingSince[relay] = 0;
if (seg >= 0) _relay[relay].external = false; // coupled relays are exclusively segment-driven
// "Take over all relays": an unlinked relay has no role anymore and must not stay powered.
// Without it the relay keeps its state until the next main power toggle (default behavior:
// relays without a role are not touched); handleSegmentCoupling() skips uncoupled relays,
// so this is the only place a menu/API unlink can switch the relay off.
else if (takeOverRelays && _relay[relay].state) switchRelay(relay, false);
if (persist) configNeedsWrite = true; // persist to cfg.json (written from main loop)
}
//Functions called by WLED
#ifndef WLED_DISABLE_MQTT
/**
* handling of MQTT message
* topic only contains stripped topic (part after /wled/MAC)
* topic should look like: /relay/X/command; where X is relay number, 0 based
*/
bool PowerManager::onMqttMessage(char* topic, char* payload) {
if (strlen(topic) > 8 && strncmp_P(topic, PSTR("/relay/"), 7) == 0) {
char *numEnd;
uint8_t relay = strtoul(topic+7, &numEnd, 10);
// relay number may have more than one digit; "/command" must directly follow it
if (numEnd != topic+7 && strcmp_P(numEnd, _Command) == 0 && relay<POWERMANAGER_MAX_RELAYS) {
String action = payload;
if (action == "on") {
if (_relay[relay].external) switchRelay(relay, true);
return true;
} else if (action == "off") {
if (_relay[relay].external) switchRelay(relay, false);
return true;
} else if (action == FPSTR(_toggle)) {
if (_relay[relay].external) toggleRelay(relay);
return true;
}
}
}
return false;
}
/**
* subscribe to MQTT topic for controlling relays
*/
void PowerManager::onMqttConnect(bool sessionPresent) {
//(re)subscribe to required topics
char subuf[64];
if (mqttDeviceTopic[0] != 0) {
strcpy(subuf, mqttDeviceTopic);
strcat_P(subuf, PSTR("/relay/#"));
mqtt->subscribe(subuf, 0);
if (HAautodiscovery) publishHomeAssistantAutodiscovery();
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
if (_relay[i].pin<0) continue;
publishMqtt(i); //publish current state
}
}
}
void PowerManager::publishHomeAssistantAutodiscovery() {
for (int i = 0; i < POWERMANAGER_MAX_RELAYS; i++) {
char uid[24], json_str[1024], buf[128];
size_t payload_size;
sprintf_P(uid, PSTR("%s_sw%d"), escapedMac.c_str(), i);
if (_relay[i].pin >= 0 && _relay[i].external) {
StaticJsonDocument<1024> json;
if (_relay[i].name[0]) sprintf_P(buf, PSTR("%s %s"), serverDescription, _relay[i].name); //max length: 33 + 1 + 32 = 66
else sprintf_P(buf, PSTR("%s Switch %d"), serverDescription, i); //max length: 33 + 8 + 3 = 44
json[F("name")] = buf;
sprintf_P(buf, PSTR("%s/relay/%d"), mqttDeviceTopic, i); //max length: 33 + 7 + 3 = 43
json["~"] = buf;
strcat_P(buf, _Command);
mqtt->subscribe(buf, 0);
json[F("stat_t")] = "~";
json[F("cmd_t")] = F("~/command");
json[F("pl_off")] = "off";
json[F("pl_on")] = "on";
json[F("uniq_id")] = uid;
strcpy(buf, mqttDeviceTopic); //max length: 33 + 7 = 40
strcat_P(buf, PSTR("/status"));
json[F("avty_t")] = buf;
json[F("pl_avail")] = F("online");
json[F("pl_not_avail")] = F("offline");
//TODO: dev
payload_size = serializeJson(json, json_str);
} else {
//Unpublish disabled or internal relays
json_str[0] = 0;
payload_size = 0;
}
sprintf_P(buf, PSTR("homeassistant/switch/%s/config"), uid);
mqtt->publish(buf, 0, true, json_str, payload_size);
}
}
#endif
/**
* setup() is called once at boot. WiFi is not yet connected at this point.
* You can use it to initialize variables, sensors or similar.
*/
void PowerManager::setup() {
// pins retrieved from cfg.json (readFromConfig()) prior to running setup()
// if we want an I2C port expander the I2C pins need to be valid
if (i2c_sda<0 || i2c_scl<0) expanderType = EXPANDER_NONE;
uint16_t state = 0; // desired expander output levels (invert applied)
uint16_t used = 0; // expander ports used by relays
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
if (isCoupled(i)) _relay[i].external = false; // coupled relays are exclusively segment-driven
// coupled relays boot in Off state; handleSegmentCoupling() syncs them once segments are up
if (_relay[i].pin >= 100) {
uint8_t port = _relay[i].pin - 100;
if (expanderType == EXPANDER_NONE || port >= expanderPortCount()) {
_relay[i].pin = -1; // no expander configured or port out of range
continue;
}
if (!_relay[i].external && !isCoupled(i)) _relay[i].state = takeOverRelays ? false : !offMode;
state |= (uint16_t)(_relay[i].invert ? !_relay[i].state : _relay[i].state) << port;
used |= (uint16_t)1 << port;
} else if (_relay[i].pin>=0) {
// UM_MultiRelay is the closest core PinOwner; the enum cannot be extended by external usermods
if (PinManager::allocatePin(_relay[i].pin,true, PinOwner::UM_MultiRelay)) {
if (!_relay[i].external && !isCoupled(i)) _relay[i].state = takeOverRelays ? false : !offMode;
switchRelay(i, _relay[i].state);
_relay[i].active = false;
} else {
_relay[i].pin = -1; // allocation failed
}
}
}
if (expanderType == EXPANDER_PCF8574) {
IOexpanderWrite(expanderAddr, (uint8_t)state); // init expander (set all outputs)
DEBUG_PRINTLN(F("PCF8574 inited."));
} else if (expanderType == EXPANDER_AW9523) {
initAW9523(state, used);
}
_oldMode = offMode;
initDone = true;
}
/**
* loop() is called continuously. Here you can check for events, read sensors, etc.
*/
void PowerManager::loop() {
static unsigned long lastUpdate = 0;
yield();
if (!enabled) return;
handleBlackout(); // ms-precision power-on sequencing for coupled relays (cheap, runs every pass)
if (strip.isUpdating() && millis() - lastUpdate < 100) return;
if (millis() - lastUpdate < 100) return; // update only 10 times/s
lastUpdate = millis();
//set relay when LEDs turn on
if (_oldMode != offMode) {
_oldMode = offMode;
_switchTimerStart = millis();
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
// with "take over all relays", unconfigured relays do not follow main power (stay off)
if ((_relay[i].pin>=0) && !_relay[i].external && !isCoupled(i) && !takeOverRelays) _relay[i].active = true;
}
}
handleOffTimer();
handleSegmentCoupling();
}
// --------------------------------------------------------------------------------------------
// Segment coupling & power sequencing
//
// A relay with `segment` >= 0 is exclusively segment-driven: on while its segment is on (or,
// for POWERMANAGER_SEG_ANY master relays, while any segment is on) and global power is on.
//
// Power-off: segment off -> wait for its fade-out to finish -> wait delay-off-s -> port off
// (whichever ends later; toggling the segment back on cancels the pending cut).
// Power-on: segment on -> delay-on-s -> min-off-ms since the last cut -> PSU stabilization
// of master relays -> blackout sequence, advanced per loop pass by handleBlackout():
// BO_PRE: handleOverlayDraw() paints the segment black every frame, port still off
// BO_POST: port energised while the incoming data is black; stays black over the power ramp
// (a master relay additionally holds all-black for stabilize-s so the PSU settles)
// BO_FADE: transitions are force-completed so a stale one (e.g. armed by a global power
// toggle, with a non-black "from" state) cannot corrupt the restart; one serviced
// frame later restartSegmentFade() fades the segment up from black
// --------------------------------------------------------------------------------------------
/**
* is any segment the relay is coupled to still running a transition (fade)?
*/
bool PowerManager::isSegFading(uint8_t r) {
bool fading = false;
forOwnedSegments(r, [&fading](Segment &seg) { fading |= seg.isInTransition(); });
return fading;
}
/**
* force any running transition on the relay's segment(s) to complete (duration 0);
* it is destroyed on the next serviced frame
*/
void PowerManager::cancelSegTransitions(uint8_t r) {
forOwnedSegments(r, [](Segment &seg) { seg.startTransition(0); });
}
// restart a segment's fade from black: with `on` temporarily false, startTransition()
// re-captures a running fade-up's "from" brightness as ~0 and restarts its timer, or
// starts a fresh transition from 0 if there is none
static void fadeFromBlack(Segment &seg) {
seg.on = false;
seg.startTransition(strip.getTransition(), blendingStyle != TRANSITION_FADE);
seg.on = true;
}
/**
* restart the fade-up of the relay's segment(s) from black. WLED starts the fade the moment
* a segment is switched on, so by the time delay-on-s and the blackout have passed it may
* have partly or fully elapsed and the LEDs would snap on - restarting it here makes the
* full fade visible once power is ready.
*/
void PowerManager::restartSegmentFade(uint8_t r) {
bool restarted = false;
forOwnedSegments(r, [&restarted](Segment &seg) {
if (seg.on) { fadeFromBlack(seg); restarted = true; }
});
if (!restarted) return;
if (strip.getTransition()) {
// handleTransitions() force-ends ALL segment transitions (setTransitionMode(false)) when the
// global transition window - started at the original on-click - expires. Re-open it so it
// outlives the restarted fade, otherwise the fade's tail gets chopped (visible brightness
// pop). If a global brightness ramp is in flight (main power on), re-anchor it at its current
// level first: resetting the timer alone rewinds briT and causes a visible dip. This is the
// same re-anchoring stateUpdated() does for changes arriving mid-transition.
briOld = briT;
transitionStartTime = millis();
transitionActive = true;
}
strip.trigger(); // rendering may have gone idle during a long hold (PSU stabilization)
}
/**
* is an "any segment" master relay (PSU trigger) either still off (its own power-on pending)
* or within the stabilization window? Dependent segment-coupled relays postpone their power-on
* until this clears, giving the power supply time to come up and settle before sections draw
* load. Only applies when a stabilization time is configured.
*/
bool PowerManager::masterHoldsOn() {
if (stabilizeSec == 0) return false;
unsigned long now = millis();
for (int m=0; m<POWERMANAGER_MAX_RELAYS; m++) {
if (_relay[m].pin < 0 || _relay[m].segment != POWERMANAGER_SEG_ANY) continue;
if (!_relay[m].state) return true; // master not on yet (its own power-on sequence is pending)
if (now - _onAt[m] < (uint32_t)stabilizeSec * 1000) return true; // still stabilizing
}
return false;
}
/**
* is any specific-segment coupled relay still switched on? An "any segment" master must be
* the last to cut power: the sections it feeds may have longer off-delays than the master.
*/
bool PowerManager::dependentsStillOn() {
for (int i=0; i<POWERMANAGER_MAX_RELAYS; i++) {
if (_relay[i].pin >= 0 && isCoupled(i) && _relay[i].segment != POWERMANAGER_SEG_ANY && _relay[i].state) return true;
}
return false;
}
/**
* enter BO_FADE: force-complete stale transitions now, restart the fade one frame later
*/
void PowerManager::beginFadePhase(uint8_t r) {
_relay[r].boPhase = BO_FADE;
_boStart[r] = millis();
cancelSegTransitions(r);
strip.trigger(); // the next serviced frame destroys the cancelled transition(s)