]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - converter/adb_usb/matrix.c
c9113c3cee103a419308f557b04b521429048b0d
[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 #include "led.h"
33 #include "timer.h"
34
35
36
37
38 static bool has_media_keys = false;
39 static bool is_iso_layout = false;
40 static uint8_t mouse_handler = ADB_HANDLER_CLASSIC1_MOUSE;
41
42 // matrix state buffer(1:on, 0:off)
43 static matrix_row_t matrix[MATRIX_ROWS];
44
45 static void register_key(uint8_t key);
46
47
48 void matrix_init(void)
49 {
50     // LED on
51     DDRD |= (1<<6); PORTD |= (1<<6);
52
53     adb_host_init();
54     // wait for keyboard to boot up and receive command
55     _delay_ms(2000);
56
57     // device scan
58     xprintf("\nScan:\n");
59     for (uint8_t addr = 1; addr < 16; addr++) {
60         uint16_t reg3 = adb_host_talk(addr, ADB_REG_3);
61         if (reg3) {
62             xprintf(" addr:%d, reg3:%04X\n", addr, reg3);
63         }
64         _delay_ms(20);
65     }
66
67
68     //
69     // Keyboard
70     //
71     xprintf("\nKeyboard:\n");
72     // Determine ISO keyboard by handler id
73     // http://lxr.free-electrons.com/source/drivers/macintosh/adbhid.c?v=4.4#L815
74     uint8_t handler_id = (uint8_t) adb_host_talk(ADB_ADDR_KEYBOARD, ADB_REG_3);
75     switch (handler_id) {
76     case 0x04: case 0x05: case 0x07: case 0x09: case 0x0D:
77     case 0x11: case 0x14: case 0x19: case 0x1D: case 0xC1:
78     case 0xC4: case 0xC7:
79         is_iso_layout = true;
80         break;
81     default:
82         is_iso_layout = false;
83         break;
84     }
85     xprintf("hadler: %02X, ISO: %s\n", handler_id, (is_iso_layout ? "yes" : "no"));
86
87     // Adjustable keyboard media keys: address=0x07 and handlerID=0x02
88     has_media_keys = (0x02 == (adb_host_talk(ADB_ADDR_APPLIANCE, ADB_REG_3) & 0xff));
89     if (has_media_keys) {
90         xprintf("Media keys\n");
91     }
92
93     // Enable keyboard left/right modifier distinction
94     // Listen Register3
95     //  upper byte: reserved bits 0000, keyboard address 0010
96     //  lower byte: device handler 00000011
97     adb_host_listen(ADB_ADDR_KEYBOARD, ADB_REG_3, ADB_ADDR_KEYBOARD, ADB_HANDLER_EXTENDED_KEYBOARD);
98
99
100     #ifdef ADB_MOUSE_ENABLE
101     //
102     // Mouse
103     //
104     // https://developer.apple.com/library/archive/technotes/hw/hw_01.html#Extended
105     xprintf("\nMouse:\n");
106
107     // Some old mouses seems to need wait between commands.
108     _delay_ms(20);
109     adb_host_listen(ADB_ADDR_MOUSE, ADB_REG_3, ADB_ADDR_MOUSE, ADB_HANDLER_CLASSIC2_MOUSE);
110
111     _delay_ms(20);
112     adb_host_listen(ADB_ADDR_MOUSE, ADB_REG_3, ADB_ADDR_MOUSE, ADB_HANDLER_EXTENDED_MOUSE);
113
114     _delay_ms(20);
115     mouse_handler = adb_host_talk(ADB_ADDR_MOUSE, ADB_REG_3) & 0xff;
116     mouse_handler = mouse_handler ? mouse_handler : ADB_HANDLER_CLASSIC1_MOUSE;
117
118     // Extended Mouse Protocol
119     if (mouse_handler == ADB_HANDLER_EXTENDED_MOUSE) {
120         // Device info format(reg1 8-byte data)
121         // 0-3: device id
122         // 4-5: resolution in units/inch (0xC8=200upi)
123         // 6  : device class      (0: Tablet, 1: Mouse, 2: Trackball)
124         // 7  : num of buttons
125         uint8_t len;
126         uint8_t buf[8];
127         len = adb_host_talk_buf(ADB_ADDR_MOUSE, ADB_REG_1, buf, sizeof(buf));
128         if (len) {
129             xprintf("Devinfo: [", len);
130             for (int8_t i = 0; i < len; i++) xprintf("%02X ", buf[i]);
131             xprintf("]\n");
132         }
133
134         // Kensington Turbo Mouse 5
135         if (len == 8 && buf[0] == 0x4B && buf[1] == 0x4D && buf[2] == 0x4C && buf[3] == 0x31) {
136             xprintf("Turbo Mouse 5\n");
137
138             // Turbo Mouse command sequence to enable four buttons
139             // https://elixir.bootlin.com/linux/v4.4/source/drivers/macintosh/adbhid.c#L1176
140             // https://github.com/NetBSD/src/blob/64b8a48e1288eb3902ed73113d157af50b2ec596/sys/arch/macppc/dev/ams.c#L261
141             static uint8_t cmd1[] = { 0xE7, 0x8C, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x94 };
142             static uint8_t cmd2[] = { 0xA5, 0x14, 0x00, 0x00, 0x69, 0xFF, 0xFF, 0x27 };
143
144             // configure with new address 9
145             adb_host_listen(ADB_ADDR_MOUSE, ADB_REG_3, 0x69, 0xFE);
146             adb_host_flush(9);
147
148             adb_host_flush(ADB_ADDR_MOUSE);
149             adb_host_listen_buf(ADB_ADDR_MOUSE, ADB_REG_2, cmd1, sizeof(cmd1));
150             adb_host_flush(ADB_ADDR_MOUSE);
151             adb_host_listen_buf(ADB_ADDR_MOUSE, ADB_REG_2, cmd2, sizeof(cmd2));
152         }
153
154         // Add device specific init here
155     }
156     mouse_handler = adb_host_talk(ADB_ADDR_MOUSE, ADB_REG_3) & 0xff;
157     mouse_handler = mouse_handler ? mouse_handler : ADB_HANDLER_CLASSIC1_MOUSE;
158     xprintf("handler: %d\n", mouse_handler);
159     #endif
160
161
162     xprintf("\nScan:\n");
163     for (uint8_t addr = 1; addr < 16; addr++) {
164         uint16_t reg3 = adb_host_talk(addr, ADB_REG_3);
165         if (reg3) {
166             xprintf(" addr:%d, reg3:%04X\n", addr, reg3);
167         }
168         _delay_ms(20);
169     }
170
171     // initialize matrix state: all keys off
172     for (uint8_t i=0; i < MATRIX_ROWS; i++) matrix[i] = 0x00;
173
174     led_set(host_keyboard_leds());
175
176     debug_enable = true;
177     //debug_matrix = true;
178     //debug_keyboard = true;
179     debug_mouse = true;
180
181     // LED off
182     DDRD |= (1<<6); PORTD &= ~(1<<6);
183     return;
184 }
185
186 #ifdef ADB_MOUSE_ENABLE
187
188 #ifdef MAX
189 #undef MAX
190 #endif
191 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
192
193 static report_mouse_t mouse_report = {};
194
195 void adb_mouse_task(void)
196 {
197     uint8_t len;
198     uint8_t buf[5];
199     int16_t x, y;
200     static int8_t mouseacc;
201
202     /* tick of last polling */
203     static uint16_t tick_ms;
204
205     // polling with 12ms interval
206     if (timer_elapsed(tick_ms) < 12) return;
207     tick_ms = timer_read();
208
209     // Extended Mouse Protocol data can be 2-5 bytes
210     // https://developer.apple.com/library/archive/technotes/hw/hw_01.html#Extended
211     //
212     //   Byte 0: b00 y06 y05 y04 y03 y02 y01 y00
213     //   Byte 1: b01 x06 x05 x04 x03 x02 x01 x00
214     //   Byte 2: b02 y09 y08 y07 b03 x09 x08 x07
215     //   Byte 3: b04 y12 y11 y10 b05 x12 x11 x10
216     //   Byte 4: b06 y15 y14 y13 b07 x15 x14 x13
217     //
218     //   b--: Button state.(0: on, 1: off)
219     //   x--: X axis movement.
220     //   y--: Y axis movement.
221     len = adb_host_talk_buf(ADB_ADDR_MOUSE, ADB_REG_0, buf, sizeof(buf));
222
223     // If nothing received reset mouse acceleration, and quit.
224     if (len < 2) {
225         mouseacc = 1;
226         return;
227     };
228
229     // Store off-buttons and 0-movements in unused bytes
230     bool xneg = false;
231     bool yneg = false;
232     if (len == 2) {
233         if (buf[0] & 0x40) yneg = true;
234         if (buf[1] & 0x40) xneg = true;
235     } else {
236         if (buf[len - 1] & 0x40) yneg = true;
237         if (buf[len - 1] & 0x04) xneg = true;
238     }
239
240     for (int8_t i = len; i < sizeof(buf); i++) {
241         buf[i] = 0x88;
242         if (yneg) buf[i] |= 0x70;
243         if (xneg) buf[i] |= 0x07;
244     }
245
246     // 8 buttons at max
247     // TODO: Fix HID report descriptor for mouse to support button6-8
248     uint8_t buttons = 0;
249     if (!(buf[4] & 0x08)) buttons |= MOUSE_BTN8;
250     if (!(buf[4] & 0x80)) buttons |= MOUSE_BTN7;
251     if (!(buf[3] & 0x08)) buttons |= MOUSE_BTN6;
252     if (!(buf[3] & 0x80)) buttons |= MOUSE_BTN5;
253     if (!(buf[2] & 0x08)) buttons |= MOUSE_BTN4;
254     if (!(buf[2] & 0x80)) buttons |= MOUSE_BTN3;
255     if (!(buf[1] & 0x80)) buttons |= MOUSE_BTN2;
256     if (!(buf[0] & 0x80)) buttons |= MOUSE_BTN1;
257     mouse_report.buttons = buttons;
258
259     int16_t xx, yy;
260     yy = (buf[0] & 0x7F) | (buf[2] & 0x70) << 3 | (buf[3] & 0x70) << 6 | (buf[4] & 0x70) << 9;
261     xx = (buf[1] & 0x7F) | (buf[2] & 0x07) << 7 | (buf[3] & 0x07) << 10 | (buf[4] & 0x07) << 13;
262
263     // Accelerate mouse. (They weren't meant to be used on screens larger than 320x200).
264     x = xx * mouseacc;
265     y = yy * mouseacc;
266
267     // TODO: Fix HID report descriptor for mouse to support finer resolution
268     // Cap our two bytes per axis to one byte.
269     // Easier with a MIN-function, but since -MAX(-a,-b) = MIN(a,b)...
270     // I.E. MIN(MAX(x,-127),127) = -MAX(-MAX(x, -127), -127) = MIN(-MIN(-x,127),127)
271     mouse_report.x = -MAX(-MAX(x, -127), -127);
272     mouse_report.y = -MAX(-MAX(y, -127), -127);
273
274     if (debug_mouse) {
275         xprintf("Mouse raw: [");
276         for (int8_t i = 0; i < len; i++) xprintf("%02X ", buf[i]);
277         xprintf("]\n");
278
279         xprintf("Mouse info[");
280         xprintf("B:%02X, X:%d(%d), Y:%d(%d), A:%d]\n", buttons, x, xx, y, yy, mouseacc);
281     }
282
283     // Send result by usb.
284     host_mouse_send(&mouse_report);
285
286     // increase acceleration of mouse
287     mouseacc += ( mouseacc < ADB_MOUSE_MAXACC ? 1 : 0 );
288
289     return;
290 }
291 #endif
292
293 uint8_t matrix_scan(void)
294 {
295     /* extra_key is volatile and more convoluted than necessary because gcc refused
296     to generate valid code otherwise. Making extra_key uint8_t and constructing codes
297     here via codes = extra_key<<8 | 0xFF; would consistently fail to even LOAD
298     extra_key from memory, and leave garbage in the high byte of codes. I tried
299     dozens of code variations and it kept generating broken assembly output. So
300     beware if attempting to make extra_key code more logical and efficient. */
301     static volatile uint16_t extra_key = 0xFFFF;
302     uint16_t codes;
303     uint8_t key0, key1;
304
305     /* tick of last polling */
306     static uint16_t tick_ms;
307
308     codes = extra_key;
309     extra_key = 0xFFFF;
310
311     if ( codes == 0xFFFF )
312     {
313         // polling with 12ms interval
314         if (timer_elapsed(tick_ms) < 12) return 0;
315         tick_ms = timer_read();
316
317         codes = adb_host_kbd_recv(ADB_ADDR_KEYBOARD);
318
319         // Adjustable keybaord media keys
320         if (codes == 0 && has_media_keys &&
321                 (codes = adb_host_kbd_recv(ADB_ADDR_APPLIANCE))) {
322             // key1
323             switch (codes & 0x7f ) {
324             case 0x00:  // Mic
325                 codes = (codes & ~0x007f) | 0x42;
326                 break;
327             case 0x01:  // Mute
328                 codes = (codes & ~0x007f) | 0x4a;
329                 break;
330             case 0x02:  // Volume down
331                 codes = (codes & ~0x007f) | 0x49;
332                 break;
333             case 0x03:  // Volume Up
334                 codes = (codes & ~0x007f) | 0x48;
335                 break;
336             case 0x7F:  // no code
337                 break;
338             default:
339                 xprintf("ERROR: media key1\n");
340                 return 0x11;
341             }
342             // key0
343             switch ((codes >> 8) & 0x7f ) {
344             case 0x00:  // Mic
345                 codes = (codes & ~0x7f00) | (0x42 << 8);
346                 break;
347             case 0x01:  // Mute
348                 codes = (codes & ~0x7f00) | (0x4a << 8);
349                 break;
350             case 0x02:  // Volume down
351                 codes = (codes & ~0x7f00) | (0x49 << 8);
352                 break;
353             case 0x03:  // Volume Up
354                 codes = (codes & ~0x7f00) | (0x48 << 8);
355                 break;
356             default:
357                 xprintf("ERROR: media key0\n");
358                 return 0x10;
359             }
360         }
361     }
362     key0 = codes>>8;
363     key1 = codes&0xFF;
364
365     if (debug_matrix && codes) {
366         print("adb_host_kbd_recv: "); phex16(codes); print("\n");
367     }
368
369     if (codes == 0) {                           // no keys
370         return 0;
371     } else if (codes == 0x7F7F) {   // power key press
372         register_key(0x7F);
373     } else if (codes == 0xFFFF) {   // power key release
374         register_key(0xFF);
375     } else if (key0 == 0xFF) {      // error
376         xprintf("adb_host_kbd_recv: ERROR(%d)\n", codes);
377         // something wrong or plug-in
378         matrix_init();
379         return key1;
380     } else {
381         /* Swap codes for ISO keyboard
382          * https://github.com/tmk/tmk_keyboard/issues/35
383          *
384          * ANSI
385          * ,-----------    ----------.
386          * | *a|  1|  2     =|Backspa|
387          * |-----------    ----------|
388          * |Tab  |  Q|     |  ]|   *c|
389          * |-----------    ----------|
390          * |CapsLo|  A|    '|Return  |
391          * |-----------    ----------|
392          * |Shift   |      Shift     |
393          * `-----------    ----------'
394          *
395          * ISO
396          * ,-----------    ----------.
397          * | *a|  1|  2     =|Backspa|
398          * |-----------    ----------|
399          * |Tab  |  Q|     |  ]|Retur|
400          * |-----------    -----`    |
401          * |CapsLo|  A|    '| *c|    |
402          * |-----------    ----------|
403          * |Shif| *b|      Shift     |
404          * `-----------    ----------'
405          *
406          *         ADB scan code   USB usage
407          *         -------------   ---------
408          * Key     ANSI    ISO     ANSI    ISO
409          * ---------------------------------------------
410          * *a      0x32    0x0A    0x35    0x35
411          * *b      ----    0x32    ----    0x64
412          * *c      0x2A    0x2A    0x31    0x31(or 0x32)
413          */
414         if (is_iso_layout) {
415             if ((key0 & 0x7F) == 0x32) {
416                 key0 = (key0 & 0x80) | 0x0A;
417             } else if ((key0 & 0x7F) == 0x0A) {
418                 key0 = (key0 & 0x80) | 0x32;
419             }
420         }
421         register_key(key0);
422         if (key1 != 0xFF)       // key1 is 0xFF when no second key.
423             extra_key = key1<<8 | 0xFF; // process in a separate call
424     }
425
426     return 1;
427 }
428
429 inline
430 matrix_row_t matrix_get_row(uint8_t row)
431 {
432     return matrix[row];
433 }
434
435 inline
436 static void register_key(uint8_t key)
437 {
438     uint8_t col, row;
439     col = key&0x07;
440     row = (key>>3)&0x0F;
441     if (key&0x80) {
442         matrix[row] &= ~(1<<col);
443     } else {
444         matrix[row] |=  (1<<col);
445     }
446 }
447
448 void led_set(uint8_t usb_led)
449 {
450     adb_host_kbd_led(ADB_ADDR_KEYBOARD, ~usb_led);
451 }