-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFaces3Validation.cpp
More file actions
1681 lines (1566 loc) · 70.9 KB
/
Copy pathFaces3Validation.cpp
File metadata and controls
1681 lines (1566 loc) · 70.9 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
#ifdef ARDUINO
#include <Arduino.h>
#include <Wire.h>
#else
#include "driver/gpio.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "sdkconfig.h"
#endif
#include <M5Faces.h>
#include <M5FacesPoller.hpp>
#include <M5Unified.h>
#include <array>
#include <cstdarg>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <nvs.h>
#ifndef ARDUINO
static inline uint32_t millis()
{
return static_cast<uint32_t>(m5gfx::millis());
}
static inline void delay(uint32_t milliseconds)
{
m5gfx::delay(milliseconds);
}
template <typename T>
static inline T constrain(T value, T minimum, T maximum)
{
return value < minimum ? minimum : (value > maximum ? maximum : value);
}
#endif
#if (defined(ARDUINO_M5STACK_Core2) || defined(ARDUINO_M5STACK_CORE2)) && !defined(M5FACES_HOST_CORE2)
#define M5FACES_HOST_CORE2 1
#endif
#if defined(ARDUINO_M5STACK_CORES3) && !defined(M5FACES_HOST_CORES3)
#define M5FACES_HOST_CORES3 1
#endif
#ifndef M5FACES_VALIDATION_FW
#define M5FACES_VALIDATION_FW "ARDUINO2.9.0"
#endif
namespace {
constexpr uint32_t kI2CFreq = 400000;
#if defined(M5FACES_HOST_CORES3)
constexpr int kFacesSda = 12;
constexpr int kFacesScl = 11;
#else
constexpr int kFacesSda = 21;
constexpr int kFacesScl = 22;
#endif
constexpr uint8_t kAppAddress = M5FACES_BOTTOM3_ADDR;
constexpr uint8_t kBootAddress = 0x54;
constexpr size_t kMaxKeys = 35;
#if defined(M5FACES_HOST_CORES3)
constexpr int kHostTouchY = 220;
constexpr int kErrorTouchY = 202;
#endif
enum class RunState { waiting, testing, error };
enum class VersionDecision { up_to_date, update, unsupported };
struct FirmwareImage {
FirmwareImage() : size(0), target(0), variant(nullptr)
{
}
FirmwareImage(size_t size_in, uint8_t target_in, const char* variant_in)
: size(size_in), target(target_in), variant(variant_in)
{
}
size_t size;
uint8_t target;
const char* variant;
};
const char* const kCalcLabels[20] = {"AC", "M", "%", "/", "7", "8", "9", "X", "4", "5",
"6", "-", "1", "2", "3", "+", ".", "0", "-/+", "="};
const uint8_t kCalcCodes[20] = {'A', 'M', '%', '/', '7', '8', '9', '*', '4', '5',
'6', '-', '1', '2', '3', '+', '.', '0', '`', '='};
const char* const kGamepadLabels[8] = {"UP", "DOWN", "LEFT", "RIGHT", "A", "B", "SELECT", "START"};
const uint8_t kGamepadMasks[8] = {GAMEPAD3_BTN_UP, GAMEPAD3_BTN_DOWN, GAMEPAD3_BTN_LEFT, GAMEPAD3_BTN_RIGHT,
GAMEPAD3_BTN_A, GAMEPAD3_BTN_B, GAMEPAD3_BTN_SELECT, GAMEPAD3_BTN_START};
const char* const kKeyboardLabels[35] = {"Q", "W", "E", "R", "T", "Y", "U", "I", "O", "P", "A", "S",
"D", "F", "G", "H", "J", "K", "L", "DEL", "ALT", "Z", "X", "C",
"V", "B", "N", "M", "$", "ENT", "aA", "0", "SPC", "SYM", "FN"};
M5Faces_Calculator3 g_calculator;
M5Faces_Gamepad3 g_gamepad;
M5Faces_Keyboard3 g_keyboard;
M5FacesPoller g_poller;
RunState g_state = RunState::waiting;
uint8_t g_device_addr = kAppAddress;
uint8_t g_model = 0;
uint8_t g_fw = 0;
bool g_tested[kMaxKeys] = {};
bool g_pressed[kMaxKeys] = {};
bool g_drawn_tested[kMaxKeys] = {};
bool g_drawn_pressed[kMaxKeys] = {};
bool g_pass_logged = false;
bool g_auto_probe = true;
bool g_detect_error_logged = false;
bool g_test_screen_ready = false;
bool g_iap_screen_ready = false;
bool g_iap_pending = false;
bool g_iap_resume_verify = false;
uint8_t g_iap_pending_target = 0;
bool g_keyboard_uppercase = false;
bool g_keyboard_aa_down = false;
bool g_keyboard_layers[5] = {};
bool g_keyboard_normal_seen = false;
bool g_api_ready = false;
size_t g_api_passed = 0;
size_t g_api_total = 0;
m5faces_mode_t g_input_mode = M5FACES_MODE_NORMAL;
uint8_t g_last_calc_key = 0;
uint32_t g_last_probe_ms = 0;
char g_status[128] = "Waiting for Faces3";
char g_uid_text[M5FACES_DEVICE_UID_SIZE * 2 + 1] = "Not read";
void log_pt(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vprintf(fmt, args);
va_end(args);
printf("\n");
}
void set_status(const char* fmt, ...)
{
va_list args;
va_start(args, fmt);
vsnprintf(g_status, sizeof(g_status), fmt, args);
va_end(args);
}
const char* model_name()
{
return M5FacesBase::modelName(g_model);
}
size_t key_count()
{
if (g_model == M5Faces_Calculator3::MODEL_ID) return 20;
if (g_model == M5Faces_Gamepad3::MODEL_ID) return 8;
if (g_model == M5Faces_Keyboard3::MODEL_ID) return 35;
return 0;
}
const char* key_label(size_t index)
{
if (g_model == M5Faces_Calculator3::MODEL_ID) return kCalcLabels[index];
if (g_model == M5Faces_Gamepad3::MODEL_ID) return kGamepadLabels[index];
return kKeyboardLabels[index];
}
size_t tested_count()
{
size_t count = 0;
for (size_t i = 0; i < key_count(); ++i) count += g_tested[i] ? 1U : 0U;
return count;
}
M5FacesBase* active_driver()
{
if (g_model == M5Faces_Calculator3::MODEL_ID) return &g_calculator;
if (g_model == M5Faces_Gamepad3::MODEL_ID) return &g_gamepad;
if (g_model == M5Faces_Keyboard3::MODEL_ID) return &g_keyboard;
return nullptr;
}
size_t keyboard_feature_count()
{
size_t count = g_keyboard_normal_seen ? 1U : 0U;
for (bool tested : g_keyboard_layers) count += tested ? 1U : 0U;
return count;
}
bool api_check(const char* name, bool passed, const char* detail = nullptr)
{
++g_api_total;
if (passed) ++g_api_passed;
log_pt("FV_API name=%s result=%s%s%s", name, passed ? "PASS" : "FAIL", detail ? " detail=" : "",
detail ? detail : "");
if (!passed) set_status("API check failed: %s", name);
return passed;
}
bool runtime_check(const char* name, bool passed)
{
log_pt("FV_RUNTIME_API name=%s result=%s", name, passed ? "PASS" : "FAIL");
if (!passed) {
g_api_ready = false;
set_status("Runtime API failed: %s", name);
}
return passed;
}
bool probe(uint8_t address)
{
return M5.In_I2C.scanID(address, kI2CFreq);
}
bool wait_for_address(uint8_t address, uint32_t timeout_ms)
{
const uint32_t start = millis();
while (millis() - start < timeout_ms) {
if (probe(address)) return true;
delay(100);
}
return false;
}
struct IapPendingRecord {
uint8_t model = 0;
uint8_t target = 0;
uint8_t address = 0;
};
struct AddressRecoveryRecord {
uint8_t model = 0;
uint8_t original = 0;
uint8_t temporary = 0;
};
bool load_address_recovery(AddressRecoveryRecord& record)
{
nvs_handle_t handle = 0;
if (nvs_open("M5FacesIAP", NVS_READONLY, &handle) != ESP_OK) return false;
const bool loaded = nvs_get_u8(handle, "addr_model", &record.model) == ESP_OK &&
nvs_get_u8(handle, "addr_orig", &record.original) == ESP_OK &&
nvs_get_u8(handle, "addr_temp", &record.temporary) == ESP_OK;
nvs_close(handle);
return loaded;
}
bool save_address_recovery(uint8_t model, uint8_t original, uint8_t temporary)
{
nvs_handle_t handle = 0;
if (nvs_open("M5FacesIAP", NVS_READWRITE, &handle) != ESP_OK) return false;
esp_err_t result = nvs_set_u8(handle, "addr_model", model);
if (result == ESP_OK) result = nvs_set_u8(handle, "addr_orig", original);
if (result == ESP_OK) result = nvs_set_u8(handle, "addr_temp", temporary);
if (result == ESP_OK) result = nvs_commit(handle);
nvs_close(handle);
return result == ESP_OK;
}
bool clear_address_recovery()
{
nvs_handle_t handle = 0;
const esp_err_t open_result = nvs_open("M5FacesIAP", NVS_READWRITE, &handle);
if (open_result == ESP_ERR_NVS_NOT_FOUND) return true;
if (open_result != ESP_OK) return false;
const char* keys[] = {"addr_model", "addr_orig", "addr_temp"};
esp_err_t result = ESP_OK;
for (const char* key : keys) {
if (result != ESP_OK) break;
result = nvs_erase_key(handle, key);
if (result == ESP_ERR_NVS_NOT_FOUND) result = ESP_OK;
}
if (result == ESP_OK) result = nvs_commit(handle);
nvs_close(handle);
return result == ESP_OK;
}
bool load_iap_pending(IapPendingRecord& record)
{
nvs_handle_t handle = 0;
if (nvs_open("M5FacesIAP", NVS_READONLY, &handle) != ESP_OK) return false;
const bool loaded = nvs_get_u8(handle, "model", &record.model) == ESP_OK &&
nvs_get_u8(handle, "target", &record.target) == ESP_OK &&
nvs_get_u8(handle, "address", &record.address) == ESP_OK;
nvs_close(handle);
return loaded;
}
bool save_iap_pending(uint8_t model, uint8_t target, uint8_t address)
{
nvs_handle_t handle = 0;
if (nvs_open("M5FacesIAP", NVS_READWRITE, &handle) != ESP_OK) return false;
esp_err_t result = nvs_set_u8(handle, "model", model);
if (result == ESP_OK) result = nvs_set_u8(handle, "target", target);
if (result == ESP_OK) result = nvs_set_u8(handle, "address", address);
if (result == ESP_OK) result = nvs_commit(handle);
nvs_close(handle);
return result == ESP_OK;
}
bool load_iap_identity(uint8_t& model, uint8_t& address)
{
nvs_handle_t handle = 0;
if (nvs_open("M5FacesIAP", NVS_READONLY, &handle) != ESP_OK) return false;
const bool loaded =
nvs_get_u8(handle, "known_model", &model) == ESP_OK && nvs_get_u8(handle, "known_addr", &address) == ESP_OK;
nvs_close(handle);
return loaded;
}
bool save_iap_identity(uint8_t model, uint8_t address)
{
nvs_handle_t handle = 0;
if (nvs_open("M5FacesIAP", NVS_READWRITE, &handle) != ESP_OK) return false;
esp_err_t result = nvs_set_u8(handle, "known_model", model);
if (result == ESP_OK) result = nvs_set_u8(handle, "known_addr", address);
if (result == ESP_OK) result = nvs_commit(handle);
nvs_close(handle);
return result == ESP_OK;
}
bool clear_iap_pending()
{
nvs_handle_t handle = 0;
const esp_err_t open_result = nvs_open("M5FacesIAP", NVS_READWRITE, &handle);
if (open_result == ESP_ERR_NVS_NOT_FOUND) return true;
if (open_result != ESP_OK) return false;
esp_err_t result = nvs_erase_key(handle, "model");
if (result == ESP_ERR_NVS_NOT_FOUND) result = ESP_OK;
if (result == ESP_OK) {
result = nvs_erase_key(handle, "target");
if (result == ESP_ERR_NVS_NOT_FOUND) result = ESP_OK;
}
if (result == ESP_OK) {
result = nvs_erase_key(handle, "address");
if (result == ESP_ERR_NVS_NOT_FOUND) result = ESP_OK;
}
if (result == ESP_OK) result = nvs_commit(handle);
nvs_close(handle);
return result == ESP_OK;
}
bool recover_pending_address()
{
AddressRecoveryRecord record;
if (!load_address_recovery(record)) return true;
const bool record_valid =
record.model >= M5Faces_Calculator3::MODEL_ID && record.model <= M5Faces_Gamepad3::MODEL_ID &&
record.original >= 0x08 && record.original < 0x78 && record.temporary >= 0x08 && record.temporary < 0x78 &&
record.original != record.temporary && record.original != kBootAddress && record.temporary != kBootAddress;
if (!record_valid) {
set_status("Invalid address recovery record; clear NVS");
log_pt("FV_ERROR stage=address_recovery_record model=0x%02X original=0x%02X temporary=0x%02X", record.model,
record.original, record.temporary);
return false;
}
const bool original_present = probe(record.original);
const bool temporary_present = probe(record.temporary);
if (original_present && !temporary_present) {
const bool cleared = clear_address_recovery();
log_pt("FV_ADDR_RECOVERY state=already_restored original=0x%02X clear=%s", record.original,
cleared ? "PASS" : "FAIL");
return cleared;
}
if (!temporary_present || original_present) {
set_status("Address recovery device state is ambiguous");
log_pt("FV_ERROR stage=address_recovery_probe original=%d temporary=%d", original_present ? 1 : 0,
temporary_present ? 1 : 0);
return false;
}
M5FacesBase device;
uint8_t model = 0;
const bool restored = device.begin(&M5.In_I2C, record.temporary, M5FACES_I2C_FREQ_STANDARD) == M5FACES_OK &&
device.getModelID(&model) == M5FACES_OK && model == record.model &&
device.setI2CAddress(record.original) == M5FACES_OK &&
wait_for_address(record.original, 1000);
const bool cleared = restored && clear_address_recovery();
log_pt("FV_ADDR_RECOVERY state=restore model=0x%02X temporary=0x%02X original=0x%02X restore=%s clear=%s",
record.model, record.temporary, record.original, restored ? "PASS" : "FAIL", cleared ? "PASS" : "FAIL");
if (!cleared) set_status(restored ? "Address restored; recovery record clear failed" : "Address recovery failed");
return cleared;
}
uint8_t latest_version(uint8_t model)
{
if (model == M5Faces_Gamepad3::MODEL_ID) return 0x04;
if (model == M5Faces_Calculator3::MODEL_ID || model == M5Faces_Keyboard3::MODEL_ID) return 0x03;
return 0;
}
const char* latest_variant(uint8_t model)
{
return model == M5Faces_Gamepad3::MODEL_ID ? "V04" : "V03";
}
VersionDecision select_image(uint8_t model, uint8_t current, uint8_t forced_target, FirmwareImage& image)
{
const uint8_t target = latest_version(model);
if (target == 0) return VersionDecision::unsupported;
if (forced_target == 0 && current == target) return VersionDecision::up_to_date;
if (forced_target != 0 && forced_target != target) return VersionDecision::unsupported;
const faces_iap_fw_t fw = faces_iap_find_firmware(model, latest_variant(model));
const faces_iap_firmware_info_t* info = faces_iap_get_firmware_info(fw);
if (!info) return VersionDecision::unsupported;
image = FirmwareImage(info->size, target, info->variant_name);
return VersionDecision::update;
}
void draw_update_screen(const char* stage, int percent, const FirmwareImage& image, uint32_t color = TFT_YELLOW)
{
g_test_screen_ready = false;
M5.Display.startWrite();
char line[72];
if (!g_iap_screen_ready) {
M5.Display.fillScreen(TFT_BLACK);
M5.Display.setFont(&fonts::efontCN_16_b);
M5.Display.setTextDatum(textdatum_t::top_center);
M5.Display.setTextColor(TFT_YELLOW);
M5.Display.drawString("M5Faces3 Firmware Update", 160, 8);
snprintf(line, sizeof(line), "%s Current: 0x%02X", model_name(), g_fw);
M5.Display.setFont(&fonts::efontCN_16);
M5.Display.setTextColor(TFT_WHITE);
M5.Display.drawString(line, 160, 48);
snprintf(line, sizeof(line), "Target: 0x%02X Image: %s", image.target, image.variant);
M5.Display.drawString(line, 160, 76);
M5.Display.drawRoundRect(16, 150, 288, 24, 4, 0x5A5A5A);
M5.Display.setFont(&fonts::efontCN_12);
M5.Display.setTextDatum(textdatum_t::bottom_center);
M5.Display.setTextColor(0xBDBDBD);
M5.Display.drawString("Keep power and Faces connected", 160, 228);
g_iap_screen_ready = true;
}
M5.Display.fillRect(0, 104, 320, 28, TFT_BLACK);
M5.Display.setFont(&fonts::efontCN_16);
M5.Display.setTextDatum(textdatum_t::top_center);
M5.Display.setTextColor(color);
M5.Display.drawString(stage, 160, 108);
M5.Display.fillRect(18, 152, 284, 20, TFT_BLACK);
const int width = constrain(percent, 0, 100) * 284 / 100;
if (width > 0) M5.Display.fillRoundRect(18, 152, width, 20, 3, TFT_GREEN);
snprintf(line, sizeof(line), "%d%%", constrain(percent, 0, 100));
M5.Display.setTextDatum(textdatum_t::middle_center);
M5.Display.setTextColor(TFT_WHITE);
M5.Display.drawString(line, 160, 162);
M5.Display.endWrite();
}
void library_iap_progress(int percent, const char* status, void* ctx)
{
const FirmwareImage& image = *static_cast<const FirmwareImage*>(ctx);
const char* stage = percent >= 99 ? "Verifying" : (percent > 0 ? "Writing" : "Preparing");
draw_update_screen(stage, percent, image);
log_pt("IAP_LIBRARY_PROGRESS model=%s image=%s percent=%d status=%s", model_name(), image.variant, percent,
status ? status : "");
}
bool upgrade_firmware(const FirmwareImage& image)
{
g_iap_screen_ready = false;
draw_update_screen("Preparing", 0, image);
log_pt("IAP_START model=%s id=0x%02X from=0x%02X target=0x%02X image=%s bytes=%u", model_name(), g_model, g_fw,
image.target, image.variant, static_cast<unsigned>(image.size));
#ifdef ARDUINO
log_pt("IAP_BACKEND framework=Arduino api=faces_iap_upgrade_by_variant bus=M5.In_I2C");
const esp_err_t result =
faces_iap_upgrade_by_variant(&M5.In_I2C, g_model, image.variant, kFacesSda, kFacesScl, g_device_addr,
library_iap_progress, const_cast<FirmwareImage*>(&image));
#else
log_pt("IAP_BACKEND framework=ESP-IDF api=faces_iap_upgrade_by_variant bus=i2c_master");
const i2c_port_t port = M5.In_I2C.getPort();
M5.In_I2C.release();
delay(20);
i2c_master_bus_config_t bus_config = {};
bus_config.i2c_port = static_cast<i2c_port_num_t>(port);
bus_config.sda_io_num = static_cast<gpio_num_t>(kFacesSda);
bus_config.scl_io_num = static_cast<gpio_num_t>(kFacesScl);
bus_config.clk_source = I2C_CLK_SRC_DEFAULT;
bus_config.glitch_ignore_cnt = 7;
bus_config.flags.enable_internal_pullup = true;
i2c_master_bus_handle_t iap_bus = nullptr;
esp_err_t result = i2c_new_master_bus(&bus_config, &iap_bus);
if (result == ESP_OK) {
result = faces_iap_upgrade_by_variant(iap_bus, g_model, image.variant, static_cast<gpio_num_t>(kFacesSda),
static_cast<gpio_num_t>(kFacesScl), g_device_addr, library_iap_progress,
const_cast<FirmwareImage*>(&image));
i2c_del_master_bus(iap_bus);
}
const bool restored = M5.In_I2C.begin(port, kFacesSda, kFacesScl);
if (result == ESP_OK && !restored) result = ESP_FAIL;
#endif
if (result != ESP_OK) {
log_pt("IAP_LIBRARY_RESULT model=%s image=%s result=FAIL error=%s", model_name(), image.variant,
esp_err_to_name(result));
log_pt("FV_ERROR stage=iap_library model=%s error=%s", model_name(), esp_err_to_name(result));
return false;
}
log_pt("IAP_LIBRARY_RESULT model=%s image=%s result=PASS", model_name(), image.variant);
return true;
}
bool verify_device(uint8_t expected_version)
{
M5FacesBase device;
if (device.begin(&M5.In_I2C, g_device_addr, 100000) != M5FACES_OK) return false;
uint8_t model = 0;
uint8_t version = 0;
if (device.getFirmwareVersion(&version) != M5FACES_OK || device.getModelID(&model) != M5FACES_OK ||
version != expected_version)
return false;
if (model != g_model) return false;
uint8_t uid[M5FACES_DEVICE_UID_SIZE] = {};
if (device.getDeviceUID(uid) != M5FACES_OK) return false;
bool uid_has_data = false;
for (uint8_t value : uid) {
uid_has_data = uid_has_data || (value != 0x00 && value != 0xFF);
}
if (!uid_has_data) return false;
// The controlled Keyboard3 V03 image implements the 0xF0 operation-mode register.
if (g_model == M5Faces_Keyboard3::MODEL_ID) {
if (device.setMode(M5FACES_MODE_NORMAL) != M5FACES_OK) return false;
m5faces_mode_t mode = M5FACES_MODE_DIRECT;
if (device.getMode(&mode) != M5FACES_OK || mode != M5FACES_MODE_NORMAL) return false;
}
g_fw = version;
return true;
}
bool find_faces()
{
if (!recover_pending_address()) {
g_auto_probe = false;
return false;
}
g_iap_pending = false;
g_iap_resume_verify = false;
g_iap_pending_target = 0;
IapPendingRecord pending;
bool pending_loaded = load_iap_pending(pending);
const bool pending_shape_valid = pending.model >= M5Faces_Calculator3::MODEL_ID &&
pending.model <= M5Faces_Gamepad3::MODEL_ID && pending.address >= 0x08 &&
pending.address < 0x78 && pending.address != kBootAddress;
const uint8_t pending_latest = latest_version(pending.model);
const bool migratable_target =
pending.target == 0xF1 || (pending.model == M5Faces_Gamepad3::MODEL_ID && pending.target == 0x03);
if (pending_loaded && pending_shape_valid && migratable_target && pending.target != pending_latest) {
log_pt("IAP_PENDING_MIGRATE model=0x%02X old_target=0x%02X new_target=0x%02X addr=0x%02X", pending.model,
pending.target, pending_latest, pending.address);
pending.target = pending_latest;
if (!save_iap_pending(pending.model, pending.target, pending.address)) {
set_status("IAP recovery record migration failed");
log_pt("FV_ERROR stage=iap_pending_migrate model=0x%02X addr=0x%02X", pending.model, pending.address);
g_auto_probe = false;
return false;
}
}
if (pending_loaded && (!pending_shape_valid || pending.target != pending_latest)) {
set_status("Invalid IAP recovery record; clear NVS");
log_pt("FV_ERROR stage=iap_pending_invalid model=0x%02X target=0x%02X addr=0x%02X", pending.model,
pending.target, pending.address);
g_auto_probe = false;
return false;
}
uint8_t known_model = 0;
uint8_t known_address = 0;
bool identity_loaded = load_iap_identity(known_model, known_address);
if (identity_loaded && (known_model < M5Faces_Calculator3::MODEL_ID || known_model > M5Faces_Gamepad3::MODEL_ID ||
known_address < 0x08 || known_address >= 0x78 || known_address == kBootAddress)) {
log_pt("FV_WARN stage=iap_identity_invalid model=0x%02X addr=0x%02X", known_model, known_address);
identity_loaded = false;
}
auto inspect = [&](uint8_t address) {
if (address < 0x08 || address >= 0x78 || address == kBootAddress || !probe(address)) return false;
M5FacesBase device;
if (device.begin(&M5.In_I2C, address, 100000) != M5FACES_OK) return false;
uint8_t model = 0;
uint8_t version = 0;
const m5faces_err_t version_result = device.getFirmwareVersion(&version);
const m5faces_err_t model_result = device.getModelID(&model);
log_pt("FV_PROBE addr=0x%02X model_result=%d model=0x%02X fw_result=%d fw=0x%02X", address,
static_cast<int>(model_result), model, static_cast<int>(version_result), version);
if (model_result != M5FACES_OK || version_result != M5FACES_OK) return false;
const bool model_valid = model >= M5Faces_Calculator3::MODEL_ID && model <= M5Faces_Gamepad3::MODEL_ID;
if (!model_valid) {
if (version != 0xF1) return false;
if (pending_loaded)
model = pending.model;
else if (identity_loaded)
model = known_model;
else {
log_pt("FV_ERROR stage=legacy_identity_missing addr=0x%02X fw=0x%02X", address, version);
return false;
}
log_pt("FV_LEGACY_IDENTITY addr=0x%02X fw=0x%02X model_hint=0x%02X source=%s", address, version, model,
pending_loaded ? "pending" : "known");
}
g_device_addr = address;
g_model = model;
g_fw = version;
return true;
};
bool app_found = false;
const uint8_t candidates[] = {
static_cast<uint8_t>(pending_loaded ? pending.address : 0U),
static_cast<uint8_t>(identity_loaded ? known_address : 0U),
0x08,
0x09,
0x10,
};
for (size_t i = 0; i < sizeof(candidates); ++i) {
const uint8_t address = candidates[i];
bool duplicate = false;
for (size_t j = 0; j < i; ++j) duplicate = duplicate || candidates[j] == address;
if (duplicate) continue;
if (inspect(address)) {
app_found = true;
break;
}
}
if (app_found) {
if (!pending_loaded) return true;
if (pending.model != g_model) {
set_status("IAP record/device mismatch");
log_pt(
"FV_ERROR stage=iap_pending_model_mismatch stored_model=0x%02X current_model=0x%02X stored_addr=0x%02X "
"current_addr=0x%02X",
pending.model, g_model, pending.address, g_device_addr);
g_auto_probe = false;
return false;
}
if (pending.address != g_device_addr) {
if (!save_iap_pending(g_model, pending.target, g_device_addr)) {
set_status("Failed to save IAP address recovery record");
log_pt("FV_ERROR stage=iap_pending_address_save old_addr=0x%02X new_addr=0x%02X", pending.address,
g_device_addr);
g_auto_probe = false;
return false;
}
log_pt("IAP_RESUME_ADDRESS model=%s old_addr=0x%02X new_addr=0x%02X", model_name(), pending.address,
g_device_addr);
pending.address = g_device_addr;
}
g_iap_pending = true;
g_iap_pending_target = pending.target;
g_iap_resume_verify = g_fw == pending.target;
log_pt("IAP_RESUME phase=%s model=%s current=0x%02X target=0x%02X addr=0x%02X",
g_iap_resume_verify ? "post_write_verify" : "application_retry", model_name(), g_fw, pending.target,
g_device_addr);
return true;
}
if (probe(kBootAddress)) {
if (!pending_loaded) {
set_status("Device in bootloader without recovery record");
log_pt("FV_ERROR stage=bootloader_no_pending addr=0x%02X", kBootAddress);
g_auto_probe = false;
return false;
}
g_model = pending.model;
g_fw = 0;
g_device_addr = pending.address;
g_iap_pending = true;
g_iap_pending_target = pending.target;
log_pt("IAP_RESUME phase=bootloader_recovery model=%s target=0x%02X app_addr=0x%02X boot_addr=0x%02X",
model_name(), pending.target, pending.address, kBootAddress);
return true;
}
return false;
}
void draw_key(size_t index)
{
int x = 0, y = 0, w = 0, h = 0;
if (g_model == M5Faces_Calculator3::MODEL_ID) {
x = 6 + static_cast<int>(index % 4) * 78;
y = 78 + static_cast<int>(index / 4) * 26;
w = 74;
h = 22;
} else if (g_model == M5Faces_Keyboard3::MODEL_ID) {
if (index < 30) {
x = 6 + static_cast<int>(index % 10) * 32;
y = 82 + static_cast<int>(index / 10) * 30;
w = 29;
h = 24;
} else {
x = 6 + static_cast<int>(index - 30) * 61;
y = 172;
w = 58;
h = 24;
}
} else {
static const int xs[8] = {54, 54, 8, 100, 262, 214, 22, 178};
static const int ys[8] = {90, 150, 120, 120, 96, 120, 178, 178};
static const int ws[8] = {56, 56, 56, 56, 44, 44, 120, 120};
x = xs[index];
y = ys[index];
w = ws[index];
h = 24;
}
const uint32_t fill = g_pressed[index] ? 0xF2B134 : (g_tested[index] ? 0x1E8E5A : 0x2F3640);
const uint32_t edge = g_pressed[index] ? 0xFFF3C4 : (g_tested[index] ? 0x7BE3B0 : 0x57606F);
M5.Display.fillRoundRect(x, y, w, h, 4, fill);
M5.Display.drawRoundRect(x, y, w, h, 4, edge);
M5.Display.setFont(&fonts::efontCN_12);
M5.Display.setTextDatum(textdatum_t::middle_center);
M5.Display.setTextColor(g_pressed[index] ? 0x1B1404 : TFT_WHITE);
M5.Display.drawString(key_label(index), x + w / 2, y + h / 2);
}
void draw_test_header()
{
M5.Display.fillRect(0, 25, 320, 49, TFT_BLACK);
char info[112];
if (g_model == M5Faces_Keyboard3::MODEL_ID) {
snprintf(info, sizeof(info), "API:%u/%u Keys:%u/%u ID:0x%02X V:0x%02X Fn:%u/6 %s",
static_cast<unsigned>(g_api_passed), static_cast<unsigned>(g_api_total),
static_cast<unsigned>(tested_count()), static_cast<unsigned>(key_count()), g_model, g_fw,
static_cast<unsigned>(keyboard_feature_count()),
g_input_mode == M5FACES_MODE_DIRECT ? "Direct" : "Normal");
} else {
snprintf(info, sizeof(info), "API:%u/%u Keys:%u/%u ID:0x%02X V:0x%02X", static_cast<unsigned>(g_api_passed),
static_cast<unsigned>(g_api_total), static_cast<unsigned>(tested_count()),
static_cast<unsigned>(key_count()), g_model, g_fw);
}
M5.Display.setFont(g_model == M5Faces_Keyboard3::MODEL_ID ? &fonts::efontCN_12 : &fonts::efontCN_16);
M5.Display.setTextDatum(textdatum_t::top_left);
M5.Display.setTextColor(TFT_WHITE);
M5.Display.drawString(info, 8, g_model == M5Faces_Keyboard3::MODEL_ID ? 30 : 27);
M5.Display.setFont(&fonts::efontCN_16);
M5.Display.setTextColor(tested_count() == key_count() ? TFT_GREEN : TFT_WHITE);
M5.Display.drawString(g_status, 8, 51);
}
void draw_test_footer()
{
M5.Display.fillRect(0, 205, 320, 35, 0x101010);
M5.Display.setFont(&fonts::efontCN_12);
M5.Display.setTextDatum(textdatum_t::top_center);
M5.Display.setTextColor(TFT_WHITE);
char uid_line[40];
snprintf(uid_line, sizeof(uid_line), "UID: %s", g_uid_text);
M5.Display.drawString(uid_line, 160, 207);
#if defined(M5FACES_HOST_CORES3)
static const char* const labels[3] = {"Reset", "Mode", "API+Addr"};
for (int i = 0; i < 3; ++i) {
const int x = i * 107;
const int width = i == 2 ? 106 : 107;
const bool enabled = i != 1 || g_model == M5Faces_Keyboard3::MODEL_ID;
M5.Display.fillRect(x, kHostTouchY, width, 20, enabled ? 0x26384A : 0x181818);
M5.Display.drawRect(x, kHostTouchY, width, 20, enabled ? 0x78B7E5 : 0x3A3A3A);
M5.Display.setTextColor(enabled ? TFT_WHITE : 0x6B6B6B);
M5.Display.drawString(labels[i], x + width / 2, kHostTouchY + 3);
}
#else
M5.Display.setTextColor(TFT_YELLOW);
M5.Display.drawString(
g_model == M5Faces_Keyboard3::MODEL_ID ? "A Reset B Mode C API+Addr" : "A Reset Keys C API+Addr", 160, 224);
#endif
}
void draw_test_screen(bool full_refresh = false)
{
if (full_refresh || !g_test_screen_ready) {
M5.Display.fillScreen(TFT_BLACK);
M5.Display.setFont(&fonts::efontCN_16_b);
M5.Display.setTextDatum(textdatum_t::top_center);
M5.Display.setTextColor(TFT_YELLOW);
char title[48];
snprintf(title, sizeof(title), "M5Faces %s Validation", model_name());
M5.Display.drawString(title, 160, 3);
draw_test_footer();
for (size_t i = 0; i < key_count(); ++i) {
draw_key(i);
g_drawn_tested[i] = g_tested[i];
g_drawn_pressed[i] = g_pressed[i];
}
g_test_screen_ready = true;
} else {
for (size_t i = 0; i < key_count(); ++i) {
if (g_drawn_tested[i] == g_tested[i] && g_drawn_pressed[i] == g_pressed[i]) continue;
draw_key(i);
g_drawn_tested[i] = g_tested[i];
g_drawn_pressed[i] = g_pressed[i];
}
}
draw_test_header();
}
void draw_error(const char* message)
{
g_test_screen_ready = false;
M5.Display.fillScreen(TFT_BLACK);
M5.Display.setTextDatum(textdatum_t::top_center);
M5.Display.setFont(&fonts::efontCN_16_b);
M5.Display.setTextColor(TFT_RED);
M5.Display.drawString("M5Faces3 Validation Failed", 160, 18);
M5.Display.setFont(&fonts::efontCN_16);
M5.Display.setTextColor(TFT_WHITE);
M5.Display.drawString(message, 160, 78);
M5.Display.setTextColor(TFT_YELLOW);
#if defined(M5FACES_HOST_CORES3)
M5.Display.drawString("Touch any bottom area to retry", 160, 170);
M5.Display.setFont(&fonts::efontCN_16);
for (int i = 0; i < 3; ++i) {
const int x = i * 107;
const int width = i == 2 ? 106 : 107;
M5.Display.fillRect(x, kErrorTouchY, width, 38, 0x26384A);
M5.Display.drawRect(x, kErrorTouchY, width, 38, 0x78B7E5);
M5.Display.setTextColor(TFT_WHITE);
M5.Display.drawString("Retry", x + width / 2, kErrorTouchY + 9);
}
#else
M5.Display.drawString("Press host A/B/C to retry", 160, 170);
#endif
}
void reset_key_test()
{
memset(g_tested, 0, sizeof(g_tested));
memset(g_pressed, 0, sizeof(g_pressed));
memset(g_keyboard_layers, 0, sizeof(g_keyboard_layers));
g_last_calc_key = 0;
g_keyboard_uppercase = false;
g_keyboard_aa_down = false;
g_keyboard_normal_seen = false;
g_pass_logged = false;
set_status("Test every key and function");
log_pt("FV_RESET model=%s progress=0/%u", model_name(), static_cast<unsigned>(key_count()));
draw_test_screen(true);
}
void check_pass()
{
if (!g_api_ready || tested_count() != key_count()) return;
if (g_model == M5Faces_Keyboard3::MODEL_ID && keyboard_feature_count() != 6) return;
set_status("All library functions passed");
if (!g_pass_logged) {
g_pass_logged = true;
log_pt("FV_PASS model=%s id=0x%02X fw=0x%02X addr=0x%02X testfw=%s", model_name(), g_model, g_fw, g_device_addr,
M5FACES_VALIDATION_FW);
}
}
bool init_driver()
{
if (g_model == M5Faces_Calculator3::MODEL_ID) {
g_input_mode = M5FACES_MODE_NORMAL;
return g_calculator.begin(&M5.In_I2C, g_device_addr, 100000) == M5FACES_OK;
}
if (g_model == M5Faces_Gamepad3::MODEL_ID) {
g_input_mode = M5FACES_MODE_NORMAL;
return g_gamepad.begin(&M5.In_I2C, g_device_addr, 100000) == M5FACES_OK;
}
g_input_mode = M5FACES_MODE_DIRECT;
return g_keyboard.begin(&M5.In_I2C, g_device_addr, 100000) == M5FACES_OK &&
g_keyboard.setMode(M5FACES_MODE_DIRECT) == M5FACES_OK;
}
bool run_common_api_validation(bool include_address_change = false)
{
M5FacesBase* device = active_driver();
g_api_passed = 0;
g_api_total = 0;
g_api_ready = false;
bool all_passed = true;
auto check = [&](const char* name, bool passed, const char* detail = nullptr) {
all_passed = api_check(name, passed, detail) && all_passed;
};
check("active_driver", device != nullptr);
if (!device) return false;
M5FacesBase uninitialized;
uint8_t byte = 0;
check("not_initialized_error", uninitialized.getModelID(&byte) == M5FACES_ERR_NOT_INIT);
check("initialized", device->isInitialized());
check("model_name", strcmp(M5FacesBase::modelName(g_model), model_name()) == 0 &&
strcmp(M5FacesBase::modelName(0xFF), "Unknown") == 0);
const char* expected_variant = latest_variant(g_model);
const faces_iap_fw_t latest_image = faces_iap_find_firmware(g_model, expected_variant);
const faces_iap_firmware_info_t* latest_info = faces_iap_get_firmware_info(latest_image);
check("iap_firmware_catalog",
faces_iap_get_firmware_count() == 3 && faces_iap_get_firmware_count() == FACES_IAP_FW_COUNT &&
faces_iap_get_model_firmware_count(g_model) == 1 && latest_image != FACES_IAP_FW_INVALID &&
latest_info != nullptr && latest_info->model_id == g_model &&
strcmp(latest_info->variant_name, expected_variant) == 0);
uint8_t model = 0;
check("get_model", device->getModelID(&model) == M5FACES_OK && model == g_model);
check("model_match", device->isModelMatch(g_model) && !device->isModelMatch(static_cast<uint8_t>(g_model ^ 0x7F)));
if (g_model == M5Faces_Calculator3::MODEL_ID) {
M5Faces_Gamepad3 wrong_driver;
check("subclass_model_mismatch",
wrong_driver.begin(&M5.In_I2C, g_device_addr, M5FACES_I2C_FREQ_STANDARD) == M5FACES_ERR_MISMATCH &&
!wrong_driver.isInitialized());
} else {
M5Faces_Calculator3 wrong_driver;
check("subclass_model_mismatch",
wrong_driver.begin(&M5.In_I2C, g_device_addr, M5FACES_I2C_FREQ_STANDARD) == M5FACES_ERR_MISMATCH &&
!wrong_driver.isInitialized());
}
check("supports_direct", device->supportsDirectMode() == (g_model == M5Faces_Keyboard3::MODEL_ID));
uint8_t uid[M5FACES_DEVICE_UID_SIZE] = {};
const bool uid_read = device->getDeviceUID(uid) == M5FACES_OK;
bool uid_has_data = false;
char uid_text[M5FACES_DEVICE_UID_SIZE * 2 + 1] = {};
for (size_t i = 0; i < M5FACES_DEVICE_UID_SIZE; ++i) {
uid_has_data = uid_has_data || (uid[i] != 0x00 && uid[i] != 0xFF);
snprintf(uid_text + i * 2, sizeof(uid_text) - i * 2, "%02X", uid[i]);
}
snprintf(g_uid_text, sizeof(g_uid_text), "%s", uid_read ? uid_text : "Read failed");
check("device_uid", uid_read && uid_has_data, uid_text);
uint8_t version = 0;
uint8_t address = 0;
check("firmware_version", device->getFirmwareVersion(&version) == M5FACES_OK && version == g_fw);
check("i2c_address_read", device->getI2CAddress(&address) == M5FACES_OK && address == g_device_addr);
version = 0;
address = 0;
check("version_addr_batch",
device->getVersionAddr(&version, &address) == M5FACES_OK && version == g_fw && address == g_device_addr);
byte = 0;
check("raw_read", device->readReg(M5FACES_REG_MODEL_ID, &byte) == M5FACES_OK && byte == g_model);
check("invalid_arguments",
device->getFirmwareVersion(nullptr) == M5FACES_ERR_INVALID &&
device->getMode(nullptr) == M5FACES_ERR_INVALID && device->getLED(nullptr) == M5FACES_ERR_INVALID &&
device->getI2CAddress(nullptr) == M5FACES_ERR_INVALID &&
device->getModeLED(nullptr, nullptr) == M5FACES_ERR_INVALID &&
device->getVersionAddr(nullptr, nullptr) == M5FACES_ERR_INVALID &&
device->readReg(M5FACES_REG_MODEL_ID, nullptr) == M5FACES_ERR_INVALID &&
device->writeReg(M5FACES_REG_LED, nullptr) == M5FACES_ERR_INVALID &&
device->setI2CAddress(0x07) == M5FACES_ERR_INVALID && device->setI2CAddress(0x78) == M5FACES_ERR_INVALID);
check("freq_400k", device->setI2CFreq(M5FACES_I2C_FREQ_FAST) == M5FACES_OK &&
device->getI2CFreq() == M5FACES_I2C_FREQ_FAST && device->getModelID(&model) == M5FACES_OK &&
model == g_model);
check("freq_100k", device->setI2CFreq(M5FACES_I2C_FREQ_STANDARD) == M5FACES_OK &&
device->getI2CFreq() == M5FACES_I2C_FREQ_STANDARD &&
device->getModelID(&model) == M5FACES_OK && model == g_model);
if (g_model == M5Faces_Keyboard3::MODEL_ID) {
m5faces_mode_t mode = M5FACES_MODE_DIRECT;
check("mode_normal", device->setMode(M5FACES_MODE_NORMAL) == M5FACES_OK &&
device->getMode(&mode) == M5FACES_OK && mode == M5FACES_MODE_NORMAL);
check("mode_direct", device->setMode(M5FACES_MODE_DIRECT) == M5FACES_OK &&
device->getMode(&mode) == M5FACES_OK && mode == M5FACES_MODE_DIRECT);
g_input_mode = M5FACES_MODE_DIRECT;
} else {
g_input_mode = M5FACES_MODE_NORMAL;
log_pt("FV_SKIP api=mode reason=model_has_no_mode_register model=%s", model_name());
}
if (g_model == M5Faces_Keyboard3::MODEL_ID) {
uint8_t original_led = 0;
const bool led_read = device->getLED(&original_led) == M5FACES_OK;
bool led_cycle = led_read;
for (uint8_t led = M5FACES_LED_OFF; led <= M5FACES_LED_ALT_FAST; ++led) {
uint8_t readback = 0xFF;
led_cycle = device->setLED(led) == M5FACES_OK && device->getLED(&readback) == M5FACES_OK &&
readback == led && led_cycle;
log_pt("FV_LED mode=0x%02X readback=0x%02X result=%s", led, readback, readback == led ? "PASS" : "FAIL");
delay(60);
}
const bool led_restored = led_read && device->setLED(original_led) == M5FACES_OK &&
device->writeReg(M5FACES_REG_LED, &original_led) == M5FACES_OK;
check("led_modes_0_8", led_cycle && led_restored);
m5faces_mode_t batch_mode = M5FACES_MODE_NORMAL;
uint8_t led_mode = 0;
check("mode_led_batch", device->getModeLED(&batch_mode, &led_mode) == M5FACES_OK &&
batch_mode == g_input_mode && led_mode == original_led);
} else {
log_pt("FV_SKIP api=led reason=model_has_no_led_register model=%s", model_name());
}
if (include_address_change) {
uint8_t temporary_address = 0;
for (uint8_t candidate = 0x09; candidate < 0x20; ++candidate) {
if (candidate != g_device_addr && candidate != kBootAddress && !probe(candidate)) {
temporary_address = candidate;
break;
}