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