-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathledchaincomm.cpp
1685 lines (1489 loc) · 54.5 KB
/
ledchaincomm.cpp
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
// SPDX-License-Identifier: GPL-3.0-or-later
//
// Copyright (c) 2016-2023 plan44.ch / Lukas Zeller, Zurich, Switzerland
//
// Author: Lukas Zeller <luz@plan44.ch>
//
// This file is part of p44utils.
//
// p44utils is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// p44utils is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with p44utils. If not, see <http://www.gnu.org/licenses/>.
//
// File scope debugging options
// - Set ALWAYS_DEBUG to 1 to enable DBGLOG output even in non-DEBUG builds of this file
#define ALWAYS_DEBUG 0
// - set FOCUSLOGLEVEL to non-zero log level (usually, 5,6, or 7==LOG_DEBUG) to get focus (extensive logging) for this file
// Note: must be before including "logger.hpp" (or anything that includes "logger.hpp")
#define FOCUSLOGLEVEL 0
#include "ledchaincomm.hpp"
#if ENABLE_APPLICATION_SUPPORT
#include "application.hpp"
#include "p44script.hpp"
#endif
#include <math.h>
using namespace p44;
// MARK: - LEDPowerConverter
#define LEDCHAIN_DEFAULT_EXP 4 // the default exponent for the power translation
void LEDPowerConverter::createExpTable(int aTableNo, double aExponent, LEDChannelPower aMinPower)
{
mTables[aTableNo] = new LEDPowerTable;
mTables[aTableNo]->mData[0] = 0; // always 0
// find min power from the curve at brightness 1
LEDChannelPower bri1pwr = round(PWMMAX*((exp((1*aExponent)/PIXELMAX)-1)/(exp(aExponent)-1)));
int offs = aMinPower>0 ? aMinPower-bri1pwr : 0; // offset
// now calculate
for (int b=1; b<=PIXELMAX; b++) {
int pwr = 0;
if (aExponent!=0) pwr = offs+round((PWMMAX-offs)*((exp((b*aExponent)/PIXELMAX)-1)/(exp(aExponent)-1)));
mTables[aTableNo]->mData[b] = pwr>0 ? pwr : 0;
}
}
LEDPowerConverter::LEDPowerConverter(double aExponent, LEDChannelPower aMinPower)
{
createExpTable(0, aExponent, aMinPower);
// use same table for all channels
mRedPowers = mTables[0]->mData;
mGreenPowers = mTables[0]->mData;
mBluePowers = mTables[0]->mData;
mWhitePowers = mTables[0]->mData;
}
LEDPowerConverter::LEDPowerConverter(double aColorExponent, LEDChannelPower aMinRedPower, LEDChannelPower aMinGreenPower, LEDChannelPower aMinBluePower, LEDChannelPower aMinWhitePower)
{
createExpTable(0, aColorExponent, aMinRedPower);
createExpTable(1, aColorExponent, aMinGreenPower);
createExpTable(2, aColorExponent, aMinBluePower);
createExpTable(3, aColorExponent, aMinWhitePower);
// use separate table for each channel
mRedPowers = mTables[0]->mData;
mGreenPowers = mTables[1]->mData;
mBluePowers = mTables[2]->mData;
mWhitePowers = mTables[3]->mData;
}
LEDPowerConverter::LEDPowerConverter(double aColorExponent, LEDChannelPower aMinColorPower, double aWhiteExponent, LEDChannelPower aMinWhitePower)
{
// common table for RGB
createExpTable(0, aColorExponent, aMinColorPower);
mRedPowers = mTables[0]->mData;
mGreenPowers = mTables[0]->mData;
mBluePowers = mTables[0]->mData;
// separate table for white
createExpTable(1, aWhiteExponent, aMinWhitePower);
mWhitePowers = mTables[1]->mData;
}
LEDPowerConverter::~LEDPowerConverter()
{
}
static LEDPowerConverterPtr gStandardPowerConverter;
LEDPowerConverter& LEDPowerConverter::standardPowerConverter()
{
if (!gStandardPowerConverter) {
gStandardPowerConverter = new LEDPowerConverter(LEDCHAIN_DEFAULT_EXP, 0);
}
return *gStandardPowerConverter;
}
void LEDPowerConverter::powersForComponents(
PixelColorComponent aDimDown,
PixelColorComponent aRed, PixelColorComponent aGreen, PixelColorComponent aBlue, PixelColorComponent aWhite,
LEDChannelPower& aRedPwr, LEDChannelPower& aGreenPwr, LEDChannelPower& aBluePwr, LEDChannelPower& aWhitePwr
) const
{
if (aDimDown) {
uint32_t f = (uint16_t)aDimDown+1;
aRedPwr = (f*mRedPowers[aRed]) >> 8;
aGreenPwr = (f*mRedPowers[aGreen]) >> 8;
aBluePwr = (f*mRedPowers[aBlue]) >> 8;
aWhitePwr = (f*mRedPowers[aWhite]) >> 8;
}
else {
aRedPwr = mRedPowers[aRed];
aGreenPwr = mRedPowers[aGreen];
aBluePwr = mRedPowers[aBlue];
aWhitePwr = mRedPowers[aWhite];
}
}
// MARK: - LedChainComm
#if ENABLE_RPIWS281X
#define TARGET_FREQ WS2811_TARGET_FREQ // in Hz, default is 800kHz
#define GPIO_DEFAULT_PIN 18 // P1 Pin 12, GPIO 18 (PCM_CLK)
#define DMA 5 // don't change unless you know why
#define MAX_BRIGHTNESS 255 // full brightness range
#endif
// Power consumption according to
// https://www.thesmarthomehookup.com/the-complete-guide-to-selecting-individually-addressable-led-strips/
static const LEDChainComm::LedChipDesc ledChipDescriptors[LEDChainComm::num_ledchips] = {
{ "none", 0, 0, 0, 1, false },
{ "WS2811", 8, 64, 0, 1, false },
{ "WS2812", 4, 60, 0, 1, false },
{ "WS2813", 4, 85, 0, 1, false },
{ "WS2815", 24, 120, 0, 1, true },
{ "P9823", 8, 80, 0, 1, false }, // no real data, rough assumption
{ "SK6812", 6, 50, 95, 1, false },
{ "WS2816", 4, 85, 0, 2, false } // no real data, assume same as WS2813
};
static const char* ledLayoutNames[LEDChainComm::num_ledlayouts] = {
"none",
"RGB",
"GRB",
"RGBW",
"GRBW",
// new since 2022-11-23
"RBG",
"GBR",
"BRG",
"BGR",
"RBGW",
"GBRW",
"BRGW",
"BGRW",
};
LEDChainComm::LEDChainComm(
const string aLedType,
const string aDeviceName,
uint16_t aNumLeds,
uint16_t aLedsPerRow,
bool aXReversed,
bool aAlternating,
bool aXYSwap,
bool aYReversed,
uint16_t aInactiveStartLeds,
uint16_t aInactiveBetweenLeds,
uint16_t aInactiveEndLeds
) :
mInitialized(false)
#ifdef ESP_PLATFORM
,gpioNo(18) // sensible default
,pixels(NULL)
#elif ENABLE_RPIWS281X
#else
,ledFd(-1)
,rawBuffer(NULL)
,ledBuffer(NULL)
,rawBytes(0)
#endif
{
// set defaults
mLedChip = ledchip_none; // none defined yet
mLedLayout = ledlayout_none; // none defined yet
mTMaxPassive_uS = 0;
mMaxRetries = 0;
mNumColorComponents = 3;
mNumBytesPerComponent = 1;
// Parse led type string
// - check legacy type names
if (aLedType=="SK6812") {
mLedChip = ledchip_sk6812;
mLedLayout = ledlayout_grbw;
}
else if (aLedType=="P9823") {
mLedChip = ledchip_p9823;
mLedLayout = ledlayout_rgb;
}
else if (aLedType=="WS2815_RGB") {
mLedChip = ledchip_ws2815;
mLedLayout = ledlayout_rgb;
}
else if (aLedType=="WS2812") {
mLedChip = ledchip_ws2812;
mLedLayout = ledlayout_grb;
}
else if (aLedType=="WS2813") {
mLedChip = ledchip_ws2813;
mLedLayout = ledlayout_grb;
}
else {
// Modern led definitions
// <chip>.<layout>[.<TMaxPassive_uS>[.<maxRetries>]]
const char* cP = aLedType.c_str();
string part;
if (nextPart(cP, part, '.')) {
// chip
for (int i=0; i<num_ledchips; i++) { if (uequals(part, ledChipDescriptors[i].name)) { mLedChip = (LedChip)i; break; } };
}
if (nextPart(cP, part, '.')) {
// layout
for (int i=0; i<num_ledlayouts; i++) { if (uequals(part, ledLayoutNames[i])) { mLedLayout = (LedLayout)i; break; } };
}
if (nextPart(cP, part, '.')) {
// custom TPassive_max_nS
mTMaxPassive_uS = atoi(part.c_str());
}
if (nextPart(cP, part, '.')) {
// custom maxrepeat
mMaxRetries = atoi(part.c_str());
}
}
// device name/channel
mDeviceName = aDeviceName;
mNumColorComponents = ledChipDescriptors[mLedChip].whiteChannelMw>0 ? 4 : 3;
mNumBytesPerComponent = ledChipDescriptors[mLedChip].numBytesPerChannel;
mInactiveStartLeds = aInactiveStartLeds;
mInactiveBetweenLeds = aInactiveBetweenLeds;
mInactiveEndLeds = aInactiveEndLeds;
// number of LEDs
mNumLeds = aNumLeds;
if (aLedsPerRow==0) {
mLedsPerRow = aNumLeds-aInactiveStartLeds; // single row
mNumRows = 1;
}
else {
mLedsPerRow = aLedsPerRow; // set row size
mNumRows = (mNumLeds-1-mInactiveStartLeds-mInactiveEndLeds)/(mLedsPerRow+mInactiveBetweenLeds)+1; // calculate number of (full or partial) rows
}
mXReversed = aXReversed;
mYReversed = aYReversed;
mAlternating = aAlternating;
mXYSwap = aXYSwap;
// make sure operation ends when mainloop terminates
MainLoop::currentMainLoop().registerCleanupHandler(boost::bind(&LEDChainComm::end, this));
}
LEDChainComm::~LEDChainComm()
{
// end the operation when object gets deleted
end();
}
void LEDChainComm::setChainDriver(LEDChainCommPtr aLedChainComm)
{
mChainDriver = aLedChainComm;
}
void LEDChainComm::setPowerConverter(const LEDPowerConverterPtr aLedPowerConverter)
{
mLEDPowerConverter = aLedPowerConverter;
}
const LEDPowerConverter& LEDChainComm::powerConverter()
{
if (!mLEDPowerConverter) {
if (mChainDriver) {
mLEDPowerConverter = const_cast<LEDPowerConverter *>(&(mChainDriver->powerConverter())); // use the chain driver's converter
}
else {
mLEDPowerConverter = &LEDPowerConverter::standardPowerConverter(); // use the standard converter
}
}
return *mLEDPowerConverter.get();
}
const LEDChainComm::LedChipDesc &LEDChainComm::ledChipDescriptor() const
{
return ledChipDescriptors[mLedChip];
}
// MARK: - LEDChainComm physical LED chain driver
#ifdef ESP_PLATFORM
static bool gEsp32_ws281x_initialized = false;
#define ESP32_LEDCHAIN_MAX_RETRIES 3
#endif // CONFIG_P44UTILS_DIGITAL_LED_LIB
bool LEDChainComm::begin(size_t aHintAtTotalChains)
{
if (!mInitialized) {
if (mChainDriver) {
// another LED chain outputs to the hardware, make sure that one is up
mInitialized = mChainDriver->begin();
}
else {
#ifdef ESP_PLATFORM
#if PWMBITS!=8
#error "16-bit LEDs not yet implemented"
#endif
if (mDeviceName.substr(0,4)=="gpio") {
sscanf(mDeviceName.c_str()+4, "%d", &gpioNo);
}
// make sure library is initialized
if (!gEsp32_ws281x_initialized) {
FOCUSLOG("calling esp_ws281x_init for %d chains", aHintAtTotalChains);
esp_ws281x_init((int)aHintAtTotalChains);
gEsp32_ws281x_initialized = true;
}
// add this chain
// TODO: refactor low level driver to use separate chip/layout params, too
Esp_ws281x_LedType elt;
switch (mLedChip) {
case ledchip_ws2811:
case ledchip_ws2812:
elt = esp_ledtype_ws2812;
break;
case ledchip_sk6812:
elt = esp_ledtype_sk6812;
break;
case ledchip_p9823:
elt = esp_ledtype_p9823;
break;
case ledchip_ws2815:
if (mLedLayout==ledlayout_rgb) elt = esp_ledtype_ws2815_rgb;
else elt = esp_ledtype_ws2813;
break;
case ledchip_ws2813:
default:
elt = esp_ledtype_ws2813;
break;
}
espLedChain = esp_ws281x_newChain(elt, gpioNo, ESP32_LEDCHAIN_MAX_RETRIES);
if (espLedChain) {
// prepare buffer
if (pixels) {
delete[] pixels;
pixels = NULL;
}
pixels = new Esp_ws281x_pixel[mNumLeds];
mInitialized = true;
clear();
}
else {
LOG(LOG_ERR, "Error: esp_ws281x_newChain failed");
return false; // cannot initialize LED chain
}
#elif ENABLE_RPIWS281X
int gpio = GPIO_DEFAULT_PIN;
bool inverted = false;
size_t n=0;
if (mDeviceName.substr(n,1)=="!") {
inverted = true;
n++;
}
if (mDeviceName.substr(n,4)=="gpio") {
sscanf(mDeviceName.c_str()+4, "%d", &gpio);
}
// prepare hardware related stuff
memset(&mRPiWS281x, 0, sizeof(mRPiWS281x));
// initialize the led string structure
mRPiWS281x.freq = TARGET_FREQ;
mRPiWS281x.dmanum = DMA;
mRPiWS281x.device = NULL; // private data pointer for library
// channel 0
mRPiWS281x.channel[0].gpionum = gpio;
mRPiWS281x.channel[0].count = mNumLeds;
mRPiWS281x.channel[0].invert = inverted ? 1 : 0;
mRPiWS281x.channel[0].brightness = MAX_BRIGHTNESS;
// map chips/layouts
switch (mLedChip) {
case ledchip_sk6812: {
// 4 channel, "SK6812" in RPIWS281X lingo
switch (mLedLayout) {
default:
case ledlayout_rgbw: mRPiWS281x.channel[0].strip_type = SK6812_STRIP_RGBW; break;
case ledlayout_rbgw: mRPiWS281x.channel[0].strip_type = SK6812_STRIP_RBGW; break;
case ledlayout_grbw: mRPiWS281x.channel[0].strip_type = SK6812_STRIP_GRBW; break;
case ledlayout_gbrw: mRPiWS281x.channel[0].strip_type = SK6812_STRIP_GBRW; break;
case ledlayout_brgw: mRPiWS281x.channel[0].strip_type = SK6812_STRIP_BRGW; break;
case ledlayout_bgrw: mRPiWS281x.channel[0].strip_type = SK6812_STRIP_BGRW; break;
}
break;
}
default:
case ledchip_ws2811:
case ledchip_ws2812:
case ledchip_ws2813:
case ledchip_ws2815:
case ledchip_p9823: {
switch (mLedLayout) {
case ledlayout_rgb: mRPiWS281x.channel[0].strip_type = WS2811_STRIP_RGB; break;
case ledlayout_rbg: mRPiWS281x.channel[0].strip_type = WS2811_STRIP_RBG; break;
default:
case ledlayout_grb: mRPiWS281x.channel[0].strip_type = WS2811_STRIP_GRB; break;
case ledlayout_gbr: mRPiWS281x.channel[0].strip_type = WS2811_STRIP_GBR; break;
case ledlayout_brg: mRPiWS281x.channel[0].strip_type = WS2811_STRIP_BRG; break;
case ledlayout_bgr: mRPiWS281x.channel[0].strip_type = WS2811_STRIP_BGR; break;
}
break;
}
case ledchip_ws2816:
// FIXME: workaround, use two RGB (non-swapped) 8-bit for one 16-bit LED
mRPiWS281x.channel[0].count = mNumLeds*2;
mRPiWS281x.channel[0].strip_type = WS2811_STRIP_RGB;
break;
}
mRPiWS281x.channel[0].leds = NULL; // will be allocated by the library
// channel 1 - unused
mRPiWS281x.channel[1].gpionum = 0;
mRPiWS281x.channel[1].count = 0;
mRPiWS281x.channel[1].invert = 0;
mRPiWS281x.channel[1].brightness = MAX_BRIGHTNESS;
mRPiWS281x.channel[1].leds = NULL; // will be allocated by the library
// initialize library
ws2811_return_t ret = ws2811_init(&mRPiWS281x);
if (ret==WS2811_SUCCESS) {
mInitialized = true;
}
else {
LOG(LOG_ERR, "Error: ws281x init for GPIO%d failed: %s", gpio, ws2811_get_return_t_str(ret));
mInitialized = false;
}
#else
// Allocate led buffer
if (rawBuffer) {
delete[] rawBuffer;
rawBuffer = NULL;
ledBuffer = NULL;
rawBytes = 0;
}
if (mLedChip!=ledchip_none) {
const int hdrsize = 5; // v6 header size
rawBytes = mNumColorComponents*mNumBytesPerComponent*mNumLeds+1+hdrsize;
rawBuffer = new uint8_t[rawBytes];
ledBuffer = rawBuffer+1+hdrsize; // led data starts here
// prepare header for p44-ledchain v6 and later compatible drivers
rawBuffer[0] = hdrsize; // driver v6 header size
rawBuffer[1] = mLedLayout;
rawBuffer[2] = mLedChip;
rawBuffer[3] = (mTMaxPassive_uS>>8) & 0xFF;
rawBuffer[4] = (mTMaxPassive_uS) & 0xFF;
rawBuffer[5] = mMaxRetries;
}
else {
// chip not known here: must be legacy driver w/o header
rawBytes = mNumColorComponents*mNumBytesPerComponent*mNumLeds;
rawBuffer = new uint8_t[rawBytes];
ledBuffer = rawBuffer;
}
memset(ledBuffer, 0, mNumColorComponents*mNumBytesPerComponent*mNumLeds);
ledFd = open(mDeviceName.c_str(), O_RDWR);
if (ledFd>=0) {
mInitialized = true;
}
else {
LOG(LOG_ERR, "Error: Cannot open LED chain device '%s'", mDeviceName.c_str());
mInitialized = false;
}
#endif
}
}
return mInitialized;
}
void LEDChainComm::clear()
{
if (!mInitialized) return;
if (mChainDriver) {
// this is just a secondary mapping on a primary chain: clear only the actually mapped LEDs
for (uint16_t led = mInactiveStartLeds; led<mNumLeds-mInactiveEndLeds; led++) {
mChainDriver->setPower(led, 0, 0, 0, 0);
}
}
else {
// this is the master driver, clear the entire buffer
#ifdef ESP_PLATFORM
for (uint16_t i=0; i<mNumLeds; i++) pixels[i].num = 0;
#elif ENABLE_RPIWS281X
// FIXME: workaround, use two 8-bit for one 16-bit LED
for (uint16_t i=0; i<mNumLeds*mNumBytesPerComponent; i++) mRPiWS281x.channel[0].leds[i] = 0;
#else
memset(ledBuffer, 0, mNumColorComponents*mNumBytesPerComponent*mNumLeds);
#endif
}
}
void LEDChainComm::end()
{
if (mInitialized) {
if (!mChainDriver) {
#ifdef ESP_PLATFORM
if (pixels) {
delete[] pixels;
pixels = NULL;
}
esp_ws281x_freeChain(espLedChain);
espLedChain = NULL;
#elif ENABLE_RPIWS281X
// deinitialize library
ws2811_fini(&mRPiWS281x);
#else
if (rawBuffer) {
delete[] rawBuffer;
rawBuffer = NULL;
ledBuffer = NULL;
rawBytes = 0;
}
if (ledFd>=0) {
close(ledFd);
ledFd = -1;
}
#endif
}
}
mInitialized = false;
}
void LEDChainComm::show()
{
if (!mChainDriver) {
// Note: no operation if this is only a secondary mapping - primary driver will update the hardware
if (!mInitialized) return;
#ifdef ESP_PLATFORM
esp_ws281x_setColors(espLedChain, mNumLeds, pixels);
#elif ENABLE_RPIWS281X
ws2811_render(&mRPiWS281x);
#else
write(ledFd, rawBuffer, rawBytes); // with header
#endif
}
}
#if LEDCHAIN_LEGACY_API && PWMBITS==8
void LEDChainComm::setColorAtLedIndex(uint16_t aLedIndex, uint8_t aRed, uint8_t aGreen, uint8_t aBlue, uint8_t aWhite)
{
// get power (PWM values)
uint8_t r = pwmtable[aRed];
uint8_t g = pwmtable[aGreen];
uint8_t b = pwmtable[aBlue];
uint8_t w = pwmtable[aWhite];
setPowerAtLedIndex(aLedIndex, r, g, b, w);
}
#if LEDCHAIN_READBACK
void LEDChainComm::getColorAtLedIndex(uint16_t aLedIndex, uint8_t &aRed, uint8_t &aGreen, uint8_t &aBlue, uint8_t &aWhite)
{
uint8_t r,g,b,w;
getPowerAtLedIndex(aLedIndex, r, g, b, w);
aRed = brightnesstable[r];
aGreen = brightnesstable[g];
aBlue = brightnesstable[b];
aWhite = brightnesstable[w];
}
#endif // LEDCHAIN_READBACK
#endif // LEDCHAIN_LEGACY_API && PWMBITS==8
#if PWMBITS==8
static uint8_t pwmTo8Bits(LEDChannelPower aPWM)
{
return aPWM;
}
#else
uint8_t pwmTo8Bits(LEDChannelPower aPWM)
{
if (aPWM>=0xFF80) return 0xFF;
return ((aPWM+0x66)>>8); // 0x66 empirically determined, least rounding errors compared with real 8bit table
}
#endif
void LEDChainComm::setPowerAtLedIndex(uint16_t aLedIndex, LEDChannelPower aRed, LEDChannelPower aGreen, LEDChannelPower aBlue, LEDChannelPower aWhite)
{
if (mChainDriver) {
// delegate actual output
mChainDriver->setPowerAtLedIndex(aLedIndex, aRed, aGreen, aBlue, aWhite);
}
else {
// local driver, store change in my own LED buffer
if (aLedIndex>=mNumLeds) return;
#ifdef ESP_PLATFORM
#if PWMBITS!=8
#error "16-bit LEDs not yet implemented"
#endif
if (!pixels) return;
pixels[aLedIndex] = esp_ws281x_makeRGBVal(aRed, aGreen, aBlue, aWhite);
#elif ENABLE_RPIWS281X
#if PWMBITS!=16
#error "implementation is for 16-bit PWM only"
#endif
if (mNumBytesPerComponent>1) {
// FIXME: workaround, only works with GRB WS2816 for now
// spread over 2 leds
aLedIndex<<1;
// - G-MSB, G-LSB, R-MSB
ws2811_led_t pixel =
((uint32_t)((uint8_t)(aGreen>>8)) << 16) |
((uint32_t)((uint8_t)(aGreen&0xFF)) << 8) |
((uint32_t)((uint8_t)(aRed>>8)));
mRPiWS281x.channel[0].leds[aLedIndex++] = pixel;
// - R-LSB, B-MSB, B-LSB
pixel =
((uint32_t)((uint8_t)(aRed&0xFF)) << 16) |
((uint32_t)((uint8_t)(aBlue>>8)) << 8) |
((uint32_t)((uint8_t)(aBlue&0xFF)));
mRPiWS281x.channel[0].leds[aLedIndex] = pixel;
}
else {
// 8-bit LEDs
ws2811_led_t pixel =
((uint32_t)pwmTo8Bits(aRed) << 16) |
((uint32_t)pwmTo8Bits(aGreen) << 8) |
((uint32_t)pwmTo8Bits(aBlue));
if (mNumColorComponents>3) {
pixel |= ((uint32_t)pwmTo8Bits(aWhite) << 24);
}
mRPiWS281x.channel[0].leds[aLedIndex] = pixel;
}
#else
#if PWMBITS!=16
#error "implementation is for 16-bit PWM only"
#endif
int byteindex = mNumColorComponents*aLedIndex;
if (mNumBytesPerComponent>1) {
// 16 bit
byteindex = byteindex<<1; // double number of bytes
ledBuffer[byteindex++] = aRed>>8;
ledBuffer[byteindex++] = aRed & 0xFF;
ledBuffer[byteindex++] = aGreen>>8;
ledBuffer[byteindex++] = aGreen & 0xFF;
ledBuffer[byteindex++] = aBlue>>8;
ledBuffer[byteindex++] = aBlue & 0xFF;
if (mNumColorComponents>3) {
ledBuffer[byteindex++] = aWhite>>8;
ledBuffer[byteindex++] = aWhite & 0xFF;
}
}
else {
// 8bit, send MSB only
ledBuffer[byteindex++] = pwmTo8Bits(aRed);
ledBuffer[byteindex++] = pwmTo8Bits(aGreen);
ledBuffer[byteindex++] = pwmTo8Bits(aBlue);
if (mNumColorComponents>3) {
ledBuffer[byteindex++] = pwmTo8Bits(aWhite);
}
}
#endif
}
}
#if LEDCHAIN_READBACK
void LEDChainComm::getPowerAtLedIndex(uint16_t aLedIndex, LEDChannelPower &aRed, LEDChannelPower &aGreen, LEDChannelPower &aBlue, LEDChannelPower &aWhite)
{
if (mChainDriver) {
// delegate actual output
mChainDriver->getPowerAtLedIndex(aLedIndex, aRed, aGreen, aBlue, aWhite);
}
else {
if (aLedIndex>=mNumLeds) return;
#ifdef ESP_PLATFORM
#if PWMBITS!=8
#error "16-bit LEDs not yet implemented"
#endif
if (!pixels) return;
Esp_ws281x_pixel &pixel = pixels[aLedIndex];
aRed = pixel.r;
aGreen = pixel.g;
aBlue = pixel.b;
aWhite = pixel.w;
#elif ENABLE_RPIWS281X
#if PWMBITS!=16
#error "implementation is for 16-bit PWM only"
#endif
if (mNumBytesPerComponent>1) {
// FIXME: workaround, only works with GRB WS2816 for now
// spread over 2 leds
aLedIndex<<1;
// - G-MSB, G-LSB, R-MSB
ws2811_led_t pixel1 = mRPiWS281x.channel[0].leds[aLedIndex];
// - R-LSB, B-MSB, B-LSB
ws2811_led_t pixel2 = mRPiWS281x.channel[1].leds[aLedIndex];
aGreen = ((pixel1>>8) & 0xFFFF);
aRed = ((pixel1<<8) & 0xFF00) + ((pixel2>>16) & 0xFF);
aBlue = (pixel2 & 0xFFFF);
}
else {
// 8-bit LED
ws2811_led_t pixel = mRPiWS281x.channel[0].leds[aLedIndex];
aRed = pwmFrom8Bits((pixel>>16) & 0xFF);
aGreen = pwmFrom8Bits((pixel>>8) & 0xFF);
aBlue = pwmFrom8Bits(pixel & 0xFF);
if (mNumColorComponents>3) {
aWhite = pwmFrom8Bits((pixel>>24) & 0xFF);
}
else {
aWhite = 0;
}
}
#else
#if PWMBITS!=16
#error "implementation is for 16-bit PWM only"
#endif
int byteindex = mNumColorComponents*aLedIndex;
if (mNumBytesPerComponent>1) {
// 16-bit
byteindex = byteindex<<1;
aRed = ((LEDChannelPower)ledBuffer[byteindex++]<<8);
aRed |= ledBuffer[byteindex++];
aGreen = ((LEDChannelPower)ledBuffer[byteindex++]<<8);
aGreen |= ledBuffer[byteindex++];
aBlue = ((LEDChannelPower)ledBuffer[byteindex++]<<8);
aBlue |= ledBuffer[byteindex++];
if (mNumColorComponents>3) {
aWhite = ((LEDChannelPower)ledBuffer[byteindex++]<<8);
aWhite |= ledBuffer[byteindex++];
}
}
else {
// 8-bit
aRed = pwmFrom8Bits((LEDChannelPower)ledBuffer[byteindex++]);
aGreen = pwmFrom8Bits((LEDChannelPower)ledBuffer[byteindex++]);
aBlue = pwmFrom8Bits((LEDChannelPower)ledBuffer[byteindex++]);
if (mNumColorComponents>3) {
aWhite = pwmFrom8Bits((LEDChannelPower)ledBuffer[byteindex++]);
}
else {
aWhite = 0;
}
}
#endif
}
}
#endif // LEDCHAIN_READBACK
// MARK: - LEDChainComm logical LED access
uint16_t LEDChainComm::getNumLeds()
{
return mNumLeds-mInactiveStartLeds-mInactiveEndLeds-(mNumRows-1)*mInactiveBetweenLeds;
}
uint16_t LEDChainComm::getSizeX()
{
return mXYSwap ? mNumRows : mLedsPerRow;
}
uint16_t LEDChainComm::getSizeY()
{
return mXYSwap ? mLedsPerRow : mNumRows;
}
PixelColorComponent LEDChainComm::getMinVisibleColorIntensity()
{
// return highest brightness that still produces lowest non-zero output.
// TODO: maybe find more accurate way to detect lowest visible brightness
return 1;
}
uint16_t LEDChainComm::ledIndexFromXY(uint16_t aX, uint16_t aY)
{
//FOCUSLOG("ledIndexFromXY: X=%d, Y=%d", aX, aY);
if (mXYSwap) { uint16_t tmp = aY; aY = aX; aX = tmp; }
if (mYReversed) { aY = mNumRows-1-aY; }
uint16_t ledindex = aY*(mLedsPerRow+mInactiveBetweenLeds);
bool reversed = mXReversed;
if (mAlternating) {
if (aY & 0x1) reversed = !reversed;
}
if (reversed) {
ledindex += (mLedsPerRow-1-aX);
}
else {
ledindex += aX;
}
//FOCUSLOG("--> ledIndex=%d", ledindex);
return ledindex+mInactiveStartLeds;
}
#if LEDCHAIN_LEGACY_API && PWMBITS==8
void LEDChainComm::setColorXY(uint16_t aX, uint16_t aY, uint8_t aRed, uint8_t aGreen, uint8_t aBlue, uint8_t aWhite)
{
uint16_t ledindex = ledIndexFromXY(aX,aY);
setColorAtLedIndex(ledindex, aRed, aGreen, aBlue, aWhite);
}
void LEDChainComm::setColor(uint16_t aLedNumber, uint8_t aRed, uint8_t aGreen, uint8_t aBlue, uint8_t aWhite)
{
//FOCUSLOG("setColor: ledNumber=%d - sizeX=%d, sizeY=%d", aLedNumber, getSizeX(), getSizeY());
int y = aLedNumber / getSizeX();
int x = aLedNumber % getSizeX();
setColorXY(x, y, aRed, aGreen, aBlue, aWhite);
}
void LEDChainComm::setColorDimmedXY(uint16_t aX, uint16_t aY, uint8_t aRed, uint8_t aGreen, uint8_t aBlue, uint8_t aWhite, uint8_t aBrightness)
{
setColorXY(aX, aY, (aRed*aBrightness)>>8, (aGreen*aBrightness)>>8, (aBlue*aBrightness)>>8, (aWhite*aBrightness)>>8);
}
void LEDChainComm::setColorDimmed(uint16_t aLedNumber, uint8_t aRed, uint8_t aGreen, uint8_t aBlue, uint8_t aWhite, uint8_t aBrightness)
{
int y = aLedNumber / getSizeX();
int x = aLedNumber % getSizeX();
setColorDimmedXY(x, y, aRed, aGreen, aBlue, aWhite, aBrightness);
}
#if LEDCHAIN_READBACK
void LEDChainComm::getColor(uint16_t aLedNumber, uint8_t &aRed, uint8_t &aGreen, uint8_t &aBlue, uint8_t &aWhite)
{
int y = aLedNumber / getSizeX();
int x = aLedNumber % getSizeX();
getColorXY(x, y, aRed, aGreen, aBlue, aWhite);
}
void LEDChainComm::getColorXY(uint16_t aX, uint16_t aY, uint8_t &aRed, uint8_t &aGreen, uint8_t &aBlue, uint8_t &aWhite)
{
uint16_t ledindex = ledIndexFromXY(aX,aY);
getColorAtLedIndex(ledindex, aRed, aGreen, aBlue, aWhite);
}
#endif // LEDCHAIN_READBACK
#endif // LEDCHAIN_LEGACY_API && PWMBITS==8
void LEDChainComm::setPowerXY(uint16_t aX, uint16_t aY, LEDChannelPower aRed, LEDChannelPower aGreen, LEDChannelPower aBlue, LEDChannelPower aWhite)
{
uint16_t ledindex = ledIndexFromXY(aX,aY);
setPowerAtLedIndex(ledindex, aRed, aGreen, aBlue, aWhite);
}
void LEDChainComm::setPower(uint16_t aLedNumber, LEDChannelPower aRed, LEDChannelPower aGreen, LEDChannelPower aBlue, LEDChannelPower aWhite)
{
int y = aLedNumber / getSizeX();
int x = aLedNumber % getSizeX();
setPowerXY(x, y, aRed, aGreen, aBlue, aWhite);
}
#if LEDCHAIN_READBACK
void LEDChainComm::getPowerXY(uint16_t aX, uint16_t aY, LEDChannelPower &aRed, LEDChannelPower &aGreen, LEDChannelPower &aBlue, LEDChannelPower &aWhite)
{
uint16_t ledindex = ledIndexFromXY(aX,aY);
getPowerAtLedIndex(ledindex, aRed, aGreen, aBlue, aWhite);
}
#endif
#if ENABLE_P44LRGRAPHICS
// MARK: - LEDChainArrangement
#if DEBUG
#define MAX_STEP_INTERVAL (10*Second) // run a step at least in this interval, even if view step() indicates no need to do so early
#define MAX_UPDATE_INTERVAL (10*Second) // send an update at least this often, even if no changes happen (LED refresh)
#else
#define MAX_STEP_INTERVAL (1*Second) // run a step at least in this interval, even if view step() indicates no need to do so early
#define MAX_UPDATE_INTERVAL (500*MilliSecond) // send an update at least this often, even if no changes happen (LED refresh)
#endif
#define DEFAULT_MIN_UPDATE_INTERVAL (15*MilliSecond) // do not send updates faster than this
#define DEFAULT_MAX_PRIORITY_INTERVAL (50*MilliSecond) // allow synchronizing prioritized timing for this timespan after the last LED refresh
#define MAX_SLOW_WARN_INTERVAL (10*Second) // how often (max) the timing violation detection will be logged
LEDChainArrangement::LEDChainArrangement() :
mStarted(false),
mCovers(zeroRect),
mPowerLimitMw(0),
mRequestedLightPowerMw(0),
mActualLightPowerMw(0),
mPowerLimited(false),
mLastUpdate(Never),
mMinUpdateInterval(DEFAULT_MIN_UPDATE_INTERVAL),
mMaxPriorityInterval(DEFAULT_MAX_PRIORITY_INTERVAL),
mSlowDetected(Never)
{
#if ENABLE_P44SCRIPT && ENABLE_P44LRGRAPHICS && ENABLE_VIEWCONFIG
// install p44script lookup providing "ledchain" global
// Note: assuming only ONE ledchain arrangement per application.
// TODO: Nothing currently prevents instantiating multiple, but makes no sense
p44::P44Script::StandardScriptingDomain::sharedDomain().registerMemberLookup(
new P44Script::LEDChainLookup(*this)
);
#endif // ENABLE_P44SCRIPT
}
LEDChainArrangement::~LEDChainArrangement()
{
end();
}
void LEDChainArrangement::clear()
{
for(LedChainVector::iterator pos = mLedChains.begin(); pos!=mLedChains.end(); ++pos) {
pos->ledChain->clear();
pos->ledChain->show();
}
}
void LEDChainArrangement::setRootView(P44ViewPtr aRootView)
{
if (mRootView) {
mRootView->setNeedUpdateCB(NoOP); // make sure previous rootview will not call back any more!
}
mRootView = aRootView;
mRootView->setDefaultLabel("rootview");
mRootView->setNeedUpdateCB(boost::bind(&LEDChainArrangement::externalUpdateRequest, this));
mRootView->setMinUpdateInterval(mMinUpdateInterval);
}
void LEDChainArrangement::setMinUpdateInterval(MLMicroSeconds aMinUpdateInterval)
{
mMinUpdateInterval = aMinUpdateInterval;
if (mRootView) mRootView->setMinUpdateInterval(mMinUpdateInterval);
}
void LEDChainArrangement::setMaxPriorityInterval(MLMicroSeconds aMaxPriorityInterval)
{
mMaxPriorityInterval = aMaxPriorityInterval;
}
#if ENABLE_P44LRGRAPHICS
#include "viewfactory.hpp"
#endif
void LEDChainArrangement::addLEDChain(LEDChainArrangementPtr &aLedChainArrangement, const string &aChainSpec)
{