@@ -52,43 +52,40 @@ namespace MatrixOS::HID::Keyboard
5252
5353 // if we are adding an element to keycodes
5454 if (s){
55- // iterate through the keycodes
55+ uint8_t emptyIndex = keycodesSize;
56+ // single pass: find existing key or first empty slot
5657 for (uint8_t i = 0 ; i < keycodesSize; i++)
5758 {
5859 auto key = _keyReport.keycodes [i];
59- // if target key is found
6060 if (key == uint8_t (k)) {
61- // do nothing and exit
6261 return true ;
6362 }
64- }
65- // iterate through the keycodes again, this only happens if no existing
66- // keycodes matches k
67- for (uint8_t i = 0 ; i < keycodesSize; i++)
68- {
69- auto key = _keyReport.keycodes [i];
70- // if first instance of empty slot is found
71- if (key == KEY_RESERVED ) {
72- // change empty slot to k and exit
73- _keyReport.keycodes [i] = k;
74- return true ;
63+ if (key == KEY_RESERVED && emptyIndex == keycodesSize) {
64+ emptyIndex = i;
7565 }
7666 }
67+ if (emptyIndex != keycodesSize) {
68+ _keyReport.keycodes [emptyIndex] = k;
69+ return true ;
70+ }
7771 } else { // we are removing k from keycodes
78- // iterate through the keycodes
7972 for (uint8_t i = 0 ; i < keycodesSize; i++)
8073 {
81- auto key = _keyReport.keycodes [i];
82- // if target key is found
83- if (key == k) {
84- // remove target and exit
85- _keyReport.keycodes [i] = KEY_RESERVED ;
74+ if (_keyReport.keycodes [i] == k) {
75+ // compact so we don't leave holes
76+ for (uint8_t j = i; j + 1 < keycodesSize; j++)
77+ {
78+ _keyReport.keycodes [j] = _keyReport.keycodes [j + 1 ];
79+ }
80+ _keyReport.keycodes [keycodesSize - 1 ] = KEY_RESERVED ;
8681 return true ;
8782 }
8883 }
8984 }
9085 }
9186
87+ MLOGD (" HID" , " Set failed" );
88+
9289 // No empty/pressed key was found
9390 return false ;
9491 }
@@ -103,6 +100,7 @@ namespace MatrixOS::HID::Keyboard
103100
104101 if (!HID::Ready ())
105102 {
103+ ulTaskNotifyTake (pdTRUE, 0 );
106104 continue ;
107105 }
108106
@@ -113,18 +111,16 @@ namespace MatrixOS::HID::Keyboard
113111 tud_remote_wakeup ();
114112 }
115113
116- uint64_t nowMicros = MatrixOS::SYS::Micros ();
117- if (_lastSendMicros != 0 )
118- {
119- uint64_t elapsed = nowMicros - _lastSendMicros;
120- if (elapsed < 1000 ) // keep at least 1ms gap
121- {
122- MatrixOS::SYS::DelayMs (1 );
123- }
124- }
114+ tud_hid_n_report (0 , REPORT_ID_KEYBOARD , &_keyReport, sizeof (_keyReport));
115+ MatrixOS::SYS::DelayMs (2 );
116+
117+ // Clear any queued notifications; we only need to send the latest _keyReport state once.
118+ ulTaskNotifyTake (pdTRUE, 0 );
125119
120+ // Send another one to make sure we didn't drop packet
126121 tud_hid_n_report (0 , REPORT_ID_KEYBOARD , &_keyReport, sizeof (_keyReport));
127- _lastSendMicros = MatrixOS::SYS::Micros ();
122+ MatrixOS::SYS::DelayMs (2 );
123+
128124 }
129125 }
130126
0 commit comments