forked from MartinNohr/MagicImageWand
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MagicImageWand.ino
6641 lines (6382 loc) · 192 KB
/
MagicImageWand.ino
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Name: MagicImageWand.ino
Created: 12/18/2020 6:12:01 PM
Author: Martin Nohr
*/
#include "MagicImageWand.h"
#include "fonts.h"
#include <nvs_flash.h>
RTC_DATA_ATTR int nBootCount = 0;
// some forward references that Arduino IDE needs
int readByte(bool clear);
void ReadAndDisplayFile(bool doingFirstHalf);
uint16_t readInt();
uint32_t readLong();
void FileSeekBuf(uint32_t place);
int FileCountOnly(int start = 0);
//static const char* TAG = "lightwand";
//esp_timer_cb_t oneshot_timer_callback(void* arg)
void oneshot_LED_timer_callback(void* arg)
{
bStripWaiting = false;
//int64_t time_since_boot = esp_timer_get_time();
//Serial.println("in isr");
//ESP_LOGI(TAG, "One-shot timer called, time since boot: %lld us", time_since_boot);
}
// timer called every second
void periodic_Second_timer_callback(void* arg)
{
if (sleepTimer)
--sleepTimer;
if (SystemInfo.eDisplayDimMode == DISPLAY_DIM_MODE_TIME && displayDimTimer) {
--displayDimTimer;
if (displayDimTimer == 0) {
displayDimNow = true;
}
}
}
constexpr int TFT_ENABLE = 4;
// use these to control the LCD brightness
const int freq = 5000;
const int ledChannel = 0;
const int resolution = 8;
TFT_eSprite LineSprite = TFT_eSprite(&tft); // Create Sprite object "LineSprite" with pointer to "tft" object
#define BATTERY_BAR_HEIGHT 5
TFT_eSprite BatterySprite = TFT_eSprite(&tft); // Create Sprite object "BatterySprite" with pointer to "tft" object
void setup()
{
// init the display
tft.init();
tft.fillScreen(TFT_BLACK);
Serial.begin(115200);
while (!Serial.availableForWrite()) {
delay(10);
}
//Serial.print("setup() is running on core ");
//Serial.println(xPortGetCoreID());
// create a mutex
macroMutex = xSemaphoreCreateMutex();
// configure LCD PWM functionalitites
pinMode(TFT_ENABLE, OUTPUT);
digitalWrite(TFT_ENABLE, 1);
ledcSetup(ledChannel, freq, resolution);
// attach the channel to the GPIO to be controlled
ledcAttachPin(TFT_ENABLE, ledChannel);
#if TTGO_T == 1
CRotaryDialButton::begin((gpio_num_t)DIAL_A, (gpio_num_t)DIAL_B, (gpio_num_t)DIAL_BTN, (gpio_num_t)0, (gpio_num_t)35, (gpio_num_t)-1, (gpio_num_t)-1, &SystemInfo.DialSettings);
#elif TTGO_T == 4
CRotaryDialButton::begin((gpio_num_t)DIAL_A, (gpio_num_t)DIAL_B, (gpio_num_t)DIAL_BTN, (gpio_num_t)0, (gpio_num_t)-1, (gpio_num_t)38, (gpio_num_t)39, &SystemInfo.DialSettings);
#endif
setupSDcard();
//gpio_set_direction((gpio_num_t)LED, GPIO_MODE_OUTPUT);
//digitalWrite(LED, HIGH);
gpio_set_direction((gpio_num_t)FRAMEBUTTON_GPIO, GPIO_MODE_INPUT);
gpio_set_pull_mode((gpio_num_t)FRAMEBUTTON_GPIO, GPIO_PULLUP_ONLY);
// init the onboard buttons
gpio_set_direction(GPIO_NUM_0, GPIO_MODE_INPUT);
gpio_set_pull_mode(GPIO_NUM_0, GPIO_PULLUP_ONLY);
gpio_set_direction(GPIO_NUM_35, GPIO_MODE_INPUT);
oneshot_LED_timer_args = {
oneshot_LED_timer_callback,
/* argument specified here will be passed to timer callback function */
(void*)0,
ESP_TIMER_TASK,
"one-shotLED"
};
esp_timer_create(&oneshot_LED_timer_args, &oneshot_LED_timer);
periodic_Second_timer_args = {
periodic_Second_timer_callback,
/* argument specified here will be passed to timer callback function */
(void*)0,
ESP_TIMER_TASK,
"second timer"
};
esp_timer_create(&periodic_Second_timer_args, &periodic_Second_timer);
esp_timer_start_periodic(periodic_Second_timer, 1000 * 1000);
SystemInfo.bCriticalBatteryLevel = false;
tft.setFreeFont(&Dialog_bold_16);
#if TTGO_T == 1
SystemInfo.nDisplayRotation = 3;
#elif TTGO_T == 4
SystemInfo.nDisplayRotation = 0;
#endif
tft.setTextSize(1);
tft.setTextPadding(tft.width());
SetScreenRotation(SystemInfo.nDisplayRotation);
//ClearScreen();
SetDisplayBrightness(SystemInfo.nDisplayBrightness);
// see if the button is down, if so clear all settings
if (gpio_get_level((gpio_num_t)DIAL_BTN) == 0) {
Preferences prefs;
prefs.begin(prefsName);
prefs.clear();
prefs.end();
WriteMessage("Factory Reset");
}
String msg;
// see if we can read the settings
if (SaveLoadSettings(false, true, false, true)) {
if ((nBootCount == 0) && bAutoLoadSettings) {
SaveLoadSettings(false, false, false, true);
msg = "Settings Loaded";
}
}
else {
// set the dial type
CheckRotaryDialType();
// see if there is a light sensor, read it until it is stable
int lastVal = 0;
int val = 0;
for (int i = 0; i < 50; ++i) {
val = ReadLightSensor();
//Serial.println("read sensor: " + String(val));
if (lastVal >= val)
break;
lastVal = val;
delay(10);
}
SystemInfo.bHasLightSensor = val < 4094;
// must not be anything there, so save it
SaveLoadSettings(true, false, false, true);
}
// in case the saved ones were different
SetScreenRotation(SystemInfo.nDisplayRotation);
//ClearScreen();
SetDisplayBrightness(SystemInfo.nDisplayBrightness);
//WiFi
if (SystemInfo.bRunWebServer) {
WiFi.softAP(ssid, password);
IPAddress myIP = WiFi.softAPIP();
// save for the menu system
strncpy(localIpAddress, myIP.toString().c_str(), sizeof(localIpAddress));
Serial.print("AP IP address: ");
Serial.println(myIP);
server.begin();
Serial.println("Server started");
for (OnServerItem item : OnServerList) {
server.on(item.path, item.function);
}
server.on("/fupload", HTTP_POST, []() { server.send(200); }, handleFileUpload);
//server.on("/settings/increpeat", HTTP_GET, []() { server.send(200); }, IncRepeat);
//server.on("/settings/increpeat", HTTP_GET, IncRepeat);
/////////////////////////// End of Request commands
server.begin();
}
if (nBootCount) {
// see if we need to get the path back
if (strlen(sleepFolder))
currentFolder = sleepFolder;
}
#if !HAS_BATTERY_LEVEL
SystemInfo.bShowBatteryLevel = false;
#endif
tft.setFreeFont(&Dialog_bold_16);
tft.setTextColor(SystemInfo.menuTextColor);
// get our text line sprite ready
LineSprite.setColorDepth(16);
LineSprite.createSprite(tft.width(), tft.fontHeight());
LineSprite.fillSprite(TFT_BLACK);
LineSprite.setFreeFont(&Dialog_bold_16);
LineSprite.setTextPadding(tft.width());
// get our Battery sprite ready
BatterySprite.setColorDepth(16);
BatterySprite.createSprite(100, tft.fontHeight() + BATTERY_BAR_HEIGHT);
BatterySprite.fillSprite(TFT_BLACK);
BatterySprite.setFreeFont(&Dialog_bold_16);
BatterySprite.setTextPadding(tft.width());
// get the menu system ready
menuPtr = new MenuInfo;
MenuStack.push(menuPtr);
MenuStack.top()->menu = MainMenu;
MenuStack.top()->index = 0;
MenuStack.top()->offset = 0;
leds = (CRGB*)calloc(LedInfo.nTotalLeds, sizeof(*leds));
if (LedInfo.bSwapControllers)
FastLED.addLeds<NEOPIXEL, DATA_PIN2>(leds, 0, LedInfo.bSecondController ? LedInfo.nTotalLeds / 2 : LedInfo.nTotalLeds);
else
FastLED.addLeds<NEOPIXEL, DATA_PIN1>(leds, 0, LedInfo.bSecondController ? LedInfo.nTotalLeds / 2 : LedInfo.nTotalLeds);
//FastLED.addLeds<NEOPIXEL, DATA_PIN2>(leds, 0, NUM_LEDS); // to test parallel second strip
// create the second led controller
if (LedInfo.bSecondController) {
if (LedInfo.bSwapControllers)
FastLED.addLeds<NEOPIXEL, DATA_PIN1>(leds, LedInfo.nTotalLeds / 2, LedInfo.nTotalLeds / 2);
else
FastLED.addLeds<NEOPIXEL, DATA_PIN2>(leds, LedInfo.nTotalLeds / 2, LedInfo.nTotalLeds / 2);
}
//FastLED.setTemperature(whiteBalance);
FastLED.setTemperature(CRGB(LedInfo.whiteBalance.r, LedInfo.whiteBalance.g, LedInfo.whiteBalance.b));
FastLED.setBrightness(LedInfo.nLEDBrightness);
//FastLED.setMaxPowerInVoltsAndMilliamps(5, LedInfo.nPixelMaxCurrent);
if (nBootCount == 0) {
// this must run on same task as main or only the first few LEDs light using FastLED 3.5, don't know why, 3.3 worked
xTaskCreatePinnedToCore(TaskInitTestLed, "LEDTEST", 10000, NULL, 1, &TaskLEDTest, xPortGetCoreID());
if (SystemInfo.bRunArtNetDMX) {
xTaskCreatePinnedToCore(TaskRunArtNet, "ARTNET", 10000, NULL, 1, &TaskArtNet, xPortGetCoreID());
}
tft.setTextColor(SystemInfo.menuTextColor);
//grey_fill();
rainbow_fill();
tft.setTextColor(TFT_BLACK);
tft.setFreeFont(&Irish_Grover_Regular_24);
tft.drawRect(0, 0, tft.width() - 1, tft.height() - 1, SystemInfo.menuTextColor);
tft.drawRect(1, 1, tft.width() - 2, tft.height() - 2, SystemInfo.menuTextColor);
tft.drawString("Magic Image Wand", 5, 10);
tft.setFreeFont(&Dialog_bold_16);
tft.drawString(String("Version ") + MIW_Version, 20, 70);
tft.setTextSize(1);
tft.drawString(__DATE__, 20, 90);
if (msg.length()) {
tft.drawString(msg, 20, 110);
}
}
// clear the button buffer
CRotaryDialButton::clear();
nBootCount = 0;
// load the sleep timer
sleepTimer = SystemInfo.nSleepTime * 60;
GetFileNamesFromSDorBuiltins(currentFolder);
// read the macro data
if (bSdCardValid)
ReadMacroInfo();
for (int cnt = 0; cnt < 400; ++cnt) {
if (ReadButton() != BTN_NONE) {
break;
}
vTaskDelay(10 / portTICK_PERIOD_MS);
}
ClearScreen();
DisplayCurrentFile();
//// wait for led test to finish
//eTaskState state = eTaskGetState(TaskLEDTest);
//for (; state != eReady; delay(10)) {
// state = eTaskGetState(TaskLEDTest);
//}
}
// task to run ArtNet
void TaskRunArtNet(void* parameter)
{
artnet.setName(SystemInfo.cArtNetName);
artnet.setNumPorts(1);
artnet.enableDMXOutput(0);
//artnet.disableDMXOutput(0);
artnet.setStartingUniverse(SystemInfo.bStartUniverseOne ? 1 : 0);
// use for ArtNetWiFi
ConnectWifi();
artnet.begin();
// this will be called for each packet received
artnet.setArtDmxCallback(onDmxFrame);
while (true) {
artnet.read();
vTaskDelay(10 / portTICK_PERIOD_MS);
}
}
// task to test the LEDS on start
void TaskInitTestLed(void* parameter)
{
FastLED.clear(true);
if (SystemInfo.bInitTest)
TestLEDs(500);
vTaskDelete(NULL);
}
// check and handle the rotary dial type
// if either A or B is 0, then this is a toggle dial
// else
// tell user to rotate one click
// delay
// if A or B is 0, then this is a toggle
// else it is a pulse dial
void CheckRotaryDialType()
{
bool bA, bB;
WriteMessage("checking dial type...", false, 1000);
bA = gpio_get_level((gpio_num_t)DIAL_A);
bB = gpio_get_level((gpio_num_t)DIAL_B);
//Serial.println("ab " + String(bA) + String(bB));
if (!bA && !bB) {
// if both low must be a toggle
SystemInfo.DialSettings.m_bToggleDial = true;
}
else {
WriteMessage("Rotate dial 1 click", false, 10);
// wait for rotate, they were both high before if we got this far, so just look at A
while (gpio_get_level((gpio_num_t)DIAL_A))
delay(10);
// wait for button bounce
delay(250);
// read them again
bA = gpio_get_level((gpio_num_t)DIAL_A);
bB = gpio_get_level((gpio_num_t)DIAL_B);
//Serial.println("ab " + String(bA) + String(bB));
// if both low must be a toggle
SystemInfo.DialSettings.m_bToggleDial = !bA && !bB;
// we shouldn't need this again
}
if (!SystemInfo.DialSettings.m_bToggleDial)
SystemInfo.DialSettings.m_nDialPulseCount = 2;
WriteMessage(String("Dial Type: ") + (SystemInfo.DialSettings.m_bToggleDial ? "Toggle" : "Pulse"), false, 1000);
}
// read the macro info from the files if we didn't find the json file first
void ReadMacroInfo()
{
if (SD.exists(MACRO_JSON_FILE)) {
// read the file
#if USE_STANDARD_SD
SDFile file;
file = SD.open(MACRO_JSON_FILE);
if (file) {
#else
FsFile file;
file = SD.open(MACRO_JSON_FILE);
if (file.getError() == 0) {
#endif
//WriteMessage("Reading: " + String(MACRO_JSON_FILE), false, 1000);
//StaticJsonDocument<JSON_DOC_SIZE> doc;
DynamicJsonDocument doc(JSON_DOC_SIZE);
String input = file.readString();
//Serial.println("json size: " + String(input.length()));
DeserializationError err = deserializeJson(doc, input);
if (err) {
WriteMessage(String("failed to parse: ") + MACRO_JSON_FILE, true);
//Serial.print(F("deserializeJson() failed with code "));
//Serial.println(err.f_str());
}
else {
// read the json into the macroinfo
for (int ix = 0; ix < 10; ++ix) {
MacroInfo[ix].description = String(doc[ix]["description"].as<const char*>());
MacroInfo[ix].mSeconds = doc[ix]["mSeconds"];
MacroInfo[ix].length = doc[ix]["length"].as<int>();
MacroInfo[ix].pixels = doc[ix]["pixels"].as<int>();
JsonArray ja = doc[ix]["images"];
for (String str : ja) {
MacroInfo[ix].fileNames.push_back(str);
}
}
}
file.close();
}
else {
#if USE_STANDARD_SD
WriteMessage(String("failed to open: ") + MACRO_JSON_FILE, true);
#else
WriteMessage(String("failed to open: ") + MACRO_JSON_FILE + " error: " + String(file.getError()), true);
#endif
}
}
else {
int fileCount, pixelWidth;
WriteMessage(String("Creating: ") + MACRO_JSON_FILE, false, 1000);
for (int ix = 0; ix < 10; ++ix) {
String fn = MakeMIWFilename(String(ix), true);
MacroInfo[ix].fileNames.clear();
MacroInfo[ix].mSeconds = MacroTime("/" + fn, &fileCount, &pixelWidth, &MacroInfo[ix].fileNames);
MacroInfo[ix].description = SD.exists("/" + fn) ? "Used" : "Empty";
MacroInfo[ix].length = (float)pixelWidth / (float)LedInfo.nTotalLeds;
MacroInfo[ix].pixels = pixelWidth;
}
// save the info since we just created it
SaveMacroInfo();
}
}
// save the macro info in json to a file called macro.json
void SaveMacroInfo()
{
#if USE_STANDARD_SD
SDFile file;
file = SD.open(MACRO_JSON_FILE, FILE_WRITE);
if (file) {
#else
FsFile file;
file = SD.open(MACRO_JSON_FILE, O_WRITE | O_CREAT | O_TRUNC);
if (file.getError() == 0) {
#endif
DynamicJsonDocument doc(JSON_DOC_SIZE);
//StaticJsonDocument<JSON_DOC_SIZE> doc;
for (int ix = 0; ix < 10; ++ix) {
doc[ix]["ID"] = ix;
doc[ix]["description"] = MacroInfo[ix].description;
doc[ix]["length"] = MacroInfo[ix].length;
doc[ix]["mSeconds"] = MacroInfo[ix].mSeconds;
doc[ix]["pixels"] = MacroInfo[ix].pixels;
//doc[ix]["filecount"] = MacroInfo[ix].fileNames.size();
JsonArray ja = doc[ix]["images"].to<JsonArray>();
int fix = 0;
// add the filenames in an array
for (String fname : MacroInfo[ix].fileNames) {
ja[fix] = fname;
++fix;
}
}
char output[JSON_DOC_SIZE];
serializeJsonPretty(doc, output);
file.write((uint8_t*)output, strlen(output));
file.close();
}
else {
// something went wrong
#if USE_STANDARD_SD
WriteMessage(String("failed to open: ") + MACRO_JSON_FILE, true);
#else
WriteMessage(String("failed to open: ") + MACRO_JSON_FILE + " error: " + String(file.getError()), true);
#endif
}
}
void ResetSleepAndDimTimers() {
sleepTimer = SystemInfo.nSleepTime * 60;
displayDimTimer = SystemInfo.nDisplayDimTime;
if (SystemInfo.eDisplayDimMode == DISPLAY_DIM_MODE_TIME && SystemInfo.nDisplayDimTime) {
SetDisplayBrightness(SystemInfo.nDisplayBrightness);
}
}
// scroll the long menu lines
// this also checks the light sensor if enabled
void MenuTextScrollSideways()
{
// this handles sideways scrolling of really long menu items
static unsigned long menuUpdateTime = 0;
static unsigned long ledUpdateTime = 0;
if (SystemInfo.eDisplayDimMode == DISPLAY_DIM_MODE_SENSOR && millis() > ledUpdateTime + 100) {
ledUpdateTime = millis();
LightSensorLedBrightness();
}
if (millis() > menuUpdateTime + SystemInfo.nSidewayScrollSpeed) {
menuUpdateTime = millis();
for (int ix = 0; ix < nMenuLineCount; ++ix) {
int offset = TextLines[ix].nRollOffset;
if (TextLines[ix].nRollLength) {
if (TextLines[ix].nRollOffset == 0 && TextLines[ix].nRollDirection == 0) {
TextLines[ix].nRollDirection = SystemInfo.nSidewaysScrollPause;
continue;
}
if (TextLines[ix].nRollDirection > 1) {
--TextLines[ix].nRollDirection;
}
if (TextLines[ix].nRollDirection == 1) {
++TextLines[ix].nRollOffset;
}
if (TextLines[ix].nRollOffset >= (TextLines[ix].nRollLength - tft.width()) && TextLines[ix].nRollDirection > 0) {
TextLines[ix].nRollDirection = -SystemInfo.nSidewaysScrollPause;
}
if (TextLines[ix].nRollDirection < -1) {
++TextLines[ix].nRollDirection;
}
if (TextLines[ix].nRollDirection == -1) {
TextLines[ix].nRollOffset -= SystemInfo.nSidewaysScrollReverse;
if (TextLines[ix].nRollOffset < 0) {
TextLines[ix].nRollOffset = 0;
}
if (TextLines[ix].nRollOffset == 0) {
TextLines[ix].nRollDirection = 0;
}
}
if (offset != TextLines[ix].nRollOffset) {
DisplayLine(ix, TextLines[ix].Line, TextLines[ix].foreColor, TextLines[ix].backColor);
}
}
}
}
}
// call the current setting for btn0 long press
void CallBtnLongFunction(int which)
{
switch (which) {
case BTN_LONG_ROTATION:
SetScreenRotation(-1);
// make the LED's upside down for mode 1.
ImgInfo.bUpsideDown = SystemInfo.nDisplayRotation == 1;
break;
case BTN_LONG_LIGHTBAR:
LightBar(NULL);
break;
}
}
void loop()
{
static LED_INFO LedInfoSaved;
static SYSTEM_INFO SystemInfoSaved;
static BUILTIN_INFO BuiltinInfoSaved;
static bool didsomething = false;
static bool bLastSettingsMode = false;
didsomething = bSettingsMode ? HandleMenus() : HandleRunMode();
if (SystemInfo.nSleepTime && sleepTimer == 0) {
// go to sleep
Sleep(NULL);
}
if (bSettingsMode && !bLastSettingsMode) {
memcpy(&SystemInfoSaved, &SystemInfo, sizeof(SystemInfo));
memcpy(&LedInfoSaved, &LedInfo, sizeof(LedInfo));
memcpy(&BuiltinInfoSaved, &BuiltinInfo, sizeof(BuiltinInfo));
}
if (!bSettingsMode && bLastSettingsMode) {
if (memcmp(&SystemInfoSaved, &SystemInfo, sizeof(SystemInfo))) {
// make sure that the lcd dim is less than the bright
if (SystemInfo.nDisplayDimValue > SystemInfo.nDisplayBrightness)
SystemInfo.nDisplayDimValue = SystemInfo.nDisplayBrightness;
SaveLoadSettings(true, false, true, true);
}
if (memcmp(&BuiltinInfoSaved, &BuiltinInfo, sizeof(BuiltinInfo))) {
SaveLoadSettings(true, false, true, true);
}
}
bLastSettingsMode = bSettingsMode;
if (!bSettingsMode && bControllerReboot) {
if (memcmp(&LedInfo, &LedInfoSaved, sizeof(LedInfo)) || memcmp(&SystemInfoSaved, &SystemInfo, sizeof(SystemInfo))) {
WriteMessage("Rebooting due to\nsystem change", false, 2000);
SaveLoadSettings(true, false, true, true);
ESP.restart();
}
else {
bControllerReboot = false;
}
}
if (SystemInfo.bRunWebServer) {
server.handleClient();
}
// wait for no keys
if (didsomething) {
didsomething = false;
delay(1);
}
// show battery level if on
if (SystemInfo.bShowBatteryLevel && !bSettingsMode) {
int raw;
ReadBattery(&raw);
//Serial.println(String("bat:") + String(raw));
ShowBattery(NULL);
if (raw > 900 && SystemInfo.bSleepOnLowBattery && SystemInfo.bCriticalBatteryLevel) {
SystemInfo.bCriticalBatteryLevel = false;
WriteMessage("Entering sleep mode\ndue to low battery", true, 10000);
Sleep(NULL);
}
}
}
// do something from the menu depending on the button argument
// only two buttons are actually handled, SELECT and HELP
void RunMenus(int button)
{
// save this so we can see if we need to save a new changed value
bool lastAutoLoadFlag = bAutoLoadSettings;
// see if we got a menu match
bool gotmatch = false;
int menuix = 0;
MenuInfo* oldMenu;
bool bExit = false;
for (int ix = 0; !gotmatch && MenuStack.top()->menu[ix].op != eTerminate; ++ix) {
// see if this is one is valid
if (!bMenuValid[ix]) {
continue; // and don't increment menix
}
if (menuix == MenuStack.top()->index) {
gotmatch = true;
switch (button) {
case BTN_B0_LONG: // handle help if there is any
if (MenuStack.top()->menu[ix].cHelpText) {
WriteMessage(MenuStack.top()->menu[ix].cHelpText, false, -1, true);
}
bMenuChanged = true;
break;
case BTN_SELECT: // handle selection
// got one, service it
switch (MenuStack.top()->menu[ix].op) {
case eTerminate: // not used, tell compiler
case eIfEqual:
case eIfIntEqual:
case eElse:
case eEndif:
break;
case eText:
case eTextInt:
case eTextCurrentFile:
case eBool:
case eList:
bMenuChanged = true;
if (MenuStack.top()->menu[ix].change != NULL) {
(*MenuStack.top()->menu[ix].change)(&MenuStack.top()->menu[ix], 1);
}
if (MenuStack.top()->menu[ix].function) {
(*MenuStack.top()->menu[ix].function)(&MenuStack.top()->menu[ix]);
}
if (MenuStack.top()->menu[ix].change != NULL) {
(*MenuStack.top()->menu[ix].change)(&MenuStack.top()->menu[ix], -1);
}
break;
case eMacroList:
bMenuChanged = true;
if (MenuStack.top()->menu[ix].change != NULL) {
(*MenuStack.top()->menu[ix].change)(&MenuStack.top()->menu[ix], 1);
}
if (MenuStack.top()->menu[ix].function) {
(*MenuStack.top()->menu[ix].function)(&MenuStack.top()->menu[ix]);
}
if (MenuStack.top()->menu[ix].change != NULL) {
(*MenuStack.top()->menu[ix].change)(&MenuStack.top()->menu[ix], -1);
}
bExit = true;
// if there is a value, set the min value in it
if (MenuStack.top()->menu[ix].value) {
*(int*)MenuStack.top()->menu[ix].value = MenuStack.top()->menu[ix].min;
}
break;
case eMenu:
if (MenuStack.top()->menu) {
oldMenu = MenuStack.top();
MenuStack.push(new MenuInfo);
MenuStack.top()->menu = oldMenu->menu[ix].menu;
bMenuChanged = true;
MenuStack.top()->index = 0;
MenuStack.top()->offset = 0;
//Serial.println("change menu");
// check if the new menu is an eMacroList and if it has a value, if it does, set the index to it
if (MenuStack.top()->menu->op == eMacroList && MenuStack.top()->menu->value) {
int ix = *(int*)MenuStack.top()->menu->value;
MenuStack.top()->index = ix;
// adjust offset if necessary
if (ix > 4) {
MenuStack.top()->offset = ix - 4;
}
}
}
break;
case eBuiltinOptions: // find it in builtins
if (BuiltInFiles[currentFileIndex.nFileIndex].menu != NULL) {
MenuStack.top()->index = MenuStack.top()->index;
MenuStack.push(new MenuInfo);
MenuStack.top()->menu = BuiltInFiles[currentFileIndex.nFileIndex].menu;
MenuStack.top()->index = 0;
MenuStack.top()->offset = 0;
}
else {
WriteMessage("No settings available for:\n" + String(BuiltInFiles[currentFileIndex.nFileIndex].text));
}
bMenuChanged = true;
break;
case eExit: // go back a level
bExit = true;
break;
case eReboot:
WriteMessage("Rebooting in 2 seconds\nHold button for factory reset", false, 2000);
ESP.restart();
break;
}
}
}
++menuix;
}
// if no match, and we are in a submenu, go back one level, or if bExit is set
if (bExit || (!bMenuChanged && MenuStack.size() > 1)) {
UpMenuLevel(false);
}
// see if the autoload flag changed
if (bAutoLoadSettings != lastAutoLoadFlag) {
// the flag is now true, so we should save the current settings
SaveLoadSettings(true);
}
}
// display the menu
// if MenuStack.top()->index is > MENU_LINES, then shift the lines up by enough to display them
// remember that we only have room for MENU_LINES lines
void ShowMenu(struct MenuItem* menu)
{
MenuStack.top()->menucount = 0;
int y = 0;
int x = 0;
// load with a false to start with
std::stack<bool> skipStack;
skipStack.push(false);
// this is the active stack level, I.E. which level should be processed
int skipLevel = 1;
bool bSkipping = false;
// loop through the menu
for (int menix = 0; menu->op != eTerminate; ++menu, ++menix) {
// make sure menu valid vector is big enough
if (bMenuValid.size() < menix + 1) {
bMenuValid.resize(menix + 1);
}
bMenuValid[menix] = false;
switch ((menu->op)) {
case eIfEqual:
// skip the next one if match, this is boolean only
skipStack.push(*(bool*)menu->value != (menu->min ? true : false));
//Serial.println("ifequal test: skip: " + String(skip));
if (!bSkipping) {
++skipLevel;
bSkipping = skipStack.top();
}
break;
case eIfIntEqual:
// skip the next one if match, this is int values
skipStack.push(*(int*)menu->value != menu->min);
//Serial.println("ifIntequal test: skip: " + String(skip));
if (!bSkipping) {
++skipLevel;
bSkipping = skipStack.top();
}
break;
case eElse:
skipStack.top() = !skipStack.top();
break;
case eEndif:
skipStack.pop();
if (!bSkipping || skipLevel > skipStack.size()) {
--skipLevel;
}
break;
default:
break;
}
bSkipping = skipLevel < skipStack.size() ? true : skipStack.top();
if (bSkipping) {
bMenuValid[menix] = false;
continue;
}
char line[120]{}, xtraline[100]{};
// only displayable menu items should be in this switch
line[0] = '\0';
int val;
bool exists = false;
switch (menu->op) {
case eTextInt:
case eText:
case eTextCurrentFile:
bMenuValid[menix] = true;
if (menu->value) {
val = *(int*)menu->value;
if (menu->op == eText) {
sprintf(line, menu->text, (char*)(menu->value));
}
else if (menu->op == eTextInt) {
sprintf(line, menu->text, (int)(val / pow10(menu->decimals)), val % (int)(pow10(menu->decimals)));
}
}
else {
if (menu->op == eTextCurrentFile) {
sprintf(line, menu->text, MakeMIWFilename(FileNames[currentFileIndex.nFileIndex], false).c_str());
}
else {
strcpy(line, menu->text);
}
}
// next line
++y;
break;
case eMacroList:
bMenuValid[menix] = true;
// the list of macro files
// min holds the macro number
val = menu->min;
//// see if the macro is there and append the text
//exists = SD.exists("/" + String(val) + ".miw");
//sprintf(line, menu->text, val, exists ? menu->on : menu->off);
sprintf(line, menu->text, val, MacroInfo[val].description.c_str());
// next line
++y;
break;
case eList:
bMenuValid[menix] = true;
val = *(int*)menu->value;
sprintf(line, menu->text, menu->nameList[val]);
// next line
++y;
break;
case eBool:
bMenuValid[menix] = true;
if (menu->value) {
bool* pb = (bool*)menu->value;
sprintf(line, menu->text, *pb ? menu->on : menu->off);
}
else {
strcpy(line, menu->text);
}
// increment displayable lines
++y;
break;
case eBuiltinOptions:
// for builtins only show if available
if (BuiltInFiles[currentFileIndex.nFileIndex].menu != NULL) {
bMenuValid[menix] = true;
sprintf(line, menu->text, BuiltInFiles[currentFileIndex.nFileIndex].text);
++y;
}
break;
case eMenu:
case eExit:
case eReboot:
bMenuValid[menix] = true;
if (menu->value) {
// check for %d or %s in string, be lazy and assume %s if %d not there
if (String(menu->text).indexOf("%d") != -1)
sprintf(xtraline, menu->text, *(int*)menu->value);
else
sprintf(xtraline, menu->text, (char*)menu->value);
}
else {
strcpy(xtraline, menu->text);
}
if (menu->op == eExit)
sprintf(line, "%s%s", "-", xtraline);
else
sprintf(line, "%s%s", (menu->op == eReboot) ? "" : "+", xtraline);
++y;
//Serial.println("menu text4: " + String(line));
break;
default:
break;
}
if (strlen(line) && y >= MenuStack.top()->offset) {
DisplayMenuLine(y - 1, y - 1 - MenuStack.top()->offset, line);
}
}
MenuStack.top()->menucount = y;
// blank the rest of the lines
for (int ix = y; ix < nMenuLineCount; ++ix) {
DisplayLine(ix, "");
}
// show line if menu has been scrolled
if (MenuStack.top()->offset > 0)
tft.fillTriangle(0, 0, 2, 0, 0, tft.fontHeight() / 3, TFT_DARKGREY);
//tft.drawLine(0, 0, 5, 0, menuLineActiveColor);TFT_DARKGREY
// show bottom line if last line is showing
if (MenuStack.top()->offset + (nMenuLineCount - 1) < MenuStack.top()->menucount - 1) {
int ypos = tft.height() - 2 - tft.fontHeight() / 3;
tft.fillTriangle(0, ypos, 2, ypos, 0, ypos - tft.fontHeight() / 3, TFT_DARKGREY);
}
//if (MenuStack.top()->offset + (MENU_LINES - 1) < MenuStack.top()->menucount - 1)
// tft.drawLine(0, tft.height() - 1, 5, tft.height() - 1, menuLineActiveColor);
//else
// tft.drawLine(0, tft.height() - 1, 5, tft.height() - 1, TFT_BLACK);
// see if we need to clean up the end, like when the menu shrank due to a choice
int extra = MenuStack.top()->menucount - MenuStack.top()->offset - nMenuLineCount;
while (extra < 0) {
DisplayLine(nMenuLineCount + extra, "");
++extra;
}
}
// switch between SD and built-ins
void ToggleFilesBuiltin(MenuItem* menu)
{
// clear filenames list
bool lastval = ImgInfo.bShowBuiltInTests;
FILEINDEXINFO oldIndex = currentFileIndex;
String oldFolder = currentFolder;
if (menu != NULL) {
ToggleBool(menu);
}
else {
ImgInfo.bShowBuiltInTests = !ImgInfo.bShowBuiltInTests;
}
if (!ImgInfo.bShowBuiltInTests && !bSdCardValid) {
// see if we can make it valid
setupSDcard();
}
if (lastval != ImgInfo.bShowBuiltInTests) {
currentFolder = lastFolder;
GetFileNamesFromSDorBuiltins(currentFolder);
}
// restore indexes
currentFileIndex = lastFileIndex;
lastFileIndex = oldIndex;
currentFolder = lastFolder;
lastFolder = oldFolder;
}
// toggle a boolean value
void ToggleBool(MenuItem* menu)
{
bool* pb = (bool*)menu->value;
*pb = !*pb;
if (menu->change != NULL) {
(*menu->change)(menu, 0);
}
ResetTextLines();
}
// choose from one of the values, update the index and wrap around if past max
void GetSelectChoice(MenuItem* menu)
{
int* pVal = (int*)menu->value;
++* pVal;
*pVal %= menu->max + 1;
if (menu->change != NULL) {
(*menu->change)(menu, 0);
}
ResetTextLines();
}
void UpdateWiringMode(MenuItem* menu, int flag)
{
bControllerReboot = true;
}
// get integer values
void GetIntegerValue(MenuItem* menu)
{
GetIntegerValueHelper(menu, false);
}
// get integer values while showing HUE
void GetIntegerValueHue(MenuItem* menu)
{
GetIntegerValueHelper(menu, true);
}
// get integer values and sometimes show other values like hue
void GetIntegerValueHelper(MenuItem* menu, bool bShowHue)
{
ClearScreen();
// -1 means to reset to original
int stepSize = 1;
int originalValue = *(int*)menu->value;
//Serial.println("int: " + String(menu->text) + String(*(int*)menu->value));
char line[50];
CRotaryDialButton::Button button = BTN_NONE;
bool done = false;
const char* fmt = menu->decimals ? "%ld.%ld" : "%ld";
char minstr[20], maxstr[20], valstr[20];
sprintf(minstr, fmt, menu->min / (int)pow10(menu->decimals), menu->min % (int)pow10(menu->decimals));
sprintf(maxstr, fmt, menu->max / (int)pow10(menu->decimals), menu->max % (int)pow10(menu->decimals));
DisplayLine(1, String("Range: ") + String(minstr) + " to " + String(maxstr), SystemInfo.menuTextColor);
DisplayLine(5, "Long Press B0 to reset", SystemInfo.menuTextColor);
DisplayLine(6, "Long Press to Accept", SystemInfo.menuTextColor);
int oldVal = *(int*)menu->value;
do {
//Serial.println("button: " + String(button));
switch (button) {
case BTN_LEFT:
if (stepSize != -1)
*(int*)menu->value -= stepSize;
break;
case BTN_RIGHT:
if (stepSize != -1)
*(int*)menu->value += stepSize;
break;
case BTN_SELECT:
case BTN_B0_CLICK:
if (stepSize == -1) {
stepSize = 1;
}
else {
stepSize *= 10;
}
if (stepSize > (menu->max / 10)) {
stepSize = -1;
}
break;
case BTN_B0_LONG: // reset
*(int*)menu->value = originalValue;
stepSize = 1;
break;
case BTN_LONG:
if (stepSize == -1) {
*(int*)menu->value = originalValue;
stepSize = 1;
}
else {
done = true;
}
break;