This repository has been archived by the owner on Aug 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathKniwwelino.cpp
2311 lines (2028 loc) · 65.6 KB
/
Kniwwelino.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
/***************************************************
KniwwelinoLIB
Copyright (C) 2017 Luxembourg Institute of Science and Technology.
This program is free software: you can redistribute it and/or modify
it under the terms of the Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License.
Derived from Adafruit_LED_Backpack_Library library
Written by Limor Fried/Ladyada for Adafruit Industries.
****************************************************/
#include "Kniwwelino.h"
#include <Adafruit_NeoPixel.h>
#include "Adafruit_GFX.h"
#include <Fonts/TomThumb.h>
//-- DEBUG Helpers -------------
#ifdef DEBUG
#define DEBUG_PRINT(x) Kniwwelino.log (String(x))
#define DEBUG_PRINTLN(x) Kniwwelino.logln (String(x))
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#endif
//-- CALLBACK Helpers -------------
typedef void (*MQTTClientCallbackSimple)(String &topic, String &payload);
MQTTClientCallbackSimple mqttCallback = nullptr;
/*
* Lib Contructor. no need to call, as we provide a static Kniwwelino object instance
*
*/
KniwwelinoLib::KniwwelinoLib() : Adafruit_GFX(5, 5) {
RGB = Adafruit_NeoPixel(1, RGB_PIN, NEO_GRB + NEO_KHZ800);
}
/*
* begin - Initializes the Board hardware, Wifi and MQTT.
* MUST be called once in the setup routine to use the board.
*
* Wifi enabled
* Fastboot false
*/
void KniwwelinoLib::begin() {
begin(true, false);
}
/*
* begin - Initializes the Board hardware, Wifi and MQTT.
* MUST be called once in the setup routine to use the board.
*
* boolean enableWifi Enable Wifi and try to connecto to Wifi and MQTT
* boolean fast Startup faster without waiting for all scrolling texts.
* MQTT logging disabled
*/
void KniwwelinoLib::begin(boolean enableWifi, boolean fast) {
begin(enableWifi, fast, false);
}
/*
* begin - Initializes the Board hardware, Wifi and MQTT.
* MUST be called once in the setup routine to use the board.
*
* boolean enableWifi Enable Wifi and try to connecto to Wifi and MQTT
* boolean fast Startup faster without waiting for all scrolling texts.
* boolean mqttLog log debug messages to mqtt server
*/
void KniwwelinoLib::begin(boolean enableWifi, boolean fast, boolean mqttLog) {
begin(FW_VERSION, enableWifi, fast, mqttLog);
}
/*
* begin - Initializes the Board hardware, Wifi and MQTT.
* MUST be called once in the setup routine to use the board.
*
* const char nameStr[] name of the running program
* boolean enableWifi Enable Wifi and try to connecto to Wifi and MQTT
* boolean fast Startup faster without waiting for all scrolling texts.
* boolean mqttLog log debug messages to mqtt server
*/
void KniwwelinoLib::begin(const char nameStr[], boolean enableWifi, boolean fast, boolean mqttLog) {
unsigned long startTime = millis();
EEPROM.begin(512);
mqttLogEnabled = mqttLog;
Serial.begin(115200);
DEBUG_PRINTLN("=====================================================");
DEBUG_PRINT("\n");DEBUG_PRINT(getName());DEBUG_PRINT(" Reset:\"");DEBUG_PRINTLN(ESP.getResetReason());
DEBUG_PRINT(F("\" booting Sketch: "));DEBUG_PRINTLN(nameStr);
// init RGB LED
RGB.begin();
if (silent) {
RGB.setBrightness(1);
} else {
RGB.setBrightness(RGB_BRIGHTNESS);
RGBsetColorEffect(255, 0, 0, RGB_FLASH, 5);
}
DEBUG_PRINT(F(" RGB:On"));
// initialize I2C and LED Matrix Driver
Wire.begin();
Wire.beginTransmission(HT16K33_ADDRESS);
Wire.write(0x21); // turn on oscillator
Wire.endTransmission();
// init LED MATRIX
setTextWrap(false);
setFont(&TomThumb);
MATRIXsetBlinkRate(MATRIX_STATIC);
if (silent) {
MATRIXsetBrightness(0);
} else {
MATRIXsetBrightness(MATRIX_DEFAULT_BRIGHTNESS);
}
MATRIXclear();
// all on to start.
fillRect(0,0, 5, 5, 1);
DEBUG_PRINT(F(" MATRIX:On"));
// init variables with defaults
mqttTopicUpdate.replace(":","");
mqttTopicReqPwd.replace(":","");
mqttTopicLogEnabled.replace(":","");
mqttTopicSentPwd.replace(":","");
mqttTopicStatus.replace(":","");
strncpy(updateServer, DEF_UPDATESERVER, sizeof(DEF_UPDATESERVER));
strncpy(mqttServer, DEF_MQTTSERVER, sizeof(DEF_MQTTSERVER));
strncpy(mqttUser, DEF_MQTTUSER, sizeof(DEF_MQTTUSER));
strncpy(mqttPW, DEF_MQTTPW, sizeof(DEF_MQTTPW));
strncpy(fwVersion, nameStr, strlen(nameStr));
getName().toCharArray(nodename, getName().length());
DynamicJsonBuffer jsonBuffer;
myParameters = &jsonBuffer.createObject();
mqttGroup = DEF_MQTTBASETOPIC;
// BOOT: vars initialized
MATRIXsetStatus(0);
// attach base ticker for display and buttons
baseTicker.attach(TICK_FREQ, _baseTick);
_baseTick();
// BOOT: ticker running
MATRIXsetStatus(1);
Kniwwelino.RGBsetColorEffect(RGB_COLOR_CYAN, RGB_FLASH, RGB_FOREVER);
SPIFFS.begin();
// BOOT: filesystem mounted
MATRIXsetStatus(2);
// init Variables from stored config
DEBUG_PRINT(F(" Config:"));
String conf = Kniwwelino.FILEread(FILE_CONF);
yield();
if (conf.length() > 10) {
Kniwwelino.PLATFORMupdateConf(conf);
yield();
DEBUG_PRINT(F("OK "));
}
// BOOT: plattform config read
MATRIXsetStatus(3);
Kniwwelino.RGBclear();
// BOOT: All done but Wifi -> line 2
MATRIXsetStatus(4);
DEBUG_PRINT(F("MAC: "));DEBUG_PRINTLN(WiFi.macAddress());
unsigned long wifiStart = millis();
if (enableWifi) {
DEBUG_PRINT(F(" WIFI:"));
boolean wifiMgr = false;
// if button B is pressed -> Wifi Manager
if (Kniwwelino.BUTTONBdown()){
wifiMgr = true;
DEBUG_PRINTLN(F("Starting Wifimanager."));
} else if (Kniwwelino.BUTTONAdown()) {
// if button A is pressed -> Display ID
Kniwwelino.MATRIXshowID();
idShowing = true;
}
Kniwwelino.WIFIsetup(wifiMgr, fast, false);
DEBUG_PRINT(F("Wifi Logon took: "));DEBUG_PRINT((millis()-wifiStart));DEBUG_PRINTLN(F("ms"));
} else {
// save Energy
WiFi.mode(WIFI_OFF);
}
if (!(WiFi.status() == WL_CONNECTED)) {
wifiEnabled = false;
}
if (wifiEnabled) {
// BOOT: Wifi Established
MATRIXsetStatus(15);
// start mqtt
Kniwwelino.MQTTsetup(mqttServer, mqttPort, mqttUser, mqttPW);
// BOOT: MQTT Established
MATRIXsetStatus(16);
_initNTP();
// BOOT: MQTT Established
MATRIXsetStatus(17);
DEBUG_PRINT(F("Network Logon took: "));DEBUG_PRINT((millis()-wifiStart));DEBUG_PRINTLN(F("ms"));
}
// wait here for button b pressed if ID is showing
if (wifiEnabled && idShowing) {
// Store that we were in update Mode
updateMode = true;
EEPROM.write(EEPROM_ADR_UPDATE, updateMode);
EEPROM.commit();
// BOOT: Update Mode stored
MATRIXsetStatus(18);
_MQTTupdateStatus(true);
// BOOT: status updated
MATRIXsetStatus(19);
DEBUG_PRINT("Time: ");DEBUG_PRINTLN(getTime());
Kniwwelino.MATRIXshowID();
Kniwwelino.RGBsetColorEffect(RGB_COLOR_ORANGE, RGB_BLINK, RGB_FOREVER);
while (idShowing && !Kniwwelino.BUTTONBdown()) {
Kniwwelino.sleep(1000);
DEBUG_PRINTLN(F("Waiting for firmware download..."));
}
idShowing = false;
} else if (!updateMode){
// if we were in update Mode before the last Reset, stay in update mode.
updateMode = EEPROM.read(EEPROM_ADR_UPDATE);
if (ESP.getResetReason() == "Software/System restart" && updateMode) {
updateMode = true;
} else if (updateMode) {
updateMode = false;
EEPROM.write(EEPROM_ADR_UPDATE, updateMode);
EEPROM.commit();
}
}
// BOOT: nearly done
MATRIXsetStatus(20);
if (updateMode) {
DEBUG_PRINTLN(F("FWUpdate Mode: Active"));
}
MATRIXclear();
if (!silent) {
MATRIXwriteOnce("Kniwwelino");
}
DEBUG_PRINT("Boot took: ");DEBUG_PRINT((millis()-startTime));DEBUG_PRINT("ms Time: ");DEBUG_PRINTLN(getTime());
DEBUG_PRINTLN(F("=== WELCOME ====================================="));
if (enableWifi && !wifiEnabled) {
RGBsetColorEffect(STATE_ERR, RGB_BLINK, RGB_FOREVER);
} else if (!silent) {
RGBsetColorEffect(RGB_COLOR_GREEN, RGB_ON, 10);
}
RGB.setBrightness(RGB_BRIGHTNESS);
MATRIXsetBrightness(MATRIX_DEFAULT_BRIGHTNESS);
}
void KniwwelinoLib::setSilent() {
silent = true;
}
//==== Kniwwelino functions===================================================
/*
* returns the Kniwwelinos Device ID = last 6 digits of the WIFI MAC address
*/
String KniwwelinoLib::getID() {
String mac = WiFi.macAddress();
mac.replace(":","");
mac = mac.substring(6);
return mac;
}
/*
* returns the Kniwwelinos Device Name = Kniwwelino + last 6 digits of the WIFI MAC address
*/
String KniwwelinoLib::getName() {
return String(NAME_PREFIX)+"_"+getID();
}
/*
* returns the Kniwwelinos WIFI MAC address
*/
String KniwwelinoLib::getMAC() {
return WiFi.macAddress();
}
/*
* returns the Kniwwelinos WIFI IP address
* returns (0.0.0.0) if not connected
*/
String KniwwelinoLib::getIP() {
return WiFi.localIP().toString();
}
/*
* Checks the Kniwwelinos Wifi and MQTT connection.
* returns true if connected, false if not connected
*/
boolean KniwwelinoLib::isConnected() {
return ((WiFi.status() == WL_CONNECTED) && mqtt.connected());
}
void KniwwelinoLib::bgI2CStop() {
bgI2C=false;
}
void KniwwelinoLib::bgI2CStart() {
bgI2C=true;
}
/*
* Sleeps the current program for the given number of milli seconds.
* Use this one instead of arduino delay, as it handles Wifi and MQTT in the background.
*/
void KniwwelinoLib::sleep(unsigned long sleepMillis) {
yield();
if (sleepMillis < 100) {
delay(sleepMillis);
} else {
unsigned long till = millis() + sleepMillis;
while (till > millis()) {
yield();
if (mqttEnabled && mqtt.connected()) {
mqtt.loop();
}
sleepMillis = till - millis();
if (sleepMillis > 100) {
delay(100);
} else {
delay(sleepMillis);
}
}
}
}
/*
* internal loop that handles the mqtt connection and message handling.
* needs to be called regularly -> end of the Arduino loop method.
*/
void KniwwelinoLib::loop() {
yield();
if (mqttEnabled) {
if (!mqtt.connected()) {
MQTTconnect();
}
if (mqtt.connected()) {
mqtt.loop();
_MQTTupdateStatus(false);
}
}
}
/*
* internal ticker function that is called in the background.
* handles the update of LED, MAtrix and reads the buttons.
*/
void KniwwelinoLib::_baseTick() {
_tick++;
Kniwwelino._PINhandle();
Kniwwelino._RGBblink();
Kniwwelino._Buttonsread();
Kniwwelino._MATRIXupdate();
}
//==== logging =============================================================
void KniwwelinoLib::log (const String s) {
Serial.print (s);
if (mqttLogEnabled && mqttEnabled && mqtt.connected()) {
mqtt.publish(mqttTopicStatus + "/log", s);
}
}
void KniwwelinoLib::logln (const String s) {
Serial.println (s);
if (mqttLogEnabled && mqttEnabled && mqtt.connected()) {
mqtt.publish(mqttTopicStatus + "/log", s + "\n");
}
}
void KniwwelinoLib::log (const char s[]) {
Serial.print (s);
if (mqttLogEnabled && mqttEnabled && mqtt.connected()) {
mqtt.publish(mqttTopicStatus + "/log", s);
}
}
void KniwwelinoLib::logln (const char s[]) {
Serial.println (s);
if (mqttLogEnabled && mqttEnabled && mqtt.connected()) {
mqtt.publish(mqttTopicStatus + "/log", s);
}
}
/*
* internal function for EXTERNAL PIN button or LED blink/flash effects
*/
void KniwwelinoLib::_PINhandle() {
pinBlinkCount++;
if (pinBlinkCount > 10) {
pinBlinkCount = 1;
}
for (int i = 0; i < sizeof(ioPinNumers); i++) {
if (ioPinStatus[i] == PIN_UNUSED) {
continue;
}
// read external Button
if (ioPinStatus[i] == PIN_INPUT) {
if (!digitalRead(ioPinNumers[i])) ioPinclicked[i] = true;
continue;
}
// if Effect Time has passed, turn off Pin
if (ioPinStatus[i] == PIN_OFF) {
//DEBUG_PRINT("_PINblink ");DEBUG_PRINT(ioPinNumers[i]);DEBUG_PRINTLN(" LOW");
digitalWrite(ioPinNumers[i], LOW);
continue;
}
// if Effect is static on, nothing to do
if (ioPinStatus[i] == PIN_ON) {
//DEBUG_PRINT("_PINblink ");DEBUG_PRINT(ioPinNumers[i]);DEBUG_PRINTLN(" HIGH");
digitalWrite(ioPinNumers[i], HIGH);
continue;
}
// handle effect
if (pinBlinkCount <= ioPinStatus[i]) {
//DEBUG_PRINT("_PINblink ");DEBUG_PRINT(ioPinNumers[i]);DEBUG_PRINTLN(" HIGH");
digitalWrite(ioPinNumers[i], HIGH);
} else {
//DEBUG_PRINT("_PINblink ");DEBUG_PRINT(ioPinNumers[i]);DEBUG_PRINTLN(" LOW");
digitalWrite(ioPinNumers[i], LOW);
}
}
}
/*
* Set the specified I/O Pin of the board to on/off/blink/flash.
* pin = D5/D6/D7
* effect = RGB_ON/RGB_BLINK/RGB_FLASH/RGB_OFF
*/
void KniwwelinoLib::PINsetEffect(uint8_t pin, int effect) {
switch (pin) {
case D0:
ioPinStatus[0] = effect;
break;
case D5:
ioPinStatus[1] = effect;
break;
case D6:
ioPinStatus[2] = effect;
break;
case D7:
ioPinStatus[3] = effect;
break;
break;
}
}
/*
* Clear the specified I/O Pin of the board.
* (set to OFF and remove from ticker)
* pin = D5/D6/D7
*/
void KniwwelinoLib::PINclear(uint8_t pin) {
digitalWrite(pin, LOW);
switch (pin) {
case D0:
ioPinStatus[0] = PIN_UNUSED;
break;
case D5:
ioPinStatus[1] = PIN_UNUSED;
break;
case D6:
ioPinStatus[2] = PIN_UNUSED;
break;
case D7:
ioPinStatus[3] = PIN_UNUSED;
break;
break;
}
}
void KniwwelinoLib::PINenableButton(uint8_t pin) {
pinMode(pin, INPUT_PULLUP);
switch (pin) {
case D0:
ioPinStatus[0] = PIN_INPUT;
break;
case D5:
ioPinStatus[1] = PIN_INPUT;
break;
case D6:
ioPinStatus[2] = PIN_INPUT;
break;
case D7:
ioPinStatus[3] = PIN_INPUT;
break;
}
}
boolean KniwwelinoLib::PINbuttonClicked(uint8_t pin) {
if (!digitalRead(pin)) return false; // still pressed
boolean clicked = false;
switch (pin) {
case D0:
clicked = ioPinclicked[0];
ioPinclicked[0] = false;
break;
case D5:
clicked = ioPinclicked[1];
ioPinclicked[1] = false;
break;
case D6:
clicked = ioPinclicked[2];
ioPinclicked[2] = false;
break;
case D7:
clicked = ioPinclicked[3];
ioPinclicked[3] = false;
break;
}
return (clicked);
}
boolean KniwwelinoLib::PINbuttonDown(uint8_t pin) {
return !digitalRead(pin);
}
//==== RGB LED functions ====================================================
/*
* Set the RGB LED of the board to show the given color.
* col = color to show as String in format #FF00FF
* first 2 digits specify the RED, second the GREEN, third the BLUE component.
*/
void KniwwelinoLib::RGBsetColor(String col) {
uint32_t color = RGBhex2int(col);
RGBsetColorEffect(color, RGB_ON, RGB_FOREVER);
}
/*
* Set the RGB LED of the board to show the given color and effect.
* col = color to show as String in format #FF00FF
* first 2 digits specify the RED, second the GREEN, third the BLUE component.
* effect = on of RGB_ON/RGB_BLINK/RGB_FLASH/RGB_OFF
* count = how long shall the effect be shown. (10 = 1sec, -1 shows forever.)
*/
void KniwwelinoLib::RGBsetColorEffect(String col, uint8_t effect, int count) {
unsigned long color = RGBhex2int(col);
RGBsetColorEffect(color, effect, count);
}
/*
* Set the RGB LED of the board to show the given color.
* col = color to show as 32 bit int.
*/
void KniwwelinoLib::RGBsetColor(unsigned long color) {
RGBsetColorEffect(color, RGB_ON, RGB_FOREVER);
}
/*
* Set the RGB LED of the board to show the given color.
* col = color to show as 32 bit int.
* effect = on of RGB_ON/RGB_BLINK/RGB_FLASH/RGB_OFF
* count = how long shall the effect be shown. (10 = 1sec, -1 shows forever.)
*/
void KniwwelinoLib::RGBsetColorEffect(unsigned long color, uint8_t effect, int count) {
RGBsetColorEffect((uint8_t)(color >> 16) ,(uint8_t)(color >> 8), (uint8_t)color, effect, count);
}
void KniwwelinoLib::RGBsetColorEffect(String colorEffect) {
int pos = 0, lastpos = 0;
String color = "";
int effect = RGB_ON;
int duration = RGB_FOREVER;
pos = colorEffect.indexOf(":", pos);
if (pos == -1) {
RGBsetColor(colorEffect);
return;
} else if (pos == 6) {
color = colorEffect.substring(0,6);
lastpos = pos+1;
pos = colorEffect.indexOf(":", lastpos);
if (pos != -1) {
effect = colorEffect.substring(lastpos,pos).toInt();
lastpos = pos+1;
if (colorEffect.length() >= lastpos) {
duration = colorEffect.substring(pos+1).toFloat();
}
}
}
RGBsetColorEffect(color, effect, duration);
}
/*
* Set the RGB LED of the board to show the given color
* red = RED color component (0-255)
* green = GREEN color component (0-255)
* blue = BLUE color component (0-255)
*/
void KniwwelinoLib::RGBsetColor(uint8_t red ,uint8_t green, uint8_t blue) {
RGBsetColorEffect(red ,green, blue, RGB_ON, RGB_FOREVER);
}
/*
* Set the RGB LED of the board to show the given color and effect.
* red = RED color component (0-255)
* green = GREEN color component (0-255)
* blue = BLUE color component (0-255)
* effect = on of RGB_ON/RGB_BLINK/RGB_FLASH/RGB_OFF
* count = how long shall the effect be shown. (10 = 1sec, -1 shows forever.)
*/
void KniwwelinoLib::RGBsetColorEffect(uint8_t red ,uint8_t green, uint8_t blue, uint8_t effect, int count) {
RGBsetEffect(effect, count);
RGB.setPixelColor(0, red, green, blue);
if (rgbColor != RGB.getPixelColor(0)) {
RGB.show();
}
rgbColor = RGB.getPixelColor(0);
}
/*
* Set the RGB LED of the board to show the given effect.
* effect = on of RGB_ON/RGB_BLINK/RGB_FLASH/RGB_OFF
* count = how long shall the effect be shown. (10 = 1sec, -1 shows forever.)
*/
void KniwwelinoLib::RGBsetEffect(uint8_t effect, int count) {
bool changed = (rgbEffect != effect);
rgbEffect = effect;
rgbEffectCount = count;
if (rgbEffect==RGB_ON) {
RGB.setPixelColor(0, rgbColor);
changed = true;
} else if (rgbEffect > 10) {
changed = true;
}
if (changed) {
RGB.setBrightness(rgbBrightness);
}
}
/*
* Set the RGB LED of the board to be OFF
*/
void KniwwelinoLib::RGBclear() {
rgbEffectCount=0;
if (rgbColor!=0) {
RGB.setPixelColor(0, 0);
RGB.show();
}
rgbColor = 0;
}
/*
* Set the Brightness of the RGB LED of the board.
* b = brightness from 0-255
*/
void KniwwelinoLib::RGBsetBrightness(uint8_t b) {
b = constrain(b, 1, 255);
rgbBrightness = b;
RGB.setBrightness(b);
RGB.show();
}
/*
* returns the current LED Color as int
*/
uint32_t KniwwelinoLib::RGBgetColor() {
return rgbColor;
}
/*
* Internal ticker function to handle the LED effects.
*/
void KniwwelinoLib::_RGBblink() {
// if Effect Time has passed, turn off LED
if (rgbEffectCount==0) {
Kniwwelino.RGBclear();
} else if (rgbEffect == RGB_ON) {
// if Effect is static on, nothing to do
rgbBlinkCount++;
if (rgbBlinkCount > 10) {
rgbBlinkCount = 1;
if (rgbEffectCount > 0) rgbEffectCount--;
}
} else if (rgbEffect <= 10) {
// blink/flash onoff Effects
if (rgbBlinkCount <= rgbEffect) {
// handle effect
if (RGB.getPixelColor(0)==0) {
RGB.setPixelColor(0, rgbColor);
RGB.show();
}
} else {
RGB.setPixelColor(0, 0);
RGB.show();
}
rgbBlinkCount++;
if (rgbBlinkCount > 10) {
rgbBlinkCount = 1;
if (rgbEffectCount > 0) rgbEffectCount--;
}
} else if (rgbEffect > 10) {
// other brightness effects
if (rgbEffect == RGB_SPARK) {
RGB.setPixelColor(0, rgbColor);
RGB.setBrightness(rgbEffectBrightness);
RGB.show();
rgbEffectBrightness /=2;
if (rgbEffectBrightness <= 0) {
rgbEffectBrightness = rgbBrightness;
if (rgbEffectCount > 0) rgbEffectCount--;
}
} else if (rgbEffect == RGB_GLOW) {
RGB.setPixelColor(0, rgbColor);
RGB.setBrightness(rgbEffectBrightness/10);
RGB.show();
if (rgbEffectModifier>0) {
rgbEffectBrightness *= 1.2;
} else {
rgbEffectBrightness /= 1.2;
}
if (rgbEffectBrightness <= 10) {
rgbEffectBrightness = 10;
rgbEffectModifier = 1;
} else if (rgbEffectBrightness >= (rgbBrightness*10)) {
rgbEffectModifier = -1;
if (rgbEffectCount > 0) rgbEffectCount--;
}
}
} else {
RGB.setPixelColor(0, 0);
RGB.show();
}
}
/*
* Helper function to convert a given color in String format (#00FF00)
* to a 32bit int color.
*/
unsigned long KniwwelinoLib::RGBhex2int(String str) {
int i;
unsigned long val = 0;
int len = str.length();
// parse the first 6 chars for HEX
if (len > 6) len = 6;
for(i=0;i<len;i++) {
char c = str.charAt(i);
if(c <= 57)
val += (c-48)*(1<<(4*(len-1-i)));
else
val += (c-55)*(1<<(4*(len-1-i)));
}
return val;
}
/*
* Helper function to convert a given color hue (0-255)
* to a 32bit int color.
* The colours are a transition r -> g -> b -> back to r
* Inspired by the Adafruit examples and WS2812FX lib.
*/
unsigned long KniwwelinoLib::RGBhue2int(uint8_t hue) {
hue = 255 - hue;
if(hue < 85) {
return ((uint32_t)(255 - hue * 3) << 16) | ((uint32_t)(0) << 8) | (hue * 3);
} else if(hue < 170) {
hue -= 85;
return ((uint32_t)(0) << 16) | ((uint32_t)(hue * 3) << 8) | (255 - hue * 3);
} else {
hue -= 170;
return ((uint32_t)(hue * 3) << 16) | ((uint32_t)(255 - hue * 3) << 8) | (0);
}
}
String KniwwelinoLib::RGB82Hex(uint8_t c) {
String s = String(String(c<16?"0":"") + String(c, HEX));
s.toUpperCase();
return s;
}
String KniwwelinoLib::RGBcolor2Hex(unsigned long color) {
return String(RGB82Hex((uint8_t)(color >> 16)) + RGB82Hex((uint8_t)(color >> 8)) + RGB82Hex((uint8_t)color));
}
String KniwwelinoLib::RGBhue2Hex(uint8_t hue) {
return Kniwwelino.RGBcolor2Hex(Kniwwelino.RGBhue2int(hue));
}
String KniwwelinoLib::RGBcolor2Hex(uint8_t r, uint8_t g, uint8_t b) {
return String(RGB82Hex(r) + RGB82Hex(g) + RGB82Hex(b));
}
//==== LED MATRIX functions ==================================================
/*
* Write the given text to the matrix and scroll it for a number of times.
*
* text = text to be shown.
* count = number of times the text shall be scrolled before disappearing (-1 = forever)
* wait = if true, wait before text has been shown before returning.
*
*/
void KniwwelinoLib::MATRIXwrite(String text, int count, boolean wait) {
MATRIXsetBlinkRate(MATRIX_STATIC);
if (text.length() == 0) {
Kniwwelino.MATRIXclear();
}
// if wait or different Text, reset position, else keep scrolling.
if (wait || text != matrixText) {
matrixPos = 4;
}
matrixText = text;
matrixCount = count;
if (wait) {
if (matrixText.length() == 1) {
Kniwwelino.sleep(1000);
} else {
//Kniwwelino.sleep((matrixText.length()+2)*4*count*(TICK_FREQ*2000.0));
while (!Kniwwelino.MATRIXtextDone()) {
Kniwwelino.sleep(100);
}
}
}
}
/*
* Write the given text to the matrix and scroll it infinitely.
*
* text = text to be shown.
*/
void KniwwelinoLib::MATRIXwrite(String text) {
MATRIXwrite(text, MATRIX_FOREVER, false);
}
/*
* Write the given text to the matrix and scroll it,
* wait before text has been shown before returning.
*
* text = text to be shown.
*/
void KniwwelinoLib::MATRIXwriteAndWait(String text) {
MATRIXwrite(text, 1, true);
}
/*
* Write the given text to the matrix and scroll it once.
*
* text = text to be shown.
*/
void KniwwelinoLib::MATRIXwriteOnce(String text) {
MATRIXwrite(text, 1, false);
}
/*
* Draw the given icon on the matrix.
* Icon is given as string and accepted in the following formats:
* "B1111100000111110000011111" 25 pixels binary one after the other, prefix B
* "0x7008E828A0" one byte for each 5px row, prefix 0x
*
* iconString = icon to be shown.
*/
void KniwwelinoLib::MATRIXdrawIcon(String iconString) {
MATRIXclear();
matrixText = "";
matrixCount = -1;
MATRIXsetBlinkRate(MATRIX_STATIC);
if (iconString.startsWith("B") || iconString.startsWith("b")) {
int pos = 0, lastpos = 0;
// count icons
iconcount = 1;
if (iconString.indexOf("\n") <= 0) {
while (pos != -1 && lastpos < iconString.length()) {
pos = iconString.indexOf("\n",lastpos);
if (pos != -1) {
iconcount++;
lastpos = pos+1;
}
}
}
// String must be like "B1111100000111110000011111" 25 pixels one after the other
if (iconString.length() >25) {
for(int i=0; i < 25; i++) {
if (iconString.charAt(i+1) != '0') {
drawPixel(i%5, i/5, 1);
}
}
if (iconString.length()>26) {
pos = 0;
lastpos = 0;
pos = iconString.indexOf(":", lastpos);
if (pos >= 26) {
lastpos = pos+1;
pos = iconString.indexOf(":", lastpos);
int effect = iconString.substring(lastpos,pos).toInt();
MATRIXsetBlinkRate(effect);
lastpos = pos+1;
if (iconString.length() >= lastpos) {
pos = iconString.indexOf("\n", lastpos);
float duration = iconString.substring(lastpos, pos).toFloat();
matrixCount = duration*10;
}
}
}
} else {
DEBUG_PRINTLN(F("MATRIXdrawIcon:Binay: Wrong String length (not 26)"));
return;
}
redrawMatrix = true;
} else if (iconString.startsWith("0x")) {
// String must be like "0x7008E828A0" one byte for each 5px row
if (iconString.length() != 12) {
DEBUG_PRINTLN(F("MATRIXdrawIcon:Hex: Wrong String length (not 12)"));
return;
} else {
}
for(int i=0; i < 5; i++) {
String sub = iconString.substring((i*2)+2,(i*2)+4);
int number = (int) strtol( &sub[0], NULL, 16);
for(int j=0; j < 5; j++) {
MATRIXsetPixel(j, i, bitRead(number, 7-j));
}
}
redrawMatrix = true;
}
}
/*
* Draw the given icon on the matrix.
* Icon is given as 32bit long.
* bits correspond to the pixels starting at top left.
*
* iconLong = icon to be shown.
*/
void KniwwelinoLib::MATRIXdrawIcon(uint32_t iconLong) {
MATRIXsetBlinkRate(MATRIX_STATIC);
matrixCount = -1;
matrixText = "";
MATRIXclear();
for(int i=0; i < 25; i++) {
MATRIXsetPixel(i%5, i/5, bitRead(iconLong, 24-i));
}
}
/*
* Sets the given pixel of the matrix to be on or off
*
* x = pixel column
* y = pixel row
* on = true-> Pixel on, false->Pixel off.