]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - converter/adb_usb/matrix.c
adb_usb: Add support for Apple Adjustable keybaord media keys
[max/tmk_keyboard.git] / converter / adb_usb / matrix.c
1 /*
2 Copyright 2011 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 /*
19  * scan matrix
20  */
21 #include <stdint.h>
22 #include <stdbool.h>
23 #include <avr/io.h>
24 #include <util/delay.h>
25 #include "print.h"
26 #include "util.h"
27 #include "debug.h"
28 #include "adb.h"
29 #include "matrix.h"
30 #include "report.h"
31 #include "host.h"
32
33
34 #if (MATRIX_COLS > 16)
35 #   error "MATRIX_COLS must not exceed 16"
36 #endif
37 #if (MATRIX_ROWS > 255)
38 #   error "MATRIX_ROWS must not exceed 255"
39 #endif
40
41
42 static bool has_media_keys = false;
43 static bool is_iso_layout = false;
44 static bool is_modified = false;
45 static report_mouse_t mouse_report = {};
46
47 // matrix state buffer(1:on, 0:off)
48 #if (MATRIX_COLS <= 8)
49 static uint8_t matrix[MATRIX_ROWS];
50 #else
51 static uint16_t matrix[MATRIX_ROWS];
52 #endif
53
54 #ifdef MATRIX_HAS_GHOST
55 static bool matrix_has_ghost_in_row(uint8_t row);
56 #endif
57 static void register_key(uint8_t key);
58
59
60 inline
61 uint8_t matrix_rows(void)
62 {
63     return MATRIX_ROWS;
64 }
65
66 inline
67 uint8_t matrix_cols(void)
68 {
69     return MATRIX_COLS;
70 }
71
72 void matrix_init(void)
73 {
74     // LED on
75     DDRD |= (1<<6); PORTD |= (1<<6);
76
77     adb_host_init();
78     // wait for keyboard to boot up and receive command
79     _delay_ms(2000);
80
81     // device scan
82     xprintf("Before init:\n");
83     for (uint8_t addr = 1; addr < 16; addr++) {
84         uint16_t reg3 = adb_host_talk(addr, ADB_REG_3);
85         if (reg3) {
86             xprintf("Scan: addr:%d, reg3:%04X\n", addr, reg3);
87         }
88         _delay_ms(20);
89     }
90
91     // Determine ISO keyboard by handler id
92     // http://lxr.free-electrons.com/source/drivers/macintosh/adbhid.c?v=4.4#L815
93     uint16_t handler_id = adb_host_talk(ADB_ADDR_KEYBOARD, ADB_REG_3);
94     switch (handler_id) {
95     case 0x04: case 0x05: case 0x07: case 0x09: case 0x0D:
96     case 0x11: case 0x14: case 0x19: case 0x1D: case 0xC1:
97     case 0xC4: case 0xC7:
98         is_iso_layout = true;
99         break;
100     default:
101         is_iso_layout = false;
102         break;
103     }
104
105     // Adjustable keyboard media keys: address=0x07 and handlerID=0x02
106     has_media_keys = (0x02 == (adb_host_talk(ADB_ADDR_APPLIANCE, ADB_REG_3) & 0xff));
107     if (has_media_keys) {
108         xprintf("Found: media keys\n");
109     }
110
111     // Enable keyboard left/right modifier distinction
112     // Listen Register3
113     //  upper byte: reserved bits 0000, keyboard address 0010
114     //  lower byte: device handler 00000011
115     adb_host_listen(ADB_ADDR_KEYBOARD, ADB_REG_3, ADB_ADDR_KEYBOARD, ADB_HANDLER_EXTENDED_PROTOCOL);
116
117     // device scan
118     xprintf("After init:\n");
119     for (uint8_t addr = 1; addr < 16; addr++) {
120         uint16_t reg3 = adb_host_talk(addr, ADB_REG_3);
121         if (reg3) {
122             xprintf("Scan: addr:%d, reg3:%04X\n", addr, reg3);
123         }
124         _delay_ms(20);
125     }
126
127     // initialize matrix state: all keys off
128     for (uint8_t i=0; i < MATRIX_ROWS; i++) matrix[i] = 0x00;
129
130     debug_enable = true;
131     //debug_matrix = true;
132     //debug_keyboard = true;
133     //debug_mouse = true;
134     print("debug enabled.\n");
135
136     // LED off
137     DDRD |= (1<<6); PORTD &= ~(1<<6);
138     return;
139 }
140
141 #ifdef ADB_MOUSE_ENABLE
142
143 #ifdef MAX
144 #undef MAX
145 #endif
146 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
147
148 void adb_mouse_task(void)
149 {
150     uint16_t codes;
151     int16_t x, y;
152     static int8_t mouseacc;
153     _delay_ms(12);  // delay for preventing overload of poor ADB keyboard controller
154     codes = adb_host_mouse_recv();
155     // If nothing received reset mouse acceleration, and quit.
156     if (!codes) {
157         mouseacc = 1;
158         return;
159     };
160     // Bit sixteen is button.
161     if (~codes & (1 << 15))
162         mouse_report.buttons |= MOUSE_BTN1;
163     if (codes & (1 << 15))
164         mouse_report.buttons &= ~MOUSE_BTN1;
165     // lower seven bits are movement, as signed int_7.
166     // low byte is X-axis, high byte is Y.
167     y = (codes>>8 & 0x3F);
168     x = (codes>>0 & 0x3F);
169     // bit seven and fifteen is negative
170     // usb does not use int_8, but int_7 (measuring distance) with sign-bit.
171     if (codes & (1 << 6))
172           x = (x-0x40);
173     if (codes & (1 << 14))
174          y = (y-0x40);
175     // Accelerate mouse. (They weren't meant to be used on screens larger than 320x200).
176     x *= mouseacc;
177     y *= mouseacc;
178     // Cap our two bytes per axis to one byte.
179     // Easier with a MIN-function, but since -MAX(-a,-b) = MIN(a,b)...
180          // I.E. MIN(MAX(x,-127),127) = -MAX(-MAX(x, -127), -127) = MIN(-MIN(-x,127),127)
181     mouse_report.x = -MAX(-MAX(x, -127), -127);
182     mouse_report.y = -MAX(-MAX(y, -127), -127);
183     if (debug_mouse) {
184             print("adb_host_mouse_recv: "); print_bin16(codes); print("\n");
185             print("adb_mouse raw: [");
186             phex(mouseacc); print(" ");
187             phex(mouse_report.buttons); print("|");
188             print_decs(mouse_report.x); print(" ");
189             print_decs(mouse_report.y); print("]\n");
190     }
191     // Send result by usb.
192     host_mouse_send(&mouse_report);
193     // increase acceleration of mouse
194     mouseacc += ( mouseacc < ADB_MOUSE_MAXACC ? 1 : 0 );
195     return;
196 }
197 #endif
198
199 uint8_t matrix_scan(void)
200 {
201     /* extra_key is volatile and more convoluted than necessary because gcc refused
202     to generate valid code otherwise. Making extra_key uint8_t and constructing codes
203     here via codes = extra_key<<8 | 0xFF; would consistently fail to even LOAD
204     extra_key from memory, and leave garbage in the high byte of codes. I tried
205     dozens of code variations and it kept generating broken assembly output. So
206     beware if attempting to make extra_key code more logical and efficient. */
207     static volatile uint16_t extra_key = 0xFFFF;
208     uint16_t codes;
209     uint8_t key0, key1;
210
211     is_modified = false;
212
213     codes = extra_key;
214     extra_key = 0xFFFF;
215
216     if ( codes == 0xFFFF )
217     {
218         _delay_ms(12);  // delay for preventing overload of poor ADB keyboard controller
219         codes = adb_host_kbd_recv(ADB_ADDR_KEYBOARD);
220
221         // Adjustable keybaord media keys
222         if (codes == 0 && has_media_keys &&
223                 (codes = adb_host_kbd_recv(ADB_ADDR_APPLIANCE))) {
224             // key1
225             switch (codes & 0x7f ) {
226             case 0x00:  // Mic
227                 codes = (codes & ~0x007f) | 0x42;
228                 break;
229             case 0x01:  // Mute
230                 codes = (codes & ~0x007f) | 0x4a;
231                 break;
232             case 0x02:  // Volume down
233                 codes = (codes & ~0x007f) | 0x49;
234                 break;
235             case 0x03:  // Volume Up
236                 codes = (codes & ~0x007f) | 0x48;
237                 break;
238             case 0x7F:  // no code
239                 break;
240             default:
241                 xprintf("ERROR: media key1\n");
242                 return 0x11;
243             }
244             // key0
245             switch ((codes >> 8) & 0x7f ) {
246             case 0x00:  // Mic
247                 codes = (codes & ~0x7f00) | (0x42 << 8);
248                 break;
249             case 0x01:  // Mute
250                 codes = (codes & ~0x7f00) | (0x4a << 8);
251                 break;
252             case 0x02:  // Volume down
253                 codes = (codes & ~0x7f00) | (0x49 << 8);
254                 break;
255             case 0x03:  // Volume Up
256                 codes = (codes & ~0x7f00) | (0x48 << 8);
257                 break;
258             default:
259                 xprintf("ERROR: media key0\n");
260                 return 0x10;
261             }
262         }
263     }
264     key0 = codes>>8;
265     key1 = codes&0xFF;
266
267     if (debug_matrix && codes) {
268         print("adb_host_kbd_recv: "); phex16(codes); print("\n");
269     }
270
271     if (codes == 0) {                           // no keys
272         return 0;
273     } else if (codes == 0x7F7F) {   // power key press
274         register_key(0x7F);
275     } else if (codes == 0xFFFF) {   // power key release
276         register_key(0xFF);
277     } else if (key0 == 0xFF) {      // error
278         xprintf("adb_host_kbd_recv: ERROR(%d)\n", codes);
279         // something wrong or plug-in
280         matrix_init();
281         return key1;
282     } else {
283         /* Swap codes for ISO keyboard
284          * https://github.com/tmk/tmk_keyboard/issues/35
285          *
286          * ANSI
287          * ,-----------    ----------.
288          * | *a|  1|  2     =|Backspa|
289          * |-----------    ----------|
290          * |Tab  |  Q|     |  ]|   *c|
291          * |-----------    ----------|
292          * |CapsLo|  A|    '|Return  |
293          * |-----------    ----------|
294          * |Shift   |      Shift     |
295          * `-----------    ----------'
296          *
297          * ISO
298          * ,-----------    ----------.
299          * | *a|  1|  2     =|Backspa|
300          * |-----------    ----------|
301          * |Tab  |  Q|     |  ]|Retur|
302          * |-----------    -----`    |
303          * |CapsLo|  A|    '| *c|    |
304          * |-----------    ----------|
305          * |Shif| *b|      Shift     |
306          * `-----------    ----------'
307          *
308          *         ADB scan code   USB usage
309          *         -------------   ---------
310          * Key     ANSI    ISO     ANSI    ISO
311          * ---------------------------------------------
312          * *a      0x32    0x0A    0x35    0x35
313          * *b      ----    0x32    ----    0x64
314          * *c      0x2A    0x2A    0x31    0x31(or 0x32)
315          */
316         if (is_iso_layout) {
317             if ((key0 & 0x7F) == 0x32) {
318                 key0 = (key0 & 0x80) | 0x0A;
319             } else if ((key0 & 0x7F) == 0x0A) {
320                 key0 = (key0 & 0x80) | 0x32;
321             }
322         }
323         register_key(key0);
324         if (key1 != 0xFF)       // key1 is 0xFF when no second key.
325             extra_key = key1<<8 | 0xFF; // process in a separate call
326     }
327
328     return 1;
329 }
330
331 bool matrix_is_modified(void)
332 {
333     return is_modified;
334 }
335
336 inline
337 bool matrix_has_ghost(void)
338 {
339 #ifdef MATRIX_HAS_GHOST
340     for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
341         if (matrix_has_ghost_in_row(i))
342             return true;
343     }
344 #endif
345     return false;
346 }
347
348 inline
349 bool matrix_is_on(uint8_t row, uint8_t col)
350 {
351     return (matrix[row] & (1<<col));
352 }
353
354 inline
355 #if (MATRIX_COLS <= 8)
356 uint8_t matrix_get_row(uint8_t row)
357 #else
358 uint16_t matrix_get_row(uint8_t row)
359 #endif
360 {
361     return matrix[row];
362 }
363
364 void matrix_print(void)
365 {
366     if (!debug_matrix) return;
367 #if (MATRIX_COLS <= 8)
368     print("r/c 01234567\n");
369 #else
370     print("r/c 0123456789ABCDEF\n");
371 #endif
372     for (uint8_t row = 0; row < matrix_rows(); row++) {
373         phex(row); print(": ");
374 #if (MATRIX_COLS <= 8)
375         pbin_reverse(matrix_get_row(row));
376 #else
377         pbin_reverse16(matrix_get_row(row));
378 #endif
379 #ifdef MATRIX_HAS_GHOST
380         if (matrix_has_ghost_in_row(row)) {
381             print(" <ghost");
382         }
383 #endif
384         print("\n");
385     }
386 }
387
388 uint8_t matrix_key_count(void)
389 {
390     uint8_t count = 0;
391     for (uint8_t i = 0; i < MATRIX_ROWS; i++) {
392 #if (MATRIX_COLS <= 8)
393         count += bitpop(matrix[i]);
394 #else
395         count += bitpop16(matrix[i]);
396 #endif
397     }
398     return count;
399 }
400
401 #ifdef MATRIX_HAS_GHOST
402 inline
403 static bool matrix_has_ghost_in_row(uint8_t row)
404 {
405     // no ghost exists in case less than 2 keys on
406     if (((matrix[row] - 1) & matrix[row]) == 0)
407         return false;
408
409     // ghost exists in case same state as other row
410     for (uint8_t i=0; i < MATRIX_ROWS; i++) {
411         if (i != row && (matrix[i] & matrix[row]) == matrix[row])
412             return true;
413     }
414     return false;
415 }
416 #endif
417
418 inline
419 static void register_key(uint8_t key)
420 {
421     uint8_t col, row;
422     col = key&0x07;
423     row = (key>>3)&0x0F;
424     if (key&0x80) {
425         matrix[row] &= ~(1<<col);
426     } else {
427         matrix[row] |=  (1<<col);
428     }
429     is_modified = true;
430 }