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