]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - tmk_core/protocol/adb.c
xt_usb: Fix comment of scancode
[max/tmk_keyboard.git] / tmk_core / protocol / adb.c
1 /*
2 Copyright 2011-19 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     // TODO: Service Request(Srq):
117     // Device holds low part of comannd stopbit for 140-260us
118     //
119     // Command:
120     // ......._     ______________________    ___ ............_     -------
121     //         |   |                      |  |   |             |   |
122     // Command |   |                      |  |   | Data bytes  |   |
123     // ........|___|  |     140-260       |__|   |_............|___|
124     //         |stop0 | Tlt Stop-to-Start |start1|             |stop0 |
125     //
126     // Command without data:
127     // ......._     __________________________
128     //         |   |
129     // Command |   |
130     // ........|___|  |     140-260       |
131     //         |stop0 | Tlt Stop-to-Start |
132     //
133     // Service Request:
134     // ......._                     ______    ___ ............_     -------
135     //         |     140-260       |      |  |   |             |   |
136     // Command |  Service Request  |      |  |   | Data bytes  |   |
137     // ........|___________________|      |__|   |_............|___|
138     //         |stop0 |                   |start1|             |stop0 |
139     // ......._                     __________
140     //         |     140-260       |
141     // Command |  Service Request  |
142     // ........|___________________|
143     //         |stop0 |
144     // This can be happened?
145     // ......._     ______________________    ___ ............_                   -----
146     //         |   |                      |  |   |             |    140-260      |
147     // Command |   |                      |  |   | Data bytes  | Service Request |
148     // ........|___|  |     140-260       |__|   |_............|_________________|
149     //         |stop0 | Tlt Stop-to-Start |start1|             |stop0 |
150     //
151     // "Service requests are issued by the devices during a very specific time at the
152     // end of the reception of the command packet.
153     // If a device in need of service issues a service request, it must do so within
154     // the 65 µs of the Stop Bit’s low time and maintain the line low for a total of 300 µs."
155     //
156     // "A device sends a Service Request signal by holding the bus low during the low
157     // portion of the stop bit of any command or data transaction. The device must lengthen
158     // the stop by a minimum of 140 J.lS beyond its normal duration, as shown in Figure 8-15."
159     // http://ww1.microchip.com/downloads/en/AppNotes/00591b.pdf
160     if (!wait_data_hi(500)) {    // Service Request(310us Adjustable Keyboard): just ignored
161         xprintf("R");
162         sei();
163         return 0;
164     }
165     if (!wait_data_lo(500)) {   // Tlt/Stop to Start(140-260us)
166         sei();
167         return 0;               // No data from device(not error);
168     }
169
170     // start bit(1)
171     if (!wait_data_hi(40)) {
172         xprintf("S");
173         sei();
174         return 0;
175     }
176     if (!wait_data_lo(100)) {
177         xprintf("s");
178         sei();
179         return 0;
180     }
181
182     uint8_t n = 0; // bit count
183     do {
184         //
185         // |<- bit_cell_max(130) ->|
186         // |        |<-   lo     ->|
187         // |        |       |<-hi->|
188         //           _______
189         // |        |       |
190         // | 130-lo | lo-hi |
191         // |________|       |
192         //
193         uint8_t lo = (uint8_t) wait_data_hi(130);
194         if (!lo)
195             goto error; // no more bit or after stop bit
196
197         uint8_t hi = (uint8_t) wait_data_lo(lo);
198         if (!hi)
199             goto error; // stop bit extedned by Srq?
200
201         if (n/8 >= len) continue; // can't store in buf
202
203         buf[n/8] <<= 1;
204         if ((130 - lo) < (lo - hi)) {
205             buf[n/8] |= 1;
206         }
207     }
208     while ( ++n );
209
210 error:
211     sei();
212     return n/8;
213 }
214
215 uint16_t adb_host_talk(uint8_t addr, uint8_t reg)
216 {
217     uint8_t len;
218     uint8_t buf[8];
219     len = adb_host_talk_buf(addr, reg, buf, 8);
220     if (len != 2) return 0;
221     return (buf[0]<<8 | buf[1]);
222 }
223
224 void adb_host_listen_buf(uint8_t addr, uint8_t reg, uint8_t *buf, uint8_t len)
225 {
226     cli();
227     attention();
228     send_byte((addr<<4) | ADB_CMD_LISTEN | reg);
229     place_bit0();               // Stopbit(0)
230     // TODO: Service Request
231     _delay_us(200);             // Tlt/Stop to Start
232     place_bit1();               // Startbit(1)
233     for (int8_t i = 0; i < len; i++) {
234         send_byte(buf[i]);
235         //xprintf("%02X ", buf[i]);
236     }
237     place_bit0();               // Stopbit(0);
238     sei();
239 }
240
241 void adb_host_listen(uint8_t addr, uint8_t reg, uint8_t data_h, uint8_t data_l)
242 {
243     uint8_t buf[2] = { data_h, data_l };
244     adb_host_listen_buf(addr, reg, buf, 2);
245 }
246
247 void adb_host_flush(uint8_t addr)
248 {
249     cli();
250     attention();
251     send_byte((addr<<4) | ADB_CMD_FLUSH);
252     place_bit0();               // Stopbit(0)
253     _delay_us(200);             // Tlt/Stop to Start
254     sei();
255 }
256
257 // send state of LEDs
258 void adb_host_kbd_led(uint8_t addr, uint8_t led)
259 {
260     // Listen Register2
261     //  upper byte: not used
262     //  lower byte: bit2=ScrollLock, bit1=CapsLock, bit0=NumLock
263     adb_host_listen(addr, 2, 0, led & 0x07);
264 }
265
266
267 #ifdef ADB_PSW_BIT
268 static inline void psw_lo()
269 {
270     ADB_DDR  |=  (1<<ADB_PSW_BIT);
271     ADB_PORT &= ~(1<<ADB_PSW_BIT);
272 }
273 static inline void psw_hi()
274 {
275     ADB_PORT |=  (1<<ADB_PSW_BIT);
276     ADB_DDR  &= ~(1<<ADB_PSW_BIT);
277 }
278 static inline bool psw_in()
279 {
280     ADB_PORT |=  (1<<ADB_PSW_BIT);
281     ADB_DDR  &= ~(1<<ADB_PSW_BIT);
282     return ADB_PIN&(1<<ADB_PSW_BIT);
283 }
284 #endif
285
286 static inline void attention(void)
287 {
288     data_lo();
289     _delay_us(800-35); // bit1 holds lo for 35 more
290     place_bit1();
291 }
292
293 static inline void place_bit0(void)
294 {
295     data_lo();
296     _delay_us(65);
297     data_hi();
298     _delay_us(35);
299 }
300
301 static inline void place_bit1(void)
302 {
303     data_lo();
304     _delay_us(35);
305     data_hi();
306     _delay_us(65);
307 }
308
309 static inline void send_byte(uint8_t data)
310 {
311     for (int i = 0; i < 8; i++) {
312         if (data&(0x80>>i))
313             place_bit1();
314         else
315             place_bit0();
316     }
317 }
318
319 // These are carefully coded to take 6 cycles of overhead.
320 // inline asm approach became too convoluted
321 static inline uint16_t wait_data_lo(uint16_t us)
322 {
323     do {
324         if ( !data_in() )
325             break;
326         _delay_us(1 - (6 * 1000000.0 / F_CPU));
327     }
328     while ( --us );
329     return us;
330 }
331
332 static inline uint16_t wait_data_hi(uint16_t us)
333 {
334     do {
335         if ( data_in() )
336             break;
337         _delay_us(1 - (6 * 1000000.0 / F_CPU));
338     }
339     while ( --us );
340     return us;
341 }
342
343
344 /*
345 ADB Protocol
346 ============
347
348 Resources
349 ---------
350 ADB - The Untold Story: Space Aliens Ate My Mouse
351     http://developer.apple.com/legacy/mac/library/#technotes/hw/hw_01.html
352 ADB Manager
353     http://developer.apple.com/legacy/mac/library/documentation/mac/pdf/Devices/ADB_Manager.pdf
354     Service request(5-17)
355 Apple IIgs Hardware Reference Second Edition [Chapter6 p121]
356     ftp://ftp.apple.asimov.net/pub/apple_II/documentation/Apple%20IIgs%20Hardware%20Reference.pdf
357 ADB Keycode
358     http://72.0.193.250/Documentation/macppc/adbkeycodes/
359     http://m0115.web.fc2.com/m0115.jpg
360     [Inside Macintosh volume V, pages 191-192]
361     http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-421.18.3/IOHIDFamily/Cosmo_USB2ADB.c
362 ADB Signaling
363     http://kbdbabel.sourceforge.net/doc/kbd_signaling_pcxt_ps2_adb.pdf
364 ADB Overview & History
365     http://en.wikipedia.org/wiki/Apple_Desktop_Bus
366 Microchip Application Note: ADB device(with code for PIC16C)
367     http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1824&appnote=en011062
368 AVR ATtiny2131 ADB to PS/2 converter(Japanese)
369     http://hp.vector.co.jp/authors/VA000177/html/KeyBoardA5DEA5CBA5A2II.html
370
371
372 Pinouts
373 -------
374     ADB female socket from the front:
375     __________
376     |        | <--- top
377     | 4o  o3 |
378     |2o    o1|
379     |   ==   |
380     |________| <--- bottom
381       |    |   <--- 4pins
382
383
384     ADB female socket from bottom:
385
386     ========== <--- front
387     |        |
388     |        |
389     |2o    o1|
390     |4o    o3|
391     ---------- <--- back
392
393     1: Data
394     2: Power SW(low when press Power key)
395     3: Vcc(5V)
396     4: GND
397
398
399 Commands
400 --------
401     ADB command is 1byte and consists of 4bit-address, 2bit-command
402     type and 2bit-register. The commands are always sent by Host.
403
404     Command format:
405     7 6 5 4 3 2 1 0
406     | | | |------------ address
407             | |-------- command type
408                 | |---- register
409
410     bits                commands
411     ------------------------------------------------------
412     - - - - 0 0 0 0     Send Reset(reset all devices)
413     A A A A 0 0 0 1     Flush(reset a device)
414     - - - - 0 0 1 0     Reserved
415     - - - - 0 0 1 1     Reserved
416     - - - - 0 1 - -     Reserved
417     A A A A 1 0 R R     Listen(write to a device)
418     A A A A 1 1 R R     Talk(read from a device)
419
420     The command to read keycodes from keyboard is 0x2C which
421     consist of keyboard address 2 and Talk against register 0.
422
423     Address:
424     2:  keyboard
425     3:  mice
426
427     Registers:
428     0: application(keyboard uses this to store its data.)
429     1: application
430     2: application(keyboard uses this for LEDs and state of modifiers)
431     3: status and command
432
433
434 Communication
435 -------------
436     This is a minimum information for keyboard communication.
437     See "Resources" for detail.
438
439     Signaling:
440
441     ~~~~____________~~||||||||||||__~~~~~_~~|||||||||||||||__~~~~
442
443         |800us     |  |7 Command 0|  |   |  |15-64  Data  0|Stopbit(0)
444         +Attention |              |  |   +Startbit(1)
445                    +Startbit(1)   |  +Tlt(140-260us)
446                                   +stopbit(0)
447
448     Bit cells:
449
450     bit0: ______~~~
451           65    :35us
452
453     bit1: ___~~~~~~
454           35 :65us
455
456     bit0 low time: 60-70% of bit cell(42-91us)
457     bit1 low time: 30-40% of bit cell(21-52us)
458     bit cell time: 70-130us
459     [from Apple IIgs Hardware Reference Second Edition]
460
461     Criterion for bit0/1:
462     After 55us if line is low/high then bit is 0/1.
463
464     Attention & start bit:
465     Host asserts low in 560-1040us then places start bit(1).
466
467     Tlt(Stop to Start):
468     Bus stays high in 140-260us then device places start bit(1).
469
470     Global reset:
471     Host asserts low in 2.8-5.2ms. All devices are forced to reset.
472
473     Service request from device(Srq):
474     Device can request to send at commad(Global only?) stop bit.
475     Requesting device keeps low for 140-260us at stop bit of command.
476
477
478 Keyboard Data(Register0)
479     This 16bit data can contains two keycodes and two released flags.
480     First keycode is palced in upper byte. When one keyocode is sent,
481     lower byte is 0xFF.
482     Release flag is 1 when key is released.
483
484     1514 . . . . . 8 7 6 . . . . . 0
485      | | | | | | | | | +-+-+-+-+-+-+-   Keycode2
486      | | | | | | | | +---------------   Released2(1 when the key is released)
487      | +-+-+-+-+-+-+-----------------   Keycode1
488      +-------------------------------   Released1(1 when the key is released)
489
490     Keycodes:
491     Scancode consists of 7bit keycode and 1bit release flag.
492     Device can send two keycodes at once. If just one keycode is sent
493     keycode1 contains it and keyocode2 is 0xFF.
494
495     Power switch:
496     You can read the state from PSW line(active low) however
497     the switch has a special scancode 0x7F7F, so you can
498     also read from Data line. It uses 0xFFFF for release scancode.
499
500 Keyboard LEDs & state of keys(Register2)
501     This register hold current state of three LEDs and nine keys.
502     The state of LEDs can be changed by sending Listen command.
503
504     1514 . . . . . . 7 6 5 . 3 2 1 0
505      | | | | | | | | | | | | | | | +-   LED1(NumLock)
506      | | | | | | | | | | | | | | +---   LED2(CapsLock)
507      | | | | | | | | | | | | | +-----   LED3(ScrollLock)
508      | | | | | | | | | | +-+-+-------   Reserved
509      | | | | | | | | | +-------------   ScrollLock
510      | | | | | | | | +---------------   NumLock
511      | | | | | | | +-----------------   Apple/Command
512      | | | | | | +-------------------   Option
513      | | | | | +---------------------   Shift
514      | | | | +-----------------------   Control
515      | | | +-------------------------   Reset/Power
516      | | +---------------------------   CapsLock
517      | +-----------------------------   Delete
518      +-------------------------------   Reserved
519
520 Address, Handler ID and bits(Register3)
521     1514131211 . . 8 7 . . . . . . 0
522      | | | | | | | | | | | | | | | |
523      | | | | | | | | +-+-+-+-+-+-+-+-   Handler ID
524      | | | | +-+-+-+-----------------   Address
525      | | | +-------------------------   0
526      | | +---------------------------   Service request enable(1 = enabled)
527      | +-----------------------------   Exceptional event(alwyas 1 if not used)
528      +-------------------------------   0
529
530 ADB Bit Cells
531     bit cell time: 70-130us
532     low part of bit0: 60-70% of bit cell
533     low part of bit1: 30-40% of bit cell
534
535        bit cell time         70us        130us
536        --------------------------------------------
537        low  part of bit0     42-49       78-91
538        high part of bit0     21-28       39-52
539        low  part of bit1     21-28       39-52
540        high part of bit1     42-49       78-91
541
542
543     bit0:
544        70us bit cell:
545          ____________~~~~~~
546          42-49        21-28
547
548        130us bit cell:
549          ____________~~~~~~
550          78-91        39-52
551
552     bit1:
553        70us bit cell:
554          ______~~~~~~~~~~~~
555          21-28        42-49
556
557        130us bit cell:
558          ______~~~~~~~~~~~~
559          39-52        78-91
560
561     [from Apple IIgs Hardware Reference Second Edition]
562
563 Keyboard Handle ID
564     Apple Standard Keyboard M0116:      0x01
565     Apple Extended Keyboard M0115:      0x02
566     Apple Extended Keyboard II M3501:   0x02
567     Apple Adjustable Keybaord:          0x10
568
569     http://lxr.free-electrons.com/source/drivers/macintosh/adbhid.c?v=4.4#L802
570
571 END_OF_ADB
572 */