]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - tmk_core/protocol/adb.c
core:adb_usb: Add Extended Mouse Protocol support #274
[max/tmk_keyboard.git] / tmk_core / protocol / adb.c
1 /*
2 Copyright 2011 Jun WAKO <wakojun@gmail.com>
3 Copyright 2013 Shay Green <gblargg@gmail.com>
4
5 This software is licensed with a Modified BSD License.
6 All of this is supposed to be Free Software, Open Source, DFSG-free,
7 GPL-compatible, and OK to use in both free and proprietary applications.
8 Additions and corrections to this file are welcome.
9
10
11 Redistribution and use in source and binary forms, with or without
12 modification, are permitted provided that the following conditions are met:
13
14 * Redistributions of source code must retain the above copyright
15   notice, this list of conditions and the following disclaimer.
16
17 * Redistributions in binary form must reproduce the above copyright
18   notice, this list of conditions and the following disclaimer in
19   the documentation and/or other materials provided with the
20   distribution.
21
22 * Neither the name of the copyright holders nor the names of
23   contributors may be used to endorse or promote products derived
24   from this software without specific prior written permission.
25
26 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
27 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
30 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 #include <stdbool.h>
40 #include <util/delay.h>
41 #include <avr/io.h>
42 #include <avr/interrupt.h>
43 #include "adb.h"
44 #include "print.h"
45
46
47 // GCC doesn't inline functions normally
48 #define data_lo() (ADB_DDR |=  (1<<ADB_DATA_BIT))
49 #define data_hi() (ADB_DDR &= ~(1<<ADB_DATA_BIT))
50 #define data_in() (ADB_PIN &   (1<<ADB_DATA_BIT))
51
52 #ifdef ADB_PSW_BIT
53 static inline void psw_lo(void);
54 static inline void psw_hi(void);
55 static inline bool psw_in(void);
56 #endif
57
58 static inline void attention(void);
59 static inline void place_bit0(void);
60 static inline void place_bit1(void);
61 static inline void send_byte(uint8_t data);
62 static inline uint16_t wait_data_lo(uint16_t us);
63 static inline uint16_t wait_data_hi(uint16_t us);
64
65
66 void adb_host_init(void)
67 {
68     ADB_PORT &= ~(1<<ADB_DATA_BIT);
69     data_hi();
70 #ifdef ADB_PSW_BIT
71     psw_hi();
72 #endif
73 }
74
75 #ifdef ADB_PSW_BIT
76 bool adb_host_psw(void)
77 {
78     return psw_in();
79 }
80 #endif
81
82 /*
83  * Don't call this in a row without the delay, otherwise it makes some of poor controllers
84  * overloaded and misses strokes. Recommended interval is 12ms.
85  *
86  * Thanks a lot, blargg!
87  * <http://geekhack.org/index.php?topic=14290.msg1068919#msg1068919>
88  * <http://geekhack.org/index.php?topic=14290.msg1070139#msg1070139>
89  */
90 uint16_t adb_host_kbd_recv(uint8_t addr)
91 {
92     return adb_host_talk(addr, ADB_REG_0);
93 }
94
95 #ifdef ADB_MOUSE_ENABLE
96 __attribute__ ((weak))
97 void adb_mouse_init(void) {
98     return;
99 }
100
101 __attribute__ ((weak))
102 void adb_mouse_task(void) {
103     return;
104 }
105 #endif
106
107 // This sends Talk command to read data from register and returns length of the data.
108 uint8_t adb_host_talk_buf(uint8_t addr, uint8_t reg, uint8_t *buf, uint8_t len)
109 {
110     for (int8_t i =0; i < len; i++) buf[i] = 0;
111
112     cli();
113     attention();
114     send_byte((addr<<4) | ADB_CMD_TALK | reg);
115     place_bit0();               // Stopbit(0)
116     if (!wait_data_hi(500)) {    // Service Request(310us Adjustable Keyboard): just ignored
117         sei();
118         return -30;             // something wrong
119     }
120     if (!wait_data_lo(500)) {   // Tlt/Stop to Start(140-260us)
121         sei();
122         return 0;               // No data to send
123     }
124
125     // start bit(1)
126     if (!wait_data_hi(40)) return 0;
127     if (!wait_data_lo(100)) return 0;
128
129     uint8_t n = 0; // bit count
130     do {
131         //
132         // |<- bit_cell_max(130) ->|
133         // |        |<-   lo     ->|
134         // |        |       |<-hi->|
135         //           _______
136         // |        |       |
137         // | 130-lo | lo-hi |
138         // |________|       |
139         //
140         uint8_t lo = (uint8_t) wait_data_hi(130);
141         if (!lo)
142             goto error; // no more bit or after stop bit
143
144         uint8_t hi = (uint8_t) wait_data_lo(lo);
145         if (!hi)
146             goto error; // stop bit extedned by Srq
147
148         if (n/8 >= len) continue; // can't store in buf
149
150         buf[n/8] <<= 1;
151         if ((130 - lo) < (lo - hi)) {
152             buf[n/8] |= 1;
153         }
154     }
155     while ( ++n );
156
157 error:
158     sei();
159     return n/8;
160 }
161
162 uint16_t adb_host_talk(uint8_t addr, uint8_t reg)
163 {
164     uint8_t len;
165     uint8_t buf[8];
166     len = adb_host_talk_buf(addr, reg, buf, 8);
167     if (len != 2) return 0;
168     return (buf[0]<<8 | buf[1]);
169 }
170
171 void adb_host_listen_buf(uint8_t addr, uint8_t reg, uint8_t *buf, uint8_t len)
172 {
173     cli();
174     attention();
175     send_byte((addr<<4) | ADB_CMD_LISTEN | reg);
176     place_bit0();               // Stopbit(0)
177     _delay_us(200);             // Tlt/Stop to Start
178     place_bit1();               // Startbit(1)
179     for (int8_t i = 0; i < len; i++) {
180         send_byte(buf[i]);
181         //xprintf("%02X ", buf[i]);
182     }
183     place_bit0();               // Stopbit(0);
184     sei();
185 }
186
187 void adb_host_listen(uint8_t addr, uint8_t reg, uint8_t data_h, uint8_t data_l)
188 {
189     uint8_t buf[2] = { data_h, data_l };
190     adb_host_listen_buf(addr, reg, buf, 2);
191 }
192
193 void adb_host_flush(uint8_t addr)
194 {
195     cli();
196     attention();
197     send_byte((addr<<4) | ADB_CMD_FLUSH);
198     place_bit0();               // Stopbit(0)
199     _delay_us(200);             // Tlt/Stop to Start
200     sei();
201 }
202
203 // send state of LEDs
204 void adb_host_kbd_led(uint8_t addr, uint8_t led)
205 {
206     // Listen Register2
207     //  upper byte: not used
208     //  lower byte: bit2=ScrollLock, bit1=CapsLock, bit0=NumLock
209     adb_host_listen(addr, 2, 0, led & 0x07);
210 }
211
212
213 #ifdef ADB_PSW_BIT
214 static inline void psw_lo()
215 {
216     ADB_DDR  |=  (1<<ADB_PSW_BIT);
217     ADB_PORT &= ~(1<<ADB_PSW_BIT);
218 }
219 static inline void psw_hi()
220 {
221     ADB_PORT |=  (1<<ADB_PSW_BIT);
222     ADB_DDR  &= ~(1<<ADB_PSW_BIT);
223 }
224 static inline bool psw_in()
225 {
226     ADB_PORT |=  (1<<ADB_PSW_BIT);
227     ADB_DDR  &= ~(1<<ADB_PSW_BIT);
228     return ADB_PIN&(1<<ADB_PSW_BIT);
229 }
230 #endif
231
232 static inline void attention(void)
233 {
234     data_lo();
235     _delay_us(800-35); // bit1 holds lo for 35 more
236     place_bit1();
237 }
238
239 static inline void place_bit0(void)
240 {
241     data_lo();
242     _delay_us(65);
243     data_hi();
244     _delay_us(35);
245 }
246
247 static inline void place_bit1(void)
248 {
249     data_lo();
250     _delay_us(35);
251     data_hi();
252     _delay_us(65);
253 }
254
255 static inline void send_byte(uint8_t data)
256 {
257     for (int i = 0; i < 8; i++) {
258         if (data&(0x80>>i))
259             place_bit1();
260         else
261             place_bit0();
262     }
263 }
264
265 // These are carefully coded to take 6 cycles of overhead.
266 // inline asm approach became too convoluted
267 static inline uint16_t wait_data_lo(uint16_t us)
268 {
269     do {
270         if ( !data_in() )
271             break;
272         _delay_us(1 - (6 * 1000000.0 / F_CPU));
273     }
274     while ( --us );
275     return us;
276 }
277
278 static inline uint16_t wait_data_hi(uint16_t us)
279 {
280     do {
281         if ( data_in() )
282             break;
283         _delay_us(1 - (6 * 1000000.0 / F_CPU));
284     }
285     while ( --us );
286     return us;
287 }
288
289
290 /*
291 ADB Protocol
292 ============
293
294 Resources
295 ---------
296 ADB - The Untold Story: Space Aliens Ate My Mouse
297     http://developer.apple.com/legacy/mac/library/#technotes/hw/hw_01.html
298 ADB Manager
299     http://developer.apple.com/legacy/mac/library/documentation/mac/pdf/Devices/ADB_Manager.pdf
300     Service request(5-17)
301 Apple IIgs Hardware Reference Second Edition [Chapter6 p121]
302     ftp://ftp.apple.asimov.net/pub/apple_II/documentation/Apple%20IIgs%20Hardware%20Reference.pdf
303 ADB Keycode
304     http://72.0.193.250/Documentation/macppc/adbkeycodes/
305     http://m0115.web.fc2.com/m0115.jpg
306     [Inside Macintosh volume V, pages 191-192]
307     http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-421.18.3/IOHIDFamily/Cosmo_USB2ADB.c
308 ADB Signaling
309     http://kbdbabel.sourceforge.net/doc/kbd_signaling_pcxt_ps2_adb.pdf
310 ADB Overview & History
311     http://en.wikipedia.org/wiki/Apple_Desktop_Bus
312 Microchip Application Note: ADB device(with code for PIC16C)
313     http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1824&appnote=en011062
314 AVR ATtiny2131 ADB to PS/2 converter(Japanese)
315     http://hp.vector.co.jp/authors/VA000177/html/KeyBoardA5DEA5CBA5A2II.html
316
317
318 Pinouts
319 -------
320     ADB female socket from the front:
321     __________
322     |        | <--- top
323     | 4o  o3 |
324     |2o    o1|
325     |   ==   |
326     |________| <--- bottom
327       |    |   <--- 4pins
328
329
330     ADB female socket from bottom:
331
332     ========== <--- front
333     |        |
334     |        |
335     |2o    o1|
336     |4o    o3|
337     ---------- <--- back
338
339     1: Data
340     2: Power SW(low when press Power key)
341     3: Vcc(5V)
342     4: GND
343
344
345 Commands
346 --------
347     ADB command is 1byte and consists of 4bit-address, 2bit-command
348     type and 2bit-register. The commands are always sent by Host.
349
350     Command format:
351     7 6 5 4 3 2 1 0
352     | | | |------------ address
353             | |-------- command type
354                 | |---- register
355
356     bits                commands
357     ------------------------------------------------------
358     - - - - 0 0 0 0     Send Reset(reset all devices)
359     A A A A 0 0 0 1     Flush(reset a device)
360     - - - - 0 0 1 0     Reserved
361     - - - - 0 0 1 1     Reserved
362     - - - - 0 1 - -     Reserved
363     A A A A 1 0 R R     Listen(write to a device)
364     A A A A 1 1 R R     Talk(read from a device)
365
366     The command to read keycodes from keyboard is 0x2C which
367     consist of keyboard address 2 and Talk against register 0.
368
369     Address:
370     2:  keyboard
371     3:  mice
372
373     Registers:
374     0: application(keyboard uses this to store its data.)
375     1: application
376     2: application(keyboard uses this for LEDs and state of modifiers)
377     3: status and command
378
379
380 Communication
381 -------------
382     This is a minimum information for keyboard communication.
383     See "Resources" for detail.
384
385     Signaling:
386
387     ~~~~____________~~||||||||||||__~~~~~_~~|||||||||||||||__~~~~
388
389         |800us     |  |7 Command 0|  |   |  |15-64  Data  0|Stopbit(0)
390         +Attention |              |  |   +Startbit(1)
391                    +Startbit(1)   |  +Tlt(140-260us)
392                                   +stopbit(0)
393
394     Bit cells:
395
396     bit0: ______~~~
397           65    :35us
398
399     bit1: ___~~~~~~
400           35 :65us
401
402     bit0 low time: 60-70% of bit cell(42-91us)
403     bit1 low time: 30-40% of bit cell(21-52us)
404     bit cell time: 70-130us
405     [from Apple IIgs Hardware Reference Second Edition]
406
407     Criterion for bit0/1:
408     After 55us if line is low/high then bit is 0/1.
409
410     Attention & start bit:
411     Host asserts low in 560-1040us then places start bit(1).
412
413     Tlt(Stop to Start):
414     Bus stays high in 140-260us then device places start bit(1).
415
416     Global reset:
417     Host asserts low in 2.8-5.2ms. All devices are forced to reset.
418
419     Service request from device(Srq):
420     Device can request to send at commad(Global only?) stop bit.
421     Requesting device keeps low for 140-260us at stop bit of command.
422
423
424 Keyboard Data(Register0)
425     This 16bit data can contains two keycodes and two released flags.
426     First keycode is palced in upper byte. When one keyocode is sent,
427     lower byte is 0xFF.
428     Release flag is 1 when key is released.
429
430     1514 . . . . . 8 7 6 . . . . . 0
431      | | | | | | | | | +-+-+-+-+-+-+-   Keycode2
432      | | | | | | | | +---------------   Released2(1 when the key is released)
433      | +-+-+-+-+-+-+-----------------   Keycode1
434      +-------------------------------   Released1(1 when the key is released)
435
436     Keycodes:
437     Scancode consists of 7bit keycode and 1bit release flag.
438     Device can send two keycodes at once. If just one keycode is sent
439     keycode1 contains it and keyocode2 is 0xFF.
440
441     Power switch:
442     You can read the state from PSW line(active low) however
443     the switch has a special scancode 0x7F7F, so you can
444     also read from Data line. It uses 0xFFFF for release scancode.
445
446 Keyboard LEDs & state of keys(Register2)
447     This register hold current state of three LEDs and nine keys.
448     The state of LEDs can be changed by sending Listen command.
449
450     1514 . . . . . . 7 6 5 . 3 2 1 0
451      | | | | | | | | | | | | | | | +-   LED1(NumLock)
452      | | | | | | | | | | | | | | +---   LED2(CapsLock)
453      | | | | | | | | | | | | | +-----   LED3(ScrollLock)
454      | | | | | | | | | | +-+-+-------   Reserved
455      | | | | | | | | | +-------------   ScrollLock
456      | | | | | | | | +---------------   NumLock
457      | | | | | | | +-----------------   Apple/Command
458      | | | | | | +-------------------   Option
459      | | | | | +---------------------   Shift
460      | | | | +-----------------------   Control
461      | | | +-------------------------   Reset/Power
462      | | +---------------------------   CapsLock
463      | +-----------------------------   Delete
464      +-------------------------------   Reserved
465
466 Address, Handler ID and bits(Register3)
467     1514131211 . . 8 7 . . . . . . 0
468      | | | | | | | | | | | | | | | |
469      | | | | | | | | +-+-+-+-+-+-+-+-   Handler ID
470      | | | | +-+-+-+-----------------   Address
471      | | | +-------------------------   0
472      | | +---------------------------   Service request enable(1 = enabled)
473      | +-----------------------------   Exceptional event(alwyas 1 if not used)
474      +-------------------------------   0
475
476 ADB Bit Cells
477     bit cell time: 70-130us
478     low part of bit0: 60-70% of bit cell
479     low part of bit1: 30-40% of bit cell
480
481        bit cell time         70us        130us
482        --------------------------------------------
483        low  part of bit0     42-49       78-91
484        high part of bit0     21-28       39-52
485        low  part of bit1     21-28       39-52
486        high part of bit1     42-49       78-91
487
488
489     bit0:
490        70us bit cell:
491          ____________~~~~~~
492          42-49        21-28
493
494        130us bit cell:
495          ____________~~~~~~
496          78-91        39-52
497
498     bit1:
499        70us bit cell:
500          ______~~~~~~~~~~~~
501          21-28        42-49
502
503        130us bit cell:
504          ______~~~~~~~~~~~~
505          39-52        78-91
506
507     [from Apple IIgs Hardware Reference Second Edition]
508
509 Keyboard Handle ID
510     Apple Standard Keyboard M0116:      0x01
511     Apple Extended Keyboard M0115:      0x02
512     Apple Extended Keyboard II M3501:   0x02
513     Apple Adjustable Keybaord:          0x10
514
515     http://lxr.free-electrons.com/source/drivers/macintosh/adbhid.c?v=4.4#L802
516
517 END_OF_ADB
518 */