]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - converter/ibmpc_usb/ibmpc_usb.c
ibmpc_usb: Add protocol and isr_debug check
[max/tmk_keyboard.git] / converter / ibmpc_usb / ibmpc_usb.c
1 /*
2 Copyright 2019,2020 Jun Wako <wakojun@gmail.com>
3
4 This program is free software: you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation, either version 2 of the License, or
7 (at your option) any later version.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 #include <stdint.h>
19 #include <stdbool.h>
20 #include "print.h"
21 #include "util.h"
22 #include "debug.h"
23 #include "ibmpc.h"
24 #include "host.h"
25 #include "led.h"
26 #include "matrix.h"
27 #include "timer.h"
28 #include "action.h"
29 #include "ibmpc_usb.h"
30 #include "ibmpc.h"
31
32
33 static void matrix_make(uint8_t code);
34 static void matrix_break(uint8_t code);
35
36 static int8_t process_cs1(void);
37 static int8_t process_cs2(void);
38 static int8_t process_cs3(void);
39
40
41 static uint8_t matrix[MATRIX_ROWS];
42 #define ROW(code)      ((code>>3)&0x0F)
43 #define COL(code)      (code&0x07)
44
45 static int16_t read_wait(uint16_t wait_ms)
46 {
47     uint16_t start = timer_read();
48     int16_t code;
49     while ((code = ibmpc_host_recv()) == -1 && timer_elapsed(start) < wait_ms);
50     return code;
51 }
52
53 static uint16_t read_keyboard_id(void)
54 {
55     uint16_t id = 0;
56     int16_t  code = 0;
57
58     // Disable
59     //code = ibmpc_host_send(0xF5);
60
61     // Read ID
62     code = ibmpc_host_send(0xF2);
63     if (code == -1) { id = 0xFFFF; goto DONE; }     // XT or No keyboard
64     if (code != 0xFA) { id = 0xFFFE; goto DONE; }   // Broken PS/2?
65
66     // ID takes 500ms max TechRef [8] 4-41
67     code = read_wait(500);
68     if (code == -1) { id = 0x0000; goto DONE; }     // AT
69     id = (code & 0xFF)<<8;
70
71     // Mouse responds with one-byte 00, this returns 00FF [y] p.14
72     code = read_wait(500);
73     id |= code & 0xFF;
74
75 DONE:
76     // Enable
77     //code = ibmpc_host_send(0xF4);
78
79     return id;
80 }
81
82 void hook_early_init(void)
83 {
84     ibmpc_host_init();
85     ibmpc_host_enable();
86 }
87
88 void matrix_init(void)
89 {
90     debug_enable = true;
91
92     // initialize matrix state: all keys off
93     for (uint8_t i=0; i < MATRIX_ROWS; i++) matrix[i] = 0x00;
94
95     return;
96 }
97
98 /*
99  * keyboard recognition
100  *
101  * 1. Send F2 to get keyboard ID
102  *      a. no ACK(FA): XT keyobard
103  *      b. ACK but no ID: 84-key AT keyboard CodeSet2
104  *      c. ID is AB 83: PS/2 keyboard CodeSet2
105  *      d. ID is BF BF: Terminal keyboard CodeSet3
106  *      e. error on recv: maybe broken PS/2
107  */
108 uint8_t current_protocol = 0;
109 uint16_t keyboard_id = 0x0000;
110 keyboard_kind_t keyboard_kind = NONE;
111 uint8_t matrix_scan(void)
112 {
113     // scan code reading states
114     static enum {
115         INIT,
116         XT_RESET,
117         XT_RESET_WAIT,
118         XT_RESET_DONE,
119         WAIT_AA,
120         WAIT_AABF,
121         WAIT_AABFBF,
122         READ_ID,
123         SETUP,
124         LOOP,
125     } state = INIT;
126     static uint16_t init_time;
127
128
129     if (ibmpc_error) {
130         xprintf("\nERR:%02X\n", ibmpc_error);
131
132         // when recv error, neither send error nor buffer full
133         if (!(ibmpc_error & (IBMPC_ERR_SEND | IBMPC_ERR_FULL))) {
134             // keyboard init again
135             if (state == LOOP) {
136                 xprintf("init\n");
137                 state = INIT;
138             }
139         }
140
141         // clear or process error
142         ibmpc_error = IBMPC_ERR_NONE;
143     }
144
145     // check ISR state debug
146     if (ibmpc_isr_debug) {
147         xprintf("\nISR:%04X\n", ibmpc_isr_debug);
148         ibmpc_isr_debug = 0;
149     }
150
151     // check protocol AT/XT
152     if (ibmpc_protocol != current_protocol) {
153         xprintf("\nPROTO:%02X\n", ibmpc_protocol);
154         current_protocol = ibmpc_protocol;
155     }
156
157     switch (state) {
158         case INIT:
159             xprintf("I%u ", timer_read());
160             keyboard_kind = NONE;
161             keyboard_id = 0x0000;
162
163             matrix_clear();
164             clear_keyboard();
165
166             state = XT_RESET;
167             break;
168         case XT_RESET:
169             // Reset XT-initialize keyboard
170             // XT: hard reset 500ms for IBM XT Type-1 keyboard and clones
171             // XT: soft reset 20ms min(clock Lo)
172             ibmpc_host_disable();   // soft reset: inihibit(clock Lo/Data Hi)
173             IBMPC_RST_LO();         // hard reset: reset pin Lo
174
175             init_time = timer_read();
176             state = XT_RESET_WAIT;
177             break;
178         case XT_RESET_WAIT:
179             if (timer_elapsed(init_time) > 500) {
180                 state = XT_RESET_DONE;
181             }
182             break;
183         case XT_RESET_DONE:
184             IBMPC_RST_HIZ();        // hard reset: reset pin HiZ
185             ibmpc_host_isr_clear();
186             ibmpc_host_enable();    // soft reset: idle(clock Hi/Data Hi)
187
188             xprintf("X%u ", timer_read());
189             init_time = timer_read();
190             state = WAIT_AA;
191             break;
192         case WAIT_AA:
193             // 1) Read BAT code and ID on keybaord power-up
194             // For example, XT/AT sends 'AA' and Terminal sends 'AA BF BF' after BAT
195             // AT 84-key: POR and BAT can take 900-9900ms according to AT TechRef [8] 4-7
196             // AT 101/102-key: POR and BAT can take 450-2500ms according to AT TechRef [8] 4-39
197             // 2) Read key typed by user or anything after error on protocol or scan code
198             // This can happen in case of keyboard hotswap, unstable hardware, signal integrity problem or bug
199
200             /* wait until keyboard sends any code without 10000ms timeout
201             if (timer_elapsed(init_time) > 10000) {
202                 state = READ_ID;
203             }
204             */
205             if (ibmpc_host_recv() != -1) {  // wait for AA
206                 xprintf("W%u ", timer_read());
207                 init_time = timer_read();
208                 state = WAIT_AABF;
209             }
210             break;
211         case WAIT_AABF:
212             // NOTE: we can omit to wait BF BF
213             // ID takes 500ms max? TechRef [8] 4-41, though 1ms is enough for 122-key Terminal 6110345
214             if (timer_elapsed(init_time) > 500) {
215                 state = READ_ID;
216             }
217             if (ibmpc_host_recv() != -1) {  // wait for BF
218                 xprintf("W%u ", timer_read());
219                 init_time = timer_read();
220                 state = WAIT_AABFBF;
221             }
222             break;
223         case WAIT_AABFBF:
224             if (timer_elapsed(init_time) > 500) {
225                 state = READ_ID;
226             }
227             if (ibmpc_host_recv() != -1) {  // wait for BF
228                 xprintf("W%u ", timer_read());
229                 state = READ_ID;
230             }
231             break;
232         case READ_ID:
233             xprintf("R%u ", timer_read());
234
235             // SKIDATA-2-DE(and some other keyboards?) stores 'Code Set' setting in nonvlatile memory
236             // and keeps it until receiving reset. Sending reset here may be useful to clear it, perhaps.
237             // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#select-alternate-scan-codesf0
238             //ibmpc_host_send(0xFF);  // reset command
239             //read_wait(500);         // BAT takes 600-900ms(84-key) or 300-500ms(101/102-key) [8] 4-7, 4-39
240
241             keyboard_id = read_keyboard_id();
242             if (ibmpc_error) {
243                 xprintf("\nERR:%02X\n", ibmpc_error);
244                 ibmpc_error = IBMPC_ERR_NONE;
245             }
246
247             if (0x0000 == keyboard_id) {            // CodeSet2 AT(IBM PC AT 84-key)
248                 keyboard_kind = PC_AT;
249             } else if (0xFFFF == keyboard_id) {     // CodeSet1 XT
250                 keyboard_kind = PC_XT;
251             } else if (0xFFFE == keyboard_id) {     // CodeSet2 PS/2 fails to response?
252                 keyboard_kind = PC_AT;
253             } else if (0x00FF == keyboard_id) {     // Mouse is not supported
254                 xprintf("Mouse: not supported\n");
255                 keyboard_kind = NONE;
256 #ifdef G80_2551_SUPPORT
257             } else if (0xAB86 == keyboard_id ||
258                        0xAB85 == keyboard_id) {     // For G80-2551 and other 122-key terminal
259                 // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#ab86
260                 // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#ab85
261
262                 if ((0xFA == ibmpc_host_send(0xF0)) &&
263                     (0xFA == ibmpc_host_send(0x03))) {
264                     // switch to code set 3
265                     keyboard_kind = PC_TERMINAL;
266                 } else {
267                     keyboard_kind = PC_AT;
268                 }
269 #endif
270             } else if (0xBFB0 == keyboard_id) {     // IBM RT Keyboard
271                 // https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#bfb0
272                 // TODO: LED indicator fix
273                 //keyboard_kind = PC_TERMINAL_IBM_RT;
274                 keyboard_kind = PC_TERMINAL;
275             } else if (0xAB00 == (keyboard_id & 0xFF00)) {  // CodeSet2 PS/2
276                 keyboard_kind = PC_AT;
277             } else if (0xBF00 == (keyboard_id & 0xFF00)) {  // CodeSet3 Terminal
278                 keyboard_kind = PC_TERMINAL;
279             } else {
280                 keyboard_kind = PC_AT;
281             }
282
283             xprintf("ID:%04X(%d)\n", keyboard_id, keyboard_kind);
284
285             state = SETUP;
286             break;
287         case SETUP:
288             xprintf("S%u ", timer_read());
289             switch (keyboard_kind) {
290                 case PC_XT:
291                     break;
292                 case PC_AT:
293                     led_set(host_keyboard_leds());
294                     break;
295                 case PC_TERMINAL:
296                     // Set all keys to make/break type
297                     ibmpc_host_send(0xF8);
298                     break;
299                 default:
300                     break;
301             }
302             state = LOOP;
303             xprintf("L%u ", timer_read());
304         case LOOP:
305             switch (keyboard_kind) {
306                 case PC_XT:
307                     if (process_cs1() == -1) state = INIT;
308                     break;
309                 case PC_AT:
310                     if (process_cs2() == -1) state = INIT;
311                     break;
312                 case PC_TERMINAL:
313                     if (process_cs3() == -1) state = INIT;
314                     break;
315                 default:
316                     break;
317             }
318             break;
319         default:
320             break;
321     }
322     return 1;
323 }
324
325 inline
326 bool matrix_is_on(uint8_t row, uint8_t col)
327 {
328     return (matrix[row] & (1<<col));
329 }
330
331 inline
332 uint8_t matrix_get_row(uint8_t row)
333 {
334     return matrix[row];
335 }
336
337 uint8_t matrix_key_count(void)
338 {
339     uint8_t count = 0;
340     for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
341         count += bitpop(matrix[i]);
342     }
343     return count;
344 }
345
346
347 inline
348 static void matrix_make(uint8_t code)
349 {
350     if (!matrix_is_on(ROW(code), COL(code))) {
351         matrix[ROW(code)] |= 1<<COL(code);
352     }
353 }
354
355 inline
356 static void matrix_break(uint8_t code)
357 {
358     if (matrix_is_on(ROW(code), COL(code))) {
359         matrix[ROW(code)] &= ~(1<<COL(code));
360     }
361 }
362
363 void matrix_clear(void)
364 {
365     for (uint8_t i=0; i < MATRIX_ROWS; i++) matrix[i] = 0x00;
366 }
367
368 void led_set(uint8_t usb_led)
369 {
370     //if (keyboard_kind != PC_AT) return;
371
372     uint8_t ibmpc_led = 0;
373     if (usb_led &  (1<<USB_LED_SCROLL_LOCK))
374         ibmpc_led |= (1<<IBMPC_LED_SCROLL_LOCK);
375     if (usb_led &  (1<<USB_LED_NUM_LOCK))
376         ibmpc_led |= (1<<IBMPC_LED_NUM_LOCK);
377     if (usb_led &  (1<<USB_LED_CAPS_LOCK))
378         ibmpc_led |= (1<<IBMPC_LED_CAPS_LOCK);
379     ibmpc_host_set_led(ibmpc_led);
380 }
381
382
383 /*******************************************************************************
384  * XT: Scan Code Set 1
385  *
386  * See [3], [a]
387  *
388  * E0-escaped scan codes are translated into unused range of the matrix.(54-7F)
389  *
390  *     01-53: Normal codes used in original XT keyboard
391  *     54-7F: Not used in original XT keyboard
392  *
393  *         0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
394  *     50  -   -   -   -   *   *   x   x   x   x   *   *   *   *   *   *
395  *     60  *   *   *   *   x   x   x   x   x   x   x   x   x   x   x   *
396  *     70  x   *   *   x   *   *   x   *   *   x   *   x   *   x   x   *
397  *
398  * -: codes existed in original XT keyboard
399  * *: E0-escaped codes translated
400  * x: Non-espcaped codes(Some are not used in real keyboards probably)
401  *
402  * Codes assigned in range 54-7F:
403  *
404  *     50  -                60  Up*                 70  KANAx
405  *     51  -                61  Left*               71  Insert*
406  *     52  -                62  Down*               72  Delete*
407  *     53  -                63  Right*              73  ROx
408  *     54  PrintScr*        64  F13x                74  Home*
409  *     55  Pause*           65  F14x                75  End*
410  *     56  Euro2x           66  F15x                76  F24x
411  *     57  F11x             67  F16x                77  PageUp*
412  *     58  F12x             68  F17x                78  PageDown*
413  *     59  Keypad=x         69  F18x                79  HENKANx
414  *     5A  LGUI*            6A  F19x                7A  RCTL*
415  *     5B  RGUI*            6B  F20x                7B  MUHENKANx
416  *     5C  APP*             6C  F21x                7C  RALT*
417  *     5D  Mute*            6D  F22x                7D  JPYx
418  *     5E  Volume Down*     6E  F23x                7E  Keypad,x
419  *     5F  Volume Up*       6F  Keypad Enter*       7F  Keypad/ *
420  */
421 static uint8_t cs1_e0code(uint8_t code) {
422     switch(code) {
423         // Original IBM XT keyboard doesn't use E0-codes probably
424         // Some XT compatilble keyobards need these keys?
425         case 0x37: return 0x54; // Print Screen
426         case 0x46: return 0x55; // Ctrl + Pause
427         case 0x5B: return 0x5A; // Left  GUI
428         case 0x5C: return 0x5B; // Right GUI
429         case 0x5D: return 0x5C; // Application
430         case 0x20: return 0x5D; // Mute
431         case 0x2E: return 0x5E; // Volume Down
432         case 0x30: return 0x5F; // Volume Up
433         case 0x48: return 0x60; // Up
434         case 0x4B: return 0x61; // Left
435         case 0x50: return 0x62; // Down
436         case 0x4D: return 0x63; // Right
437         case 0x1C: return 0x6F; // Keypad Enter
438         case 0x52: return 0x71; // Insert
439         case 0x53: return 0x72; // Delete
440         case 0x47: return 0x74; // Home
441         case 0x4F: return 0x75; // End
442         case 0x49: return 0x77; // Page Up
443         case 0x51: return 0x78; // Page Down
444         case 0x1D: return 0x7A; // Right Ctrl
445         case 0x38: return 0x7C; // Right Alt
446         case 0x35: return 0x7F; // Keypad /
447
448         // Shared matrix cell with other keys
449         case 0x5E: return 0x70; // Power (KANA)
450         case 0x5F: return 0x79; // Sleep (HENKAN)
451         case 0x63: return 0x7B; // Wake  (MUHENKAN)
452
453         default:
454            xprintf("!CS1_E0_%02X!\n", code);
455            return code;
456     }
457     return 0x00;
458 }
459
460 static int8_t process_cs1(void)
461 {
462     static enum {
463         INIT,
464         E0,
465         // Pause: E1 1D 45, E1 9D C5 [a] (TODO: test)
466         E1,
467         E1_1D,
468         E1_9D,
469     } state = INIT;
470
471     uint16_t code = ibmpc_host_recv();
472     if (code == -1) {
473         return 0;
474     }
475
476     // Check invalid codes; 0x59-7F won't be used in real XT keyboards probably
477     // 0x62 is used to handle escape code E0 and E1
478     if ((code & 0x7F) >= 0x62) {
479         xprintf("!CS1_INV!\n");
480         state = INIT;
481         return -1;
482     }
483
484     switch (state) {
485         case INIT:
486             switch (code) {
487                 case 0x00:
488                 case 0xFF:  // Error/Overrun [3]p.26
489                     xprintf("!CS1_ERR!\n");
490                     return -1;
491                     break;
492                 case 0xE0:
493                     state = E0;
494                     break;
495                 case 0xE1:
496                     state = E1;
497                     break;
498                 default:
499                     if (code < 0x80)
500                         matrix_make(code);
501                     else
502                         matrix_break(code & 0x7F);
503                     break;
504             }
505             break;
506         case E0:
507             switch (code) {
508                 case 0x2A:
509                 case 0xAA:
510                 case 0x36:
511                 case 0xB6:
512                     //ignore fake shift
513                     state = INIT;
514                     break;
515                 default:
516                     if (code < 0x80)
517                         matrix_make(cs1_e0code(code));
518                     else
519                         matrix_break(cs1_e0code(code & 0x7F));
520                     state = INIT;
521                     break;
522             }
523             break;
524         case E1:
525             switch (code) {
526                 case 0x1D:
527                     state = E1_1D;
528                     break;
529                 case 0x9D:
530                     state = E1_9D;
531                     break;
532                 default:
533                     state = INIT;
534                     break;
535             }
536             break;
537         case E1_1D:
538             switch (code) {
539                 case 0x45:
540                     matrix_make(0x55);
541                     break;
542                 default:
543                     state = INIT;
544                     break;
545             }
546             break;
547         case E1_9D:
548             switch (code) {
549                 case 0x45:
550                     matrix_break(0x55);
551                     break;
552                 default:
553                     state = INIT;
554                     break;
555             }
556             break;
557         default:
558             state = INIT;
559     }
560     return 0;
561 }
562
563
564 /*******************************************************************************
565  * AT, PS/2: Scan Code Set 2
566  *
567  * Exceptional Handling
568  * --------------------
569  * Some keys should be handled exceptionally. See [b].
570  *
571  * Scan codes are varied or prefix/postfix'd depending on modifier key state.
572  *
573  * 1) Insert, Delete, Home, End, PageUp, PageDown, Up, Down, Right, Left
574  *     a) when Num Lock is off
575  *     modifiers | make                      | break
576  *     ----------+---------------------------+----------------------
577  *     Ohter     |                    <make> | <break>
578  *     LShift    | E0 F0 12           <make> | <break>  E0 12
579  *     RShift    | E0 F0 59           <make> | <break>  E0 59
580  *     L+RShift  | E0 F0 12  E0 F0 59 <make> | <break>  E0 59 E0 12
581  *
582  *     b) when Num Lock is on
583  *     modifiers | make                      | break
584  *     ----------+---------------------------+----------------------
585  *     Other     | E0 12              <make> | <break>  E0 F0 12
586  *     Shift'd   |                    <make> | <break>
587  *
588  *     Handling: These prefix/postfix codes are ignored.
589  *
590  *
591  * 2) Keypad /
592  *     modifiers | make                      | break
593  *     ----------+---------------------------+----------------------
594  *     Ohter     |                    <make> | <break>
595  *     LShift    | E0 F0 12           <make> | <break>  E0 12
596  *     RShift    | E0 F0 59           <make> | <break>  E0 59
597  *     L+RShift  | E0 F0 12  E0 F0 59 <make> | <break>  E0 59 E0 12
598  *
599  *     Handling: These prefix/postfix codes are ignored.
600  *
601  *
602  * 3) PrintScreen
603  *     modifiers | make         | break
604  *     ----------+--------------+-----------------------------------
605  *     Other     | E0 12  E0 7C | E0 F0 7C  E0 F0 12
606  *     Shift'd   |        E0 7C | E0 F0 7C
607  *     Control'd |        E0 7C | E0 F0 7C
608  *     Alt'd     |           84 | F0 84
609  *
610  *     Handling: These prefix/postfix codes are ignored, and both scan codes
611  *               'E0 7C' and 84 are seen as PrintScreen.
612  *
613  * 4) Pause
614  *     modifiers | make(no break code)
615  *     ----------+--------------------------------------------------
616  *     Other     | E1 14 77 E1 F0 14 F0 77
617  *     Control'd | E0 7E E0 F0 7E
618  *
619  *     Handling: Both code sequences are treated as a whole.
620  *               And we need a ad hoc 'pseudo break code' hack to get the key off
621  *               because it has no break code.
622  *
623  * Notes:
624  * 'Hanguel/English'(F1) and 'Hanja'(F2) have no break code. See [a].
625  * These two Korean keys need exceptional handling and are not supported for now.
626  *
627  */
628 static uint8_t cs2_e0code(uint8_t code) {
629     switch(code) {
630         // E0 prefixed codes translation See [a].
631         case 0x11: return 0x0F; // right alt
632         case 0x14: return 0x17; // right control
633         case 0x1F: return 0x19; // left GUI
634         case 0x27: return 0x1F; // right GUI
635         case 0x2F: return 0x5C; // apps
636         case 0x4A: return 0x60; // keypad /
637         case 0x5A: return 0x62; // keypad enter
638         case 0x69: return 0x27; // end
639         case 0x6B: return 0x53; // cursor left
640         case 0x6C: return 0x2F; // home
641         case 0x70: return 0x39; // insert
642         case 0x71: return 0x37; // delete
643         case 0x72: return 0x3F; // cursor down
644         case 0x74: return 0x47; // cursor right
645         case 0x75: return 0x4F; // cursor up
646         case 0x7A: return 0x56; // page down
647         case 0x7D: return 0x5E; // page up
648         case 0x7C: return 0x7F; // Print Screen
649         case 0x7E: return 0x00; // Control'd Pause
650
651         case 0x21: return 0x65; // volume down
652         case 0x32: return 0x6E; // volume up
653         case 0x23: return 0x6F; // mute
654         case 0x10: return 0x08; // (WWW search)     -> F13
655         case 0x18: return 0x10; // (WWW favourites) -> F14
656         case 0x20: return 0x18; // (WWW refresh)    -> F15
657         case 0x28: return 0x20; // (WWW stop)       -> F16
658         case 0x30: return 0x28; // (WWW forward)    -> F17
659         case 0x38: return 0x30; // (WWW back)       -> F18
660         case 0x3A: return 0x38; // (WWW home)       -> F19
661         case 0x40: return 0x40; // (my computer)    -> F20
662         case 0x48: return 0x48; // (email)          -> F21
663         case 0x2B: return 0x50; // (calculator)     -> F22
664         case 0x34: return 0x08; // (play/pause)     -> F13
665         case 0x3B: return 0x10; // (stop)           -> F14
666         case 0x15: return 0x18; // (previous track) -> F15
667         case 0x4D: return 0x20; // (next track)     -> F16
668         case 0x50: return 0x28; // (media select)   -> F17
669         case 0x5E: return 0x50; // (ACPI wake)      -> F22
670         case 0x3F: return 0x57; // (ACPI sleep)     -> F23
671         case 0x37: return 0x5F; // (ACPI power)     -> F24
672
673         // https://github.com/tmk/tmk_keyboard/pull/636
674         case 0x03: return 0x18; // Help        DEC LK411 -> F15
675         case 0x04: return 0x08; // F13         DEC LK411
676         case 0x0B: return 0x20; // Do          DEC LK411 -> F16
677         case 0x0C: return 0x10; // F14         DEC LK411
678         case 0x0D: return 0x19; // LCompose    DEC LK411 -> LGUI
679         case 0x79: return 0x6D; // KP-         DEC LK411 -> PCMM
680         case 0x83: return 0x28; // F17         DEC LK411
681         default: return (code & 0x7F);
682     }
683 }
684
685 static int8_t process_cs2(void)
686 {
687     // scan code reading states
688     static enum {
689         INIT,
690         F0,
691         E0,
692         E0_F0,
693         // Pause
694         E1,
695         E1_14,
696         E1_F0,
697         E1_F0_14,
698         E1_F0_14_F0,
699     } state = INIT;
700
701     uint16_t code = ibmpc_host_recv();
702     if (code == -1) {
703         return 0;
704     }
705
706     switch (state) {
707         case INIT:
708             switch (code) {
709                 case 0x00:  // Error/Overrun [3]p.26
710                     xprintf("!CS2_OVR!\n");
711                     matrix_clear();
712                     clear_keyboard();
713                     break;
714                 case 0xFF:
715                     matrix_clear();
716                     xprintf("!CS2_ERR!\n");
717                     state = INIT;
718                     return -1;
719                     break;
720                 case 0xE0:
721                     state = E0;
722                     break;
723                 case 0xF0:
724                     state = F0;
725                     break;
726                 case 0xE1:
727                     state = E1;
728                     break;
729                 case 0x83:  // F7
730                     matrix_make(0x02);
731                     state = INIT;
732                     break;
733                 case 0x84:  // Alt'd PrintScreen
734                     matrix_make(0x7F);
735                     state = INIT;
736                     break;
737                 case 0xAA:  // Self-test passed
738                 case 0xFC:  // Self-test failed
739                     // reset or plugin-in new keyboard
740                     state = INIT;
741                     return -1;
742                     break;
743                 default:    // normal key make
744                     state = INIT;
745                     if (code < 0x80) {
746                         matrix_make(code);
747                     } else {
748                         matrix_clear();
749                         xprintf("!CS2_INIT!\n");
750                         return -1;
751                     }
752             }
753             break;
754         case E0:    // E0-Prefixed
755             switch (code) {
756                 case 0x12:  // to be ignored
757                 case 0x59:  // to be ignored
758                     state = INIT;
759                     break;
760                 case 0xF0:
761                     state = E0_F0;
762                     break;
763                 default:
764                     state = INIT;
765                     if (code < 0x80) {
766                         matrix_make(cs2_e0code(code));
767                     } else {
768                         matrix_clear();
769                         xprintf("!CS2_E0!\n");
770                         return -1;
771                     }
772             }
773             break;
774         case F0:    // Break code
775             switch (code) {
776                 case 0x83:  // F7
777                     matrix_break(0x02);
778                     state = INIT;
779                     break;
780                 case 0x84:  // Alt'd PrintScreen
781                     matrix_break(0x7F);
782                     state = INIT;
783                     break;
784                 default:
785                     state = INIT;
786                     if (code < 0x80) {
787                         matrix_break(code);
788                     } else {
789                         matrix_clear();
790                         xprintf("!CS2_F0!\n");
791                         return -1;
792                     }
793             }
794             break;
795         case E0_F0: // Break code of E0-prefixed
796             switch (code) {
797                 case 0x12:  // to be ignored
798                 case 0x59:  // to be ignored
799                     state = INIT;
800                     break;
801                 default:
802                     state = INIT;
803                     if (code < 0x80) {
804                         matrix_break(cs2_e0code(code));
805                     } else {
806                         matrix_clear();
807                         xprintf("!CS2_E0_F0!\n");
808                         return -1;
809                     }
810             }
811             break;
812         // Pause make: E1 14 77
813         case E1:
814             switch (code) {
815                 case 0x14:
816                     state = E1_14;
817                     break;
818                 case 0xF0:
819                     state = E1_F0;
820                     break;
821                 default:
822                     state = INIT;
823             }
824             break;
825         case E1_14:
826             switch (code) {
827                 case 0x77:
828                     matrix_make(0x00);
829                     state = INIT;
830                     break;
831                 default:
832                     state = INIT;
833             }
834             break;
835         // Pause break: E1 F0 14 F0 77
836         case E1_F0:
837             switch (code) {
838                 case 0x14:
839                     state = E1_F0_14;
840                     break;
841                 default:
842                     state = INIT;
843             }
844             break;
845         case E1_F0_14:
846             switch (code) {
847                 case 0xF0:
848                     state = E1_F0_14_F0;
849                     break;
850                 default:
851                     state = INIT;
852             }
853             break;
854         case E1_F0_14_F0:
855             switch (code) {
856                 case 0x77:
857                     matrix_break(0x00);
858                     state = INIT;
859                     break;
860                 default:
861                     state = INIT;
862             }
863             break;
864         default:
865             state = INIT;
866     }
867     return 0;
868 }
869
870 /*
871  * Terminal: Scan Code Set 3
872  *
873  * See [3], [7] and
874  * https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#scan-code-set-3
875  */
876 static int8_t process_cs3(void)
877 {
878     static enum {
879         READY,
880         F0,
881 #ifdef G80_2551_SUPPORT
882         // G80-2551 four extra keys around cursor keys
883         G80,
884         G80_F0,
885 #endif
886     } state = READY;
887
888     uint16_t code = ibmpc_host_recv();
889     if (code == -1) {
890         return 0;
891     }
892
893     switch (state) {
894         case READY:
895             switch (code) {
896                 case 0x00:  // Error/Overrun [3]p.26
897                     xprintf("!CS3_OVR!\n");
898                     matrix_clear();
899                     clear_keyboard();
900                     break;
901                 case 0xFF:
902                     xprintf("!CS3_ERR!\n");
903                     return -1;
904                     break;
905                 case 0xF0:
906                     state = F0;
907                     break;
908                 case 0x83:  // PrintScreen
909                     matrix_make(0x02);
910                     break;
911                 case 0x84:  // Keypad *
912                     matrix_make(0x7F);
913                     break;
914                 case 0x85:  // Muhenkan
915                     matrix_make(0x0B);
916                     break;
917                 case 0x86:  // Henkan
918                     matrix_make(0x06);
919                     break;
920                 case 0x87:  // Hiragana
921                     matrix_make(0x00);
922                     break;
923                 case 0x8B:  // Left GUI
924                     matrix_make(0x01);
925                     break;
926                 case 0x8C:  // Right GUI
927                     matrix_make(0x09);
928                     break;
929                 case 0x8D:  // Application
930                     matrix_make(0x0A);
931                     break;
932 #ifdef G80_2551_SUPPORT
933                 case 0x80:  // G80-2551 four extra keys around cursor keys
934                     state = G80;
935                     break;
936 #endif
937                 default:    // normal key make
938                     if (code < 0x80) {
939                         matrix_make(code);
940                     } else {
941                         xprintf("!CS3_READY!\n");
942                         //return -1;
943                     }
944             }
945             break;
946         case F0:    // Break code
947             switch (code) {
948                 case 0x00:
949                     xprintf("!CS3_F0_OVR!\n");
950                     matrix_clear();
951                     clear_keyboard();
952                     state = READY;
953                     break;
954                 case 0xFF:
955                     xprintf("!CS3_F0_ERR!\n");
956                     state = READY;
957                     return -1;
958                     break;
959                 case 0x83:  // PrintScreen
960                     matrix_break(0x02);
961                     state = READY;
962                     break;
963                 case 0x84:  // Keypad *
964                     matrix_break(0x7F);
965                     state = READY;
966                     break;
967                 case 0x85:  // Muhenkan
968                     matrix_break(0x0B);
969                     state = READY;
970                     break;
971                 case 0x86:  // Henkan
972                     matrix_break(0x06);
973                     state = READY;
974                     break;
975                 case 0x87:  // Hiragana
976                     matrix_break(0x00);
977                     state = READY;
978                     break;
979                 case 0x8B:  // Left GUI
980                     matrix_break(0x01);
981                     state = READY;
982                     break;
983                 case 0x8C:  // Right GUI
984                     matrix_break(0x09);
985                     state = READY;
986                     break;
987                 case 0x8D:  // Application
988                     matrix_break(0x0A);
989                     state = READY;
990                     break;
991                 default:
992                     state = READY;
993                     if (code < 0x80) {
994                         matrix_break(code);
995                     } else {
996                         xprintf("!CS3_F0!\n");
997                         //return -1;
998                     }
999             }
1000             break;
1001 #ifdef G80_2551_SUPPORT
1002         /*
1003          * G80-2551 terminal keyboard support
1004          * https://deskthority.net/wiki/Cherry_G80-2551
1005          * https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-AT-Keyboard-Protocol#g80-2551-in-code-set-3
1006          */
1007         case G80:   // G80-2551 four extra keys around cursor keys
1008             switch (code) {
1009                 case (0x26):    // TD= -> JYEN
1010                     matrix_make(0x5D);
1011                     break;
1012                 case (0x25):    // page with edge -> NUHS
1013                     matrix_make(0x53);
1014                     break;
1015                 case (0x16):    // two pages -> RO
1016                     matrix_make(0x51);
1017                     break;
1018                 case (0x1E):    // calc -> KANA
1019                     matrix_make(0x00);
1020                     break;
1021                 case (0xF0):
1022                     state = G80_F0;
1023                     return 0;
1024                 default:
1025                     // Not supported
1026                     matrix_clear();
1027                     break;
1028             }
1029             state = READY;
1030             break;
1031         case G80_F0:
1032             switch (code) {
1033                 case (0x26):    // TD= -> JYEN
1034                     matrix_break(0x5D);
1035                     break;
1036                 case (0x25):    // page with edge -> NUHS
1037                     matrix_break(0x53);
1038                     break;
1039                 case (0x16):    // two pages -> RO
1040                     matrix_break(0x51);
1041                     break;
1042                 case (0x1E):    // calc -> KANA
1043                     matrix_break(0x00);
1044                     break;
1045                 default:
1046                     // Not supported
1047                     matrix_clear();
1048                     break;
1049             }
1050             state = READY;
1051             break;
1052 #endif
1053     }
1054     return 0;
1055 }
1056
1057 /*
1058  * IBM PC Keyboard Protocol Resources:
1059  *
1060  * [a] Microsoft USB HID to PS/2 Translation Table - Scan Code Set 1 and 2
1061  * http://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/translate.pdf
1062  *
1063  * [b] Microsoft Keyboard Scan Code Specification - Special rules of Scan Code Set 1 and 2
1064  * http://download.microsoft.com/download/1/6/1/161ba512-40e2-4cc9-843a-923143f3456c/scancode.doc
1065  *
1066  * [1] PS/2 Reference Manuals - Collection of IBM Personal System/2 documents.
1067  * http://www.mcamafia.de/pdf/pdfref.htm
1068  *
1069  * [2] Keyboard and Auxiliary Device Controller - Signal Timing and Format
1070  * http://www.mcamafia.de/pdf/ibm_hitrc07.pdf
1071  *
1072  * [3] Keyboards(101- and 102-key) - Keyboard Layout, Scan Code Set, POR, and Commands.
1073  * http://www.mcamafia.de/pdf/ibm_hitrc11.pdf
1074  *
1075  * [4] IBM PC XT Keyboard Protocol
1076  * https://github.com/tmk/tmk_keyboard/wiki/IBM-PC-XT-Keyboard-Protocol
1077  *
1078  * [5] IBM Keyboard Scan Code by John Elliott - 83-key, 84-key, 102-key and 122-key
1079  * https://www.seasip.info/VintagePC/index.html
1080  *
1081  * [6] IBM 1391406 Keyboard - Scan Code Set 2 of 102-key PS/2 keyboard
1082  * https://www.seasip.info/VintagePC/ibm_1391406.html
1083  *
1084  * [7] The IBM 6110344 Keyboard - Scan Code Set 3 of 122-key terminal keyboard
1085  * https://www.seasip.info/VintagePC/ibm_6110344.html
1086  *
1087  * [8] IBM PC AT Technical Reference 1986
1088  * http://bitsavers.org/pdf/ibm/pc/at/6183355_PC_AT_Technical_Reference_Mar86.pdf
1089  *
1090  * [y] TrackPoint Engineering Specifications for version 3E
1091  * https://web.archive.org/web/20100526161812/http://wwwcssrv.almaden.ibm.com/trackpoint/download.html
1092  *
1093  * [z] [Soarer's XT/AT/PS2/Terminal to USB converter]
1094  * https://geekhack.org/index.php?topic=17458.0
1095  *
1096  */