-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathWiPhone.ino
More file actions
2241 lines (1942 loc) · 79.6 KB
/
WiPhone.ino
File metadata and controls
2241 lines (1942 loc) · 79.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright © 2019, 2020, 2021, 2022, 2023 HackEDA, Inc.
Licensed under the WiPhone Public License v.1.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at
https://wiphone.io/WiPhone_Public_License_v1.0.txt.
Unless required by applicable law or agreed to in writing, software,
hardware or documentation distributed under the License is distributed
on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
//check version of SDK
#if __has_include(<WiPhone.h>)
#include <WiPhone.h>
#if WIPHONE_SDK_VER < 1
#error "The installed WiPhone board definition is outdated. To use the current firmware, you need to upgrade the WiPhone Board definition to v0.1.3 or higher. Go to "Tools" > "Board" > "Boards Manager" to upgrade, or refer to the Technical Manual for instructions."
#endif
#else
#error "The installed WiPhone board definition is outdated and missing the WiPhone.h file. To use the current firmware, you need to upgrade the WiPhone Board definition to v0.1.3 or higher. Go to "Tools" > "Board" > "Boards Manager" to upgrade, or refer to the Technical Manual for instructions."
#endif
#include <dummy.h>
#include <HTTPClient.h>
#include <HTTPUpdate.h>
// TODO:
// - check WiFi before calling => checked so issue#69 is fixed
// - check if using strncpy correctly (does not terminate with a nul)
#include "esp32-hal.h"
#include <stdio.h>
#include "GUI.h"
#include "tinySIP.h"
#include "WiPhoneConfig.h"
#include "WiPhone.h"
#include "clock.h"
#include "Audio.h"
#include "lwip/api.h"
#include <WiFi.h>
#include "Networks.h"
#include "esp_log.h"
#include <Update.h>
#include "ota.h"
#include "lora.h"
#include "esp_ota_ops.h"
#include "Test.h"
#include <esp_wifi.h>
#include "ErrorsPopupStrings.h"
void powerOff();
static bool been_in_verify = false;
extern bool wifiOn;
#ifndef WIPHONE_PRODUCTION
#include "Test.h"
#endif
//#define UDP_SIP no need this here
extern "C" bool verifyOta() {
log_d("In verify ota");
been_in_verify = true;
return true;
}
static Ota ota("");
GUI gui;
extern uint32_t chipId;
#ifdef LORA_MESSAGING
/*static*/ Lora lora;
#endif
// # # # # # # # # # # # # # # # # # # # # # # # # # # # # PERIPHERALS # # # # # # # # # # # # # # # # # # # # # # # # # # # #
SN7326 keypad(SN7326_I2C_ADDR_BASE, I2C_SDA_PIN, I2C_SCK_PIN);
CW2015 gauge(CW2015_I2C_ADDR, I2C_SDA_PIN, I2C_SCK_PIN);
#if defined(MOTOR_DRIVER) && MOTOR_DRIVER == 8833
DRV8833 motorDriver = DRV8833();
#endif
#ifdef USER_SERIAL
HardwareSerial userSerial(2);
int userSerialLastSize = 0;
#endif
#ifdef USE_VIRTUAL_KEYBOARD
WiFiUDP *udpKeypad = NULL;
#endif
// # # # # # # # # # # # # # # # # # # # # # # # # # # # # I2S AUDIO # # # # # # # # # # # # # # # # # # # # # # # # # # # #
Audio* audio;
void audio_test() {
log_e("AUDIO TEST");
if (audio->start()) {
log_d("audio: started");
audio->playRingtone(&SPIFFS);
//audio->playFile(&SPIFFS, "/ringtone.mp3");
} else {
log_e("audio: failed");
}
}
/* Description:
* Setup ringtone playback and vibration motor.
* For the ringtone to work, SPIFFS should have two files:
* ringtone.mp3
* - VERY preferably 16 KHz (or less) audio file
* ringtone.ini
* - INI file (compatible with NanoINI) which allows three configurations:
* - "vibro_on" - time the vibration motor is ON at a time, milliseconds
* - "vibro_off" - time the vibration motor is OFF at a time, milliseconds
* - "delay" - delay before the vibration motor turn ON for the first time, milliseconds
* TODO: generate both files if they are absent
*/
void startRingtone() {
// Start audio
audio->start();
// Start playing ringtone
if (!audio->playRingtone(&SPIFFS)) {
log_d("ERROR: could not play file in SPIFFS");
}
// Initialize vibrating
gui.state.vibroOn = false;
gui.state.vibroToggledMs = millis();
// Default configuration
gui.state.vibroOnPeriodMs = 500;
gui.state.vibroOffPeriodMs = 2500;
gui.state.vibroDelayMs = gui.state.vibroOnPeriodMs + gui.state.vibroOffPeriodMs;
gui.state.vibroNextDelayMs = gui.state.vibroDelayMs;
// Initialize the keyboard LED and motor: both OFF
allDigitalWrite(VIBRO_MOTOR_CONTROL, LOW);
allDigitalWrite(KEYBOARD_LED, HIGH);
// Load vibromotor configuration
IniFile ini("/ringtone.ini");
if (ini.load() && !ini.isEmpty()) {
gui.state.vibroOnPeriodMs = ini[0].getIntValueSafe("vibro_on", gui.state.vibroOnPeriodMs);
gui.state.vibroOffPeriodMs = ini[0].getIntValueSafe("vibro_off", gui.state.vibroOffPeriodMs);
gui.state.vibroDelayMs = ini[0].getIntValueSafe("delay", gui.state.vibroOnPeriodMs + gui.state.vibroOffPeriodMs);
gui.state.vibroNextDelayMs = gui.state.vibroDelayMs;
log_d("vibro on = %d", gui.state.vibroOnPeriodMs);
log_d("vibro off = %d", gui.state.vibroOffPeriodMs);
log_d("vibro delay = %d", gui.state.vibroDelayMs);
}
// Kickstart ringing
gui.state.ringing = true;
}
/* Description:
* ringtone stops ringing in two cases:
* 1) user reacted: accepted or declined an incoming call
* 2) incoming call got cancelled before user reacted
*/
void stopRingtone() {
audio->shutdown();
gui.state.ringing = false;
gui.state.vibroOn = false;
allDigitalWrite(VIBRO_MOTOR_CONTROL, LOW);
//allDigitalWrite(KEYBOARD_LED, HIGH);
}
// # # # # # # # # # # # # # # # # # # # # # # # # # # # # HEADPHONE INTERRUPT # # # # # # # # # # # # # # # # # # # # # # # # # # # #
volatile bool headphoneEvent = false;
void IRAM_ATTR headphoneInterrupt() {
headphoneEvent = true;
}
// Function that is called after interrupt occurs (not within interrupt)
void headphoneServiceInterrupt() {
#ifdef HEADPHONE_DETECT_PIN
bool headphones = allDigitalRead(HEADPHONE_DETECT_PIN);
#else
bool headphones = false; // TODO: maybe make headphone detect for version 1.3
#endif // HEADPHONE_DETECT_PIN
log_d("Headphones event = %d", headphones);
audio->setHeadphones(headphones);
headphoneEvent = false;
}
// # # # # # # # # # # # # # # # # # # # # # # # # # # # # KEYPAD INTERRUPT & PROCESSING # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#define KEYBOARD_BUFFER_LENGTH 13 // up to 12 keypresses can be remembered
volatile uint8_t keypadToRead = 0;
uint32_t keypadState = 0; // 32-bit mask for current state of buttons
RingBuffer<char> keypadBuff(KEYBOARD_BUFFER_LENGTH); // TODO: maybe used cbuf.h from ESP32 stack?
void IRAM_ATTR keyboardInterrupt() {
// This function is intentionally minimal
// (for example, adding a Serial output here produces ISR crashes)
keypadToRead = 1;
}
// Function that is called after interrupt occurs (not within interrupt)
// Connect to keypad scanners via I2C and decode the keyboard events into buffer keypadBuff
void keyboardRead() {
uint8_t key;
uint32_t mask;
uint32_t newState = 0;
char c;
do {
key = 0;
sn7326_err_t err = keypad.readKey(key);
if (err) {
log_d("keypad err code=%d", err);
}
if (err == SN7326_ERROR_BUSY) {
log_d("i2c reset");
keypad.reset(); // this seems to resolve rare event of complete hanging
}
// Decode lower 6 bits for character
switch (key & B111111) {
#ifndef WIPHONE_KEYBOARD
// 16-key stock keyboard
case B001011:
mask = WIPHONE_KEY_MASK_0;
break;
case B000000:
mask = WIPHONE_KEY_MASK_1;
break;
case B001000:
mask = WIPHONE_KEY_MASK_2;
break;
case B010000:
mask = WIPHONE_KEY_MASK_3;
break;
case B000001:
mask = WIPHONE_KEY_MASK_4;
break;
case B001001:
mask = WIPHONE_KEY_MASK_5;
break;
case B010001:
mask = WIPHONE_KEY_MASK_6;
break;
case B000010:
mask = WIPHONE_KEY_MASK_7;
break;
case B001010:
mask = WIPHONE_KEY_MASK_8;
break;
case B010010:
mask = WIPHONE_KEY_MASK_9;
break;
case B000011:
mask = WIPHONE_KEY_MASK_ASTERISK;
break;
case B010011:
mask = WIPHONE_KEY_MASK_HASH;
break;
case B011000:
mask = WIPHONE_KEY_MASK_UP;
break;
case B011001:
mask = WIPHONE_KEY_MASK_BACK;
break;
case B011010:
mask = WIPHONE_KEY_MASK_OK;
break;
case B011011:
mask = WIPHONE_KEY_MASK_DOWN;
break;
#else
// 25-key WiPhone keyboard layout
case B100001:
mask = WIPHONE_KEY_MASK_0;
break;
case B1000:
mask = WIPHONE_KEY_MASK_1;
break;
case B1001:
mask = WIPHONE_KEY_MASK_2;
break;
case B1010:
mask = WIPHONE_KEY_MASK_3;
break;
case B10000:
mask = WIPHONE_KEY_MASK_4;
break;
case B10001:
mask = WIPHONE_KEY_MASK_5;
break;
case B10010:
mask = WIPHONE_KEY_MASK_6;
break;
case B11000:
mask = WIPHONE_KEY_MASK_7;
break;
case B11001:
mask = WIPHONE_KEY_MASK_8;
break;
case B11010:
mask = WIPHONE_KEY_MASK_9;
break;
case B100000:
mask = WIPHONE_KEY_MASK_ASTERISK;
break;
case B100010:
mask = WIPHONE_KEY_MASK_HASH;
break;
case B10:
mask = WIPHONE_KEY_MASK_UP;
break;
case B100100:
mask = WIPHONE_KEY_MASK_BACK;
break;
case B10100:
mask = WIPHONE_KEY_MASK_OK;
break;
case B1:
mask = WIPHONE_KEY_MASK_DOWN;
break;
case B1100:
mask = WIPHONE_KEY_MASK_LEFT;
break;
case B11100:
mask = WIPHONE_KEY_MASK_RIFHT;
break;
case B100:
mask = WIPHONE_KEY_MASK_SELECT;
break;
case B0:
mask = WIPHONE_KEY_MASK_CALL;
break;
case B11:
mask = WIPHONE_KEY_MASK_END;
break;
case B1011:
mask = WIPHONE_KEY_MASK_F1;
break;
case B10011:
mask = WIPHONE_KEY_MASK_F2;
break;
case B11011:
mask = WIPHONE_KEY_MASK_F3;
break;
case B100011:
mask = WIPHONE_KEY_MASK_F4;
break;
#endif
default:
mask = 0; // unknown button detected
}
// Decode "pressed/released" bit
if (key & SN7326_PRESSED) {
if (!(keypadState & mask)) {
keypadState |= mask;
newState |= mask;
//Serial.print(c); Serial.println(" pressed");
// Process key if there is still space left in the key buffer
if (!keypadBuff.full()) {
switch (mask) {
case WIPHONE_KEY_MASK_0:
c = '0';
break;
case WIPHONE_KEY_MASK_1:
c = '1';
break;
case WIPHONE_KEY_MASK_2:
c = '2';
break;
case WIPHONE_KEY_MASK_3:
c = '3';
break;
case WIPHONE_KEY_MASK_4:
c = '4';
break;
case WIPHONE_KEY_MASK_5:
c = '5';
break;
case WIPHONE_KEY_MASK_6:
c = '6';
break;
case WIPHONE_KEY_MASK_7:
c = '7';
break;
case WIPHONE_KEY_MASK_8:
c = '8';
break;
case WIPHONE_KEY_MASK_9:
c = '9';
break;
case WIPHONE_KEY_MASK_ASTERISK:
c = '*';
break;
case WIPHONE_KEY_MASK_HASH:
c = '#';
break;
case WIPHONE_KEY_MASK_UP:
c = WIPHONE_KEY_UP;
break;
case WIPHONE_KEY_MASK_BACK:
c = WIPHONE_KEY_BACK;
break;
case WIPHONE_KEY_MASK_OK:
c = WIPHONE_KEY_OK;
break;
case WIPHONE_KEY_MASK_DOWN:
c = WIPHONE_KEY_DOWN;
break;
case WIPHONE_KEY_MASK_LEFT:
c = WIPHONE_KEY_LEFT;
break;
case WIPHONE_KEY_MASK_RIFHT:
c = WIPHONE_KEY_RIGHT;
break;
case WIPHONE_KEY_MASK_SELECT:
c = WIPHONE_KEY_SELECT;
break;
case WIPHONE_KEY_MASK_CALL:
c = WIPHONE_KEY_CALL;
break;
case WIPHONE_KEY_MASK_END:
c = WIPHONE_KEY_END;
break;
case WIPHONE_KEY_MASK_F1:
c = WIPHONE_KEY_F1;
break;
case WIPHONE_KEY_MASK_F2:
c = WIPHONE_KEY_F2;
break;
case WIPHONE_KEY_MASK_F3:
c = WIPHONE_KEY_F3;
break;
case WIPHONE_KEY_MASK_F4:
c = WIPHONE_KEY_F4;
break;
default:
c = 0;
}
if (c) {
keypadBuff.put(c);
}
}
}
} else {
if (keypadState & mask) {
keypadState &= ~mask;
//Serial.print(c); Serial.println(" released");
}
}
} while (key & SN7326_MORE); // decode "more" bit
keypadToRead = 0;
// Some buttons were "released" silently
if (newState < keypadState) {
keypadState = newState;
}
}
#ifdef USE_VIRTUAL_KEYBOARD
void keyboardUdpRead() {
if (udpKeypad && udpKeypad->parsePacket() > 0) {
char buff[1000];
int cb = udpKeypad->read(buff, sizeof(buff) - 1);
buff[cb] = 0;
//log_d("Keypad received: %s", buff);
for (int i = 0; i < cb && !keypadBuff.full(); i++) {
if (buff[i] == 10 || buff[i] == 13 || !buff[i]) {
continue;
}
keypadBuff.put(buff[i]);
}
}
}
#endif
// # # # # # # # # # # # # # # # # # # # # # # # # # # # # POWER/END BUTTON INTERRUPT # # # # # # # # # # # # # # # # # # # # # # # # # # # #
// Interrup routines to check for the power button presses, which is not connected to keypad scanner, but via a dedicated GPIO extender pin
bool powerButtonPressed = false;
bool poweringOff = false;
volatile bool gpioExtenderEvent = false;
void IRAM_ATTR gpioExtenderInterrupt() {
// This function is intentionally minimal
gpioExtenderEvent = true;
}
// Function that is called after interrupt occurs (not within interrupt)
bool gpioExtenderServiceInterrupt() {
gpioExtenderEvent = false;
bool powerButton = gpioExtender.digitalRead(POWER_CHECK & ~EXTENDER_FLAG) == LOW;
//log_d("powerButton = %d", powerButton);
if (powerButton != powerButtonPressed) {
powerButtonPressed = powerButton;
if (powerButton) {
keypadBuff.put(WIPHONE_KEY_END);
}
return true;
}
return false;
}
// # # # # # # # # # # # # # # # # # # # # # # # # # # # # SETUP # # # # # # # # # # # # # # # # # # # # # # # # # # # #
void setup() {
WiPhoneSetup();
log_i("\r\nChip id: %X %d %d", chipId, ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
log_i("Firmware version: %s", FIRMWARE_VERSION);
// Initialize I2C and wake up battery gauge first
gauge.connect();
#if defined(WIPHONE_BOARD) || defined(WIPHONE_INTEGRATED)
gui.state.gaugeInited = gauge.configure();
log_d("\r\nBattery gauge: %s\n", gui.state.gaugeInited ? "OK" : "FAILED");
delay(10);
#endif // WIPHONE_BOARD || WIPHONE_INTEGRATED
log_v("Free memory after gauge: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// Initialize GPIO extender
#ifdef WIPHONE_INTEGRATED_1_4
if (gpioExtender.begin()) {
log_v("extender succ");
gui.state.extenderInited = true;
// Input
allPinMode(POWER_CHECK, INPUT);
allPinMode(TF_CARD_DETECT_PIN, INPUT);
allPinMode(BATTERY_CHARGING_STATUS_PIN, INPUT);
// Output
allPinMode(KEYBOARD_LED, OUTPUT);
allPinMode(VIBRO_MOTOR_CONTROL, OUTPUT);
allPinMode(POWER_CONTROL, OUTPUT);
allPinMode(ENABLE_DAUGHTER_3V3, OUTPUT);
// Default state
allDigitalWrite(POWER_CONTROL, LOW);
allDigitalWrite(VIBRO_MOTOR_CONTROL, LOW);
allDigitalWrite(KEYBOARD_LED, HIGH);
} else {
log_d("extender failed");
gui.state.extenderInited = false;
}
#else // not WIPHONE_INTEGRATED_1_4
#ifdef WIPHONE_INTEGRATED_1_3
{
auto err = gpioExtender.config(
// Input pins
EXTENDER_PIN_FLAG_A2 | EXTENDER_PIN_FLAG_B1,
// Output HIGH
EXTENDER_PIN_FLAG_A0 | EXTENDER_PIN_FLAG_A2 | EXTENDER_PIN_FLAG_B0 | EXTENDER_PIN_FLAG_B1 | EXTENDER_PIN_FLAG_B7
);
if (err != SN7325_ERROR_OK) {
log_d("GPIO extender error = %d", err);
}
gpioExtender.showState();
}
#else // not WIPHONE_INTEGRATED_1_3
#ifdef WIPHONE_INTEGRATED_1
{
auto err = gpioExtender.config(
// Input pins
EXTENDER_PIN_FLAG_A2 | EXTENDER_PIN_FLAG_B1,
// Output HIGH
EXTENDER_PIN_FLAG_A0 | EXTENDER_PIN_FLAG_A1 | EXTENDER_PIN_FLAG_B0 | EXTENDER_PIN_FLAG_B1
);
if (err != SN7325_ERROR_OK) {
log_d("GPIO extender error = %d", err);
}
gui.state.extenderInited = (err == SN7325_ERROR_OK);
err = gpioExtender.setInterrupts(EXTENDER_PIN_FLAG_A2); // POWER_OFF interrupt
if (err != SN7325_ERROR_OK) {
log_d("GPIO extender error = %d", err);
}
gpioExtender.showState();
}
#endif // WIPHONE_INTEGRATED_1
#endif // WIPHONE_INTEGRATED_1_3
#endif // WIPHONE_INTEGRATED_1_4
log_v("Free memory after integrated: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// Fast test of PSRAM presence
void* p = heap_caps_malloc(100000, MALLOC_CAP_SPIRAM);
if (p != NULL) {
gui.state.psramInited = true;
freeNull((void **) &p);
}
log_v("Free memory after psram: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// Initialize power
#if defined(POWER_CONTROL) && POWER_CONTROL >= 0
allPinMode(POWER_CONTROL, OUTPUT);
allDigitalWrite(POWER_CONTROL, LOW);
#endif
log_v("Free memory after power: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
#if defined(POWER_CHECK) && POWER_CHECK >= 0
#ifdef WIPHONE_INTEGRATED_1_4
log_d("enabling interrupt (rev1.4)");
gpioExtender.enableInterrupt(2, FALLING);
#else // not WIPHONE_INTEGRATED_1_4
#ifdef WIPHONE_INTEGRATED_1_3
log_d("enabling interrupt input (rev1.3)");
allPinMode(POWER_CHECK, INPUT_PULLUP);
#endif // WIPHONE_INTEGRATED_1_3
#endif // WIPHONE_INTEGRATED_1_4
#endif // defined(POWER_CHECK) && POWER_CHECK >= 0
Random.feed(micros()); // TODO: maybe feed microphone data to Random.feed()
// Mounter internal filesystem
if (SPIFFS.begin(true)) {
log_d("SPI filesystem mounted");
} else {
log_d("SPI filesystem mount FAILED");
}
log_v("Free memory after internal fs: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// Initialize GUI
log_d("Initializing screen");
gui.init(lcdLedOnOff);
gui.redrawScreen(false, false, true); // only screen
log_v("Free memory after gui: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
#if LCD_LED_PIN >= 0
// Turn on backlight
log_d("LCD_LED_PIN = %d", LCD_LED_PIN);
allPinMode(LCD_LED_PIN, OUTPUT);
#if GPIO_EXTENDER == 1509
gpioExtender.ledDriverInit(LCD_LED_PIN ^ EXTENDER_FLAG);
#else
allPinMode(LCD_LED_PIN, OUTPUT);
#endif // GPIO_EXTENDER == 1509
gui.toggleScreen();
#endif
log_v("Free memory after lcd led: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// Mount SD card and SPIFFS (AFTER the screen & SPI initialization)
#if defined(WIPHONE_BOARD) || defined(WIPHONE_INTEGRATED)
// Init SD card detection pin
allPinMode(TF_CARD_DETECT_PIN, INPUT);
// Initilize hardware serial:
gui.state.battVoltage = gauge.readVoltage();
gui.state.battSoc = gauge.readSocPrecise();
log_d("Voltage = %.2f", gui.state.battVoltage);
log_d("SOC = %.1f", gui.state.battSoc);
#endif // WIPHONE_BOARD || WIPHONE_INTEGRATED
log_v("Free memory after sd spiffs: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// If voltage is extremely low, power off immediately
if (gui.state.battVoltage < 3.1) {
powerOff();
gui.processEvent(millis(), POWER_OFF_EVENT);
}
// INITIALIZE OTHER I2C DEVICES
// Battery gauge
#if defined(WIPHONE_BOARD) || defined(WIPHONE_INTEGRATED)
gauge.showVersion();
#endif // WIPHONE_BOARD
// Mount SD card
if (SD.begin(SD_CARD_CS_PIN, SPI, SD_CARD_FREQUENCY)) {
log_d("Card mounted");
} /*else {
log_d("Card mount FAILED");
}*/
// Initialize keypad
{
//keypad.connect(); // sets I2C speed to 400 kHz (as per datasheet)
sn7326_err_t err = keypad.config();
if (err != SN7326_ERROR_OK) {
log_d("keypad error = %d", err);
}
gui.state.scannerInited = (err == SN7326_ERROR_OK);
}
log_v("Free memory after keypad: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// Initialize RMT peripheral to enable the amplifier
#ifdef WIPHONE_INTEGRATED_1_4
rmtTxInit(AMPLIFIER_SHUTDOWN, false);
#else
#ifdef WIPHONE_INTEGRATED_1_3
// ?
#endif // WIPHONE_INTEGRATED_1_3
#endif // WIPHONE_INTEGRATED_1_4
// Initialize audio systems (hardware codec and I2S peripheral)
#ifdef I2S_MCLK_GPIO0
{
// Use GPIO_0 for providing MCLK to the audio codec IC
//SET_PERI_REG_BITS(PIN_CTRL, CLK_OUT1, 0, CLK_OUT1_S); // esp-adf
PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO0_U, FUNC_GPIO0_CLK_OUT1); // esp-adf
REG_SET_FIELD(PIN_CTRL, CLK_OUT1, 0); // Source: https://esp32.com/viewtopic.php?t=1521
}
#endif // I2S_MCLK_GPIO0
log_v("Free memory after config files: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// GPIOs
#ifdef WIPHONE_INTEGRATED
pinMode(BATTERY_CHARGING_STATUS_PIN, INPUT);
pinMode(BATTERY_PPR_PIN, INPUT);
#endif // WIPHONE_INTEGRATED
#ifdef WIPHONE_BOARD
pinMode(BATTERY_CHARGING_STATUS_PIN, INPUT);
//pinMode(USB_POWER_DETECT_PIN, INPUT);
#endif // WIPHONE_BOARD
#if defined(KEYBOARD_RESET_PIN) && KEYBOARD_RESET_PIN > 0
pinMode(KEYBOARD_RESET_PIN, OUTPUT); // keypad RST
digitalWrite(KEYBOARD_RESET_PIN, HIGH); // no RST
delay(1); // 1 ms
digitalWrite(KEYBOARD_RESET_PIN, LOW); // RST
delay(1); // 1 ms
digitalWrite(KEYBOARD_RESET_PIN, HIGH); // no RST
#endif
pinMode(KEYBOARD_INTERRUPT_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(KEYBOARD_INTERRUPT_PIN), keyboardInterrupt, FALLING);
pinMode(GPIO_EXTENDER_INTERRUPT_PIN, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(GPIO_EXTENDER_INTERRUPT_PIN), gpioExtenderInterrupt, FALLING);
#if defined(MOTOR_DRIVER) && MOTOR_DRIVER == 8833
motorDriver.attachMotorA(AIN1, AIN2);
motorDriver.attachMotorB(BIN1, BIN2);
pinMode(MotorEN, OUTPUT);
digitalWrite(MotorEN, LOW);
#endif
//esp_pm_config_esp32_t conf = { RTC_CPU_FREQ_240M, 240, RTC_CPU_FREQ_80M, 10, true };
// esp_pm_config_esp32_t conf = { RTC_CPU_FREQ_240M, RTC_CPU_FREQ_80M, true };
// esp_err_t err;
// err = esp_pm_configure((const void*) &conf);
// log_d("Power management: %d", (int) err);
#ifdef USER_SERIAL
userSerial.begin(USER_SERIAL_BAUD, USER_SERIAL_CONFIG, USER_SERIAL_RX, USER_SERIAL_TX);
//allDigitalWrite(EXTENDER_PIN_B0, HIGH); // TODO: why do we do this?
#endif
printf("\r\nBooting...\r\n");
uint8_t mac[6];
wifiState.getMac(mac);
nvs_stats_t nvs_stats;
nvs_get_stats(NULL, &nvs_stats);
log_d("NVS stats: UsedEntries = %d, FreeEntries = %d, AllEntries = %d\n",
nvs_stats.used_entries, nvs_stats.free_entries, nvs_stats.total_entries);
gui.loadSettings();
gui.reloadMessages();
bool memtestresult = test_memory(1 /*100*/);
log_d("memtestresult: %d", memtestresult);
log_v("Free memory after reload messages: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
if (gui.state.dimming || gui.state.sleeping) {
uint32_t now = millis();
if (gui.state.doDimming()) {
gui.state.scheduleEvent(SCREEN_DIM_EVENT, now + gui.state.dimAfterMs*2);
}
if (gui.state.doSleeping()) {
gui.state.scheduleEvent(SCREEN_SLEEP_EVENT, now + gui.state.sleepAfterMs*2);
}
}
log_v("Free memory after gui sleeping: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
// Set thread priorities (NOTE: in FreeRTOS, tasks with higher priorities will always be exectuted first, unless they have nothing to do)
uint32_t mainThreadPrio = ESP_TASK_TCPIP_PRIO >> 1;
if (tskIDLE_PRIORITY >= mainThreadPrio) {
mainThreadPrio = tskIDLE_PRIORITY + 1;
}
log_i("lwIP thread priority: %d", ESP_TASK_TCPIP_PRIO);
log_i("Main loop thread priority: %d", mainThreadPrio);
log_i("Idle task priority: %d", tskIDLE_PRIORITY);
log_i("Tick period: %d ms", portTICK_PERIOD_MS);
vTaskPrioritySet(NULL, mainThreadPrio);
log_v("Free memory after vTaskPrioritySet: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
wifiState.init();
/*Check the wifi-on-off selection to disable the WiFi connection.*/
CriticalFile iniNetworks(Networks::filename);
if(iniNetworks.load() && !iniNetworks.isEmpty()) {
if(iniNetworks.hasSection("wifi") && iniNetworks["wifi"].hasKey("wifionoff")) {
wifiOn = (strncmp(iniNetworks["wifi"]["wifionoff"], "on", 2) == 0);
if (strncmp(iniNetworks["wifi"]["wifionoff"], "on", 2) == 0) {
log_v("Free memory after wifi init: %d %d", ESP.getFreeHeap(), heap_caps_get_free_size(MALLOC_CAP_32BIT));
if (!wifiState.hasPreferredSsid() ) {
wifiState.disable(); // if we don't have a saved SSID to connect to, turn off WiFi to save power
} else {
int counter = 0;
//lora.detachInterrupts(); we are in setup, so detach&attach no needed
wifiState.loadPreferred();
wifiState.connectToPreferred();
//lora.attachInterrupts();
while (!wifiState.isConnected() && ++counter < 5) {
log_d("Waiting for wifi: %d %d", counter, ESP.getFreeHeap());
//lora.detachInterrupts();
wifiState.connectToPreferred();
//lora.attachInterrupts();
if(!wifiState.isConnected()) {
delay(500);
}
}
backupWiFiConnected = wifiState.isConnected();
backupConnectedSsid = wifiState.ssid() ? strdup(wifiState.ssid()) : nullptr;
}
} else if ((strncmp(iniNetworks["wifi"]["wifionoff"], "off", 3) == 0) && (wifiState.hasPreferredSsid())) {
//lora.detachInterrupts();
wifiState.loadPreferred();
wifiState.connectToPreferred();
//lora.attachInterrupts();
wifiState.disable();
}
} else {
wifiOn = true; //TODO: what is the default state? Should be true for previous ini versions.
}
if(!wifiOn) {
esp_err_t err = esp_wifi_stop();
if(err != ESP_OK) {
log_e("WIFI cann't be stopped");
} else {
log_d("WIFI will be stopped");
wifiState.disable();
}
}
iniNetworks.unload();
}
log_d("WiFi State is %d",wifiState.isConnected());
if (wifiState.isConnected()) {
if (!ota.hasJustUpdated() && ota.userRequestedUpdate()) {
gui.drawOtaUpdate();
ota.doUpdate();
} else if (!ota.hasJustUpdated() && ota.updateExists() && (ota.autoUpdateEnabled() || ota.userRequestedUpdate())) {
gui.drawOtaUpdate();
ota.doUpdate();
}
ota.setUserRequestedUpdate(false);
}
static Audio audio_local(true, I2S_BCK_PIN, I2S_WS_PIN, I2S_MOSI_PIN, I2S_MISO_PIN);
audio = &audio_local;
gui.state.codecInited = !audio->error();
// Setup for LoRa messaging
#ifdef LORA_MESSAGING
// allDigitalWrite(ENABLE_DAUGHTER_3V3, LOW);
lora.setup();
#endif
// Load phone configs
{
CriticalFile ini(Storage::ConfigsFile);
ini.unload();
if ((ini.load() || ini.restore()) && !ini.isEmpty()) {
log_d("WiPhone init audio, time zn and screen from ini file");
if (ini[0].hasKey("v") && strcmp(ini[0]["v"], "1") == 0) { // check version of the file format
log_d("WiPhone init file check format is done");
// Load audio volume
if (ini.hasSection("audio")) {
int8_t speakerVol, headphonesVol, loudspeakerVol;
audio->getVolumes(speakerVol, headphonesVol, loudspeakerVol); // default values
speakerVol = ini["audio"].getIntValueSafe("speaker_vol", speakerVol);
headphonesVol = ini["audio"].getIntValueSafe("headphones_vol", headphonesVol);
loudspeakerVol = ini["audio"].getIntValueSafe("loudspeaker_vol", loudspeakerVol);
audio->setVolumes(speakerVol, headphonesVol, loudspeakerVol);
log_d("loaded volume: earpiece = %d dB, headphones = %d dB, loudspeaker = %d dB", speakerVol, headphonesVol, loudspeakerVol);
log_i("loaded volume: earpiece = %d dB, headphones = %d dB, loudspeaker = %d dB", speakerVol, headphonesVol, loudspeakerVol);
}
// Load timezone config
if (ini.hasSection("time")) {
float tz = ini["time"].getFloatValueSafe("zone", 0);
ntpClock.setTimeZone(tz);
}
// Load Lora settings
if (!ini.hasSection("lora")) {
// log_d("adding section `lora`");
// ini.addSection("lora");
// ini["lora"]["onOff"] = "On";
// ini["lora"]["freq"] = "915Mhz";
// ini["lora"]["resendUndelivereds"] = "No";
// ini.store();
lora.setOnOff(true);
lora.setFrequency((float)915.0 );// can be defined in a header
// log_d("WiPhone ini file corrupt or may be this the first boot");
// log_d("ini file load %d restore %d isempty %d>>>>>>", ini.load(), ini.restore(), ini.isEmpty());
// log_d("adding section `lora`");
// ini.addSection("lora");
// ini["lora"]["onOff"] = "On";
// ini["lora"]["freq"] = "915Mhz";
// lora.setSendUndelivereds(false);
} else {
log_d("Lora Section exist");
lora.setOnOff((strcmp(ini["lora"]["onOff"], "On") == 0) ? true : false);
lora.setFrequency((strcmp(ini["lora"]["freq"], "915Mhz") == 0) ? (float)915.0 : (float)868.0);// can be defined in a header
// lora.setSendUndelivereds((strcmp(ini["lora"]["resendUndelivereds"], "No") == 0) ? false : true);
}
// Load screen dimming & sleeping config
if (ini.hasSection("screen")) {
gui.state.brightLevel = ini["screen"].getIntValueSafe("bright_level", 100);
gui.state.dimming = ini["screen"].getIntValueSafe("dimming", 0) > 0;
gui.state.dimLevel = ini["screen"].getIntValueSafe("dim_level", 15);
gui.state.dimAfterMs = ini["screen"].getIntValueSafe("dim_after_s", 20)*1000;
gui.state.sleeping = ini["screen"].getIntValueSafe("sleeping", 0) > 0;
gui.state.sleepAfterMs = ini["screen"].getIntValueSafe("sleep_after_s", 30)*1000;
gui.state.screenBrightness = gui.state.brightLevel-1; // Forces the new brightness setting to be applied
gui.processEvent(0, 0); // Need to call gui event loop so brightness settings are applied
} else {
log_d("WiPhone no scrren settings in ini file" );
gui.state.brightLevel = 100;
gui.state.dimming = true;
gui.state.dimLevel = 15;
gui.state.dimAfterMs = 20000;
gui.state.sleeping = true;
gui.state.sleepAfterMs = 30000;
}
// Load keypad locking config
gui.state.locking = ini.hasSection("lock") ? ini["lock"].getIntValueSafe("lock_keyboard", 0) : 1;
}
} else { // any ini data that need to be exist when first boot should be put here
// lora.setOnOff(true);
// lora.setFrequency((float)915.0);// can be defined in a header
// log_d("WiPhone ini file corrupt or may be this the first boot");
// log_d("ini file load %d restore %d isempty %d>>>>>>", ini.load(), ini.restore(), ini.isEmpty());
// if (!ini.hasSection("lora")) {
// log_d("adding section `lora`");
// ini.addSection("lora");
// ini["lora"]["onOff"] = "On";
// ini["lora"]["freq"] = "915Mhz";
//ini["lora"]["resendUndelivereds"] = "No";
// ini.store();
// lora.setSendUndelivereds((strcmp(ini["lora"]["resendUndelivereds"], "No") == 0) ? false : true);
// }
}
gui.setAudio(audio);
}
#ifdef HEADPHONE_DETECT_PIN