-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cpp
More file actions
1389 lines (1198 loc) · 40.6 KB
/
main.cpp
File metadata and controls
1389 lines (1198 loc) · 40.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
#include <Arduino.h>
#include <Adafruit_TinyUSB.h>
#include <Adafruit_LittleFS.h>
#include <InternalFileSystem.h>
#include <bluefruit.h>
using namespace Adafruit_LittleFS_Namespace;
extern "C" void enterSerialDfu(void);
// Normal mode should enumerate as USB HID keyboard only.
// USB CDC Serial is useful for debugging but makes the device show up as a COM port.
static constexpr bool kEnableUsbCdcSerialLog = false;
// 펌웨어 버전 (메이저.마이너.패치)
static const char* kFirmwareVersion = "1.1.42";
static void start_advertising();
// BLE 연결 정책
// - Control PC는 동시에 1대만 허용한다.
// - 이미 연결된 상태에서는 광고를 중지하고, 추가 연결 시도는 즉시 끊는다.
static volatile uint16_t g_control_conn_handle = BLE_CONN_HANDLE_INVALID;
// -----------------------------
// BLE Nickname (Flash persisted)
// -----------------------------
// - Web UI에서 닉네임을 설정하면 보드 내부 Flash에 저장한다.
// - 저장/로드 실패 시에도 기존 기능(전송/타이핑)은 영향 없이 동작해야 한다.
static constexpr size_t kDeviceNicknameMaxLen = 12;
static char g_device_nickname[kDeviceNicknameMaxLen + 1] = {0};
static bool g_storage_ready = false;
static bool g_storage_tried = false;
static const char* kDeviceNicknameFilePath = "/bf_nick.txt";
static bool storage_try_begin() {
if (g_storage_tried) return g_storage_ready;
g_storage_tried = true;
g_storage_ready = InternalFS.begin();
return g_storage_ready;
}
static void sanitize_nickname_to(char* out, size_t out_size, const char* in) {
if (!out || out_size == 0) return;
out[0] = 0;
if (!in) return;
size_t o = 0;
for (const char* p = in; *p && o + 1 < out_size; ++p) {
const char c = *p;
if (c >= 'a' && c <= 'z') {
out[o++] = c;
continue;
}
if (c >= 'A' && c <= 'Z') {
out[o++] = c;
continue;
}
if (c >= '0' && c <= '9') {
out[o++] = c;
continue;
}
if (c == '-' || c == '_') {
out[o++] = c;
continue;
}
// Ignore other chars (spaces, unicode, etc) for 안정성/호환성.
}
out[o] = 0;
}
static void set_device_nickname_runtime(const char* nickname_ascii) {
char sanitized[kDeviceNicknameMaxLen + 1] = {0};
sanitize_nickname_to(sanitized, sizeof(sanitized), nickname_ascii);
strncpy(g_device_nickname, sanitized, sizeof(g_device_nickname) - 1);
g_device_nickname[sizeof(g_device_nickname) - 1] = 0;
}
static void try_load_device_nickname_from_flash() {
if (!storage_try_begin()) return;
File f(InternalFS.open(kDeviceNicknameFilePath, FILE_O_READ));
if (!f) return;
char buf[48] = {0};
f.read(reinterpret_cast<uint8_t*>(buf), sizeof(buf) - 1);
f.close();
// Strip trailing whitespace/newlines/nulls.
for (int i = static_cast<int>(sizeof(buf)) - 2; i >= 0; --i) {
if (buf[i] == 0 || buf[i] == '\n' || buf[i] == '\r' || buf[i] == ' ' || buf[i] == '\t') {
buf[i] = 0;
continue;
}
break;
}
set_device_nickname_runtime(buf);
}
static void try_save_device_nickname_to_flash() {
if (!storage_try_begin()) return;
if (g_device_nickname[0] == 0) {
InternalFS.remove(kDeviceNicknameFilePath);
return;
}
InternalFS.remove(kDeviceNicknameFilePath);
File f(InternalFS.open(kDeviceNicknameFilePath, FILE_O_WRITE));
if (!f) return;
f.write(reinterpret_cast<const uint8_t*>(g_device_nickname), strlen(g_device_nickname));
f.close();
}
static const char* build_ble_device_name() {
// 동일 기기가 여러 대일 때, 광고 이름만으로도 구분 가능하게 한다.
// nRF52840은 FICR에 고유 DEVICEID가 있다.
const uint32_t id0 = NRF_FICR->DEVICEID[0];
const uint32_t id1 = NRF_FICR->DEVICEID[1];
const uint32_t suffix32 = (id0 ^ id1);
static char name[32];
if (g_device_nickname[0] != 0) {
// 닉네임이 있으면 이름이 길어지므로 suffix는 4자리로 유지한다.
const uint16_t suffix16 = static_cast<uint16_t>(suffix32 & 0xFFFFu);
snprintf(name, sizeof(name), "ByteFlusher-%s-%04X", g_device_nickname, suffix16);
} else {
// 닉네임이 없으면 다중 장치 구분을 위해 8자리 suffix.
snprintf(name, sizeof(name), "ByteFlusher-%08lX", static_cast<unsigned long>(suffix32));
}
return name;
}
// -----------------------------
// BLE UUID (현재 사용값)
// -----------------------------
static const char* kFlusherServiceUuid = "f3641400-00b0-4240-ba50-05ca45bf8abc";
static const char* kFlushTextCharUuid = "f3641401-00b0-4240-ba50-05ca45bf8abc";
static const char* kConfigCharUuid = "f3641402-00b0-4240-ba50-05ca45bf8abc";
static const char* kStatusCharUuid = "f3641403-00b0-4240-ba50-05ca45bf8abc";
// Macro / special keys (Windows automation)
// - Separate characteristic to avoid impacting text flusher protocol.
static const char* kMacroCharUuid = "f3641404-00b0-4240-ba50-05ca45bf8abc";
// Bootloader entry (button-less firmware upload)
// - Request from Control PC(BLE) to reboot into Serial DFU bootloader.
static const char* kBootloaderCharUuid = "f3641405-00b0-4240-ba50-05ca45bf8abc";
// Device nickname (persisted, optional)
static const char* kNicknameCharUuid = "f3641406-00b0-4240-ba50-05ca45bf8abc";
// Flush Text 패킷 포맷(LE)
// - [sessionId(2)][seq(2)][payload...]
// - BT 끊김/재시도 시 동일 패킷을 재전송해도 중복 타이핑이 발생하지 않게 한다.
static constexpr uint16_t kFlushHeaderSize = 4;
// -----------------------------
// 타이핑/전환 타이밍 (ms)
// -----------------------------
// 속도보다 안정성(키 씹힘 방지)을 우선한다.
static constexpr uint16_t kDefaultTypingDelayMs = 30; // 각 키 입력 후 대기
static constexpr uint16_t kDefaultModeSwitchDelayMs = 100; // 한/영 전환 후 대기
static constexpr uint16_t kDefaultKeyPressDelayMs = 10; // 키 눌림 유지 시간
// 웹에서 BLE로 설정 가능(런타임)
static volatile uint16_t g_typing_delay_ms = kDefaultTypingDelayMs;
static volatile uint16_t g_mode_switch_delay_ms = kDefaultModeSwitchDelayMs;
static volatile uint16_t g_key_press_delay_ms = kDefaultKeyPressDelayMs;
// Pause/Resume (런타임)
// - true면 RX 버퍼를 소비(타이핑)하지 않는다.
// - 정확성 우선: 버퍼가 full일 때는 write(with response)가 블로킹되며 웹 전송도 멈춘다.
static volatile bool g_paused = false;
// NOTE: pause/resume 요청을 BLE 콜백에서 즉시 적용하면,
// flush_text_write_cb 내부의 "버퍼 full -> 공간 날 때까지 대기" 루프와 결합될 때
// (pause=true 상태에서) 콜백이 영원히 빠져나오지 못해 config write(resume)가 처리되지 않는 교착이 생길 수 있다.
// 정확성 우선 정책을 유지하면서도 resume이 항상 먹히도록, 상태 변경은 loop에서 적용한다.
static volatile bool g_pause_change_pending = false;
static volatile bool g_pause_target = false;
static volatile bool g_abort_requested = false;
// 한/영 전환키 선택(웹 설정)
// 0=RightAlt(기본), 1=LeftAlt, 2=RightCtrl, 3=LeftCtrl, 4=RightGUI, 5=LeftGUI, 6=CapsLock
static volatile uint8_t g_toggle_key = 0;
// -----------------------------
// Mouse Jiggler (화면잠금 방지)
// -----------------------------
// USB 연결 시 자동 시작, Flush 동작 중 자동 정지, 종료 후 자동 재개.
static constexpr uint32_t kJigglerIntervalMs = 30000; // 30초마다 1회 이동
static constexpr int8_t kJigglerPixels = 1; // 1픽셀 이동
static constexpr uint32_t kJigglerCooldownMs = 5000; // 버퍼가 빈 후 5초 대기 후 재개
static uint32_t g_jiggler_last_move_ms = 0;
static bool g_jiggler_direction = false; // false=오른쪽, true=왼쪽
static uint32_t g_last_flush_activity_ms = 0;
// -----------------------------
// 디버그(USB CDC Serial)
// -----------------------------
static void log_line(const char* msg) {
#if CFG_TUD_CDC
if (!kEnableUsbCdcSerialLog) return;
if (Serial) Serial.println(msg);
#else
(void)msg;
#endif
}
static void log_kv(const char* key, const char* value) {
#if CFG_TUD_CDC
if (!kEnableUsbCdcSerialLog) return;
if (Serial) {
Serial.print(key);
Serial.print(": ");
Serial.println(value);
}
#else
(void)key;
(void)value;
#endif
}
static volatile bool g_bootloader_request_pending = false;
// -----------------------------
// USB HID 키보드
// -----------------------------
Adafruit_USBD_HID usb_hid;
static uint8_t const kHidReportDescriptor[] = {
TUD_HID_REPORT_DESC_KEYBOARD(HID_REPORT_ID(1)),
TUD_HID_REPORT_DESC_MOUSE(HID_REPORT_ID(2))
};
static constexpr uint8_t kReportIdKeyboard = 1;
static constexpr uint8_t kReportIdMouse = 2;
static void hid_begin() {
usb_hid.setPollInterval(2);
usb_hid.setReportDescriptor(kHidReportDescriptor, sizeof(kHidReportDescriptor));
usb_hid.begin();
}
static inline bool hid_ready() {
return TinyUSBDevice.mounted() && usb_hid.ready();
}
static void hid_send_key(uint8_t modifier, uint8_t keycode) {
if (!hid_ready()) {
return;
}
uint8_t keycodes[6] = {0};
keycodes[0] = keycode;
usb_hid.keyboardReport(kReportIdKeyboard, modifier, keycodes);
delay(g_key_press_delay_ms);
usb_hid.keyboardRelease(kReportIdKeyboard);
delay(g_key_press_delay_ms);
}
static void hid_tap_modifier(uint8_t modifier) {
// modifier만 눌렀다 떼는 용도(예: 한/영 전환 Right Alt)
if (!hid_ready()) {
return;
}
uint8_t keycodes[6] = {0};
usb_hid.keyboardReport(kReportIdKeyboard, modifier, keycodes);
delay(g_key_press_delay_ms);
usb_hid.keyboardRelease(kReportIdKeyboard);
delay(g_key_press_delay_ms);
}
static void hid_tap_toggle_key() {
switch (g_toggle_key) {
case 6:
hid_send_key(0, HID_KEY_CAPS_LOCK);
return;
case 1:
hid_tap_modifier(KEYBOARD_MODIFIER_LEFTALT);
return;
case 2:
hid_tap_modifier(KEYBOARD_MODIFIER_RIGHTCTRL);
return;
case 3:
hid_tap_modifier(KEYBOARD_MODIFIER_LEFTCTRL);
return;
case 4:
hid_tap_modifier(KEYBOARD_MODIFIER_RIGHTGUI);
return;
case 5:
hid_tap_modifier(KEYBOARD_MODIFIER_LEFTGUI);
return;
case 0:
default:
hid_tap_modifier(KEYBOARD_MODIFIER_RIGHTALT);
return;
}
}
static bool ascii_to_hid(char c, uint8_t& modifier, uint8_t& keycode) {
modifier = 0;
keycode = 0;
if (c >= 'a' && c <= 'z') {
keycode = HID_KEY_A + (c - 'a');
return true;
}
if (c >= 'A' && c <= 'Z') {
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_A + (c - 'A');
return true;
}
if (c >= '1' && c <= '9') {
keycode = HID_KEY_1 + (c - '1');
return true;
}
if (c == '0') {
keycode = HID_KEY_0;
return true;
}
switch (c) {
case '\n':
keycode = HID_KEY_ENTER;
return true;
case '\r':
keycode = HID_KEY_ENTER;
return true;
case '\t':
keycode = HID_KEY_TAB;
return true;
case ' ':
keycode = HID_KEY_SPACE;
return true;
case '-':
keycode = HID_KEY_MINUS;
return true;
case '_':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_MINUS;
return true;
case '=':
keycode = HID_KEY_EQUAL;
return true;
case '+':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_EQUAL;
return true;
case '[':
keycode = HID_KEY_BRACKET_LEFT;
return true;
case '{':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_BRACKET_LEFT;
return true;
case ']':
keycode = HID_KEY_BRACKET_RIGHT;
return true;
case '}':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_BRACKET_RIGHT;
return true;
case '\\':
keycode = HID_KEY_BACKSLASH;
return true;
case '|':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_BACKSLASH;
return true;
case ';':
keycode = HID_KEY_SEMICOLON;
return true;
case ':':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_SEMICOLON;
return true;
case '\'':
keycode = HID_KEY_APOSTROPHE;
return true;
case '"':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_APOSTROPHE;
return true;
case ',':
keycode = HID_KEY_COMMA;
return true;
case '<':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_COMMA;
return true;
case '.':
keycode = HID_KEY_PERIOD;
return true;
case '>':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_PERIOD;
return true;
case '/':
keycode = HID_KEY_SLASH;
return true;
case '?':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_SLASH;
return true;
case '`':
keycode = HID_KEY_GRAVE;
return true;
case '~':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_GRAVE;
return true;
case '!':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_1;
return true;
case '@':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_2;
return true;
case '#':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_3;
return true;
case '$':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_4;
return true;
case '%':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_5;
return true;
case '^':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_6;
return true;
case '&':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_7;
return true;
case '*':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_8;
return true;
case '(':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_9;
return true;
case ')':
modifier = KEYBOARD_MODIFIER_LEFTSHIFT;
keycode = HID_KEY_0;
return true;
default:
return false;
}
}
// -----------------------------
// 한/영 전환 + 한글(두벌식) 타이핑
// -----------------------------
static bool g_is_korean_mode = false;
static bool g_prev_was_cr = false;
// 두벌식 매핑(SD Flusher 테이블 기반)
static const char* const kChoData[19] = {
"r", "R", "s", "e", "E", "f", "a", "q", "Q", "t", "T", "d", "w", "W", "c", "z", "x", "v", "g"};
static const char* const kJungData[21] = {
"k", "o", "i", "O", "j", "p", "u", "P", "h", "hk", "ho", "hl", "y", "n", "nj", "np", "nl", "b", "m", "ml", "l"};
static const char* const kJongData[28] = {"", "r", "R", "rt", "s", "sw", "sg", "e", "f", "fr", "fa", "fq", "ft", "fx", "fv", "fg",
"a", "q", "qt", "t", "T", "d", "w", "c", "z", "x", "v", "g"};
static void switch_to_korean() {
if (g_is_korean_mode) {
return;
}
// Target PC에서 선택된 전환키가 한/영 전환으로 설정되어 있다는 전제
hid_tap_toggle_key();
delay(g_mode_switch_delay_ms);
g_is_korean_mode = true;
}
static void switch_to_english() {
if (!g_is_korean_mode) {
return;
}
hid_tap_toggle_key();
delay(g_mode_switch_delay_ms);
g_is_korean_mode = false;
}
static void type_ascii_char(char c) {
uint8_t modifier = 0;
uint8_t keycode = 0;
if (!ascii_to_hid(c, modifier, keycode)) {
// 매핑이 없는 ASCII는 '?'로 대체
ascii_to_hid('?', modifier, keycode);
}
hid_send_key(modifier, keycode);
delay(g_typing_delay_ms);
}
static void type_keys(const char* keys) {
for (int i = 0; keys[i] != '\0'; i++) {
// 매핑 문자열은 ASCII 키 시퀀스이므로 영어 모드에서 타이핑한다.
// (한글 모드에서 알파벳을 누르면 자모가 입력되어야 한다.)
// 단, 이 함수는 '이미 한국어 모드' 상태에서 호출된다.
// 따라서 여기서는 모드 전환을 하지 않는다.
type_ascii_char(keys[i]);
}
}
static void type_korean_syllable(uint16_t unicode) {
// 한글 음절(가~힣)만 처리
const uint16_t kKoreanStart = 0xAC00;
const uint16_t kKoreanEnd = 0xD7A3;
if (unicode < kKoreanStart || unicode > kKoreanEnd) {
return;
}
const uint16_t code = static_cast<uint16_t>(unicode - kKoreanStart);
const int cho = code / (21 * 28);
const int jung = (code % (21 * 28)) / 28;
const int jong = code % 28;
if (cho >= 0 && cho < 19) {
type_keys(kChoData[cho]);
}
if (jung >= 0 && jung < 21) {
type_keys(kJungData[jung]);
}
if (jong > 0 && jong < 28) {
type_keys(kJongData[jong]);
}
}
static void type_codepoint(uint32_t cp) {
// ASCII 제어문자/기본 문자
if (cp <= 0x7F) {
const char c = static_cast<char>(cp);
// ASCII는 영어 모드에서 처리
if (c == '\r') {
// CR 단독도 줄바꿈으로 취급한다.
// 단, 바로 뒤에 LF가 오면 CRLF로 보고 LF는 무시(엔터 중복 방지).
g_prev_was_cr = true;
switch_to_english();
type_ascii_char('\n');
return;
}
if (c == '\n') {
if (g_prev_was_cr) {
// CRLF: 이미 CR에서 엔터를 쳤으므로 LF는 무시
g_prev_was_cr = false;
return;
}
// 한글 모드에서 엔터가 어색한 케이스가 있어서 영어로 돌려 엔터
switch_to_english();
type_ascii_char('\n');
return;
}
if (c == '\t') {
g_prev_was_cr = false;
switch_to_english();
type_ascii_char('\t');
return;
}
g_prev_was_cr = false;
switch_to_english();
type_ascii_char(c);
return;
}
g_prev_was_cr = false;
// 한글 음절(가~힣)
if (cp >= 0xAC00 && cp <= 0xD7A3) {
switch_to_korean();
type_korean_syllable(static_cast<uint16_t>(cp));
return;
}
// 그 외 유니코드는 현재 입력 정책이 애매하므로 '?'로 대체
// (현재 입력 텍스트는 ASCII + 한글 음절로 제한하는 것을 권장)
switch_to_english();
type_ascii_char('?');
}
// UTF-8 스트림 디코더 상태
static uint32_t g_utf8_cp = 0;
static uint8_t g_utf8_need = 0;
static void reset_input_state_no_keystroke() {
// Stop(즉시 폐기) 시 정확성 우선:
// - 기존 버퍼 내용을 버린다.
// - UTF-8/CRLF/한글모드 내부 상태만 초기화한다(추가 키 입력은 하지 않는다).
g_utf8_cp = 0;
g_utf8_need = 0;
g_prev_was_cr = false;
g_is_korean_mode = false;
}
static void process_input_byte(uint8_t b) {
if (g_utf8_need == 0) {
if (b < 0x80) {
type_codepoint(b);
return;
}
if ((b & 0xE0) == 0xC0) {
g_utf8_cp = (b & 0x1F);
g_utf8_need = 1;
return;
}
if ((b & 0xF0) == 0xE0) {
g_utf8_cp = (b & 0x0F);
g_utf8_need = 2;
return;
}
if ((b & 0xF8) == 0xF0) {
g_utf8_cp = (b & 0x07);
g_utf8_need = 3;
return;
}
// 잘못된 시작 바이트는 무시
return;
}
if ((b & 0xC0) != 0x80) {
// 깨진 UTF-8: 상태 리셋
g_utf8_cp = 0;
g_utf8_need = 0;
// 현재 바이트는 새 시작으로 재해석
process_input_byte(b);
return;
}
g_utf8_cp = (g_utf8_cp << 6) | (b & 0x3F);
g_utf8_need--;
if (g_utf8_need == 0) {
type_codepoint(g_utf8_cp);
g_utf8_cp = 0;
}
}
static inline uint16_t le16(const uint8_t* p) {
return static_cast<uint16_t>(p[0]) | (static_cast<uint16_t>(p[1]) << 8);
}
static inline uint16_t clamp_u16(uint16_t v, uint16_t min_v, uint16_t max_v) {
if (v < min_v) return min_v;
if (v > max_v) return max_v;
return v;
}
static void rb_clear();
static void stash_clear();
static void notify_status_if_needed(bool force);
static void config_write_cb(uint16_t /*conn_hdl*/, BLECharacteristic* /*chr*/, uint8_t* data, uint16_t len) {
// 포맷(호환):
// - LE u16 * 3 => [typingDelayMs][modeSwitchDelayMs][keyPressDelayMs]
// - + u8(선택) => [toggleKey]
// - + u8(선택) => [flags]
// - flags bit0: paused
// - flags bit1: abort(즉시 폐기)
if (len < 6) {
return;
}
const uint16_t typing_ms = le16(&data[0]);
const uint16_t mode_ms = le16(&data[2]);
const uint16_t press_ms = le16(&data[4]);
g_typing_delay_ms = clamp_u16(typing_ms, 0, 1000);
g_mode_switch_delay_ms = clamp_u16(mode_ms, 0, 3000);
g_key_press_delay_ms = clamp_u16(press_ms, 0, 300);
if (len >= 7) {
const uint8_t toggle = data[6];
g_toggle_key = static_cast<uint8_t>(toggle <= 6 ? toggle : 0);
}
if (len >= 8) {
const uint8_t flags = data[7];
// Pause/resume 및 abort는 loop에서 적용한다(교착 방지).
g_pause_target = (flags & 0x01) != 0;
g_pause_change_pending = true;
if ((flags & 0x02) != 0) {
// 즉시 폐기: 버퍼/상태를 리셋하고 정상 모드로 복귀한다.
g_abort_requested = true;
g_pause_target = false;
g_pause_change_pending = true;
}
}
}
static void apply_pending_controls_in_loop() {
// Copy volatile flags atomically-ish (keep it short).
bool pending = false;
bool target = false;
bool abort_now = false;
noInterrupts();
pending = g_pause_change_pending;
target = g_pause_target;
abort_now = g_abort_requested;
g_pause_change_pending = false;
g_abort_requested = false;
interrupts();
if (abort_now) {
g_paused = false;
rb_clear();
stash_clear();
reset_input_state_no_keystroke();
notify_status_if_needed(true);
}
if (pending) {
const bool prev = g_paused;
g_paused = target;
if (prev != g_paused) {
notify_status_if_needed(true);
}
}
}
// -----------------------------
// Macro queue (BLE write -> loop)
// -----------------------------
// Format (byte stream): [cmd(u8)][len(u8)][payload...]
// Commands are executed in the main loop to avoid blocking BLE callbacks.
constexpr size_t kMacroBufferSize = 256;
static uint8_t macro_buf[kMacroBufferSize];
static volatile size_t macro_head = 0;
static volatile size_t macro_tail = 0;
static inline size_t macro_next(size_t v) {
return (v + 1) % kMacroBufferSize;
}
static inline uint16_t macro_used_bytes() {
const size_t head = macro_head;
const size_t tail = macro_tail;
if (head >= tail) {
return static_cast<uint16_t>(head - tail);
}
return static_cast<uint16_t>(kMacroBufferSize - (tail - head));
}
static bool macro_push(uint8_t b) {
size_t next = macro_next(macro_head);
if (next == macro_tail) {
return false;
}
macro_buf[macro_head] = b;
macro_head = next;
return true;
}
static inline uint8_t macro_peek(uint16_t offset) {
const uint16_t used = macro_used_bytes();
if (offset >= used) {
return 0;
}
const size_t idx = (macro_tail + offset) % kMacroBufferSize;
return macro_buf[idx];
}
static void macro_drop(uint16_t n) {
if (n == 0) return;
noInterrupts();
for (uint16_t i = 0; i < n; i++) {
if (macro_tail == macro_head) break;
macro_tail = macro_next(macro_tail);
}
interrupts();
}
static void hid_send_combo(uint8_t modifier, uint8_t keycode) {
hid_send_key(modifier, keycode);
}
static bool macro_try_process_one() {
if (!hid_ready()) return false;
if (g_paused) return false;
const uint16_t used = macro_used_bytes();
if (used < 2) return false;
const uint8_t cmd = macro_peek(0);
const uint8_t len = macro_peek(1);
const uint16_t total = static_cast<uint16_t>(2u + len);
if (used < total) return false;
// Drop header, then consume payload as needed.
macro_drop(2);
switch (cmd) {
case 0x01: // WIN+R
hid_send_combo(KEYBOARD_MODIFIER_LEFTGUI, HID_KEY_R);
break;
case 0x02: // ENTER
hid_send_combo(0, HID_KEY_ENTER);
break;
case 0x03: // ESC
hid_send_combo(0, HID_KEY_ESCAPE);
break;
case 0x04: { // TYPE_ASCII
// Macro typing is intended for OS dialogs/CLI; keep it in English mode.
switch_to_english();
for (uint8_t i = 0; i < len; i++) {
const char c = static_cast<char>(macro_peek(0));
macro_drop(1);
type_ascii_char(c);
}
return true;
}
case 0x05: { // SLEEP_MS (u16 LE)
uint16_t ms = 0;
if (len >= 2) {
const uint8_t b0 = macro_peek(0);
const uint8_t b1 = macro_peek(1);
ms = static_cast<uint16_t>(b0) | (static_cast<uint16_t>(b1) << 8);
}
macro_drop(len);
if (ms > 0) {
delay(ms);
}
return true;
}
case 0x06: // FORCE_ENGLISH (best-effort)
switch_to_english();
break;
default:
// Unknown command: consume payload and ignore.
break;
}
// Consume any payload bytes not explicitly consumed.
if (len > 0) {
macro_drop(len);
}
return true;
}
// -----------------------------
// RX 버퍼 (BLE write -> loop)
// -----------------------------
// 기본값은 작게 시작하고, 유실이 보이면 웹에서 Delay를 올리는 방식으로 안정화한다.
constexpr size_t kRxBufferSize = 512;
static uint8_t rx_buf[kRxBufferSize];
static volatile size_t rx_head = 0;
static volatile size_t rx_tail = 0;
// Pause stash
// - pause 상태에서 RX 링버퍼가 full이면, BLE write 콜백이 무한 대기할 수 있다.
// - 정확성 우선: 데이터를 버리지 않고, 오래된 바이트를 stash로 옮겨 RX에 공간을 만든다.
// - resume 후에는 stash -> RX 순으로 소비하여 원래 순서를 보장한다.
constexpr size_t kPauseStashSize = 512;
static uint8_t stash_buf[kPauseStashSize];
static volatile size_t stash_head = 0;
static volatile size_t stash_tail = 0;
static inline size_t stash_next(size_t v) {
return (v + 1) % kPauseStashSize;
}
static inline bool stash_push(uint8_t b) {
const size_t next = stash_next(stash_head);
if (next == stash_tail) {
return false;
}
stash_buf[stash_head] = b;
stash_head = next;
return true;
}
static inline bool stash_pop(uint8_t& out) {
if (stash_tail == stash_head) {
return false;
}
out = stash_buf[stash_tail];
stash_tail = stash_next(stash_tail);
return true;
}
static void stash_clear() {
noInterrupts();
stash_tail = stash_head;
interrupts();
}
static inline uint16_t rb_capacity_bytes() {
// 링버퍼는 (head+1==tail)로 full을 판정하므로, 실사용 용량은 size-1이다.
return static_cast<uint16_t>(kRxBufferSize - 1);
}
static inline uint16_t rb_used_bytes() {
const size_t head = rx_head;
const size_t tail = rx_tail;
if (head >= tail) {
return static_cast<uint16_t>(head - tail);
}
return static_cast<uint16_t>(kRxBufferSize - (tail - head));
}
static inline uint16_t rb_free_bytes() {
const uint16_t used = rb_used_bytes();
const uint16_t cap = rb_capacity_bytes();
return static_cast<uint16_t>(cap - (used <= cap ? used : cap));
}
static inline size_t rb_next(size_t v) {
return (v + 1) % kRxBufferSize;
}
static bool rb_push(uint8_t b) {
size_t next = rb_next(rx_head);
if (next == rx_tail) {
return false;
}
rx_buf[rx_head] = b;
rx_head = next;
return true;
}
static bool rb_pop(uint8_t& out) {
if (rx_tail == rx_head) {
return false;
}
out = rx_buf[rx_tail];
rx_tail = rb_next(rx_tail);
return true;
}
static void rb_clear() {
noInterrupts();
rx_tail = rx_head;
interrupts();
}
static inline bool pop_next_byte(uint8_t& out) {
// Preserve order: bytes moved to stash are always older.
if (stash_pop(out)) return true;
return rb_pop(out);
}
// -----------------------------
// BLE GATT
// -----------------------------
BLEService flusher_service(kFlusherServiceUuid);
BLECharacteristic flush_text_char(kFlushTextCharUuid);
BLECharacteristic config_char(kConfigCharUuid);
BLECharacteristic nickname_char(kNicknameCharUuid);
BLECharacteristic status_char(kStatusCharUuid);
BLECharacteristic macro_char(kMacroCharUuid);
BLECharacteristic bootloader_char(kBootloaderCharUuid);
static void nickname_write_cb(uint16_t /*conn_hdl*/, BLECharacteristic* /*chr*/, uint8_t* data, uint16_t len) {
// Payload: UTF-8(권장 ASCII). 빈 값(또는 0x00 1바이트)이면 닉네임을 제거한다.
if (!data) return;
char raw[48] = {0};
if (len == 0 || (len == 1 && data[0] == 0)) {
raw[0] = 0;
} else {
const uint16_t n = static_cast<uint16_t>(len < (sizeof(raw) - 1) ? len : (sizeof(raw) - 1));
memcpy(raw, data, n);
raw[n] = 0;
}
// Trim (simple)
for (int i = static_cast<int>(sizeof(raw)) - 2; i >= 0; --i) {
if (raw[i] == 0 || raw[i] == '\n' || raw[i] == '\r' || raw[i] == ' ' || raw[i] == '\t') {
raw[i] = 0;
continue;
}
break;
}
set_device_nickname_runtime(raw);
try_save_device_nickname_to_flash();
// Update characteristic read value.
nickname_char.write(reinterpret_cast<const uint8_t*>(g_device_nickname), strlen(g_device_nickname));
// Update GAP name for next advertising (현재 연결 중에는 광고를 중지하므로 여기서 재광고는 하지 않는다).
Bluefruit.setName(build_ble_device_name());