forked from Raycast7373/FreeTouchDeck
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathFreeTouchDeck-CYD.ino
2008 lines (1731 loc) · 57.6 KB
/
FreeTouchDeck-CYD.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
/*
Author: Dustin Watts
Date: 27-08-2020
My thanks goes out to Brian Lough, Colin Hickey, and the people on my Discord server
for helping me a lot with the code and troubleshooting! https://discord.gg/RE3XevS
FreeTouchDeck is based on the FreeDeck idea by Koriwi. It uses the TFT_eSPI library
by Bodmer for the display and touch functionality and it uses an ESP32-BLE-Keyboard fork
with a few modifications. For saving and loading configuration it uses ArduinoJson V6.
FreeTouchDeck uses some libraries from other sources. These must be installed for
FreeTouchDeck to compile and run.
These are those libraries:
!----------------------------- Library Dependencies --------------------------- !
- Adafruit-GFX-Library (tested with version 1.10.4), available through Library Manager
- TFT_eSPI (tested with version 2.3.70), available through Library Manager
- ESP32-BLE-Keyboard (tested with version 0.3.0) download from: https://github.com/T-vK/ESP32-BLE-Keyboard
- ESPAsyncWebserver (latest version) download from: https://github.com/me-no-dev/ESPAsyncWebServer
- AsyncTCP (latest version) download from: https://github.com/me-no-dev/AsyncTCP
- ArduinoJson (tested with version 6.17.3), available through Library Manager
- for CYD, XPT2046_Touchscreen (tested with version 1.4), available through Library Manager
--- If you use a ESP32 TouchDown ---
- Dustin Watts FT6236 Library (version 1.0.2), https://github.com/DustinWatts/FT6236
--- If you use a GT911 touchscreen or the esp323248s035 capacitive board ---
- TAMCTEC GT911 library (version 1.0.2 or newer), https://github.com/TAMCTec/gt911-arduino
--- If you use the esp322432s028 resistive board ---
- TFT_Touch (Latest), https://github.com/Bodmer/TFT_Touch
--- If you use Resistive Touch ---
- You only need to uncomment ResistiveTouch
--- If you use a XPT2046 touchscreen and can't get it working by enabling ResistiveTouch ---
- TFT_Touch (Latest), https://github.com/Bodmer/TFT_Touch
- 1. Uncomment the esp322432s028r line
- 2. Comment the autobrightness option for the esp322432s028r
- 3. Change the resolution to match the resolution for your screen (the screen resolution in the line after #ifdef esp322432s028r)
- 4. Change the pins at the touchscreen part for the esp322432s028r somewhere down there to match your pin layout
- 5. Try and see if it works
The FILESYSTEM (SPI FLASH filing system) is used to hold touch screen calibration data.
It has to be runs at least once when using resistive touch. After that you can set
REPEAT_CAL to false (default).
!-- Make sure you have setup your TFT display and ESP setup correctly in TFT_eSPI/user_setup.h --!
Select the right screen driver and the board (ESP32 is the only one tested) you are
using. Also make sure TOUCH_CS is defined correctly. TFT_BL is also be needed!
You can find examples of User_Setup.h in the "user_setup.h Examples" folder.
*/
// ------- Uncomment the line of the device/touchscreen you use -------
// (The ESP32 TOUCHDOWN and the ESP32 TouchDown S3 uses this!)
//#define TouchDown
// (The esp323248s035 capacitive uses the below one!)
//#define esp323248s035c
// (The gt911 touchscreen uses the lowest one)
//#define GT911 //no need to set this if you use a esp323248s035c, setting it wont affect anything tho
// (The esp322432s028r uses the below one!)
#define esp322432s028r
// (Uncomment this if you use a resistive touchscreen, not needed for the esp322432s028r)
//#define ResistiveTouch
// ------- Extra things
//Possible global (affects all devices) button spam fix (makes it a bit less)
#define SpamFix
// ------- Settings for the esp323248s035 capacitive board -------
#ifdef esp323248s035c
//Brightness related stuff, an option to change the color and disable the led light on the board will come soon
#define AUTO_BRIGHTNESS //disable this if you dont want auto brightness
#ifdef AUTO_BRIGHTNESS
uint8_t AutoOffset = 0; //change this number to change the offset of the auto brightness
unsigned int iLightTolerance = 20; //the required diffrence in brightness before it updates the brightness of the screen
#endif //defined(AUTO_BRIGHTNESS)
//Touchscreen related
//Possible fixes (for touchscreen button spamming and the info page directly closing):
#define GT911_Possible_Spam_Fix1 // makes it read the touch info 5 times instead of once a loop
#define GT911_Possible_Spam_Fix2 // diffrent way of reading the touches, does cause the screen to only have 1 touch point
#define LONGER_DELAY //adds a bit more delay in the loop which might fix some touch issues
#define GT911
#endif // defined(esp323248s035c)
// ------- Settings for the GT911 touchscreen (default is for the esp323248s035c board)-------
#ifdef GT911
#define TOUCH_SDA 33 //33
#define TOUCH_SCL 32 //32
#define TOUCH_INT 21 //21
#define TOUCH_RST 25 //25
#define TOUCH_ROTATION ROTATION_RIGHT //(Default: ROTATION_RIGHT)Possible values(or smth): ROTATION_LEFT ROTATION_RIGHT ROTATION_NORMAL ROTATION_INVERSED
#endif
// ------- Settings for the esp322432s028r board -------
#ifdef esp322432s028r
//Brightness related stuff, an option to change the color and disable the led light on the board will come soon
#define AUTO_BRIGHTNESS //disable this if you dont want auto brightness
#ifdef AUTO_BRIGHTNESS
#define LIGHT_SENSOR 34 //A test to see if it uses the same pin as the esp323248s035c
uint8_t AutoOffset = 0; //change this number to change the offset of the auto brightness
unsigned int iLightTolerance = 20; //the required diffrence in brightness before it updates the brightness of the screen
#endif //defined(AUTO_BRIGHTNESS)
#endif // defined(esp323248s035c)
// ------- Settings for the ESP32 TouchDown board -------
#ifdef TouchDown
// ------- Uncomment and populate the following if your cap touch uses custom i2c pins -------
//#define CUSTOM_TOUCH_SDA 17
//#define CUSTOM_TOUCH_SCL 18
#endif
// ------- Other settings -------
// ------- Uncomment the define below if you want to use a piezo buzzer and specify the pin where the speaker is connected -------
//#define speakerPin 26
// ------- If your board is capapble of USB HID you can uncomment this -
//#define USEUSBHID
// ------- Uncomment the define below if you want to use SLEEP and wake up on touch -------
// The pin where the IRQ from the touch screen is connected uses ESP-style GPIO_NUM_* instead of just pinnumber
#define touchInterruptPin GPIO_NUM_27 //Broken on esp323248s035c and probably esp322432s028r
// ------- NimBLE definition, use only if the NimBLE library is installed
// and if you are using the original ESP32-BLE-Keyboard library by T-VK -------
//#define USE_NIMBLE
// Define the filesystem to be used. For now just SPIFFS.
#define FILESYSTEM SPIFFS
#include <SPIFFS.h> // Filesystem support header
//#include <LittleFS.h> // Filesystem support header
#ifdef GT911
#define DefaultRes
#endif
#ifdef Touchdown
#define DefaultRes
#endif
#ifdef ResistiveTouch
#define DefaultRes
#endif
// (Uncomment this if you wanna use XPT2046_TOUCHSCREEN )
#define XPT2046
#ifdef XPT2046
#define TOUCH_MAP_X1 3900
#define TOUCH_MAP_X2 200
#define TOUCH_MAP_Y1 200
#define TOUCH_MAP_Y2 3900
#endif
//Set your resolution here (default is for the ESP32 Touchdown and esp323248s035c)
//No need to change anything if you use a esp322432s028r
#ifdef DefaultRes
#define SCREEN_WIDTH 480
#define SCREEN_HEIGHT 320
#endif
#ifdef esp322432s028r
#define SCREEN_WIDTH 320
#define SCREEN_HEIGHT 240
#endif
const char *versionnumber = "0.9.18a";
/* Version 0.9.18a.
Adding ESP32-S3 support
Trying to add LitteFS Support
Fix #89
Fix #90
*/
#include <pgmspace.h> // PROGMEM support header
#include <FS.h> // Filesystem support header
#include <Preferences.h> // Used to store states before sleep/reboot
#include <TFT_eSPI.h> // The TFT_eSPI library
#if defined(USEUSBHID)
#include "USB.h"
#include "USBHIDKeyboard.h"
#include "Keydefines.h"
USBHIDKeyboard bleKeyboard;
#else
#include <BleKeyboard.h> // BleKeyboard is used to communicate over BLE
BleKeyboard bleKeyboard("FreeTouchDeck", "Made by me");
// Checking for BLE Keyboard version
#ifndef BLE_KEYBOARD_VERSION
#warning Old BLE Keyboard version detected. Please update.
#define BLE_KEYBOARD_VERSION "Outdated"
#endif // !defined(BLE_KEYBOARD_VERSION)
#endif // if
#if defined(USE_NIMBLE)
#include "NimBLEDevice.h" // Additional BLE functionaity using NimBLE
#include "NimBLEUtils.h" // Additional BLE functionaity using NimBLE
#include "NimBLEBeacon.h" // Additional BLE functionaity using NimBLE
#else
#include "BLEDevice.h" // Additional BLE functionaity
#include "BLEUtils.h" // Additional BLE functionaity
#include "BLEBeacon.h" // Additional BLE functionaity
#endif // defined(USE_NIMBLE)
#include "esp_sleep.h" // Additional BLE functionaity
#include "esp_bt_main.h" // Additional BLE functionaity
#include "esp_bt_device.h" // Additional BLE functionaity
#include <ArduinoJson.h> // Using ArduinoJson to read and write config files
#include <WiFi.h> // Wifi support
#include <AsyncTCP.h> //Async Webserver support header
#include <ESPAsyncWebServer.h> //Async Webserver support header
#include <ESPmDNS.h> // DNS functionality
// Touchscreen part i guess
#ifdef TouchDown
#include <Wire.h>
#include <FT6236.h>
FT6236 ts = FT6236();
#endif // defined(TouchDown)
#ifdef GT911
#include <Wire.h>
#include <TAMC_GT911.h>
TAMC_GT911 ts = TAMC_GT911(TOUCH_SDA, TOUCH_SCL, TOUCH_INT, TOUCH_RST, SCREEN_WIDTH, SCREEN_HEIGHT);
#endif
#ifdef esp322432s028r
uint16_t touchX, touchY;
#include <Wire.h>
#ifndef XPT2046
#include <TFT_Touch.h>
// These are the pins used to interface between the 2046 touch controller and Arduino Pro
#define DOUT 39 /* Data out pin (T_DO) of touch screen */
#define DIN 32 /* Data in pin (T_DIN) of touch screen */
#define DCS 33 /* Chip select pin (T_CS) of touch screen */
#define DCLK 25 /* Clock pin (T_CLK) of touch screen */
/* Create an instance of the touch screen library */
TFT_Touch touch = TFT_Touch(DCS, DCLK, DIN, DOUT);
#endif
#ifdef XPT2046
#include <XPT2046_Touchscreen.h>
// ----------------------------
// Touch Screen pins
// ----------------------------
// The CYD touch uses some non default
// SPI pins
#define XPT2046_IRQ 36
#define XPT2046_MOSI 32
#define XPT2046_MISO 39
#define XPT2046_CLK 25
#define XPT2046_CS 33
// ----------------------------
SPIClass mySpi = SPIClass(VSPI);
XPT2046_Touchscreen touch(XPT2046_CS, XPT2046_IRQ);
#endif
#endif
// auto brightness part i guess
#ifdef AUTO_BRIGHTNESS
//some required things you need to set
int iLastLightLevel = 0;
int iLastBrightness = 0;
uint8_t ConvertedLightLevel = 0;
uint8_t OffsetLightLevel = 0;
uint8_t OffsetLast = 0;
uint8_t iSomething = 0;
#ifdef esp323248s035c
#define LIGHT_SENSOR 34 //no need to change this
#endif
#endif
AsyncWebServer webserver(80);
TFT_eSPI tft = TFT_eSPI();
Preferences savedStates;
bool prevthing = false;
bool pressed = false;
uint16_t t_x = 0, t_y = 0;
// This is the file name used to store the calibration data
// You can change this to create new calibration files.
// The FILESYSTEM file name must start with "/".
#define CALIBRATION_FILE "/TouchCalData"
// Set REPEAT_CAL to true instead of false to run calibration
// again, otherwise it will only be done once.
// Repeat calibration if you change the screen rotation.
#define REPEAT_CAL false
// Keypad start position, centre of the first button
#define KEY_X SCREEN_WIDTH / 6
#define KEY_Y SCREEN_HEIGHT / 4
// Gaps between buttons
#define KEY_SPACING_X SCREEN_WIDTH / 24
#define KEY_SPACING_Y SCREEN_HEIGHT / 16
// Width and height of a button
#define KEY_W (SCREEN_WIDTH / 3) - KEY_SPACING_X
#define KEY_H (SCREEN_WIDTH / 3) - KEY_SPACING_Y
// Font size multiplier
#define KEY_TEXTSIZE 1
// Text Button Label Font
#define LABEL_FONT &FreeSansBold12pt7b
// placeholder for the pagenumber we are on (0 indicates home)
int pageNum = 0;
// Initial LED brightness
int ledBrightness = 255;
// Every button has a row associated with it
uint8_t rowArray[6] = {0, 0, 0, 1, 1, 1};
// Every button has a column associated with it
uint8_t colArray[6] = {0, 1, 2, 0, 1, 2};
//path to the directory the logo are in ! including leading AND trailing / !
char logopath[64] = "/logos/";
// templogopath is used to hold the complete path of an image. It is empty for now.
char templogopath[64] = "";
// Struct to hold the logos per screen
struct Logos
{
char logo0[32];
char logo1[32];
char logo2[32];
char logo3[32];
char logo4[32];
char logo5[32];
};
// Struct Action: 3 actions and 3 values per button
struct Actions
{
uint8_t action0;
uint8_t value0;
char symbol0[64];
uint8_t action1;
uint8_t value1;
char symbol1[64];
uint8_t action2;
uint8_t value2;
char symbol2[64];
};
// Each button has an action struct in it
struct Button
{
struct Actions actions;
bool latch;
char latchlogo[32];
};
// Each menu has 6 buttons
struct Menu
{
struct Button button0;
struct Button button1;
struct Button button2;
struct Button button3;
struct Button button4;
struct Button button5;
};
// Struct to hold the general logos.
struct Generallogos
{
char homebutton[64];
char configurator[64];
};
//Struct to hold the general config like colours.
struct Config
{
uint16_t menuButtonColour;
uint16_t functionButtonColour;
uint16_t backgroundColour;
uint16_t latchedColour;
bool sleepenable;
uint16_t sleeptimer;
bool beep;
uint8_t modifier1;
uint8_t modifier2;
uint8_t modifier3;
uint16_t helperdelay;
};
struct Wificonfig
{
char ssid[64];
char password[64];
char wifimode[9];
char hostname[64];
uint8_t attempts;
uint16_t attemptdelay;
};
// Array to hold all the latching statuses
bool islatched[30] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
// Create instances of the structs
Wificonfig wificonfig;
Config generalconfig;
Generallogos generallogo;
Logos screen0;
Logos screen1;
Logos screen2;
Logos screen3;
Logos screen4;
Logos screen5;
Logos screen6;
Menu menu1;
Menu menu2;
Menu menu3;
Menu menu4;
Menu menu5;
Menu menu6;
unsigned long previousMillis = 0;
unsigned long Interval = 0;
bool displayinginfo;
char* jsonfilefail = "";
// Invoke the TFT_eSPI button class and create all the button objects
TFT_eSPI_Button key[6];
//--------- Internal references ------------
// (this needs to be below all structs etc..)
#include "ScreenHelper.h"
#include "ConfigLoad.h"
#include "DrawHelper.h"
#include "ConfigHelper.h"
#include "UserActions.h"
#include "Action.h"
#include "Webserver.h"
#include "Touch.h"
void GetTouch() {
bool prevthing = pressed;
#ifdef GT911
ts.read();
bool pressed = ts.isTouched;
if (pressed) {
#ifndef GT911_Possible_Spam_Fix2
for (int i = 0; i < ts.touches; i++) {
t_x = ts.points[i].x;
t_y = ts.points[i].y;
}
#else
t_x = ts.points[0].x; //need to test this, might need to set it to 1 instead
t_y = ts.points[0].y;
#endif
}
#endif
#ifdef TouchDown
bool pressed = ts.touched();
if (pressed)
{
// Retrieve a point
TS_Point p = ts.getPoint();
//Flip things around so it matches our screen rotation
p.x = map(p.x, 0, 320, 320, 0);
t_y = p.x;
t_x = p.y;
}
#endif
#ifdef esp322432s028r
#ifndef XPT2046
bool pressed = touch.Pressed();//tft.getTouch( &touchX, &touchY, 600 );
if (pressed)
{
t_x = touch.X();
t_y = touch.Y();
/*Set the coordinates*/
//data->point.x = touchX;
//data->point.y = touchY;
//Serial.print( "Data x " );
//Serial.println( touchX );
//Serial.print( "Data y " );
//Serial.println( touchY );
// Retrieve a point
//TS_Point p = ts.getPoint();
//Flip things around so it matches our screen rotation
//p.x = map(p.x, 0, 320, 320, 0);
//t_y = p.x;
//t_x = p.y;
}
#endif
#ifdef XPT2046
pressed = (touch.touched());
if (pressed)
{
TS_Point p = touch.getPoint();
t_x = map(p.x, TOUCH_MAP_X1, TOUCH_MAP_X2, SCREEN_WIDTH - 1, 0);
t_y = map(p.y, TOUCH_MAP_Y1, TOUCH_MAP_Y2, 0, SCREEN_HEIGHT - 1);
#endif //XPT2046
#endif //esp322432s028r
#ifdef ResistiveTouch
pressed = tft.getTouch(&t_x, &t_y);
#endif
#ifdef SpamFix
if (prevthing) {
pressed = false;
}
#endif //Spamfix
}
}
void SetTouch() {
#ifdef GT911 //delay can be made lower, but that might cause the touch driver to not function
delay(300); //delay to prevent the touchscreen from not working right
ts.begin();
delay(300);
ts.reset();
delay(60);
ts.setRotation(TOUCH_ROTATION);
Serial.println("[INFO]: Capacitive touch started! (GT911)");
#endif
#ifdef TouchDown
#ifdef CUSTOM_TOUCH_SDA
if (!ts.begin(40, CUSTOM_TOUCH_SDA, CUSTOM_TOUCH_SCL))
#else
if (!ts.begin(40))
#endif // defined(CUSTOM_TOUCH_SDA)
{
Serial.println("[WARNING]: Unable to start the capacitive touchscreen.");
}
else
{
Serial.println("[INFO]: Capacitive touch started!");
}
#endif // defined(TouchDown)
#ifdef esp322432s028r
#ifndef XPT2046
/*Set the touchscreen calibration data,
the actual data for your display can be acquired using
the Generic -> Touch_calibrate example from the TFT_eSPI library*/
//uint16_t calData[] = { 456, 3608, 469, 272, 3625, 3582, 3518, 263, };
// tft.setTouchCalibrate(calData);//
// uint16_t calData[5] = { 275, 3620, 264, 3532, 1 };
// tft.setTouch( calData );
touch.setCal(526, 3443, 750, 3377, 320, 240, 1);
#endif
#ifdef XPT2046
mySpi.begin(XPT2046_CLK, XPT2046_MISO, XPT2046_MOSI, XPT2046_CS);
touch.begin(mySpi);
touch.setRotation(1);
#endif
#endif // defined(esp322432s028r)
}
void ExtraThings() {
#ifdef AUTO_BRIGHTNESS
pinMode(LIGHT_SENSOR, ANALOG);
analogSetPinAttenuation(LIGHT_SENSOR, ADC_0db); // 0dB(1.0) 0~800mV
iLastLightLevel = analogReadMilliVolts(LIGHT_SENSOR);
#endif
}
//-------------------------------- SETUP --------------------------------------------------------------
void setup()
{
// Use serial port
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println("");
Serial.println("[INFO]: Loading saved brightness state");
savedStates.begin("ftd", false);
ledBrightness = savedStates.getInt("ledBrightness", 255);
Serial.println("[INFO]: Reading latch stated back from memory:");
savedStates.getBytes("latched", islatched, sizeof(islatched));
for (int i = 0; i < sizeof(islatched); i++) {
Serial.print(islatched[i]);
}
Serial.println("");
SetTouch();
ExtraThings();
// --------------- Init Display -------------------------
// Initialise the TFT screen
tft.init();
// Set the rotation before we calibrate
tft.setRotation(1);
// Clear the screen
tft.fillScreen(TFT_BLACK);
esp_sleep_wakeup_cause_t wakeup_reason;
wakeup_reason = esp_sleep_get_wakeup_cause();
// Setup PWM channel and attach pin bl_pin
ledcSetup(0, 5000, 8);
#ifdef TFT_BL
ledcAttachPin(TFT_BL, 0);
#else
ledcAttachPin(backlightPin, 0);
#endif // defined(TFT_BL)
ledcWrite(0, ledBrightness); // Start @ initial Brightness
// -------------- Start filesystem ----------------------
if (!FILESYSTEM.begin())
{
Serial.println("[ERROR]: FILESYSTEM initialisation failed!");
drawErrorMessage("Failed to init FILESYSTEM! Did you upload the data folder?");
while (1)
yield(); // We stop here
}
Serial.println("[INFO]: FILESYSTEM initialised.");
// Check for free space
Serial.print("[INFO]: Free Space: ");
Serial.println(FILESYSTEM.totalBytes() - FILESYSTEM.usedBytes());
//------------------ Load Wifi Config ----------------------------------------------
Serial.println("[INFO]: Loading Wifi Config");
if (!loadMainConfig())
{
Serial.println("[WARNING]: Failed to load WiFi Credentials!");
}
else
{
Serial.println("[INFO]: WiFi Credentials Loaded");
}
// ----------------- Load webserver ---------------------
handlerSetup();
// ------------------- Splash screen ------------------
// If we are woken up we do not need the splash screen
if (wakeup_reason > 0)
{
// But we do draw something to indicate we are waking up
tft.setTextFont(2);
tft.println(" Waking up...");
}
else
{
// Draw a splash screen
drawBmp("/logos/freetouchdeck_logo.bmp", 0, 0);
tft.setCursor(1, 3);
tft.setTextFont(2);
tft.setTextSize(1);
tft.setTextColor(TFT_WHITE, TFT_BLACK);
tft.printf("Loading version %s\n", versionnumber);
Serial.printf("[INFO]: Loading version %s\n", versionnumber);
}
// Calibrate the touch screen and retrieve the scaling factors
#ifdef ResistiveTouch
Serial.println("[INFO]: Waiting for touch calibration...");
touch_calibrate();
Serial.println("[INFO]: Touch calibration completed!");
#endif // !defined(ResistiveTouch)
// Let's first check if all the files we need exist
if (!checkfile("/config/general.json"))
{
Serial.println("[ERROR]: /config/general.json not found!");
while (1)
yield(); // Stop!
}
if (!checkfile("/config/homescreen.json"))
{
Serial.println("[ERROR]: /config/homescreen.json not found!");
while (1)
yield(); // Stop!
}
if (!checkfile("/config/menu1.json"))
{
Serial.println("[ERROR]: /config/menu1.json not found!");
while (1)
yield(); // Stop!
}
if (!checkfile("/config/menu2.json"))
{
Serial.println("[ERROR]: /config/menu2.json not found!");
while (1)
yield(); // Stop!
}
if (!checkfile("/config/menu3.json"))
{
Serial.println("[ERROR]: /config/menu3.json not found!");
while (1)
yield(); // Stop!
}
if (!checkfile("/config/menu4.json"))
{
Serial.println("[ERROR]: /config/menu4.json not found!");
while (1)
yield(); // Stop!
}
if (!checkfile("/config/menu5.json"))
{
Serial.println("[ERROR]: /config/menu5.json not found!");
while (1)
yield(); // Stop!
}
// After checking the config files exist, actually load them
if (!loadConfig("general")) {
Serial.println("[WARNING]: general.json seems to be corrupted!");
Serial.println("[WARNING]: To reset to default type 'reset general'.");
jsonfilefail = "general";
pageNum = 10;
}
// Setup PWM channel for Piezo speaker
#ifdef speakerPin
ledcSetup(2, 500, 8);
if (generalconfig.beep) {
ledcAttachPin(speakerPin, 2);
ledcWriteTone(2, 600);
delay(150);
ledcDetachPin(speakerPin);
ledcWrite(2, 0);
ledcAttachPin(speakerPin, 2);
ledcWriteTone(2, 800);
delay(150);
ledcDetachPin(speakerPin);
ledcWrite(2, 0);
ledcAttachPin(speakerPin, 2);
ledcWriteTone(2, 1200);
delay(150);
ledcDetachPin(speakerPin);
ledcWrite(2, 0);
}
#endif // defined(speakerPin)
if (!loadConfig("homescreen")) {
Serial.println("[WARNING]: homescreen.json seems to be corrupted!");
Serial.println("[WARNING]: To reset to default type 'reset homescreen'.");
jsonfilefail = "homescreen";
pageNum = 10;
}
if (!loadConfig("menu1")) {
Serial.println("[WARNING]: menu1.json seems to be corrupted!");
Serial.println("[WARNING]: To reset to default type 'reset menu1'.");
jsonfilefail = "menu1";
pageNum = 10;
}
if (!loadConfig("menu2")) {
Serial.println("[WARNING]: menu2.json seems to be corrupted!");
Serial.println("[WARNING]: To reset to default type 'reset menu2'.");
jsonfilefail = "menu2";
pageNum = 10;
}
if (!loadConfig("menu3")) {
Serial.println("[WARNING]: menu3.json seems to be corrupted!");
Serial.println("[WARNING]: To reset to default type 'reset menu3'.");
jsonfilefail = "menu3";
pageNum = 10;
}
if (!loadConfig("menu4")) {
Serial.println("[WARNING]: menu4.json seems to be corrupted!");
Serial.println("[WARNING]: To reset to default type 'reset menu4'.");
jsonfilefail = "menu4";
pageNum = 10;
}
if (!loadConfig("menu5")) {
Serial.println("[WARNING]: menu5.json seems to be corrupted!");
Serial.println("[WARNING]: To reset to default type 'reset menu5'.");
jsonfilefail = "menu5";
pageNum = 10;
}
Serial.println("[INFO]: All configs loaded");
strcpy(generallogo.homebutton, "/logos/home.bmp");
strcpy(generallogo.configurator, "/logos/wifi.bmp");
Serial.println("[INFO]: General logos loaded.");
// Setup the Font used for plain text
tft.setFreeFont(LABEL_FONT);
//------------------BLE Initialization ------------------------------------------------------------------------
#if defined(USEUSBHID)
// initialize control over the keyboard:
bleKeyboard.begin();
USB.begin();
#else
Serial.println("[INFO]: Starting BLE");
bleKeyboard.begin();
#endif //if defined(USEUSBHID)
// ---------------- Printing version numbers -----------------------------------------------
#if defined(USEUSBHID)
Serial.println("[INFO]: Using USB Keyboard");
#else
Serial.print("[INFO]: BLE Keyboard version: ");
Serial.println(BLE_KEYBOARD_VERSION);
#endif //if defined(USEUSBHID)
Serial.print("[INFO]: ArduinoJson version: ");
Serial.println(ARDUINOJSON_VERSION);
Serial.print("[INFO]: TFT_eSPI version: ");
Serial.println(TFT_ESPI_VERSION);
// ---------------- Start the first keypad -------------
// Draw background
tft.fillScreen(generalconfig.backgroundColour);
// Draw keypad
Serial.println("[INFO]: Drawing keypad");
drawKeypad();
#ifdef touchInterruptPin
if (generalconfig.sleepenable)
{
pinMode(touchInterruptPin, INPUT_PULLUP);
Interval = generalconfig.sleeptimer * 60000;
Serial.println("[INFO]: Sleep enabled.");
Serial.print("[INFO]: Sleep timer = ");
Serial.print(generalconfig.sleeptimer);
Serial.println(" minutes");
islatched[28] = 1;
}
#endif // defined(touchInterruptPin)
Serial.println("[INFO]: Boot completed and successful!");
}
//--------------------- LOOP ---------------------------------------------------------------------
void loop(void)
{
#ifdef LONGER_DELAY
delay(30); // seemed to help some problems with the touchscreen
#endif // defined(LONGER_DELAY)
#ifdef AUTO_BRIGHTNESS
// Check if there is data available on the serial input that needs to be handled.
char sLightLevel[32];
// change brightness if light level changed
int iNewLightLevel = analogReadMilliVolts(LIGHT_SENSOR);
if ((iNewLightLevel > (iLastLightLevel + iLightTolerance)) || (iNewLightLevel < (iLastLightLevel - iLightTolerance))) {
snprintf_P(sLightLevel, sizeof(sLightLevel), PSTR("{\"light\":%d}"), iNewLightLevel);
//dispatch_state_subtopic("light",sLightLevel);
if (iNewLightLevel > 1020) {
iNewLightLevel = 1020;
}
iLastLightLevel = iNewLightLevel;
OffsetLightLevel = 255 - iNewLightLevel / 4;
//ConvertedLightLevel = OffsetLightLevel * 0.25; // 0.2490234375
//ConvertedLightLevel = iNewLightLevel * 0.25 - AutoOffset; // 0.2490234375
ConvertedLightLevel = OffsetLightLevel - AutoOffset; // 25.5
//ConvertedLightLevel = 255 - OffsetLightLevel;
/*
#ifdef DEBUG
Serial.println(' '); Serial.print("Light level sensor: "); Serial.print(iNewLightLevel); Serial.println(' ');
Serial.println(' '); Serial.print("Light level sensor offset: "); Serial.print(OffsetLightLevel); Serial.println(' ');
Serial.println(' '); Serial.print("Light level converted: "); Serial.print(ConvertedLightLevel); Serial.println(' ');
#endif
*/
ledBrightness = ConvertedLightLevel;
if (ledBrightness > 255) {
ledBrightness = 255;
}
else {
if (ledBrightness < 10) {
ledBrightness = 10;
}
}
/*
#ifdef DEBUG
Serial.println(' '); Serial.print("Light level: "); Serial.print(brightness_l); Serial.println(' ');
#endif
#ifdef smooth
if (iLastBrightness >= brightness_l){
for (int i = iLastBrightness; i >= brightness_l; i = i - iLightTolerance){