summaryrefslogtreecommitdiff
path: root/tmk_core/protocol
diff options
context:
space:
mode:
Diffstat (limited to 'tmk_core/protocol')
-rw-r--r--tmk_core/protocol/adb.c478
-rw-r--r--tmk_core/protocol/adb.h66
-rw-r--r--tmk_core/protocol/bluefruit.mk27
-rw-r--r--tmk_core/protocol/bluefruit/bluefruit.c205
-rw-r--r--tmk_core/protocol/bluefruit/bluefruit.h25
-rw-r--r--tmk_core/protocol/bluefruit/main.c138
-rw-r--r--tmk_core/protocol/chibios.mk10
-rw-r--r--tmk_core/protocol/chibios/README.md55
-rw-r--r--tmk_core/protocol/chibios/main.c186
-rw-r--r--tmk_core/protocol/chibios/usb_main.c1375
-rw-r--r--tmk_core/protocol/chibios/usb_main.h139
-rw-r--r--tmk_core/protocol/ibm4704.c189
-rw-r--r--tmk_core/protocol/ibm4704.h110
-rw-r--r--tmk_core/protocol/iwrap.mk26
-rw-r--r--tmk_core/protocol/iwrap/iWRAP4.txt376
-rw-r--r--tmk_core/protocol/iwrap/iWRAP5.txt356
-rw-r--r--tmk_core/protocol/iwrap/iwrap.c469
-rw-r--r--tmk_core/protocol/iwrap/iwrap.h49
-rw-r--r--tmk_core/protocol/iwrap/main.c376
-rw-r--r--tmk_core/protocol/iwrap/mux_exit.rb7
-rw-r--r--tmk_core/protocol/iwrap/suart.S156
-rw-r--r--tmk_core/protocol/iwrap/suart.h8
-rw-r--r--tmk_core/protocol/iwrap/wd.h159
-rw-r--r--tmk_core/protocol/lufa.mk81
-rw-r--r--tmk_core/protocol/lufa/adafruit_ble.cpp823
-rw-r--r--tmk_core/protocol/lufa/adafruit_ble.h60
-rw-r--r--tmk_core/protocol/lufa/bluetooth.c36
-rw-r--r--tmk_core/protocol/lufa/bluetooth.h79
-rw-r--r--tmk_core/protocol/lufa/descriptor.c987
-rw-r--r--tmk_core/protocol/lufa/descriptor.h271
-rw-r--r--tmk_core/protocol/lufa/lufa.c1293
-rw-r--r--tmk_core/protocol/lufa/lufa.h96
-rw-r--r--tmk_core/protocol/lufa/outputselect.c56
-rw-r--r--tmk_core/protocol/lufa/outputselect.h40
-rw-r--r--tmk_core/protocol/lufa/ringbuffer.hpp66
-rw-r--r--tmk_core/protocol/m0110.c591
-rw-r--r--tmk_core/protocol/m0110.h92
-rw-r--r--tmk_core/protocol/mbed/HIDKeyboard.cpp271
-rw-r--r--tmk_core/protocol/mbed/HIDKeyboard.h31
-rw-r--r--tmk_core/protocol/mbed/mbed_driver.cpp41
-rw-r--r--tmk_core/protocol/mbed/mbed_driver.h3
-rw-r--r--tmk_core/protocol/midi.mk10
-rwxr-xr-xtmk_core/protocol/midi/Config/LUFAConfig.h93
-rwxr-xr-xtmk_core/protocol/midi/bytequeue/COPYING674
-rwxr-xr-xtmk_core/protocol/midi/bytequeue/bytequeue.c65
-rwxr-xr-xtmk_core/protocol/midi/bytequeue/bytequeue.h59
-rwxr-xr-xtmk_core/protocol/midi/bytequeue/interrupt_setting.c36
-rwxr-xr-xtmk_core/protocol/midi/bytequeue/interrupt_setting.h39
-rwxr-xr-xtmk_core/protocol/midi/midi.c277
-rwxr-xr-xtmk_core/protocol/midi/midi.h498
-rwxr-xr-xtmk_core/protocol/midi/midi_device.c291
-rwxr-xr-xtmk_core/protocol/midi/midi_device.h156
-rwxr-xr-xtmk_core/protocol/midi/midi_function_types.h50
-rwxr-xr-xtmk_core/protocol/midi/sysex_tools.c99
-rwxr-xr-xtmk_core/protocol/midi/sysex_tools.h95
-rw-r--r--tmk_core/protocol/news.c168
-rw-r--r--tmk_core/protocol/news.h51
-rw-r--r--tmk_core/protocol/next_kbd.c212
-rw-r--r--tmk_core/protocol/next_kbd.h63
-rw-r--r--tmk_core/protocol/pjrc.mk30
-rw-r--r--tmk_core/protocol/pjrc/MEMO.txt25
-rw-r--r--tmk_core/protocol/pjrc/main.c74
-rw-r--r--tmk_core/protocol/pjrc/pjrc.c76
-rw-r--r--tmk_core/protocol/pjrc/pjrc.h26
-rw-r--r--tmk_core/protocol/pjrc/usb.c1008
-rw-r--r--tmk_core/protocol/pjrc/usb.h137
-rw-r--r--tmk_core/protocol/pjrc/usb_debug.c102
-rw-r--r--tmk_core/protocol/pjrc/usb_debug.h42
-rw-r--r--tmk_core/protocol/pjrc/usb_extra.c70
-rw-r--r--tmk_core/protocol/pjrc/usb_extra.h46
-rw-r--r--tmk_core/protocol/pjrc/usb_keyboard.c116
-rw-r--r--tmk_core/protocol/pjrc/usb_keyboard.h40
-rw-r--r--tmk_core/protocol/pjrc/usb_mouse.c81
-rw-r--r--tmk_core/protocol/pjrc/usb_mouse.h50
-rw-r--r--tmk_core/protocol/ps2.h134
-rw-r--r--tmk_core/protocol/ps2_busywait.c189
-rw-r--r--tmk_core/protocol/ps2_interrupt.c279
-rw-r--r--tmk_core/protocol/ps2_io.h15
-rw-r--r--tmk_core/protocol/ps2_io_avr.c75
-rw-r--r--tmk_core/protocol/ps2_io_mbed.c60
-rw-r--r--tmk_core/protocol/ps2_mouse.c247
-rw-r--r--tmk_core/protocol/ps2_mouse.h178
-rw-r--r--tmk_core/protocol/ps2_usart.c223
-rw-r--r--tmk_core/protocol/serial.h47
-rw-r--r--tmk_core/protocol/serial_mouse.h33
-rw-r--r--tmk_core/protocol/serial_mouse_microsoft.c124
-rw-r--r--tmk_core/protocol/serial_mouse_mousesystems.c131
-rw-r--r--tmk_core/protocol/serial_soft.c240
-rw-r--r--tmk_core/protocol/serial_uart.c112
-rw-r--r--tmk_core/protocol/usb_hid.mk74
-rw-r--r--tmk_core/protocol/usb_hid/README47
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitattributes23
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitignore4
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitmodules12
-rwxr-xr-xtmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTD.cpp1364
-rwxr-xr-xtmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTD.h620
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTHID.cpp399
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTHID.h155
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3BT.cpp634
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3BT.h240
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3Enums.h141
-rwxr-xr-xtmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3USB.cpp572
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3USB.h303
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4BT.h121
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4Parser.cpp116
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4Parser.h407
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4USB.h130
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PSBuzz.cpp82
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PSBuzz.h185
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/SPP.cpp829
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/SPP.h225
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Usb.cpp812
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Usb.h41
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/UsbCore.h298
-rwxr-xr-xtmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Wii.cpp1268
-rwxr-xr-xtmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Wii.h518
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/WiiCameraReadme.md13
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXOLD.cpp337
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXOLD.h185
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXONE.cpp374
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXONE.h172
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXRECV.cpp583
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXRECV.h276
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXUSB.cpp361
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXUSB.h225
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/address.h282
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/adk.cpp371
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/adk.h140
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/avrpins.h1130
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdc_XR21B1411.cpp211
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdc_XR21B1411.h272
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcacm.cpp331
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcacm.h252
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcftdi.cpp334
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcftdi.h145
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcprolific.cpp247
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcprolific.h159
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/confdescparser.h213
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/controllerEnums.h204
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/BTHID.ino55
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/KeyboardParser.h105
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/MouseParser.h46
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3BT/PS3BT.ino188
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3Multi/PS3Multi.ino149
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3SPP/PS3SPP.ino162
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS4BT/PS4BT.ino146
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/SPP/SPP.ino52
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/SPPMulti/SPPMulti.ino67
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/Wii/Wii.ino118
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiBalanceBoard/WiiBalanceBoard.ino51
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino133
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiMulti/WiiMulti.ino132
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiUProController/WiiUProController.ino104
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino129
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootKbdAndMouse/USBHIDBootKbdAndMouse.ino178
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino83
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/USBHIDJoystick.ino38
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/hidjoystickrptparser.cpp84
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/hidjoystickrptparser.h33
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHID_desc/USBHID_desc.ino77
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHID_desc/pgmstrings.h52
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp.ino42
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp_rptparser.cpp43
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp_rptparser.h42
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale.ino51
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale_rptparser.cpp150
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale_rptparser.h55
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PS3USB/PS3USB.ino148
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PS4USB/PS4USB.ino133
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PSBuzz/PSBuzz.ino49
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/USB_desc/USB_desc.ino349
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/USB_desc/pgmstrings.h52
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXOLD/XBOXOLD.ino110
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXONE/XBOXONE.ino106
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXRECV/XBOXRECV.ino122
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXUSB/XBOXUSB.ino113
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/acm/acm_terminal/acm_terminal.ino100
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/acm/acm_terminal/pgmstrings.h52
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino89
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/adk_barcode/adk_barcode.ino91
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/demokit_20/demokit_20.ino103
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/term_test/term_test.ino65
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/term_time/term_time.ino50
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/board_qc/board_qc.ino259
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/cdc_XR21B1411/XR_terminal/XR_terminal.ino83
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/ftdi/USBFTDILoopback/USBFTDILoopback.ino98
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/ftdi/USBFTDILoopback/pgmstrings.h52
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/hub_demo/hub_demo.ino345
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/hub_demo/pgmstrings.h52
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/max_LCD/max_LCD.ino29
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_gprs_terminal/pl2303_gprs_terminal.ino101
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_gps/pl2303_gps.ino88
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_tinygps/pl2303_tinygps.ino217
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_xbee_terminal/pl2303_xbee_terminal.ino117
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/Makefile64
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/readme.md29
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/testusbhostFAT.ino736
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/gpl2.txt340
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hexdump.h61
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hid.cpp112
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hid.h188
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidboot.cpp201
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidboot.h618
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidescriptorparser.cpp1588
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidescriptorparser.h176
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hiduniversal.cpp425
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hiduniversal.h108
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidusagestr.h977
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidusagetitlearrays.cpp1048
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/keywords.txt371
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/library.json47
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/library.properties9
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/macros.h82
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/masstorage.cpp1266
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/masstorage.h571
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max3421e.h228
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max_LCD.cpp255
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max_LCD.h106
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/message.cpp116
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/message.h78
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/parsetools.cpp67
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/parsetools.h140
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/printhex.h84
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/readme.md351
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/settings.h139
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/sink_parser.h41
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usb_ch9.h166
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhost.h529
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhub.cpp425
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhub.h252
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/version_helper.h194
-rw-r--r--tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/xboxEnums.h65
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Arduino.h215
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/CDC.cpp233
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Client.h26
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HID.cpp520
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HardwareSerial.cpp428
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HardwareSerial.h81
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/IPAddress.cpp56
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/IPAddress.h76
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Platform.h23
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Print.cpp263
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Print.h78
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Printable.h40
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Server.h9
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Stream.cpp270
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Stream.h96
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Tone.cpp601
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBAPI.h195
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBCore.cpp672
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBCore.h303
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBDesc.h63
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Udp.h88
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WCharacter.h168
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WInterrupts.c298
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WMath.cpp60
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WString.cpp645
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WString.h205
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/binary.h515
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/main.cpp20
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/new.cpp18
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/new.h22
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring.c324
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_analog.c282
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_digital.c178
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_private.h69
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_pulse.c69
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_shift.c55
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/variants/eightanaloginputs/pins_arduino.h27
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/variants/leonardo/pins_arduino.h256
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/variants/mega/pins_arduino.h363
-rw-r--r--tmk_core/protocol/usb_hid/arduino-1.0.1/variants/standard/pins_arduino.h218
-rw-r--r--tmk_core/protocol/usb_hid/override_Serial.cpp51
-rw-r--r--tmk_core/protocol/usb_hid/override_wiring.c29
-rw-r--r--tmk_core/protocol/usb_hid/parser.cpp33
-rw-r--r--tmk_core/protocol/usb_hid/parser.h12
-rw-r--r--tmk_core/protocol/usb_hid/test/Makefile88
-rw-r--r--tmk_core/protocol/usb_hid/test/config.h40
-rw-r--r--tmk_core/protocol/usb_hid/test/test.cpp92
-rw-r--r--tmk_core/protocol/usb_hid/usb_hid.h10
-rw-r--r--tmk_core/protocol/vusb.mk22
-rw-r--r--tmk_core/protocol/vusb/main.c104
-rw-r--r--tmk_core/protocol/vusb/sendchar_usart.c23
-rw-r--r--tmk_core/protocol/vusb/usbdrv/Changelog.txt308
-rw-r--r--tmk_core/protocol/vusb/usbdrv/CommercialLicense.txt166
-rw-r--r--tmk_core/protocol/vusb/usbdrv/License.txt361
-rw-r--r--tmk_core/protocol/vusb/usbdrv/Readme.txt172
-rw-r--r--tmk_core/protocol/vusb/usbdrv/USB-ID-FAQ.txt149
-rw-r--r--tmk_core/protocol/vusb/usbdrv/USB-IDs-for-free.txt148
-rw-r--r--tmk_core/protocol/vusb/usbdrv/asmcommon.inc188
-rw-r--r--tmk_core/protocol/vusb/usbdrv/oddebug.c50
-rw-r--r--tmk_core/protocol/vusb/usbdrv/oddebug.h123
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbconfig-prototype.h376
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrv.c625
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrv.h735
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm.S393
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm.asm21
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm12.inc393
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm128.inc750
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm15.inc423
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm16.inc346
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm165.inc453
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm18-crc.inc707
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbdrvasm20.inc360
-rw-r--r--tmk_core/protocol/vusb/usbdrv/usbportability.h144
-rw-r--r--tmk_core/protocol/vusb/vusb.c510
-rw-r--r--tmk_core/protocol/vusb/vusb.h27
307 files changed, 67836 insertions, 0 deletions
diff --git a/tmk_core/protocol/adb.c b/tmk_core/protocol/adb.c
new file mode 100644
index 000000000..5c6c99b4f
--- /dev/null
+++ b/tmk_core/protocol/adb.c
@@ -0,0 +1,478 @@
+/*
+Copyright 2011 Jun WAKO <wakojun@gmail.com>
+Copyright 2013 Shay Green <gblargg@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <stdbool.h>
+#include <util/delay.h>
+#include <avr/io.h>
+#include <avr/interrupt.h>
+#include "adb.h"
+
+
+// GCC doesn't inline functions normally
+#define data_lo() (ADB_DDR |= (1<<ADB_DATA_BIT))
+#define data_hi() (ADB_DDR &= ~(1<<ADB_DATA_BIT))
+#define data_in() (ADB_PIN & (1<<ADB_DATA_BIT))
+
+#ifdef ADB_PSW_BIT
+static inline void psw_lo(void);
+static inline void psw_hi(void);
+static inline bool psw_in(void);
+#endif
+
+static inline void attention(void);
+static inline void place_bit0(void);
+static inline void place_bit1(void);
+static inline void send_byte(uint8_t data);
+static inline uint16_t wait_data_lo(uint16_t us);
+static inline uint16_t wait_data_hi(uint16_t us);
+static inline uint16_t adb_host_dev_recv(uint8_t device);
+
+
+void adb_host_init(void)
+{
+ ADB_PORT &= ~(1<<ADB_DATA_BIT);
+ data_hi();
+#ifdef ADB_PSW_BIT
+ psw_hi();
+#endif
+}
+
+#ifdef ADB_PSW_BIT
+bool adb_host_psw(void)
+{
+ return psw_in();
+}
+#endif
+
+/*
+ * Don't call this in a row without the delay, otherwise it makes some of poor controllers
+ * overloaded and misses strokes. Recommended interval is 12ms.
+ *
+ * Thanks a lot, blargg!
+ * <http://geekhack.org/index.php?topic=14290.msg1068919#msg1068919>
+ * <http://geekhack.org/index.php?topic=14290.msg1070139#msg1070139>
+ */
+
+// ADB Bit Cells
+//
+// bit cell time: 70-130us
+// low part of bit0: 60-70% of bit cell
+// low part of bit1: 30-40% of bit cell
+//
+// bit cell time 70us 130us
+// --------------------------------------------
+// low part of bit0 42-49 78-91
+// high part of bit0 21-28 39-52
+// low part of bit1 21-28 39-52
+// high part of bit1 42-49 78-91
+//
+//
+// bit0:
+// 70us bit cell:
+// ____________~~~~~~
+// 42-49 21-28
+//
+// 130us bit cell:
+// ____________~~~~~~
+// 78-91 39-52
+//
+// bit1:
+// 70us bit cell:
+// ______~~~~~~~~~~~~
+// 21-28 42-49
+//
+// 130us bit cell:
+// ______~~~~~~~~~~~~
+// 39-52 78-91
+//
+// [from Apple IIgs Hardware Reference Second Edition]
+
+enum {
+ ADDR_KEYB = 0x20,
+ ADDR_MOUSE = 0x30
+};
+
+uint16_t adb_host_kbd_recv(void)
+{
+ return adb_host_dev_recv(ADDR_KEYB);
+}
+
+#ifdef ADB_MOUSE_ENABLE
+void adb_mouse_init(void) {
+ return;
+}
+
+uint16_t adb_host_mouse_recv(void)
+{
+ return adb_host_dev_recv(ADDR_MOUSE);
+}
+#endif
+
+static inline uint16_t adb_host_dev_recv(uint8_t device)
+{
+ uint16_t data = 0;
+ cli();
+ attention();
+ send_byte(device|0x0C); // Addr:Keyboard(0010)/Mouse(0011), Cmd:Talk(11), Register0(00)
+ place_bit0(); // Stopbit(0)
+ if (!wait_data_hi(500)) { // Service Request(310us Adjustable Keyboard): just ignored
+ sei();
+ return -30; // something wrong
+ }
+ if (!wait_data_lo(500)) { // Tlt/Stop to Start(140-260us)
+ sei();
+ return 0; // No data to send
+ }
+
+ uint8_t n = 17; // start bit + 16 data bits
+ do {
+ uint8_t lo = (uint8_t) wait_data_hi(130);
+ if (!lo)
+ goto error;
+
+ uint8_t hi = (uint8_t) wait_data_lo(lo);
+ if (!hi)
+ goto error;
+
+ hi = lo - hi;
+ lo = 130 - lo;
+
+ data <<= 1;
+ if (lo < hi) {
+ data |= 1;
+ }
+ else if (n == 17) {
+ sei();
+ return -20;
+ }
+ }
+ while ( --n );
+
+ // Stop bit can't be checked normally since it could have service request lenghtening
+ // and its high state never goes low.
+ if (!wait_data_hi(351) || wait_data_lo(91)) {
+ sei();
+ return -21;
+ }
+ sei();
+ return data;
+
+error:
+ sei();
+ return -n;
+}
+
+void adb_host_listen(uint8_t cmd, uint8_t data_h, uint8_t data_l)
+{
+ cli();
+ attention();
+ send_byte(cmd);
+ place_bit0(); // Stopbit(0)
+ _delay_us(200); // Tlt/Stop to Start
+ place_bit1(); // Startbit(1)
+ send_byte(data_h);
+ send_byte(data_l);
+ place_bit0(); // Stopbit(0);
+ sei();
+}
+
+// send state of LEDs
+void adb_host_kbd_led(uint8_t led)
+{
+ // Addr:Keyboard(0010), Cmd:Listen(10), Register2(10)
+ // send upper byte (not used)
+ // send lower byte (bit2: ScrollLock, bit1: CapsLock, bit0:
+ adb_host_listen(0x2A,0,led&0x07);
+}
+
+
+#ifdef ADB_PSW_BIT
+static inline void psw_lo()
+{
+ ADB_DDR |= (1<<ADB_PSW_BIT);
+ ADB_PORT &= ~(1<<ADB_PSW_BIT);
+}
+static inline void psw_hi()
+{
+ ADB_PORT |= (1<<ADB_PSW_BIT);
+ ADB_DDR &= ~(1<<ADB_PSW_BIT);
+}
+static inline bool psw_in()
+{
+ ADB_PORT |= (1<<ADB_PSW_BIT);
+ ADB_DDR &= ~(1<<ADB_PSW_BIT);
+ return ADB_PIN&(1<<ADB_PSW_BIT);
+}
+#endif
+
+static inline void attention(void)
+{
+ data_lo();
+ _delay_us(800-35); // bit1 holds lo for 35 more
+ place_bit1();
+}
+
+static inline void place_bit0(void)
+{
+ data_lo();
+ _delay_us(65);
+ data_hi();
+ _delay_us(35);
+}
+
+static inline void place_bit1(void)
+{
+ data_lo();
+ _delay_us(35);
+ data_hi();
+ _delay_us(65);
+}
+
+static inline void send_byte(uint8_t data)
+{
+ for (int i = 0; i < 8; i++) {
+ if (data&(0x80>>i))
+ place_bit1();
+ else
+ place_bit0();
+ }
+}
+
+// These are carefully coded to take 6 cycles of overhead.
+// inline asm approach became too convoluted
+static inline uint16_t wait_data_lo(uint16_t us)
+{
+ do {
+ if ( !data_in() )
+ break;
+ _delay_us(1 - (6 * 1000000.0 / F_CPU));
+ }
+ while ( --us );
+ return us;
+}
+
+static inline uint16_t wait_data_hi(uint16_t us)
+{
+ do {
+ if ( data_in() )
+ break;
+ _delay_us(1 - (6 * 1000000.0 / F_CPU));
+ }
+ while ( --us );
+ return us;
+}
+
+
+/*
+ADB Protocol
+============
+
+Resources
+---------
+ADB - The Untold Story: Space Aliens Ate My Mouse
+ http://developer.apple.com/legacy/mac/library/#technotes/hw/hw_01.html
+ADB Manager
+ http://developer.apple.com/legacy/mac/library/documentation/mac/pdf/Devices/ADB_Manager.pdf
+ Service request(5-17)
+Apple IIgs Hardware Reference Second Edition [Chapter6 p121]
+ ftp://ftp.apple.asimov.net/pub/apple_II/documentation/Apple%20IIgs%20Hardware%20Reference.pdf
+ADB Keycode
+ http://72.0.193.250/Documentation/macppc/adbkeycodes/
+ http://m0115.web.fc2.com/m0115.jpg
+ [Inside Macintosh volume V, pages 191-192]
+ http://www.opensource.apple.com/source/IOHIDFamily/IOHIDFamily-421.18.3/IOHIDFamily/Cosmo_USB2ADB.c
+ADB Signaling
+ http://kbdbabel.sourceforge.net/doc/kbd_signaling_pcxt_ps2_adb.pdf
+ADB Overview & History
+ http://en.wikipedia.org/wiki/Apple_Desktop_Bus
+Microchip Application Note: ADB device(with code for PIC16C)
+ http://www.microchip.com/stellent/idcplg?IdcService=SS_GET_PAGE&nodeId=1824&appnote=en011062
+AVR ATtiny2131 ADB to PS/2 converter(Japanese)
+ http://hp.vector.co.jp/authors/VA000177/html/KeyBoardA5DEA5CBA5A2II.html
+
+
+Pinouts
+-------
+ ADB female socket from the front:
+ __________
+ | | <--- top
+ | 4o o3 |
+ |2o o1|
+ | == |
+ |________| <--- bottom
+ | | <--- 4pins
+
+
+ ADB female socket from bottom:
+
+ ========== <--- front
+ | |
+ | |
+ |2o o1|
+ |4o o3|
+ ---------- <--- back
+
+ 1: Data
+ 2: Power SW(low when press Power key)
+ 3: Vcc(5V)
+ 4: GND
+
+
+Commands
+--------
+ ADB command is 1byte and consists of 4bit-address, 2bit-command
+ type and 2bit-register. The commands are always sent by Host.
+
+ Command format:
+ 7 6 5 4 3 2 1 0
+ | | | |------------ address
+ | |-------- command type
+ | |---- register
+
+ bits commands
+ ------------------------------------------------------
+ - - - - 0 0 0 0 Send Request(reset all devices)
+ A A A A 0 0 0 1 Flush(reset a device)
+ - - - - 0 0 1 0 Reserved
+ - - - - 0 0 1 1 Reserved
+ - - - - 0 1 - - Reserved
+ A A A A 1 0 R R Listen(write to a device)
+ A A A A 1 1 R R Talk(read from a device)
+
+ The command to read keycodes from keyboard is 0x2C which
+ consist of keyboard address 2 and Talk against register 0.
+
+ Address:
+ 2: keyboard
+ 3: mice
+
+ Registers:
+ 0: application(keyboard uses this to store its data.)
+ 1: application
+ 2: application(keyboard uses this for LEDs and state of modifiers)
+ 3: status and command
+
+
+Communication
+-------------
+ This is a minimum information for keyboard communication.
+ See "Resources" for detail.
+
+ Signaling:
+
+ ~~~~____________~~||||||||||||__~~~~~_~~|||||||||||||||__~~~~
+
+ |800us | |7 Command 0| | | |15-64 Data 0|Stopbit(0)
+ +Attention | | | +Startbit(1)
+ +Startbit(1) | +Tlt(140-260us)
+ +stopbit(0)
+
+ Bit cells:
+
+ bit0: ______~~~
+ 65 :35us
+
+ bit1: ___~~~~~~
+ 35 :65us
+
+ bit0 low time: 60-70% of bit cell(42-91us)
+ bit1 low time: 30-40% of bit cell(21-52us)
+ bit cell time: 70-130us
+ [from Apple IIgs Hardware Reference Second Edition]
+
+ Criterion for bit0/1:
+ After 55us if line is low/high then bit is 0/1.
+
+ Attention & start bit:
+ Host asserts low in 560-1040us then places start bit(1).
+
+ Tlt(Stop to Start):
+ Bus stays high in 140-260us then device places start bit(1).
+
+ Global reset:
+ Host asserts low in 2.8-5.2ms. All devices are forced to reset.
+
+ Service request from device(Srq):
+ Device can request to send at commad(Global only?) stop bit.
+ Requesting device keeps low for 140-260us at stop bit of command.
+
+
+Keyboard Data(Register0)
+ This 16bit data can contains two keycodes and two released flags.
+ First keycode is palced in upper byte. When one keyocode is sent,
+ lower byte is 0xFF.
+ Release flag is 1 when key is released.
+
+ 1514 . . . . . 8 7 6 . . . . . 0
+ | | | | | | | | | +-+-+-+-+-+-+- Keycode2
+ | | | | | | | | +--------------- Released2(1 when the key is released)
+ | +-+-+-+-+-+-+----------------- Keycode1
+ +------------------------------- Released1(1 when the key is released)
+
+ Keycodes:
+ Scancode consists of 7bit keycode and 1bit release flag.
+ Device can send two keycodes at once. If just one keycode is sent
+ keycode1 contains it and keyocode2 is 0xFF.
+
+ Power switch:
+ You can read the state from PSW line(active low) however
+ the switch has a special scancode 0x7F7F, so you can
+ also read from Data line. It uses 0xFFFF for release scancode.
+
+Keyboard LEDs & state of keys(Register2)
+ This register hold current state of three LEDs and nine keys.
+ The state of LEDs can be changed by sending Listen command.
+
+ 1514 . . . . . . 7 6 5 . 3 2 1 0
+ | | | | | | | | | | | | | | | +- LED1(NumLock)
+ | | | | | | | | | | | | | | +--- LED2(CapsLock)
+ | | | | | | | | | | | | | +----- LED3(ScrollLock)
+ | | | | | | | | | | +-+-+------- Reserved
+ | | | | | | | | | +------------- ScrollLock
+ | | | | | | | | +--------------- NumLock
+ | | | | | | | +----------------- Apple/Command
+ | | | | | | +------------------- Option
+ | | | | | +--------------------- Shift
+ | | | | +----------------------- Control
+ | | | +------------------------- Reset/Power
+ | | +--------------------------- CapsLock
+ | +----------------------------- Delete
+ +------------------------------- Reserved
+
+END_OF_ADB
+*/
diff --git a/tmk_core/protocol/adb.h b/tmk_core/protocol/adb.h
new file mode 100644
index 000000000..b4b3633cf
--- /dev/null
+++ b/tmk_core/protocol/adb.h
@@ -0,0 +1,66 @@
+/*
+Copyright 2011 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef ADB_H
+#define ADB_H
+
+#include <stdint.h>
+#include <stdbool.h>
+
+#if !(defined(ADB_PORT) && \
+ defined(ADB_PIN) && \
+ defined(ADB_DDR) && \
+ defined(ADB_DATA_BIT))
+# error "ADB port setting is required in config.h"
+#endif
+
+#define ADB_POWER 0x7F
+#define ADB_CAPS 0x39
+
+
+// ADB host
+void adb_host_init(void);
+bool adb_host_psw(void);
+uint16_t adb_host_kbd_recv(void);
+uint16_t adb_host_mouse_recv(void);
+void adb_host_listen(uint8_t cmd, uint8_t data_h, uint8_t data_l);
+void adb_host_kbd_led(uint8_t led);
+void adb_mouse_task(void);
+void adb_mouse_init(void);
+
+
+#endif
diff --git a/tmk_core/protocol/bluefruit.mk b/tmk_core/protocol/bluefruit.mk
new file mode 100644
index 000000000..e1c5fff77
--- /dev/null
+++ b/tmk_core/protocol/bluefruit.mk
@@ -0,0 +1,27 @@
+BLUEFRUIT_DIR = protocol/bluefruit
+PJRC_DIR = protocol/pjrc
+
+SRC += $(BLUEFRUIT_DIR)/main.c \
+ $(BLUEFRUIT_DIR)/bluefruit.c \
+ serial_uart.c \
+ $(PJRC_DIR)/pjrc.c \
+ $(PJRC_DIR)/usb_keyboard.c \
+ $(PJRC_DIR)/usb_debug.c \
+ $(PJRC_DIR)/usb.c
+
+# Option modules
+ifdef $(or MOUSEKEY_ENABLE, PS2_MOUSE_ENABLE)
+ SRC += $(PJRC_DIR)/usb_mouse.c
+endif
+
+ifdef EXTRAKEY_ENABLE
+ SRC += $(PJRC_DIR)/usb_extra.c
+endif
+
+# Search Path
+VPATH += $(TMK_DIR)/$(BLUEFRUIT_DIR)
+#VPATH += $(TMK_DIR)/$(BLUEFRUIT_DIR)/usb_debug_only
+VPATH += $(TMK_DIR)/$(PJRC_DIR)
+
+OPT_DEFS += -DPROTOCOL_BLUEFRUIT
+OPT_DEFS += -DPROTOCOL_PJRC
diff --git a/tmk_core/protocol/bluefruit/bluefruit.c b/tmk_core/protocol/bluefruit/bluefruit.c
new file mode 100644
index 000000000..47c63555c
--- /dev/null
+++ b/tmk_core/protocol/bluefruit/bluefruit.c
@@ -0,0 +1,205 @@
+/*
+Bluefruit Protocol for TMK firmware
+Author: Benjamin Gould, 2013
+Based on code Copyright 2011 Jun Wako <wakojun@gmail.com>
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdint.h>
+#include "host.h"
+#include "report.h"
+#include "print.h"
+#include "debug.h"
+#include "host_driver.h"
+#include "serial.h"
+#include "bluefruit.h"
+
+#define BLUEFRUIT_TRACE_SERIAL 1
+
+static uint8_t bluefruit_keyboard_leds = 0;
+
+static void bluefruit_serial_send(uint8_t);
+
+void bluefruit_keyboard_print_report(report_keyboard_t *report)
+{
+ if (!debug_keyboard) return;
+ dprintf("keys: "); for (int i = 0; i < KEYBOARD_REPORT_KEYS; i++) { debug_hex8(report->keys[i]); dprintf(" "); }
+ dprintf(" mods: "); debug_hex8(report->mods);
+ dprintf(" reserved: "); debug_hex8(report->reserved);
+ dprintf("\n");
+}
+
+#ifdef BLUEFRUIT_TRACE_SERIAL
+static void bluefruit_trace_header()
+{
+ dprintf("+------------------------------------+\n");
+ dprintf("| HID report to Bluefruit via serial |\n");
+ dprintf("+------------------------------------+\n|");
+}
+
+static void bluefruit_trace_footer()
+{
+ dprintf("|\n+------------------------------------+\n\n");
+}
+#endif
+
+static void bluefruit_serial_send(uint8_t data)
+{
+#ifdef BLUEFRUIT_TRACE_SERIAL
+ dprintf(" ");
+ debug_hex8(data);
+ dprintf(" ");
+#endif
+ serial_send(data);
+}
+
+/*------------------------------------------------------------------*
+ * Host driver
+ *------------------------------------------------------------------*/
+
+static uint8_t keyboard_leds(void);
+static void send_keyboard(report_keyboard_t *report);
+static void send_mouse(report_mouse_t *report);
+static void send_system(uint16_t data);
+static void send_consumer(uint16_t data);
+
+
+void sendString(char string[], int length) {
+ for(int i = 0; i < length; i++) {
+ serial_send(string[i]);
+ }
+}
+
+static host_driver_t driver = {
+ keyboard_leds,
+ send_keyboard,
+ send_mouse,
+ send_system,
+ send_consumer
+};
+
+host_driver_t *bluefruit_driver(void)
+{
+ return &driver;
+}
+
+static uint8_t keyboard_leds(void) {
+ return bluefruit_keyboard_leds;
+}
+
+static void send_keyboard(report_keyboard_t *report)
+{
+#ifdef BLUEFRUIT_TRACE_SERIAL
+ bluefruit_trace_header();
+#endif
+ bluefruit_serial_send(0xFD);
+ for (uint8_t i = 0; i < KEYBOARD_REPORT_SIZE; i++) {
+
+ bluefruit_serial_send(report->raw[i]);
+ }
+#ifdef BLUEFRUIT_TRACE_SERIAL
+ bluefruit_trace_footer();
+#endif
+}
+
+static void send_mouse(report_mouse_t *report)
+{
+#ifdef BLUEFRUIT_TRACE_SERIAL
+ bluefruit_trace_header();
+#endif
+ bluefruit_serial_send(0xFD);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x03);
+ bluefruit_serial_send(report->buttons);
+ bluefruit_serial_send(report->x);
+ bluefruit_serial_send(report->y);
+ bluefruit_serial_send(report->v); // should try sending the wheel v here
+ bluefruit_serial_send(report->h); // should try sending the wheel h here
+ bluefruit_serial_send(0x00);
+#ifdef BLUEFRUIT_TRACE_SERIAL
+ bluefruit_trace_footer();
+#endif
+}
+
+static void send_system(uint16_t data)
+{
+}
+
+/*
++-----------------+-------------------+-------+
+| Consumer Key | Bit Map | Hex |
++-----------------+-------------------+-------+
+| Home | 00000001 00000000 | 01 00 |
+| KeyboardLayout | 00000010 00000000 | 02 00 |
+| Search | 00000100 00000000 | 04 00 |
+| Snapshot | 00001000 00000000 | 08 00 |
+| VolumeUp | 00010000 00000000 | 10 00 |
+| VolumeDown | 00100000 00000000 | 20 00 |
+| Play/Pause | 01000000 00000000 | 40 00 |
+| Fast Forward | 10000000 00000000 | 80 00 |
+| Rewind | 00000000 00000001 | 00 01 |
+| Scan Next Track | 00000000 00000010 | 00 02 |
+| Scan Prev Track | 00000000 00000100 | 00 04 |
+| Random Play | 00000000 00001000 | 00 08 |
+| Stop | 00000000 00010000 | 00 10 |
++-------------------------------------+-------+
+*/
+#define CONSUMER2BLUEFRUIT(usage) \
+ (usage == AUDIO_MUTE ? 0x0000 : \
+ (usage == AUDIO_VOL_UP ? 0x1000 : \
+ (usage == AUDIO_VOL_DOWN ? 0x2000 : \
+ (usage == TRANSPORT_NEXT_TRACK ? 0x0002 : \
+ (usage == TRANSPORT_PREV_TRACK ? 0x0004 : \
+ (usage == TRANSPORT_STOP ? 0x0010 : \
+ (usage == TRANSPORT_STOP_EJECT ? 0x0000 : \
+ (usage == TRANSPORT_PLAY_PAUSE ? 0x4000 : \
+ (usage == AL_CC_CONFIG ? 0x0000 : \
+ (usage == AL_EMAIL ? 0x0000 : \
+ (usage == AL_CALCULATOR ? 0x0000 : \
+ (usage == AL_LOCAL_BROWSER ? 0x0000 : \
+ (usage == AC_SEARCH ? 0x0400 : \
+ (usage == AC_HOME ? 0x0100 : \
+ (usage == AC_BACK ? 0x0000 : \
+ (usage == AC_FORWARD ? 0x0000 : \
+ (usage == AC_STOP ? 0x0000 : \
+ (usage == AC_REFRESH ? 0x0000 : \
+ (usage == AC_BOOKMARKS ? 0x0000 : 0)))))))))))))))))))
+
+static void send_consumer(uint16_t data)
+{
+ static uint16_t last_data = 0;
+ if (data == last_data) return;
+ last_data = data;
+
+ uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
+
+#ifdef BLUEFRUIT_TRACE_SERIAL
+ dprintf("\nData: ");
+ debug_hex16(data);
+ dprintf("; bitmap: ");
+ debug_hex16(bitmap);
+ dprintf("\n");
+ bluefruit_trace_header();
+#endif
+ bluefruit_serial_send(0xFD);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x02);
+ bluefruit_serial_send((bitmap>>8)&0xFF);
+ bluefruit_serial_send(bitmap&0xFF);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x00);
+#ifdef BLUEFRUIT_TRACE_SERIAL
+ bluefruit_trace_footer();
+#endif
+} \ No newline at end of file
diff --git a/tmk_core/protocol/bluefruit/bluefruit.h b/tmk_core/protocol/bluefruit/bluefruit.h
new file mode 100644
index 000000000..ceacc4a36
--- /dev/null
+++ b/tmk_core/protocol/bluefruit/bluefruit.h
@@ -0,0 +1,25 @@
+/*
+Bluefruit Protocol for TMK firmware
+Author: Benjamin Gould, 2013
+Based on code Copyright 2011 Jun Wako <wakojun@gmail.com>
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef VUSB_H
+#define VUSB_H
+
+#include "host_driver.h"
+
+
+host_driver_t *bluefruit_driver(void);
+
+#endif \ No newline at end of file
diff --git a/tmk_core/protocol/bluefruit/main.c b/tmk_core/protocol/bluefruit/main.c
new file mode 100644
index 000000000..0dbb637e2
--- /dev/null
+++ b/tmk_core/protocol/bluefruit/main.c
@@ -0,0 +1,138 @@
+/*
+Bluefruit Protocol for TMK firmware
+Author: Benjamin Gould, 2013
+Based on code Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdint.h>
+#include <avr/interrupt.h>
+#include <avr/wdt.h>
+#include <avr/sleep.h>
+#include <util/delay.h>
+#include "../serial.h"
+#include "keyboard.h"
+#include "usb.h"
+#include "host.h"
+#include "timer.h"
+#include "print.h"
+#include "debug.h"
+#include "sendchar.h"
+#include "suspend.h"
+#include "bluefruit.h"
+#include "pjrc.h"
+
+#define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
+
+#define HOST_DRIVER_NOT_SET 0
+#define BLUEFRUIT_HOST_DRIVER 1
+#define PJRC_HOST_DRIVER 2
+
+
+int main(void)
+{
+
+ CPU_PRESCALE(0);
+
+ // DDRD = _BV(PD5);
+ // DDRB = _BV(PB0);
+
+ // PORTD = _BV(PD5);
+ // PORTB = _BV(PB0);
+
+ print_set_sendchar(sendchar);
+
+ // usb_init();
+ // _delay_ms(2000);
+ // while (!usb_configured()) /* wait */
+
+
+
+ dprintf("Initializing keyboard...\n");
+ keyboard_init();
+
+ // This implementation is pretty simplistic... if the USB connection
+ // is not configured, choose the Bluefruit, otherwise use USB
+ // Definitely would prefer to have this driven by an input pin and make
+ // it switch dynamically - BCG
+ // if (!usb_configured()) {
+
+ // // Send power to Bluefruit... Adafruit says it takes 27 mA, I think
+ // // the pins should provide 40 mA, but just in case I switch the
+ // // Bluefruit using a transistor - BCG
+ // DDRB = _BV(PB6);
+ // PORTB |= _BV(PB6);
+
+ dprintf("Setting host driver to bluefruit...\n");
+ host_set_driver(bluefruit_driver());
+
+ dprintf("Initializing serial...\n");
+ serial_init();
+
+ // char swpa[] = "+++\r\n";
+ // for (int i = 0; i < 5; i++) {
+ // serial_send(swpa[i]);
+ // }
+
+ // char ble_enable[] = "AT+BLEKEYBOARDEN=1\r\n";
+ // for (int i = 0; i < 20; i++) {
+ // serial_send(ble_enable[i]);
+ // }
+
+ // char reset[] = "ATZ\r\n";
+ // for (int i = 0; i < 5; i++) {
+ // serial_send(reset[i]);
+ // }
+
+ // for (int i = 0; i < 5; i++) {
+ // serial_send(swpa[i]);
+ // }
+
+ // wait an extra second for the PC's operating system
+ // to load drivers and do whatever it does to actually
+ // be ready for input
+ _delay_ms(1000);
+ // PORTD = ~_BV(PD5);
+ dprintf("Starting main loop");
+ while (1) {
+ keyboard_task();
+ }
+
+// } else {
+
+// // I'm not smart enough to get this done with LUFA - BCG
+// dprintf("Setting host driver to PJRC...\n");
+// host_set_driver(pjrc_driver());
+// #ifdef SLEEP_LED_ENABLE
+// sleep_led_init();
+// #endif
+// // wait an extra second for the PC's operating system
+// // to load drivers and do whatever it does to actually
+// // be ready for input
+// _delay_ms(1000);
+// PORTB = ~_BV(PB0);
+// dprintf("Starting main loop");
+// while (1) {
+// while (suspend) {
+// suspend_power_down();
+// if (remote_wakeup && suspend_wakeup_condition()) {
+// usb_remote_wakeup();
+// }
+// }
+// keyboard_task();
+// }
+// }
+
+}
diff --git a/tmk_core/protocol/chibios.mk b/tmk_core/protocol/chibios.mk
new file mode 100644
index 000000000..3f4e0a71f
--- /dev/null
+++ b/tmk_core/protocol/chibios.mk
@@ -0,0 +1,10 @@
+PROTOCOL_DIR = protocol
+CHIBIOS_DIR = $(PROTOCOL_DIR)/chibios
+
+
+SRC += $(CHIBIOS_DIR)/usb_main.c
+SRC += $(CHIBIOS_DIR)/main.c
+
+VPATH += $(TMK_PATH)/$(PROTOCOL_DIR)
+VPATH += $(TMK_PATH)/$(CHIBIOS_DIR)
+
diff --git a/tmk_core/protocol/chibios/README.md b/tmk_core/protocol/chibios/README.md
new file mode 100644
index 000000000..63e6641f8
--- /dev/null
+++ b/tmk_core/protocol/chibios/README.md
@@ -0,0 +1,55 @@
+## TMK running on top of ChibiOS
+
+This code can be used to run TMK keyboard logic on top of [ChibiOS], meaning that you can run TMK on whatever [ChibiOS] supports. The notable examples are ARM-based Teensies (3.x and LC) and on the boards with STM32 MCUs.
+
+### Usage
+
+- To use, [get a zip of chibios](https://github.com/ChibiOS/ChibiOS/archive/a7df9a891067621e8e1a5c2a2c0ceada82403afe.zip) and unpack/rename it to `tmk_core/tool/chibios/chibios`; or you can just clone [the repo](https://github.com/ChibiOS/ChibiOS) there. For Freescale/NXP Kinetis support (meaning ARM Teensies and the Infinity keyboard), you'll also need [a zip of chibios-contrib](https://github.com/ChibiOS/ChibiOS-Contrib/archive/e1311c4db6cd366cf760673f769e925741ac0ad3.zip), unpacked/renamed to `tmk_core/tool/chibios/chibios-contrib`. Likewise, for git-savvy people, just clone [the repo](https://github.com/ChibiOS/ChibiOS-Contrib) there.
+- Note: the abovementioned directories are the defaults. You can have the two chibios repositories wherever you want, just define their location in `CHIBIOS` and `CHIBIOS_CONTRIB` variables in your `Makefile`.
+- You will also need to install an ARM toolchain, for instance from [here](https://launchpad.net/gcc-arm-embedded). On linux, this is usually also present as a package for your distribution (as `gcc-arm` or something similar). On OS X, you can use [homebrew](http://brew.sh/) with an appropriate tap.
+
+### Notes
+
+- Some comments about ChibiOS syntax and the most commonly used GPIO functions are, as well as an example for ARM Teensies, is [here](https://github.com/tmk/tmk_keyboard/blob/master/keyboard/teensy_lc_onekey/instructions.md).
+- For gcc options, inspect `tmk_core/tool/chibios/chibios.mk`. For instance, I enabled `-Wno-missing-field-initializers`, because TMK common bits generated a lot of warnings on that.
+- For debugging, it is sometimes useful disable gcc optimisations, you can do that by adding `-O0` to `OPT_DEFS` in your `Makefile`.
+- USB string descriptors are messy. I did not find a way to cleanly generate the right structures from actual strings, so the definitions in individual keyboards' `config.h` are ugly as heck.
+- It is easy to add some code for testing (e.g. blink LED, do stuff on button press, etc...) - just create another thread in `main.c`, it will run independently of the keyboard business.
+- Jumping to (the built-in) bootloaders on STM32 works, but it is not entirely pleasant, since it is very much MCU dependent. So, one needs to dig out the right address to jump to, and either pass it to the compiler in the `Makefile`, or better, define it in `<your_kb>/bootloader_defs.h`. An additional startup code is also needed; the best way to deal with this is to define custom board files. (Example forthcoming.) In any case, there are no problems for Teensies.
+
+
+### Immediate todo
+
+- power saving for suspend
+
+### Not tested, but possibly working
+
+- backlight
+
+### Missing / not working (TMK vs ChibiOS bits)
+
+- eeprom / bootmagic for STM32 (will be chip dependent; eeprom needs to be emulated in flash, which means less writes; wear-levelling?) There is a semi-official ST "driver" for eeprom, with wear-levelling, but I think it consumes a lot of RAM (like 2 pages, i.e. 1kB or so).
+
+### Tried with
+
+- Infinity, WhiteFox keyboards
+- all ARM-based Teensies
+- some STM32-based boards (e.g. ST-F072RB-DISCOVERY board, STM32F042 breakout board, Maple Mini (STM32F103-based))
+
+## ChibiOS-supported MCUs
+
+- Pretty much all STM32 chips.
+- K20x and KL2x Freescale/NXP chips (i.e. Teensy 3.x/LC, mchck, FRDM-KL2{5,6}Z, FRDM-K20D50M), via the [ChibiOS-Contrib](https://github.com/ChibiOS/ChibiOS-Contrib) repository.
+- There is also support for AVR8, but the USB stack is not implemented for them yet (some news on that front recently though), and also the kernel itself takes about 1k of RAM. I think people managed to get ChibiOS running on atmega32[8p/u4] though.
+- There is also support for Nordic NRF51822 (the chip in Adafruit's Bluefruit bluetooth-low-energy boards), but be aware that that chip does *not* have USB, and the BLE softdevice (i.e. Bluetooth) is not supported directly at the moment.
+
+## STM32-based keyboard design considerations
+
+- STM32F0x2 chips can do crystal-less USB, but they still need a 3.3V voltage regulator.
+- The BOOT0 pin should be tied to GND.
+- For a hardware way of accessing the in-built DFU bootloader, in addition to the reset button, put another button between the BOOT0 pin and 3V3.
+- There is a working example of a STM32F042-based keyboard: [firmware here](https://github.com/flabbergast/flabber_kbs/tree/master/kb45p) and [hardware (kicad) here](https://github.com/flabbergast/kicad/tree/master/kb45p). You can check this example firmware for custom board files, and a more complicated matrix than just one key.
+
+
+
+[ChibiOS]: http://chibios.org
diff --git a/tmk_core/protocol/chibios/main.c b/tmk_core/protocol/chibios/main.c
new file mode 100644
index 000000000..b0eb9aef8
--- /dev/null
+++ b/tmk_core/protocol/chibios/main.c
@@ -0,0 +1,186 @@
+/*
+ * (c) 2015 flabberast <s3+flabbergast@sdfeu.org>
+ *
+ * Based on the following work:
+ * - Guillaume Duc's raw hid example (MIT License)
+ * https://github.com/guiduc/usb-hid-chibios-example
+ * - PJRC Teensy examples (MIT License)
+ * https://www.pjrc.com/teensy/usb_keyboard.html
+ * - hasu's TMK keyboard code (GPL v2 and some code Modified BSD)
+ * https://github.com/tmk/tmk_keyboard/
+ * - ChibiOS demo code (Apache 2.0 License)
+ * http://www.chibios.org
+ *
+ * Since some GPL'd code is used, this work is licensed under
+ * GPL v2 or later.
+ */
+
+#include "ch.h"
+#include "hal.h"
+
+#include "usb_main.h"
+
+/* TMK includes */
+#include "report.h"
+#include "host.h"
+#include "host_driver.h"
+#include "keyboard.h"
+#include "action.h"
+#include "action_util.h"
+#include "mousekey.h"
+#include "led.h"
+#include "sendchar.h"
+#include "debug.h"
+#include "printf.h"
+#ifdef SLEEP_LED_ENABLE
+#include "sleep_led.h"
+#endif
+#ifdef SERIAL_LINK_ENABLE
+#include "serial_link/system/serial_link.h"
+#endif
+#ifdef VISUALIZER_ENABLE
+#include "visualizer/visualizer.h"
+#endif
+#include "suspend.h"
+
+
+/* -------------------------
+ * TMK host driver defs
+ * -------------------------
+ */
+
+/* declarations */
+uint8_t keyboard_leds(void);
+void send_keyboard(report_keyboard_t *report);
+void send_mouse(report_mouse_t *report);
+void send_system(uint16_t data);
+void send_consumer(uint16_t data);
+
+/* host struct */
+host_driver_t chibios_driver = {
+ keyboard_leds,
+ send_keyboard,
+ send_mouse,
+ send_system,
+ send_consumer
+};
+
+
+/* TESTING
+ * Amber LED blinker thread, times are in milliseconds.
+ */
+/* set this variable to non-zero anywhere to blink once */
+// uint8_t blinkLed = 0;
+// static THD_WORKING_AREA(waBlinkerThread, 128);
+// static THD_FUNCTION(blinkerThread, arg) {
+// (void)arg;
+// chRegSetThreadName("blinkOrange");
+// while(true) {
+// if(blinkLed) {
+// blinkLed = 0;
+// palSetPad(TEENSY_PIN13_IOPORT, TEENSY_PIN13);
+// chThdSleepMilliseconds(100);
+// palClearPad(TEENSY_PIN13_IOPORT, TEENSY_PIN13);
+// }
+// chThdSleepMilliseconds(100);
+// }
+// }
+
+
+
+/* Main thread
+ */
+int main(void) {
+ /* ChibiOS/RT init */
+ halInit();
+ chSysInit();
+
+ // TESTING
+ // chThdCreateStatic(waBlinkerThread, sizeof(waBlinkerThread), NORMALPRIO, blinkerThread, NULL);
+
+ /* Init USB */
+ init_usb_driver(&USB_DRIVER);
+
+ /* init printf */
+ init_printf(NULL,sendchar_pf);
+
+#ifdef SERIAL_LINK_ENABLE
+ init_serial_link();
+#endif
+
+#ifdef VISUALIZER_ENABLE
+ visualizer_init();
+#endif
+
+
+ host_driver_t* driver = NULL;
+
+ /* Wait until the USB or serial link is active */
+ while (true) {
+ if(USB_DRIVER.state == USB_ACTIVE) {
+ driver = &chibios_driver;
+ break;
+ }
+#ifdef SERIAL_LINK_ENABLE
+ if(is_serial_link_connected()) {
+ driver = get_serial_link_driver();
+ break;
+ }
+ serial_link_update();
+#endif
+ chThdSleepMilliseconds(50);
+ }
+
+ /* Do need to wait here!
+ * Otherwise the next print might start a transfer on console EP
+ * before the USB is completely ready, which sometimes causes
+ * HardFaults.
+ */
+ chThdSleepMilliseconds(50);
+
+ print("USB configured.\n");
+
+ /* init TMK modules */
+ keyboard_init();
+ host_set_driver(driver);
+
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_init();
+#endif
+
+ print("Keyboard start.\n");
+
+ /* Main loop */
+ while(true) {
+
+ if(USB_DRIVER.state == USB_SUSPENDED) {
+ print("[s]");
+#ifdef VISUALIZER_ENABLE
+ visualizer_suspend();
+#endif
+ while(USB_DRIVER.state == USB_SUSPENDED) {
+ /* Do this in the suspended state */
+#ifdef SERIAL_LINK_ENABLE
+ serial_link_update();
+#endif
+ suspend_power_down(); // on AVR this deep sleeps for 15ms
+ /* Remote wakeup */
+ if((USB_DRIVER.status & 2) && suspend_wakeup_condition()) {
+ send_remote_wakeup(&USB_DRIVER);
+ }
+ }
+ /* Woken up */
+ // variables has been already cleared by the wakeup hook
+ send_keyboard_report();
+#ifdef MOUSEKEY_ENABLE
+ mousekey_send();
+#endif /* MOUSEKEY_ENABLE */
+
+#ifdef VISUALIZER_ENABLE
+ visualizer_resume();
+#endif
+ }
+
+ keyboard_task();
+ }
+}
diff --git a/tmk_core/protocol/chibios/usb_main.c b/tmk_core/protocol/chibios/usb_main.c
new file mode 100644
index 000000000..d0c72c46c
--- /dev/null
+++ b/tmk_core/protocol/chibios/usb_main.c
@@ -0,0 +1,1375 @@
+/*
+ * (c) 2015 flabberast <s3+flabbergast@sdfeu.org>
+ *
+ * Based on the following work:
+ * - Guillaume Duc's raw hid example (MIT License)
+ * https://github.com/guiduc/usb-hid-chibios-example
+ * - PJRC Teensy examples (MIT License)
+ * https://www.pjrc.com/teensy/usb_keyboard.html
+ * - hasu's TMK keyboard code (GPL v2 and some code Modified BSD)
+ * https://github.com/tmk/tmk_keyboard/
+ * - ChibiOS demo code (Apache 2.0 License)
+ * http://www.chibios.org
+ *
+ * Since some GPL'd code is used, this work is licensed under
+ * GPL v2 or later.
+ */
+
+#include "ch.h"
+#include "hal.h"
+
+#include "usb_main.h"
+
+#include "host.h"
+#include "debug.h"
+#include "suspend.h"
+#ifdef SLEEP_LED_ENABLE
+#include "sleep_led.h"
+#include "led.h"
+#endif
+
+#ifdef NKRO_ENABLE
+ #include "keycode_config.h"
+
+ extern keymap_config_t keymap_config;
+#endif
+
+/* ---------------------------------------------------------
+ * Global interface variables and declarations
+ * ---------------------------------------------------------
+ */
+
+uint8_t keyboard_idle __attribute__((aligned(2))) = 0;
+uint8_t keyboard_protocol __attribute__((aligned(2))) = 1;
+uint16_t keyboard_led_stats __attribute__((aligned(2))) = 0;
+volatile uint16_t keyboard_idle_count = 0;
+static virtual_timer_t keyboard_idle_timer;
+static void keyboard_idle_timer_cb(void *arg);
+
+report_keyboard_t keyboard_report_sent = {{0}};
+#ifdef MOUSE_ENABLE
+report_mouse_t mouse_report_blank = {0};
+#endif /* MOUSE_ENABLE */
+#ifdef EXTRAKEY_ENABLE
+uint8_t extra_report_blank[3] = {0};
+#endif /* EXTRAKEY_ENABLE */
+
+#ifdef CONSOLE_ENABLE
+/* The emission buffers queue */
+output_buffers_queue_t console_buf_queue;
+static uint8_t console_queue_buffer[BQ_BUFFER_SIZE(CONSOLE_QUEUE_CAPACITY, CONSOLE_EPSIZE)];
+
+static virtual_timer_t console_flush_timer;
+void console_queue_onotify(io_buffers_queue_t *bqp);
+static void console_flush_cb(void *arg);
+#endif /* CONSOLE_ENABLE */
+
+/* ---------------------------------------------------------
+ * Descriptors and USB driver objects
+ * ---------------------------------------------------------
+ */
+
+/* HID specific constants */
+#define USB_DESCRIPTOR_HID 0x21
+#define USB_DESCRIPTOR_HID_REPORT 0x22
+#define HID_GET_REPORT 0x01
+#define HID_GET_IDLE 0x02
+#define HID_GET_PROTOCOL 0x03
+#define HID_SET_REPORT 0x09
+#define HID_SET_IDLE 0x0A
+#define HID_SET_PROTOCOL 0x0B
+
+/* USB Device Descriptor */
+static const uint8_t usb_device_descriptor_data[] = {
+ USB_DESC_DEVICE(0x0200, // bcdUSB (1.1)
+ 0, // bDeviceClass (defined in later in interface)
+ 0, // bDeviceSubClass
+ 0, // bDeviceProtocol
+ 64, // bMaxPacketSize (64 bytes) (the driver didn't work with 32)
+ VENDOR_ID, // idVendor
+ PRODUCT_ID, // idProduct
+ DEVICE_VER, // bcdDevice
+ 1, // iManufacturer
+ 2, // iProduct
+ 3, // iSerialNumber
+ 1) // bNumConfigurations
+};
+
+/* Device Descriptor wrapper */
+static const USBDescriptor usb_device_descriptor = {
+ sizeof usb_device_descriptor_data,
+ usb_device_descriptor_data
+};
+
+/*
+ * HID Report Descriptor
+ *
+ * See "Device Class Definition for Human Interface Devices (HID)"
+ * (http://www.usb.org/developers/hidpage/HID1_11.pdf) for the
+ * detailed descrition of all the fields
+ */
+
+/* Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60 */
+static const uint8_t keyboard_hid_report_desc_data[] = {
+ 0x05, 0x01, // Usage Page (Generic Desktop),
+ 0x09, 0x06, // Usage (Keyboard),
+ 0xA1, 0x01, // Collection (Application),
+ 0x75, 0x01, // Report Size (1),
+ 0x95, 0x08, // Report Count (8),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0xE0, // Usage Minimum (224),
+ 0x29, 0xE7, // Usage Maximum (231),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x01, // Logical Maximum (1),
+ 0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte
+ 0x95, 0x01, // Report Count (1),
+ 0x75, 0x08, // Report Size (8),
+ 0x81, 0x03, // Input (Constant), ;Reserved byte
+ 0x95, 0x05, // Report Count (5),
+ 0x75, 0x01, // Report Size (1),
+ 0x05, 0x08, // Usage Page (LEDs),
+ 0x19, 0x01, // Usage Minimum (1),
+ 0x29, 0x05, // Usage Maximum (5),
+ 0x91, 0x02, // Output (Data, Variable, Absolute), ;LED report
+ 0x95, 0x01, // Report Count (1),
+ 0x75, 0x03, // Report Size (3),
+ 0x91, 0x03, // Output (Constant), ;LED report padding
+ 0x95, KBD_REPORT_KEYS, // Report Count (),
+ 0x75, 0x08, // Report Size (8),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0xFF, // Logical Maximum(255),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0x00, // Usage Minimum (0),
+ 0x29, 0xFF, // Usage Maximum (255),
+ 0x81, 0x00, // Input (Data, Array),
+ 0xc0 // End Collection
+};
+/* wrapper */
+static const USBDescriptor keyboard_hid_report_descriptor = {
+ sizeof keyboard_hid_report_desc_data,
+ keyboard_hid_report_desc_data
+};
+
+#ifdef NKRO_ENABLE
+static const uint8_t nkro_hid_report_desc_data[] = {
+ 0x05, 0x01, // Usage Page (Generic Desktop),
+ 0x09, 0x06, // Usage (Keyboard),
+ 0xA1, 0x01, // Collection (Application),
+ // bitmap of modifiers
+ 0x75, 0x01, // Report Size (1),
+ 0x95, 0x08, // Report Count (8),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0xE0, // Usage Minimum (224),
+ 0x29, 0xE7, // Usage Maximum (231),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x01, // Logical Maximum (1),
+ 0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte
+ // LED output report
+ 0x95, 0x05, // Report Count (5),
+ 0x75, 0x01, // Report Size (1),
+ 0x05, 0x08, // Usage Page (LEDs),
+ 0x19, 0x01, // Usage Minimum (1),
+ 0x29, 0x05, // Usage Maximum (5),
+ 0x91, 0x02, // Output (Data, Variable, Absolute),
+ 0x95, 0x01, // Report Count (1),
+ 0x75, 0x03, // Report Size (3),
+ 0x91, 0x03, // Output (Constant),
+ // bitmap of keys
+ 0x95, NKRO_REPORT_KEYS * 8, // Report Count (),
+ 0x75, 0x01, // Report Size (1),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x01, // Logical Maximum(1),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0x00, // Usage Minimum (0),
+ 0x29, NKRO_REPORT_KEYS * 8 - 1, // Usage Maximum (),
+ 0x81, 0x02, // Input (Data, Variable, Absolute),
+ 0xc0 // End Collection
+};
+/* wrapper */
+static const USBDescriptor nkro_hid_report_descriptor = {
+ sizeof nkro_hid_report_desc_data,
+ nkro_hid_report_desc_data
+};
+#endif /* NKRO_ENABLE */
+
+#ifdef MOUSE_ENABLE
+/* Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension
+ * http://www.microchip.com/forums/tm.aspx?high=&m=391435&mpage=1#391521
+ * http://www.keil.com/forum/15671/
+ * http://www.microsoft.com/whdc/device/input/wheel.mspx */
+static const uint8_t mouse_hid_report_desc_data[] = {
+ /* mouse */
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x02, // USAGE (Mouse)
+ 0xa1, 0x01, // COLLECTION (Application)
+ //0x85, REPORT_ID_MOUSE, // REPORT_ID (1)
+ 0x09, 0x01, // USAGE (Pointer)
+ 0xa1, 0x00, // COLLECTION (Physical)
+ // ---------------------------- Buttons
+ 0x05, 0x09, // USAGE_PAGE (Button)
+ 0x19, 0x01, // USAGE_MINIMUM (Button 1)
+ 0x29, 0x05, // USAGE_MAXIMUM (Button 5)
+ 0x15, 0x00, // LOGICAL_MINIMUM (0)
+ 0x25, 0x01, // LOGICAL_MAXIMUM (1)
+ 0x75, 0x01, // REPORT_SIZE (1)
+ 0x95, 0x05, // REPORT_COUNT (5)
+ 0x81, 0x02, // INPUT (Data,Var,Abs)
+ 0x75, 0x03, // REPORT_SIZE (3)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x03, // INPUT (Cnst,Var,Abs)
+ // ---------------------------- X,Y position
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x30, // USAGE (X)
+ 0x09, 0x31, // USAGE (Y)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x02, // REPORT_COUNT (2)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ // ---------------------------- Vertical wheel
+ 0x09, 0x38, // USAGE (Wheel)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x35, 0x00, // PHYSICAL_MINIMUM (0) - reset physical
+ 0x45, 0x00, // PHYSICAL_MAXIMUM (0)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ // ---------------------------- Horizontal wheel
+ 0x05, 0x0c, // USAGE_PAGE (Consumer Devices)
+ 0x0a, 0x38, 0x02, // USAGE (AC Pan)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ 0xc0, // END_COLLECTION
+ 0xc0, // END_COLLECTION
+};
+/* wrapper */
+static const USBDescriptor mouse_hid_report_descriptor = {
+ sizeof mouse_hid_report_desc_data,
+ mouse_hid_report_desc_data
+};
+#endif /* MOUSE_ENABLE */
+
+#ifdef CONSOLE_ENABLE
+static const uint8_t console_hid_report_desc_data[] = {
+ 0x06, 0x31, 0xFF, // Usage Page 0xFF31 (vendor defined)
+ 0x09, 0x74, // Usage 0x74
+ 0xA1, 0x53, // Collection 0x53
+ 0x75, 0x08, // report size = 8 bits
+ 0x15, 0x00, // logical minimum = 0
+ 0x26, 0xFF, 0x00, // logical maximum = 255
+ 0x95, CONSOLE_EPSIZE, // report count
+ 0x09, 0x75, // usage
+ 0x81, 0x02, // Input (array)
+ 0xC0 // end collection
+};
+/* wrapper */
+static const USBDescriptor console_hid_report_descriptor = {
+ sizeof console_hid_report_desc_data,
+ console_hid_report_desc_data
+};
+#endif /* CONSOLE_ENABLE */
+
+#ifdef EXTRAKEY_ENABLE
+/* audio controls & system controls
+ * http://www.microsoft.com/whdc/archive/w2kbd.mspx */
+static const uint8_t extra_hid_report_desc_data[] = {
+ /* system control */
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x80, // USAGE (System Control)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x85, REPORT_ID_SYSTEM, // REPORT_ID (2)
+ 0x15, 0x01, // LOGICAL_MINIMUM (0x1)
+ 0x25, 0xb7, // LOGICAL_MAXIMUM (0xb7)
+ 0x19, 0x01, // USAGE_MINIMUM (0x1)
+ 0x29, 0xb7, // USAGE_MAXIMUM (0xb7)
+ 0x75, 0x10, // REPORT_SIZE (16)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x00, // INPUT (Data,Array,Abs)
+ 0xc0, // END_COLLECTION
+ /* consumer */
+ 0x05, 0x0c, // USAGE_PAGE (Consumer Devices)
+ 0x09, 0x01, // USAGE (Consumer Control)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x85, REPORT_ID_CONSUMER, // REPORT_ID (3)
+ 0x15, 0x01, // LOGICAL_MINIMUM (0x1)
+ 0x26, 0x9c, 0x02, // LOGICAL_MAXIMUM (0x29c)
+ 0x19, 0x01, // USAGE_MINIMUM (0x1)
+ 0x2a, 0x9c, 0x02, // USAGE_MAXIMUM (0x29c)
+ 0x75, 0x10, // REPORT_SIZE (16)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x00, // INPUT (Data,Array,Abs)
+ 0xc0, // END_COLLECTION
+};
+/* wrapper */
+static const USBDescriptor extra_hid_report_descriptor = {
+ sizeof extra_hid_report_desc_data,
+ extra_hid_report_desc_data
+};
+#endif /* EXTRAKEY_ENABLE */
+
+
+/*
+ * Configuration Descriptor tree for a HID device
+ *
+ * The HID Specifications version 1.11 require the following order:
+ * - Configuration Descriptor
+ * - Interface Descriptor
+ * - HID Descriptor
+ * - Endpoints Descriptors
+ */
+#define KBD_HID_DESC_NUM 0
+#define KBD_HID_DESC_OFFSET (9 + (9 + 9 + 7) * KBD_HID_DESC_NUM + 9)
+
+#ifdef MOUSE_ENABLE
+# define MOUSE_HID_DESC_NUM (KBD_HID_DESC_NUM + 1)
+# define MOUSE_HID_DESC_OFFSET (9 + (9 + 9 + 7) * MOUSE_HID_DESC_NUM + 9)
+#else /* MOUSE_ENABLE */
+# define MOUSE_HID_DESC_NUM (KBD_HID_DESC_NUM + 0)
+#endif /* MOUSE_ENABLE */
+
+#ifdef CONSOLE_ENABLE
+#define CONSOLE_HID_DESC_NUM (MOUSE_HID_DESC_NUM + 1)
+#define CONSOLE_HID_DESC_OFFSET (9 + (9 + 9 + 7) * CONSOLE_HID_DESC_NUM + 9)
+#else /* CONSOLE_ENABLE */
+# define CONSOLE_HID_DESC_NUM (MOUSE_HID_DESC_NUM + 0)
+#endif /* CONSOLE_ENABLE */
+
+#ifdef EXTRAKEY_ENABLE
+# define EXTRA_HID_DESC_NUM (CONSOLE_HID_DESC_NUM + 1)
+# define EXTRA_HID_DESC_OFFSET (9 + (9 + 9 + 7) * EXTRA_HID_DESC_NUM + 9)
+#else /* EXTRAKEY_ENABLE */
+# define EXTRA_HID_DESC_NUM (CONSOLE_HID_DESC_NUM + 0)
+#endif /* EXTRAKEY_ENABLE */
+
+#ifdef NKRO_ENABLE
+# define NKRO_HID_DESC_NUM (EXTRA_HID_DESC_NUM + 1)
+# define NKRO_HID_DESC_OFFSET (9 + (9 + 9 + 7) * EXTRA_HID_DESC_NUM + 9)
+#else /* NKRO_ENABLE */
+# define NKRO_HID_DESC_NUM (EXTRA_HID_DESC_NUM + 0)
+#endif /* NKRO_ENABLE */
+
+#define NUM_INTERFACES (NKRO_HID_DESC_NUM + 1)
+#define CONFIG1_DESC_SIZE (9 + (9 + 9 + 7) * NUM_INTERFACES)
+
+static const uint8_t hid_configuration_descriptor_data[] = {
+ /* Configuration Descriptor (9 bytes) USB spec 9.6.3, page 264-266, Table 9-10 */
+ USB_DESC_CONFIGURATION(CONFIG1_DESC_SIZE, // wTotalLength
+ NUM_INTERFACES, // bNumInterfaces
+ 1, // bConfigurationValue
+ 0, // iConfiguration
+ 0xA0, // bmAttributes (RESERVED|REMOTEWAKEUP)
+ 50), // bMaxPower (50mA)
+
+ /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
+ USB_DESC_INTERFACE(KBD_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass: HID
+ 0x01, // bInterfaceSubClass: Boot
+ 0x01, // bInterfaceProtocol: Keyboard
+ 0), // iInterface
+
+ /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
+ USB_DESC_BYTE(9), // bLength
+ USB_DESC_BYTE(0x21), // bDescriptorType (HID class)
+ USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11
+ USB_DESC_BYTE(0), // bCountryCode
+ USB_DESC_BYTE(1), // bNumDescriptors
+ USB_DESC_BYTE(0x22), // bDescriptorType (report desc)
+ USB_DESC_WORD(sizeof(keyboard_hid_report_desc_data)), // wDescriptorLength
+
+ /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
+ USB_DESC_ENDPOINT(KBD_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (Interrupt)
+ KBD_EPSIZE,// wMaxPacketSize
+ 10), // bInterval
+
+ #ifdef MOUSE_ENABLE
+ /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
+ USB_DESC_INTERFACE(MOUSE_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ // ThinkPad T23 BIOS doesn't work with boot mouse.
+ 0x00, // bInterfaceSubClass (0x01 = Boot)
+ 0x00, // bInterfaceProtocol (0x02 = Mouse)
+ /*
+ 0x01, // bInterfaceSubClass (0x01 = Boot)
+ 0x02, // bInterfaceProtocol (0x02 = Mouse)
+ */
+ 0), // iInterface
+
+ /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
+ USB_DESC_BYTE(9), // bLength
+ USB_DESC_BYTE(0x21), // bDescriptorType (HID class)
+ USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11
+ USB_DESC_BYTE(0), // bCountryCode
+ USB_DESC_BYTE(1), // bNumDescriptors
+ USB_DESC_BYTE(0x22), // bDescriptorType (report desc)
+ USB_DESC_WORD(sizeof(mouse_hid_report_desc_data)), // wDescriptorLength
+
+ /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
+ USB_DESC_ENDPOINT(MOUSE_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (Interrupt)
+ MOUSE_EPSIZE, // wMaxPacketSize
+ 1), // bInterval
+ #endif /* MOUSE_ENABLE */
+
+ #ifdef CONSOLE_ENABLE
+ /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
+ USB_DESC_INTERFACE(CONSOLE_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass: HID
+ 0x00, // bInterfaceSubClass: None
+ 0x00, // bInterfaceProtocol: None
+ 0), // iInterface
+
+ /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
+ USB_DESC_BYTE(9), // bLength
+ USB_DESC_BYTE(0x21), // bDescriptorType (HID class)
+ USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11
+ USB_DESC_BYTE(0), // bCountryCode
+ USB_DESC_BYTE(1), // bNumDescriptors
+ USB_DESC_BYTE(0x22), // bDescriptorType (report desc)
+ USB_DESC_WORD(sizeof(console_hid_report_desc_data)), // wDescriptorLength
+
+ /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
+ USB_DESC_ENDPOINT(CONSOLE_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (Interrupt)
+ CONSOLE_EPSIZE, // wMaxPacketSize
+ 1), // bInterval
+ #endif /* CONSOLE_ENABLE */
+
+ #ifdef EXTRAKEY_ENABLE
+ /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
+ USB_DESC_INTERFACE(EXTRA_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass: HID
+ 0x00, // bInterfaceSubClass: None
+ 0x00, // bInterfaceProtocol: None
+ 0), // iInterface
+
+ /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
+ USB_DESC_BYTE(9), // bLength
+ USB_DESC_BYTE(0x21), // bDescriptorType (HID class)
+ USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11
+ USB_DESC_BYTE(0), // bCountryCode
+ USB_DESC_BYTE(1), // bNumDescriptors
+ USB_DESC_BYTE(0x22), // bDescriptorType (report desc)
+ USB_DESC_WORD(sizeof(extra_hid_report_desc_data)), // wDescriptorLength
+
+ /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
+ USB_DESC_ENDPOINT(EXTRA_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (Interrupt)
+ EXTRA_EPSIZE, // wMaxPacketSize
+ 10), // bInterval
+ #endif /* EXTRAKEY_ENABLE */
+
+ #ifdef NKRO_ENABLE
+ /* Interface Descriptor (9 bytes) USB spec 9.6.5, page 267-269, Table 9-12 */
+ USB_DESC_INTERFACE(NKRO_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass: HID
+ 0x00, // bInterfaceSubClass: None
+ 0x00, // bInterfaceProtocol: None
+ 0), // iInterface
+
+ /* HID descriptor (9 bytes) HID 1.11 spec, section 6.2.1 */
+ USB_DESC_BYTE(9), // bLength
+ USB_DESC_BYTE(0x21), // bDescriptorType (HID class)
+ USB_DESC_BCD(0x0111), // bcdHID: HID version 1.11
+ USB_DESC_BYTE(0), // bCountryCode
+ USB_DESC_BYTE(1), // bNumDescriptors
+ USB_DESC_BYTE(0x22), // bDescriptorType (report desc)
+ USB_DESC_WORD(sizeof(nkro_hid_report_desc_data)), // wDescriptorLength
+
+ /* Endpoint Descriptor (7 bytes) USB spec 9.6.6, page 269-271, Table 9-13 */
+ USB_DESC_ENDPOINT(NKRO_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (Interrupt)
+ NKRO_EPSIZE, // wMaxPacketSize
+ 1), // bInterval
+ #endif /* NKRO_ENABLE */
+};
+
+/* Configuration Descriptor wrapper */
+static const USBDescriptor hid_configuration_descriptor = {
+ sizeof hid_configuration_descriptor_data,
+ hid_configuration_descriptor_data
+};
+
+/* wrappers */
+#define HID_DESCRIPTOR_SIZE 9
+static const USBDescriptor keyboard_hid_descriptor = {
+ HID_DESCRIPTOR_SIZE,
+ &hid_configuration_descriptor_data[KBD_HID_DESC_OFFSET]
+};
+#ifdef MOUSE_ENABLE
+static const USBDescriptor mouse_hid_descriptor = {
+ HID_DESCRIPTOR_SIZE,
+ &hid_configuration_descriptor_data[MOUSE_HID_DESC_OFFSET]
+};
+#endif /* MOUSE_ENABLE */
+#ifdef CONSOLE_ENABLE
+static const USBDescriptor console_hid_descriptor = {
+ HID_DESCRIPTOR_SIZE,
+ &hid_configuration_descriptor_data[CONSOLE_HID_DESC_OFFSET]
+};
+#endif /* CONSOLE_ENABLE */
+#ifdef EXTRAKEY_ENABLE
+static const USBDescriptor extra_hid_descriptor = {
+ HID_DESCRIPTOR_SIZE,
+ &hid_configuration_descriptor_data[EXTRA_HID_DESC_OFFSET]
+};
+#endif /* EXTRAKEY_ENABLE */
+#ifdef NKRO_ENABLE
+static const USBDescriptor nkro_hid_descriptor = {
+ HID_DESCRIPTOR_SIZE,
+ &hid_configuration_descriptor_data[NKRO_HID_DESC_OFFSET]
+};
+#endif /* NKRO_ENABLE */
+
+
+/* U.S. English language identifier */
+static const uint8_t usb_string_langid[] = {
+ USB_DESC_BYTE(4), // bLength
+ USB_DESC_BYTE(USB_DESCRIPTOR_STRING), // bDescriptorType
+ USB_DESC_WORD(0x0409) // wLANGID (U.S. English)
+};
+
+/* ugly ugly hack */
+#define PP_NARG(...) \
+ PP_NARG_(__VA_ARGS__,PP_RSEQ_N())
+#define PP_NARG_(...) \
+ PP_ARG_N(__VA_ARGS__)
+#define PP_ARG_N( \
+ _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \
+ _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \
+ _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \
+ _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \
+ _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \
+ _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \
+ _61,_62,_63,N,...) N
+#define PP_RSEQ_N() \
+ 63,62,61,60, \
+ 59,58,57,56,55,54,53,52,51,50, \
+ 49,48,47,46,45,44,43,42,41,40, \
+ 39,38,37,36,35,34,33,32,31,30, \
+ 29,28,27,26,25,24,23,22,21,20, \
+ 19,18,17,16,15,14,13,12,11,10, \
+ 9,8,7,6,5,4,3,2,1,0
+
+/* Vendor string = manufacturer */
+static const uint8_t usb_string_vendor[] = {
+ USB_DESC_BYTE(PP_NARG(USBSTR_MANUFACTURER)+2), // bLength
+ USB_DESC_BYTE(USB_DESCRIPTOR_STRING), // bDescriptorType
+ USBSTR_MANUFACTURER
+};
+
+/* Device Description string = product */
+static const uint8_t usb_string_description[] = {
+ USB_DESC_BYTE(PP_NARG(USBSTR_PRODUCT)+2), // bLength
+ USB_DESC_BYTE(USB_DESCRIPTOR_STRING), // bDescriptorType
+ USBSTR_PRODUCT
+};
+
+/* Serial Number string (will be filled by the function init_usb_serial_string) */
+static uint8_t usb_string_serial[] = {
+ USB_DESC_BYTE(22), // bLength
+ USB_DESC_BYTE(USB_DESCRIPTOR_STRING), // bDescriptorType
+ '0', 0, 'x', 0, 'D', 0, 'E', 0, 'A', 0, 'D', 0, 'B', 0, 'E', 0, 'E', 0, 'F', 0
+};
+
+/* Strings wrappers array */
+static const USBDescriptor usb_strings[] = {
+ { sizeof usb_string_langid, usb_string_langid }
+ ,
+ { sizeof usb_string_vendor, usb_string_vendor }
+ ,
+ { sizeof usb_string_description, usb_string_description }
+ ,
+ { sizeof usb_string_serial, usb_string_serial }
+};
+
+/*
+ * Handles the GET_DESCRIPTOR callback
+ *
+ * Returns the proper descriptor
+ */
+static const USBDescriptor *usb_get_descriptor_cb(USBDriver *usbp, uint8_t dtype, uint8_t dindex, uint16_t lang) {
+ (void)usbp;
+ (void)lang;
+ switch(dtype) {
+ /* Generic descriptors */
+ case USB_DESCRIPTOR_DEVICE: /* Device Descriptor */
+ return &usb_device_descriptor;
+
+ case USB_DESCRIPTOR_CONFIGURATION: /* Configuration Descriptor */
+ return &hid_configuration_descriptor;
+
+ case USB_DESCRIPTOR_STRING: /* Strings */
+ if(dindex < 4)
+ return &usb_strings[dindex];
+ break;
+
+ /* HID specific descriptors */
+ case USB_DESCRIPTOR_HID: /* HID Descriptors */
+ switch(lang) { /* yea, poor label, it's actually wIndex from the setup packet */
+ case KBD_INTERFACE:
+ return &keyboard_hid_descriptor;
+
+#ifdef MOUSE_ENABLE
+ case MOUSE_INTERFACE:
+ return &mouse_hid_descriptor;
+#endif /* MOUSE_ENABLE */
+#ifdef CONSOLE_ENABLE
+ case CONSOLE_INTERFACE:
+ return &console_hid_descriptor;
+#endif /* CONSOLE_ENABLE */
+#ifdef EXTRAKEY_ENABLE
+ case EXTRA_INTERFACE:
+ return &extra_hid_descriptor;
+#endif /* EXTRAKEY_ENABLE */
+#ifdef NKRO_ENABLE
+ case NKRO_INTERFACE:
+ return &nkro_hid_descriptor;
+#endif /* NKRO_ENABLE */
+ }
+
+ case USB_DESCRIPTOR_HID_REPORT: /* HID Report Descriptor */
+ switch(lang) {
+ case KBD_INTERFACE:
+ return &keyboard_hid_report_descriptor;
+
+#ifdef MOUSE_ENABLE
+ case MOUSE_INTERFACE:
+ return &mouse_hid_report_descriptor;
+#endif /* MOUSE_ENABLE */
+#ifdef CONSOLE_ENABLE
+ case CONSOLE_INTERFACE:
+ return &console_hid_report_descriptor;
+#endif /* CONSOLE_ENABLE */
+#ifdef EXTRAKEY_ENABLE
+ case EXTRA_INTERFACE:
+ return &extra_hid_report_descriptor;
+#endif /* EXTRAKEY_ENABLE */
+#ifdef NKRO_ENABLE
+ case NKRO_INTERFACE:
+ return &nkro_hid_report_descriptor;
+#endif /* NKRO_ENABLE */
+ }
+ }
+ return NULL;
+}
+
+/* keyboard endpoint state structure */
+static USBInEndpointState kbd_ep_state;
+/* keyboard endpoint initialization structure (IN) */
+static const USBEndpointConfig kbd_ep_config = {
+ USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
+ NULL, /* SETUP packet notification callback */
+ kbd_in_cb, /* IN notification callback */
+ NULL, /* OUT notification callback */
+ KBD_EPSIZE, /* IN maximum packet size */
+ 0, /* OUT maximum packet size */
+ &kbd_ep_state, /* IN Endpoint state */
+ NULL, /* OUT endpoint state */
+ 2, /* IN multiplier */
+ NULL /* SETUP buffer (not a SETUP endpoint) */
+};
+
+#ifdef MOUSE_ENABLE
+/* mouse endpoint state structure */
+static USBInEndpointState mouse_ep_state;
+
+/* mouse endpoint initialization structure (IN) */
+static const USBEndpointConfig mouse_ep_config = {
+ USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
+ NULL, /* SETUP packet notification callback */
+ mouse_in_cb, /* IN notification callback */
+ NULL, /* OUT notification callback */
+ MOUSE_EPSIZE, /* IN maximum packet size */
+ 0, /* OUT maximum packet size */
+ &mouse_ep_state, /* IN Endpoint state */
+ NULL, /* OUT endpoint state */
+ 2, /* IN multiplier */
+ NULL /* SETUP buffer (not a SETUP endpoint) */
+};
+#endif /* MOUSE_ENABLE */
+
+#ifdef CONSOLE_ENABLE
+/* console endpoint state structure */
+static USBInEndpointState console_ep_state;
+
+/* console endpoint initialization structure (IN) */
+static const USBEndpointConfig console_ep_config = {
+ USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
+ NULL, /* SETUP packet notification callback */
+ console_in_cb, /* IN notification callback */
+ NULL, /* OUT notification callback */
+ CONSOLE_EPSIZE, /* IN maximum packet size */
+ 0, /* OUT maximum packet size */
+ &console_ep_state, /* IN Endpoint state */
+ NULL, /* OUT endpoint state */
+ 2, /* IN multiplier */
+ NULL /* SETUP buffer (not a SETUP endpoint) */
+};
+#endif /* CONSOLE_ENABLE */
+
+#ifdef EXTRAKEY_ENABLE
+/* extrakey endpoint state structure */
+static USBInEndpointState extra_ep_state;
+
+/* extrakey endpoint initialization structure (IN) */
+static const USBEndpointConfig extra_ep_config = {
+ USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
+ NULL, /* SETUP packet notification callback */
+ extra_in_cb, /* IN notification callback */
+ NULL, /* OUT notification callback */
+ EXTRA_EPSIZE, /* IN maximum packet size */
+ 0, /* OUT maximum packet size */
+ &extra_ep_state, /* IN Endpoint state */
+ NULL, /* OUT endpoint state */
+ 2, /* IN multiplier */
+ NULL /* SETUP buffer (not a SETUP endpoint) */
+};
+#endif /* EXTRAKEY_ENABLE */
+
+#ifdef NKRO_ENABLE
+/* nkro endpoint state structure */
+static USBInEndpointState nkro_ep_state;
+
+/* nkro endpoint initialization structure (IN) */
+static const USBEndpointConfig nkro_ep_config = {
+ USB_EP_MODE_TYPE_INTR, /* Interrupt EP */
+ NULL, /* SETUP packet notification callback */
+ nkro_in_cb, /* IN notification callback */
+ NULL, /* OUT notification callback */
+ NKRO_EPSIZE, /* IN maximum packet size */
+ 0, /* OUT maximum packet size */
+ &nkro_ep_state, /* IN Endpoint state */
+ NULL, /* OUT endpoint state */
+ 2, /* IN multiplier */
+ NULL /* SETUP buffer (not a SETUP endpoint) */
+};
+#endif /* NKRO_ENABLE */
+
+/* ---------------------------------------------------------
+ * USB driver functions
+ * ---------------------------------------------------------
+ */
+
+/* Handles the USB driver global events
+ * TODO: maybe disable some things when connection is lost? */
+static void usb_event_cb(USBDriver *usbp, usbevent_t event) {
+ switch(event) {
+ case USB_EVENT_RESET:
+ //TODO: from ISR! print("[R]");
+ return;
+
+ case USB_EVENT_ADDRESS:
+ return;
+
+ case USB_EVENT_CONFIGURED:
+ osalSysLockFromISR();
+ /* Enable the endpoints specified into the configuration. */
+ usbInitEndpointI(usbp, KBD_ENDPOINT, &kbd_ep_config);
+#ifdef MOUSE_ENABLE
+ usbInitEndpointI(usbp, MOUSE_ENDPOINT, &mouse_ep_config);
+#endif /* MOUSE_ENABLE */
+#ifdef CONSOLE_ENABLE
+ usbInitEndpointI(usbp, CONSOLE_ENDPOINT, &console_ep_config);
+ /* don't need to start the flush timer, it starts from console_in_cb automatically */
+#endif /* CONSOLE_ENABLE */
+#ifdef EXTRAKEY_ENABLE
+ usbInitEndpointI(usbp, EXTRA_ENDPOINT, &extra_ep_config);
+#endif /* EXTRAKEY_ENABLE */
+#ifdef NKRO_ENABLE
+ usbInitEndpointI(usbp, NKRO_ENDPOINT, &nkro_ep_config);
+#endif /* NKRO_ENABLE */
+ osalSysUnlockFromISR();
+ return;
+
+ case USB_EVENT_SUSPEND:
+ //TODO: from ISR! print("[S]");
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_enable();
+#endif /* SLEEP_LED_ENABLE */
+ return;
+
+ case USB_EVENT_WAKEUP:
+ //TODO: from ISR! print("[W]");
+ suspend_wakeup_init();
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_disable();
+ // NOTE: converters may not accept this
+ led_set(host_keyboard_leds());
+#endif /* SLEEP_LED_ENABLE */
+ return;
+
+ case USB_EVENT_STALLED:
+ return;
+ }
+}
+
+/* Function used locally in os/hal/src/usb.c for getting descriptors
+ * need it here for HID descriptor */
+static uint16_t get_hword(uint8_t *p) {
+ uint16_t hw;
+
+ hw = (uint16_t)*p++;
+ hw |= (uint16_t)*p << 8U;
+ return hw;
+}
+
+/*
+ * Appendix G: HID Request Support Requirements
+ *
+ * The following table enumerates the requests that need to be supported by various types of HID class devices.
+ * Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
+ * ------------------------------------------------------------------------------------------
+ * Boot Mouse Required Optional Optional Optional Required Required
+ * Non-Boot Mouse Required Optional Optional Optional Optional Optional
+ * Boot Keyboard Required Optional Required Required Required Required
+ * Non-Boot Keybrd Required Optional Required Required Optional Optional
+ * Other Device Required Optional Optional Optional Optional Optional
+ */
+
+/* Callback for SETUP request on the endpoint 0 (control) */
+static bool usb_request_hook_cb(USBDriver *usbp) {
+ const USBDescriptor *dp;
+
+ /* usbp->setup fields:
+ * 0: bmRequestType (bitmask)
+ * 1: bRequest
+ * 2,3: (LSB,MSB) wValue
+ * 4,5: (LSB,MSB) wIndex
+ * 6,7: (LSB,MSB) wLength (number of bytes to transfer if there is a data phase) */
+
+ /* Handle HID class specific requests */
+ if(((usbp->setup[0] & USB_RTYPE_TYPE_MASK) == USB_RTYPE_TYPE_CLASS) &&
+ ((usbp->setup[0] & USB_RTYPE_RECIPIENT_MASK) == USB_RTYPE_RECIPIENT_INTERFACE)) {
+ switch(usbp->setup[0] & USB_RTYPE_DIR_MASK) {
+ case USB_RTYPE_DIR_DEV2HOST:
+ switch(usbp->setup[1]) { /* bRequest */
+ case HID_GET_REPORT:
+ switch(usbp->setup[4]) { /* LSB(wIndex) (check MSB==0?) */
+ case KBD_INTERFACE:
+#ifdef NKRO_ENABLE
+ case NKRO_INTERFACE:
+#endif /* NKRO_ENABLE */
+ usbSetupTransfer(usbp, (uint8_t *)&keyboard_report_sent, sizeof(keyboard_report_sent), NULL);
+ return TRUE;
+ break;
+
+#ifdef MOUSE_ENABLE
+ case MOUSE_INTERFACE:
+ usbSetupTransfer(usbp, (uint8_t *)&mouse_report_blank, sizeof(mouse_report_blank), NULL);
+ return TRUE;
+ break;
+#endif /* MOUSE_ENABLE */
+
+#ifdef CONSOLE_ENABLE
+ case CONSOLE_INTERFACE:
+ usbSetupTransfer(usbp, console_queue_buffer, CONSOLE_EPSIZE, NULL);
+ return TRUE;
+ break;
+#endif /* CONSOLE_ENABLE */
+
+#ifdef EXTRAKEY_ENABLE
+ case EXTRA_INTERFACE:
+ if(usbp->setup[3] == 1) { /* MSB(wValue) [Report Type] == 1 [Input Report] */
+ switch(usbp->setup[2]) { /* LSB(wValue) [Report ID] */
+ case REPORT_ID_SYSTEM:
+ extra_report_blank[0] = REPORT_ID_SYSTEM;
+ usbSetupTransfer(usbp, (uint8_t *)extra_report_blank, sizeof(extra_report_blank), NULL);
+ return TRUE;
+ break;
+ case REPORT_ID_CONSUMER:
+ extra_report_blank[0] = REPORT_ID_CONSUMER;
+ usbSetupTransfer(usbp, (uint8_t *)extra_report_blank, sizeof(extra_report_blank), NULL);
+ return TRUE;
+ break;
+ default:
+ return FALSE;
+ }
+ } else {
+ return FALSE;
+ }
+ break;
+#endif /* EXTRAKEY_ENABLE */
+
+ default:
+ usbSetupTransfer(usbp, NULL, 0, NULL);
+ return TRUE;
+ break;
+ }
+ break;
+
+ case HID_GET_PROTOCOL:
+ if((usbp->setup[4] == KBD_INTERFACE) && (usbp->setup[5] == 0)) { /* wIndex */
+ usbSetupTransfer(usbp, &keyboard_protocol, 1, NULL);
+ return TRUE;
+ }
+ break;
+
+ case HID_GET_IDLE:
+ usbSetupTransfer(usbp, &keyboard_idle, 1, NULL);
+ return TRUE;
+ break;
+ }
+ break;
+
+ case USB_RTYPE_DIR_HOST2DEV:
+ switch(usbp->setup[1]) { /* bRequest */
+ case HID_SET_REPORT:
+ switch(usbp->setup[4]) { /* LSB(wIndex) (check MSB==0 and wLength==1?) */
+ case KBD_INTERFACE:
+#ifdef NKRO_ENABLE
+ case NKRO_INTERFACE:
+#endif /* NKRO_ENABLE */
+ /* keyboard_led_stats = <read byte from next OUT report>
+ * keyboard_led_stats needs be word (or dword), otherwise we get an exception on F0 */
+ usbSetupTransfer(usbp, (uint8_t *)&keyboard_led_stats, 1, NULL);
+ return TRUE;
+ break;
+ }
+ break;
+
+ case HID_SET_PROTOCOL:
+ if((usbp->setup[4] == KBD_INTERFACE) && (usbp->setup[5] == 0)) { /* wIndex */
+ keyboard_protocol = ((usbp->setup[2]) != 0x00); /* LSB(wValue) */
+#ifdef NKRO_ENABLE
+ keymap_config.nkro = !!keyboard_protocol;
+ if(!keymap_config.nkro && keyboard_idle) {
+#else /* NKRO_ENABLE */
+ if(keyboard_idle) {
+#endif /* NKRO_ENABLE */
+ /* arm the idle timer if boot protocol & idle */
+ osalSysLockFromISR();
+ chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
+ osalSysUnlockFromISR();
+ }
+ }
+ usbSetupTransfer(usbp, NULL, 0, NULL);
+ return TRUE;
+ break;
+
+ case HID_SET_IDLE:
+ keyboard_idle = usbp->setup[3]; /* MSB(wValue) */
+ /* arm the timer */
+#ifdef NKRO_ENABLE
+ if(!keymap_config.nkro && keyboard_idle) {
+#else /* NKRO_ENABLE */
+ if(keyboard_idle) {
+#endif /* NKRO_ENABLE */
+ osalSysLockFromISR();
+ chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
+ osalSysUnlockFromISR();
+ }
+ usbSetupTransfer(usbp, NULL, 0, NULL);
+ return TRUE;
+ break;
+ }
+ break;
+ }
+ }
+
+ /* Handle the Get_Descriptor Request for HID class (not handled by the default hook) */
+ if((usbp->setup[0] == 0x81) && (usbp->setup[1] == USB_REQ_GET_DESCRIPTOR)) {
+ dp = usbp->config->get_descriptor_cb(usbp, usbp->setup[3], usbp->setup[2], get_hword(&usbp->setup[4]));
+ if(dp == NULL)
+ return FALSE;
+ usbSetupTransfer(usbp, (uint8_t *)dp->ud_string, dp->ud_size, NULL);
+ return TRUE;
+ }
+
+ return FALSE;
+}
+
+/* Start-of-frame callback */
+static void usb_sof_cb(USBDriver *usbp) {
+ kbd_sof_cb(usbp);
+}
+
+
+/* USB driver configuration */
+static const USBConfig usbcfg = {
+ usb_event_cb, /* USB events callback */
+ usb_get_descriptor_cb, /* Device GET_DESCRIPTOR request callback */
+ usb_request_hook_cb, /* Requests hook callback */
+ usb_sof_cb /* Start Of Frame callback */
+};
+
+/*
+ * Initialize the USB driver
+ */
+void init_usb_driver(USBDriver *usbp) {
+ /*
+ * Activates the USB driver and then the USB bus pull-up on D+.
+ * Note, a delay is inserted in order to not have to disconnect the cable
+ * after a reset.
+ */
+ usbDisconnectBus(usbp);
+ chThdSleepMilliseconds(1500);
+ usbStart(usbp, &usbcfg);
+ usbConnectBus(usbp);
+
+ chVTObjectInit(&keyboard_idle_timer);
+#ifdef CONSOLE_ENABLE
+ obqObjectInit(&console_buf_queue, console_queue_buffer, CONSOLE_EPSIZE, CONSOLE_QUEUE_CAPACITY, console_queue_onotify, (void*)usbp);
+ chVTObjectInit(&console_flush_timer);
+#endif
+}
+
+/*
+ * Send remote wakeup packet
+ * Note: should not be called from ISR
+ */
+void send_remote_wakeup(USBDriver *usbp) {
+ (void)usbp;
+#if defined(K20x) || defined(KL2x)
+#if KINETIS_USB_USE_USB0
+ USB0->CTL |= USBx_CTL_RESUME;
+ chThdSleepMilliseconds(15);
+ USB0->CTL &= ~USBx_CTL_RESUME;
+#endif /* KINETIS_USB_USE_USB0 */
+#elif defined(STM32F0XX) || defined(STM32F1XX) /* K20x || KL2x */
+ STM32_USB->CNTR |= CNTR_RESUME;
+ chThdSleepMilliseconds(15);
+ STM32_USB->CNTR &= ~CNTR_RESUME;
+#else /* STM32F0XX || STM32F1XX */
+#warning Sending remote wakeup packet not implemented for your platform.
+#endif /* K20x || KL2x */
+}
+
+/* ---------------------------------------------------------
+ * Keyboard functions
+ * ---------------------------------------------------------
+ */
+
+/* keyboard IN callback hander (a kbd report has made it IN) */
+void kbd_in_cb(USBDriver *usbp, usbep_t ep) {
+ /* STUB */
+ (void)usbp;
+ (void)ep;
+}
+
+#ifdef NKRO_ENABLE
+/* nkro IN callback hander (a nkro report has made it IN) */
+void nkro_in_cb(USBDriver *usbp, usbep_t ep) {
+ /* STUB */
+ (void)usbp;
+ (void)ep;
+}
+#endif /* NKRO_ENABLE */
+
+/* start-of-frame handler
+ * TODO: i guess it would be better to re-implement using timers,
+ * so that this is not going to have to be checked every 1ms */
+void kbd_sof_cb(USBDriver *usbp) {
+ (void)usbp;
+}
+
+/* Idle requests timer code
+ * callback (called from ISR, unlocked state) */
+static void keyboard_idle_timer_cb(void *arg) {
+ USBDriver *usbp = (USBDriver *)arg;
+
+ osalSysLockFromISR();
+
+ /* check that the states of things are as they're supposed to */
+ if(usbGetDriverStateI(usbp) != USB_ACTIVE) {
+ /* do not rearm the timer, should be enabled on IDLE request */
+ osalSysUnlockFromISR();
+ return;
+ }
+
+#ifdef NKRO_ENABLE
+ if(!keymap_config.nkro && keyboard_idle) {
+#else /* NKRO_ENABLE */
+ if(keyboard_idle) {
+#endif /* NKRO_ENABLE */
+ /* TODO: are we sure we want the KBD_ENDPOINT? */
+ if(!usbGetTransmitStatusI(usbp, KBD_ENDPOINT)) {
+ usbStartTransmitI(usbp, KBD_ENDPOINT, (uint8_t *)&keyboard_report_sent, KBD_EPSIZE);
+ }
+ /* rearm the timer */
+ chVTSetI(&keyboard_idle_timer, 4*MS2ST(keyboard_idle), keyboard_idle_timer_cb, (void *)usbp);
+ }
+
+ /* do not rearm the timer if the condition above fails
+ * it should be enabled again on either IDLE or SET_PROTOCOL requests */
+ osalSysUnlockFromISR();
+}
+
+/* LED status */
+uint8_t keyboard_leds(void) {
+ return (uint8_t)(keyboard_led_stats & 0xFF);
+}
+
+/* prepare and start sending a report IN
+ * not callable from ISR or locked state */
+void send_keyboard(report_keyboard_t *report) {
+ osalSysLock();
+ if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
+ osalSysUnlock();
+ return;
+ }
+ osalSysUnlock();
+
+#ifdef NKRO_ENABLE
+ if(keymap_config.nkro) { /* NKRO protocol */
+ /* need to wait until the previous packet has made it through */
+ /* can rewrite this using the synchronous API, then would wait
+ * until *after* the packet has been transmitted. I think
+ * this is more efficient */
+ /* busy wait, should be short and not very common */
+ osalSysLock();
+ if(usbGetTransmitStatusI(&USB_DRIVER, NKRO_ENDPOINT)) {
+ /* Need to either suspend, or loop and call unlock/lock during
+ * every iteration - otherwise the system will remain locked,
+ * no interrupts served, so USB not going through as well.
+ * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
+ osalThreadSuspendS(&(&USB_DRIVER)->epc[NKRO_ENDPOINT]->in_state->thread);
+ }
+ usbStartTransmitI(&USB_DRIVER, NKRO_ENDPOINT, (uint8_t *)report, sizeof(report_keyboard_t));
+ osalSysUnlock();
+ } else
+#endif /* NKRO_ENABLE */
+ { /* boot protocol */
+ /* need to wait until the previous packet has made it through */
+ /* busy wait, should be short and not very common */
+ osalSysLock();
+ if(usbGetTransmitStatusI(&USB_DRIVER, KBD_ENDPOINT)) {
+ /* Need to either suspend, or loop and call unlock/lock during
+ * every iteration - otherwise the system will remain locked,
+ * no interrupts served, so USB not going through as well.
+ * Note: for suspend, need USB_USE_WAIT == TRUE in halconf.h */
+ osalThreadSuspendS(&(&USB_DRIVER)->epc[KBD_ENDPOINT]->in_state->thread);
+ }
+ usbStartTransmitI(&USB_DRIVER, KBD_ENDPOINT, (uint8_t *)report, KBD_EPSIZE);
+ osalSysUnlock();
+ }
+ keyboard_report_sent = *report;
+}
+
+/* ---------------------------------------------------------
+ * Mouse functions
+ * ---------------------------------------------------------
+ */
+
+#ifdef MOUSE_ENABLE
+
+/* mouse IN callback hander (a mouse report has made it IN) */
+void mouse_in_cb(USBDriver *usbp, usbep_t ep) {
+ (void)usbp;
+ (void)ep;
+}
+
+void send_mouse(report_mouse_t *report) {
+ osalSysLock();
+ if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
+ osalSysUnlock();
+ return;
+ }
+ osalSysUnlock();
+
+ /* TODO: LUFA manually waits for the endpoint to become ready
+ * for about 10ms for mouse, kbd, system; 1ms for nkro
+ * is this really needed?
+ */
+
+ osalSysLock();
+ usbStartTransmitI(&USB_DRIVER, MOUSE_ENDPOINT, (uint8_t *)report, sizeof(report_mouse_t));
+ osalSysUnlock();
+}
+
+#else /* MOUSE_ENABLE */
+void send_mouse(report_mouse_t *report) {
+ (void)report;
+}
+#endif /* MOUSE_ENABLE */
+
+/* ---------------------------------------------------------
+ * Extrakey functions
+ * ---------------------------------------------------------
+ */
+
+#ifdef EXTRAKEY_ENABLE
+
+/* extrakey IN callback hander */
+void extra_in_cb(USBDriver *usbp, usbep_t ep) {
+ /* STUB */
+ (void)usbp;
+ (void)ep;
+}
+
+static void send_extra_report(uint8_t report_id, uint16_t data) {
+ osalSysLock();
+ if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
+ osalSysUnlock();
+ return;
+ }
+
+ report_extra_t report = {
+ .report_id = report_id,
+ .usage = data
+ };
+
+ usbStartTransmitI(&USB_DRIVER, EXTRA_ENDPOINT, (uint8_t *)&report, sizeof(report_extra_t));
+ osalSysUnlock();
+}
+
+void send_system(uint16_t data) {
+ send_extra_report(REPORT_ID_SYSTEM, data);
+}
+
+void send_consumer(uint16_t data) {
+ send_extra_report(REPORT_ID_CONSUMER, data);
+}
+
+#else /* EXTRAKEY_ENABLE */
+void send_system(uint16_t data) {
+ (void)data;
+}
+void send_consumer(uint16_t data) {
+ (void)data;
+}
+#endif /* EXTRAKEY_ENABLE */
+
+/* ---------------------------------------------------------
+ * Console functions
+ * ---------------------------------------------------------
+ */
+
+#ifdef CONSOLE_ENABLE
+
+/* console IN callback hander */
+void console_in_cb(USBDriver *usbp, usbep_t ep) {
+ (void)ep; /* should have ep == CONSOLE_ENDPOINT, so use that to save time/space */
+ uint8_t *buf;
+ size_t n;
+
+ osalSysLockFromISR();
+
+ /* rearm the timer */
+ chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp);
+
+ /* Freeing the buffer just transmitted, if it was not a zero size packet.*/
+ if (usbp->epc[CONSOLE_ENDPOINT]->in_state->txsize > 0U) {
+ obqReleaseEmptyBufferI(&console_buf_queue);
+ }
+
+ /* Checking if there is a buffer ready for transmission.*/
+ buf = obqGetFullBufferI(&console_buf_queue, &n);
+
+ if (buf != NULL) {
+ /* The endpoint cannot be busy, we are in the context of the callback,
+ so it is safe to transmit without a check.*/
+ /* Should have n == CONSOLE_EPSIZE; check it? */
+ usbStartTransmitI(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_EPSIZE);
+ } else {
+ /* Nothing to transmit.*/
+ }
+
+ osalSysUnlockFromISR();
+}
+
+/* Callback when data is inserted into the output queue
+ * Called from a locked state */
+void console_queue_onotify(io_buffers_queue_t *bqp) {
+ size_t n;
+ USBDriver *usbp = bqGetLinkX(bqp);
+
+ if(usbGetDriverStateI(usbp) != USB_ACTIVE)
+ return;
+
+ /* Checking if there is already a transaction ongoing on the endpoint.*/
+ if (!usbGetTransmitStatusI(usbp, CONSOLE_ENDPOINT)) {
+ /* Trying to get a full buffer.*/
+ uint8_t *buf = obqGetFullBufferI(&console_buf_queue, &n);
+ if (buf != NULL) {
+ /* Buffer found, starting a new transaction.*/
+ /* Should have n == CONSOLE_EPSIZE; check this? */
+ usbStartTransmitI(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_EPSIZE);
+ }
+ }
+}
+
+/* Flush timer code
+ * callback (called from ISR, unlocked state) */
+static void console_flush_cb(void *arg) {
+ USBDriver *usbp = (USBDriver *)arg;
+ osalSysLockFromISR();
+
+ /* check that the states of things are as they're supposed to */
+ if(usbGetDriverStateI(usbp) != USB_ACTIVE) {
+ /* rearm the timer */
+ chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp);
+ osalSysUnlockFromISR();
+ return;
+ }
+
+ /* If there is already a transaction ongoing then another one cannot be
+ started.*/
+ if (usbGetTransmitStatusI(usbp, CONSOLE_ENDPOINT)) {
+ /* rearm the timer */
+ chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp);
+ osalSysUnlockFromISR();
+ return;
+ }
+
+ /* Checking if there only a buffer partially filled, if so then it is
+ enforced in the queue and transmitted.*/
+ if(obqTryFlushI(&console_buf_queue)) {
+ size_t n,i;
+ uint8_t *buf = obqGetFullBufferI(&console_buf_queue, &n);
+
+ osalDbgAssert(buf != NULL, "queue is empty");
+
+ /* zero the rest of the buffer (buf should point to allocated space) */
+ for(i=n; i<CONSOLE_EPSIZE; i++)
+ buf[i]=0;
+ usbStartTransmitI(usbp, CONSOLE_ENDPOINT, buf, CONSOLE_EPSIZE);
+ }
+
+ /* rearm the timer */
+ chVTSetI(&console_flush_timer, MS2ST(CONSOLE_FLUSH_MS), console_flush_cb, (void *)usbp);
+ osalSysUnlockFromISR();
+}
+
+
+int8_t sendchar(uint8_t c) {
+ osalSysLock();
+ if(usbGetDriverStateI(&USB_DRIVER) != USB_ACTIVE) {
+ osalSysUnlock();
+ return 0;
+ }
+ osalSysUnlock();
+ /* Timeout after 100us if the queue is full.
+ * Increase this timeout if too much stuff is getting
+ * dropped (i.e. the buffer is getting full too fast
+ * for USB/HIDRAW to dequeue). Another possibility
+ * for fixing this kind of thing is to increase
+ * CONSOLE_QUEUE_CAPACITY. */
+ return(obqPutTimeout(&console_buf_queue, c, US2ST(100)));
+}
+
+#else /* CONSOLE_ENABLE */
+int8_t sendchar(uint8_t c) {
+ (void)c;
+ return 0;
+}
+#endif /* CONSOLE_ENABLE */
+
+void sendchar_pf(void *p, char c) {
+ (void)p;
+ sendchar((uint8_t)c);
+}
diff --git a/tmk_core/protocol/chibios/usb_main.h b/tmk_core/protocol/chibios/usb_main.h
new file mode 100644
index 000000000..30d8fcaef
--- /dev/null
+++ b/tmk_core/protocol/chibios/usb_main.h
@@ -0,0 +1,139 @@
+/*
+ * (c) 2015 flabberast <s3+flabbergast@sdfeu.org>
+ *
+ * Based on the following work:
+ * - Guillaume Duc's raw hid example (MIT License)
+ * https://github.com/guiduc/usb-hid-chibios-example
+ * - PJRC Teensy examples (MIT License)
+ * https://www.pjrc.com/teensy/usb_keyboard.html
+ * - hasu's TMK keyboard code (GPL v2 and some code Modified BSD)
+ * https://github.com/tmk/tmk_keyboard/
+ * - ChibiOS demo code (Apache 2.0 License)
+ * http://www.chibios.org
+ *
+ * Since some GPL'd code is used, this work is licensed under
+ * GPL v2 or later.
+ */
+
+
+#ifndef _USB_MAIN_H_
+#define _USB_MAIN_H_
+
+// TESTING
+// extern uint8_t blinkLed;
+
+#include "ch.h"
+#include "hal.h"
+
+/* -------------------------
+ * General USB driver header
+ * -------------------------
+ */
+
+/* The USB driver to use */
+#define USB_DRIVER USBD1
+
+/* Initialize the USB driver and bus */
+void init_usb_driver(USBDriver *usbp);
+
+/* Send remote wakeup packet */
+void send_remote_wakeup(USBDriver *usbp);
+
+/* ---------------
+ * Keyboard header
+ * ---------------
+ */
+
+/* main keyboard (6kro) */
+#define KBD_INTERFACE 0
+#define KBD_ENDPOINT 1
+#define KBD_EPSIZE 8
+#define KBD_REPORT_KEYS (KBD_EPSIZE - 2)
+
+/* secondary keyboard */
+#ifdef NKRO_ENABLE
+#define NKRO_INTERFACE 4
+#define NKRO_ENDPOINT 5
+#define NKRO_EPSIZE 16
+#define NKRO_REPORT_KEYS (NKRO_EPSIZE - 1)
+#endif
+
+/* extern report_keyboard_t keyboard_report_sent; */
+
+/* keyboard IN request callback handler */
+void kbd_in_cb(USBDriver *usbp, usbep_t ep);
+
+/* start-of-frame handler */
+void kbd_sof_cb(USBDriver *usbp);
+
+#ifdef NKRO_ENABLE
+/* nkro IN callback hander */
+void nkro_in_cb(USBDriver *usbp, usbep_t ep);
+#endif /* NKRO_ENABLE */
+
+/* ------------
+ * Mouse header
+ * ------------
+ */
+
+#ifdef MOUSE_ENABLE
+
+#define MOUSE_INTERFACE 1
+#define MOUSE_ENDPOINT 2
+#define MOUSE_EPSIZE 8
+
+/* mouse IN request callback handler */
+void mouse_in_cb(USBDriver *usbp, usbep_t ep);
+#endif /* MOUSE_ENABLE */
+
+/* ---------------
+ * Extrakey header
+ * ---------------
+ */
+
+#ifdef EXTRAKEY_ENABLE
+
+#define EXTRA_INTERFACE 3
+#define EXTRA_ENDPOINT 4
+#define EXTRA_EPSIZE 8
+
+/* extrakey IN request callback handler */
+void extra_in_cb(USBDriver *usbp, usbep_t ep);
+
+/* extra report structure */
+typedef struct {
+ uint8_t report_id;
+ uint16_t usage;
+} __attribute__ ((packed)) report_extra_t;
+#endif /* EXTRAKEY_ENABLE */
+
+/* --------------
+ * Console header
+ * --------------
+ */
+
+#ifdef CONSOLE_ENABLE
+
+#define CONSOLE_INTERFACE 2
+#define CONSOLE_ENDPOINT 3
+#define CONSOLE_EPSIZE 16
+
+/* Number of IN reports that can be stored inside the output queue */
+#define CONSOLE_QUEUE_CAPACITY 4
+
+/* Console flush time */
+#define CONSOLE_FLUSH_MS 50
+
+/* Putchar over the USB console */
+int8_t sendchar(uint8_t c);
+
+/* Flush output (send everything immediately) */
+void console_flush_output(void);
+
+/* console IN request callback handler */
+void console_in_cb(USBDriver *usbp, usbep_t ep);
+#endif /* CONSOLE_ENABLE */
+
+void sendchar_pf(void *p, char c);
+
+#endif /* _USB_MAIN_H_ */
diff --git a/tmk_core/protocol/ibm4704.c b/tmk_core/protocol/ibm4704.c
new file mode 100644
index 000000000..6a03cd441
--- /dev/null
+++ b/tmk_core/protocol/ibm4704.c
@@ -0,0 +1,189 @@
+/*
+Copyright 2010,2011,2012,2013 Jun WAKO <wakojun@gmail.com>
+*/
+#include <stdbool.h>
+#include <util/delay.h>
+#include "debug.h"
+#include "ring_buffer.h"
+#include "ibm4704.h"
+
+
+#define WAIT(stat, us, err) do { \
+ if (!wait_##stat(us)) { \
+ ibm4704_error = err; \
+ goto ERROR; \
+ } \
+} while (0)
+
+
+uint8_t ibm4704_error = 0;
+
+
+void ibm4704_init(void)
+{
+ inhibit(); // keep keyboard from sending
+ IBM4704_INT_INIT();
+ IBM4704_INT_ON();
+ idle(); // allow keyboard sending
+}
+
+/*
+Host to Keyboard
+----------------
+Data bits are LSB first and Parity is odd. Clock has around 60us high and 30us low part.
+
+ ____ __ __ __ __ __ __ __ __ __ ________
+Clock \______/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
+ ^ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____ ___
+Data ____|__/ X____X____X____X____X____X____X____X____X____X \___
+ | Start 0 1 2 3 4 5 6 7 P Stop
+ Request by host
+
+Start bit: can be long as 300-350us.
+Request: Host pulls Clock line down to request to send a command.
+Timing: After Request keyboard pull up Data and down Clock line to low for start bit.
+ After request host release Clock line once Data line becomes hi.
+ Host writes a bit while Clock is hi and Keyboard reads while low.
+Stop bit: Host releases or pulls up Data line to hi after 9th clock and waits for keyboard pull down the line to lo.
+*/
+uint8_t ibm4704_send(uint8_t data)
+{
+ bool parity = true; // odd parity
+ ibm4704_error = 0;
+
+ IBM4704_INT_OFF();
+
+ /* Request to send */
+ idle();
+ clock_lo();
+
+ /* wait for Start bit(Clock:lo/Data:hi) */
+ WAIT(data_hi, 300, 0x30);
+
+ /* Data bit */
+ for (uint8_t i = 0; i < 8; i++) {
+ WAIT(clock_hi, 100, 0x40+i);
+ if (data&(1<<i)) {
+ parity = !parity;
+ data_hi();
+ } else {
+ data_lo();
+ }
+ WAIT(clock_lo, 100, 0x48+i);
+ }
+
+ /* Parity bit */
+ WAIT(clock_hi, 100, 0x34);
+ if (parity) { data_hi(); } else { data_lo(); }
+ WAIT(clock_lo, 100, 0x35);
+
+ /* Stop bit */
+ WAIT(clock_hi, 100, 0x34);
+ data_hi();
+
+ /* End */
+ WAIT(data_lo, 100, 0x36);
+
+ idle();
+ IBM4704_INT_ON();
+ return 0;
+ERROR:
+ idle();
+ if (ibm4704_error > 0x30) {
+ xprintf("S:%02X ", ibm4704_error);
+ }
+ IBM4704_INT_ON();
+ return -1;
+}
+
+/* wait forever to receive data */
+uint8_t ibm4704_recv_response(void)
+{
+ while (!rbuf_has_data()) {
+ _delay_ms(1);
+ }
+ return rbuf_dequeue();
+}
+
+uint8_t ibm4704_recv(void)
+{
+ if (rbuf_has_data()) {
+ return rbuf_dequeue();
+ } else {
+ return -1;
+ }
+}
+
+/*
+Keyboard to Host
+----------------
+Data bits are LSB first and Parity is odd. Clock has around 60us high and 30us low part.
+
+ ____ __ __ __ __ __ __ __ __ __ _______
+Clock \_____/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/ \_/
+ ____ ____ ____ ____ ____ ____ ____ ____ ____ ____
+Data ____/ X____X____X____X____X____X____X____X____X____X________
+ Start 0 1 2 3 4 5 6 7 P Stop
+
+Start bit: can be long as 300-350us.
+Inhibit: Pull Data line down to inhibit keyboard to send.
+Timing: Host reads bit while Clock is hi.(rising edge)
+Stop bit: Keyboard pulls down Data line to lo after 9th clock.
+*/
+ISR(IBM4704_INT_VECT)
+{
+ static enum {
+ BIT0, BIT1, BIT2, BIT3, BIT4, BIT5, BIT6, BIT7, PARITY, STOP
+ } state = BIT0;
+ // LSB first
+ static uint8_t data = 0;
+ // Odd parity
+ static uint8_t parity = false;
+
+ ibm4704_error = 0;
+
+ switch (state) {
+ case BIT0:
+ case BIT1:
+ case BIT2:
+ case BIT3:
+ case BIT4:
+ case BIT5:
+ case BIT6:
+ case BIT7:
+ data >>= 1;
+ if (data_in()) {
+ data |= 0x80;
+ parity = !parity;
+ }
+ break;
+ case PARITY:
+ if (data_in()) {
+ parity = !parity;
+ }
+ if (!parity)
+ goto ERROR;
+ break;
+ case STOP:
+ // Data:Low
+ WAIT(data_lo, 100, state);
+ rbuf_enqueue(data);
+ ibm4704_error = IBM4704_ERR_NONE;
+ goto DONE;
+ break;
+ default:
+ goto ERROR;
+ }
+ state++;
+ goto RETURN;
+ERROR:
+ ibm4704_error = state;
+ while (ibm4704_send(0xFE)) _delay_ms(1); // resend
+ xprintf("R:%02X%02X\n", state, data);
+DONE:
+ state = BIT0;
+ data = 0;
+ parity = false;
+RETURN:
+ return;
+}
diff --git a/tmk_core/protocol/ibm4704.h b/tmk_core/protocol/ibm4704.h
new file mode 100644
index 000000000..618cce6be
--- /dev/null
+++ b/tmk_core/protocol/ibm4704.h
@@ -0,0 +1,110 @@
+/*
+Copyright 2014 Jun WAKO <wakojun@gmail.com>
+*/
+#ifndef IBM4704_H
+#define IBM4704_H
+
+#define IBM4704_ERR_NONE 0
+#define IBM4704_ERR_PARITY 0x70
+
+
+void ibm4704_init(void);
+uint8_t ibm4704_send(uint8_t data);
+uint8_t ibm4704_recv_response(void);
+uint8_t ibm4704_recv(void);
+
+
+/* Check pin configuration */
+#if !(defined(IBM4704_CLOCK_PORT) && \
+ defined(IBM4704_CLOCK_PIN) && \
+ defined(IBM4704_CLOCK_DDR) && \
+ defined(IBM4704_CLOCK_BIT))
+# error "ibm4704 clock pin configuration is required in config.h"
+#endif
+
+#if !(defined(IBM4704_DATA_PORT) && \
+ defined(IBM4704_DATA_PIN) && \
+ defined(IBM4704_DATA_DDR) && \
+ defined(IBM4704_DATA_BIT))
+# error "ibm4704 data pin configuration is required in config.h"
+#endif
+
+
+/*--------------------------------------------------------------------
+ * static functions
+ *------------------------------------------------------------------*/
+static inline void clock_lo(void)
+{
+ IBM4704_CLOCK_PORT &= ~(1<<IBM4704_CLOCK_BIT);
+ IBM4704_CLOCK_DDR |= (1<<IBM4704_CLOCK_BIT);
+}
+static inline void clock_hi(void)
+{
+ /* input with pull up */
+ IBM4704_CLOCK_DDR &= ~(1<<IBM4704_CLOCK_BIT);
+ IBM4704_CLOCK_PORT |= (1<<IBM4704_CLOCK_BIT);
+}
+static inline bool clock_in(void)
+{
+ IBM4704_CLOCK_DDR &= ~(1<<IBM4704_CLOCK_BIT);
+ IBM4704_CLOCK_PORT |= (1<<IBM4704_CLOCK_BIT);
+ _delay_us(1);
+ return IBM4704_CLOCK_PIN&(1<<IBM4704_CLOCK_BIT);
+}
+static inline void data_lo(void)
+{
+ IBM4704_DATA_PORT &= ~(1<<IBM4704_DATA_BIT);
+ IBM4704_DATA_DDR |= (1<<IBM4704_DATA_BIT);
+}
+static inline void data_hi(void)
+{
+ /* input with pull up */
+ IBM4704_DATA_DDR &= ~(1<<IBM4704_DATA_BIT);
+ IBM4704_DATA_PORT |= (1<<IBM4704_DATA_BIT);
+}
+static inline bool data_in(void)
+{
+ IBM4704_DATA_DDR &= ~(1<<IBM4704_DATA_BIT);
+ IBM4704_DATA_PORT |= (1<<IBM4704_DATA_BIT);
+ _delay_us(1);
+ return IBM4704_DATA_PIN&(1<<IBM4704_DATA_BIT);
+}
+
+static inline uint16_t wait_clock_lo(uint16_t us)
+{
+ while (clock_in() && us) { asm(""); _delay_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_clock_hi(uint16_t us)
+{
+ while (!clock_in() && us) { asm(""); _delay_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_data_lo(uint16_t us)
+{
+ while (data_in() && us) { asm(""); _delay_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_data_hi(uint16_t us)
+{
+ while (!data_in() && us) { asm(""); _delay_us(1); us--; }
+ return us;
+}
+
+/* idle state that device can send */
+static inline void idle(void)
+{
+ clock_hi();
+ data_hi();
+}
+
+/* inhibit device to send
+ * keyboard checks Data line on start bit(Data:hi) and it stops sending if Data line is low.
+ */
+static inline void inhibit(void)
+{
+ clock_hi();
+ data_lo();
+}
+
+#endif
diff --git a/tmk_core/protocol/iwrap.mk b/tmk_core/protocol/iwrap.mk
new file mode 100644
index 000000000..eeedd83af
--- /dev/null
+++ b/tmk_core/protocol/iwrap.mk
@@ -0,0 +1,26 @@
+IWRAP_DIR = protocol/iwrap
+
+OPT_DEFS += -DPROTOCOL_IWRAP
+
+SRC += $(IWRAP_DIR)/main.c \
+ $(IWRAP_DIR)/iwrap.c \
+ $(IWRAP_DIR)/suart.S \
+ $(COMMON_DIR)/sendchar_uart.c \
+ $(COMMON_DIR)/uart.c
+
+# Search Path
+VPATH += $(TMK_DIR)/protocol/iwrap
+
+
+# TODO: compatible with LUFA and PJRC
+# V-USB
+#
+VUSB_DIR = protocol/vusb
+OPT_DEFS += -DPROTOCOL_VUSB
+SRC += $(VUSB_DIR)/vusb.c \
+ $(VUSB_DIR)/usbdrv/usbdrv.c \
+ $(VUSB_DIR)/usbdrv/usbdrvasm.S \
+ $(VUSB_DIR)/usbdrv/oddebug.c
+VPATH += $(TMK_DIR)/protocol/vusb:$(TMK_DIR)/protocol/vusb/usbdrv
+
+
diff --git a/tmk_core/protocol/iwrap/iWRAP4.txt b/tmk_core/protocol/iwrap/iWRAP4.txt
new file mode 100644
index 000000000..2a062d9d9
--- /dev/null
+++ b/tmk_core/protocol/iwrap/iWRAP4.txt
@@ -0,0 +1,376 @@
+Bulegiga WT12
+=============
+WT12 is a bluetooth module from Bluegiga. http://www.bluegiga.com/
+
+iWRAP
+ higher layer interface for bluetooth firmware
+ communicate with UART
+
+iWRAP HID
+default setting
+ 115200 8bit/n/1/n
+
+
+TODO
+----
+KiCAD circuit/PCB design
+power saving
+ AVR sleep(15ms by watch dog timer)
+ WT12 sleep
+ measuring current consumption
+ measuring battery life of normal usage/idle/intensive usage
+software reset/bootloarder
+LED indicator(chaging/paring/connecting)
+license confirmation of suart.c
+consumer page is not working
+authenticate method/SSP
+SPP keyboard support
+SPP debug console support
+mouse wheel feature request to Bluegiga
+
+
+Problems
+--------
+power consumption
+no consumer page support(bug?)
+no mouse wheel support
+no paring management
+no interactive auth method
+
+
+UART hardware flow control
+--------------------------
+(iWRAP4 User Guide 9.5)
+Hardware flow control is enabled by default and it should not be disabled unless mandatory, because without the hardware flow control the data transmission may not be reliable.
+If the hardware flow control is enabled from PS-keys, but no flow control is used, the following steps should be implemented in the hardware design:
+- CTS pin must be grounded
+- RTS pin must be left floating
+
+
+Power Saving
+------------
+power consume
+ without opimization: 4hr to shutdown(310mAh)
+ 2011/08/25: 9hr(310mAh) SNIFF MASTER sleep/WDTO_120MS
+
+measure current consumption
+ HHKB keyswitch matrix board
+ idle
+ scanning
+ Bluegiga WT12 module
+ SLEEP command
+ deep sleep on/off in config bits
+
+HHKB keyswich
+ how to power off
+ I/O pin configuration when sleeping
+ FET switch for 5V regulator
+
+Bluetooth module
+ power off when in USB mode
+ power off by FET switch
+
+AVR configuration
+ unused pins
+ ADC
+
+
+
+SET CONTROL CONFIG
+------------------
+ SET CONTROL CONFIG 4810
+ SET CONTROL CONFIG LIST
+ SET CONTROL CONFIG 0000 0000 4910 DEEP_SLEEP KLUDGE INTERACTIVE_PIN UART_LATENCY
+
+ Bit14 UART low latency
+ Bit11 Interactive pairing mode
+ Bit04 Deep sleep
+
+
+Reconnection
+------------
+SET CONTROL AUTOCALL 1124 5000 HID
+ 1124 HID service class
+ 5000 interval ms
+
+HID profile
+-----------
+This is needed to configure only once.
+ SET PROFILE HID ON
+ RESET
+
+HID class
+---------
+ SET BT CLASS 005C0 // keyboard/mouse combined devie
+
+Pairing Security
+----------------
+Secure Simple Pairing(SSP)
+ SET BT SSP 2 0 // Enables SSP for keyboard and Man-in-the-middle protection
+ SET BT SSP 3 0 // Enables SSP just works mode
+
+for keyboard with SSP
+ SET BT AUTH * 0000
+ SET BT SSP 2 0
+ SET CONTROL CONFIG 800
+ RESET
+
+for keyboard without SSP
+ SET BT AUTH * 0000
+ SET CONTROL CONFIG 800
+ RESET
+
+AUTH
+ AUTH xx:xx:xx:xx:xx:xx? // Pairing request event
+ AUTH xx:xx:xx:xx:xx:xx 0000
+
+ SSP PASSKEY 78:dd:08:b7:e4:a2 ?
+ SSP PASSKEY 78:dd:08:b7:e4:a2 xxxxx
+ (SSP COMPLETE 78:dd:08:b7:e4:a2 HCI_ERROR_AUTH_FAIL // failed)
+ RING 0 78:dd:08:b7:e4:a2 11 HID
+
+Connecton
+ RING xx:xx:xx:xx:xx:xx xx HID // connection event
+
+ KILL xx:xx:xx:xx:xx:xx
+
+Mode
+----
+Command mode
+Data mode
+ Raw mode
+ (Simple mode not for a real keyboard)
+
+Raw mode
+ Keyboard:
+ 0x9f, length(10), 0xa1, 0x01, mods, 0x00, key1, key2, key3, key4, key5, key6
+
+ Mouse:
+ 0x9f, length(5), 0xa1, 0x02, buttons, X, Y
+
+ Consumer page:
+ 0x9f, length(5), 0xa1, 0x03, bitfield1, bitfield2, bitfield3
+
+ consumer page suage
+ Bitfield 1:
+ 0x01 Volume Increment
+ 0x02 Volume Decrement
+ 0x04 Mute
+ 0x08 Play/Pause
+ 0x10 Scan Next Track
+ 0x20 Scan Previous Track
+ 0x40 Stop
+ 0x80 Eject
+ Bitfield 2:
+ 0x01 Email Reader
+ 0x02 Application Control Search
+ 0x04 AC Bookmarks
+ 0x08 AC Home
+ 0x10 AC Back
+ 0x20 AC Forward
+ 0x40 AC Stop
+ 0x80 AC Refresh
+ Bitfield 3:
+ 0x01 Application Launch Generic Consumer Control
+ 0x02 AL Internet Browser
+ 0x04 AL Calculator
+ 0x08 AL Terminal Lock / Screensaver
+ 0x10 AL Local Machine Browser
+ 0x20 AC Minimize
+ 0x40 Record
+ 0x80 Rewind
+
+
+
+
+
+2011/07/13
+set
+SET BT BDADDR 00:07:80:47:22:14
+SET BT NAME HHKB pro BT
+SET BT CLASS 0005c0
+SET BT AUTH * 0000
+SET BT IDENT BT:47 f000 4.1.0 Bluegiga iWRAP
+SET BT LAP 9e8b33
+SET BT PAGEMODE 4 2000 1
+SET BT PAIR 78:dd:08:b7:e4:a2 a191189cd7e51030ad6a07848ce879bb
+SET BT POWER 3 3 3
+SET BT ROLE 0 f 7d00
+SET BT SNIFF 0 20 1 8
+SET BT SSP 2 1
+SET BT MTU 667
+SET CONTROL AUTOCALL 1124 3000 HID
+SET CONTROL BAUD 38400,8n1
+SET CONTROL CD 00 0
+SET CONTROL ECHO 7
+SET CONTROL ESCAPE 43 00 1
+SET CONTROL GAIN 0 5
+SET CONTROL INIT SET CONTROL MUX 0
+SET CONTROL MSC DTE 00 00 00 00 00 00
+SET CONTROL MUX 1
+SET CONTROL PIO 00 00
+SET CONTROL READY 00
+SET PROFILE HID f HID
+SET
+
+info config
+
+!!! THIS IS BETA RELEASE AND MAY BE USED FOR EVALUATION PURPOSES ONLY !!!
+
+WRAP THOR AI (4.1.0 build 435)
+Copyright (c) 2003-2011 Bluegiga Technologies Inc.
+Compiled on Jun 28 2011 17:19:51, running on WT12-A module, psr v31
+ AVRCP BGIO FTP HFP HFP_AG HID HID_CONSUMER_PAGE HSP LEDS MAP OTA PBAP PIO=0x00fc SSP SUBRATE TEST VOLUME
+ - BOCK3 version 435 (Jun 28 2011 17:19:37) (max acl/sco 7/1)
+ - Bluetooth version 2.1, Power class 2
+ - Loader 4279, firmware 6297 (56-bit encryption), native execution mode
+ - up 0 days, 06:23, 2 connections (pool 2)
+ - User configuration:
+&028a = 0001 0000 0000 0011 0024 0000 0000 0010 0000 0080 0000 0000 0080 005f 009b 0034 00fb 0006
+&028b = 0000 0bb8
+&028d = 0001
+&0295 = 0000 0005 000b 0000 0003 0000 0000 0000 0000 0000 0000
+&0298 = a006
+&0299 = 0000 0000
+&02a3 = 0030 0030 0030 0030
+&02a4 = 009d 0000
+&02a5 = 0053 0045 0054 0020 0043 004f 004e 0054 0052 004f 004c 0020 004d 0055 0058 0020 0030
+&02a7 = 0000 05c0
+&02a8 = 4910 0000 0000
+&02aa = 0004 2000 0001 0033 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
+&02ac = 0000 0000 002b 0000 0000 0000 0000 0000 0000 0000 0002 0000 0000 0000 0010 0000 0000 0000 0000 029b 0000 0000 0000 0000
+&02ad = 4848 424b 7020 6f72 4220 0054
+&02b3 = 0005 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003
+&02b7 = 000f 4948 0044
+&02bb = 8000
+READY.
+
+
+
+
+2011/07/07 settings:
+set
+SET BT BDADDR 00:07:80:47:22:14
+SET BT NAME HHKB Pro BT
+SET BT CLASS 0005c0
+SET BT AUTH * 000
+SET BT IDENT BT:47 f000 4.0.0 Bluegiga iWRAP
+SET BT LAP 9e8b33
+SET BT PAGEMODE 4 2000 1
+SET BT PAIR 78:dd:08:b7:e4:a2 9e54d0aabb1b4d73cfccddb1ea4ef2d6
+SET BT POWER 3 3 3
+SET BT ROLE 0 f 7d00
+SET BT SNIFF 0 20 1 8
+SET BT SSP 3 0
+SET BT MTU 667
+SET CONTROL BAUD 38400,8n1
+SET CONTROL CD 00 0
+SET CONTROL ECHO 7
+SET CONTROL ESCAPE 255 00 1
+SET CONTROL GAIN 0 5
+SET CONTROL INIT set control mux 0
+SET CONTROL MSC DTE 00 00 00 00 00 00
+SET CONTROL PREAMP 1 1
+SET CONTROL READY 00
+SET PROFILE HID HID
+SET PROFILE SPP Bluetooth Serial Port
+SET
+
+info config
+WRAP THOR AI (4.0.0 build 317)
+Copyright (c) 2003-2010 Bluegiga Technologies Inc.
+Compiled on Apr 20 2010 16:44:28, running on WT12-A module, psr v31
+ AVRCP FTP PBAP PIO=0x00fc SSP SUBRATE VOLUME
+ - BOCK3 version 317 (Apr 20 2010 16:44:21) (max acl/sco 7/1)
+ - Bluetooth version 2.1, Power class 2
+ - Loader 4279, firmware 6297 (56-bit encryption), native execution mode
+ - up 0 days, 00:00, 0 connections (pool 1)
+ - User configuration:
+&028c = 0001 0020 0000 0001 0008 0000
+&028d = 0000
+&0296 = 0047 0001 f000 0400 6c42 6575 6967 6167 6920 5257 5041
+&0298 = c006
+&02a3 = 0030 0030 0030
+&02a4 = 009d 0000
+&02a5 = 0073 0065 0074 0020 0063 006f 006e 0074 0072 006f 006c 0020 006d 0075 0078 0020 0030
+&02a7 = 0000 05c0
+&02a8 = 0800 0000 0000
+&02ac = 0000 0000 00ff 0000 0000 0000 0000 0000 0000 0000 0002 0000 0000 0000 0010 0000 0000 0000 0000 029b 0000 0000 0000 0000
+&02ad = 4848 424b 5020 6f72 4220 0054
+&02b3 = 0004 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003
+&02b7 = 0000
+&02bb = 6c42 6575 6f74 746f 2068 6553 6972 6c61 5020 726f 0074
+READY.
+
+
+
+2011/08/23:
+SET BT BDADDR 00:07:80:47:22:14
+SET BT NAME HHKB pro BT
+SET BT CLASS 0005c0
+SET BT AUTH * 0000
+SET BT IDENT BT:47 f000 4.1.0 Bluegiga iWRAP
+SET BT LAP 9e8b33
+SET BT PAGEMODE 4 2000 1
+SET BT PAIRCOUNT 4
+SET BT POWER 3 3 3
+SET BT ROLE 1 f 12c0
+SET BT SNIFF 10 2 1 8
+SET BT SSP 3 0
+SET BT MTU 667
+SET CONTROL BAUD 38400,8n1
+SET CONTROL CD 00 0
+SET CONTROL ECHO 7
+SET CONTROL ESCAPE 43 00 1
+SET CONTROL GAIN 0 5
+SET CONTROL INIT SET CONTROL MUX 0
+SET CONTROL MSC DTE 00 00 00 00 00 00
+SET CONTROL MUX 1
+SET CONTROL PIO 00 00
+SET CONTROL READY 00
+SET PROFILE HID 7 HIDKeyboardMouse
+SET
+
+SET CONTROL CONFIG 0000 0004 481e CLOCK_CACHE INTERLACED_INQ INTERLACED_PAGE DEEP_SLEEP INTERACTIVE_PIN UART_LATENCY 23D_NOKLUDGE
+
+
+
+2011/08/25:
+SET BT BDADDR 00:07:80:47:22:14
+SET BT NAME HHKB pro BT
+SET BT CLASS 0005c0
+
+SET BT IDENT BT:47 f000 4.1.0 Bluegiga iWRAP
+SET BT LAP 9e8b33
+SET BT PAGEMODE 4 2000 1
+SET BT PAIRCOUNT 4
+SET BT PAIR 78:dd:08:b7:e4:a2 0be83335a03fed8ededae42e99554e28
+SET BT POWER 3 3 3
+SET BT ROLE 1 f 12c0
+SET BT SNIFF 100 20 1 8
+SET BT SSP 3 0
+SET BT MTU 667
+SET CONTROL BAUD 38400,8n1
+SET CONTROL CD 00 0
+SET CONTROL ECHO 7
+SET CONTROL ESCAPE - 20 1
+SET CONTROL GAIN 0 5
+SET CONTROL INIT SET CONTROL MUX 0
+SET CONTROL MSC DTE 00 00 00 00 00 00
+SET CONTROL MUX 1
+SET CONTROL PIO 00 00
+SET CONTROL READY 00
+SET PROFILE HID f HIDKeyboardMouse
+SET
+
+
+SET CONTROL CONFIG 0000 0000 490e CLOCK_CACHE INTERLACED_INQ INTERLACED_PAGE KLUDGE INTERACTIVE_PIN UART_LATENCY
+
+
+2011/09/08:
+SET CONTROL CONFIG 0000 0000 410e CLOCK_CACHE INTERLACED_INQ INTERLACED_PAGE KLUDGE UART_LATENCY
+
+ Removed INTERACTIVE_PIN to avoid interactive auth and use SET BT AUTH pin(0000).
+
+
+EOF
diff --git a/tmk_core/protocol/iwrap/iWRAP5.txt b/tmk_core/protocol/iwrap/iWRAP5.txt
new file mode 100644
index 000000000..ce3310f1b
--- /dev/null
+++ b/tmk_core/protocol/iwrap/iWRAP5.txt
@@ -0,0 +1,356 @@
+Terminology
+===========
+PSM
+HIDP HID Protocol
+L2CAP Logical Link Control Adaptation Protocol
+MTU Maximum Transmission Unit
+
+
+
+HID Protocol
+============
+3 of HID_SPEC_V11.pdf
+
+Channel
+-------
+Control channel PSM=0x0011
+Interrupt channel PSM=0x0013
+
+Message
+-------
+HANDSHAKE(0)
+HID_CONTROL(1)
+
+GET_REPORT(4)
+ Host requests report(DATA payload on Control channel) from Device
+ Size Desc
+ ------------------------------------------------------------------------------
+ HIDP-Hdr 1 7..4: HIDP Message TYpe(4: GET_REPORT)
+ 3: Size(1:2-octed buffer size, 0:size of the report)
+ 2: 0
+ 1..0: Report Type(1:input, 2:output, 3: feature)
+ ReportID 1 Optional
+ BufferSize 2 Optional(specified when Size=1)
+
+SET_REPORT(5)
+GET_PROTOCOL(6)
+SET_PROTOCOL(7)
+
+DATA(A)
+ Input/Output Report: All DATA payloads flow on Interrupt channel.
+ Other: flows on Control channel.
+ Size Desc
+ ------------------------------------------------------------------------------
+ HIDP-Hdr 1 7..4 0xA
+ 3..2 Reserved(0)
+ 1..0 Report Type(0:Other, 1:Input, 2:Output, 3:Feature)
+ Payload N Data
+
+
+
+
+Boot Protocol
+=============
+3.3.2
+No report descriptor, fixed report descriptors defined.
+
+Device ReportID Size
+---------------------------------
+Reserved 0
+Keyboard 1 9octets
+Mouse 2 4octets
+Reserved 3-255
+
+Report descriptor
+-----------------
+Report ID is added to USB HID boot protocol descriptor.
+Boot Protocol device doesn't need to supply descriptors. and can send extra data on end of boot report this data will be ignored unless host supports report descriptor.
+
+Report Protocol devices can have specific descriptors. Using Boot protocol descriptor followed by extra data may be useful for compatibility to Boot protocol only supported host.
+
+NOTE:
+Bluegiga HID sample say report ID of mouse is 1 but 2?
+Bluegiga HID sample say report ID of consumer page is 2 but 3?
+** mouse.desc and consumer.desc were fixed.
+ size
+keyboard.desc 67 0x43
+mouse.desc 60 0x3c
+consumer.desc 82 0x52
+combo.desc 209 0xd1
+
+
+
+SDP
+===
+attributes(3.3.2)
+----------
+HIDDeviceSubclass
+ which type is supported in Boot Protocol Mode
+ 7 6
+ ---
+ 0 1 Keyboard
+ 1 0 Pointing device
+ 1 1 Combo keyboard/pointing device
+
+HIDBootDevice
+ TRUE
+HIDReconnectInitiate
+ TRUE
+
+
+Class of Device/Service
+=======================
+http://phys.sci.hokudai.ac.jp/LABS/yts/pic/GB002/Bluetooth_assigned_numbers_baseband.pdf
+
+0x0005C0 Keyboard and Pointing deivce(combo)
+
+
+ 23 16 15 8 7 0
+ ---------------------------------
+ Service |Major |Minor |Format
+
+ Format type
+ 1 0
+ ---
+ 0 0
+
+ Minor Device Class of Peripheral Major
+ 7 6
+ ---
+ 0 1 Keyboard
+ 1 0 Pointing device
+ 1 1 Combo keyboard/pointing device
+
+
+ Major device classes
+ 12 11 10 9 8
+ --------------
+ 0 0 0 0 0 Miscellaneous
+ 0 0 0 0 1 Computer
+ 0 0 0 1 0 Phone
+ 0 0 0 1 1 LAN /Network Access point
+ 0 0 1 0 0 Audio/Video (headset,speaker,stereo, video display, vcr.....
+ 0 0 1 0 1 *Peripheral (mouse, joystick, keyboards, ..... )
+ 0 0 1 1 0 Imaging (printing, scanner, camera, display, ...)
+ 1 1 1 1 1 Uncategorized, specific device code not specified
+ X X X X X All other values reserved
+
+
+ Major service classes
+ bit
+ --------------------------------------
+ 13 Limited Discoverable Mode [Ref #1]
+ 14 (reserved)
+ 15 (reserved)
+ 16 Positioning (Location identification)
+ 17 Networking (LAN, Ad hoc, ...)
+ 18 Rendering (Printing, Speaker, ...)
+ 19 Capturing (Scanner, Microphone, ...)
+ 20 Object Transfer (v-Inbox, v-Folder, ...)
+ 21 Audio (Speaker, Microphone, Headset service, ...)
+ 22 Telephony (Cordless telephony, Modem, Headset service, ...)
+ 23 Information (WEB-server, WAP-server, ...)
+
+
+
+
+Authentication SSP
+-------------------
+SET BT SSP 2 0 PASS KEY entering
+SET BT SSP 3 0 NO PASS KEY entering
+SET BT SSP <capabilities> <mitm>
+ <capabilities>: 0:display only 1:display+yes/no button 2:keyboard only 3:none
+SET BT SSP 2 1 # 2:keyboard only 1:Man-in-the-middle protection is needed
+SET BT SSP 2 0 # 2:keyboard only 0:Man-in-the-middle protection is not needed
+
+
+SET BT SSP 2 1
+ bond only if MITM protection is supported by host
+SET BT SSP 2 0
+ bond even if MITM protection is not supported by host
+
+On Windows 'Add device' causes SSP PASSKEY event on iWRAP
+ SSP PASSKEY 78:dd:08:b7:e4:a2 ?
+
+If device has display(0 or 1) this event occurs. User should be shown this code on the device.
+ SSP CONFIRM 78:dd:08:b7:e4:a2 517572
+
+
+SET BT SSP 3 0
+ No input/output, No MITM protection.
+ Without procedure of authentication the divice is bond to host.
+
+
+Connect
+=======
+CALL 78:dd:08:b7:e4:a2 11 HID
+
+
+Setting
+========
+Following settings need to be done before wiring into keyboard.
+- UART speed: 38400bps(115200bps didn't work with software serial)
+- No SSP procedure(without MITM protection)
+- No Power Saving
+
+# clear pairing record and set default
+SET BT PAIR *
+SET RESET
+
+SET CONTROL INIT SET CONTROL MUX 0
+SET CONTROL BAUD 38400,8n1
+SET BT NAME TMK Blootooth WT12
+SET BT CLASS 0005c0
+SET BT AUTH * 0000
+SET BT SSP 3 0
+SET CONTROL CONFIG 4800
+SET PROFILE HID 0f c0 0100 00 en 0409 TMK Bluetooth keyboard(WT12)
+SET PROFILE SPP
+
+# power saving?
+SET BT SNIFF 100 20 1 8
+
+
+# Report Descriptor
+# combo keyboard + mouse + consumer
+HID SET d2 05010906a1010507850119e029e715002501750195088102950175088101950575010508850119012905910295017503910395067508150025650507190029658100c005010902a1010901a1008502050919012908150025017501950881020501093009311581257f750895028106093895018106050c0a380295018106c0c0050c0901a1018503050c1500250109e909ea09e209cd19b529b87501950881020a8a010a21020a2a021a23022a27027501950881020a83010a96010a92010a9e010a94010a060209b209b4750195088102c0
+
+
+
+SET PROFILE HID
+---------------
+ SET PROFILE HID 0d c0 100 0 en 0409 HHKB pro Bluetooth keyboard
+ {function bit} uint8
+ {subclass} uint8
+ {version} uint16
+ {country} uint8
+ {BTlang} char[2]
+ {USBlang} uint16
+ {name} string
+
+
+SET BT CLASS
+------------
+ See Class of Device
+ composite device: keyboard and mouse
+ SET BT CLASS 005c0
+
+
+
+
+
+
+----------
+after setting
+----------
+set
+SET BT BDADDR 00:07:80:47:22:14
+SET BT NAME TMK Blootooth WT12
+SET BT CLASS 0005c0
+SET BT AUTH * 0000
+SET BT IDENT BT:47 f000 5.0.1 Bluegiga iWRAP
+SET BT LAP 9e8b33
+SET BT PAGEMODE 4 2000 1
+SET BT PAIR 78:dd:08:b7:e4:a2 9e3d85c91bcae73fef8cc10bec18b42f
+SET BT POWER 3 3 3
+SET BT ROLE 0 f 7d00
+SET BT SNIFF 0 20 1 8
+SET BT SSP 3 0
+SET BT MTU 667
+SET CONTROL BAUD 38400,8n1
+SET CONTROL CD 00 0
+SET CONTROL ECHO 7
+SET CONTROL ESCAPE 43 00 1
+SET CONTROL GAIN 0 5
+SET CONTROL INIT SET CONTROL MUX 0
+SET CONTROL MSC DTE 00 00 00 00 00 00
+SET CONTROL MUX 1
+SET CONTROL PIO 00 00
+SET CONTROL READY 00
+SET PROFILE HID 0f c0 0100 00 en 0409 TMK Bluetooth keyboard(WT12)
+SET
+
+set control config list
+SET CONTROL CONFIG 0000 0000 0000 4900 KLUDGE INTERACTIVE_PIN UART_LATENCY
+
+
+info config
+WRAP THOR AI (5.0.1 build 620)
+Copyright (c) 2003-2012 Bluegiga Technologies Inc.
+Compiled on Oct 1 2012 10:56:21, running on WT12-A module, psr v31
+ BGIO FTP HFP HFP_AG HID HID_CONSUMER_PAGE HSP MAP MDP OTA PBAP PIO=0x00fc SSP SUBRATE TEST VOLUME
+ - BOCK4 version 620 (Oct 1 2012 10:56:03) (max acl/sco 7/1)
+ - Bluetooth version 3.0, Power class 2
+ - Loader 8615, firmware 8825 (56-bit encryption), native execution mode
+ - up 0 days, 01:50, 2 connections (pool 2)
+ - User configuration:
+&028d = 0001
+&0295 = 0000 0005 000b 0000 0003 0000 0000 0000 0000 0000 0000
+&0298 = c053
+&0299 = 0000 0000
+&02a3 = 0030 0030 0030 0030
+&02a4 = 009d 0000
+&02a5 = 0053 0045 0054 0020 0043 004f 004e 0054 0052 004f 004c 0020 004d 0055 0058 0020 0030
+&02a7 = 0000 05c0
+&02a8 = 0800 0000 0000 0000
+&02aa = 0004 2000 0001 0033 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
+&02ac = 0000 0000 002b 0000 0000 0000 0000 0000 0000 0000 0002 0000 0000 0000 0010 0000 0000 0000 0000 029b 0000 0000 0000 0000
+&02ad = 4d54 204b 6c42 6f6f 6f74 746f 2068 5457 3231
+&02b0 = fa65 b0aa 934a 077b a600 d1cc fe58 8dd5
+&02b3 = 0004 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0003 0005 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0005
+&02b7 = 000f 00c0 0100 0000 0065 006e 0409 4d54 204b 6c42 6575 6f74 746f &02bb = 8000
+READY.
+----------
+
+
+
+-----
+After 5.0.1 Firmware update
+Firmware: ai-5.0.1-620-25b.bc4.dfu
+PSR: wt12-a.ai-5.0.1-620-25b.psrf
+-----
+info config
+WRAP THOR AI (5.0.1 build 620)
+Copyright (c) 2003-2012 Bluegiga Technologies Inc.
+Compiled on Oct 1 2012 10:56:21, running on WT12-A module, psr v31
+ BGIO FTP HFP HFP_AG HID HID_CONSUMER_PAGE HSP MAP MDP OTA PBAP PIO=0x00fc SSP SUBRATE TEST VOLUME
+ - BOCK4 version 620 (Oct 1 2012 10:56:03) (max acl/sco 7/1)
+ - Bluetooth version 3.0, Power class 2
+ - Loader 8615, firmware 8825 (56-bit encryption), native execution mode
+ - up 0 days, 00:03, 0 connections (pool 1)
+ - User configuration:
+&0295 = 0000 0005 000b 0000 0003 0000 0000 0000 0000 0000 0000
+&0299 = 0000 0000
+&02aa = 0004 2000 0001 0033 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
+&02ac = 0000 0000 002b 0000 0000 0000 0000 0000 0000 0000 0002 0000 0000 0000 0010 0000 0000 0000 0000 029b 0000 0000 0000 0000
+&02ad = 5457 3231 412d
+&02b0 = fa65 b0aa 934a 077b a600 d1cc fe58 8dd5
+READY.
+
+set
+SET BT BDADDR 00:07:80:47:22:14
+SET BT NAME WT12-A
+SET BT CLASS 001f00
+SET BT IDENT BT:47 f000 5.0.1 Bluegiga iWRAP
+SET BT LAP 9e8b33
+SET BT PAGEMODE 4 2000 1
+SET BT PAIR 78:dd:08:b7:e4:a2 af18f81faa107e6dd068762ef921f48b
+SET BT POWER 3 3 3
+SET BT ROLE 0 f 7d00
+SET BT SNIFF 0 20 1 8
+SET BT SSP 3 0
+SET BT MTU 667
+SET CONTROL BAUD 115200,8n1
+SET CONTROL CD 00 0
+SET CONTROL ECHO 7
+SET CONTROL ESCAPE 43 00 1
+SET CONTROL GAIN 0 5
+SET CONTROL MSC DTE 00 00 00 00 00 00
+SET CONTROL PIO 00 00
+SET CONTROL READY 00
+SET PROFILE SPP Bluetooth Serial Port
+SET
+
+set control config list
+SET CONTROL CONFIG 0000 0000 0000 0100 KLUDGE
+---------
diff --git a/tmk_core/protocol/iwrap/iwrap.c b/tmk_core/protocol/iwrap/iwrap.c
new file mode 100644
index 000000000..6a404116a
--- /dev/null
+++ b/tmk_core/protocol/iwrap/iwrap.c
@@ -0,0 +1,469 @@
+/*
+Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* host driver for Bulegiga iWRAP */
+/* Bluegiga BT12
+ * Connections
+ * Hardware UART Software UART BlueTooth
+ * PC=====UART=======AVR=====SUART====iWRAP(BT12)-----------PC
+ *
+ * - Hardware UART for Debug Console to communicate iWRAP
+ * - Software UART for iWRAP control to send keyboard/mouse data
+ */
+
+#include <stdint.h>
+#include <string.h>
+#include <avr/interrupt.h>
+#include <util/delay.h>
+#include "keycode.h"
+#include "suart.h"
+#include "uart.h"
+#include "report.h"
+#include "host_driver.h"
+#include "iwrap.h"
+#include "print.h"
+
+
+/* iWRAP MUX mode utils. 3.10 HID raw mode(iWRAP_HID_Application_Note.pdf) */
+#define MUX_HEADER(LINK, LENGTH) do { \
+ xmit(0xbf); /* SOF */ \
+ xmit(LINK); /* Link */ \
+ xmit(0x00); /* Flags */ \
+ xmit(LENGTH); /* Length */ \
+} while (0)
+#define MUX_FOOTER(LINK) xmit(LINK^0xff)
+
+
+static uint8_t connected = 0;
+//static uint8_t channel = 1;
+
+/* iWRAP buffer */
+#define MUX_BUF_SIZE 64
+static char buf[MUX_BUF_SIZE];
+static uint8_t snd_pos = 0;
+
+#define MUX_RCV_BUF_SIZE 256
+static char rcv_buf[MUX_RCV_BUF_SIZE];
+static uint8_t rcv_head = 0;
+static uint8_t rcv_tail = 0;
+
+
+/* receive buffer */
+static void rcv_enq(char c)
+{
+ uint8_t next = (rcv_head + 1) % MUX_RCV_BUF_SIZE;
+ if (next != rcv_tail) {
+ rcv_buf[rcv_head] = c;
+ rcv_head = next;
+ }
+}
+
+static char rcv_deq(void)
+{
+ char c = 0;
+ if (rcv_head != rcv_tail) {
+ c = rcv_buf[rcv_tail++];
+ rcv_tail %= MUX_RCV_BUF_SIZE;
+ }
+ return c;
+}
+
+/*
+static char rcv_peek(void)
+{
+ if (rcv_head == rcv_tail)
+ return 0;
+ return rcv_buf[rcv_tail];
+}
+*/
+
+static void rcv_clear(void)
+{
+ rcv_tail = rcv_head = 0;
+}
+
+/* iWRAP response */
+ISR(PCINT1_vect, ISR_BLOCK) // recv() runs away in case of ISR_NOBLOCK
+{
+ if ((SUART_IN_PIN & (1<<SUART_IN_BIT)))
+ return;
+
+ static volatile uint8_t mux_state = 0xff;
+ static volatile uint8_t mux_link = 0xff;
+ uint8_t c = recv();
+ switch (mux_state) {
+ case 0xff: // SOF
+ if (c == 0xbf)
+ mux_state--;
+ break;
+ case 0xfe: // Link
+ mux_state--;
+ mux_link = c;
+ break;
+ case 0xfd: // Flags
+ mux_state--;
+ break;
+ case 0xfc: // Length
+ mux_state = c;
+ break;
+ case 0x00:
+ mux_state = 0xff;
+ mux_link = 0xff;
+ break;
+ default:
+ if (mux_state--) {
+ uart_putchar(c);
+ rcv_enq(c);
+ }
+ }
+}
+
+
+/*------------------------------------------------------------------*
+ * iWRAP communication
+ *------------------------------------------------------------------*/
+void iwrap_init(void)
+{
+ // reset iWRAP if in already MUX mode after AVR software-reset
+ iwrap_send("RESET");
+ iwrap_mux_send("RESET");
+ _delay_ms(3000);
+ iwrap_send("\r\nSET CONTROL MUX 1\r\n");
+ _delay_ms(500);
+ iwrap_check_connection();
+}
+
+void iwrap_mux_send(const char *s)
+{
+ rcv_clear();
+ MUX_HEADER(0xff, strlen((char *)s));
+ iwrap_send(s);
+ MUX_FOOTER(0xff);
+}
+
+void iwrap_send(const char *s)
+{
+ while (*s)
+ xmit(*s++);
+}
+
+/* send buffer */
+void iwrap_buf_add(uint8_t c)
+{
+ // need space for '\0'
+ if (snd_pos < MUX_BUF_SIZE-1)
+ buf[snd_pos++] = c;
+}
+
+void iwrap_buf_del(void)
+{
+ if (snd_pos)
+ snd_pos--;
+}
+
+void iwrap_buf_send(void)
+{
+ buf[snd_pos] = '\0';
+ snd_pos = 0;
+ iwrap_mux_send(buf);
+}
+
+void iwrap_call(void)
+{
+ char *p;
+
+ iwrap_mux_send("SET BT PAIR");
+ _delay_ms(500);
+
+ p = rcv_buf + rcv_tail;
+ while (!strncmp(p, "SET BT PAIR", 11)) {
+ p += 7;
+ strncpy(p, "CALL", 4);
+ strncpy(p+22, " 11 HID\n\0", 9);
+ print_S(p);
+ iwrap_mux_send(p);
+ // TODO: skip to next line
+ p += 57;
+
+ DEBUG_LED_CONFIG;
+ DEBUG_LED_ON;
+ _delay_ms(500);
+ DEBUG_LED_OFF;
+ _delay_ms(500);
+ DEBUG_LED_ON;
+ _delay_ms(500);
+ DEBUG_LED_OFF;
+ _delay_ms(500);
+ DEBUG_LED_ON;
+ _delay_ms(500);
+ DEBUG_LED_OFF;
+ _delay_ms(500);
+ DEBUG_LED_ON;
+ _delay_ms(500);
+ DEBUG_LED_OFF;
+ _delay_ms(500);
+ DEBUG_LED_ON;
+ _delay_ms(500);
+ DEBUG_LED_OFF;
+ _delay_ms(500);
+ }
+ iwrap_check_connection();
+}
+
+void iwrap_kill(void)
+{
+ char c;
+ iwrap_mux_send("LIST");
+ _delay_ms(500);
+
+ while ((c = rcv_deq()) && c != '\n') ;
+ if (strncmp(rcv_buf + rcv_tail, "LIST ", 5)) {
+ print("no connection to kill.\n");
+ return;
+ }
+ // skip 10 'space' chars
+ for (uint8_t i = 10; i; i--)
+ while ((c = rcv_deq()) && c != ' ') ;
+
+ char *p = rcv_buf + rcv_tail - 5;
+ strncpy(p, "KILL ", 5);
+ strncpy(p + 22, "\n\0", 2);
+ print_S(p);
+ iwrap_mux_send(p);
+ _delay_ms(500);
+
+ iwrap_check_connection();
+}
+
+void iwrap_unpair(void)
+{
+ iwrap_mux_send("SET BT PAIR");
+ _delay_ms(500);
+
+ char *p = rcv_buf + rcv_tail;
+ if (!strncmp(p, "SET BT PAIR", 11)) {
+ strncpy(p+29, "\n\0", 2);
+ print_S(p);
+ iwrap_mux_send(p);
+ }
+}
+
+void iwrap_sleep(void)
+{
+ iwrap_mux_send("SLEEP");
+}
+
+void iwrap_sniff(void)
+{
+}
+
+void iwrap_subrate(void)
+{
+}
+
+bool iwrap_failed(void)
+{
+ if (strncmp(rcv_buf, "SYNTAX ERROR", 12))
+ return true;
+ else
+ return false;
+}
+
+uint8_t iwrap_connected(void)
+{
+ return connected;
+}
+
+uint8_t iwrap_check_connection(void)
+{
+ iwrap_mux_send("LIST");
+ _delay_ms(100);
+
+ if (strncmp(rcv_buf, "LIST ", 5) || !strncmp(rcv_buf, "LIST 0", 6))
+ connected = 0;
+ else
+ connected = 1;
+ return connected;
+}
+
+
+/*------------------------------------------------------------------*
+ * Host driver
+ *------------------------------------------------------------------*/
+static uint8_t keyboard_leds(void);
+static void send_keyboard(report_keyboard_t *report);
+static void send_mouse(report_mouse_t *report);
+static void send_system(uint16_t data);
+static void send_consumer(uint16_t data);
+
+static host_driver_t driver = {
+ keyboard_leds,
+ send_keyboard,
+ send_mouse,
+ send_system,
+ send_consumer
+};
+
+host_driver_t *iwrap_driver(void)
+{
+ return &driver;
+}
+
+static uint8_t keyboard_leds(void) {
+ return 0;
+}
+
+static void send_keyboard(report_keyboard_t *report)
+{
+ if (!iwrap_connected() && !iwrap_check_connection()) return;
+ MUX_HEADER(0x01, 0x0c);
+ // HID raw mode header
+ xmit(0x9f);
+ xmit(0x0a); // Length
+ xmit(0xa1); // DATA(Input)
+ xmit(0x01); // Report ID
+ xmit(report->mods);
+ xmit(0x00); // reserved byte(always 0)
+ xmit(report->keys[0]);
+ xmit(report->keys[1]);
+ xmit(report->keys[2]);
+ xmit(report->keys[3]);
+ xmit(report->keys[4]);
+ xmit(report->keys[5]);
+ MUX_FOOTER(0x01);
+}
+
+static void send_mouse(report_mouse_t *report)
+{
+#if defined(MOUSEKEY_ENABLE) || defined(PS2_MOUSE_ENABLE)
+ if (!iwrap_connected() && !iwrap_check_connection()) return;
+ MUX_HEADER(0x01, 0x09);
+ // HID raw mode header
+ xmit(0x9f);
+ xmit(0x07); // Length
+ xmit(0xa1); // DATA(Input)
+ xmit(0x02); // Report ID
+ xmit(report->buttons);
+ xmit(report->x);
+ xmit(report->y);
+ xmit(report->v);
+ xmit(report->h);
+ MUX_FOOTER(0x01);
+#endif
+}
+
+static void send_system(uint16_t data)
+{
+ /* not supported */
+}
+
+static void send_consumer(uint16_t data)
+{
+#ifdef EXTRAKEY_ENABLE
+ static uint16_t last_data = 0;
+ uint8_t bits1 = 0;
+ uint8_t bits2 = 0;
+ uint8_t bits3 = 0;
+
+ if (!iwrap_connected() && !iwrap_check_connection()) return;
+ if (data == last_data) return;
+ last_data = data;
+
+ // 3.10 HID raw mode(iWRAP_HID_Application_Note.pdf)
+ switch (data) {
+ case AUDIO_VOL_UP:
+ bits1 = 0x01;
+ break;
+ case AUDIO_VOL_DOWN:
+ bits1 = 0x02;
+ break;
+ case AUDIO_MUTE:
+ bits1 = 0x04;
+ break;
+ case TRANSPORT_PLAY_PAUSE:
+ bits1 = 0x08;
+ break;
+ case TRANSPORT_NEXT_TRACK:
+ bits1 = 0x10;
+ break;
+ case TRANSPORT_PREV_TRACK:
+ bits1 = 0x20;
+ break;
+ case TRANSPORT_STOP:
+ bits1 = 0x40;
+ break;
+ case TRANSPORT_EJECT:
+ bits1 = 0x80;
+ break;
+ case AL_EMAIL:
+ bits2 = 0x01;
+ break;
+ case AC_SEARCH:
+ bits2 = 0x02;
+ break;
+ case AC_BOOKMARKS:
+ bits2 = 0x04;
+ break;
+ case AC_HOME:
+ bits2 = 0x08;
+ break;
+ case AC_BACK:
+ bits2 = 0x10;
+ break;
+ case AC_FORWARD:
+ bits2 = 0x20;
+ break;
+ case AC_STOP:
+ bits2 = 0x40;
+ break;
+ case AC_REFRESH:
+ bits2 = 0x80;
+ break;
+ case AL_CC_CONFIG:
+ bits3 = 0x01;
+ break;
+ case AL_CALCULATOR:
+ bits3 = 0x04;
+ break;
+ case AL_LOCK:
+ bits3 = 0x08;
+ break;
+ case AL_LOCAL_BROWSER:
+ bits3 = 0x10;
+ break;
+ case AC_MINIMIZE:
+ bits3 = 0x20;
+ break;
+ case TRANSPORT_RECORD:
+ bits3 = 0x40;
+ break;
+ case TRANSPORT_REWIND:
+ bits3 = 0x80;
+ break;
+ }
+
+ MUX_HEADER(0x01, 0x07);
+ xmit(0x9f);
+ xmit(0x05); // Length
+ xmit(0xa1); // DATA(Input)
+ xmit(0x03); // Report ID
+ xmit(bits1);
+ xmit(bits2);
+ xmit(bits3);
+ MUX_FOOTER(0x01);
+#endif
+}
diff --git a/tmk_core/protocol/iwrap/iwrap.h b/tmk_core/protocol/iwrap/iwrap.h
new file mode 100644
index 000000000..ffaad9395
--- /dev/null
+++ b/tmk_core/protocol/iwrap/iwrap.h
@@ -0,0 +1,49 @@
+/*
+Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef IWRAP_H
+#define IWRAP_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "host_driver.h"
+
+
+/* enable iWRAP MUX mode */
+#define MUX_MODE
+
+
+host_driver_t *iwrap_driver(void);
+
+void iwrap_init(void);
+void iwrap_send(const char *s);
+void iwrap_mux_send(const char *s);
+void iwrap_buf_send(void);
+void iwrap_buf_add(uint8_t c);
+void iwrap_buf_del(void);
+
+void iwrap_call(void);
+void iwrap_kill(void);
+void iwrap_unpair(void);
+void iwrap_sleep(void);
+void iwrap_sniff(void);
+void iwrap_subrate(void);
+bool iwrap_failed(void);
+uint8_t iwrap_connected(void);
+uint8_t iwrap_check_connection(void);
+
+#endif
diff --git a/tmk_core/protocol/iwrap/main.c b/tmk_core/protocol/iwrap/main.c
new file mode 100644
index 000000000..3abdce8df
--- /dev/null
+++ b/tmk_core/protocol/iwrap/main.c
@@ -0,0 +1,376 @@
+/*
+Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+#include <stdint.h>
+#include <avr/interrupt.h>
+#include <avr/io.h>
+//#include <avr/wdt.h>
+#include "wd.h" // in order to use watchdog in interrupt mode
+#include <avr/sleep.h>
+#include <util/delay.h>
+#include <avr/power.h>
+#include "keyboard.h"
+#include "matrix.h"
+#include "host.h"
+#include "action.h"
+#include "iwrap.h"
+#ifdef PROTOCOL_VUSB
+# include "vusb.h"
+# include "usbdrv.h"
+#endif
+#include "uart.h"
+#include "suart.h"
+#include "timer.h"
+#include "debug.h"
+#include "keycode.h"
+#include "command.h"
+
+
+static void sleep(uint8_t term);
+static bool console(void);
+static bool console_command(uint8_t c);
+static uint8_t key2asc(uint8_t key);
+
+
+/*
+static void set_prr(void)
+{
+ power_adc_disable();
+ power_spi_disable();
+ power_twi_disable();
+#ifndef TIMER_H
+ //power_timer0_disable(); // used in timer.c
+#endif
+ power_timer1_disable();
+ power_timer2_disable();
+}
+*/
+
+/*
+static void pullup_pins(void)
+{
+ // DDRs are set to 0(input) by default.
+#ifdef PORTA
+ PORTA = 0xFF;
+#endif
+ PORTB = 0xFF;
+ PORTC = 0xFF;
+ PORTD = 0xFF;
+#ifdef PORTE
+ PORTE = 0xFF;
+#endif
+#ifdef PORTE
+ PORTF = 0xFF;
+#endif
+}
+*/
+
+
+#ifdef PROTOCOL_VUSB
+static void disable_vusb(void)
+{
+ // disable interrupt & disconnect to prevent host from enumerating
+ USB_INTR_ENABLE &= ~(1 << USB_INTR_ENABLE_BIT);
+ usbDeviceDisconnect();
+}
+
+static void enable_vusb(void)
+{
+ USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT);
+ usbDeviceConnect();
+}
+
+static void init_vusb(void)
+{
+ uint8_t i = 0;
+
+ usbInit();
+ disable_vusb();
+ /* fake USB disconnect for > 250 ms */
+ while(--i){
+ _delay_ms(1);
+ }
+ enable_vusb();
+}
+#endif
+
+void change_driver(host_driver_t *driver)
+{
+ /*
+ host_clear_keyboard_report();
+ host_swap_keyboard_report();
+ host_clear_keyboard_report();
+ host_send_keyboard_report();
+ */
+ clear_keyboard();
+ _delay_ms(1000);
+ host_set_driver(driver);
+}
+
+
+static bool sleeping = false;
+static bool insomniac = false; // TODO: should be false for power saving
+static uint16_t last_timer = 0;
+
+int main(void)
+{
+ MCUSR = 0;
+ clock_prescale_set(clock_div_1);
+ WD_SET(WD_OFF);
+
+ // power saving: the result is worse than nothing... why?
+ //pullup_pins();
+ //set_prr();
+
+#ifdef PROTOCOL_VUSB
+ disable_vusb();
+#endif
+ uart_init(115200);
+ keyboard_init();
+ print("\nSend BREAK for UART Console Commands.\n");
+
+ // TODO: move to iWRAP/suart file
+ print("suart init\n");
+ // suart init
+ // PC4: Tx Output IDLE(Hi)
+ PORTC |= (1<<4);
+ DDRC |= (1<<4);
+ // PC5: Rx Input(pull-up)
+ PORTC |= (1<<5);
+ DDRC &= ~(1<<5);
+ // suart receive interrut(PC5/PCINT13)
+ PCMSK1 = 0b00100000;
+ PCICR = 0b00000010;
+
+ host_set_driver(iwrap_driver());
+
+ print("iwrap_init()\n");
+ iwrap_init();
+ iwrap_call();
+
+ last_timer = timer_read();
+ while (true) {
+#ifdef PROTOCOL_VUSB
+ if (host_get_driver() == vusb_driver())
+ usbPoll();
+#endif
+ keyboard_task();
+#ifdef PROTOCOL_VUSB
+ if (host_get_driver() == vusb_driver())
+ vusb_transfer_keyboard();
+#endif
+ // TODO: depricated
+ if (matrix_is_modified() || console()) {
+ last_timer = timer_read();
+ sleeping = false;
+ } else if (!sleeping && timer_elapsed(last_timer) > 4000) {
+ sleeping = true;
+ iwrap_check_connection();
+ }
+
+ // TODO: suspend.h
+ if (host_get_driver() == iwrap_driver()) {
+ if (sleeping && !insomniac) {
+ _delay_ms(1); // wait for UART to send
+ iwrap_sleep();
+ sleep(WDTO_60MS);
+ }
+ }
+ }
+}
+
+static void sleep(uint8_t term)
+{
+ WD_SET(WD_IRQ, term);
+
+ cli();
+ set_sleep_mode(SLEEP_MODE_PWR_DOWN);
+ sleep_enable();
+ sleep_bod_disable();
+ sei();
+ sleep_cpu();
+ sleep_disable();
+
+ WD_SET(WD_OFF);
+}
+
+static bool console(void)
+{
+ // Send to Bluetoot module WT12
+ static bool breaked = false;
+ if (!uart_available())
+ return false;
+ else {
+ uint8_t c;
+ c = uart_getchar();
+ uart_putchar(c);
+ switch (c) {
+ case 0x00: // BREAK signal
+ if (!breaked) {
+ print("break(? for help): ");
+ breaked = true;
+ }
+ break;
+ case '\r':
+ uart_putchar('\n');
+ iwrap_buf_send();
+ break;
+ case '\b':
+ iwrap_buf_del();
+ break;
+ default:
+ if (breaked) {
+ print("\n");
+ console_command(c);
+ breaked = false;
+ } else {
+ iwrap_buf_add(c);
+ }
+ break;
+ }
+ return true;
+ }
+}
+
+bool command_extra(uint8_t code)
+{
+ return console_command(key2asc(code));
+}
+
+static bool console_command(uint8_t c)
+{
+ switch (c) {
+ case 'h':
+ case '?':
+ print("\nCommands for Bluetooth(WT12/iWRAP):\n");
+ print("r: reset. software reset by watchdog\n");
+ print("i: insomniac. prevent KB from sleeping\n");
+ print("c: iwrap_call. CALL for BT connection.\n");
+#ifdef PROTOCOL_VUSB
+ print("u: USB mode. switch to USB.\n");
+ print("w: BT mode. switch to Bluetooth.\n");
+#endif
+ print("k: kill first connection.\n");
+ print("Del: unpair first pairing.\n");
+ print("\n");
+ return 0;
+ case 'r':
+ print("reset\n");
+ WD_AVR_RESET();
+ return 1;
+ case 'i':
+ insomniac = !insomniac;
+ if (insomniac)
+ print("insomniac\n");
+ else
+ print("not insomniac\n");
+ return 1;
+ case 'c':
+ print("iwrap_call()\n");
+ iwrap_call();
+ return 1;
+#ifdef PROTOCOL_VUSB
+ case 'u':
+ print("USB mode\n");
+ init_vusb();
+ change_driver(vusb_driver());
+ //iwrap_kill();
+ //iwrap_sleep();
+ // disable suart receive interrut(PC5/PCINT13)
+ PCMSK1 &= ~(0b00100000);
+ PCICR &= ~(0b00000010);
+ return 1;
+ case 'w':
+ print("iWRAP mode\n");
+ change_driver(iwrap_driver());
+ disable_vusb();
+ // enable suart receive interrut(PC5/PCINT13)
+ PCMSK1 |= 0b00100000;
+ PCICR |= 0b00000010;
+ return 1;
+#endif
+ case 'k':
+ print("kill\n");
+ iwrap_kill();
+ return 1;
+ case 0x7F: // DELETE
+ print("unpair\n");
+ iwrap_unpair();
+ return 1;
+ }
+ return 0;
+}
+
+// convert keycode into ascii charactor
+static uint8_t key2asc(uint8_t key)
+{
+ switch (key) {
+ case KC_A: return 'a';
+ case KC_B: return 'b';
+ case KC_C: return 'c';
+ case KC_D: return 'd';
+ case KC_E: return 'e';
+ case KC_F: return 'f';
+ case KC_G: return 'g';
+ case KC_H: return 'h';
+ case KC_I: return 'i';
+ case KC_J: return 'j';
+ case KC_K: return 'k';
+ case KC_L: return 'l';
+ case KC_M: return 'm';
+ case KC_N: return 'n';
+ case KC_O: return 'o';
+ case KC_P: return 'p';
+ case KC_Q: return 'q';
+ case KC_R: return 'r';
+ case KC_S: return 's';
+ case KC_T: return 't';
+ case KC_U: return 'u';
+ case KC_V: return 'v';
+ case KC_W: return 'w';
+ case KC_X: return 'x';
+ case KC_Y: return 'y';
+ case KC_Z: return 'z';
+ case KC_1: return '1';
+ case KC_2: return '2';
+ case KC_3: return '3';
+ case KC_4: return '4';
+ case KC_5: return '5';
+ case KC_6: return '6';
+ case KC_7: return '7';
+ case KC_8: return '8';
+ case KC_9: return '9';
+ case KC_0: return '0';
+ case KC_ENTER: return '\n';
+ case KC_ESCAPE: return 0x1B;
+ case KC_BSPACE: return '\b';
+ case KC_TAB: return '\t';
+ case KC_SPACE: return ' ';
+ case KC_MINUS: return '-';
+ case KC_EQUAL: return '=';
+ case KC_LBRACKET: return '[';
+ case KC_RBRACKET: return ']';
+ case KC_BSLASH: return '\\';
+ case KC_NONUS_HASH: return '\\';
+ case KC_SCOLON: return ';';
+ case KC_QUOTE: return '\'';
+ case KC_GRAVE: return '`';
+ case KC_COMMA: return ',';
+ case KC_DOT: return '.';
+ case KC_SLASH: return '/';
+ default: return 0x00;
+ }
+}
diff --git a/tmk_core/protocol/iwrap/mux_exit.rb b/tmk_core/protocol/iwrap/mux_exit.rb
new file mode 100644
index 000000000..1f6be48af
--- /dev/null
+++ b/tmk_core/protocol/iwrap/mux_exit.rb
@@ -0,0 +1,7 @@
+#
+# Rescue from Bluegiga iWRAP MUX mode
+# 6.75 of iWRAP5_User_Guid.pdf
+#
+[0xBF, 0xFF, 0x00, 0x11, 0x53, 0x45, 0x54, 0x20, 0x43, 0x4f, 0x4e, 0x54, 0x52, 0x4f, 0x4c, 0x20, 0x4d, 0x55, 0x58, 0x20, 0x30, 0x00].each do |x|
+ print x.chr
+end
diff --git a/tmk_core/protocol/iwrap/suart.S b/tmk_core/protocol/iwrap/suart.S
new file mode 100644
index 000000000..a873515e1
--- /dev/null
+++ b/tmk_core/protocol/iwrap/suart.S
@@ -0,0 +1,156 @@
+;---------------------------------------------------------------------------;
+; Software implemented UART module ;
+; (C)ChaN, 2005 (http://elm-chan.org/) ;
+;---------------------------------------------------------------------------;
+; Bit rate settings:
+;
+; 1MHz 2MHz 4MHz 6MHz 8MHz 10MHz 12MHz 16MHz 20MHz
+; 2.4kbps 138 - - - - - - - -
+; 4.8kbps 68 138 - - - - - - -
+; 9.6kbps 33 68 138 208 - - - - -
+; 19.2kbps - 33 68 102 138 173 208 - -
+; 38.4kbps - - 33 50 68 85 102 138 172
+; 57.6kbps - - 21 33 44 56 68 91 114
+; 115.2kbps - - - - 21 27 33 44 56
+
+.nolist
+#include <avr/io.h>
+.list
+
+#define BPS 102 /* Bit delay. (see above table) */
+#define BIDIR 0 /* 0:Separated Tx/Rx, 1:Shared Tx/Rx */
+
+#define OUT_1 sbi _SFR_IO_ADDR(SUART_OUT_PORT), SUART_OUT_BIT /* Output 1 */
+#define OUT_0 cbi _SFR_IO_ADDR(SUART_OUT_PORT), SUART_OUT_BIT /* Output 0 */
+#define SKIP_IN_1 sbis _SFR_IO_ADDR(SUART_IN_PIN), SUART_IN_BIT /* Skip if 1 */
+#define SKIP_IN_0 sbic _SFR_IO_ADDR(SUART_IN_PIN), SUART_IN_BIT /* Skip if 0 */
+
+
+
+#ifdef SPM_PAGESIZE
+.macro _LPMI reg
+ lpm \reg, Z+
+.endm
+.macro _MOVW dh,dl, sh,sl
+ movw \dl, \sl
+.endm
+#else
+.macro _LPMI reg
+ lpm
+ mov \reg, r0
+ adiw ZL, 1
+.endm
+.macro _MOVW dh,dl, sh,sl
+ mov \dl, \sl
+ mov \dh, \sh
+.endm
+#endif
+
+
+
+;---------------------------------------------------------------------------;
+; Transmit a byte in serial format of N81
+;
+;Prototype: void xmit (uint8_t data);
+;Size: 16 words
+
+.global xmit
+.func xmit
+xmit:
+#if BIDIR
+ ldi r23, BPS-1 ;Pre-idle time for bidirectional data line
+5: dec r23 ;
+ brne 5b ;/
+#endif
+ in r0, _SFR_IO_ADDR(SREG) ;Save flags
+
+ com r24 ;C = start bit
+ ldi r25, 10 ;Bit counter
+ cli ;Start critical section
+
+1: ldi r23, BPS-1 ;----- Bit transferring loop
+2: dec r23 ;Wait for a bit time
+ brne 2b ;/
+ brcs 3f ;MISO = bit to be sent
+ OUT_1 ;
+3: brcc 4f ;
+ OUT_0 ;/
+4: lsr r24 ;Get next bit into C
+ dec r25 ;All bits sent?
+ brne 1b ; no, coutinue
+
+ out _SFR_IO_ADDR(SREG), r0 ;End of critical section
+ ret
+.endfunc
+
+
+
+;---------------------------------------------------------------------------;
+; Receive a byte
+;
+;Prototype: uint8_t rcvr (void);
+;Size: 19 words
+
+.global rcvr
+.func rcvr
+rcvr:
+ in r0, _SFR_IO_ADDR(SREG) ;Save flags
+
+ ldi r24, 0x80 ;Receiving shift reg
+ cli ;Start critical section
+
+1: SKIP_IN_1 ;Wait for idle
+ rjmp 1b
+2: SKIP_IN_0 ;Wait for start bit
+ rjmp 2b
+ ldi r25, BPS/2 ;Wait for half bit time
+3: dec r25
+ brne 3b
+
+4: ldi r25, BPS ;----- Bit receiving loop
+5: dec r25 ;Wait for a bit time
+ brne 5b ;/
+ lsr r24 ;Next bit
+ SKIP_IN_0 ;Get a data bit into r24.7
+ ori r24, 0x80
+ brcc 4b ;All bits received? no, continue
+
+ out _SFR_IO_ADDR(SREG), r0 ;End of critical section
+ ret
+.endfunc
+
+
+; Not wait for start bit. This should be called after detecting start bit.
+.global recv
+.func recv
+recv:
+ in r0, _SFR_IO_ADDR(SREG) ;Save flags
+
+ ldi r24, 0x80 ;Receiving shift reg
+ cli ;Start critical section
+
+;1: SKIP_IN_1 ;Wait for idle
+; rjmp 1b
+;2: SKIP_IN_0 ;Wait for start bit
+; rjmp 2b
+ ldi r25, BPS/2 ;Wait for half bit time
+3: dec r25
+ brne 3b
+
+4: ldi r25, BPS ;----- Bit receiving loop
+5: dec r25 ;Wait for a bit time
+ brne 5b ;/
+ lsr r24 ;Next bit
+ SKIP_IN_0 ;Get a data bit into r24.7
+ ori r24, 0x80
+ brcc 4b ;All bits received? no, continue
+
+ ldi r25, BPS/2 ;Wait for half bit time
+6: dec r25
+ brne 6b
+7: SKIP_IN_1 ;Wait for stop bit
+ rjmp 7b
+
+ out _SFR_IO_ADDR(SREG), r0 ;End of critical section
+ ret
+.endfunc
diff --git a/tmk_core/protocol/iwrap/suart.h b/tmk_core/protocol/iwrap/suart.h
new file mode 100644
index 000000000..7d92be069
--- /dev/null
+++ b/tmk_core/protocol/iwrap/suart.h
@@ -0,0 +1,8 @@
+#ifndef SUART
+#define SUART
+
+void xmit(uint8_t);
+uint8_t rcvr(void);
+uint8_t recv(void);
+
+#endif /* SUART */
diff --git a/tmk_core/protocol/iwrap/wd.h b/tmk_core/protocol/iwrap/wd.h
new file mode 100644
index 000000000..12395bf69
--- /dev/null
+++ b/tmk_core/protocol/iwrap/wd.h
@@ -0,0 +1,159 @@
+/* This is from http://www.mtcnet.net/~henryvm/wdt/ */
+#ifndef _AVR_WD_H_
+#define _AVR_WD_H_
+
+#include <avr/io.h>
+
+/*
+Copyright (c) 2009, Curt Van Maanen
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+
+include usage-
+ #include "wd.h" //if in same directory as project
+ #include <avr/wd.h> //if wd.h is in avr directory
+
+set watchdog modes and prescale
+
+usage-
+ WD_SET(mode,[timeout]); //prescale always set
+
+modes-
+ WD_OFF disabled
+ WD_RST normal reset mode
+ WD_IRQ interrupt only mode (if supported)
+ WD_RST_IRQ interrupt+reset mode (if supported)
+
+timeout-
+ WDTO_15MS default if no timeout provided
+ WDTO_30MS
+ WDTO_60MS
+ WDTO_120MS
+ WDTO_250MS
+ WDTO_500MS
+ WDTO_1S
+ WDTO_2S
+ WDTO_4S (if supported)
+ WDTO_8S (if supported)
+
+examples-
+ WD_SET(WD_RST,WDTO_1S); //reset mode, 1s timeout
+ WD_SET(WD_OFF); //watchdog disabled (if not fused on)
+ WD_SET(WD_RST); //reset mode, 15ms (default timeout)
+ WD_SET(WD_IRQ,WDTO_120MS); //interrupt only mode, 120ms timeout
+ WD_SET(WD_RST_IRQ,WDTO_2S); //interrupt+reset mode, 2S timeout
+
+
+for enhanced watchdogs, if the watchdog is not being used WDRF should be
+cleared on every power up or reset, along with disabling the watchdog-
+ WD_DISABLE(); //clear WDRF, then turn off watchdog
+
+*/
+
+//reset registers to the same name (MCUCSR)
+#if !defined(MCUCSR)
+#define MCUCSR MCUSR
+#endif
+
+//watchdog registers to the same name (WDTCSR)
+#if !defined(WDTCSR)
+#define WDTCSR WDTCR
+#endif
+
+//if enhanced watchdog, define irq values, create disable macro
+#if defined(WDIF)
+#define WD_IRQ 0xC0
+#define WD_RST_IRQ 0xC8
+#define WD_DISABLE() do{ \
+ MCUCSR &= ~(1<<WDRF); \
+ WD_SET(WD_OFF); \
+ }while(0)
+#endif
+
+//all watchdogs
+#define WD_RST 8
+#define WD_OFF 0
+
+//prescale values
+#define WDTO_15MS 0
+#define WDTO_30MS 1
+#define WDTO_60MS 2
+#define WDTO_120MS 3
+#define WDTO_250MS 4
+#define WDTO_500MS 5
+#define WDTO_1S 6
+#define WDTO_2S 7
+
+//prescale values for avrs with WDP3
+#if defined(WDP3)
+#define WDTO_4S 0x20
+#define WDTO_8S 0x21
+#endif
+
+//watchdog reset
+#define WDR() __asm__ __volatile__("wdr")
+
+//avr reset using watchdog
+#define WD_AVR_RESET() do{ \
+ __asm__ __volatile__("cli"); \
+ WD_SET_UNSAFE(WD_RST); \
+ while(1); \
+ }while(0)
+
+/*set the watchdog-
+1. save SREG
+2. turn off irq's
+3. reset watchdog timer
+4. enable watchdog change
+5. write watchdog value
+6. restore SREG (restoring irq status)
+*/
+#define WD_SET(val,...) \
+ __asm__ __volatile__( \
+ "in __tmp_reg__,__SREG__" "\n\t" \
+ "cli" "\n\t" \
+ "wdr" "\n\t" \
+ "sts %[wdreg],%[wden]" "\n\t" \
+ "sts %[wdreg],%[wdval]" "\n\t" \
+ "out __SREG__,__tmp_reg__" "\n\t" \
+ : \
+ : [wdreg] "M" (&WDTCSR), \
+ [wden] "r" ((uint8_t)(0x18)), \
+ [wdval] "r" ((uint8_t)(val|(__VA_ARGS__+0))) \
+ : "r0" \
+)
+
+/*set the watchdog when I bit in SREG known to be clear-
+1. reset watchdog timer
+2. enable watchdog change
+5. write watchdog value
+*/
+#define WD_SET_UNSAFE(val,...) \
+ __asm__ __volatile__( \
+ "wdr" "\n\t" \
+ "sts %[wdreg],%[wden]" "\n\t" \
+ "sts %[wdreg],%[wdval]" "\n\t" \
+ : \
+ : [wdreg] "M" (&WDTCSR), \
+ [wden] "r" ((uint8_t)(0x18)), \
+ [wdval] "r" ((uint8_t)(val|(__VA_ARGS__+0))) \
+)
+
+
+//for compatibility with avr/wdt.h
+#define wdt_enable(val) WD_SET(WD_RST,val)
+#define wdt_disable() WD_SET(WD_OFF)
+
+
+#endif /* _AVR_WD_H_ */
diff --git a/tmk_core/protocol/lufa.mk b/tmk_core/protocol/lufa.mk
new file mode 100644
index 000000000..4d005debc
--- /dev/null
+++ b/tmk_core/protocol/lufa.mk
@@ -0,0 +1,81 @@
+LUFA_DIR = protocol/lufa
+
+# Path to the LUFA library
+LUFA_PATH = $(LIB_PATH)/lufa
+
+
+# Create the LUFA source path variables by including the LUFA makefile
+ifneq (, $(wildcard $(LUFA_PATH)/LUFA/Build/lufa_sources.mk))
+ # New build system from 20120730
+ LUFA_ROOT_PATH = $(LUFA_PATH)/LUFA
+ DMBS_LUFA_PATH = $(LUFA_PATH)/LUFA/Build/LUFA
+ include $(LUFA_PATH)/LUFA/Build/lufa_sources.mk
+else
+ include $(LUFA_PATH)/LUFA/makefile
+endif
+
+LUFA_SRC = lufa.c \
+ descriptor.c \
+ outputselect.c \
+ $(LUFA_SRC_USB)
+
+ifeq ($(strip $(MIDI_ENABLE)), yes)
+ include $(TMK_PATH)/protocol/midi.mk
+endif
+
+ifeq ($(strip $(BLUETOOTH_ENABLE)), yes)
+ LUFA_SRC += $(LUFA_DIR)/bluetooth.c \
+ $(TMK_DIR)/protocol/serial_uart.c
+endif
+
+ifeq ($(strip $(BLUETOOTH)), AdafruitBLE)
+ LUFA_SRC += $(LUFA_DIR)/adafruit_ble.cpp
+endif
+
+ifeq ($(strip $(BLUETOOTH)), AdafruitEZKey)
+ LUFA_SRC += $(LUFA_DIR)/bluetooth.c \
+ $(TMK_DIR)/protocol/serial_uart.c
+endif
+
+ifeq ($(strip $(BLUETOOTH)), RN42)
+ LUFA_SRC += $(LUFA_DIR)/bluetooth.c \
+ $(TMK_DIR)/protocol/serial_uart.c
+endif
+
+ifeq ($(strip $(VIRTSER_ENABLE)), yes)
+ LUFA_SRC += $(LUFA_ROOT_PATH)/Drivers/USB/Class/Device/CDCClassDevice.c
+endif
+
+SRC += $(LUFA_SRC)
+
+# Search Path
+VPATH += $(TMK_PATH)/$(LUFA_DIR)
+VPATH += $(LUFA_PATH)
+
+# Option modules
+#ifdef $(or MOUSEKEY_ENABLE, PS2_MOUSE_ENABLE)
+#endif
+
+#ifdef EXTRAKEY_ENABLE
+#endif
+
+# LUFA library compile-time options and predefined tokens
+LUFA_OPTS = -DUSB_DEVICE_ONLY
+LUFA_OPTS += -DUSE_FLASH_DESCRIPTORS
+LUFA_OPTS += -DUSE_STATIC_OPTIONS="(USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)"
+#LUFA_OPTS += -DINTERRUPT_CONTROL_ENDPOINT
+LUFA_OPTS += -DFIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -DFIXED_CONTROL_ENDPOINT_SIZE=8
+LUFA_OPTS += -DFIXED_NUM_CONFIGURATIONS=1
+
+# Remote wakeup fix for ATmega32U2 https://github.com/tmk/tmk_keyboard/issues/361
+ifeq ($(MCU),atmega32u2)
+ LUFA_OPTS += -DNO_LIMITED_CONTROLLER_CONNECT
+endif
+
+OPT_DEFS += -DF_USB=$(F_USB)UL
+OPT_DEFS += -DARCH=ARCH_$(ARCH)
+OPT_DEFS += $(LUFA_OPTS)
+
+# This indicates using LUFA stack
+OPT_DEFS += -DPROTOCOL_LUFA
diff --git a/tmk_core/protocol/lufa/adafruit_ble.cpp b/tmk_core/protocol/lufa/adafruit_ble.cpp
new file mode 100644
index 000000000..bee6bb2c1
--- /dev/null
+++ b/tmk_core/protocol/lufa/adafruit_ble.cpp
@@ -0,0 +1,823 @@
+#include "adafruit_ble.h"
+#include <stdio.h>
+#include <stdlib.h>
+#include <alloca.h>
+#include <util/delay.h>
+#include <util/atomic.h>
+#include "debug.h"
+#include "pincontrol.h"
+#include "timer.h"
+#include "action_util.h"
+#include "ringbuffer.hpp"
+#include <string.h>
+
+// These are the pin assignments for the 32u4 boards.
+// You may define them to something else in your config.h
+// if yours is wired up differently.
+#ifndef AdafruitBleResetPin
+#define AdafruitBleResetPin D4
+#endif
+
+#ifndef AdafruitBleCSPin
+#define AdafruitBleCSPin B4
+#endif
+
+#ifndef AdafruitBleIRQPin
+#define AdafruitBleIRQPin E6
+#endif
+
+
+#define SAMPLE_BATTERY
+#define ConnectionUpdateInterval 1000 /* milliseconds */
+
+static struct {
+ bool is_connected;
+ bool initialized;
+ bool configured;
+
+#define ProbedEvents 1
+#define UsingEvents 2
+ bool event_flags;
+
+#ifdef SAMPLE_BATTERY
+ uint16_t last_battery_update;
+ uint32_t vbat;
+#endif
+ uint16_t last_connection_update;
+} state;
+
+// Commands are encoded using SDEP and sent via SPI
+// https://github.com/adafruit/Adafruit_BluefruitLE_nRF51/blob/master/SDEP.md
+
+#define SdepMaxPayload 16
+struct sdep_msg {
+ uint8_t type;
+ uint8_t cmd_low;
+ uint8_t cmd_high;
+ struct __attribute__((packed)) {
+ uint8_t len:7;
+ uint8_t more:1;
+ };
+ uint8_t payload[SdepMaxPayload];
+} __attribute__((packed));
+
+// The recv latency is relatively high, so when we're hammering keys quickly,
+// we want to avoid waiting for the responses in the matrix loop. We maintain
+// a short queue for that. Since there is quite a lot of space overhead for
+// the AT command representation wrapped up in SDEP, we queue the minimal
+// information here.
+
+enum queue_type {
+ QTKeyReport, // 1-byte modifier + 6-byte key report
+ QTConsumer, // 16-bit key code
+#ifdef MOUSE_ENABLE
+ QTMouseMove, // 4-byte mouse report
+#endif
+};
+
+struct queue_item {
+ enum queue_type queue_type;
+ uint16_t added;
+ union __attribute__((packed)) {
+ struct __attribute__((packed)) {
+ uint8_t modifier;
+ uint8_t keys[6];
+ } key;
+
+ uint16_t consumer;
+ struct __attribute__((packed)) {
+ int8_t x, y, scroll, pan;
+ uint8_t buttons;
+ } mousemove;
+ };
+};
+
+// Items that we wish to send
+static RingBuffer<queue_item, 40> send_buf;
+// Pending response; while pending, we can't send any more requests.
+// This records the time at which we sent the command for which we
+// are expecting a response.
+static RingBuffer<uint16_t, 2> resp_buf;
+
+static bool process_queue_item(struct queue_item *item, uint16_t timeout);
+
+enum sdep_type {
+ SdepCommand = 0x10,
+ SdepResponse = 0x20,
+ SdepAlert = 0x40,
+ SdepError = 0x80,
+ SdepSlaveNotReady = 0xfe, // Try again later
+ SdepSlaveOverflow = 0xff, // You read more data than is available
+};
+
+enum ble_cmd {
+ BleInitialize = 0xbeef,
+ BleAtWrapper = 0x0a00,
+ BleUartTx = 0x0a01,
+ BleUartRx = 0x0a02,
+};
+
+enum ble_system_event_bits {
+ BleSystemConnected = 0,
+ BleSystemDisconnected = 1,
+ BleSystemUartRx = 8,
+ BleSystemMidiRx = 10,
+};
+
+// The SDEP.md file says 2MHz but the web page and the sample driver
+// both use 4MHz
+#define SpiBusSpeed 4000000
+
+#define SdepTimeout 150 /* milliseconds */
+#define SdepShortTimeout 10 /* milliseconds */
+#define SdepBackOff 25 /* microseconds */
+#define BatteryUpdateInterval 10000 /* milliseconds */
+
+static bool at_command(const char *cmd, char *resp, uint16_t resplen,
+ bool verbose, uint16_t timeout = SdepTimeout);
+static bool at_command_P(const char *cmd, char *resp, uint16_t resplen,
+ bool verbose = false);
+
+struct SPI_Settings {
+ uint8_t spcr, spsr;
+};
+
+static struct SPI_Settings spi;
+
+// Initialize 4Mhz MSBFIRST MODE0
+void SPI_init(struct SPI_Settings *spi) {
+ spi->spcr = _BV(SPE) | _BV(MSTR);
+ spi->spsr = _BV(SPI2X);
+
+ static_assert(SpiBusSpeed == F_CPU / 2, "hard coded at 4Mhz");
+
+ ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {
+ // Ensure that SS is OUTPUT High
+ digitalWrite(B0, PinLevelHigh);
+ pinMode(B0, PinDirectionOutput);
+
+ SPCR |= _BV(MSTR);
+ SPCR |= _BV(SPE);
+ pinMode(B1 /* SCK */, PinDirectionOutput);
+ pinMode(B2 /* MOSI */, PinDirectionOutput);
+ }
+}
+
+static inline void SPI_begin(struct SPI_Settings*spi) {
+ SPCR = spi->spcr;
+ SPSR = spi->spsr;
+}
+
+static inline uint8_t SPI_TransferByte(uint8_t data) {
+ SPDR = data;
+ asm volatile("nop");
+ while (!(SPSR & _BV(SPIF))) {
+ ; // wait
+ }
+ return SPDR;
+}
+
+static inline void spi_send_bytes(const uint8_t *buf, uint8_t len) {
+ if (len == 0) return;
+ const uint8_t *end = buf + len;
+ while (buf < end) {
+ SPDR = *buf;
+ while (!(SPSR & _BV(SPIF))) {
+ ; // wait
+ }
+ ++buf;
+ }
+}
+
+static inline uint16_t spi_read_byte(void) {
+ return SPI_TransferByte(0x00 /* dummy */);
+}
+
+static inline void spi_recv_bytes(uint8_t *buf, uint8_t len) {
+ const uint8_t *end = buf + len;
+ if (len == 0) return;
+ while (buf < end) {
+ SPDR = 0; // write a dummy to initiate read
+ while (!(SPSR & _BV(SPIF))) {
+ ; // wait
+ }
+ *buf = SPDR;
+ ++buf;
+ }
+}
+
+#if 0
+static void dump_pkt(const struct sdep_msg *msg) {
+ print("pkt: type=");
+ print_hex8(msg->type);
+ print(" cmd=");
+ print_hex8(msg->cmd_high);
+ print_hex8(msg->cmd_low);
+ print(" len=");
+ print_hex8(msg->len);
+ print(" more=");
+ print_hex8(msg->more);
+ print("\n");
+}
+#endif
+
+// Send a single SDEP packet
+static bool sdep_send_pkt(const struct sdep_msg *msg, uint16_t timeout) {
+ SPI_begin(&spi);
+
+ digitalWrite(AdafruitBleCSPin, PinLevelLow);
+ uint16_t timerStart = timer_read();
+ bool success = false;
+ bool ready = false;
+
+ do {
+ ready = SPI_TransferByte(msg->type) != SdepSlaveNotReady;
+ if (ready) {
+ break;
+ }
+
+ // Release it and let it initialize
+ digitalWrite(AdafruitBleCSPin, PinLevelHigh);
+ _delay_us(SdepBackOff);
+ digitalWrite(AdafruitBleCSPin, PinLevelLow);
+ } while (timer_elapsed(timerStart) < timeout);
+
+ if (ready) {
+ // Slave is ready; send the rest of the packet
+ spi_send_bytes(&msg->cmd_low,
+ sizeof(*msg) - (1 + sizeof(msg->payload)) + msg->len);
+ success = true;
+ }
+
+ digitalWrite(AdafruitBleCSPin, PinLevelHigh);
+
+ return success;
+}
+
+static inline void sdep_build_pkt(struct sdep_msg *msg, uint16_t command,
+ const uint8_t *payload, uint8_t len,
+ bool moredata) {
+ msg->type = SdepCommand;
+ msg->cmd_low = command & 0xff;
+ msg->cmd_high = command >> 8;
+ msg->len = len;
+ msg->more = (moredata && len == SdepMaxPayload) ? 1 : 0;
+
+ static_assert(sizeof(*msg) == 20, "msg is correctly packed");
+
+ memcpy(msg->payload, payload, len);
+}
+
+// Read a single SDEP packet
+static bool sdep_recv_pkt(struct sdep_msg *msg, uint16_t timeout) {
+ bool success = false;
+ uint16_t timerStart = timer_read();
+ bool ready = false;
+
+ do {
+ ready = digitalRead(AdafruitBleIRQPin);
+ if (ready) {
+ break;
+ }
+ _delay_us(1);
+ } while (timer_elapsed(timerStart) < timeout);
+
+ if (ready) {
+ SPI_begin(&spi);
+
+ digitalWrite(AdafruitBleCSPin, PinLevelLow);
+
+ do {
+ // Read the command type, waiting for the data to be ready
+ msg->type = spi_read_byte();
+ if (msg->type == SdepSlaveNotReady || msg->type == SdepSlaveOverflow) {
+ // Release it and let it initialize
+ digitalWrite(AdafruitBleCSPin, PinLevelHigh);
+ _delay_us(SdepBackOff);
+ digitalWrite(AdafruitBleCSPin, PinLevelLow);
+ continue;
+ }
+
+ // Read the rest of the header
+ spi_recv_bytes(&msg->cmd_low, sizeof(*msg) - (1 + sizeof(msg->payload)));
+
+ // and get the payload if there is any
+ if (msg->len <= SdepMaxPayload) {
+ spi_recv_bytes(msg->payload, msg->len);
+ }
+ success = true;
+ break;
+ } while (timer_elapsed(timerStart) < timeout);
+
+ digitalWrite(AdafruitBleCSPin, PinLevelHigh);
+ }
+ return success;
+}
+
+static void resp_buf_read_one(bool greedy) {
+ uint16_t last_send;
+ if (!resp_buf.peek(last_send)) {
+ return;
+ }
+
+ if (digitalRead(AdafruitBleIRQPin)) {
+ struct sdep_msg msg;
+
+again:
+ if (sdep_recv_pkt(&msg, SdepTimeout)) {
+ if (!msg.more) {
+ // We got it; consume this entry
+ resp_buf.get(last_send);
+ dprintf("recv latency %dms\n", TIMER_DIFF_16(timer_read(), last_send));
+ }
+
+ if (greedy && resp_buf.peek(last_send) && digitalRead(AdafruitBleIRQPin)) {
+ goto again;
+ }
+ }
+
+ } else if (timer_elapsed(last_send) > SdepTimeout * 2) {
+ dprintf("waiting_for_result: timeout, resp_buf size %d\n",
+ (int)resp_buf.size());
+
+ // Timed out: consume this entry
+ resp_buf.get(last_send);
+ }
+}
+
+static void send_buf_send_one(uint16_t timeout = SdepTimeout) {
+ struct queue_item item;
+
+ // Don't send anything more until we get an ACK
+ if (!resp_buf.empty()) {
+ return;
+ }
+
+ if (!send_buf.peek(item)) {
+ return;
+ }
+ if (process_queue_item(&item, timeout)) {
+ // commit that peek
+ send_buf.get(item);
+ dprintf("send_buf_send_one: have %d remaining\n", (int)send_buf.size());
+ } else {
+ dprint("failed to send, will retry\n");
+ _delay_ms(SdepTimeout);
+ resp_buf_read_one(true);
+ }
+}
+
+static void resp_buf_wait(const char *cmd) {
+ bool didPrint = false;
+ while (!resp_buf.empty()) {
+ if (!didPrint) {
+ dprintf("wait on buf for %s\n", cmd);
+ didPrint = true;
+ }
+ resp_buf_read_one(true);
+ }
+}
+
+static bool ble_init(void) {
+ state.initialized = false;
+ state.configured = false;
+ state.is_connected = false;
+
+ pinMode(AdafruitBleIRQPin, PinDirectionInput);
+ pinMode(AdafruitBleCSPin, PinDirectionOutput);
+ digitalWrite(AdafruitBleCSPin, PinLevelHigh);
+
+ SPI_init(&spi);
+
+ // Perform a hardware reset
+ pinMode(AdafruitBleResetPin, PinDirectionOutput);
+ digitalWrite(AdafruitBleResetPin, PinLevelHigh);
+ digitalWrite(AdafruitBleResetPin, PinLevelLow);
+ _delay_ms(10);
+ digitalWrite(AdafruitBleResetPin, PinLevelHigh);
+
+ _delay_ms(1000); // Give it a second to initialize
+
+ state.initialized = true;
+ return state.initialized;
+}
+
+static inline uint8_t min(uint8_t a, uint8_t b) {
+ return a < b ? a : b;
+}
+
+static bool read_response(char *resp, uint16_t resplen, bool verbose) {
+ char *dest = resp;
+ char *end = dest + resplen;
+
+ while (true) {
+ struct sdep_msg msg;
+
+ if (!sdep_recv_pkt(&msg, 2 * SdepTimeout)) {
+ dprint("sdep_recv_pkt failed\n");
+ return false;
+ }
+
+ if (msg.type != SdepResponse) {
+ *resp = 0;
+ return false;
+ }
+
+ uint8_t len = min(msg.len, end - dest);
+ if (len > 0) {
+ memcpy(dest, msg.payload, len);
+ dest += len;
+ }
+
+ if (!msg.more) {
+ // No more data is expected!
+ break;
+ }
+ }
+
+ // Ensure the response is NUL terminated
+ *dest = 0;
+
+ // "Parse" the result text; we want to snip off the trailing OK or ERROR line
+ // Rewind past the possible trailing CRLF so that we can strip it
+ --dest;
+ while (dest > resp && (dest[0] == '\n' || dest[0] == '\r')) {
+ *dest = 0;
+ --dest;
+ }
+
+ // Look back for start of preceeding line
+ char *last_line = strrchr(resp, '\n');
+ if (last_line) {
+ ++last_line;
+ } else {
+ last_line = resp;
+ }
+
+ bool success = false;
+ static const char kOK[] PROGMEM = "OK";
+
+ success = !strcmp_P(last_line, kOK );
+
+ if (verbose || !success) {
+ dprintf("result: %s\n", resp);
+ }
+ return success;
+}
+
+static bool at_command(const char *cmd, char *resp, uint16_t resplen,
+ bool verbose, uint16_t timeout) {
+ const char *end = cmd + strlen(cmd);
+ struct sdep_msg msg;
+
+ if (verbose) {
+ dprintf("ble send: %s\n", cmd);
+ }
+
+ if (resp) {
+ // They want to decode the response, so we need to flush and wait
+ // for all pending I/O to finish before we start this one, so
+ // that we don't confuse the results
+ resp_buf_wait(cmd);
+ *resp = 0;
+ }
+
+ // Fragment the command into a series of SDEP packets
+ while (end - cmd > SdepMaxPayload) {
+ sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, SdepMaxPayload, true);
+ if (!sdep_send_pkt(&msg, timeout)) {
+ return false;
+ }
+ cmd += SdepMaxPayload;
+ }
+
+ sdep_build_pkt(&msg, BleAtWrapper, (uint8_t *)cmd, end - cmd, false);
+ if (!sdep_send_pkt(&msg, timeout)) {
+ return false;
+ }
+
+ if (resp == NULL) {
+ auto now = timer_read();
+ while (!resp_buf.enqueue(now)) {
+ resp_buf_read_one(false);
+ }
+ auto later = timer_read();
+ if (TIMER_DIFF_16(later, now) > 0) {
+ dprintf("waited %dms for resp_buf\n", TIMER_DIFF_16(later, now));
+ }
+ return true;
+ }
+
+ return read_response(resp, resplen, verbose);
+}
+
+bool at_command_P(const char *cmd, char *resp, uint16_t resplen, bool verbose) {
+ auto cmdbuf = (char *)alloca(strlen_P(cmd) + 1);
+ strcpy_P(cmdbuf, cmd);
+ return at_command(cmdbuf, resp, resplen, verbose);
+}
+
+bool adafruit_ble_is_connected(void) {
+ return state.is_connected;
+}
+
+bool adafruit_ble_enable_keyboard(void) {
+ char resbuf[128];
+
+ if (!state.initialized && !ble_init()) {
+ return false;
+ }
+
+ state.configured = false;
+
+ // Disable command echo
+ static const char kEcho[] PROGMEM = "ATE=0";
+ // Make the advertised name match the keyboard
+ static const char kGapDevName[] PROGMEM =
+ "AT+GAPDEVNAME=" STR(PRODUCT) " " STR(DESCRIPTION);
+ // Turn on keyboard support
+ static const char kHidEnOn[] PROGMEM = "AT+BLEHIDEN=1";
+
+ // Adjust intervals to improve latency. This causes the "central"
+ // system (computer/tablet) to poll us every 10-30 ms. We can't
+ // set a smaller value than 10ms, and 30ms seems to be the natural
+ // processing time on my macbook. Keeping it constrained to that
+ // feels reasonable to type to.
+ static const char kGapIntervals[] PROGMEM = "AT+GAPINTERVALS=10,30,,";
+
+ // Reset the device so that it picks up the above changes
+ static const char kATZ[] PROGMEM = "ATZ";
+
+ // Turn down the power level a bit
+ static const char kPower[] PROGMEM = "AT+BLEPOWERLEVEL=-12";
+ static PGM_P const configure_commands[] PROGMEM = {
+ kEcho,
+ kGapIntervals,
+ kGapDevName,
+ kHidEnOn,
+ kPower,
+ kATZ,
+ };
+
+ uint8_t i;
+ for (i = 0; i < sizeof(configure_commands) / sizeof(configure_commands[0]);
+ ++i) {
+ PGM_P cmd;
+ memcpy_P(&cmd, configure_commands + i, sizeof(cmd));
+
+ if (!at_command_P(cmd, resbuf, sizeof(resbuf))) {
+ dprintf("failed BLE command: %S: %s\n", cmd, resbuf);
+ goto fail;
+ }
+ }
+
+ state.configured = true;
+
+ // Check connection status in a little while; allow the ATZ time
+ // to kick in.
+ state.last_connection_update = timer_read();
+fail:
+ return state.configured;
+}
+
+static void set_connected(bool connected) {
+ if (connected != state.is_connected) {
+ if (connected) {
+ print("****** BLE CONNECT!!!!\n");
+ } else {
+ print("****** BLE DISCONNECT!!!!\n");
+ }
+ state.is_connected = connected;
+
+ // TODO: if modifiers are down on the USB interface and
+ // we cut over to BLE or vice versa, they will remain stuck.
+ // This feels like a good point to do something like clearing
+ // the keyboard and/or generating a fake all keys up message.
+ // However, I've noticed that it takes a couple of seconds
+ // for macOS to to start recognizing key presses after BLE
+ // is in the connected state, so I worry that doing that
+ // here may not be good enough.
+ }
+}
+
+void adafruit_ble_task(void) {
+ char resbuf[48];
+
+ if (!state.configured && !adafruit_ble_enable_keyboard()) {
+ return;
+ }
+ resp_buf_read_one(true);
+ send_buf_send_one(SdepShortTimeout);
+
+ if (resp_buf.empty() && (state.event_flags & UsingEvents) &&
+ digitalRead(AdafruitBleIRQPin)) {
+ // Must be an event update
+ if (at_command_P(PSTR("AT+EVENTSTATUS"), resbuf, sizeof(resbuf))) {
+ uint32_t mask = strtoul(resbuf, NULL, 16);
+
+ if (mask & BleSystemConnected) {
+ set_connected(true);
+ } else if (mask & BleSystemDisconnected) {
+ set_connected(false);
+ }
+ }
+ }
+
+ if (timer_elapsed(state.last_connection_update) > ConnectionUpdateInterval) {
+ bool shouldPoll = true;
+ if (!(state.event_flags & ProbedEvents)) {
+ // Request notifications about connection status changes.
+ // This only works in SPIFRIEND firmware > 0.6.7, which is why
+ // we check for this conditionally here.
+ // Note that at the time of writing, HID reports only work correctly
+ // with Apple products on firmware version 0.6.7!
+ // https://forums.adafruit.com/viewtopic.php?f=8&t=104052
+ if (at_command_P(PSTR("AT+EVENTENABLE=0x1"), resbuf, sizeof(resbuf))) {
+ at_command_P(PSTR("AT+EVENTENABLE=0x2"), resbuf, sizeof(resbuf));
+ state.event_flags |= UsingEvents;
+ }
+ state.event_flags |= ProbedEvents;
+
+ // leave shouldPoll == true so that we check at least once
+ // before relying solely on events
+ } else {
+ shouldPoll = false;
+ }
+
+ static const char kGetConn[] PROGMEM = "AT+GAPGETCONN";
+ state.last_connection_update = timer_read();
+
+ if (at_command_P(kGetConn, resbuf, sizeof(resbuf))) {
+ set_connected(atoi(resbuf));
+ }
+ }
+
+#ifdef SAMPLE_BATTERY
+ // I don't know if this really does anything useful yet; the reported
+ // voltage level always seems to be around 3200mV. We may want to just rip
+ // this code out.
+ if (timer_elapsed(state.last_battery_update) > BatteryUpdateInterval &&
+ resp_buf.empty()) {
+ state.last_battery_update = timer_read();
+
+ if (at_command_P(PSTR("AT+HWVBAT"), resbuf, sizeof(resbuf))) {
+ state.vbat = atoi(resbuf);
+ }
+ }
+#endif
+}
+
+static bool process_queue_item(struct queue_item *item, uint16_t timeout) {
+ char cmdbuf[48];
+ char fmtbuf[64];
+
+ // Arrange to re-check connection after keys have settled
+ state.last_connection_update = timer_read();
+
+#if 1
+ if (TIMER_DIFF_16(state.last_connection_update, item->added) > 0) {
+ dprintf("send latency %dms\n",
+ TIMER_DIFF_16(state.last_connection_update, item->added));
+ }
+#endif
+
+ switch (item->queue_type) {
+ case QTKeyReport:
+ strcpy_P(fmtbuf,
+ PSTR("AT+BLEKEYBOARDCODE=%02x-00-%02x-%02x-%02x-%02x-%02x-%02x"));
+ snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->key.modifier,
+ item->key.keys[0], item->key.keys[1], item->key.keys[2],
+ item->key.keys[3], item->key.keys[4], item->key.keys[5]);
+ return at_command(cmdbuf, NULL, 0, true, timeout);
+
+ case QTConsumer:
+ strcpy_P(fmtbuf, PSTR("AT+BLEHIDCONTROLKEY=0x%04x"));
+ snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->consumer);
+ return at_command(cmdbuf, NULL, 0, true, timeout);
+
+#ifdef MOUSE_ENABLE
+ case QTMouseMove:
+ strcpy_P(fmtbuf, PSTR("AT+BLEHIDMOUSEMOVE=%d,%d,%d,%d"));
+ snprintf(cmdbuf, sizeof(cmdbuf), fmtbuf, item->mousemove.x,
+ item->mousemove.y, item->mousemove.scroll, item->mousemove.pan);
+ if (!at_command(cmdbuf, NULL, 0, true, timeout)) {
+ return false;
+ }
+ strcpy_P(cmdbuf, PSTR("AT+BLEHIDMOUSEBUTTON="));
+ if (item->mousemove.buttons & MOUSE_BTN1) {
+ strcat(cmdbuf, "L");
+ }
+ if (item->mousemove.buttons & MOUSE_BTN2) {
+ strcat(cmdbuf, "R");
+ }
+ if (item->mousemove.buttons & MOUSE_BTN3) {
+ strcat(cmdbuf, "M");
+ }
+ if (item->mousemove.buttons == 0) {
+ strcat(cmdbuf, "0");
+ }
+ return at_command(cmdbuf, NULL, 0, true, timeout);
+#endif
+ default:
+ return true;
+ }
+}
+
+bool adafruit_ble_send_keys(uint8_t hid_modifier_mask, uint8_t *keys,
+ uint8_t nkeys) {
+ struct queue_item item;
+ bool didWait = false;
+
+ item.queue_type = QTKeyReport;
+ item.key.modifier = hid_modifier_mask;
+ item.added = timer_read();
+
+ while (nkeys >= 0) {
+ item.key.keys[0] = keys[0];
+ item.key.keys[1] = nkeys >= 1 ? keys[1] : 0;
+ item.key.keys[2] = nkeys >= 2 ? keys[2] : 0;
+ item.key.keys[3] = nkeys >= 3 ? keys[3] : 0;
+ item.key.keys[4] = nkeys >= 4 ? keys[4] : 0;
+ item.key.keys[5] = nkeys >= 5 ? keys[5] : 0;
+
+ if (!send_buf.enqueue(item)) {
+ if (!didWait) {
+ dprint("wait for buf space\n");
+ didWait = true;
+ }
+ send_buf_send_one();
+ continue;
+ }
+
+ if (nkeys <= 6) {
+ return true;
+ }
+
+ nkeys -= 6;
+ keys += 6;
+ }
+
+ return true;
+}
+
+bool adafruit_ble_send_consumer_key(uint16_t keycode, int hold_duration) {
+ struct queue_item item;
+
+ item.queue_type = QTConsumer;
+ item.consumer = keycode;
+
+ while (!send_buf.enqueue(item)) {
+ send_buf_send_one();
+ }
+ return true;
+}
+
+#ifdef MOUSE_ENABLE
+bool adafruit_ble_send_mouse_move(int8_t x, int8_t y, int8_t scroll,
+ int8_t pan, uint8_t buttons) {
+ struct queue_item item;
+
+ item.queue_type = QTMouseMove;
+ item.mousemove.x = x;
+ item.mousemove.y = y;
+ item.mousemove.scroll = scroll;
+ item.mousemove.pan = pan;
+ item.mousemove.buttons = buttons;
+
+ while (!send_buf.enqueue(item)) {
+ send_buf_send_one();
+ }
+ return true;
+}
+#endif
+
+uint32_t adafruit_ble_read_battery_voltage(void) {
+ return state.vbat;
+}
+
+bool adafruit_ble_set_mode_leds(bool on) {
+ if (!state.configured) {
+ return false;
+ }
+
+ // The "mode" led is the red blinky one
+ at_command_P(on ? PSTR("AT+HWMODELED=1") : PSTR("AT+HWMODELED=0"), NULL, 0);
+
+ // Pin 19 is the blue "connected" LED; turn that off too.
+ // When turning LEDs back on, don't turn that LED on if we're
+ // not connected, as that would be confusing.
+ at_command_P(on && state.is_connected ? PSTR("AT+HWGPIO=19,1")
+ : PSTR("AT+HWGPIO=19,0"),
+ NULL, 0);
+ return true;
+}
+
+// https://learn.adafruit.com/adafruit-feather-32u4-bluefruit-le/ble-generic#at-plus-blepowerlevel
+bool adafruit_ble_set_power_level(int8_t level) {
+ char cmd[46];
+ if (!state.configured) {
+ return false;
+ }
+ snprintf(cmd, sizeof(cmd), "AT+BLEPOWERLEVEL=%d", level);
+ return at_command(cmd, NULL, 0, false);
+}
diff --git a/tmk_core/protocol/lufa/adafruit_ble.h b/tmk_core/protocol/lufa/adafruit_ble.h
new file mode 100644
index 000000000..036b7d14e
--- /dev/null
+++ b/tmk_core/protocol/lufa/adafruit_ble.h
@@ -0,0 +1,60 @@
+/* Bluetooth Low Energy Protocol for QMK.
+ * Author: Wez Furlong, 2016
+ * Supports the Adafruit BLE board built around the nRF51822 chip.
+ */
+#pragma once
+#ifdef MODULE_ADAFRUIT_BLE
+#include <stdbool.h>
+#include <stdint.h>
+#include <string.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Instruct the module to enable HID keyboard support and reset */
+extern bool adafruit_ble_enable_keyboard(void);
+
+/* Query to see if the BLE module is connected */
+extern bool adafruit_ble_query_is_connected(void);
+
+/* Returns true if we believe that the BLE module is connected.
+ * This uses our cached understanding that is maintained by
+ * calling ble_task() periodically. */
+extern bool adafruit_ble_is_connected(void);
+
+/* Call this periodically to process BLE-originated things */
+extern void adafruit_ble_task(void);
+
+/* Generates keypress events for a set of keys.
+ * The hid modifier mask specifies the state of the modifier keys for
+ * this set of keys.
+ * Also sends a key release indicator, so that the keys do not remain
+ * held down. */
+extern bool adafruit_ble_send_keys(uint8_t hid_modifier_mask, uint8_t *keys,
+ uint8_t nkeys);
+
+/* Send a consumer keycode, holding it down for the specified duration
+ * (milliseconds) */
+extern bool adafruit_ble_send_consumer_key(uint16_t keycode, int hold_duration);
+
+#ifdef MOUSE_ENABLE
+/* Send a mouse/wheel movement report.
+ * The parameters are signed and indicate positive of negative direction
+ * change. */
+extern bool adafruit_ble_send_mouse_move(int8_t x, int8_t y, int8_t scroll,
+ int8_t pan, uint8_t buttons);
+#endif
+
+/* Compute battery voltage by reading an analog pin.
+ * Returns the integer number of millivolts */
+extern uint32_t adafruit_ble_read_battery_voltage(void);
+
+extern bool adafruit_ble_set_mode_leds(bool on);
+extern bool adafruit_ble_set_power_level(int8_t level);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // MODULE_ADAFRUIT_BLE
diff --git a/tmk_core/protocol/lufa/bluetooth.c b/tmk_core/protocol/lufa/bluetooth.c
new file mode 100644
index 000000000..549606162
--- /dev/null
+++ b/tmk_core/protocol/lufa/bluetooth.c
@@ -0,0 +1,36 @@
+/*
+Bluefruit Protocol for TMK firmware
+Author: Benjamin Gould, 2013
+ Jack Humbert, 2015
+Based on code Copyright 2011 Jun Wako <wakojun@gmail.com>
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdint.h>
+#include "report.h"
+#include "print.h"
+#include "debug.h"
+#include "bluetooth.h"
+
+void bluefruit_keyboard_print_report(report_keyboard_t *report)
+{
+ if (!debug_keyboard) return;
+ dprintf("keys: "); for (int i = 0; i < KEYBOARD_REPORT_KEYS; i++) { debug_hex8(report->keys[i]); dprintf(" "); }
+ dprintf(" mods: "); debug_hex8(report->mods);
+ dprintf(" reserved: "); debug_hex8(report->reserved);
+ dprintf("\n");
+}
+
+void bluefruit_serial_send(uint8_t data)
+{
+ serial_send(data);
+} \ No newline at end of file
diff --git a/tmk_core/protocol/lufa/bluetooth.h b/tmk_core/protocol/lufa/bluetooth.h
new file mode 100644
index 000000000..f4b2f6f8b
--- /dev/null
+++ b/tmk_core/protocol/lufa/bluetooth.h
@@ -0,0 +1,79 @@
+/*
+Bluefruit Protocol for TMK firmware
+Author: Benjamin Gould, 2013
+ Jack Humbert, 2015
+Based on code Copyright 2011 Jun Wako <wakojun@gmail.com>
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef BLUETOOTH_H
+#define BLUETOOTH_H
+
+#include "../serial.h"
+
+void bluefruit_serial_send(uint8_t data);
+
+/*
++-----------------+-------------------+-------+
+| Consumer Key | Bit Map | Hex |
++-----------------+-------------------+-------+
+| Home | 00000001 00000000 | 01 00 |
+| KeyboardLayout | 00000010 00000000 | 02 00 |
+| Search | 00000100 00000000 | 04 00 |
+| Snapshot | 00001000 00000000 | 08 00 |
+| VolumeUp | 00010000 00000000 | 10 00 |
+| VolumeDown | 00100000 00000000 | 20 00 |
+| Play/Pause | 01000000 00000000 | 40 00 |
+| Fast Forward | 10000000 00000000 | 80 00 |
+| Rewind | 00000000 00000001 | 00 01 |
+| Scan Next Track | 00000000 00000010 | 00 02 |
+| Scan Prev Track | 00000000 00000100 | 00 04 |
+| Random Play | 00000000 00001000 | 00 08 |
+| Stop | 00000000 00010000 | 00 10 |
++-------------------------------------+-------+
+*/
+#define CONSUMER2BLUEFRUIT(usage) \
+ (usage == AUDIO_MUTE ? 0x0000 : \
+ (usage == AUDIO_VOL_UP ? 0x1000 : \
+ (usage == AUDIO_VOL_DOWN ? 0x2000 : \
+ (usage == TRANSPORT_NEXT_TRACK ? 0x0002 : \
+ (usage == TRANSPORT_PREV_TRACK ? 0x0004 : \
+ (usage == TRANSPORT_STOP ? 0x0010 : \
+ (usage == TRANSPORT_STOP_EJECT ? 0x0000 : \
+ (usage == TRANSPORT_PLAY_PAUSE ? 0x4000 : \
+ (usage == AL_CC_CONFIG ? 0x0000 : \
+ (usage == AL_EMAIL ? 0x0000 : \
+ (usage == AL_CALCULATOR ? 0x0000 : \
+ (usage == AL_LOCAL_BROWSER ? 0x0000 : \
+ (usage == AC_SEARCH ? 0x0400 : \
+ (usage == AC_HOME ? 0x0100 : \
+ (usage == AC_BACK ? 0x0000 : \
+ (usage == AC_FORWARD ? 0x0000 : \
+ (usage == AC_STOP ? 0x0000 : \
+ (usage == AC_REFRESH ? 0x0000 : \
+ (usage == AC_BOOKMARKS ? 0x0000 : 0)))))))))))))))))))
+
+#define CONSUMER2RN42(usage) \
+ (usage == AUDIO_MUTE ? 0x0040 : \
+ (usage == AUDIO_VOL_UP ? 0x0010 : \
+ (usage == AUDIO_VOL_DOWN ? 0x0020 : \
+ (usage == TRANSPORT_NEXT_TRACK ? 0x0100 : \
+ (usage == TRANSPORT_PREV_TRACK ? 0x0200 : \
+ (usage == TRANSPORT_STOP ? 0x0400 : \
+ (usage == TRANSPORT_STOP_EJECT ? 0x0800 : \
+ (usage == TRANSPORT_PLAY_PAUSE ? 0x0080 : \
+ (usage == AL_EMAIL ? 0x0200 : \
+ (usage == AL_LOCAL_BROWSER ? 0x8000 : \
+ (usage == AC_SEARCH ? 0x0400 : \
+ (usage == AC_HOME ? 0x0100 : 0))))))))))))
+
+ #endif
diff --git a/tmk_core/protocol/lufa/descriptor.c b/tmk_core/protocol/lufa/descriptor.c
new file mode 100644
index 000000000..357954368
--- /dev/null
+++ b/tmk_core/protocol/lufa/descriptor.c
@@ -0,0 +1,987 @@
+/*
+ * Copyright 2012 Jun Wako <wakojun@gmail.com>
+ * This file is based on:
+ * LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
+ * LUFA-120219/Demos/Device/Lowlevel/GenericHID
+ */
+
+/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+ Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+#include "util.h"
+#include "report.h"
+#include "descriptor.h"
+
+#ifndef USB_MAX_POWER_CONSUMPTION
+#define USB_MAX_POWER_CONSUMPTION 500
+#endif
+
+/*******************************************************************************
+ * HID Report Descriptors
+ ******************************************************************************/
+const USB_Descriptor_HIDReport_Datatype_t PROGMEM KeyboardReport[] =
+{
+ HID_RI_USAGE_PAGE(8, 0x01), /* Generic Desktop */
+ HID_RI_USAGE(8, 0x06), /* Keyboard */
+ HID_RI_COLLECTION(8, 0x01), /* Application */
+ HID_RI_USAGE_PAGE(8, 0x07), /* Key Codes */
+ HID_RI_USAGE_MINIMUM(8, 0xE0), /* Keyboard Left Control */
+ HID_RI_USAGE_MAXIMUM(8, 0xE7), /* Keyboard Right GUI */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(8, 0x01),
+ HID_RI_REPORT_COUNT(8, 0x08),
+ HID_RI_REPORT_SIZE(8, 0x01),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
+
+ HID_RI_REPORT_COUNT(8, 0x01),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_INPUT(8, HID_IOF_CONSTANT), /* reserved */
+
+ HID_RI_USAGE_PAGE(8, 0x08), /* LEDs */
+ HID_RI_USAGE_MINIMUM(8, 0x01), /* Num Lock */
+ HID_RI_USAGE_MAXIMUM(8, 0x05), /* Kana */
+ HID_RI_REPORT_COUNT(8, 0x05),
+ HID_RI_REPORT_SIZE(8, 0x01),
+ HID_RI_OUTPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE | HID_IOF_NON_VOLATILE),
+ HID_RI_REPORT_COUNT(8, 0x01),
+ HID_RI_REPORT_SIZE(8, 0x03),
+ HID_RI_OUTPUT(8, HID_IOF_CONSTANT),
+
+ HID_RI_USAGE_PAGE(8, 0x07), /* Keyboard */
+ HID_RI_USAGE_MINIMUM(8, 0x00), /* Reserved (no event indicated) */
+ HID_RI_USAGE_MAXIMUM(8, 0xFF), /* Keyboard Application */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(16, 0x00FF),
+ HID_RI_REPORT_COUNT(8, 0x06),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_ARRAY | HID_IOF_ABSOLUTE),
+ HID_RI_END_COLLECTION(0),
+};
+
+#ifdef MOUSE_ENABLE
+const USB_Descriptor_HIDReport_Datatype_t PROGMEM MouseReport[] =
+{
+ HID_RI_USAGE_PAGE(8, 0x01), /* Generic Desktop */
+ HID_RI_USAGE(8, 0x02), /* Mouse */
+ HID_RI_COLLECTION(8, 0x01), /* Application */
+ HID_RI_USAGE(8, 0x01), /* Pointer */
+ HID_RI_COLLECTION(8, 0x00), /* Physical */
+
+ HID_RI_USAGE_PAGE(8, 0x09), /* Button */
+ HID_RI_USAGE_MINIMUM(8, 0x01), /* Button 1 */
+ HID_RI_USAGE_MAXIMUM(8, 0x05), /* Button 5 */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(8, 0x01),
+ HID_RI_REPORT_COUNT(8, 0x05),
+ HID_RI_REPORT_SIZE(8, 0x01),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
+ HID_RI_REPORT_COUNT(8, 0x01),
+ HID_RI_REPORT_SIZE(8, 0x03),
+ HID_RI_INPUT(8, HID_IOF_CONSTANT),
+
+ HID_RI_USAGE_PAGE(8, 0x01), /* Generic Desktop */
+ HID_RI_USAGE(8, 0x30), /* Usage X */
+ HID_RI_USAGE(8, 0x31), /* Usage Y */
+ HID_RI_LOGICAL_MINIMUM(8, -127),
+ HID_RI_LOGICAL_MAXIMUM(8, 127),
+ HID_RI_REPORT_COUNT(8, 0x02),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_RELATIVE),
+
+ HID_RI_USAGE(8, 0x38), /* Wheel */
+ HID_RI_LOGICAL_MINIMUM(8, -127),
+ HID_RI_LOGICAL_MAXIMUM(8, 127),
+ HID_RI_REPORT_COUNT(8, 0x01),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_RELATIVE),
+
+ HID_RI_USAGE_PAGE(8, 0x0C), /* Consumer */
+ HID_RI_USAGE(16, 0x0238), /* AC Pan (Horizontal wheel) */
+ HID_RI_LOGICAL_MINIMUM(8, -127),
+ HID_RI_LOGICAL_MAXIMUM(8, 127),
+ HID_RI_REPORT_COUNT(8, 0x01),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_RELATIVE),
+
+ HID_RI_END_COLLECTION(0),
+ HID_RI_END_COLLECTION(0),
+};
+#endif
+
+#ifdef EXTRAKEY_ENABLE
+const USB_Descriptor_HIDReport_Datatype_t PROGMEM ExtrakeyReport[] =
+{
+ HID_RI_USAGE_PAGE(8, 0x01), /* Generic Desktop */
+ HID_RI_USAGE(8, 0x80), /* System Control */
+ HID_RI_COLLECTION(8, 0x01), /* Application */
+ HID_RI_REPORT_ID(8, REPORT_ID_SYSTEM),
+ HID_RI_LOGICAL_MINIMUM(16, 0x0001),
+ HID_RI_LOGICAL_MAXIMUM(16, 0x0003),
+ HID_RI_USAGE_MINIMUM(16, 0x0081), /* System Power Down */
+ HID_RI_USAGE_MAXIMUM(16, 0x0083), /* System Wake Up */
+ HID_RI_REPORT_SIZE(8, 16),
+ HID_RI_REPORT_COUNT(8, 1),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_ARRAY | HID_IOF_ABSOLUTE),
+ HID_RI_END_COLLECTION(0),
+
+ HID_RI_USAGE_PAGE(8, 0x0C), /* Consumer */
+ HID_RI_USAGE(8, 0x01), /* Consumer Control */
+ HID_RI_COLLECTION(8, 0x01), /* Application */
+ HID_RI_REPORT_ID(8, REPORT_ID_CONSUMER),
+ HID_RI_LOGICAL_MINIMUM(16, 0x0001),
+ HID_RI_LOGICAL_MAXIMUM(16, 0x029C),
+ HID_RI_USAGE_MINIMUM(16, 0x0001), /* +10 */
+ HID_RI_USAGE_MAXIMUM(16, 0x029C), /* AC Distribute Vertically */
+ HID_RI_REPORT_SIZE(8, 16),
+ HID_RI_REPORT_COUNT(8, 1),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_ARRAY | HID_IOF_ABSOLUTE),
+ HID_RI_END_COLLECTION(0),
+};
+#endif
+
+#ifdef RAW_ENABLE
+const USB_Descriptor_HIDReport_Datatype_t PROGMEM RawReport[] =
+{
+ HID_RI_USAGE_PAGE(16, 0xFF60), /* Vendor Page 0xFF60 */
+ HID_RI_USAGE(8, 0x61), /* Vendor Usage 0x61 */
+ HID_RI_COLLECTION(8, 0x01), /* Application */
+ HID_RI_USAGE(8, 0x62), /* Vendor Usage 0x62 */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(16, 0x00FF),
+ HID_RI_REPORT_COUNT(8, RAW_EPSIZE),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
+ HID_RI_USAGE(8, 0x63), /* Vendor Usage 0x63 */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(16, 0x00FF),
+ HID_RI_REPORT_COUNT(8, RAW_EPSIZE),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_OUTPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE | HID_IOF_NON_VOLATILE),
+ HID_RI_END_COLLECTION(0),
+};
+#endif
+
+#ifdef CONSOLE_ENABLE
+const USB_Descriptor_HIDReport_Datatype_t PROGMEM ConsoleReport[] =
+{
+ HID_RI_USAGE_PAGE(16, 0xFF31), /* Vendor Page(PJRC Teensy compatible) */
+ HID_RI_USAGE(8, 0x74), /* Vendor Usage(PJRC Teensy compatible) */
+ HID_RI_COLLECTION(8, 0x01), /* Application */
+ HID_RI_USAGE(8, 0x75), /* Vendor Usage 0x75 */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(16, 0x00FF),
+ HID_RI_REPORT_COUNT(8, CONSOLE_EPSIZE),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
+ HID_RI_USAGE(8, 0x76), /* Vendor Usage 0x76 */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(16, 0x00FF),
+ HID_RI_REPORT_COUNT(8, CONSOLE_EPSIZE),
+ HID_RI_REPORT_SIZE(8, 0x08),
+ HID_RI_OUTPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE | HID_IOF_NON_VOLATILE),
+ HID_RI_END_COLLECTION(0),
+};
+#endif
+
+#ifdef NKRO_ENABLE
+const USB_Descriptor_HIDReport_Datatype_t PROGMEM NKROReport[] =
+{
+ HID_RI_USAGE_PAGE(8, 0x01), /* Generic Desktop */
+ HID_RI_USAGE(8, 0x06), /* Keyboard */
+ HID_RI_COLLECTION(8, 0x01), /* Application */
+ HID_RI_USAGE_PAGE(8, 0x07), /* Key Codes */
+ HID_RI_USAGE_MINIMUM(8, 0xE0), /* Keyboard Left Control */
+ HID_RI_USAGE_MAXIMUM(8, 0xE7), /* Keyboard Right GUI */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(8, 0x01),
+ HID_RI_REPORT_COUNT(8, 0x08),
+ HID_RI_REPORT_SIZE(8, 0x01),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
+
+ HID_RI_USAGE_PAGE(8, 0x08), /* LEDs */
+ HID_RI_USAGE_MINIMUM(8, 0x01), /* Num Lock */
+ HID_RI_USAGE_MAXIMUM(8, 0x05), /* Kana */
+ HID_RI_REPORT_COUNT(8, 0x05),
+ HID_RI_REPORT_SIZE(8, 0x01),
+ HID_RI_OUTPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE | HID_IOF_NON_VOLATILE),
+ HID_RI_REPORT_COUNT(8, 0x01),
+ HID_RI_REPORT_SIZE(8, 0x03),
+ HID_RI_OUTPUT(8, HID_IOF_CONSTANT),
+
+ HID_RI_USAGE_PAGE(8, 0x07), /* Key Codes */
+ HID_RI_USAGE_MINIMUM(8, 0x00), /* Keyboard 0 */
+ HID_RI_USAGE_MAXIMUM(8, (NKRO_EPSIZE-1)*8-1), /* Keyboard Right GUI */
+ HID_RI_LOGICAL_MINIMUM(8, 0x00),
+ HID_RI_LOGICAL_MAXIMUM(8, 0x01),
+ HID_RI_REPORT_COUNT(8, (NKRO_EPSIZE-1)*8),
+ HID_RI_REPORT_SIZE(8, 0x01),
+ HID_RI_INPUT(8, HID_IOF_DATA | HID_IOF_VARIABLE | HID_IOF_ABSOLUTE),
+ HID_RI_END_COLLECTION(0),
+};
+#endif
+
+/*******************************************************************************
+ * Device Descriptors
+ ******************************************************************************/
+const USB_Descriptor_Device_t PROGMEM DeviceDescriptor =
+{
+ .Header = {.Size = sizeof(USB_Descriptor_Device_t), .Type = DTYPE_Device},
+
+ .USBSpecification = VERSION_BCD(1,1,0),
+#if VIRTSER_ENABLE
+ .Class = USB_CSCP_IADDeviceClass,
+ .SubClass = USB_CSCP_IADDeviceSubclass,
+ .Protocol = USB_CSCP_IADDeviceProtocol,
+#else
+ .Class = USB_CSCP_NoDeviceClass,
+ .SubClass = USB_CSCP_NoDeviceSubclass,
+ .Protocol = USB_CSCP_NoDeviceProtocol,
+#endif
+
+ .Endpoint0Size = FIXED_CONTROL_ENDPOINT_SIZE,
+
+ /* specified in config.h */
+ .VendorID = VENDOR_ID,
+ .ProductID = PRODUCT_ID,
+ .ReleaseNumber = DEVICE_VER,
+
+ .ManufacturerStrIndex = 0x01,
+ .ProductStrIndex = 0x02,
+ .SerialNumStrIndex = NO_DESCRIPTOR,
+
+ .NumberOfConfigurations = FIXED_NUM_CONFIGURATIONS
+};
+
+/*******************************************************************************
+ * Configuration Descriptors
+ ******************************************************************************/
+const USB_Descriptor_Configuration_t PROGMEM ConfigurationDescriptor =
+{
+ .Config =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Configuration_Header_t), .Type = DTYPE_Configuration},
+
+ .TotalConfigurationSize = sizeof(USB_Descriptor_Configuration_t),
+ .TotalInterfaces = TOTAL_INTERFACES,
+
+ .ConfigurationNumber = 1,
+ .ConfigurationStrIndex = NO_DESCRIPTOR,
+
+ .ConfigAttributes = (USB_CONFIG_ATTR_RESERVED | USB_CONFIG_ATTR_REMOTEWAKEUP),
+
+ .MaxPowerConsumption = USB_CONFIG_POWER_MA(USB_MAX_POWER_CONSUMPTION)
+ },
+
+ /*
+ * Keyboard
+ */
+ .Keyboard_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = KEYBOARD_INTERFACE,
+ .AlternateSetting = 0x00,
+
+ .TotalEndpoints = 1,
+
+ .Class = HID_CSCP_HIDClass,
+ .SubClass = HID_CSCP_BootSubclass,
+ .Protocol = HID_CSCP_KeyboardBootProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Keyboard_HID =
+ {
+ .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
+
+ .HIDSpec = VERSION_BCD(1,1,1),
+ .CountryCode = 0x00,
+ .TotalReportDescriptors = 1,
+ .HIDReportType = HID_DTYPE_Report,
+ .HIDReportLength = sizeof(KeyboardReport)
+ },
+
+ .Keyboard_INEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | KEYBOARD_IN_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = KEYBOARD_EPSIZE,
+ .PollingIntervalMS = 0x0A
+ },
+
+ /*
+ * Mouse
+ */
+#ifdef MOUSE_ENABLE
+ .Mouse_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = MOUSE_INTERFACE,
+ .AlternateSetting = 0x00,
+
+ .TotalEndpoints = 1,
+
+ .Class = HID_CSCP_HIDClass,
+ .SubClass = HID_CSCP_BootSubclass,
+ .Protocol = HID_CSCP_MouseBootProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Mouse_HID =
+ {
+ .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
+
+ .HIDSpec = VERSION_BCD(1,1,1),
+ .CountryCode = 0x00,
+ .TotalReportDescriptors = 1,
+ .HIDReportType = HID_DTYPE_Report,
+ .HIDReportLength = sizeof(MouseReport)
+ },
+
+ .Mouse_INEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | MOUSE_IN_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = MOUSE_EPSIZE,
+ .PollingIntervalMS = 0x0A
+ },
+#endif
+
+ /*
+ * Extra
+ */
+#ifdef EXTRAKEY_ENABLE
+ .Extrakey_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = EXTRAKEY_INTERFACE,
+ .AlternateSetting = 0x00,
+
+ .TotalEndpoints = 1,
+
+ .Class = HID_CSCP_HIDClass,
+ .SubClass = HID_CSCP_NonBootSubclass,
+ .Protocol = HID_CSCP_NonBootProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Extrakey_HID =
+ {
+ .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
+
+ .HIDSpec = VERSION_BCD(1,1,1),
+ .CountryCode = 0x00,
+ .TotalReportDescriptors = 1,
+ .HIDReportType = HID_DTYPE_Report,
+ .HIDReportLength = sizeof(ExtrakeyReport)
+ },
+
+ .Extrakey_INEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | EXTRAKEY_IN_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = EXTRAKEY_EPSIZE,
+ .PollingIntervalMS = 0x0A
+ },
+#endif
+
+ /*
+ * Raw
+ */
+ #ifdef RAW_ENABLE
+ .Raw_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = RAW_INTERFACE,
+ .AlternateSetting = 0x00,
+
+ .TotalEndpoints = 2,
+
+ .Class = HID_CSCP_HIDClass,
+ .SubClass = HID_CSCP_NonBootSubclass,
+ .Protocol = HID_CSCP_NonBootProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Raw_HID =
+ {
+ .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
+
+ .HIDSpec = VERSION_BCD(1,1,1),
+ .CountryCode = 0x00,
+ .TotalReportDescriptors = 1,
+ .HIDReportType = HID_DTYPE_Report,
+ .HIDReportLength = sizeof(RawReport)
+ },
+
+ .Raw_INEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | RAW_IN_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = RAW_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .Raw_OUTEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_OUT | RAW_OUT_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = RAW_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+ #endif
+
+ /*
+ * Console
+ */
+#ifdef CONSOLE_ENABLE
+ .Console_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = CONSOLE_INTERFACE,
+ .AlternateSetting = 0x00,
+
+ .TotalEndpoints = 2,
+
+ .Class = HID_CSCP_HIDClass,
+ .SubClass = HID_CSCP_NonBootSubclass,
+ .Protocol = HID_CSCP_NonBootProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Console_HID =
+ {
+ .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
+
+ .HIDSpec = VERSION_BCD(1,1,1),
+ .CountryCode = 0x00,
+ .TotalReportDescriptors = 1,
+ .HIDReportType = HID_DTYPE_Report,
+ .HIDReportLength = sizeof(ConsoleReport)
+ },
+
+ .Console_INEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | CONSOLE_IN_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CONSOLE_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+
+ .Console_OUTEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_OUT | CONSOLE_OUT_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CONSOLE_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+#endif
+
+ /*
+ * NKRO
+ */
+#ifdef NKRO_ENABLE
+ .NKRO_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = NKRO_INTERFACE,
+ .AlternateSetting = 0x00,
+
+ .TotalEndpoints = 1,
+
+ .Class = HID_CSCP_HIDClass,
+ .SubClass = HID_CSCP_NonBootSubclass,
+ .Protocol = HID_CSCP_NonBootProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .NKRO_HID =
+ {
+ .Header = {.Size = sizeof(USB_HID_Descriptor_HID_t), .Type = HID_DTYPE_HID},
+
+ .HIDSpec = VERSION_BCD(1,1,1),
+ .CountryCode = 0x00,
+ .TotalReportDescriptors = 1,
+ .HIDReportType = HID_DTYPE_Report,
+ .HIDReportLength = sizeof(NKROReport)
+ },
+
+ .NKRO_INEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = (ENDPOINT_DIR_IN | NKRO_IN_EPNUM),
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = NKRO_EPSIZE,
+ .PollingIntervalMS = 0x01
+ },
+#endif
+
+#ifdef MIDI_ENABLE
+ .Audio_ControlInterface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = AC_INTERFACE,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 0,
+
+ .Class = AUDIO_CSCP_AudioClass,
+ .SubClass = AUDIO_CSCP_ControlSubclass,
+ .Protocol = AUDIO_CSCP_ControlProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Audio_ControlInterface_SPC =
+ {
+ .Header = {.Size = sizeof(USB_Audio_Descriptor_Interface_AC_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_Header,
+
+ .ACSpecification = VERSION_BCD(1,0,0),
+ .TotalLength = sizeof(USB_Audio_Descriptor_Interface_AC_t),
+
+ .InCollection = 1,
+ .InterfaceNumber = AS_INTERFACE,
+ },
+
+ .Audio_StreamInterface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = AS_INTERFACE,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 2,
+
+ .Class = AUDIO_CSCP_AudioClass,
+ .SubClass = AUDIO_CSCP_MIDIStreamingSubclass,
+ .Protocol = AUDIO_CSCP_StreamingProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .Audio_StreamInterface_SPC =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_AudioInterface_AS_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_General,
+
+ .AudioSpecification = VERSION_BCD(1,0,0),
+
+ .TotalLength = (sizeof(USB_Descriptor_Configuration_t) -
+ offsetof(USB_Descriptor_Configuration_t, Audio_StreamInterface_SPC))
+ },
+
+ .MIDI_In_Jack_Emb =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_InputJack_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_InputTerminal,
+
+ .JackType = MIDI_JACKTYPE_Embedded,
+ .JackID = 0x01,
+
+ .JackStrIndex = NO_DESCRIPTOR
+ },
+
+ .MIDI_In_Jack_Ext =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_InputJack_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_InputTerminal,
+
+ .JackType = MIDI_JACKTYPE_External,
+ .JackID = 0x02,
+
+ .JackStrIndex = NO_DESCRIPTOR
+ },
+
+ .MIDI_Out_Jack_Emb =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_OutputJack_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_OutputTerminal,
+
+ .JackType = MIDI_JACKTYPE_Embedded,
+ .JackID = 0x03,
+
+ .NumberOfPins = 1,
+ .SourceJackID = {0x02},
+ .SourcePinID = {0x01},
+
+ .JackStrIndex = NO_DESCRIPTOR
+ },
+
+ .MIDI_Out_Jack_Ext =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_OutputJack_t), .Type = DTYPE_CSInterface},
+ .Subtype = AUDIO_DSUBTYPE_CSInterface_OutputTerminal,
+
+ .JackType = MIDI_JACKTYPE_External,
+ .JackID = 0x04,
+
+ .NumberOfPins = 1,
+ .SourceJackID = {0x01},
+ .SourcePinID = {0x01},
+
+ .JackStrIndex = NO_DESCRIPTOR
+ },
+
+ .MIDI_In_Jack_Endpoint =
+ {
+ .Endpoint =
+ {
+ .Header = {.Size = sizeof(USB_Audio_Descriptor_StreamEndpoint_Std_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = MIDI_STREAM_OUT_EPADDR,
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = MIDI_STREAM_EPSIZE,
+ .PollingIntervalMS = 0x05
+ },
+
+ .Refresh = 0,
+ .SyncEndpointNumber = 0
+ },
+
+ .MIDI_In_Jack_Endpoint_SPC =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_Jack_Endpoint_t), .Type = DTYPE_CSEndpoint},
+ .Subtype = AUDIO_DSUBTYPE_CSEndpoint_General,
+
+ .TotalEmbeddedJacks = 0x01,
+ .AssociatedJackID = {0x01}
+ },
+
+ .MIDI_Out_Jack_Endpoint =
+ {
+ .Endpoint =
+ {
+ .Header = {.Size = sizeof(USB_Audio_Descriptor_StreamEndpoint_Std_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = MIDI_STREAM_IN_EPADDR,
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = MIDI_STREAM_EPSIZE,
+ .PollingIntervalMS = 0x05
+ },
+
+ .Refresh = 0,
+ .SyncEndpointNumber = 0
+ },
+
+ .MIDI_Out_Jack_Endpoint_SPC =
+ {
+ .Header = {.Size = sizeof(USB_MIDI_Descriptor_Jack_Endpoint_t), .Type = DTYPE_CSEndpoint},
+ .Subtype = AUDIO_DSUBTYPE_CSEndpoint_General,
+
+ .TotalEmbeddedJacks = 0x01,
+ .AssociatedJackID = {0x03}
+ },
+#endif
+
+#ifdef VIRTSER_ENABLE
+ .CDC_Interface_Association =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_Association_t), .Type = DTYPE_InterfaceAssociation},
+
+ .FirstInterfaceIndex = CCI_INTERFACE,
+ .TotalInterfaces = 2,
+
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_ACMSubclass,
+ .Protocol = CDC_CSCP_ATCommandProtocol,
+
+ .IADStrIndex = NO_DESCRIPTOR,
+ },
+
+ .CDC_CCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = CCI_INTERFACE,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 1,
+
+ .Class = CDC_CSCP_CDCClass,
+ .SubClass = CDC_CSCP_ACMSubclass,
+ .Protocol = CDC_CSCP_ATCommandProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC_Functional_Header =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalHeader_t), .Type = DTYPE_CSInterface},
+ .Subtype = 0x00,
+
+ .CDCSpecification = VERSION_BCD(1,1,0),
+ },
+
+ .CDC_Functional_ACM =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalACM_t), .Type = DTYPE_CSInterface},
+ .Subtype = 0x02,
+
+ .Capabilities = 0x02,
+ },
+
+ .CDC_Functional_Union =
+ {
+ .Header = {.Size = sizeof(USB_CDC_Descriptor_FunctionalUnion_t), .Type = DTYPE_CSInterface},
+ .Subtype = 0x06,
+
+ .MasterInterfaceNumber = CCI_INTERFACE,
+ .SlaveInterfaceNumber = CDI_INTERFACE,
+ },
+
+ .CDC_NotificationEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = CDC_NOTIFICATION_EPADDR,
+ .Attributes = (EP_TYPE_INTERRUPT | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_NOTIFICATION_EPSIZE,
+ .PollingIntervalMS = 0xFF
+ },
+
+ .CDC_DCI_Interface =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Interface_t), .Type = DTYPE_Interface},
+
+ .InterfaceNumber = CDI_INTERFACE,
+ .AlternateSetting = 0,
+
+ .TotalEndpoints = 2,
+
+ .Class = CDC_CSCP_CDCDataClass,
+ .SubClass = CDC_CSCP_NoDataSubclass,
+ .Protocol = CDC_CSCP_NoDataProtocol,
+
+ .InterfaceStrIndex = NO_DESCRIPTOR
+ },
+
+ .CDC_DataOutEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = CDC_OUT_EPADDR,
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_EPSIZE,
+ .PollingIntervalMS = 0x05
+ },
+
+ .CDC_DataInEndpoint =
+ {
+ .Header = {.Size = sizeof(USB_Descriptor_Endpoint_t), .Type = DTYPE_Endpoint},
+
+ .EndpointAddress = CDC_IN_EPADDR,
+ .Attributes = (EP_TYPE_BULK | ENDPOINT_ATTR_NO_SYNC | ENDPOINT_USAGE_DATA),
+ .EndpointSize = CDC_EPSIZE,
+ .PollingIntervalMS = 0x05
+ },
+#endif
+};
+
+
+/*******************************************************************************
+ * String Descriptors
+ ******************************************************************************/
+const USB_Descriptor_String_t PROGMEM LanguageString =
+{
+ .Header = {.Size = USB_STRING_LEN(1), .Type = DTYPE_String},
+
+ .UnicodeString = {LANGUAGE_ID_ENG}
+};
+
+const USB_Descriptor_String_t PROGMEM ManufacturerString =
+{
+ /* subtract 1 for null terminator */
+ .Header = {.Size = USB_STRING_LEN(sizeof(STR(MANUFACTURER))-1), .Type = DTYPE_String},
+
+ .UnicodeString = LSTR(MANUFACTURER)
+};
+
+const USB_Descriptor_String_t PROGMEM ProductString =
+{
+ /* subtract 1 for null terminator */
+ .Header = {.Size = USB_STRING_LEN(sizeof(STR(PRODUCT))-1), .Type = DTYPE_String},
+
+ .UnicodeString = LSTR(PRODUCT)
+};
+
+
+/** This function is called by the library when in device mode, and must be overridden (see library "USB Descriptors"
+ * documentation) by the application code so that the address and size of a requested descriptor can be given
+ * to the USB library. When the device receives a Get Descriptor request on the control endpoint, this function
+ * is called so that the descriptor details can be passed back and the appropriate descriptor sent back to the
+ * USB host.
+ */
+uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint16_t wIndex,
+ const void** const DescriptorAddress)
+{
+ const uint8_t DescriptorType = (wValue >> 8);
+ const uint8_t DescriptorIndex = (wValue & 0xFF);
+
+ const void* Address = NULL;
+ uint16_t Size = NO_DESCRIPTOR;
+
+ switch (DescriptorType)
+ {
+ case DTYPE_Device:
+ Address = &DeviceDescriptor;
+ Size = sizeof(USB_Descriptor_Device_t);
+ break;
+ case DTYPE_Configuration:
+ Address = &ConfigurationDescriptor;
+ Size = sizeof(USB_Descriptor_Configuration_t);
+ break;
+ case DTYPE_String:
+ switch (DescriptorIndex )
+ {
+ case 0x00:
+ Address = &LanguageString;
+ Size = pgm_read_byte(&LanguageString.Header.Size);
+ break;
+ case 0x01:
+ Address = &ManufacturerString;
+ Size = pgm_read_byte(&ManufacturerString.Header.Size);
+ break;
+ case 0x02:
+ Address = &ProductString;
+ Size = pgm_read_byte(&ProductString.Header.Size);
+ break;
+ }
+ break;
+ case HID_DTYPE_HID:
+ switch (wIndex) {
+ case KEYBOARD_INTERFACE:
+ Address = &ConfigurationDescriptor.Keyboard_HID;
+ Size = sizeof(USB_HID_Descriptor_HID_t);
+ break;
+#ifdef MOUSE_ENABLE
+ case MOUSE_INTERFACE:
+ Address = &ConfigurationDescriptor.Mouse_HID;
+ Size = sizeof(USB_HID_Descriptor_HID_t);
+ break;
+#endif
+#ifdef EXTRAKEY_ENABLE
+ case EXTRAKEY_INTERFACE:
+ Address = &ConfigurationDescriptor.Extrakey_HID;
+ Size = sizeof(USB_HID_Descriptor_HID_t);
+ break;
+#endif
+#ifdef RAW_ENABLE
+ case RAW_INTERFACE:
+ Address = &ConfigurationDescriptor.Raw_HID;
+ Size = sizeof(USB_HID_Descriptor_HID_t);
+ break;
+#endif
+#ifdef CONSOLE_ENABLE
+ case CONSOLE_INTERFACE:
+ Address = &ConfigurationDescriptor.Console_HID;
+ Size = sizeof(USB_HID_Descriptor_HID_t);
+ break;
+#endif
+#ifdef NKRO_ENABLE
+ case NKRO_INTERFACE:
+ Address = &ConfigurationDescriptor.NKRO_HID;
+ Size = sizeof(USB_HID_Descriptor_HID_t);
+ break;
+#endif
+ }
+ break;
+ case HID_DTYPE_Report:
+ switch (wIndex) {
+ case KEYBOARD_INTERFACE:
+ Address = &KeyboardReport;
+ Size = sizeof(KeyboardReport);
+ break;
+#ifdef MOUSE_ENABLE
+ case MOUSE_INTERFACE:
+ Address = &MouseReport;
+ Size = sizeof(MouseReport);
+ break;
+#endif
+#ifdef EXTRAKEY_ENABLE
+ case EXTRAKEY_INTERFACE:
+ Address = &ExtrakeyReport;
+ Size = sizeof(ExtrakeyReport);
+ break;
+#endif
+#ifdef RAW_ENABLE
+ case RAW_INTERFACE:
+ Address = &RawReport;
+ Size = sizeof(RawReport);
+ break;
+#endif
+#ifdef CONSOLE_ENABLE
+ case CONSOLE_INTERFACE:
+ Address = &ConsoleReport;
+ Size = sizeof(ConsoleReport);
+ break;
+#endif
+#ifdef NKRO_ENABLE
+ case NKRO_INTERFACE:
+ Address = &NKROReport;
+ Size = sizeof(NKROReport);
+ break;
+#endif
+ }
+ break;
+ }
+
+ *DescriptorAddress = Address;
+ return Size;
+}
diff --git a/tmk_core/protocol/lufa/descriptor.h b/tmk_core/protocol/lufa/descriptor.h
new file mode 100644
index 000000000..cde44abc9
--- /dev/null
+++ b/tmk_core/protocol/lufa/descriptor.h
@@ -0,0 +1,271 @@
+/*
+ * Copyright 2012,2013 Jun Wako <wakojun@gmail.com>
+ * This file is based on:
+ * LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
+ * LUFA-120219/Demos/Device/Lowlevel/GenericHID
+ */
+
+/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+ Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ *
+ * Header file for Descriptors.c.
+ */
+
+#ifndef _DESCRIPTORS_H_
+#define _DESCRIPTORS_H_
+
+#include <LUFA/Drivers/USB/USB.h>
+#include <avr/pgmspace.h>
+
+
+typedef struct
+{
+ USB_Descriptor_Configuration_Header_t Config;
+
+ // Keyboard HID Interface
+ USB_Descriptor_Interface_t Keyboard_Interface;
+ USB_HID_Descriptor_HID_t Keyboard_HID;
+ USB_Descriptor_Endpoint_t Keyboard_INEndpoint;
+
+#ifdef MOUSE_ENABLE
+ // Mouse HID Interface
+ USB_Descriptor_Interface_t Mouse_Interface;
+ USB_HID_Descriptor_HID_t Mouse_HID;
+ USB_Descriptor_Endpoint_t Mouse_INEndpoint;
+#endif
+
+#ifdef EXTRAKEY_ENABLE
+ // Extrakey HID Interface
+ USB_Descriptor_Interface_t Extrakey_Interface;
+ USB_HID_Descriptor_HID_t Extrakey_HID;
+ USB_Descriptor_Endpoint_t Extrakey_INEndpoint;
+#endif
+
+#ifdef RAW_ENABLE
+ // Raw HID Interface
+ USB_Descriptor_Interface_t Raw_Interface;
+ USB_HID_Descriptor_HID_t Raw_HID;
+ USB_Descriptor_Endpoint_t Raw_INEndpoint;
+ USB_Descriptor_Endpoint_t Raw_OUTEndpoint;
+#endif
+
+#ifdef CONSOLE_ENABLE
+ // Console HID Interface
+ USB_Descriptor_Interface_t Console_Interface;
+ USB_HID_Descriptor_HID_t Console_HID;
+ USB_Descriptor_Endpoint_t Console_INEndpoint;
+ USB_Descriptor_Endpoint_t Console_OUTEndpoint;
+#endif
+
+#ifdef NKRO_ENABLE
+ // NKRO HID Interface
+ USB_Descriptor_Interface_t NKRO_Interface;
+ USB_HID_Descriptor_HID_t NKRO_HID;
+ USB_Descriptor_Endpoint_t NKRO_INEndpoint;
+#endif
+
+#ifdef MIDI_ENABLE
+ // MIDI Audio Control Interface
+ USB_Descriptor_Interface_t Audio_ControlInterface;
+ USB_Audio_Descriptor_Interface_AC_t Audio_ControlInterface_SPC;
+
+ // MIDI Audio Streaming Interface
+ USB_Descriptor_Interface_t Audio_StreamInterface;
+ USB_MIDI_Descriptor_AudioInterface_AS_t Audio_StreamInterface_SPC;
+ USB_MIDI_Descriptor_InputJack_t MIDI_In_Jack_Emb;
+ USB_MIDI_Descriptor_InputJack_t MIDI_In_Jack_Ext;
+ USB_MIDI_Descriptor_OutputJack_t MIDI_Out_Jack_Emb;
+ USB_MIDI_Descriptor_OutputJack_t MIDI_Out_Jack_Ext;
+ USB_Audio_Descriptor_StreamEndpoint_Std_t MIDI_In_Jack_Endpoint;
+ USB_MIDI_Descriptor_Jack_Endpoint_t MIDI_In_Jack_Endpoint_SPC;
+ USB_Audio_Descriptor_StreamEndpoint_Std_t MIDI_Out_Jack_Endpoint;
+ USB_MIDI_Descriptor_Jack_Endpoint_t MIDI_Out_Jack_Endpoint_SPC;
+#endif
+
+#ifdef VIRTSER_ENABLE
+ USB_Descriptor_Interface_Association_t CDC_Interface_Association;
+
+ // CDC Control Interface
+ USB_Descriptor_Interface_t CDC_CCI_Interface;
+ USB_CDC_Descriptor_FunctionalHeader_t CDC_Functional_Header;
+ USB_CDC_Descriptor_FunctionalACM_t CDC_Functional_ACM;
+ USB_CDC_Descriptor_FunctionalUnion_t CDC_Functional_Union;
+ USB_Descriptor_Endpoint_t CDC_NotificationEndpoint;
+
+ // CDC Data Interface
+ USB_Descriptor_Interface_t CDC_DCI_Interface;
+ USB_Descriptor_Endpoint_t CDC_DataOutEndpoint;
+ USB_Descriptor_Endpoint_t CDC_DataInEndpoint;
+#endif
+} USB_Descriptor_Configuration_t;
+
+
+/* index of interface */
+#define KEYBOARD_INTERFACE 0
+
+#ifdef MOUSE_ENABLE
+# define MOUSE_INTERFACE (KEYBOARD_INTERFACE + 1)
+#else
+# define MOUSE_INTERFACE KEYBOARD_INTERFACE
+#endif
+
+#ifdef EXTRAKEY_ENABLE
+# define EXTRAKEY_INTERFACE (MOUSE_INTERFACE + 1)
+#else
+# define EXTRAKEY_INTERFACE MOUSE_INTERFACE
+#endif
+
+#ifdef RAW_ENABLE
+# define RAW_INTERFACE (EXTRAKEY_INTERFACE + 1)
+#else
+# define RAW_INTERFACE EXTRAKEY_INTERFACE
+#endif
+
+#ifdef CONSOLE_ENABLE
+# define CONSOLE_INTERFACE (RAW_INTERFACE + 1)
+#else
+# define CONSOLE_INTERFACE RAW_INTERFACE
+#endif
+
+#ifdef NKRO_ENABLE
+# define NKRO_INTERFACE (CONSOLE_INTERFACE + 1)
+#else
+# define NKRO_INTERFACE CONSOLE_INTERFACE
+#endif
+
+#ifdef MIDI_ENABLE
+# define AC_INTERFACE (NKRO_INTERFACE + 1)
+# define AS_INTERFACE (NKRO_INTERFACE + 2)
+#else
+# define AS_INTERFACE NKRO_INTERFACE
+#endif
+
+#ifdef VIRTSER_ENABLE
+# define CCI_INTERFACE (AS_INTERFACE + 1)
+# define CDI_INTERFACE (AS_INTERFACE + 2)
+#else
+# define CDI_INTERFACE AS_INTERFACE
+#endif
+
+/* nubmer of interfaces */
+#define TOTAL_INTERFACES (CDI_INTERFACE + 1)
+
+
+// Endopoint number and size
+#define KEYBOARD_IN_EPNUM 1
+
+#ifdef MOUSE_ENABLE
+# define MOUSE_IN_EPNUM (KEYBOARD_IN_EPNUM + 1)
+#else
+# define MOUSE_IN_EPNUM KEYBOARD_IN_EPNUM
+#endif
+
+#ifdef EXTRAKEY_ENABLE
+# define EXTRAKEY_IN_EPNUM (MOUSE_IN_EPNUM + 1)
+#else
+# define EXTRAKEY_IN_EPNUM MOUSE_IN_EPNUM
+#endif
+
+#ifdef RAW_ENABLE
+# define RAW_IN_EPNUM (EXTRAKEY_IN_EPNUM + 1)
+# define RAW_OUT_EPNUM (EXTRAKEY_IN_EPNUM + 2)
+#else
+# define RAW_OUT_EPNUM EXTRAKEY_IN_EPNUM
+#endif
+
+#ifdef CONSOLE_ENABLE
+# define CONSOLE_IN_EPNUM (RAW_OUT_EPNUM + 1)
+//# define CONSOLE_OUT_EPNUM (RAW_OUT_EPNUM + 2)
+# define CONSOLE_OUT_EPNUM (RAW_OUT_EPNUM + 1)
+#else
+# define CONSOLE_OUT_EPNUM RAW_OUT_EPNUM
+#endif
+
+#ifdef NKRO_ENABLE
+# define NKRO_IN_EPNUM (CONSOLE_OUT_EPNUM + 1)
+#else
+# define NKRO_IN_EPNUM CONSOLE_OUT_EPNUM
+#endif
+
+#ifdef MIDI_ENABLE
+# define MIDI_STREAM_IN_EPNUM (NKRO_IN_EPNUM + 1)
+// # define MIDI_STREAM_OUT_EPNUM (NKRO_IN_EPNUM + 1)
+# define MIDI_STREAM_OUT_EPNUM (NKRO_IN_EPNUM + 2)
+# define MIDI_STREAM_IN_EPADDR (ENDPOINT_DIR_IN | MIDI_STREAM_IN_EPNUM)
+# define MIDI_STREAM_OUT_EPADDR (ENDPOINT_DIR_OUT | MIDI_STREAM_OUT_EPNUM)
+#else
+# define MIDI_STREAM_OUT_EPNUM NKRO_IN_EPNUM
+#endif
+
+#ifdef VIRTSER_ENABLE
+# define CDC_NOTIFICATION_EPNUM (MIDI_STREAM_OUT_EPNUM + 1)
+# define CDC_IN_EPNUM (MIDI_STREAM_OUT_EPNUM + 2)
+# define CDC_OUT_EPNUM (MIDI_STREAM_OUT_EPNUM + 3)
+# define CDC_NOTIFICATION_EPADDR (ENDPOINT_DIR_IN | CDC_NOTIFICATION_EPNUM)
+# define CDC_IN_EPADDR (ENDPOINT_DIR_IN | CDC_IN_EPNUM)
+# define CDC_OUT_EPADDR (ENDPOINT_DIR_OUT | CDC_OUT_EPNUM)
+#else
+# define CDC_OUT_EPNUM MIDI_STREAM_OUT_EPNUM
+#endif
+
+#if defined(__AVR_ATmega32U2__) && CDC_OUT_EPNUM > 4
+# error "Endpoints are not available enough to support all functions. Remove some in Makefile.(MOUSEKEY, EXTRAKEY, CONSOLE, NKRO, MIDI, SERIAL)"
+#endif
+
+#define KEYBOARD_EPSIZE 8
+#define MOUSE_EPSIZE 8
+#define EXTRAKEY_EPSIZE 8
+#define RAW_EPSIZE 32
+#define CONSOLE_EPSIZE 32
+#define NKRO_EPSIZE 32
+#define MIDI_STREAM_EPSIZE 64
+#define CDC_NOTIFICATION_EPSIZE 8
+#define CDC_EPSIZE 16
+
+
+uint16_t CALLBACK_USB_GetDescriptor(const uint16_t wValue,
+ const uint16_t wIndex,
+ const void** const DescriptorAddress)
+ ATTR_WARN_UNUSED_RESULT ATTR_NON_NULL_PTR_ARG(3);
+
+
+/* new API */
+#if LUFA_VERSION_INTEGER < 0x140302
+ #undef VERSION_BCD
+ #define VERSION_BCD(Major, Minor, Revision) \
+ CPU_TO_LE16( ((Major & 0xFF) << 8) | \
+ ((Minor & 0x0F) << 4) | \
+ (Revision & 0x0F) )
+#endif
+
+#endif
diff --git a/tmk_core/protocol/lufa/lufa.c b/tmk_core/protocol/lufa/lufa.c
new file mode 100644
index 000000000..e3f8724e8
--- /dev/null
+++ b/tmk_core/protocol/lufa/lufa.c
@@ -0,0 +1,1293 @@
+/*
+ * Copyright 2012 Jun Wako <wakojun@gmail.com>
+ * This file is based on:
+ * LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
+ * LUFA-120219/Demos/Device/Lowlevel/GenericHID
+ */
+
+/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+ Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+#include "report.h"
+#include "host.h"
+#include "host_driver.h"
+#include "keyboard.h"
+#include "action.h"
+#include "led.h"
+#include "sendchar.h"
+#include "debug.h"
+#ifdef SLEEP_LED_ENABLE
+#include "sleep_led.h"
+#endif
+#include "suspend.h"
+
+#include "descriptor.h"
+#include "lufa.h"
+#include "quantum.h"
+#include <util/atomic.h>
+#include "outputselect.h"
+
+#ifdef NKRO_ENABLE
+ #include "keycode_config.h"
+
+ extern keymap_config_t keymap_config;
+#endif
+
+
+#ifdef AUDIO_ENABLE
+ #include <audio.h>
+#endif
+
+#ifdef BLUETOOTH_ENABLE
+ #ifdef MODULE_ADAFRUIT_BLE
+ #include "adafruit_ble.h"
+ #else
+ #include "bluetooth.h"
+ #endif
+#endif
+
+#ifdef VIRTSER_ENABLE
+ #include "virtser.h"
+#endif
+
+#if (defined(RGB_MIDI) | defined(RGBLIGHT_ANIMATIONS)) & defined(RGBLIGHT_ENABLE)
+ #include "rgblight.h"
+#endif
+
+#ifdef MIDI_ENABLE
+ #include "sysex_tools.h"
+#endif
+
+#ifdef RAW_ENABLE
+ #include "raw_hid.h"
+#endif
+
+uint8_t keyboard_idle = 0;
+/* 0: Boot Protocol, 1: Report Protocol(default) */
+uint8_t keyboard_protocol = 1;
+static uint8_t keyboard_led_stats = 0;
+
+static report_keyboard_t keyboard_report_sent;
+
+#ifdef MIDI_ENABLE
+static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
+static void usb_get_midi(MidiDevice * device);
+static void midi_usb_init(MidiDevice * device);
+#endif
+
+/* Host driver */
+static uint8_t keyboard_leds(void);
+static void send_keyboard(report_keyboard_t *report);
+static void send_mouse(report_mouse_t *report);
+static void send_system(uint16_t data);
+static void send_consumer(uint16_t data);
+host_driver_t lufa_driver = {
+ keyboard_leds,
+ send_keyboard,
+ send_mouse,
+ send_system,
+ send_consumer,
+#ifdef MIDI_ENABLE
+ usb_send_func,
+ usb_get_midi,
+ midi_usb_init
+#endif
+};
+
+/*******************************************************************************
+ * MIDI
+ ******************************************************************************/
+
+#ifdef MIDI_ENABLE
+USB_ClassInfo_MIDI_Device_t USB_MIDI_Interface =
+{
+ .Config =
+ {
+ .StreamingInterfaceNumber = AS_INTERFACE,
+ .DataINEndpoint =
+ {
+ .Address = MIDI_STREAM_IN_EPADDR,
+ .Size = MIDI_STREAM_EPSIZE,
+ .Banks = 1,
+ },
+ .DataOUTEndpoint =
+ {
+ .Address = MIDI_STREAM_OUT_EPADDR,
+ .Size = MIDI_STREAM_EPSIZE,
+ .Banks = 1,
+ },
+ },
+};
+
+#define SYSEX_START_OR_CONT 0x40
+#define SYSEX_ENDS_IN_1 0x50
+#define SYSEX_ENDS_IN_2 0x60
+#define SYSEX_ENDS_IN_3 0x70
+
+#define SYS_COMMON_1 0x50
+#define SYS_COMMON_2 0x20
+#define SYS_COMMON_3 0x30
+#endif
+
+#ifdef VIRTSER_ENABLE
+USB_ClassInfo_CDC_Device_t cdc_device =
+{
+ .Config =
+ {
+ .ControlInterfaceNumber = CCI_INTERFACE,
+ .DataINEndpoint =
+ {
+ .Address = CDC_IN_EPADDR,
+ .Size = CDC_EPSIZE,
+ .Banks = 1,
+ },
+ .DataOUTEndpoint =
+ {
+ .Address = CDC_OUT_EPADDR,
+ .Size = CDC_EPSIZE,
+ .Banks = 1,
+ },
+ .NotificationEndpoint =
+ {
+ .Address = CDC_NOTIFICATION_EPADDR,
+ .Size = CDC_NOTIFICATION_EPSIZE,
+ .Banks = 1,
+ },
+ },
+};
+#endif
+
+#ifdef RAW_ENABLE
+
+void raw_hid_send( uint8_t *data, uint8_t length )
+{
+ // TODO: implement variable size packet
+ if ( length != RAW_EPSIZE )
+ {
+ return;
+ }
+
+ if (USB_DeviceState != DEVICE_STATE_Configured)
+ {
+ return;
+ }
+
+ // TODO: decide if we allow calls to raw_hid_send() in the middle
+ // of other endpoint usage.
+ uint8_t ep = Endpoint_GetCurrentEndpoint();
+
+ Endpoint_SelectEndpoint(RAW_IN_EPNUM);
+
+ // Check to see if the host is ready to accept another packet
+ if (Endpoint_IsINReady())
+ {
+ // Write data
+ Endpoint_Write_Stream_LE(data, RAW_EPSIZE, NULL);
+ // Finalize the stream transfer to send the last packet
+ Endpoint_ClearIN();
+ }
+
+ Endpoint_SelectEndpoint(ep);
+}
+
+__attribute__ ((weak))
+void raw_hid_receive( uint8_t *data, uint8_t length )
+{
+ // Users should #include "raw_hid.h" in their own code
+ // and implement this function there. Leave this as weak linkage
+ // so users can opt to not handle data coming in.
+}
+
+static void raw_hid_task(void)
+{
+ // Create a temporary buffer to hold the read in data from the host
+ uint8_t data[RAW_EPSIZE];
+ bool data_read = false;
+
+ // Device must be connected and configured for the task to run
+ if (USB_DeviceState != DEVICE_STATE_Configured)
+ return;
+
+ Endpoint_SelectEndpoint(RAW_OUT_EPNUM);
+
+ // Check to see if a packet has been sent from the host
+ if (Endpoint_IsOUTReceived())
+ {
+ // Check to see if the packet contains data
+ if (Endpoint_IsReadWriteAllowed())
+ {
+ /* Read data */
+ Endpoint_Read_Stream_LE(data, sizeof(data), NULL);
+ data_read = true;
+ }
+
+ // Finalize the stream transfer to receive the last packet
+ Endpoint_ClearOUT();
+
+ if ( data_read )
+ {
+ raw_hid_receive( data, sizeof(data) );
+ }
+ }
+}
+#endif
+
+/*******************************************************************************
+ * Console
+ ******************************************************************************/
+#ifdef CONSOLE_ENABLE
+static void Console_Task(void)
+{
+ /* Device must be connected and configured for the task to run */
+ if (USB_DeviceState != DEVICE_STATE_Configured)
+ return;
+
+ uint8_t ep = Endpoint_GetCurrentEndpoint();
+
+#if 0
+ // TODO: impl receivechar()/recvchar()
+ Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
+
+ /* Check to see if a packet has been sent from the host */
+ if (Endpoint_IsOUTReceived())
+ {
+ /* Check to see if the packet contains data */
+ if (Endpoint_IsReadWriteAllowed())
+ {
+ /* Create a temporary buffer to hold the read in report from the host */
+ uint8_t ConsoleData[CONSOLE_EPSIZE];
+
+ /* Read Console Report Data */
+ Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
+
+ /* Process Console Report Data */
+ //ProcessConsoleHIDReport(ConsoleData);
+ }
+
+ /* Finalize the stream transfer to send the last packet */
+ Endpoint_ClearOUT();
+ }
+#endif
+
+ /* IN packet */
+ Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
+ if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
+ Endpoint_SelectEndpoint(ep);
+ return;
+ }
+
+ // fill empty bank
+ while (Endpoint_IsReadWriteAllowed())
+ Endpoint_Write_8(0);
+
+ // flash senchar packet
+ if (Endpoint_IsINReady()) {
+ Endpoint_ClearIN();
+ }
+
+ Endpoint_SelectEndpoint(ep);
+}
+#endif
+
+
+/*******************************************************************************
+ * USB Events
+ ******************************************************************************/
+/*
+ * Event Order of Plug in:
+ * 0) EVENT_USB_Device_Connect
+ * 1) EVENT_USB_Device_Suspend
+ * 2) EVENT_USB_Device_Reset
+ * 3) EVENT_USB_Device_Wake
+*/
+void EVENT_USB_Device_Connect(void)
+{
+ print("[C]");
+ /* For battery powered device */
+ if (!USB_IsInitialized) {
+ USB_Disable();
+ USB_Init();
+ USB_Device_EnableSOFEvents();
+ }
+}
+
+void EVENT_USB_Device_Disconnect(void)
+{
+ print("[D]");
+ /* For battery powered device */
+ USB_IsInitialized = false;
+/* TODO: This doesn't work. After several plug in/outs can not be enumerated.
+ if (USB_IsInitialized) {
+ USB_Disable(); // Disable all interrupts
+ USB_Controller_Enable();
+ USB_INT_Enable(USB_INT_VBUSTI);
+ }
+*/
+}
+
+void EVENT_USB_Device_Reset(void)
+{
+ print("[R]");
+}
+
+void EVENT_USB_Device_Suspend()
+{
+ print("[S]");
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_enable();
+#endif
+}
+
+void EVENT_USB_Device_WakeUp()
+{
+ print("[W]");
+ suspend_wakeup_init();
+
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_disable();
+ // NOTE: converters may not accept this
+ led_set(host_keyboard_leds());
+#endif
+}
+
+
+
+#ifdef CONSOLE_ENABLE
+static bool console_flush = false;
+#define CONSOLE_FLUSH_SET(b) do { \
+ ATOMIC_BLOCK(ATOMIC_RESTORESTATE) {\
+ console_flush = b; \
+ } \
+} while (0)
+
+// called every 1ms
+void EVENT_USB_Device_StartOfFrame(void)
+{
+ static uint8_t count;
+ if (++count % 50) return;
+ count = 0;
+
+ if (!console_flush) return;
+ Console_Task();
+ console_flush = false;
+}
+
+#endif
+
+/** Event handler for the USB_ConfigurationChanged event.
+ * This is fired when the host sets the current configuration of the USB device after enumeration.
+ *
+ * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
+ * it is safe to use singl bank for all endpoints.
+ */
+void EVENT_USB_Device_ConfigurationChanged(void)
+{
+ bool ConfigSuccess = true;
+
+ /* Setup Keyboard HID Report Endpoints */
+ ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
+ KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
+
+#ifdef MOUSE_ENABLE
+ /* Setup Mouse HID Report Endpoint */
+ ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
+ MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
+#endif
+
+#ifdef EXTRAKEY_ENABLE
+ /* Setup Extra HID Report Endpoint */
+ ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
+ EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
+#endif
+
+#ifdef RAW_ENABLE
+ /* Setup Raw HID Report Endpoints */
+ ConfigSuccess &= ENDPOINT_CONFIG(RAW_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
+ RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
+ ConfigSuccess &= ENDPOINT_CONFIG(RAW_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
+ RAW_EPSIZE, ENDPOINT_BANK_SINGLE);
+#endif
+
+#ifdef CONSOLE_ENABLE
+ /* Setup Console HID Report Endpoints */
+ ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
+ CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
+#if 0
+ ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
+ CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
+#endif
+#endif
+
+#ifdef NKRO_ENABLE
+ /* Setup NKRO HID Report Endpoints */
+ ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
+ NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
+#endif
+
+#ifdef MIDI_ENABLE
+ ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_IN_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
+ ConfigSuccess &= Endpoint_ConfigureEndpoint(MIDI_STREAM_OUT_EPADDR, EP_TYPE_BULK, MIDI_STREAM_EPSIZE, ENDPOINT_BANK_SINGLE);
+#endif
+
+#ifdef VIRTSER_ENABLE
+ ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_NOTIFICATION_EPADDR, EP_TYPE_INTERRUPT, CDC_NOTIFICATION_EPSIZE, ENDPOINT_BANK_SINGLE);
+ ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_OUT_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
+ ConfigSuccess &= Endpoint_ConfigureEndpoint(CDC_IN_EPADDR, EP_TYPE_BULK, CDC_EPSIZE, ENDPOINT_BANK_SINGLE);
+#endif
+}
+
+/*
+Appendix G: HID Request Support Requirements
+
+The following table enumerates the requests that need to be supported by various types of HID class devices.
+
+Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
+------------------------------------------------------------------------------------------
+Boot Mouse Required Optional Optional Optional Required Required
+Non-Boot Mouse Required Optional Optional Optional Optional Optional
+Boot Keyboard Required Optional Required Required Required Required
+Non-Boot Keybrd Required Optional Required Required Optional Optional
+Other Device Required Optional Optional Optional Optional Optional
+*/
+/** Event handler for the USB_ControlRequest event.
+ * This is fired before passing along unhandled control requests to the library for processing internally.
+ */
+void EVENT_USB_Device_ControlRequest(void)
+{
+ uint8_t* ReportData = NULL;
+ uint8_t ReportSize = 0;
+
+ /* Handle HID Class specific requests */
+ switch (USB_ControlRequest.bRequest)
+ {
+ case HID_REQ_GetReport:
+ if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
+ {
+ Endpoint_ClearSETUP();
+
+ // Interface
+ switch (USB_ControlRequest.wIndex) {
+ case KEYBOARD_INTERFACE:
+ // TODO: test/check
+ ReportData = (uint8_t*)&keyboard_report_sent;
+ ReportSize = sizeof(keyboard_report_sent);
+ break;
+ }
+
+ /* Write the report data to the control endpoint */
+ Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
+ Endpoint_ClearOUT();
+ }
+
+ break;
+ case HID_REQ_SetReport:
+ if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
+ {
+
+ // Interface
+ switch (USB_ControlRequest.wIndex) {
+ case KEYBOARD_INTERFACE:
+#ifdef NKRO_ENABLE
+ case NKRO_INTERFACE:
+#endif
+ Endpoint_ClearSETUP();
+
+ while (!(Endpoint_IsOUTReceived())) {
+ if (USB_DeviceState == DEVICE_STATE_Unattached)
+ return;
+ }
+ keyboard_led_stats = Endpoint_Read_8();
+
+ Endpoint_ClearOUT();
+ Endpoint_ClearStatusStage();
+ break;
+ }
+
+ }
+
+ break;
+
+ case HID_REQ_GetProtocol:
+ if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
+ {
+ if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
+ Endpoint_ClearSETUP();
+ while (!(Endpoint_IsINReady()));
+ Endpoint_Write_8(keyboard_protocol);
+ Endpoint_ClearIN();
+ Endpoint_ClearStatusStage();
+ }
+ }
+
+ break;
+ case HID_REQ_SetProtocol:
+ if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
+ {
+ if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
+ Endpoint_ClearSETUP();
+ Endpoint_ClearStatusStage();
+
+ keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
+ clear_keyboard();
+ }
+ }
+
+ break;
+ case HID_REQ_SetIdle:
+ if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
+ {
+ Endpoint_ClearSETUP();
+ Endpoint_ClearStatusStage();
+
+ keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
+ }
+
+ break;
+ case HID_REQ_GetIdle:
+ if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
+ {
+ Endpoint_ClearSETUP();
+ while (!(Endpoint_IsINReady()));
+ Endpoint_Write_8(keyboard_idle);
+ Endpoint_ClearIN();
+ Endpoint_ClearStatusStage();
+ }
+
+ break;
+ }
+
+#ifdef VIRTSER_ENABLE
+ CDC_Device_ProcessControlRequest(&cdc_device);
+#endif
+}
+
+/*******************************************************************************
+ * Host driver
+ ******************************************************************************/
+static uint8_t keyboard_leds(void)
+{
+ return keyboard_led_stats;
+}
+
+static void send_keyboard(report_keyboard_t *report)
+{
+ uint8_t timeout = 255;
+ uint8_t where = where_to_send();
+
+#ifdef BLUETOOTH_ENABLE
+ if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
+ #ifdef MODULE_ADAFRUIT_BLE
+ adafruit_ble_send_keys(report->mods, report->keys, sizeof(report->keys));
+ #elif MODULE_RN42
+ bluefruit_serial_send(0xFD);
+ bluefruit_serial_send(0x09);
+ bluefruit_serial_send(0x01);
+ for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
+ bluefruit_serial_send(report->raw[i]);
+ }
+ #else
+ bluefruit_serial_send(0xFD);
+ for (uint8_t i = 0; i < KEYBOARD_EPSIZE; i++) {
+ bluefruit_serial_send(report->raw[i]);
+ }
+ #endif
+ }
+#endif
+
+ if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
+ return;
+ }
+
+ /* Select the Keyboard Report Endpoint */
+#ifdef NKRO_ENABLE
+ if (keyboard_protocol && keymap_config.nkro) {
+ /* Report protocol - NKRO */
+ Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
+
+ /* Check if write ready for a polling interval around 1ms */
+ while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
+ if (!Endpoint_IsReadWriteAllowed()) return;
+
+ /* Write Keyboard Report Data */
+ Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
+ }
+ else
+#endif
+ {
+ /* Boot protocol */
+ Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
+
+ /* Check if write ready for a polling interval around 10ms */
+ while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
+ if (!Endpoint_IsReadWriteAllowed()) return;
+
+ /* Write Keyboard Report Data */
+ Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
+ }
+
+ /* Finalize the stream transfer to send the last packet */
+ Endpoint_ClearIN();
+
+ keyboard_report_sent = *report;
+}
+
+static void send_mouse(report_mouse_t *report)
+{
+#ifdef MOUSE_ENABLE
+ uint8_t timeout = 255;
+ uint8_t where = where_to_send();
+
+#ifdef BLUETOOTH_ENABLE
+ if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
+ #ifdef MODULE_ADAFRUIT_BLE
+ // FIXME: mouse buttons
+ adafruit_ble_send_mouse_move(report->x, report->y, report->v, report->h, report->buttons);
+ #else
+ bluefruit_serial_send(0xFD);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x03);
+ bluefruit_serial_send(report->buttons);
+ bluefruit_serial_send(report->x);
+ bluefruit_serial_send(report->y);
+ bluefruit_serial_send(report->v); // should try sending the wheel v here
+ bluefruit_serial_send(report->h); // should try sending the wheel h here
+ bluefruit_serial_send(0x00);
+ #endif
+ }
+#endif
+
+ if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
+ return;
+ }
+
+ /* Select the Mouse Report Endpoint */
+ Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
+
+ /* Check if write ready for a polling interval around 10ms */
+ while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
+ if (!Endpoint_IsReadWriteAllowed()) return;
+
+ /* Write Mouse Report Data */
+ Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
+
+ /* Finalize the stream transfer to send the last packet */
+ Endpoint_ClearIN();
+#endif
+}
+
+static void send_system(uint16_t data)
+{
+ uint8_t timeout = 255;
+
+ if (USB_DeviceState != DEVICE_STATE_Configured)
+ return;
+
+ report_extra_t r = {
+ .report_id = REPORT_ID_SYSTEM,
+ .usage = data - SYSTEM_POWER_DOWN + 1
+ };
+ Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
+
+ /* Check if write ready for a polling interval around 10ms */
+ while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
+ if (!Endpoint_IsReadWriteAllowed()) return;
+
+ Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
+ Endpoint_ClearIN();
+}
+
+static void send_consumer(uint16_t data)
+{
+ uint8_t timeout = 255;
+ uint8_t where = where_to_send();
+
+#ifdef BLUETOOTH_ENABLE
+ if (where == OUTPUT_BLUETOOTH || where == OUTPUT_USB_AND_BT) {
+ #ifdef MODULE_ADAFRUIT_BLE
+ adafruit_ble_send_consumer_key(data, 0);
+ #elif MODULE_RN42
+ static uint16_t last_data = 0;
+ if (data == last_data) return;
+ last_data = data;
+ uint16_t bitmap = CONSUMER2RN42(data);
+ bluefruit_serial_send(0xFD);
+ bluefruit_serial_send(0x03);
+ bluefruit_serial_send(0x03);
+ bluefruit_serial_send(bitmap&0xFF);
+ bluefruit_serial_send((bitmap>>8)&0xFF);
+ #else
+ static uint16_t last_data = 0;
+ if (data == last_data) return;
+ last_data = data;
+ uint16_t bitmap = CONSUMER2BLUEFRUIT(data);
+ bluefruit_serial_send(0xFD);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x02);
+ bluefruit_serial_send((bitmap>>8)&0xFF);
+ bluefruit_serial_send(bitmap&0xFF);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x00);
+ bluefruit_serial_send(0x00);
+ #endif
+ }
+#endif
+
+ if (where != OUTPUT_USB && where != OUTPUT_USB_AND_BT) {
+ return;
+ }
+
+ report_extra_t r = {
+ .report_id = REPORT_ID_CONSUMER,
+ .usage = data
+ };
+ Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
+
+ /* Check if write ready for a polling interval around 10ms */
+ while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
+ if (!Endpoint_IsReadWriteAllowed()) return;
+
+ Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
+ Endpoint_ClearIN();
+}
+
+
+/*******************************************************************************
+ * sendchar
+ ******************************************************************************/
+#ifdef CONSOLE_ENABLE
+#define SEND_TIMEOUT 5
+int8_t sendchar(uint8_t c)
+{
+ // Not wait once timeouted.
+ // Because sendchar() is called so many times, waiting each call causes big lag.
+ static bool timeouted = false;
+
+ // prevents Console_Task() from running during sendchar() runs.
+ // or char will be lost. These two function is mutually exclusive.
+ CONSOLE_FLUSH_SET(false);
+
+ if (USB_DeviceState != DEVICE_STATE_Configured)
+ return -1;
+
+ uint8_t ep = Endpoint_GetCurrentEndpoint();
+ Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
+ if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
+ goto ERROR_EXIT;
+ }
+
+ if (timeouted && !Endpoint_IsReadWriteAllowed()) {
+ goto ERROR_EXIT;
+ }
+
+ timeouted = false;
+
+ uint8_t timeout = SEND_TIMEOUT;
+ while (!Endpoint_IsReadWriteAllowed()) {
+ if (USB_DeviceState != DEVICE_STATE_Configured) {
+ goto ERROR_EXIT;
+ }
+ if (Endpoint_IsStalled()) {
+ goto ERROR_EXIT;
+ }
+ if (!(timeout--)) {
+ timeouted = true;
+ goto ERROR_EXIT;
+ }
+ _delay_ms(1);
+ }
+
+ Endpoint_Write_8(c);
+
+ // send when bank is full
+ if (!Endpoint_IsReadWriteAllowed()) {
+ while (!(Endpoint_IsINReady()));
+ Endpoint_ClearIN();
+ } else {
+ CONSOLE_FLUSH_SET(true);
+ }
+
+ Endpoint_SelectEndpoint(ep);
+ return 0;
+ERROR_EXIT:
+ Endpoint_SelectEndpoint(ep);
+ return -1;
+}
+#else
+int8_t sendchar(uint8_t c)
+{
+ return 0;
+}
+#endif
+
+/*******************************************************************************
+ * MIDI
+ ******************************************************************************/
+
+#ifdef MIDI_ENABLE
+static void usb_send_func(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2) {
+ MIDI_EventPacket_t event;
+ event.Data1 = byte0;
+ event.Data2 = byte1;
+ event.Data3 = byte2;
+
+ uint8_t cable = 0;
+
+// Endpoint_SelectEndpoint(MIDI_STREAM_IN_EPNUM);
+
+ //if the length is undefined we assume it is a SYSEX message
+ if (midi_packet_length(byte0) == UNDEFINED) {
+ switch(cnt) {
+ case 3:
+ if (byte2 == SYSEX_END)
+ event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_3);
+ else
+ event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
+ break;
+ case 2:
+ if (byte1 == SYSEX_END)
+ event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_2);
+ else
+ event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
+ break;
+ case 1:
+ if (byte0 == SYSEX_END)
+ event.Event = MIDI_EVENT(cable, SYSEX_ENDS_IN_1);
+ else
+ event.Event = MIDI_EVENT(cable, SYSEX_START_OR_CONT);
+ break;
+ default:
+ return; //invalid cnt
+ }
+ } else {
+ //deal with 'system common' messages
+ //TODO are there any more?
+ switch(byte0 & 0xF0){
+ case MIDI_SONGPOSITION:
+ event.Event = MIDI_EVENT(cable, SYS_COMMON_3);
+ break;
+ case MIDI_SONGSELECT:
+ case MIDI_TC_QUARTERFRAME:
+ event.Event = MIDI_EVENT(cable, SYS_COMMON_2);
+ break;
+ default:
+ event.Event = MIDI_EVENT(cable, byte0);
+ break;
+ }
+ }
+
+// Endpoint_Write_Stream_LE(&event, sizeof(event), NULL);
+// Endpoint_ClearIN();
+
+ MIDI_Device_SendEventPacket(&USB_MIDI_Interface, &event);
+ MIDI_Device_Flush(&USB_MIDI_Interface);
+ MIDI_Device_USBTask(&USB_MIDI_Interface);
+ USB_USBTask();
+}
+
+static void usb_get_midi(MidiDevice * device) {
+ MIDI_EventPacket_t event;
+ while (MIDI_Device_ReceiveEventPacket(&USB_MIDI_Interface, &event)) {
+
+ midi_packet_length_t length = midi_packet_length(event.Data1);
+ uint8_t input[3];
+ input[0] = event.Data1;
+ input[1] = event.Data2;
+ input[2] = event.Data3;
+ if (length == UNDEFINED) {
+ //sysex
+ if (event.Event == MIDI_EVENT(0, SYSEX_START_OR_CONT) || event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_3)) {
+ length = 3;
+ } else if (event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_2)) {
+ length = 2;
+ } else if(event.Event == MIDI_EVENT(0, SYSEX_ENDS_IN_1)) {
+ length = 1;
+ } else {
+ //XXX what to do?
+ }
+ }
+
+ //pass the data to the device input function
+ if (length != UNDEFINED)
+ midi_device_input(device, length, input);
+ }
+ MIDI_Device_USBTask(&USB_MIDI_Interface);
+ USB_USBTask();
+}
+
+static void midi_usb_init(MidiDevice * device){
+ midi_device_init(device);
+ midi_device_set_send_func(device, usb_send_func);
+ midi_device_set_pre_input_process_func(device, usb_get_midi);
+
+ // SetupHardware();
+ sei();
+}
+
+void MIDI_Task(void)
+{
+
+ /* Device must be connected and configured for the task to run */
+ dprint("in MIDI_TASK\n");
+ if (USB_DeviceState != DEVICE_STATE_Configured)
+ return;
+ dprint("continuing in MIDI_TASK\n");
+
+ Endpoint_SelectEndpoint(MIDI_STREAM_IN_EPADDR);
+
+ if (Endpoint_IsINReady())
+ {
+
+ dprint("Endpoint is ready\n");
+
+ uint8_t MIDICommand = 0;
+ uint8_t MIDIPitch;
+
+ /* Get board button status - if pressed use channel 10 (percussion), otherwise use channel 1 */
+ uint8_t Channel = MIDI_CHANNEL(1);
+
+ MIDICommand = MIDI_COMMAND_NOTE_ON;
+ MIDIPitch = 0x3E;
+
+ /* Check if a MIDI command is to be sent */
+ if (MIDICommand)
+ {
+ dprint("Command exists\n");
+ MIDI_EventPacket_t MIDIEvent = (MIDI_EventPacket_t)
+ {
+ .Event = MIDI_EVENT(0, MIDICommand),
+
+ .Data1 = MIDICommand | Channel,
+ .Data2 = MIDIPitch,
+ .Data3 = MIDI_STANDARD_VELOCITY,
+ };
+
+ /* Write the MIDI event packet to the endpoint */
+ Endpoint_Write_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);
+
+ /* Send the data in the endpoint to the host */
+ Endpoint_ClearIN();
+ }
+ }
+
+
+ /* Select the MIDI OUT stream */
+ Endpoint_SelectEndpoint(MIDI_STREAM_OUT_EPADDR);
+
+ /* Check if a MIDI command has been received */
+ if (Endpoint_IsOUTReceived())
+ {
+ MIDI_EventPacket_t MIDIEvent;
+
+ /* Read the MIDI event packet from the endpoint */
+ Endpoint_Read_Stream_LE(&MIDIEvent, sizeof(MIDIEvent), NULL);
+
+ /* If the endpoint is now empty, clear the bank */
+ if (!(Endpoint_BytesInEndpoint()))
+ {
+ /* Clear the endpoint ready for new packet */
+ Endpoint_ClearOUT();
+ }
+ }
+}
+
+#endif
+
+/*******************************************************************************
+ * VIRTUAL SERIAL
+ ******************************************************************************/
+
+#ifdef VIRTSER_ENABLE
+void virtser_init(void)
+{
+ cdc_device.State.ControlLineStates.DeviceToHost = CDC_CONTROL_LINE_IN_DSR ;
+ CDC_Device_SendControlLineStateChange(&cdc_device);
+}
+
+void virtser_recv(uint8_t c) __attribute__ ((weak));
+void virtser_recv(uint8_t c)
+{
+ // Ignore by default
+}
+
+void virtser_task(void)
+{
+ uint16_t count = CDC_Device_BytesReceived(&cdc_device);
+ uint8_t ch;
+ if (count)
+ {
+ ch = CDC_Device_ReceiveByte(&cdc_device);
+ virtser_recv(ch);
+ }
+}
+void virtser_send(const uint8_t byte)
+{
+ uint8_t timeout = 255;
+ uint8_t ep = Endpoint_GetCurrentEndpoint();
+
+ if (cdc_device.State.ControlLineStates.HostToDevice & CDC_CONTROL_LINE_OUT_DTR)
+ {
+ /* IN packet */
+ Endpoint_SelectEndpoint(cdc_device.Config.DataINEndpoint.Address);
+
+ if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
+ Endpoint_SelectEndpoint(ep);
+ return;
+ }
+
+ while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
+
+ Endpoint_Write_8(byte);
+ CDC_Device_Flush(&cdc_device);
+
+ if (Endpoint_IsINReady()) {
+ Endpoint_ClearIN();
+ }
+
+ Endpoint_SelectEndpoint(ep);
+ }
+}
+#endif
+
+/*******************************************************************************
+ * main
+ ******************************************************************************/
+static void setup_mcu(void)
+{
+ /* Disable watchdog if enabled by bootloader/fuses */
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ /* Disable clock division */
+ // clock_prescale_set(clock_div_1);
+
+ CLKPR = (1 << CLKPCE);
+ CLKPR = (0 << CLKPS3) | (0 << CLKPS2) | (0 << CLKPS1) | (0 << CLKPS0);
+}
+
+static void setup_usb(void)
+{
+ // Leonardo needs. Without this USB device is not recognized.
+ USB_Disable();
+
+ USB_Init();
+
+ // for Console_Task
+ USB_Device_EnableSOFEvents();
+ print_set_sendchar(sendchar);
+}
+
+
+#ifdef MIDI_ENABLE
+void fallthrough_callback(MidiDevice * device,
+ uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
+void cc_callback(MidiDevice * device,
+ uint8_t chan, uint8_t num, uint8_t val);
+void sysex_callback(MidiDevice * device,
+ uint16_t start, uint8_t length, uint8_t * data);
+
+void setup_midi(void)
+{
+#ifdef MIDI_ADVANCED
+ midi_init();
+#endif
+ midi_device_init(&midi_device);
+ midi_device_set_send_func(&midi_device, usb_send_func);
+ midi_device_set_pre_input_process_func(&midi_device, usb_get_midi);
+}
+#endif
+
+int main(void) __attribute__ ((weak));
+int main(void)
+{
+#ifdef MIDI_ENABLE
+ setup_midi();
+#endif
+
+ setup_mcu();
+ keyboard_setup();
+ setup_usb();
+ sei();
+
+#ifdef MIDI_ENABLE
+ midi_register_fallthrough_callback(&midi_device, fallthrough_callback);
+ midi_register_cc_callback(&midi_device, cc_callback);
+ midi_register_sysex_callback(&midi_device, sysex_callback);
+
+ // init_notes();
+ // midi_send_cc(&midi_device, 0, 1, 2);
+ // midi_send_cc(&midi_device, 15, 1, 0);
+ // midi_send_noteon(&midi_device, 0, 64, 127);
+ // midi_send_noteoff(&midi_device, 0, 64, 127);
+#endif
+
+#if defined(MODULE_ADAFRUIT_EZKEY) || defined(MODULE_RN42)
+ serial_init();
+#endif
+
+ /* wait for USB startup & debug output */
+
+#ifdef WAIT_FOR_USB
+ while (USB_DeviceState != DEVICE_STATE_Configured) {
+ #if defined(INTERRUPT_CONTROL_ENDPOINT)
+ ;
+ #else
+ USB_USBTask();
+ #endif
+ }
+ print("USB configured.\n");
+#else
+ USB_USBTask();
+#endif
+ /* init modules */
+ keyboard_init();
+ host_set_driver(&lufa_driver);
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_init();
+#endif
+
+#ifdef VIRTSER_ENABLE
+ virtser_init();
+#endif
+
+ print("Keyboard start.\n");
+ while (1) {
+ #if !defined(NO_USB_STARTUP_CHECK)
+ while (USB_DeviceState == DEVICE_STATE_Suspended) {
+ print("[s]");
+ suspend_power_down();
+ if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
+ USB_Device_SendRemoteWakeup();
+ }
+ }
+ #endif
+
+ keyboard_task();
+
+#ifdef MIDI_ENABLE
+ midi_device_process(&midi_device);
+#ifdef MIDI_ADVANCED
+ midi_task();
+#endif
+#endif
+
+#if defined(RGBLIGHT_ANIMATIONS) & defined(RGBLIGHT_ENABLE)
+ rgblight_task();
+#endif
+
+#ifdef MODULE_ADAFRUIT_BLE
+ adafruit_ble_task();
+#endif
+
+#ifdef VIRTSER_ENABLE
+ virtser_task();
+ CDC_Device_USBTask(&cdc_device);
+#endif
+
+#ifdef RAW_ENABLE
+ raw_hid_task();
+#endif
+
+#if !defined(INTERRUPT_CONTROL_ENDPOINT)
+ USB_USBTask();
+#endif
+
+ }
+}
+
+#ifdef MIDI_ENABLE
+void fallthrough_callback(MidiDevice * device,
+ uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2){
+
+#ifdef AUDIO_ENABLE
+ if (cnt == 3) {
+ switch (byte0 & 0xF0) {
+ case MIDI_NOTEON:
+ play_note(((double)261.6)*pow(2.0, -4.0)*pow(2.0,(byte1 & 0x7F)/12.0), (byte2 & 0x7F) / 8);
+ break;
+ case MIDI_NOTEOFF:
+ stop_note(((double)261.6)*pow(2.0, -4.0)*pow(2.0,(byte1 & 0x7F)/12.0));
+ break;
+ }
+ }
+ if (byte0 == MIDI_STOP) {
+ stop_all_notes();
+ }
+#endif
+}
+
+
+void cc_callback(MidiDevice * device,
+ uint8_t chan, uint8_t num, uint8_t val) {
+ //sending it back on the next channel
+ // midi_send_cc(device, (chan + 1) % 16, num, val);
+}
+
+#ifdef API_SYSEX_ENABLE
+uint8_t midi_buffer[MIDI_SYSEX_BUFFER] = {0};
+#endif
+
+void sysex_callback(MidiDevice * device, uint16_t start, uint8_t length, uint8_t * data) {
+ #ifdef API_SYSEX_ENABLE
+ // SEND_STRING("\n");
+ // send_word(start);
+ // SEND_STRING(": ");
+ // Don't store the header
+ int16_t pos = start - 4;
+ for (uint8_t place = 0; place < length; place++) {
+ // send_byte(*data);
+ if (pos >= 0) {
+ if (*data == 0xF7) {
+ // SEND_STRING("\nRD: ");
+ // for (uint8_t i = 0; i < start + place + 1; i++){
+ // send_byte(midi_buffer[i]);
+ // SEND_STRING(" ");
+ // }
+ const unsigned decoded_length = sysex_decoded_length(pos);
+ uint8_t decoded[API_SYSEX_MAX_SIZE];
+ sysex_decode(decoded, midi_buffer, pos);
+ process_api(decoded_length, decoded);
+ return;
+ }
+ else if (pos >= MIDI_SYSEX_BUFFER) {
+ return;
+ }
+ midi_buffer[pos] = *data;
+ }
+ // SEND_STRING(" ");
+ data++;
+ pos++;
+ }
+ #endif
+}
+
+
+#endif
diff --git a/tmk_core/protocol/lufa/lufa.h b/tmk_core/protocol/lufa/lufa.h
new file mode 100644
index 000000000..a51573786
--- /dev/null
+++ b/tmk_core/protocol/lufa/lufa.h
@@ -0,0 +1,96 @@
+/*
+ * Copyright 2012 Jun Wako <wakojun@gmail.com>
+ * This file is based on:
+ * LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
+ * LUFA-120219/Demos/Device/Lowlevel/GenericHID
+ */
+
+/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+ Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+#ifndef _LUFA_H_
+#define _LUFA_H_
+
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/power.h>
+#include <avr/interrupt.h>
+#include <stdbool.h>
+#include <string.h>
+#include <LUFA/Version.h>
+#include <LUFA/Drivers/USB/USB.h>
+#include "host.h"
+#ifdef MIDI_ENABLE
+ #include "process_midi.h"
+#endif
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern host_driver_t lufa_driver;
+
+#ifdef __cplusplus
+}
+#endif
+
+/* extra report structure */
+typedef struct {
+ uint8_t report_id;
+ uint16_t usage;
+} __attribute__ ((packed)) report_extra_t;
+
+#ifdef MIDI_ENABLE
+ void MIDI_Task(void);
+ MidiDevice midi_device;
+#endif
+
+#ifdef API_ENABLE
+ #include "api.h"
+#endif
+
+#ifdef API_SYSEX_ENABLE
+ #include "api_sysex.h"
+ // Allocate space for encoding overhead.
+ //The header and terminator are not stored to save a few bytes of precious ram
+ #define MIDI_SYSEX_BUFFER (API_SYSEX_MAX_SIZE + API_SYSEX_MAX_SIZE / 7 + (API_SYSEX_MAX_SIZE % 7 ? 1 : 0))
+#endif
+
+// #if LUFA_VERSION_INTEGER < 0x120730
+// /* old API 120219 */
+// #define ENDPOINT_CONFIG(epnum, eptype, epdir, epsize, epbank) Endpoint_ConfigureEndpoint(epnum, eptype, epdir, epsize, epbank)
+// #else
+ /* new API >= 120730 */
+ #define ENDPOINT_BANK_SINGLE 1
+ #define ENDPOINT_BANK_DOUBLE 2
+ #define ENDPOINT_CONFIG(epnum, eptype, epdir, epsize, epbank) Endpoint_ConfigureEndpoint((epdir) | (epnum) , eptype, epsize, epbank)
+// #endif
+
+#endif
diff --git a/tmk_core/protocol/lufa/outputselect.c b/tmk_core/protocol/lufa/outputselect.c
new file mode 100644
index 000000000..0df5d3b75
--- /dev/null
+++ b/tmk_core/protocol/lufa/outputselect.c
@@ -0,0 +1,56 @@
+/*
+Copyright 2017 Priyadi Iman Nurcahyo
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "lufa.h"
+#include "outputselect.h"
+#ifdef MODULE_ADAFRUIT_BLE
+ #include "adafruit_ble.h"
+#endif
+
+uint8_t desired_output = OUTPUT_DEFAULT;
+
+void set_output(uint8_t output) {
+ set_output_user(output);
+ desired_output = output;
+}
+
+__attribute__((weak))
+void set_output_user(uint8_t output) {
+}
+
+uint8_t auto_detect_output(void) {
+ if (USB_DeviceState == DEVICE_STATE_Configured) {
+ return OUTPUT_USB;
+ }
+
+#ifdef MODULE_ADAFRUIT_BLE
+ if (adafruit_ble_is_connected()) {
+ return OUTPUT_BLUETOOTH;
+ }
+#endif
+
+#ifdef BLUETOOTH_ENABLE
+ return OUTPUT_BLUETOOTH; // should check if BT is connected here
+#endif
+
+ return OUTPUT_NONE;
+}
+
+uint8_t where_to_send(void) {
+ if (desired_output == OUTPUT_AUTO) {
+ return auto_detect_output();
+ }
+ return desired_output;
+}
+
diff --git a/tmk_core/protocol/lufa/outputselect.h b/tmk_core/protocol/lufa/outputselect.h
new file mode 100644
index 000000000..28cc3298e
--- /dev/null
+++ b/tmk_core/protocol/lufa/outputselect.h
@@ -0,0 +1,40 @@
+/*
+Copyright 2017 Priyadi Iman Nurcahyo
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+enum outputs {
+ OUTPUT_AUTO,
+
+ OUTPUT_NONE,
+ OUTPUT_USB,
+ OUTPUT_BLUETOOTH,
+
+ // backward compatibility
+ OUTPUT_USB_AND_BT
+};
+
+/**
+ * backward compatibility for BLUETOOTH_ENABLE, send to BT and USB by default
+ */
+#ifndef OUTPUT_DEFAULT
+ #ifdef BLUETOOTH_ENABLE
+ #define OUTPUT_DEFAULT OUTPUT_USB_AND_BT
+ #else
+ #define OUTPUT_DEFAULT OUTPUT_AUTO
+ #endif
+#endif
+
+void set_output(uint8_t output);
+void set_output_user(uint8_t output);
+uint8_t auto_detect_output(void);
+uint8_t where_to_send(void); \ No newline at end of file
diff --git a/tmk_core/protocol/lufa/ringbuffer.hpp b/tmk_core/protocol/lufa/ringbuffer.hpp
new file mode 100644
index 000000000..70a3c4881
--- /dev/null
+++ b/tmk_core/protocol/lufa/ringbuffer.hpp
@@ -0,0 +1,66 @@
+#pragma once
+// A simple ringbuffer holding Size elements of type T
+template <typename T, uint8_t Size>
+class RingBuffer {
+ protected:
+ T buf_[Size];
+ uint8_t head_{0}, tail_{0};
+ public:
+ inline uint8_t nextPosition(uint8_t position) {
+ return (position + 1) % Size;
+ }
+
+ inline uint8_t prevPosition(uint8_t position) {
+ if (position == 0) {
+ return Size - 1;
+ }
+ return position - 1;
+ }
+
+ inline bool enqueue(const T &item) {
+ static_assert(Size > 1, "RingBuffer size must be > 1");
+ uint8_t next = nextPosition(head_);
+ if (next == tail_) {
+ // Full
+ return false;
+ }
+
+ buf_[head_] = item;
+ head_ = next;
+ return true;
+ }
+
+ inline bool get(T &dest, bool commit = true) {
+ auto tail = tail_;
+ if (tail == head_) {
+ // No more data
+ return false;
+ }
+
+ dest = buf_[tail];
+ tail = nextPosition(tail);
+
+ if (commit) {
+ tail_ = tail;
+ }
+ return true;
+ }
+
+ inline bool empty() const { return head_ == tail_; }
+
+ inline uint8_t size() const {
+ int diff = head_ - tail_;
+ if (diff >= 0) {
+ return diff;
+ }
+ return Size + diff;
+ }
+
+ inline T& front() {
+ return buf_[tail_];
+ }
+
+ inline bool peek(T &item) {
+ return get(item, false);
+ }
+};
diff --git a/tmk_core/protocol/m0110.c b/tmk_core/protocol/m0110.c
new file mode 100644
index 000000000..0d3a5aaa4
--- /dev/null
+++ b/tmk_core/protocol/m0110.c
@@ -0,0 +1,591 @@
+/*
+Copyright 2011,2012 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+/* M0110A Support was contributed by skagon@github */
+
+#include <stdbool.h>
+#include <avr/io.h>
+#include <avr/interrupt.h>
+#include <util/delay.h>
+#include "m0110.h"
+#include "debug.h"
+
+
+static inline uint8_t raw2scan(uint8_t raw);
+static inline uint8_t inquiry(void);
+static inline uint8_t instant(void);
+static inline void clock_lo(void);
+static inline void clock_hi(void);
+static inline bool clock_in(void);
+static inline void data_lo(void);
+static inline void data_hi(void);
+static inline bool data_in(void);
+static inline uint16_t wait_clock_lo(uint16_t us);
+static inline uint16_t wait_clock_hi(uint16_t us);
+static inline uint16_t wait_data_lo(uint16_t us);
+static inline uint16_t wait_data_hi(uint16_t us);
+static inline void idle(void);
+static inline void request(void);
+
+
+#define WAIT_US(stat, us, err) do { \
+ if (!wait_##stat(us)) { \
+ m0110_error = err; \
+ goto ERROR; \
+ } \
+} while (0)
+
+#define WAIT_MS(stat, ms, err) do { \
+ uint16_t _ms = ms; \
+ while (_ms) { \
+ if (wait_##stat(1000)) { \
+ break; \
+ } \
+ _ms--; \
+ } \
+ if (_ms == 0) { \
+ m0110_error = err; \
+ goto ERROR; \
+ } \
+} while (0)
+
+#define KEY(raw) ((raw) & 0x7f)
+#define IS_BREAK(raw) (((raw) & 0x80) == 0x80)
+
+
+uint8_t m0110_error = 0;
+
+
+void m0110_init(void)
+{
+ idle();
+ _delay_ms(1000);
+
+/* Not needed to initialize in fact.
+ uint8_t data;
+ m0110_send(M0110_MODEL);
+ data = m0110_recv();
+ print("m0110_init model: "); phex(data); print("\n");
+
+ m0110_send(M0110_TEST);
+ data = m0110_recv();
+ print("m0110_init test: "); phex(data); print("\n");
+*/
+}
+
+uint8_t m0110_send(uint8_t data)
+{
+ m0110_error = 0;
+
+ request();
+ WAIT_MS(clock_lo, 250, 1); // keyboard may block long time
+ for (uint8_t bit = 0x80; bit; bit >>= 1) {
+ WAIT_US(clock_lo, 250, 3);
+ if (data&bit) {
+ data_hi();
+ } else {
+ data_lo();
+ }
+ WAIT_US(clock_hi, 200, 4);
+ }
+ _delay_us(100); // hold last bit for 80us
+ idle();
+ return 1;
+ERROR:
+ print("m0110_send err: "); phex(m0110_error); print("\n");
+ _delay_ms(500);
+ idle();
+ return 0;
+}
+
+uint8_t m0110_recv(void)
+{
+ uint8_t data = 0;
+ m0110_error = 0;
+
+ WAIT_MS(clock_lo, 250, 1); // keyboard may block long time
+ for (uint8_t i = 0; i < 8; i++) {
+ data <<= 1;
+ WAIT_US(clock_lo, 200, 2);
+ WAIT_US(clock_hi, 200, 3);
+ if (data_in()) {
+ data |= 1;
+ }
+ }
+ idle();
+ return data;
+ERROR:
+ print("m0110_recv err: "); phex(m0110_error); print("\n");
+ _delay_ms(500);
+ idle();
+ return 0xFF;
+}
+
+/*
+Handling for exceptional case of key combinations for M0110A
+
+Shift and Calc/Arrow key could be operated simultaneously:
+
+ Case Shift Arrow Events Interpret
+ -------------------------------------------------------------------
+ 1 Down Down 71, 79, DD Calc(d)*a *b
+ 2 Down Up 71, 79, UU Arrow&Calc(u)*a
+ 3 Up Down F1, 79, DD Shift(u) *c
+ 4 Up Up F1, 79, UU Shift(u) and Arrow&Calc(u)*a
+
+ Case Shift Calc Events Interpret
+ -------------------------------------------------------------------
+ 5(1) Down Down 71, 71, 79, DD Shift(d) and Cacl(d)
+ 6(2) Down Up F1, 71, 79, UU Shift(u) and Arrow&Calc(u)*a
+ 7(1) Up Down F1, 71, 79, DD Shift(u) and Calc(d)
+ 8(4) Up Up F1, F1, 79, UU Shift(ux2) and Arrow&Calc(u)*a
+
+During Calc key is hold:
+ Case Shift Arrow Events Interpret
+ -------------------------------------------------------------------
+ A(3) ---- Down F1, 79, DD Shift(u) *c
+ B ---- Up 79, UU Arrow&Calc(u)*a
+ C Down ---- F1, 71 Shift(u) and Shift(d)
+ D Up ---- F1 Shift(u)
+ E Hold Down 79, DD Normal
+ F Hold Up 79, UU Arrow&Calc(u)*a
+ G(1) Down Down F1, 71, 79, DD Shift(u)*b and Calc(d)*a
+ H(2) Down Up F1, 71, 79, UU Shift(u) and Arrow&Calc(u)*a
+ I(3) Up Down F1, F1, 79, DD Shift(ux2) *c
+ J(4) Up Up F1, 79, UU Shift(u) and Arrow&Calc(u)*a
+
+ Case Shift Calc Events Interpret
+ -------------------------------------------------------------------
+ K(1) ---- Down 71, 79, DD Calc(d)*a
+ L(4) ---- Up F1, 79, UU Shift(u) and Arrow&Calc(u)*a
+ M(1) Hold Down 71, 79, DD Calc(d)*a
+ N Hold Up 79, UU Arrow&Calc(u)*a
+
+ Where DD/UU indicates part of Keypad Down/Up event.
+ *a: Impossible to distinguish btween Arrow and Calc event.
+ *b: Shift(d) event is ignored.
+ *c: Arrow/Calc(d) event is ignored.
+*/
+uint8_t m0110_recv_key(void)
+{
+ static uint8_t keybuf = 0x00;
+ static uint8_t keybuf2 = 0x00;
+ static uint8_t rawbuf = 0x00;
+ uint8_t raw, raw2, raw3;
+
+ if (keybuf) {
+ raw = keybuf;
+ keybuf = 0x00;
+ return raw;
+ }
+ if (keybuf2) {
+ raw = keybuf2;
+ keybuf2 = 0x00;
+ return raw;
+ }
+
+ if (rawbuf) {
+ raw = rawbuf;
+ rawbuf = 0x00;
+ } else {
+ raw = instant(); // Use INSTANT for better response. Should be INQUIRY ?
+ }
+ switch (KEY(raw)) {
+ case M0110_KEYPAD:
+ raw2 = instant();
+ switch (KEY(raw2)) {
+ case M0110_ARROW_UP:
+ case M0110_ARROW_DOWN:
+ case M0110_ARROW_LEFT:
+ case M0110_ARROW_RIGHT:
+ if (IS_BREAK(raw2)) {
+ // Case B,F,N:
+ keybuf = (raw2scan(raw2) | M0110_CALC_OFFSET); // Calc(u)
+ return (raw2scan(raw2) | M0110_KEYPAD_OFFSET); // Arrow(u)
+ }
+ break;
+ }
+ // Keypad or Arrow
+ return (raw2scan(raw2) | M0110_KEYPAD_OFFSET);
+ break;
+ case M0110_SHIFT:
+ raw2 = instant();
+ switch (KEY(raw2)) {
+ case M0110_SHIFT:
+ // Case: 5-8,C,G,H
+ rawbuf = raw2;
+ return raw2scan(raw); // Shift(d/u)
+ break;
+ case M0110_KEYPAD:
+ // Shift + Arrow, Calc, or etc.
+ raw3 = instant();
+ switch (KEY(raw3)) {
+ case M0110_ARROW_UP:
+ case M0110_ARROW_DOWN:
+ case M0110_ARROW_LEFT:
+ case M0110_ARROW_RIGHT:
+ if (IS_BREAK(raw)) {
+ if (IS_BREAK(raw3)) {
+ // Case 4:
+ print("(4)\n");
+ keybuf2 = raw2scan(raw); // Shift(u)
+ keybuf = (raw2scan(raw3) | M0110_CALC_OFFSET); // Calc(u)
+ return (raw2scan(raw3) | M0110_KEYPAD_OFFSET); // Arrow(u)
+ } else {
+ // Case 3:
+ print("(3)\n");
+ return (raw2scan(raw)); // Shift(u)
+ }
+ } else {
+ if (IS_BREAK(raw3)) {
+ // Case 2:
+ print("(2)\n");
+ keybuf = (raw2scan(raw3) | M0110_CALC_OFFSET); // Calc(u)
+ return (raw2scan(raw3) | M0110_KEYPAD_OFFSET); // Arrow(u)
+ } else {
+ // Case 1:
+ print("(1)\n");
+ return (raw2scan(raw3) | M0110_CALC_OFFSET); // Calc(d)
+ }
+ }
+ break;
+ default:
+ // Shift + Keypad
+ keybuf = (raw2scan(raw3) | M0110_KEYPAD_OFFSET);
+ return raw2scan(raw); // Shift(d/u)
+ break;
+ }
+ break;
+ default:
+ // Shift + Normal keys
+ keybuf = raw2scan(raw2);
+ return raw2scan(raw); // Shift(d/u)
+ break;
+ }
+ break;
+ default:
+ // Normal keys
+ return raw2scan(raw);
+ break;
+ }
+}
+
+
+static inline uint8_t raw2scan(uint8_t raw) {
+ return (raw == M0110_NULL) ? M0110_NULL : (
+ (raw == M0110_ERROR) ? M0110_ERROR : (
+ ((raw&0x80) | ((raw&0x7F)>>1))
+ )
+ );
+}
+
+static inline uint8_t inquiry(void)
+{
+ m0110_send(M0110_INQUIRY);
+ return m0110_recv();
+}
+
+static inline uint8_t instant(void)
+{
+ m0110_send(M0110_INSTANT);
+ uint8_t data = m0110_recv();
+ if (data != M0110_NULL) {
+ debug_hex(data); debug(" ");
+ }
+ return data;
+}
+
+static inline void clock_lo()
+{
+ M0110_CLOCK_PORT &= ~(1<<M0110_CLOCK_BIT);
+ M0110_CLOCK_DDR |= (1<<M0110_CLOCK_BIT);
+}
+static inline void clock_hi()
+{
+ /* input with pull up */
+ M0110_CLOCK_DDR &= ~(1<<M0110_CLOCK_BIT);
+ M0110_CLOCK_PORT |= (1<<M0110_CLOCK_BIT);
+}
+static inline bool clock_in()
+{
+ M0110_CLOCK_DDR &= ~(1<<M0110_CLOCK_BIT);
+ M0110_CLOCK_PORT |= (1<<M0110_CLOCK_BIT);
+ _delay_us(1);
+ return M0110_CLOCK_PIN&(1<<M0110_CLOCK_BIT);
+}
+static inline void data_lo()
+{
+ M0110_DATA_PORT &= ~(1<<M0110_DATA_BIT);
+ M0110_DATA_DDR |= (1<<M0110_DATA_BIT);
+}
+static inline void data_hi()
+{
+ /* input with pull up */
+ M0110_DATA_DDR &= ~(1<<M0110_DATA_BIT);
+ M0110_DATA_PORT |= (1<<M0110_DATA_BIT);
+}
+static inline bool data_in()
+{
+ M0110_DATA_DDR &= ~(1<<M0110_DATA_BIT);
+ M0110_DATA_PORT |= (1<<M0110_DATA_BIT);
+ _delay_us(1);
+ return M0110_DATA_PIN&(1<<M0110_DATA_BIT);
+}
+
+static inline uint16_t wait_clock_lo(uint16_t us)
+{
+ while (clock_in() && us) { asm(""); _delay_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_clock_hi(uint16_t us)
+{
+ while (!clock_in() && us) { asm(""); _delay_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_data_lo(uint16_t us)
+{
+ while (data_in() && us) { asm(""); _delay_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_data_hi(uint16_t us)
+{
+ while (!data_in() && us) { asm(""); _delay_us(1); us--; }
+ return us;
+}
+
+static inline void idle(void)
+{
+ clock_hi();
+ data_hi();
+}
+
+static inline void request(void)
+{
+ clock_hi();
+ data_lo();
+}
+
+
+
+/*
+Primitive M0110 Library for AVR
+==============================
+
+
+Signaling
+---------
+CLOCK is always from KEYBOARD. DATA are sent with MSB first.
+
+1) IDLE: both lines are high.
+ CLOCK ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ DATA ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+2) KEYBOARD->HOST: HOST reads bit on rising edge.
+ CLOCK ~~~~~~~~~~~~|__|~~~|__|~~~|__|~~~|__|~~~|__|~~~|__|~~~|__|~~~|__|~~~~~~~~~~~
+ DATA ~~~~~~~~~~~~X777777X666666X555555X444444X333333X222222X111111X000000X~~~~~~~
+ <--> 160us(clock low)
+ <---> 180us(clock high)
+
+3) HOST->KEYBOARD: HOST asserts bit on falling edge.
+ CLOCK ~~~~~~~~~~~~|__|~~~|__|~~~|__|~~~|__|~~~|__|~~~|__|~~~|__|~~~|__|~~~~~~~~~~~
+ DATA ~~~~~~|_____X777777X666666X555555X444444X333333X222222X111111X000000X~~~~~~~
+ <----> 840us(request to send by host) <---> 80us(hold DATA)
+ <--> 180us(clock low)
+ <---> 220us(clock high)
+
+
+Protocol
+--------
+COMMAND:
+ Inquiry 0x10 get key event with block
+ Instant 0x12 get key event
+ Model 0x14 get model number(M0110 responds with 0x09)
+ bit 7 1 if another device connected(used when keypad exists?)
+ bit4-6 next device model number
+ bit1-3 keyboard model number
+ bit 0 always 1
+ Test 0x16 test(ACK:0x7D/NAK:0x77)
+
+KEY EVENT:
+ bit 7 key state(0:press 1:release)
+ bit 6-1 scan code(see below)
+ bit 0 always 1
+ To get scan code use this: ((bits&(1<<7)) | ((bits&0x7F))>>1).
+
+ Note: On the M0110A, Keypad keys and Arrow keys are preceded by 0x79.
+ Moreover, some Keypad keys(=, /, * and +) are preceded by 0x71 on press and 0xF1 on release.
+
+ARROW KEYS:
+ Arrow keys and Calc keys(+,*,/,= on keypad) share same byte sequence and preceding byte of
+ Calc keys(0x71 and 0xF1) means press and release event of SHIFT. This causes a very confusing situation,
+ it is difficult or impossible to tell Calc key from Arrow key plus SHIFT in some cases.
+
+ Raw key events:
+ press release
+ ---------------- ----------------
+ Left: 0x79, 0x0D 0x79, 0x8D
+ Right: 0x79, 0x05 0x79, 0x85
+ Up: 0x79, 0x1B 0x79, 0x9B
+ Down: 0x79, 0x11 0x79, 0x91
+ Pad+: 0x71, 0x79, 0x0D 0xF1, 0x79, 0x8D
+ Pad*: 0x71, 0x79, 0x05 0xF1, 0x79, 0x85
+ Pad/: 0x71, 0x79, 0x1B 0xF1, 0x79, 0x9B
+ Pad=: 0x71, 0x79, 0x11 0xF1, 0x79, 0x91
+
+
+RAW CODE:
+ M0110A
+ ,---------------------------------------------------------. ,---------------.
+ | `| 1| 2| 3| 4| 5| 6| 7| 8| 9| 0| -| =|Bcksp| |Clr| =| /| *|
+ |---------------------------------------------------------| |---------------|
+ |Tab | Q| W| E| R| T| Y| U| I| O| P| [| ]| | | 7| 8| 9| -|
+ |-----------------------------------------------------' | |---------------|
+ |CapsLo| A| S| D| F| G| H| J| K| L| ;| '|Return| | 4| 5| 6| +|
+ |---------------------------------------------------------| |---------------|
+ |Shift | Z| X| C| V| B| N| M| ,| ,| /|Shft|Up | | 1| 2| 3| |
+ |---------------------------------------------------------' |-----------|Ent|
+ |Optio|Mac | Space | \|Lft|Rgt|Dn | | 0| .| |
+ `---------------------------------------------------------' `---------------'
+ ,---------------------------------------------------------. ,---------------.
+ | 65| 25| 27| 29| 2B| 2F| 2D| 35| 39| 33| 3B| 37| 31| 67| |+0F|*11|*1B|*05|
+ |---------------------------------------------------------| |---------------|
+ | 61| 19| 1B| 1D| 1F| 23| 21| 41| 45| 3F| 47| 43| 3D| | |+33|+37|+39|+1D|
+ |-----------------------------------------------------' | |---------------|
+ | 73| 01| 03| 05| 07| 0B| 09| 4D| 51| 4B| 53| 4F| 49| |+2D|+2F|+31|*0D|
+ |---------------------------------------------------------| |---------------|
+ | 71| 0D| 0F| 11| 13| 17| 5B| 5D| 27| 5F| 59| 71|+1B| |+27|+29|+2B| |
+ |---------------------------------------------------------' |-----------|+19|
+ | 75| 6F| 63 | 55|+0D|+05|+11| | +25|+03| |
+ `---------------------------------------------------------' `---------------'
+ + 0x79, 0xDD / 0xF1, 0xUU
+ * 0x71, 0x79,DD / 0xF1, 0x79, 0xUU
+
+
+MODEL NUMBER:
+ M0110: 0x09 00001001 : model number 4 (100)
+ M0110A: 0x0B 00001011 : model number 5 (101)
+ M0110 & M0120: ???
+
+
+Scan Code
+---------
+ m0110_recv_key() function returns following scan codes instead of M0110 raw codes.
+ Scan codes are 1 byte size and MSB(bit7) is set when key is released.
+
+ scancode = ((raw&0x80) | ((raw&0x7F)>>1))
+
+ M0110 M0120
+ ,---------------------------------------------------------. ,---------------.
+ | `| 1| 2| 3| 4| 5| 6| 7| 8| 9| 0| -| =|Backs| |Clr| -|Lft|Rgt|
+ |---------------------------------------------------------| |---------------|
+ |Tab | Q| W| E| R| T| Y| U| I| O| P| [| ]| \| | 7| 8| 9|Up |
+ |---------------------------------------------------------| |---------------|
+ |CapsLo| A| S| D| F| G| H| J| K| L| ;| '|Return| | 4| 5| 6|Dn |
+ |---------------------------------------------------------| |---------------|
+ |Shift | Z| X| C| V| B| N| M| ,| ,| /| | | 1| 2| 3| |
+ `---------------------------------------------------------' |-----------|Ent|
+ |Opt|Mac | Space |Enter|Opt| | 0| .| |
+ `------------------------------------------------' `---------------'
+ ,---------------------------------------------------------. ,---------------.
+ | 32| 12| 13| 14| 15| 17| 16| 1A| 1C| 19| 1D| 1B| 18| 33| | 47| 4E| 46| 42|
+ |---------------------------------------------------------| |---------------|
+ | 30| 0C| 0D| 0E| 0F| 10| 11| 20| 22| 1F| 23| 21| 1E| 2A| | 59| 5B| 5C| 4D|
+ |---------------------------------------------------------| |---------------|
+ | 39| 00| 01| 02| 03| 05| 04| 26| 28| 25| 29| 27| 24| | 56| 57| 58| 48|
+ |---------------------------------------------------------| |---------------|
+ | 38| 06| 07| 08| 09| 0B| 2D| 2E| 2B| 2F| 2C| 38| | 53| 54| 55| |
+ `---------------------------------------------------------' |-----------| 4C|
+ | 3A| 37| 31 | 34| 3A| | 52| 41| |
+ `------------------------------------------------' `---------------'
+
+ International keyboard(See page 22 of "Technical Info for 128K/512K")
+ ,---------------------------------------------------------.
+ | 32| 12| 13| 14| 15| 17| 16| 1A| 1C| 19| 1D| 1B| 18| 33|
+ |---------------------------------------------------------|
+ | 30| 0C| 0D| 0E| 0F| 10| 11| 20| 22| 1F| 23| 21| 1E| 2A|
+ |------------------------------------------------------ |
+ | 39| 00| 01| 02| 03| 05| 04| 26| 28| 25| 29| 27| 24| |
+ |---------------------------------------------------------|
+ | 38| 06| 07| 08| 09| 0B| 2D| 2E| 2B| 2F| 2C| 0A| 38|
+ `---------------------------------------------------------'
+ | 3A| 37| 34 | 31| 3A|
+ `------------------------------------------------'
+
+ M0110A
+ ,---------------------------------------------------------. ,---------------.
+ | `| 1| 2| 3| 4| 5| 6| 7| 8| 9| 0| -| =|Bcksp| |Clr| =| /| *|
+ |---------------------------------------------------------| |---------------|
+ |Tab | Q| W| E| R| T| Y| U| I| O| P| [| ]| | | 7| 8| 9| -|
+ |-----------------------------------------------------' | |---------------|
+ |CapsLo| A| S| D| F| G| H| J| K| L| ;| '|Return| | 4| 5| 6| +|
+ |---------------------------------------------------------| |---------------|
+ |Shift | Z| X| C| V| B| N| M| ,| ,| /|Shft|Up | | 1| 2| 3| |
+ |---------------------------------------------------------' |-----------|Ent|
+ |Optio|Mac | Space | \|Lft|Rgt|Dn | | 0| .| |
+ `---------------------------------------------------------' `---------------'
+ ,---------------------------------------------------------. ,---------------.
+ | 32| 12| 13| 14| 15| 17| 16| 1A| 1C| 19| 1D| 1B| 18| 33| | 47| 68| 6D| 62|
+ |---------------------------------------------------------| |---------------|
+ | 30| 0C| 0D| 0E| 0F| 10| 11| 20| 22| 1F| 23| 21| 1E| | | 59| 5B| 5C| 4E|
+ |-----------------------------------------------------' | |---------------|
+ | 39| 00| 01| 02| 03| 05| 04| 26| 28| 25| 29| 27| 24| | 56| 57| 58| 66|
+ |---------------------------------------------------------| |---------------|
+ | 38| 06| 07| 08| 09| 0B| 2D| 2E| 2B| 2F| 2C| 38| 4D| | 53| 54| 55| |
+ |---------------------------------------------------------' |-----------| 4C|
+ | 3A| 37| 31 | 2A| 46| 42| 48| | 52| 41| |
+ `---------------------------------------------------------' `---------------'
+
+
+References
+----------
+Technical Info for 128K/512K and Plus
+ ftp://ftp.apple.asimov.net/pub/apple_II/documentation/macintosh/Mac%20Hardware%20Info%20-%20Mac%20128K.pdf
+ ftp://ftp.apple.asimov.net/pub/apple_II/documentation/macintosh/Mac%20Hardware%20Info%20-%20Mac%20Plus.pdf
+Protocol:
+ Page 20 of Tech Info for 128K/512K
+ http://www.mac.linux-m68k.org/devel/plushw.php
+Connector:
+ Page 20 of Tech Info for 128K/512K
+ http://www.kbdbabel.org/conn/kbd_connector_macplus.png
+Signaling:
+ http://www.kbdbabel.org/signaling/kbd_signaling_mac.png
+ http://typematic.blog.shinobi.jp/Entry/14/
+M0110 raw scan codes:
+ Page 22 of Tech Info for 128K/512K
+ Page 07 of Tech Info for Plus
+ http://m0115.web.fc2.com/m0110.jpg
+ http://m0115.web.fc2.com/m0110a.jpg
+*/
diff --git a/tmk_core/protocol/m0110.h b/tmk_core/protocol/m0110.h
new file mode 100644
index 000000000..2b95ed34d
--- /dev/null
+++ b/tmk_core/protocol/m0110.h
@@ -0,0 +1,92 @@
+/*
+Copyright 2011,2012 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef M0110_H
+#define M0110_H
+
+
+/* port settings for clock and data line */
+#if !(defined(M0110_CLOCK_PORT) && \
+ defined(M0110_CLOCK_PIN) && \
+ defined(M0110_CLOCK_DDR) && \
+ defined(M0110_CLOCK_BIT))
+# error "M0110 clock port setting is required in config.h"
+#endif
+
+#if !(defined(M0110_DATA_PORT) && \
+ defined(M0110_DATA_PIN) && \
+ defined(M0110_DATA_DDR) && \
+ defined(M0110_DATA_BIT))
+# error "M0110 data port setting is required in config.h"
+#endif
+
+/* Commands */
+#define M0110_INQUIRY 0x10
+#define M0110_INSTANT 0x14
+#define M0110_MODEL 0x16
+#define M0110_TEST 0x36
+
+/* Response(raw byte from M0110) */
+#define M0110_NULL 0x7B
+#define M0110_KEYPAD 0x79
+#define M0110_TEST_ACK 0x7D
+#define M0110_TEST_NAK 0x77
+#define M0110_SHIFT 0x71
+#define M0110_ARROW_UP 0x1B
+#define M0110_ARROW_DOWN 0x11
+#define M0110_ARROW_LEFT 0x0D
+#define M0110_ARROW_RIGHT 0x05
+
+/* This inidcates no response. */
+#define M0110_ERROR 0xFF
+
+/* scan code offset for keypad and arrow keys */
+#define M0110_KEYPAD_OFFSET 0x40
+#define M0110_CALC_OFFSET 0x60
+
+
+extern uint8_t m0110_error;
+
+/* host role */
+void m0110_init(void);
+uint8_t m0110_send(uint8_t data);
+uint8_t m0110_recv(void);
+uint8_t m0110_recv_key(void);
+uint8_t m0110_inquiry(void);
+uint8_t m0110_instant(void);
+
+#endif
diff --git a/tmk_core/protocol/mbed/HIDKeyboard.cpp b/tmk_core/protocol/mbed/HIDKeyboard.cpp
new file mode 100644
index 000000000..947077cd2
--- /dev/null
+++ b/tmk_core/protocol/mbed/HIDKeyboard.cpp
@@ -0,0 +1,271 @@
+#include <stdint.h>
+#include "USBHID.h"
+#include "USBHID_Types.h"
+#include "USBDescriptor.h"
+#include "HIDKeyboard.h"
+
+#define DEFAULT_CONFIGURATION (1)
+
+
+HIDKeyboard::HIDKeyboard(uint16_t vendor_id, uint16_t product_id, uint16_t product_release): USBDevice(vendor_id, product_id, product_release)
+{
+ USBDevice::connect();
+}
+
+bool HIDKeyboard::sendReport(report_keyboard_t report) {
+ USBDevice::write(EP1IN, report.raw, sizeof(report), MAX_PACKET_SIZE_EP1);
+ return true;
+}
+
+uint8_t HIDKeyboard::leds() {
+ return led_state;
+}
+
+bool HIDKeyboard::USBCallback_setConfiguration(uint8_t configuration) {
+ if (configuration != DEFAULT_CONFIGURATION) {
+ return false;
+ }
+
+ // Configure endpoints > 0
+ addEndpoint(EPINT_IN, MAX_PACKET_SIZE_EPINT);
+ //addEndpoint(EPINT_OUT, MAX_PACKET_SIZE_EPINT);
+
+ // We activate the endpoint to be able to recceive data
+ //readStart(EPINT_OUT, MAX_PACKET_SIZE_EPINT);
+ return true;
+}
+
+
+uint8_t * HIDKeyboard::stringImanufacturerDesc() {
+ static uint8_t stringImanufacturerDescriptor[] = {
+ 0x18, /*bLength*/
+ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
+ 't',0,'m',0,'k',0,'-',0,'k',0,'b',0,'d',0,'.',0,'c',0,'o',0,'m',0 /*bString iManufacturer*/
+ };
+ return stringImanufacturerDescriptor;
+}
+
+uint8_t * HIDKeyboard::stringIproductDesc() {
+ static uint8_t stringIproductDescriptor[] = {
+ 0x0a, /*bLength*/
+ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
+ 'm',0,'b',0,'e',0,'d',0 /*bString iProduct*/
+ };
+ return stringIproductDescriptor;
+}
+
+uint8_t * HIDKeyboard::stringIserialDesc() {
+ static uint8_t stringIserialDescriptor[] = {
+ 0x04, /*bLength*/
+ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/
+ '0',0 /*bString iSerial*/
+ };
+ return stringIserialDescriptor;
+}
+
+uint8_t * HIDKeyboard::reportDesc() {
+ static uint8_t reportDescriptor[] = {
+ USAGE_PAGE(1), 0x01, // Generic Desktop
+ USAGE(1), 0x06, // Keyboard
+ COLLECTION(1), 0x01, // Application
+
+ USAGE_PAGE(1), 0x07, // Key Codes
+ USAGE_MINIMUM(1), 0xE0,
+ USAGE_MAXIMUM(1), 0xE7,
+ LOGICAL_MINIMUM(1), 0x00,
+ LOGICAL_MAXIMUM(1), 0x01,
+ REPORT_SIZE(1), 0x01,
+ REPORT_COUNT(1), 0x08,
+ INPUT(1), 0x02, // Data, Variable, Absolute
+
+ REPORT_COUNT(1), 0x01,
+ REPORT_SIZE(1), 0x08,
+ INPUT(1), 0x01, // Constant
+
+ REPORT_COUNT(1), 0x05,
+ REPORT_SIZE(1), 0x01,
+ USAGE_PAGE(1), 0x08, // LEDs
+ USAGE_MINIMUM(1), 0x01,
+ USAGE_MAXIMUM(1), 0x05,
+ OUTPUT(1), 0x02, // Data, Variable, Absolute
+
+ REPORT_COUNT(1), 0x01,
+ REPORT_SIZE(1), 0x03,
+ OUTPUT(1), 0x01, // Constant
+
+
+ REPORT_COUNT(1), 0x06,
+ REPORT_SIZE(1), 0x08,
+ LOGICAL_MINIMUM(1), 0x00,
+ LOGICAL_MAXIMUM(1), 0xFF,
+ USAGE_PAGE(1), 0x07, // Key Codes
+ USAGE_MINIMUM(1), 0x00,
+ USAGE_MAXIMUM(1), 0xFF,
+ INPUT(1), 0x00, // Data, Array
+ END_COLLECTION(0),
+ };
+ reportLength = sizeof(reportDescriptor);
+ return reportDescriptor;
+}
+
+uint16_t HIDKeyboard::reportDescLength() {
+ reportDesc();
+ return reportLength;
+}
+
+#define TOTAL_DESCRIPTOR_LENGTH ((1 * CONFIGURATION_DESCRIPTOR_LENGTH) \
+ + (1 * INTERFACE_DESCRIPTOR_LENGTH) \
+ + (1 * HID_DESCRIPTOR_LENGTH) \
+ + (1 * ENDPOINT_DESCRIPTOR_LENGTH))
+uint8_t * HIDKeyboard::configurationDesc() {
+ static uint8_t configurationDescriptor[] = {
+ CONFIGURATION_DESCRIPTOR_LENGTH,// bLength
+ CONFIGURATION_DESCRIPTOR, // bDescriptorType
+ LSB(TOTAL_DESCRIPTOR_LENGTH), // wTotalLength (LSB)
+ MSB(TOTAL_DESCRIPTOR_LENGTH), // wTotalLength (MSB)
+ 0x01, // bNumInterfaces
+ DEFAULT_CONFIGURATION, // bConfigurationValue
+ 0x00, // iConfiguration
+ C_RESERVED | C_REMOTE_WAKEUP, // bmAttributes
+ C_POWER(100), // bMaxPowerHello World from Mbed
+
+ INTERFACE_DESCRIPTOR_LENGTH, // bLength
+ INTERFACE_DESCRIPTOR, // bDescriptorType
+ 0x00, // bInterfaceNumber
+ 0x00, // bAlternateSetting
+ 0x01, // bNumEndpoints
+ HID_CLASS, // bInterfaceClass
+ 1, // bInterfaceSubClass (boot)
+ 1, // bInterfaceProtocol (keyboard)
+ 0x00, // iInterface
+
+ HID_DESCRIPTOR_LENGTH, // bLength
+ HID_DESCRIPTOR, // bDescriptorType
+ LSB(HID_VERSION_1_11), // bcdHID (LSB)
+ MSB(HID_VERSION_1_11), // bcdHID (MSB)
+ 0x00, // bCountryCode
+ 0x01, // bNumDescriptors
+ REPORT_DESCRIPTOR, // bDescriptorType
+ (uint8_t)(LSB(reportDescLength())), // wDescriptorLength (LSB)
+ (uint8_t)(MSB(reportDescLength())), // wDescriptorLength (MSB)
+
+ ENDPOINT_DESCRIPTOR_LENGTH, // bLength
+ ENDPOINT_DESCRIPTOR, // bDescriptorType
+ PHY_TO_DESC(EP1IN), // bEndpointAddress
+ E_INTERRUPT, // bmAttributes
+ LSB(MAX_PACKET_SIZE_EPINT), // wMaxPacketSize (LSB)
+ MSB(MAX_PACKET_SIZE_EPINT), // wMaxPacketSize (MSB)
+ 1, // bInterval (milliseconds)
+ };
+ return configurationDescriptor;
+}
+
+#if 0
+uint8_t * HIDKeyboard::deviceDesc() {
+ static uint8_t deviceDescriptor[] = {
+ DEVICE_DESCRIPTOR_LENGTH, /* bLength */
+ DEVICE_DESCRIPTOR, /* bDescriptorType */
+ LSB(USB_VERSION_2_0), /* bcdUSB (LSB) */
+ MSB(USB_VERSION_2_0), /* bcdUSB (MSB) */
+ 0x00, /* bDeviceClass */
+ 0x00, /* bDeviceSubClass */
+ 0x00, /* bDeviceprotocol */
+ MAX_PACKET_SIZE_EP0, /* bMaxPacketSize0 */
+ (uint8_t)(LSB(0xfeed)), /* idVendor (LSB) */
+ (uint8_t)(MSB(0xfeed)), /* idVendor (MSB) */
+ (uint8_t)(LSB(0x1bed)), /* idProduct (LSB) */
+ (uint8_t)(MSB(0x1bed)), /* idProduct (MSB) */
+ (uint8_t)(LSB(0x0002)), /* bcdDevice (LSB) */
+ (uint8_t)(MSB(0x0002)), /* bcdDevice (MSB) */
+ 0, /* iManufacturer */
+ 0, /* iProduct */
+ 0, /* iSerialNumber */
+ 0x01 /* bNumConfigurations */
+ };
+ return deviceDescriptor;
+}
+#endif
+
+bool HIDKeyboard::USBCallback_request() {
+ bool success = false;
+ CONTROL_TRANSFER * transfer = getTransferPtr();
+ uint8_t *hidDescriptor;
+
+ // Process additional standard requests
+
+ if ((transfer->setup.bmRequestType.Type == STANDARD_TYPE))
+ {
+ switch (transfer->setup.bRequest)
+ {
+ case GET_DESCRIPTOR:
+ switch (DESCRIPTOR_TYPE(transfer->setup.wValue))
+ {
+ case REPORT_DESCRIPTOR:
+ if ((reportDesc() != NULL) \
+ && (reportDescLength() != 0))
+ {
+ transfer->remaining = reportDescLength();
+ transfer->ptr = reportDesc();
+ transfer->direction = DEVICE_TO_HOST;
+ success = true;
+ }
+ break;
+ case HID_DESCRIPTOR:
+ // Find the HID descriptor, after the configuration descriptor
+ hidDescriptor = findDescriptor(HID_DESCRIPTOR);
+ if (hidDescriptor != NULL)
+ {
+ transfer->remaining = HID_DESCRIPTOR_LENGTH;
+ transfer->ptr = hidDescriptor;
+ transfer->direction = DEVICE_TO_HOST;
+ success = true;
+ }
+ break;
+
+ default:
+ break;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ // Process class-specific requests
+ if (transfer->setup.bmRequestType.Type == CLASS_TYPE)
+ {
+ switch (transfer->setup.bRequest) {
+ case SET_REPORT:
+ // LED indicator
+ // TODO: check Interface and Report length?
+ // if (transfer->setup.wIndex == INTERFACE_KEYBOAD) { }
+ // if (transfer->setup.wLength == 1)
+
+ transfer->remaining = 1;
+ //transfer->ptr = ?? what ptr should be set when OUT(not used?)
+ transfer->direction = HOST_TO_DEVICE;
+ transfer->notify = true; /* notify with USBCallback_requestCompleted */
+ success = true;
+ default:
+ break;
+ }
+ }
+
+ return success;
+}
+
+void HIDKeyboard::USBCallback_requestCompleted(uint8_t * buf, uint32_t length)
+{
+ if (length > 0) {
+ CONTROL_TRANSFER *transfer = getTransferPtr();
+ if (transfer->setup.bmRequestType.Type == CLASS_TYPE) {
+ switch (transfer->setup.bRequest) {
+ case SET_REPORT:
+ led_state = buf[0];
+ break;
+ default:
+ break;
+ }
+ }
+ }
+}
diff --git a/tmk_core/protocol/mbed/HIDKeyboard.h b/tmk_core/protocol/mbed/HIDKeyboard.h
new file mode 100644
index 000000000..c537e5ece
--- /dev/null
+++ b/tmk_core/protocol/mbed/HIDKeyboard.h
@@ -0,0 +1,31 @@
+#ifndef HIDKEYBOARD_H
+
+#include "stdint.h"
+#include "stdbool.h"
+#include "USBHID.h"
+#include "report.h"
+
+
+class HIDKeyboard : public USBDevice {
+public:
+ HIDKeyboard(uint16_t vendor_id = 0xFEED, uint16_t product_id = 0xabed, uint16_t product_release = 0x0001);
+
+ bool sendReport(report_keyboard_t report);
+ uint8_t leds(void);
+protected:
+ uint16_t reportLength;
+ virtual bool USBCallback_setConfiguration(uint8_t configuration);
+ virtual uint8_t * stringImanufacturerDesc();
+ virtual uint8_t * stringIproductDesc();
+ virtual uint8_t * stringIserialDesc();
+ virtual uint16_t reportDescLength();
+ virtual uint8_t * reportDesc();
+ virtual uint8_t * configurationDesc();
+ //virtual uint8_t * deviceDesc();
+ virtual bool USBCallback_request();
+ virtual void USBCallback_requestCompleted(uint8_t * buf, uint32_t length);
+private:
+ uint8_t led_state;
+};
+
+#endif
diff --git a/tmk_core/protocol/mbed/mbed_driver.cpp b/tmk_core/protocol/mbed/mbed_driver.cpp
new file mode 100644
index 000000000..6c7b16e23
--- /dev/null
+++ b/tmk_core/protocol/mbed/mbed_driver.cpp
@@ -0,0 +1,41 @@
+#include "HIDKeyboard.h"
+#include "host.h"
+#include "host_driver.h"
+#include "mbed_driver.h"
+
+HIDKeyboard keyboard;
+
+
+/* Host driver */
+static uint8_t keyboard_leds(void);
+static void send_keyboard(report_keyboard_t *report);
+static void send_mouse(report_mouse_t *report);
+static void send_system(uint16_t data);
+static void send_consumer(uint16_t data);
+
+host_driver_t mbed_driver = {
+ keyboard_leds,
+ send_keyboard,
+ send_mouse,
+ send_system,
+ send_consumer
+};
+
+
+static uint8_t keyboard_leds(void)
+{
+ return keyboard.leds();
+}
+static void send_keyboard(report_keyboard_t *report)
+{
+ keyboard.sendReport(*report);
+}
+static void send_mouse(report_mouse_t *report)
+{
+}
+static void send_system(uint16_t data)
+{
+}
+static void send_consumer(uint16_t data)
+{
+}
diff --git a/tmk_core/protocol/mbed/mbed_driver.h b/tmk_core/protocol/mbed/mbed_driver.h
new file mode 100644
index 000000000..dd1153b43
--- /dev/null
+++ b/tmk_core/protocol/mbed/mbed_driver.h
@@ -0,0 +1,3 @@
+#include "host_driver.h"
+
+extern host_driver_t mbed_driver;
diff --git a/tmk_core/protocol/midi.mk b/tmk_core/protocol/midi.mk
new file mode 100644
index 000000000..4855b23d3
--- /dev/null
+++ b/tmk_core/protocol/midi.mk
@@ -0,0 +1,10 @@
+MIDI_DIR = protocol/midi
+
+SRC += midi.c \
+ midi_device.c \
+ bytequeue/bytequeue.c \
+ bytequeue/interrupt_setting.c \
+ sysex_tools.c \
+ $(LUFA_SRC_USBCLASS)
+
+VPATH += $(TMK_PATH)/$(MIDI_DIR) \ No newline at end of file
diff --git a/tmk_core/protocol/midi/Config/LUFAConfig.h b/tmk_core/protocol/midi/Config/LUFAConfig.h
new file mode 100755
index 000000000..a1d748267
--- /dev/null
+++ b/tmk_core/protocol/midi/Config/LUFAConfig.h
@@ -0,0 +1,93 @@
+/*
+ LUFA Library
+ Copyright (C) Dean Camera, 2012.
+
+ dean [at] fourwalledcubicle [dot] com
+ www.lufa-lib.org
+*/
+
+/*
+ Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
+
+ Permission to use, copy, modify, distribute, and sell this
+ software and its documentation for any purpose is hereby granted
+ without fee, provided that the above copyright notice appear in
+ all copies and that both that the copyright notice and this
+ permission notice and warranty disclaimer appear in supporting
+ documentation, and that the name of the author not be used in
+ advertising or publicity pertaining to distribution of the
+ software without specific, written prior permission.
+
+ The author disclaim all warranties with regard to this
+ software, including all implied warranties of merchantability
+ and fitness. In no event shall the author be liable for any
+ special, indirect or consequential damages or any damages
+ whatsoever resulting from loss of use, data or profits, whether
+ in an action of contract, negligence or other tortious action,
+ arising out of or in connection with the use or performance of
+ this software.
+*/
+
+/** \file
+ * \brief LUFA Library Configuration Header File
+ *
+ * This header file is used to configure LUFA's compile time options,
+ * as an alternative to the compile time constants supplied through
+ * a makefile.
+ *
+ * For information on what each token does, refer to the LUFA
+ * manual section "Summary of Compile Tokens".
+ */
+
+#ifndef _LUFA_CONFIG_H_
+#define _LUFA_CONFIG_H_
+
+ #if (ARCH == ARCH_AVR8)
+
+ /* Non-USB Related Configuration Tokens: */
+// #define DISABLE_TERMINAL_CODES
+
+ /* USB Class Driver Related Tokens: */
+// #define HID_HOST_BOOT_PROTOCOL_ONLY
+// #define HID_STATETABLE_STACK_DEPTH {Insert Value Here}
+// #define HID_USAGE_STACK_DEPTH {Insert Value Here}
+// #define HID_MAX_COLLECTIONS {Insert Value Here}
+// #define HID_MAX_REPORTITEMS {Insert Value Here}
+// #define HID_MAX_REPORT_IDS {Insert Value Here}
+// #define NO_CLASS_DRIVER_AUTOFLUSH
+
+ /* General USB Driver Related Tokens: */
+// #define ORDERED_EP_CONFIG
+ #define USE_STATIC_OPTIONS (USB_DEVICE_OPT_FULLSPEED | USB_OPT_REG_ENABLED | USB_OPT_AUTO_PLL)
+ #define USB_DEVICE_ONLY
+// #define USB_HOST_ONLY
+// #define USB_STREAM_TIMEOUT_MS {Insert Value Here}
+// #define NO_LIMITED_CONTROLLER_CONNECT
+// #define NO_SOF_EVENTS
+
+ /* USB Device Mode Driver Related Tokens: */
+// #define USE_RAM_DESCRIPTORS
+ #define USE_FLASH_DESCRIPTORS
+// #define USE_EEPROM_DESCRIPTORS
+// #define NO_INTERNAL_SERIAL
+ #define FIXED_CONTROL_ENDPOINT_SIZE 8
+// #define DEVICE_STATE_AS_GPIOR {Insert Value Here}
+ #define FIXED_NUM_CONFIGURATIONS 1
+// #define CONTROL_ONLY_DEVICE
+// #define INTERRUPT_CONTROL_ENDPOINT
+// #define NO_DEVICE_REMOTE_WAKEUP
+// #define NO_DEVICE_SELF_POWER
+
+ /* USB Host Mode Driver Related Tokens: */
+// #define HOST_STATE_AS_GPIOR {Insert Value Here}
+// #define USB_HOST_TIMEOUT_MS {Insert Value Here}
+// #define HOST_DEVICE_SETTLE_DELAY_MS {Insert Value Here}
+// #define NO_AUTO_VBUS_MANAGEMENT
+// #define INVERTED_VBUS_ENABLE_LINE
+
+ #else
+
+ #error Unsupported architecture for this LUFA configuration file.
+
+ #endif
+#endif
diff --git a/tmk_core/protocol/midi/bytequeue/COPYING b/tmk_core/protocol/midi/bytequeue/COPYING
new file mode 100755
index 000000000..94a9ed024
--- /dev/null
+++ b/tmk_core/protocol/midi/bytequeue/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ <program> Copyright (C) <year> <name of author>
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+<http://www.gnu.org/licenses/>.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+<http://www.gnu.org/philosophy/why-not-lgpl.html>.
diff --git a/tmk_core/protocol/midi/bytequeue/bytequeue.c b/tmk_core/protocol/midi/bytequeue/bytequeue.c
new file mode 100755
index 000000000..e43495632
--- /dev/null
+++ b/tmk_core/protocol/midi/bytequeue/bytequeue.c
@@ -0,0 +1,65 @@
+//this is a single reader [maybe multiple writer?] byte queue
+//Copyright 2008 Alex Norman
+//writen by Alex Norman
+//
+//This file is part of avr-bytequeue.
+//
+//avr-bytequeue is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-bytequeue is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-bytequeue. If not, see <http://www.gnu.org/licenses/>.
+
+#include "bytequeue.h"
+#include "interrupt_setting.h"
+
+void bytequeue_init(byteQueue_t * queue, uint8_t * dataArray, byteQueueIndex_t arrayLen){
+ queue->length = arrayLen;
+ queue->data = dataArray;
+ queue->start = queue->end = 0;
+}
+
+bool bytequeue_enqueue(byteQueue_t * queue, uint8_t item){
+ interrupt_setting_t setting = store_and_clear_interrupt();
+ //full
+ if(((queue->end + 1) % queue->length) == queue->start){
+ restore_interrupt_setting(setting);
+ return false;
+ } else {
+ queue->data[queue->end] = item;
+ queue->end = (queue->end + 1) % queue->length;
+ restore_interrupt_setting(setting);
+ return true;
+ }
+}
+
+byteQueueIndex_t bytequeue_length(byteQueue_t * queue){
+ byteQueueIndex_t len;
+ interrupt_setting_t setting = store_and_clear_interrupt();
+ if(queue->end >= queue->start)
+ len = queue->end - queue->start;
+ else
+ len = (queue->length - queue->start) + queue->end;
+ restore_interrupt_setting(setting);
+ return len;
+}
+
+//we don't need to avoid interrupts if there is only one reader
+uint8_t bytequeue_get(byteQueue_t * queue, byteQueueIndex_t index){
+ return queue->data[(queue->start + index) % queue->length];
+}
+
+//we just update the start index to remove elements
+void bytequeue_remove(byteQueue_t * queue, byteQueueIndex_t numToRemove){
+ interrupt_setting_t setting = store_and_clear_interrupt();
+ queue->start = (queue->start + numToRemove) % queue->length;
+ restore_interrupt_setting(setting);
+}
+
diff --git a/tmk_core/protocol/midi/bytequeue/bytequeue.h b/tmk_core/protocol/midi/bytequeue/bytequeue.h
new file mode 100755
index 000000000..e4a286134
--- /dev/null
+++ b/tmk_core/protocol/midi/bytequeue/bytequeue.h
@@ -0,0 +1,59 @@
+//this is a single reader [maybe multiple writer?] byte queue
+//Copyright 2008 Alex Norman
+//writen by Alex Norman
+//
+//This file is part of avr-bytequeue.
+//
+//avr-bytequeue is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-bytequeue is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-bytequeue. If not, see <http://www.gnu.org/licenses/>.
+
+#ifndef BYTEQUEUE_H
+#define BYTEQUEUE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <inttypes.h>
+#include <stdbool.h>
+
+typedef uint8_t byteQueueIndex_t;
+
+typedef struct {
+ byteQueueIndex_t start;
+ byteQueueIndex_t end;
+ byteQueueIndex_t length;
+ uint8_t * data;
+} byteQueue_t;
+
+//you must have a queue, an array of data which the queue will use, and the length of that array
+void bytequeue_init(byteQueue_t * queue, uint8_t * dataArray, byteQueueIndex_t arrayLen);
+
+//add an item to the queue, returns false if the queue is full
+bool bytequeue_enqueue(byteQueue_t * queue, uint8_t item);
+
+//get the length of the queue
+byteQueueIndex_t bytequeue_length(byteQueue_t * queue);
+
+//this grabs data at the index given [starting at queue->start]
+uint8_t bytequeue_get(byteQueue_t * queue, byteQueueIndex_t index);
+
+//update the index in the queue to reflect data that has been dealt with
+void bytequeue_remove(byteQueue_t * queue, byteQueueIndex_t numToRemove);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/tmk_core/protocol/midi/bytequeue/interrupt_setting.c b/tmk_core/protocol/midi/bytequeue/interrupt_setting.c
new file mode 100755
index 000000000..eafef527c
--- /dev/null
+++ b/tmk_core/protocol/midi/bytequeue/interrupt_setting.c
@@ -0,0 +1,36 @@
+//Copyright 20010 Alex Norman
+//writen by Alex Norman
+//
+//This file is part of avr-bytequeue.
+//
+//avr-bytequeue is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-bytequeue is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-bytequeue. If not, see <http://www.gnu.org/licenses/>.
+
+
+//AVR specific code
+//should be able to port to other systems by simply providing chip specific
+//implementations of the typedef and these functions
+
+#include "interrupt_setting.h"
+#include <avr/interrupt.h>
+
+interrupt_setting_t store_and_clear_interrupt(void) {
+ uint8_t sreg = SREG;
+ cli();
+ return sreg;
+}
+
+void restore_interrupt_setting(interrupt_setting_t setting) {
+ SREG = setting;
+}
+
diff --git a/tmk_core/protocol/midi/bytequeue/interrupt_setting.h b/tmk_core/protocol/midi/bytequeue/interrupt_setting.h
new file mode 100755
index 000000000..053d02c9d
--- /dev/null
+++ b/tmk_core/protocol/midi/bytequeue/interrupt_setting.h
@@ -0,0 +1,39 @@
+//Copyright 20010 Alex Norman
+//writen by Alex Norman
+//
+//This file is part of avr-bytequeue.
+//
+//avr-bytequeue is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-bytequeue is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-bytequeue. If not, see <http://www.gnu.org/licenses/>.
+
+#ifndef INTERRUPT_SETTING_H
+#define INTERRUPT_SETTING_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <inttypes.h>
+
+//AVR specific typedef
+typedef uint8_t interrupt_setting_t;
+
+interrupt_setting_t store_and_clear_interrupt(void);
+void restore_interrupt_setting(interrupt_setting_t setting);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/tmk_core/protocol/midi/midi.c b/tmk_core/protocol/midi/midi.c
new file mode 100755
index 000000000..11a589078
--- /dev/null
+++ b/tmk_core/protocol/midi/midi.c
@@ -0,0 +1,277 @@
+//midi for embedded chips,
+//Copyright 2010 Alex Norman
+//
+//This file is part of avr-midi.
+//
+//avr-midi is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-midi is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-midi. If not, see <http://www.gnu.org/licenses/>.
+
+#include "midi.h"
+#include <string.h> //for memcpy
+
+#define MIN(x,y) (((x) < (y)) ? (x) : (y))
+
+#ifndef NULL
+#define NULL 0
+#endif
+
+bool midi_is_statusbyte(uint8_t theByte){
+ return (bool)(theByte & MIDI_STATUSMASK);
+}
+
+bool midi_is_realtime(uint8_t theByte){
+ return (theByte >= MIDI_CLOCK);
+}
+
+midi_packet_length_t midi_packet_length(uint8_t status){
+ switch(status & 0xF0){
+ case MIDI_CC:
+ case MIDI_NOTEON:
+ case MIDI_NOTEOFF:
+ case MIDI_AFTERTOUCH:
+ case MIDI_PITCHBEND:
+ return THREE;
+ case MIDI_PROGCHANGE:
+ case MIDI_CHANPRESSURE:
+ case MIDI_SONGSELECT:
+ return TWO;
+ case 0xF0:
+ switch(status) {
+ case MIDI_CLOCK:
+ case MIDI_TICK:
+ case MIDI_START:
+ case MIDI_CONTINUE:
+ case MIDI_STOP:
+ case MIDI_ACTIVESENSE:
+ case MIDI_RESET:
+ case MIDI_TUNEREQUEST:
+ return ONE;
+ case MIDI_SONGPOSITION:
+ return THREE;
+ case MIDI_TC_QUARTERFRAME:
+ case MIDI_SONGSELECT:
+ return TWO;
+ case SYSEX_END:
+ case SYSEX_BEGIN:
+ default:
+ return UNDEFINED;
+ }
+ default:
+ return UNDEFINED;
+ }
+}
+
+void midi_send_cc(MidiDevice * device, uint8_t chan, uint8_t num, uint8_t val){
+ //CC Status: 0xB0 to 0xBF where the low nibble is the MIDI channel.
+ //CC Data: Controller Num, Controller Val
+ device->send_func(device, 3,
+ MIDI_CC | (chan & MIDI_CHANMASK),
+ num & 0x7F,
+ val & 0x7F);
+}
+
+void midi_send_noteon(MidiDevice * device, uint8_t chan, uint8_t num, uint8_t vel){
+ //Note Data: Note Num, Note Velocity
+ device->send_func(device, 3,
+ MIDI_NOTEON | (chan & MIDI_CHANMASK),
+ num & 0x7F,
+ vel & 0x7F);
+}
+
+void midi_send_noteoff(MidiDevice * device, uint8_t chan, uint8_t num, uint8_t vel){
+ //Note Data: Note Num, Note Velocity
+ device->send_func(device, 3,
+ MIDI_NOTEOFF | (chan & MIDI_CHANMASK),
+ num & 0x7F,
+ vel & 0x7F);
+}
+
+void midi_send_aftertouch(MidiDevice * device, uint8_t chan, uint8_t note_num, uint8_t amt){
+ device->send_func(device, 3,
+ MIDI_AFTERTOUCH | (chan & MIDI_CHANMASK),
+ note_num & 0x7F,
+ amt & 0x7F);
+}
+
+//XXX does this work right?
+//amt in range -0x2000, 0x1fff
+//uAmt should be in range..
+//0x0000 to 0x3FFF
+void midi_send_pitchbend(MidiDevice * device, uint8_t chan, int16_t amt){
+ uint16_t uAmt;
+ //check range
+ if(amt > 0x1fff){
+ uAmt = 0x3FFF;
+ } else if(amt < -0x2000){
+ uAmt = 0;
+ } else {
+ uAmt = amt + 0x2000;
+ }
+ device->send_func(device, 3,
+ MIDI_PITCHBEND | (chan & MIDI_CHANMASK),
+ uAmt & 0x7F,
+ (uAmt >> 7) & 0x7F);
+}
+
+void midi_send_programchange(MidiDevice * device, uint8_t chan, uint8_t num){
+ device->send_func(device, 2,
+ MIDI_PROGCHANGE | (chan & MIDI_CHANMASK),
+ num & 0x7F,
+ 0);
+}
+
+void midi_send_channelpressure(MidiDevice * device, uint8_t chan, uint8_t amt){
+ device->send_func(device, 2,
+ MIDI_CHANPRESSURE | (chan & MIDI_CHANMASK),
+ amt & 0x7F,
+ 0);
+}
+
+void midi_send_clock(MidiDevice * device){
+ device->send_func(device, 1, MIDI_CLOCK, 0, 0);
+}
+
+void midi_send_tick(MidiDevice * device){
+ device->send_func(device, 1, MIDI_TICK, 0, 0);
+}
+
+void midi_send_start(MidiDevice * device){
+ device->send_func(device, 1, MIDI_START, 0, 0);
+}
+
+void midi_send_continue(MidiDevice * device){
+ device->send_func(device, 1, MIDI_CONTINUE, 0, 0);
+}
+
+void midi_send_stop(MidiDevice * device){
+ device->send_func(device, 1, MIDI_STOP, 0, 0);
+}
+
+void midi_send_activesense(MidiDevice * device){
+ device->send_func(device, 1, MIDI_ACTIVESENSE, 0, 0);
+}
+
+void midi_send_reset(MidiDevice * device){
+ device->send_func(device, 1, MIDI_RESET, 0, 0);
+}
+
+void midi_send_tcquarterframe(MidiDevice * device, uint8_t time){
+ device->send_func(device, 2,
+ MIDI_TC_QUARTERFRAME,
+ time & 0x7F,
+ 0);
+}
+
+//XXX is this right?
+void midi_send_songposition(MidiDevice * device, uint16_t pos){
+ device->send_func(device, 3,
+ MIDI_SONGPOSITION,
+ pos & 0x7F,
+ (pos >> 7) & 0x7F);
+}
+
+void midi_send_songselect(MidiDevice * device, uint8_t song){
+ device->send_func(device, 2,
+ MIDI_SONGSELECT,
+ song & 0x7F,
+ 0);
+}
+
+void midi_send_tunerequest(MidiDevice * device){
+ device->send_func(device, 1, MIDI_TUNEREQUEST, 0, 0);
+}
+
+void midi_send_byte(MidiDevice * device, uint8_t b){
+ device->send_func(device, 1, b, 0, 0);
+}
+
+void midi_send_data(MidiDevice * device, uint16_t count, uint8_t byte0, uint8_t byte1, uint8_t byte2){
+ //ensure that the count passed along is always 3 or lower
+ if (count > 3) {
+ //TODO how to do this correctly?
+ }
+ device->send_func(device, count, byte0, byte1, byte2);
+}
+
+void midi_send_array(MidiDevice * device, uint16_t count, uint8_t * array) {
+ uint16_t i;
+ for (i = 0; i < count; i += 3) {
+ uint8_t b[3] = { 0, 0, 0 };
+ uint16_t to_send = count - i;
+ to_send = (to_send > 3) ? 3 : to_send;
+ memcpy(b, array + i, to_send);
+ midi_send_data(device, to_send, b[0], b[1], b[2]);
+ }
+}
+
+
+void midi_register_cc_callback(MidiDevice * device, midi_three_byte_func_t func){
+ device->input_cc_callback = func;
+}
+
+void midi_register_noteon_callback(MidiDevice * device, midi_three_byte_func_t func){
+ device->input_noteon_callback = func;
+}
+
+void midi_register_noteoff_callback(MidiDevice * device, midi_three_byte_func_t func){
+ device->input_noteoff_callback = func;
+}
+
+void midi_register_aftertouch_callback(MidiDevice * device, midi_three_byte_func_t func){
+ device->input_aftertouch_callback = func;
+}
+
+void midi_register_pitchbend_callback(MidiDevice * device, midi_three_byte_func_t func){
+ device->input_pitchbend_callback = func;
+}
+
+void midi_register_songposition_callback(MidiDevice * device, midi_three_byte_func_t func){
+ device->input_songposition_callback = func;
+}
+
+void midi_register_progchange_callback(MidiDevice * device, midi_two_byte_func_t func) {
+ device->input_progchange_callback = func;
+}
+
+void midi_register_chanpressure_callback(MidiDevice * device, midi_two_byte_func_t func) {
+ device->input_chanpressure_callback = func;
+}
+
+void midi_register_songselect_callback(MidiDevice * device, midi_two_byte_func_t func) {
+ device->input_songselect_callback = func;
+}
+
+void midi_register_tc_quarterframe_callback(MidiDevice * device, midi_two_byte_func_t func) {
+ device->input_tc_quarterframe_callback = func;
+}
+
+void midi_register_realtime_callback(MidiDevice * device, midi_one_byte_func_t func){
+ device->input_realtime_callback = func;
+}
+
+void midi_register_tunerequest_callback(MidiDevice * device, midi_one_byte_func_t func){
+ device->input_tunerequest_callback = func;
+}
+
+void midi_register_sysex_callback(MidiDevice * device, midi_sysex_func_t func) {
+ device->input_sysex_callback = func;
+}
+
+void midi_register_fallthrough_callback(MidiDevice * device, midi_var_byte_func_t func){
+ device->input_fallthrough_callback = func;
+}
+
+void midi_register_catchall_callback(MidiDevice * device, midi_var_byte_func_t func){
+ device->input_catchall_callback = func;
+}
+
diff --git a/tmk_core/protocol/midi/midi.h b/tmk_core/protocol/midi/midi.h
new file mode 100755
index 000000000..1a36737df
--- /dev/null
+++ b/tmk_core/protocol/midi/midi.h
@@ -0,0 +1,498 @@
+//midi for embedded chips,
+//Copyright 2010 Alex Norman
+//
+//This file is part of avr-midi.
+//
+//avr-midi is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-midi is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-midi. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * @file
+ * @brief The main midi functions
+ *
+ * This file includes all of the functions you need to set up and process a
+ * midi device, send midi, and register midi callbacks.
+ *
+ */
+
+#ifndef XNOR_MIDI_H
+#define XNOR_MIDI_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include "midi_device.h"
+#include "midi_function_types.h"
+
+/**
+ * @defgroup midi_device_setup_process Device initialization and processing
+ * @brief These are method that you must use to initialize and run a device
+ *
+ * @{
+ */
+
+/**
+ * @brief Initialize a device
+ *
+ * You must call this before using the device in question.
+ *
+ * @param device the device to initialize
+*/
+void midi_device_init(MidiDevice * device); // [implementation in midi_device.c]
+
+/**
+ * @brief Process input data
+ *
+ * This method drives the input processing, you must call this method frequently
+ * if you expect to have your input callbacks called.
+ *
+ * @param device the device to process
+*/
+void midi_device_process(MidiDevice * device); // [implementation in midi_device.c]
+
+/**@}*/
+
+/**
+ * @defgroup send_functions Midi send functions
+ * @brief These are the functions you use to send midi data through a device.
+ * @{
+ */
+
+/**
+ * @brief Send a control change message (cc) via the given device.
+ *
+ * @param device the device to use for sending
+ * @param chan the channel to send on, 0-15
+ * @param num the cc num
+ * @param val the value of that cc num
+*/
+void midi_send_cc(MidiDevice * device, uint8_t chan, uint8_t num, uint8_t val);
+
+/**
+ * @brief Send a note on message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param chan the channel to send on, 0-15
+ * @param num the note number
+ * @param vel the note velocity
+*/
+void midi_send_noteon(MidiDevice * device, uint8_t chan, uint8_t num, uint8_t vel);
+
+/**
+ * @brief Send a note off message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param chan the channel to send on, 0-15
+ * @param num the note number
+ * @param vel the note velocity
+*/
+void midi_send_noteoff(MidiDevice * device, uint8_t chan, uint8_t num, uint8_t vel);
+
+/**
+ * @brief Send an after touch message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param chan the channel to send on, 0-15
+ * @param note_num the note number
+ * @param amt the after touch amount
+*/
+void midi_send_aftertouch(MidiDevice * device, uint8_t chan, uint8_t note_num, uint8_t amt);
+
+/**
+ * @brief Send a pitch bend message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param chan the channel to send on, 0-15
+ * @param amt the bend amount range: -8192..8191, 0 means no bend
+*/
+void midi_send_pitchbend(MidiDevice * device, uint8_t chan, int16_t amt); //range -8192, 8191
+
+/**
+ * @brief Send a program change message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param chan the channel to send on, 0-15
+ * @param num the program to change to
+*/
+void midi_send_programchange(MidiDevice * device, uint8_t chan, uint8_t num);
+
+/**
+ * @brief Send a channel pressure message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param chan the channel to send on, 0-15
+ * @param amt the amount of channel pressure
+*/
+void midi_send_channelpressure(MidiDevice * device, uint8_t chan, uint8_t amt);
+
+/**
+ * @brief Send a clock message via the given device.
+ *
+ * @param device the device to use for sending
+ */
+void midi_send_clock(MidiDevice * device);
+
+/**
+ * @brief Send a tick message via the given device.
+ *
+ * @param device the device to use for sending
+ */
+void midi_send_tick(MidiDevice * device);
+
+/**
+ * @brief Send a start message via the given device.
+ *
+ * @param device the device to use for sending
+ */
+void midi_send_start(MidiDevice * device);
+
+/**
+ * @brief Send a continue message via the given device.
+ *
+ * @param device the device to use for sending
+ */
+void midi_send_continue(MidiDevice * device);
+
+/**
+ * @brief Send a stop message via the given device.
+ *
+ * @param device the device to use for sending
+ */
+void midi_send_stop(MidiDevice * device);
+
+/**
+ * @brief Send an active sense message via the given device.
+ *
+ * @param device the device to use for sending
+ */
+void midi_send_activesense(MidiDevice * device);
+
+/**
+ * @brief Send a reset message via the given device.
+ *
+ * @param device the device to use for sending
+ */
+void midi_send_reset(MidiDevice * device);
+
+
+/**
+ * @brief Send a tc quarter frame message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param time the time of this quarter frame, range 0..16383
+ */
+void midi_send_tcquarterframe(MidiDevice * device, uint8_t time);
+
+/**
+ * @brief Send a song position message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param pos the song position
+ */
+void midi_send_songposition(MidiDevice * device, uint16_t pos);
+
+/**
+ * @brief Send a song select message via the given device.
+ *
+ * @param device the device to use for sending
+ * @param song the song to select
+ */
+void midi_send_songselect(MidiDevice * device, uint8_t song);
+
+/**
+ * @brief Send a tune request message via the given device.
+ *
+ * @param device the device to use for sending
+ */
+void midi_send_tunerequest(MidiDevice * device);
+
+/**
+ * @brief Send a byte via the given device.
+ *
+ * This is a generic method for sending data via the given midi device.
+ * This would be useful for sending sysex data or messages that are not
+ * implemented in this API, if there are any. Please contact the author
+ * if you find some so we can add them.
+ *
+ * @param device the device to use for sending
+ * @param b the byte to send
+ */
+void midi_send_byte(MidiDevice * device, uint8_t b);
+
+/**
+ * @brief Send up to 3 bytes of data
+ *
+ * % 4 is applied to count so that you can use this to pass sysex through
+ *
+ * @param device the device to use for sending
+ * @param count the count of bytes to send, %4 is applied
+ * @param byte0 the first byte
+ * @param byte1 the second byte, ignored if cnt % 4 != 2
+ * @param byte2 the third byte, ignored if cnt % 4 != 3
+ */
+void midi_send_data(MidiDevice * device, uint16_t count, uint8_t byte0, uint8_t byte1, uint8_t byte2);
+
+/**
+ * @brief Send an array of formatted midi data.
+ *
+ * Can be used for sysex.
+ *
+ * @param device the device to use for sending
+ * @param count the count of bytes to send
+ * @param array the array of bytes
+ */
+void midi_send_array(MidiDevice * device, uint16_t count, uint8_t * array);
+
+/**@}*/
+
+
+/**
+ * @defgroup input_callback_reg Input callback registration functions
+ *
+ * @brief These are the functions you use to register your input callbacks.
+ *
+ * The functions are called when the appropriate midi message is matched on the
+ * associated device's input.
+ *
+ * @{
+ */
+
+//three byte funcs
+
+/**
+ * @brief Register a control change message (cc) callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_cc_callback(MidiDevice * device, midi_three_byte_func_t func);
+
+/**
+ * @brief Register a note on callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_noteon_callback(MidiDevice * device, midi_three_byte_func_t func);
+
+/**
+ * @brief Register a note off callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_noteoff_callback(MidiDevice * device, midi_three_byte_func_t func);
+
+/**
+ * @brief Register an after touch callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+
+void midi_register_aftertouch_callback(MidiDevice * device, midi_three_byte_func_t func);
+
+/**
+ * @brief Register a pitch bend callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_pitchbend_callback(MidiDevice * device, midi_three_byte_func_t func);
+
+/**
+ * @brief Register a song position callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_songposition_callback(MidiDevice * device, midi_three_byte_func_t func);
+
+//two byte funcs
+
+/**
+ * @brief Register a program change callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_progchange_callback(MidiDevice * device, midi_two_byte_func_t func);
+
+/**
+ * @brief Register a channel pressure callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_chanpressure_callback(MidiDevice * device, midi_two_byte_func_t func);
+
+/**
+ * @brief Register a song select callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_songselect_callback(MidiDevice * device, midi_two_byte_func_t func);
+
+/**
+ * @brief Register a tc quarter frame callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_tc_quarterframe_callback(MidiDevice * device, midi_two_byte_func_t func);
+
+//one byte funcs
+
+/**
+ * @brief Register a realtime callback.
+ *
+ * The callback will be called for all of the real time message types.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_realtime_callback(MidiDevice * device, midi_one_byte_func_t func);
+
+/**
+ * @brief Register a tune request callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_tunerequest_callback(MidiDevice * device, midi_one_byte_func_t func);
+
+/**
+ * @brief Register a sysex callback.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_sysex_callback(MidiDevice * device, midi_sysex_func_t func);
+
+/**
+ * @brief Register fall through callback.
+ *
+ * This is only called if a more specific callback is not matched and called.
+ * For instance, if you don't register a note on callback but you get a note on message
+ * the fall through callback will be called, if it is registered.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_fallthrough_callback(MidiDevice * device, midi_var_byte_func_t func);
+
+
+/**
+ * @brief Register a catch all callback.
+ *
+ * If registered, the catch all callback is called for every message that is
+ * matched, even if a more specific or the fallthrough callback is registered.
+ *
+ * @param device the device associate with
+ * @param func the callback function to register
+ */
+void midi_register_catchall_callback(MidiDevice * device, midi_var_byte_func_t func);
+
+/**@}*/
+
+/**
+ * @defgroup midi_util Device independent utility functions.
+ * @{
+ */
+
+/**
+ * \enum midi_packet_length_t
+ *
+ * An enumeration of the possible packet length values.
+ */
+typedef enum {
+ UNDEFINED = 0,
+ ONE = 1,
+ TWO = 2,
+ THREE = 3} midi_packet_length_t;
+
+/**
+ * @brief Test to see if the byte given is a status byte
+ * @param theByte the byte to test
+ * @return true if the byte given is a midi status byte
+ */
+bool midi_is_statusbyte(uint8_t theByte);
+
+/**
+ * @brief Test to see if the byte given is a realtime message
+ * @param theByte the byte to test
+ * @return true if it is a realtime message, false otherwise
+ */
+bool midi_is_realtime(uint8_t theByte);
+
+/**
+ * @brief Find the length of the packet associated with the status byte given
+ * @param status the status byte
+ * @return the length of the packet, will return UNDEFINED if the byte is not
+ * a status byte or if it is a sysex status byte
+ */
+midi_packet_length_t midi_packet_length(uint8_t status);
+
+/**@}*/
+
+/**
+ * @defgroup defines Midi status and miscellaneous utility #defines
+ *
+ * @{
+ */
+
+#define SYSEX_BEGIN 0xF0
+#define SYSEX_END 0xF7
+
+//if you and this with a byte and you get anything non-zero
+//it is a status message
+#define MIDI_STATUSMASK 0x80
+//if you and this with a status message that contains channel info,
+//you'll get the channel
+#define MIDI_CHANMASK 0x0F
+
+#define MIDI_CC 0xB0
+#define MIDI_NOTEON 0x90
+#define MIDI_NOTEOFF 0x80
+#define MIDI_AFTERTOUCH 0xA0
+#define MIDI_PITCHBEND 0xE0
+#define MIDI_PROGCHANGE 0xC0
+#define MIDI_CHANPRESSURE 0xD0
+
+//midi realtime
+#define MIDI_CLOCK 0xF8
+#define MIDI_TICK 0xF9
+#define MIDI_START 0xFA
+#define MIDI_CONTINUE 0xFB
+#define MIDI_STOP 0xFC
+#define MIDI_ACTIVESENSE 0xFE
+#define MIDI_RESET 0xFF
+
+#define MIDI_TC_QUARTERFRAME 0xF1
+#define MIDI_SONGPOSITION 0xF2
+#define MIDI_SONGSELECT 0xF3
+#define MIDI_TUNEREQUEST 0xF6
+
+//This ID is for educational or development use only
+#define SYSEX_EDUMANUFID 0x7D
+
+/**@}*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/tmk_core/protocol/midi/midi_device.c b/tmk_core/protocol/midi/midi_device.c
new file mode 100755
index 000000000..3215a007d
--- /dev/null
+++ b/tmk_core/protocol/midi/midi_device.c
@@ -0,0 +1,291 @@
+//midi for embedded chips,
+//Copyright 2010 Alex Norman
+//
+//This file is part of avr-midi.
+//
+//avr-midi is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-midi is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-midi. If not, see <http://www.gnu.org/licenses/>.
+
+#include "midi_device.h"
+#include "midi.h"
+
+#ifndef NULL
+#define NULL 0
+#endif
+
+//forward declarations, internally used to call the callbacks
+void midi_input_callbacks(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2);
+void midi_process_byte(MidiDevice * device, uint8_t input);
+
+void midi_device_init(MidiDevice * device){
+ device->input_state = IDLE;
+ device->input_count = 0;
+ bytequeue_init(&device->input_queue, device->input_queue_data, MIDI_INPUT_QUEUE_LENGTH);
+
+ //three byte funcs
+ device->input_cc_callback = NULL;
+ device->input_noteon_callback = NULL;
+ device->input_noteoff_callback = NULL;
+ device->input_aftertouch_callback = NULL;
+ device->input_pitchbend_callback = NULL;
+ device->input_songposition_callback = NULL;
+
+ //two byte funcs
+ device->input_progchange_callback = NULL;
+ device->input_chanpressure_callback = NULL;
+ device->input_songselect_callback = NULL;
+ device->input_tc_quarterframe_callback = NULL;
+
+ //one byte funcs
+ device->input_realtime_callback = NULL;
+ device->input_tunerequest_callback = NULL;
+
+ //var byte functions
+ device->input_sysex_callback = NULL;
+ device->input_fallthrough_callback = NULL;
+ device->input_catchall_callback = NULL;
+
+ device->pre_input_process_callback = NULL;
+}
+
+void midi_device_input(MidiDevice * device, uint8_t cnt, uint8_t * input) {
+ uint8_t i;
+ for (i = 0; i < cnt; i++)
+ bytequeue_enqueue(&device->input_queue, input[i]);
+}
+
+void midi_device_set_send_func(MidiDevice * device, midi_var_byte_func_t send_func){
+ device->send_func = send_func;
+}
+
+void midi_device_set_pre_input_process_func(MidiDevice * device, midi_no_byte_func_t pre_process_func){
+ device->pre_input_process_callback = pre_process_func;
+}
+
+void midi_device_process(MidiDevice * device) {
+ //call the pre_input_process_callback if there is one
+ if(device->pre_input_process_callback)
+ device->pre_input_process_callback(device);
+
+ //pull stuff off the queue and process
+ byteQueueIndex_t len = bytequeue_length(&device->input_queue);
+ uint16_t i;
+ //TODO limit number of bytes processed?
+ for(i = 0; i < len; i++) {
+ uint8_t val = bytequeue_get(&device->input_queue, 0);
+ midi_process_byte(device, val);
+ bytequeue_remove(&device->input_queue, 1);
+ }
+}
+
+void midi_process_byte(MidiDevice * device, uint8_t input) {
+ if (midi_is_realtime(input)) {
+ //call callback, store and restore state
+ input_state_t state = device->input_state;
+ device->input_state = ONE_BYTE_MESSAGE;
+ midi_input_callbacks(device, 1, input, 0, 0);
+ device->input_state = state;
+ } else if (midi_is_statusbyte(input)) {
+ //store the byte
+ if (device->input_state != SYSEX_MESSAGE) {
+ device->input_buffer[0] = input;
+ device->input_count = 1;
+ }
+ switch (midi_packet_length(input)) {
+ case ONE:
+ device->input_state = ONE_BYTE_MESSAGE;;
+ midi_input_callbacks(device, 1, input, 0, 0);
+ device->input_state = IDLE;
+ break;
+ case TWO:
+ device->input_state = TWO_BYTE_MESSAGE;
+ break;
+ case THREE:
+ device->input_state = THREE_BYTE_MESSAGE;
+ break;
+ case UNDEFINED:
+ switch(input) {
+ case SYSEX_BEGIN:
+ device->input_state = SYSEX_MESSAGE;
+ device->input_buffer[0] = input;
+ device->input_count = 1;
+ break;
+ case SYSEX_END:
+ //send what is left in the input buffer, set idle
+ device->input_buffer[device->input_count % 3] = input;
+ device->input_count += 1;
+ //call the callback
+ midi_input_callbacks(device, device->input_count,
+ device->input_buffer[0], device->input_buffer[1], device->input_buffer[2]);
+ device->input_state = IDLE;
+ break;
+ default:
+ device->input_state = IDLE;
+ device->input_count = 0;
+ }
+
+ break;
+ default:
+ device->input_state = IDLE;
+ device->input_count = 0;
+ break;
+ }
+ } else {
+ if (device->input_state != IDLE) {
+ //store the byte
+ device->input_buffer[device->input_count % 3] = input;
+ //increment count
+ uint16_t prev = device->input_count;
+ device->input_count += 1;
+
+ switch(prev % 3) {
+ case 2:
+ //call callback
+ midi_input_callbacks(device, device->input_count,
+ device->input_buffer[0], device->input_buffer[1], device->input_buffer[2]);
+ if (device->input_state != SYSEX_MESSAGE) {
+ //set to 1, keeping status byte, allowing for running status
+ device->input_count = 1;
+ }
+ break;
+ case 1:
+ if (device->input_state == TWO_BYTE_MESSAGE) {
+ //call callback
+ midi_input_callbacks(device, device->input_count,
+ device->input_buffer[0], device->input_buffer[1], 0);
+ if (device->input_state != SYSEX_MESSAGE) {
+ //set to 1, keeping status byte, allowing for running status
+ device->input_count = 1;
+ }
+ }
+ break;
+ case 0:
+ default:
+ //one byte messages are dealt with directly
+ break;
+ }
+ }
+ }
+}
+
+void midi_input_callbacks(MidiDevice * device, uint16_t cnt, uint8_t byte0, uint8_t byte1, uint8_t byte2) {
+ //did we end up calling a callback?
+ bool called = false;
+ if (device->input_state == SYSEX_MESSAGE) {
+ if (device->input_sysex_callback) {
+ const uint16_t start = ((cnt - 1) / 3) * 3;
+ const uint8_t length = (cnt - start);
+ uint8_t data[3];
+ data[0] = byte0;
+ data[1] = byte1;
+ data[2] = byte2;
+ device->input_sysex_callback(device, start, length, data);
+ called = true;
+ }
+ } else {
+ switch (cnt) {
+ case 3:
+ {
+ midi_three_byte_func_t func = NULL;
+ switch (byte0 & 0xF0) {
+ case MIDI_CC:
+ func = device->input_cc_callback;
+ break;
+ case MIDI_NOTEON:
+ func = device->input_noteon_callback;
+ break;
+ case MIDI_NOTEOFF:
+ func = device->input_noteoff_callback;
+ break;
+ case MIDI_AFTERTOUCH:
+ func = device->input_aftertouch_callback;
+ break;
+ case MIDI_PITCHBEND:
+ func = device->input_pitchbend_callback;
+ break;
+ case 0xF0:
+ if (byte0 == MIDI_SONGPOSITION)
+ func = device->input_songposition_callback;
+ break;
+ default:
+ break;
+ }
+ if(func) {
+ //mask off the channel for non song position functions
+ if (byte0 == MIDI_SONGPOSITION)
+ func(device, byte0, byte1, byte2);
+ else
+ func(device, byte0 & 0x0F, byte1, byte2);
+ called = true;
+ }
+ }
+ break;
+ case 2:
+ {
+ midi_two_byte_func_t func = NULL;
+ switch (byte0 & 0xF0) {
+ case MIDI_PROGCHANGE:
+ func = device->input_progchange_callback;
+ break;
+ case MIDI_CHANPRESSURE:
+ func = device->input_chanpressure_callback;
+ break;
+ case 0xF0:
+ if (byte0 == MIDI_SONGSELECT)
+ func = device->input_songselect_callback;
+ else if (byte0 == MIDI_TC_QUARTERFRAME)
+ func = device->input_tc_quarterframe_callback;
+ break;
+ default:
+ break;
+ }
+ if(func) {
+ //mask off the channel
+ if (byte0 == MIDI_SONGSELECT || byte0 == MIDI_TC_QUARTERFRAME)
+ func(device, byte0, byte1);
+ else
+ func(device, byte0 & 0x0F, byte1);
+ called = true;
+ }
+ }
+ break;
+ case 1:
+ {
+ midi_one_byte_func_t func = NULL;
+ if (midi_is_realtime(byte0))
+ func = device->input_realtime_callback;
+ else if (byte0 == MIDI_TUNEREQUEST)
+ func = device->input_tunerequest_callback;
+ if (func) {
+ func(device, byte0);
+ called = true;
+ }
+ }
+ break;
+ default:
+ //just in case
+ if (cnt > 3)
+ cnt = 0;
+ break;
+ }
+ }
+
+ //if there is fallthrough default callback and we haven't called a more specific one,
+ //call the fallthrough
+ if (!called && device->input_fallthrough_callback)
+ device->input_fallthrough_callback(device, cnt, byte0, byte1, byte2);
+ //always call the catch all if it exists
+ if (device->input_catchall_callback)
+ device->input_catchall_callback(device, cnt, byte0, byte1, byte2);
+}
+
diff --git a/tmk_core/protocol/midi/midi_device.h b/tmk_core/protocol/midi/midi_device.h
new file mode 100755
index 000000000..088995286
--- /dev/null
+++ b/tmk_core/protocol/midi/midi_device.h
@@ -0,0 +1,156 @@
+//midi for embedded chips,
+//Copyright 2010 Alex Norman
+//
+//This file is part of avr-midi.
+//
+//avr-midi is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-midi is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-midi. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * @file
+ * @brief Device implementation functions
+ */
+
+#ifndef MIDI_DEVICE_H
+#define MIDI_DEVICE_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @defgroup midi_device Functions used when implementing your own midi device.
+ *
+ * You use the functions when you are implementing your own midi device.
+ *
+ * You set a send function to actually send bytes via your device, this method
+ * is called when you call a send function with this device, for instance
+ * midi_send_cc
+ *
+ * You use the midi_device_input to process input data from the device and pass
+ * it through the device's associated callbacks.
+ *
+ * You use the midi_device_set_pre_input_process_func if you want to have a
+ * function called at the beginning of the device's process function, generally
+ * to poll for input and pass that into midi_device_input
+ *
+ * @{
+ */
+
+#include "midi_function_types.h"
+#include "bytequeue/bytequeue.h"
+#define MIDI_INPUT_QUEUE_LENGTH 192
+
+typedef enum {
+ IDLE,
+ ONE_BYTE_MESSAGE = 1,
+ TWO_BYTE_MESSAGE = 2,
+ THREE_BYTE_MESSAGE = 3,
+ SYSEX_MESSAGE} input_state_t;
+
+typedef void (* midi_no_byte_func_t)(MidiDevice * device);
+
+/**
+ * \struct _midi_device
+ *
+ * @brief This structure represents the input and output functions and
+ * processing data for a midi device.
+ *
+ * A device can represent an actual physical device [serial port, usb port] or
+ * something virtual.
+ * You should not need to modify this structure directly.
+ */
+struct _midi_device {
+ //output send function
+ midi_var_byte_func_t send_func;
+
+ //********input callbacks
+ //three byte funcs
+ midi_three_byte_func_t input_cc_callback;
+ midi_three_byte_func_t input_noteon_callback;
+ midi_three_byte_func_t input_noteoff_callback;
+ midi_three_byte_func_t input_aftertouch_callback;
+ midi_three_byte_func_t input_pitchbend_callback;
+ midi_three_byte_func_t input_songposition_callback;
+ //two byte funcs
+ midi_two_byte_func_t input_progchange_callback;
+ midi_two_byte_func_t input_chanpressure_callback;
+ midi_two_byte_func_t input_songselect_callback;
+ midi_two_byte_func_t input_tc_quarterframe_callback;
+ //one byte funcs
+ midi_one_byte_func_t input_realtime_callback;
+ midi_one_byte_func_t input_tunerequest_callback;
+
+ //sysex
+ midi_sysex_func_t input_sysex_callback;
+
+ //only called if more specific callback is not matched
+ midi_var_byte_func_t input_fallthrough_callback;
+ //called if registered, independent of other callbacks
+ midi_var_byte_func_t input_catchall_callback;
+
+ //pre input processing function
+ midi_no_byte_func_t pre_input_process_callback;
+
+ //for internal input processing
+ uint8_t input_buffer[3];
+ input_state_t input_state;
+ uint16_t input_count;
+
+ //for queueing data between the input and the processing functions
+ uint8_t input_queue_data[MIDI_INPUT_QUEUE_LENGTH];
+ byteQueue_t input_queue;
+};
+
+/**
+ * @brief Process input bytes. This function parses bytes and calls the
+ * appropriate callbacks associated with the given device. You use this
+ * function if you are creating a custom device and you want to have midi
+ * input.
+ *
+ * @param device the midi device to associate the input with
+ * @param cnt the number of bytes you are processing
+ * @param input the bytes to process
+ */
+void midi_device_input(MidiDevice * device, uint8_t cnt, uint8_t * input);
+
+/**
+ * @brief Set the callback function that will be used for sending output
+ * data bytes. This is only used if you're creating a custom device.
+ * You'll most likely want the callback function to disable interrupts so
+ * that you can call the various midi send functions without worrying about
+ * locking.
+ *
+ * \param device the midi device to associate this callback with
+ * \param send_func the callback function that will do the sending
+ */
+void midi_device_set_send_func(MidiDevice * device, midi_var_byte_func_t send_func);
+
+/**
+ * @brief Set a callback which is called at the beginning of the
+ * midi_device_process call. This can be used to poll for input
+ * data and send the data through the midi_device_input function.
+ * You'll probably only use this if you're creating a custom device.
+ *
+ * \param device the midi device to associate this callback with
+ * \param midi_no_byte_func_t the actual callback function
+ */
+void midi_device_set_pre_input_process_func(MidiDevice * device, midi_no_byte_func_t pre_process_func);
+
+/**@}*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/tmk_core/protocol/midi/midi_function_types.h b/tmk_core/protocol/midi/midi_function_types.h
new file mode 100755
index 000000000..35c4601b2
--- /dev/null
+++ b/tmk_core/protocol/midi/midi_function_types.h
@@ -0,0 +1,50 @@
+//midi for embedded chips,
+//Copyright 2010 Alex Norman
+//
+//This file is part of avr-midi.
+//
+//avr-midi is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-midi is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-midi. If not, see <http://www.gnu.org/licenses/>.
+
+/**
+ * @file
+ * @brief Function signature definitions
+ */
+
+#ifndef MIDI_FUNCTION_TYPES_H
+#define MIDI_FUNCTION_TYPES_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <inttypes.h>
+#include <stdbool.h>
+
+//forward declaration
+typedef struct _midi_device MidiDevice;
+
+typedef void (* midi_one_byte_func_t)(MidiDevice * device, uint8_t byte);
+typedef void (* midi_two_byte_func_t)(MidiDevice * device, uint8_t byte0, uint8_t byte1);
+typedef void (* midi_three_byte_func_t)(MidiDevice * device, uint8_t byte0, uint8_t byte1, uint8_t byte2);
+//all bytes after count bytes should be ignored
+typedef void (* midi_var_byte_func_t)(MidiDevice * device, uint16_t count, uint8_t byte0, uint8_t byte1, uint8_t byte2);
+
+//the start byte tells you how far into the sysex message you are, the data_length tells you how many bytes data is
+typedef void (* midi_sysex_func_t)(MidiDevice * device, uint16_t start_byte, uint8_t data_length, uint8_t *data);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/tmk_core/protocol/midi/sysex_tools.c b/tmk_core/protocol/midi/sysex_tools.c
new file mode 100755
index 000000000..7563a3e2a
--- /dev/null
+++ b/tmk_core/protocol/midi/sysex_tools.c
@@ -0,0 +1,99 @@
+//midi for embedded chips,
+//Copyright 2010 Alex Norman
+//
+//This file is part of avr-midi.
+//
+//avr-midi is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-midi is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-midi. If not, see <http://www.gnu.org/licenses/>.
+
+#include "sysex_tools.h"
+
+uint16_t sysex_encoded_length(uint16_t decoded_length){
+ uint8_t remainder = decoded_length % 7;
+ if (remainder)
+ return (decoded_length / 7) * 8 + remainder + 1;
+ else
+ return (decoded_length / 7) * 8;
+}
+
+uint16_t sysex_decoded_length(uint16_t encoded_length){
+ uint8_t remainder = encoded_length % 8;
+ if (remainder)
+ return (encoded_length / 8) * 7 + remainder - 1;
+ else
+ return (encoded_length / 8) * 7;
+}
+
+uint16_t sysex_encode(uint8_t *encoded, const uint8_t *source, const uint16_t length){
+ uint16_t encoded_full = length / 7; //number of full 8 byte sections from 7 bytes of input
+ uint16_t i,j;
+
+ //fill out the fully encoded sections
+ for(i = 0; i < encoded_full; i++) {
+ uint16_t encoded_msb_idx = i * 8;
+ uint16_t input_start_idx = i * 7;
+ encoded[encoded_msb_idx] = 0;
+ for(j = 0; j < 7; j++){
+ uint8_t current = source[input_start_idx + j];
+ encoded[encoded_msb_idx] |= (0x80 & current) >> (1 + j);
+ encoded[encoded_msb_idx + 1 + j] = 0x7F & current;
+ }
+ }
+
+ //fill out the rest if there is any more
+ uint8_t remainder = length % 7;
+ if (remainder) {
+ uint16_t encoded_msb_idx = encoded_full * 8;
+ uint16_t input_start_idx = encoded_full * 7;
+ encoded[encoded_msb_idx] = 0;
+ for(j = 0; j < remainder; j++){
+ uint8_t current = source[input_start_idx + j];
+ encoded[encoded_msb_idx] |= (0x80 & current) >> (1 + j);
+ encoded[encoded_msb_idx + 1 + j] = 0x7F & current;
+ }
+ return encoded_msb_idx + remainder + 1;
+ } else {
+ return encoded_full * 8;
+ }
+}
+
+uint16_t sysex_decode(uint8_t *decoded, const uint8_t *source, const uint16_t length){
+ uint16_t decoded_full = length / 8;
+ uint16_t i,j;
+
+ if (length < 2)
+ return 0;
+
+ //fill out the fully encoded sections
+ for(i = 0; i < decoded_full; i++) {
+ uint16_t encoded_msb_idx = i * 8;
+ uint16_t output_start_index = i * 7;
+ for(j = 0; j < 7; j++){
+ decoded[output_start_index + j] = 0x7F & source[encoded_msb_idx + j + 1];
+ decoded[output_start_index + j] |= (0x80 & (source[encoded_msb_idx] << (1 + j)));
+ }
+ }
+ uint8_t remainder = length % 8;
+ if (remainder) {
+ uint16_t encoded_msb_idx = decoded_full * 8;
+ uint16_t output_start_index = decoded_full * 7;
+ for(j = 0; j < (remainder - 1); j++) {
+ decoded[output_start_index + j] = 0x7F & source[encoded_msb_idx + j + 1];
+ decoded[output_start_index + j] |= (0x80 & (source[encoded_msb_idx] << (1 + j)));
+ }
+ return decoded_full * 7 + remainder - 1;
+ } else {
+ return decoded_full * 7;
+ }
+}
+
diff --git a/tmk_core/protocol/midi/sysex_tools.h b/tmk_core/protocol/midi/sysex_tools.h
new file mode 100755
index 000000000..3654d0114
--- /dev/null
+++ b/tmk_core/protocol/midi/sysex_tools.h
@@ -0,0 +1,95 @@
+//midi for embedded chips,
+//Copyright 2010 Alex Norman
+//
+//This file is part of avr-midi.
+//
+//avr-midi is free software: you can redistribute it and/or modify
+//it under the terms of the GNU General Public License as published by
+//the Free Software Foundation, either version 3 of the License, or
+//(at your option) any later version.
+//
+//avr-midi is distributed in the hope that it will be useful,
+//but WITHOUT ANY WARRANTY; without even the implied warranty of
+//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+//GNU General Public License for more details.
+//
+//You should have received a copy of the GNU General Public License
+//along with avr-midi. If not, see <http://www.gnu.org/licenses/>.
+
+#ifndef SYSEX_TOOLS_H
+#define SYSEX_TOOLS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <inttypes.h>
+
+/**
+ * @file
+ * @brief Sysex utility functions
+ *
+ * These functions are for converting data to and from a "midi-safe" format,
+ * which can be use to send data with sysex messages. Sysex messages may only
+ * contain data where the to bit is not set.
+ *
+ * An "encoded" midi message is one that contains all of the data from its
+ * original state, but does not have any of the top bits set.
+ *
+ * Every 7 bytes of decoded data is converted into 8 bytes of encoded data and
+ * visa-versa. If you'd like to operate on small segments, make sure that you
+ * encode in 7 byte increments and decode in 8 byte increments.
+ *
+ */
+
+/** @defgroup sysex_tools Sysex utility functions
+ * @{
+ */
+
+/**
+ * @brief Compute the length of a message after it is encoded.
+ *
+ * @param decoded_length The length, in bytes, of the message to encode.
+ *
+ * @return The length, in bytes, of the message after encodeing.
+ */
+uint16_t sysex_encoded_length(uint16_t decoded_length);
+
+/**
+ * @brief Compute the length of a message after it is decoded.
+ *
+ * @param encoded_length The length, in bytes, of the encoded message.
+ *
+ * @return The length, in bytes, of the message after it is decoded.
+ */
+uint16_t sysex_decoded_length(uint16_t encoded_length);
+
+/**
+ * @brief Encode data so that it can be transmitted safely in a sysex message.
+ *
+ * @param encoded The output data buffer, must be at least sysex_encoded_length(length) bytes long.
+ * @param source The input buffer of data to be encoded.
+ * @param length The number of bytes from the input buffer to encode.
+ *
+ * @return number of bytes encoded.
+ */
+uint16_t sysex_encode(uint8_t *encoded, const uint8_t *source, uint16_t length);
+
+/**
+ * @brief Decode encoded data.
+ *
+ * @param decoded The output data buffer, must be at least sysex_decoded_length(length) bytes long.
+ * @param source The input buffer of data to be decoded.
+ * @param length The number of bytes from the input buffer to decode.
+ *
+ * @return number of bytes decoded.
+ */
+uint16_t sysex_decode(uint8_t *decoded, const uint8_t *source, uint16_t length);
+
+/**@}*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/tmk_core/protocol/news.c b/tmk_core/protocol/news.c
new file mode 100644
index 000000000..00755a5e2
--- /dev/null
+++ b/tmk_core/protocol/news.c
@@ -0,0 +1,168 @@
+/*
+Copyright 2012 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <stdbool.h>
+#include <avr/io.h>
+#include <avr/interrupt.h>
+#include "news.h"
+
+
+void news_init(void)
+{
+ NEWS_KBD_RX_INIT();
+}
+
+// RX ring buffer
+#define RBUF_SIZE 8
+static uint8_t rbuf[RBUF_SIZE];
+static uint8_t rbuf_head = 0;
+static uint8_t rbuf_tail = 0;
+
+uint8_t news_recv(void)
+{
+ uint8_t data = 0;
+ if (rbuf_head == rbuf_tail) {
+ return 0;
+ }
+
+ data = rbuf[rbuf_tail];
+ rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
+ return data;
+}
+
+// USART RX complete interrupt
+ISR(NEWS_KBD_RX_VECT)
+{
+ uint8_t next = (rbuf_head + 1) % RBUF_SIZE;
+ if (next != rbuf_tail) {
+ rbuf[rbuf_head] = NEWS_KBD_RX_DATA;
+ rbuf_head = next;
+ }
+}
+
+
+/*
+SONY NEWS Keyboard Protocol
+===========================
+
+Resources
+---------
+ Mouse protocol of NWA-5461(Japanese)
+ http://groups.google.com/group/fj.sys.news/browse_thread/thread/a01b3e3ac6ae5b2d
+
+ SONY NEWS Info(Japanese)
+ http://katsu.watanabe.name/doc/sonynews/
+
+
+Pinouts
+-------
+ EIA 232 male connector from NWP-5461
+ -------------
+ \ 1 2 3 4 5 /
+ \ 6 7 8 9 /
+ ---------
+ 1 VCC
+ 2 BZ(Speaker)
+ 3 Keyboard Data(from keyboard MCU TxD)
+ 4 NC
+ 5 GND
+ 6 Unknown Input(to keyboard MCU RxD via schmitt trigger)
+ 7 Mouse Data(from Mouse Ext connector)
+ 8 Unknown Input(to Keyboard MCU Input via diode and buffer)
+ 9 FG
+ NOTE: Two LED on keyboard are controlled by pin 6,8?
+
+ EIA 232 male connector from NWP-411A
+ -------------
+ \ 1 2 3 4 5 /
+ \ 6 7 8 9 /
+ ---------
+ 1 VCC
+ 2 BZ(Speaker)
+ 3 Keyboard Data(from keyboard MCU TxD)
+ 4 NC
+ 5 GND
+ 6 NC
+ 7 Mouse Data(from Mouse Ext connector)
+ 8 NC
+ 9 FG
+ NOTE: These are just from my guess and not confirmed.
+
+
+Signaling
+---------
+ ~~~~~~~~~~ ____XOO0X111X222X333X444X555X666X777~~~~ ~~~~~~~
+ Idle Start LSB MSB Stop Idle
+
+ Idle: High
+ Start bit: Low
+ Stop bit: High
+ Bit order: LSB first
+
+ Baud rate: 9600
+ Interface: TTL level(5V) UART
+
+ NOTE: This is observed on NWP-5461 with its DIP switch all OFF.
+
+
+Format
+------
+ MSB LSB
+ 7 6 5 4 3 2 1 0 bit
+ | | | | | | | |
+ | +-+-+-+-+-+-+-- scan code(00-7F)
+ +---------------- break flag: sets when released
+
+
+Scan Codes
+----------
+ SONY NEWS NWP-5461
+ ,---. ,------------------------, ,------------------------. ,---------.
+ | 7A| | 01 | 02 | 03 | 04 | 05 | | 06 | 07 | 08 | 09 | 0A | | 68 | 69 | ,-----------.
+ `---' `------------------------' `------------------------' `---------' | 64| 65| 52|
+ ,-------------------------------------------------------------. ,---. ,---------------|
+ | 0B| 0C| 0D| 0E| 0F| 10| 11| 12| 13| 14| 15| 16| 17| 18| 19 | | 6A| | 4B| 4C| 4D| 4E|
+ |-------------------------------------------------------------| |---| |---------------|
+ | 1A | 1B| 1C| 1D| 1E| 1F| 20| 21| 22| 23| 24| 25| 26| 27| | | 6B| | 4F| 50| 51| 56|
+ |---------------------------------------------------------' | |---| |---------------|
+ | 28 | 29| 2A| 2B| 2C| 2D| 2E| 2F| 30| 31| 32| 33| 34| 35 | | 6C| | 53| 54| 55| |
+ |-------------------------------------------------------------| |---| |-----------| 5A|
+ | 36 | 37| 38| 39| 3A| 3B| 3C| 3D| 3E| 3F| 40| 41| 42 | | 6D| | 57| 59| 58| |
+ |-------------------------------------------------------------| |---| |---------------|
+ | 43 | 44 | 45 | 46 | 47 | 48| 49| 4A | | 6E| | 66| 5B| 5C| 5D|
+ `-------------------------------------------------------------' `---' `---------------'
+*/
diff --git a/tmk_core/protocol/news.h b/tmk_core/protocol/news.h
new file mode 100644
index 000000000..35e09c4d2
--- /dev/null
+++ b/tmk_core/protocol/news.h
@@ -0,0 +1,51 @@
+/*
+Copyright 2012 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef NEWS_H
+#define NEWS_H
+/*
+ * Primitive PS/2 Library for AVR
+ */
+
+
+/* host role */
+void news_init(void);
+uint8_t news_recv(void);
+
+/* device role */
+
+#endif
diff --git a/tmk_core/protocol/next_kbd.c b/tmk_core/protocol/next_kbd.c
new file mode 100644
index 000000000..fa3034b3f
--- /dev/null
+++ b/tmk_core/protocol/next_kbd.c
@@ -0,0 +1,212 @@
+/*
+
+NeXT non-ADB Keyboard Protocol
+
+Copyright 2013, Benjamin Gould (bgould@github.com)
+
+Based on:
+TMK firmware code Copyright 2011,2012 Jun WAKO <wakojun@gmail.com>
+Arduino code by "Ladyada" Limor Fried (http://ladyada.net/, http://adafruit.com/), released under BSD license
+
+Timing reference thanks to http://m0115.web.fc2.com/ (dead link), http://cfile7.uf.tistory.com/image/14448E464F410BF22380BB
+Pinouts thanks to http://www.68k.org/~degs/nextkeyboard.html
+Keycodes from http://ftp.netbsd.org/pub/NetBSD/NetBSD-release-6/src/sys/arch/next68k/dev/
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+*/
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <util/atomic.h>
+#include <util/delay.h>
+#include "next_kbd.h"
+#include "debug.h"
+
+static inline void out_lo(void);
+static inline void out_hi(void);
+static inline void query(void);
+static inline void reset(void);
+static inline uint32_t response(void);
+
+/* The keyboard sends signal with 50us pulse width on OUT line
+ * while it seems to miss the 50us pulse on In line.
+ * next_kbd_set_leds() often fails to sync LED status with 50us
+ * but it works well with 51us(+1us) on TMK converter(ATMeaga32u2) at least.
+ * TODO: test on Teensy and Pro Micro configuration
+ */
+#define out_hi_delay(intervals) do { out_hi(); _delay_us((NEXT_KBD_TIMING+1) * intervals); } while (0);
+#define out_lo_delay(intervals) do { out_lo(); _delay_us((NEXT_KBD_TIMING+1) * intervals); } while (0);
+#define query_delay(intervals) do { query(); _delay_us((NEXT_KBD_TIMING+1) * intervals); } while (0);
+#define reset_delay(intervals) do { reset(); _delay_us((NEXT_KBD_TIMING+1) * intervals); } while (0);
+
+void next_kbd_init(void)
+{
+ out_hi();
+ NEXT_KBD_IN_DDR &= ~(1<<NEXT_KBD_IN_BIT); // KBD_IN to input
+ NEXT_KBD_IN_PORT |= (1<<NEXT_KBD_IN_BIT); // KBD_IN pull up
+
+ query_delay(5);
+ reset_delay(8);
+
+ query_delay(5);
+ reset_delay(8);
+}
+
+void next_kbd_set_leds(bool left, bool right)
+{
+ cli();
+ out_lo_delay(9);
+
+ out_hi_delay(3);
+ out_lo_delay(1);
+
+ if (left) {
+ out_hi_delay(1);
+ } else {
+ out_lo_delay(1);
+ }
+
+ if (right) {
+ out_hi_delay(1);
+ } else {
+ out_lo_delay(1);
+ }
+
+ out_lo_delay(7);
+ out_hi();
+ sei();
+}
+
+#define NEXT_KBD_READ (NEXT_KBD_IN_PIN&(1<<NEXT_KBD_IN_BIT))
+uint32_t next_kbd_recv(void)
+{
+
+ // First check to make sure that the keyboard is actually connected;
+ // if not, just return
+ // TODO: reflect the status of the keyboard in a return code
+ if (!NEXT_KBD_READ) {
+ sei();
+ return 0;
+ }
+
+ query();
+ uint32_t resp = response();
+
+ return resp;
+}
+
+static inline uint32_t response(void)
+{
+ cli();
+
+ // try a 5ms read; this should be called after the query method has
+ // been run so if a key is pressed we should get a response within
+ // 5ms; if not then send a reset and exit
+ uint8_t i = 0;
+ uint32_t data = 0;
+ uint16_t reset_timeout = 50000;
+ while (NEXT_KBD_READ && reset_timeout) {
+ asm(""); _delay_us(1); reset_timeout--;
+ }
+ if (!reset_timeout) {
+ reset();
+ sei();
+ return 0;
+ }
+ _delay_us(NEXT_KBD_TIMING / 2);
+ for (; i < 22; i++)
+ {
+ if (NEXT_KBD_READ)
+ {
+ data |= ((uint32_t) 1 << i);
+ /* Note:
+ * My testing with the ATmega32u4 showed that there might
+ * something wrong with the timing here; by the end of the
+ * second data byte some of the modifiers can get bumped out
+ * to the next bit over if we just cycle through the data
+ * based on the expected interval. There is a bit (i = 10)
+ * in the middle of the data that is always on followed by
+ * one that is always off - so we'll use that to reset our
+ * timing in case we've gotten ahead of the keyboard;
+ */
+ if (i == 10)
+ {
+ i++;
+ while (NEXT_KBD_READ) ;
+ _delay_us(NEXT_KBD_TIMING / 2);
+ }
+ } else {
+ /* redundant - but I don't want to remove if it might screw
+ * up the timing
+ */
+ data |= ((uint32_t) 0 << i);
+ }
+ _delay_us(NEXT_KBD_TIMING);
+ }
+
+ sei();
+
+ return data;
+}
+
+static inline void out_lo(void)
+{
+ NEXT_KBD_OUT_PORT &= ~(1<<NEXT_KBD_OUT_BIT);
+ NEXT_KBD_OUT_DDR |= (1<<NEXT_KBD_OUT_BIT);
+}
+
+static inline void out_hi(void)
+{
+ /* input with pull up */
+ NEXT_KBD_OUT_DDR &= ~(1<<NEXT_KBD_OUT_BIT);
+ NEXT_KBD_OUT_PORT |= (1<<NEXT_KBD_OUT_BIT);
+}
+
+static inline void query(void)
+{
+ out_lo_delay(5);
+ out_hi_delay(1);
+ out_lo_delay(3);
+ out_hi();
+}
+
+static inline void reset(void)
+{
+ out_lo_delay(1);
+ out_hi_delay(4);
+ out_lo_delay(1);
+ out_hi_delay(6);
+ out_lo_delay(10);
+ out_hi();
+}
diff --git a/tmk_core/protocol/next_kbd.h b/tmk_core/protocol/next_kbd.h
new file mode 100644
index 000000000..6d455d4fa
--- /dev/null
+++ b/tmk_core/protocol/next_kbd.h
@@ -0,0 +1,63 @@
+/*
+NeXT non-ADB Keyboard Protocol
+
+Copyright 2013, Benjamin Gould (bgould@github.com)
+
+Based on:
+TMK firmware code Copyright 2011,2012 Jun WAKO <wakojun@gmail.com>
+Arduino code by "Ladyada" Limor Fried (http://ladyada.net/, http://adafruit.com/), released under BSD license
+
+Timing reference thanks to http://m0115.web.fc2.com/ (dead link), http://cfile7.uf.tistory.com/image/14448E464F410BF22380BB
+Pinouts thanks to http://www.68k.org/~degs/nextkeyboard.html
+Keycodes from http://ftp.netbsd.org/pub/NetBSD/NetBSD-release-6/src/sys/arch/next68k/dev/
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+
+*/
+
+#include <stdbool.h>
+
+#ifndef NEXT_KBD_H
+#define NEXT_KBD_H
+
+#define NEXT_KBD_KMBUS_IDLE 0x300600
+#define NEXT_KBD_TIMING 50
+
+extern uint8_t next_kbd_error;
+
+/* host role */
+void next_kbd_init(void);
+void next_kbd_set_leds(bool left, bool right);
+uint32_t next_kbd_recv(void);
+
+#endif
diff --git a/tmk_core/protocol/pjrc.mk b/tmk_core/protocol/pjrc.mk
new file mode 100644
index 000000000..2b1ba2cbf
--- /dev/null
+++ b/tmk_core/protocol/pjrc.mk
@@ -0,0 +1,30 @@
+PJRC_DIR = protocol/pjrc
+
+SRC += $(PJRC_DIR)/main.c \
+ $(PJRC_DIR)/pjrc.c \
+ $(PJRC_DIR)/usb_keyboard.c \
+ $(PJRC_DIR)/usb_debug.c \
+ $(PJRC_DIR)/usb.c
+
+# Option modules
+ifdef MOUSEKEY_ENABLE
+ SRC += $(PJRC_DIR)/usb_mouse.c
+endif
+
+ifdef ADB_MOUSE_ENABLE
+ SRC += $(PJRC_DIR)/usb_mouse.c
+endif
+
+ifdef PS2_MOUSE_ENABLE
+ SRC += $(PJRC_DIR)/usb_mouse.c
+endif
+
+ifdef EXTRAKEY_ENABLE
+ SRC += $(PJRC_DIR)/usb_extra.c
+endif
+
+# Search Path
+VPATH += $(TMK_DIR)/$(PJRC_DIR)
+
+# This indicates using LUFA stack
+OPT_DEFS += -DPROTOCOL_PJRC
diff --git a/tmk_core/protocol/pjrc/MEMO.txt b/tmk_core/protocol/pjrc/MEMO.txt
new file mode 100644
index 000000000..b0f059831
--- /dev/null
+++ b/tmk_core/protocol/pjrc/MEMO.txt
@@ -0,0 +1,25 @@
+Endpoint configuration
+----------------------
+0 Control endpoint
+1 keyboard
+2 mouse
+3 debug
+4 extra key(consumer/system)
+5 nkro keyboard(supported only on ATmega32U4/16U4 and AT90USB64/128)
+
+
+ATmega32U4/16U4, AT90USB64/128
+• Endpoint 0:programmable size FIFO up to 64 bytes, default control endpoint
+• Endpoints 1 programmable size FIFO up to 256 bytes in ping-pong mode.
+• Endpoints 2 to 6: programmable size FIFO up to 64 bytes in ping-pong mode.
+
+AT90USB82/162, ATmega8U2/16U2/32U2
+• Endpoint 0:programmable size FIFO up to 64 bytes, default control endpoint
+• Endpoints 1 and 2: programmable size FIFO up to 64 bytes.
+• Endpoints 3 and 4: programmable size FIFO up to 64 bytes with ping-pong mode.
+
+ping-pong mode means double buffer feature.
+
+
+NOTE: ATmega8U2/16U2/32U2 is not supported with PJRC stack at this time.
+TODO: Macro definition for ATmega8U2/16U2/32U2 in usb.h
diff --git a/tmk_core/protocol/pjrc/main.c b/tmk_core/protocol/pjrc/main.c
new file mode 100644
index 000000000..45eb17d4c
--- /dev/null
+++ b/tmk_core/protocol/pjrc/main.c
@@ -0,0 +1,74 @@
+/* Keyboard example with debug channel, for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2008 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <stdbool.h>
+#include <avr/io.h>
+#include <avr/interrupt.h>
+#include <avr/wdt.h>
+#include <util/delay.h>
+#include "keyboard.h"
+#include "usb.h"
+#include "matrix.h"
+#include "print.h"
+#include "debug.h"
+#include "sendchar.h"
+#include "util.h"
+#include "suspend.h"
+#include "host.h"
+#include "pjrc.h"
+
+
+#define CPU_PRESCALE(n) (CLKPR = 0x80, CLKPR = (n))
+
+
+int main(void)
+{
+ // set for 16 MHz clock
+ CPU_PRESCALE(0);
+
+ keyboard_setup();
+
+ // Initialize the USB, and then wait for the host to set configuration.
+ // If the Teensy is powered without a PC connected to the USB port,
+ // this will wait forever.
+ usb_init();
+ while (!usb_configured()) /* wait */ ;
+
+ print_set_sendchar(sendchar);
+
+ keyboard_init();
+ host_set_driver(pjrc_driver());
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_init();
+#endif
+ while (1) {
+ while (suspend) {
+ suspend_power_down();
+ if (remote_wakeup && suspend_wakeup_condition()) {
+ usb_remote_wakeup();
+ }
+ }
+
+ keyboard_task();
+ }
+}
diff --git a/tmk_core/protocol/pjrc/pjrc.c b/tmk_core/protocol/pjrc/pjrc.c
new file mode 100644
index 000000000..0562a12ff
--- /dev/null
+++ b/tmk_core/protocol/pjrc/pjrc.c
@@ -0,0 +1,76 @@
+/*
+Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdint.h>
+#include "usb_keyboard.h"
+#include "usb_mouse.h"
+#include "usb_extra.h"
+#include "host_driver.h"
+#include "pjrc.h"
+
+
+/*------------------------------------------------------------------*
+ * Host driver
+ *------------------------------------------------------------------*/
+static uint8_t keyboard_leds(void);
+static void send_keyboard(report_keyboard_t *report);
+static void send_mouse(report_mouse_t *report);
+static void send_system(uint16_t data);
+static void send_consumer(uint16_t data);
+
+static host_driver_t driver = {
+ keyboard_leds,
+ send_keyboard,
+ send_mouse,
+ send_system,
+ send_consumer
+};
+
+host_driver_t *pjrc_driver(void)
+{
+ return &driver;
+}
+
+static uint8_t keyboard_leds(void) {
+ return usb_keyboard_leds;
+}
+
+static void send_keyboard(report_keyboard_t *report)
+{
+ usb_keyboard_send_report(report);
+}
+
+static void send_mouse(report_mouse_t *report)
+{
+#ifdef MOUSE_ENABLE
+ usb_mouse_send(report->x, report->y, report->v, report->h, report->buttons);
+#endif
+}
+
+static void send_system(uint16_t data)
+{
+#ifdef EXTRAKEY_ENABLE
+ usb_extra_system_send(data);
+#endif
+}
+
+static void send_consumer(uint16_t data)
+{
+#ifdef EXTRAKEY_ENABLE
+ usb_extra_consumer_send(data);
+#endif
+}
diff --git a/tmk_core/protocol/pjrc/pjrc.h b/tmk_core/protocol/pjrc/pjrc.h
new file mode 100644
index 000000000..06e79626f
--- /dev/null
+++ b/tmk_core/protocol/pjrc/pjrc.h
@@ -0,0 +1,26 @@
+/*
+Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PJRC_H
+#define PJRC_H
+
+#include "host_driver.h"
+
+
+host_driver_t *pjrc_driver(void);
+
+#endif
diff --git a/tmk_core/protocol/pjrc/usb.c b/tmk_core/protocol/pjrc/usb.c
new file mode 100644
index 000000000..09efbe076
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb.c
@@ -0,0 +1,1008 @@
+/* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <avr/io.h>
+#include <avr/pgmspace.h>
+#include <avr/interrupt.h>
+#include "usb.h"
+#include "usb_keyboard.h"
+#include "usb_mouse.h"
+#include "usb_debug.h"
+#include "usb_extra.h"
+#include "led.h"
+#include "print.h"
+#include "util.h"
+#ifdef SLEEP_LED_ENABLE
+#include "sleep_led.h"
+#endif
+#include "suspend.h"
+#include "action.h"
+#include "action_util.h"
+
+#ifdef NKRO_ENABLE
+ #include "keycode_config.h"
+
+ extern keymap_config_t keymap_config;
+#endif
+
+
+/**************************************************************************
+ *
+ * Configurable Options
+ *
+ **************************************************************************/
+
+// You can change these to give your code its own name.
+#ifndef MANUFACTURER
+# define STR_MANUFACTURER L"t.m.k."
+#else
+# define STR_MANUFACTURER LSTR(MANUFACTURER)
+#endif
+#ifndef PRODUCT
+# define STR_PRODUCT L"t.m.k. keyboard"
+#else
+# define STR_PRODUCT LSTR(PRODUCT)
+#endif
+
+
+// Mac OS-X and Linux automatically load the correct drivers. On
+// Windows, even though the driver is supplied by Microsoft, an
+// INF file is needed to load the driver. These numbers need to
+// match the INF file.
+#ifndef VENDOR_ID
+# define VENDOR_ID 0xFEED
+#endif
+
+#ifndef PRODUCT_ID
+# define PRODUCT_ID 0xBABE
+#endif
+
+#ifndef DEVICE_VER
+# define DEVICE_VER 0x0100
+#endif
+
+
+// USB devices are supposed to implment a halt feature, which is
+// rarely (if ever) used. If you comment this line out, the halt
+// code will be removed, saving 102 bytes of space (gcc 4.3.0).
+// This is not strictly USB compliant, but works with all major
+// operating systems.
+#define SUPPORT_ENDPOINT_HALT
+
+
+
+/**************************************************************************
+ *
+ * Endpoint Buffer Configuration
+ *
+ **************************************************************************/
+
+#define ENDPOINT0_SIZE 32
+
+bool remote_wakeup = false;
+bool suspend = false;
+
+// 0:control endpoint is enabled automatically by controller.
+static const uint8_t PROGMEM endpoint_config_table[] = {
+ // enable, UECFG0X(type, direction), UECFG1X(size, bank, allocation)
+ 1, EP_TYPE_INTERRUPT_IN, EP_SIZE(KBD_SIZE) | KBD_BUFFER, // 1
+#ifdef MOUSE_ENABLE
+ 1, EP_TYPE_INTERRUPT_IN, EP_SIZE(MOUSE_SIZE) | MOUSE_BUFFER, // 2
+#else
+ 0, // 2
+#endif
+#ifdef CONSOLE_ENABLE
+ 1, EP_TYPE_INTERRUPT_IN, EP_SIZE(DEBUG_TX_SIZE) | DEBUG_TX_BUFFER, // 3
+#else
+ 0,
+#endif
+#ifdef EXTRAKEY_ENABLE
+ 1, EP_TYPE_INTERRUPT_IN, EP_SIZE(EXTRA_SIZE) | EXTRA_BUFFER, // 4
+#else
+ 0, // 4
+#endif
+#ifdef NKRO_ENABLE
+ 1, EP_TYPE_INTERRUPT_IN, EP_SIZE(KBD2_SIZE) | KBD2_BUFFER, // 5
+#else
+ 0, // 5
+#endif
+ 0, // 6
+};
+
+
+/**************************************************************************
+ *
+ * Descriptor Data
+ *
+ **************************************************************************/
+
+// Descriptors are the data that your computer reads when it auto-detects
+// this USB device (called "enumeration" in USB lingo). The most commonly
+// changed items are editable at the top of this file. Changing things
+// in here should only be done by those who've read chapter 9 of the USB
+// spec and relevant portions of any USB class specifications!
+
+
+static const uint8_t PROGMEM device_descriptor[] = {
+ 18, // bLength
+ 1, // bDescriptorType
+ 0x00, 0x02, // bcdUSB
+ 0, // bDeviceClass
+ 0, // bDeviceSubClass
+ 0, // bDeviceProtocol
+ ENDPOINT0_SIZE, // bMaxPacketSize0
+ LSB(VENDOR_ID), MSB(VENDOR_ID), // idVendor
+ LSB(PRODUCT_ID), MSB(PRODUCT_ID), // idProduct
+ LSB(DEVICE_VER), MSB(DEVICE_VER), // bcdDevice
+ 1, // iManufacturer
+ 2, // iProduct
+ 0, // iSerialNumber
+ 1 // bNumConfigurations
+};
+
+// Keyboard Protocol 1, HID 1.11 spec, Appendix B, page 59-60
+static const uint8_t PROGMEM keyboard_hid_report_desc[] = {
+ 0x05, 0x01, // Usage Page (Generic Desktop),
+ 0x09, 0x06, // Usage (Keyboard),
+ 0xA1, 0x01, // Collection (Application),
+ 0x75, 0x01, // Report Size (1),
+ 0x95, 0x08, // Report Count (8),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0xE0, // Usage Minimum (224),
+ 0x29, 0xE7, // Usage Maximum (231),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x01, // Logical Maximum (1),
+ 0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte
+ 0x95, 0x01, // Report Count (1),
+ 0x75, 0x08, // Report Size (8),
+ 0x81, 0x03, // Input (Constant), ;Reserved byte
+ 0x95, 0x05, // Report Count (5),
+ 0x75, 0x01, // Report Size (1),
+ 0x05, 0x08, // Usage Page (LEDs),
+ 0x19, 0x01, // Usage Minimum (1),
+ 0x29, 0x05, // Usage Maximum (5),
+ 0x91, 0x02, // Output (Data, Variable, Absolute), ;LED report
+ 0x95, 0x01, // Report Count (1),
+ 0x75, 0x03, // Report Size (3),
+ 0x91, 0x03, // Output (Constant), ;LED report padding
+ 0x95, KBD_REPORT_KEYS, // Report Count (),
+ 0x75, 0x08, // Report Size (8),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0xFF, // Logical Maximum(255),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0x00, // Usage Minimum (0),
+ 0x29, 0xFF, // Usage Maximum (255),
+ 0x81, 0x00, // Input (Data, Array),
+ 0xc0 // End Collection
+};
+#ifdef NKRO_ENABLE
+static const uint8_t PROGMEM keyboard2_hid_report_desc[] = {
+ 0x05, 0x01, // Usage Page (Generic Desktop),
+ 0x09, 0x06, // Usage (Keyboard),
+ 0xA1, 0x01, // Collection (Application),
+ // bitmap of modifiers
+ 0x75, 0x01, // Report Size (1),
+ 0x95, 0x08, // Report Count (8),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0xE0, // Usage Minimum (224),
+ 0x29, 0xE7, // Usage Maximum (231),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x01, // Logical Maximum (1),
+ 0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte
+ // LED output report
+ 0x95, 0x05, // Report Count (5),
+ 0x75, 0x01, // Report Size (1),
+ 0x05, 0x08, // Usage Page (LEDs),
+ 0x19, 0x01, // Usage Minimum (1),
+ 0x29, 0x05, // Usage Maximum (5),
+ 0x91, 0x02, // Output (Data, Variable, Absolute),
+ 0x95, 0x01, // Report Count (1),
+ 0x75, 0x03, // Report Size (3),
+ 0x91, 0x03, // Output (Constant),
+ // bitmap of keys
+ 0x95, KBD2_REPORT_KEYS*8, // Report Count (),
+ 0x75, 0x01, // Report Size (1),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x01, // Logical Maximum(1),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0x00, // Usage Minimum (0),
+ 0x29, KBD2_REPORT_KEYS*8-1, // Usage Maximum (),
+ 0x81, 0x02, // Input (Data, Variable, Absolute),
+ 0xc0 // End Collection
+};
+#endif
+
+#ifdef MOUSE_ENABLE
+// Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension
+// http://www.microchip.com/forums/tm.aspx?high=&m=391435&mpage=1#391521
+// http://www.keil.com/forum/15671/
+// http://www.microsoft.com/whdc/device/input/wheel.mspx
+static const uint8_t PROGMEM mouse_hid_report_desc[] = {
+ /* mouse */
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x02, // USAGE (Mouse)
+ 0xa1, 0x01, // COLLECTION (Application)
+ //0x85, REPORT_ID_MOUSE, // REPORT_ID (1)
+ 0x09, 0x01, // USAGE (Pointer)
+ 0xa1, 0x00, // COLLECTION (Physical)
+ // ---------------------------- Buttons
+ 0x05, 0x09, // USAGE_PAGE (Button)
+ 0x19, 0x01, // USAGE_MINIMUM (Button 1)
+ 0x29, 0x05, // USAGE_MAXIMUM (Button 5)
+ 0x15, 0x00, // LOGICAL_MINIMUM (0)
+ 0x25, 0x01, // LOGICAL_MAXIMUM (1)
+ 0x75, 0x01, // REPORT_SIZE (1)
+ 0x95, 0x05, // REPORT_COUNT (5)
+ 0x81, 0x02, // INPUT (Data,Var,Abs)
+ 0x75, 0x03, // REPORT_SIZE (3)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x03, // INPUT (Cnst,Var,Abs)
+ // ---------------------------- X,Y position
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x30, // USAGE (X)
+ 0x09, 0x31, // USAGE (Y)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x02, // REPORT_COUNT (2)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ // ---------------------------- Vertical wheel
+ 0x09, 0x38, // USAGE (Wheel)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x35, 0x00, // PHYSICAL_MINIMUM (0) - reset physical
+ 0x45, 0x00, // PHYSICAL_MAXIMUM (0)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ // ---------------------------- Horizontal wheel
+ 0x05, 0x0c, // USAGE_PAGE (Consumer Devices)
+ 0x0a, 0x38, 0x02, // USAGE (AC Pan)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ 0xc0, // END_COLLECTION
+ 0xc0, // END_COLLECTION
+};
+#endif
+
+static const uint8_t PROGMEM debug_hid_report_desc[] = {
+ 0x06, 0x31, 0xFF, // Usage Page 0xFF31 (vendor defined)
+ 0x09, 0x74, // Usage 0x74
+ 0xA1, 0x53, // Collection 0x53
+ 0x75, 0x08, // report size = 8 bits
+ 0x15, 0x00, // logical minimum = 0
+ 0x26, 0xFF, 0x00, // logical maximum = 255
+ 0x95, DEBUG_TX_SIZE, // report count
+ 0x09, 0x75, // usage
+ 0x81, 0x02, // Input (array)
+ 0xC0 // end collection
+};
+
+#ifdef EXTRAKEY_ENABLE
+// audio controls & system controls
+// http://www.microsoft.com/whdc/archive/w2kbd.mspx
+static const uint8_t PROGMEM extra_hid_report_desc[] = {
+ /* system control */
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x80, // USAGE (System Control)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x85, REPORT_ID_SYSTEM, // REPORT_ID (2)
+ 0x15, 0x01, // LOGICAL_MINIMUM (0x1)
+ 0x25, 0xb7, // LOGICAL_MAXIMUM (0xb7)
+ 0x19, 0x01, // USAGE_MINIMUM (0x1)
+ 0x29, 0xb7, // USAGE_MAXIMUM (0xb7)
+ 0x75, 0x10, // REPORT_SIZE (16)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x00, // INPUT (Data,Array,Abs)
+ 0xc0, // END_COLLECTION
+ /* consumer */
+ 0x05, 0x0c, // USAGE_PAGE (Consumer Devices)
+ 0x09, 0x01, // USAGE (Consumer Control)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x85, REPORT_ID_CONSUMER, // REPORT_ID (3)
+ 0x15, 0x01, // LOGICAL_MINIMUM (0x1)
+ 0x26, 0x9c, 0x02, // LOGICAL_MAXIMUM (0x29c)
+ 0x19, 0x01, // USAGE_MINIMUM (0x1)
+ 0x2a, 0x9c, 0x02, // USAGE_MAXIMUM (0x29c)
+ 0x75, 0x10, // REPORT_SIZE (16)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x00, // INPUT (Data,Array,Abs)
+ 0xc0, // END_COLLECTION
+};
+#endif
+
+#define KBD_HID_DESC_NUM 0
+#define KBD_HID_DESC_OFFSET (9+(9+9+7)*KBD_HID_DESC_NUM+9)
+
+#ifdef MOUSE_ENABLE
+# define MOUSE_HID_DESC_NUM (KBD_HID_DESC_NUM + 1)
+# define MOUSE_HID_DESC_OFFSET (9+(9+9+7)*MOUSE_HID_DESC_NUM+9)
+#else
+# define MOUSE_HID_DESC_NUM (KBD_HID_DESC_NUM + 0)
+#endif
+
+#ifdef CONSOLE_ENABLE
+#define DEBUG_HID_DESC_NUM (MOUSE_HID_DESC_NUM + 1)
+#define DEBUG_HID_DESC_OFFSET (9+(9+9+7)*DEBUG_HID_DESC_NUM+9)
+#else
+# define DEBUG_HID_DESC_NUM (MOUSE_HID_DESC_NUM + 0)
+#endif
+
+#ifdef EXTRAKEY_ENABLE
+# define EXTRA_HID_DESC_NUM (DEBUG_HID_DESC_NUM + 1)
+# define EXTRA_HID_DESC_OFFSET (9+(9+9+7)*EXTRA_HID_DESC_NUM+9)
+#else
+# define EXTRA_HID_DESC_NUM (DEBUG_HID_DESC_NUM + 0)
+#endif
+
+#ifdef NKRO_ENABLE
+# define KBD2_HID_DESC_NUM (EXTRA_HID_DESC_NUM + 1)
+# define KBD2_HID_DESC_OFFSET (9+(9+9+7)*EXTRA_HID_DESC_NUM+9)
+#else
+# define KBD2_HID_DESC_NUM (EXTRA_HID_DESC_NUM + 0)
+#endif
+
+#define NUM_INTERFACES (KBD2_HID_DESC_NUM + 1)
+#define CONFIG1_DESC_SIZE (9+(9+9+7)*NUM_INTERFACES)
+static const uint8_t PROGMEM config1_descriptor[CONFIG1_DESC_SIZE] = {
+ // configuration descriptor, USB spec 9.6.3, page 264-266, Table 9-10
+ 9, // bLength;
+ 2, // bDescriptorType;
+ LSB(CONFIG1_DESC_SIZE), // wTotalLength
+ MSB(CONFIG1_DESC_SIZE),
+ NUM_INTERFACES, // bNumInterfaces
+ 1, // bConfigurationValue
+ 0, // iConfiguration
+ 0xA0, // bmAttributes
+ 50, // bMaxPower
+
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ KBD_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x01, // bInterfaceSubClass (0x01 = Boot)
+ 0x01, // bInterfaceProtocol (0x01 = Keyboard)
+ 0, // iInterface
+ // HID descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ sizeof(keyboard_hid_report_desc), // wDescriptorLength
+ 0,
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ KBD_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ KBD_SIZE, 0, // wMaxPacketSize
+ 10, // bInterval
+
+#ifdef MOUSE_ENABLE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ MOUSE_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ // ThinkPad T23 BIOS doesn't work with boot mouse.
+ 0x00, // bInterfaceSubClass (0x01 = Boot)
+ 0x00, // bInterfaceProtocol (0x02 = Mouse)
+/*
+ 0x01, // bInterfaceSubClass (0x01 = Boot)
+ 0x02, // bInterfaceProtocol (0x02 = Mouse)
+*/
+ 0, // iInterface
+ // HID descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ sizeof(mouse_hid_report_desc), // wDescriptorLength
+ 0,
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ MOUSE_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ MOUSE_SIZE, 0, // wMaxPacketSize
+ 1, // bInterval
+#endif
+
+#ifdef CONSOLE_ENABLE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ DEBUG_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x00, // bInterfaceSubClass
+ 0x00, // bInterfaceProtocol
+ 0, // iInterface
+ // HID descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ sizeof(debug_hid_report_desc), // wDescriptorLength
+ 0,
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ DEBUG_TX_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ DEBUG_TX_SIZE, 0, // wMaxPacketSize
+ 1, // bInterval
+#endif
+
+#ifdef EXTRAKEY_ENABLE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ EXTRA_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x00, // bInterfaceSubClass
+ 0x00, // bInterfaceProtocol
+ 0, // iInterface
+ // HID descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ sizeof(extra_hid_report_desc), // wDescriptorLength
+ 0,
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ EXTRA_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ EXTRA_SIZE, 0, // wMaxPacketSize
+ 10, // bInterval
+#endif
+
+#ifdef NKRO_ENABLE
+ // interface descriptor, USB spec 9.6.5, page 267-269, Table 9-12
+ 9, // bLength
+ 4, // bDescriptorType
+ KBD2_INTERFACE, // bInterfaceNumber
+ 0, // bAlternateSetting
+ 1, // bNumEndpoints
+ 0x03, // bInterfaceClass (0x03 = HID)
+ 0x00, // bInterfaceSubClass (0x01 = Boot)
+ 0x00, // bInterfaceProtocol (0x01 = Keyboard)
+ 0, // iInterface
+ // HID descriptor, HID 1.11 spec, section 6.2.1
+ 9, // bLength
+ 0x21, // bDescriptorType
+ 0x11, 0x01, // bcdHID
+ 0, // bCountryCode
+ 1, // bNumDescriptors
+ 0x22, // bDescriptorType
+ sizeof(keyboard2_hid_report_desc), // wDescriptorLength
+ 0,
+ // endpoint descriptor, USB spec 9.6.6, page 269-271, Table 9-13
+ 7, // bLength
+ 5, // bDescriptorType
+ KBD2_ENDPOINT | 0x80, // bEndpointAddress
+ 0x03, // bmAttributes (0x03=intr)
+ KBD2_SIZE, 0, // wMaxPacketSize
+ 1, // bInterval
+#endif
+};
+
+// If you're desperate for a little extra code memory, these strings
+// can be completely removed if iManufacturer, iProduct, iSerialNumber
+// in the device desciptor are changed to zeros.
+struct usb_string_descriptor_struct {
+ uint8_t bLength;
+ uint8_t bDescriptorType;
+ int16_t wString[];
+};
+static const struct usb_string_descriptor_struct PROGMEM string0 = {
+ 4,
+ 3,
+ {0x0409}
+};
+static const struct usb_string_descriptor_struct PROGMEM string1 = {
+ sizeof(STR_MANUFACTURER),
+ 3,
+ STR_MANUFACTURER
+};
+static const struct usb_string_descriptor_struct PROGMEM string2 = {
+ sizeof(STR_PRODUCT),
+ 3,
+ STR_PRODUCT
+};
+
+// This table defines which descriptor data is sent for each specific
+// request from the host (in wValue and wIndex).
+static const struct descriptor_list_struct {
+ uint16_t wValue; // descriptor type
+ uint16_t wIndex;
+ const uint8_t *addr;
+ uint8_t length;
+} PROGMEM descriptor_list[] = {
+ // DEVICE descriptor
+ {0x0100, 0x0000, device_descriptor, sizeof(device_descriptor)},
+ // CONFIGURATION descriptor
+ {0x0200, 0x0000, config1_descriptor, sizeof(config1_descriptor)},
+ // HID/REPORT descriptors
+ {0x2100, KBD_INTERFACE, config1_descriptor+KBD_HID_DESC_OFFSET, 9},
+ {0x2200, KBD_INTERFACE, keyboard_hid_report_desc, sizeof(keyboard_hid_report_desc)},
+#ifdef MOUSE_ENABLE
+ {0x2100, MOUSE_INTERFACE, config1_descriptor+MOUSE_HID_DESC_OFFSET, 9},
+ {0x2200, MOUSE_INTERFACE, mouse_hid_report_desc, sizeof(mouse_hid_report_desc)},
+#endif
+#ifdef CONSOLE_ENABLE
+ {0x2100, DEBUG_INTERFACE, config1_descriptor+DEBUG_HID_DESC_OFFSET, 9},
+ {0x2200, DEBUG_INTERFACE, debug_hid_report_desc, sizeof(debug_hid_report_desc)},
+#endif
+#ifdef EXTRAKEY_ENABLE
+ {0x2100, EXTRA_INTERFACE, config1_descriptor+EXTRA_HID_DESC_OFFSET, 9},
+ {0x2200, EXTRA_INTERFACE, extra_hid_report_desc, sizeof(extra_hid_report_desc)},
+#endif
+#ifdef NKRO_ENABLE
+ {0x2100, KBD2_INTERFACE, config1_descriptor+KBD2_HID_DESC_OFFSET, 9},
+ {0x2200, KBD2_INTERFACE, keyboard2_hid_report_desc, sizeof(keyboard2_hid_report_desc)},
+#endif
+ // STRING descriptors
+ {0x0300, 0x0000, (const uint8_t *)&string0, 4},
+ {0x0301, 0x0409, (const uint8_t *)&string1, sizeof(STR_MANUFACTURER)},
+ {0x0302, 0x0409, (const uint8_t *)&string2, sizeof(STR_PRODUCT)}
+};
+#define NUM_DESC_LIST (sizeof(descriptor_list)/sizeof(struct descriptor_list_struct))
+
+
+/**************************************************************************
+ *
+ * Variables - these are the only non-stack RAM usage
+ *
+ **************************************************************************/
+
+// zero when we are not configured, non-zero when enumerated
+static volatile uint8_t usb_configuration=0;
+
+
+/**************************************************************************
+ *
+ * Public Functions - these are the API intended for the user
+ *
+ **************************************************************************/
+
+
+// initialize USB
+void usb_init(void)
+{
+ HW_CONFIG();
+ USB_FREEZE(); // enable USB
+ PLL_CONFIG(); // config PLL
+ while (!(PLLCSR & (1<<PLOCK))) ; // wait for PLL lock
+ USB_CONFIG(); // start USB clock
+ UDCON = 0; // enable attach resistor
+ usb_configuration = 0;
+ suspend = false;
+ UDIEN = (1<<EORSTE)|(1<<SOFE)|(1<<SUSPE)|(1<<WAKEUPE);
+ sei();
+}
+
+// return 0 if the USB is not configured, or the configuration
+// number selected by the HOST
+uint8_t usb_configured(void)
+{
+ return usb_configuration && !suspend;
+}
+
+void usb_remote_wakeup(void)
+{
+ UDCON |= (1<<RMWKUP);
+ while (UDCON & (1<<RMWKUP));
+}
+
+
+
+/**************************************************************************
+ *
+ * Private Functions - not intended for general user consumption....
+ *
+ **************************************************************************/
+
+
+
+// USB Device Interrupt - handle all device-level events
+// the transmit buffer flushing is triggered by the start of frame
+//
+ISR(USB_GEN_vect)
+{
+ uint8_t intbits, t;
+ static uint8_t div4=0;
+
+ intbits = UDINT;
+ UDINT = 0;
+ if ((intbits & (1<<SUSPI)) && (UDIEN & (1<<SUSPE)) && usb_configuration) {
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_enable();
+#endif
+ UDIEN &= ~(1<<SUSPE);
+ UDIEN |= (1<<WAKEUPE);
+ suspend = true;
+ }
+ if ((intbits & (1<<WAKEUPI)) && (UDIEN & (1<<WAKEUPE)) && usb_configuration) {
+ suspend_wakeup_init();
+#ifdef SLEEP_LED_ENABLE
+ sleep_led_disable();
+ // NOTE: converters may not accept this
+ led_set(host_keyboard_leds());
+#endif
+
+ UDIEN |= (1<<SUSPE);
+ UDIEN &= ~(1<<WAKEUPE);
+ suspend = false;
+ }
+ if (intbits & (1<<EORSTI)) {
+ UENUM = 0;
+ UECONX = 1;
+ UECFG0X = EP_TYPE_CONTROL;
+ UECFG1X = EP_SIZE(ENDPOINT0_SIZE) | EP_SINGLE_BUFFER;
+ UEIENX = (1<<RXSTPE);
+ usb_configuration = 0;
+ }
+ if ((intbits & (1<<SOFI)) && usb_configuration) {
+ t = debug_flush_timer;
+ if (t) {
+ debug_flush_timer = -- t;
+ if (!t) {
+ UENUM = DEBUG_TX_ENDPOINT;
+ while ((UEINTX & (1<<RWAL))) {
+ UEDATX = 0;
+ }
+ UEINTX = 0x3A;
+ }
+ }
+ /* TODO: should keep IDLE rate on each keyboard interface */
+#ifdef NKRO_ENABLE
+ if (!keymap_config.nkro && keyboard_idle && (++div4 & 3) == 0) {
+#else
+ if (keyboard_idle && (++div4 & 3) == 0) {
+#endif
+ UENUM = KBD_ENDPOINT;
+ if (UEINTX & (1<<RWAL)) {
+ usb_keyboard_idle_count++;
+ if (usb_keyboard_idle_count == keyboard_idle) {
+ usb_keyboard_idle_count = 0;
+ /* TODO: fix keyboard_report inconsistency */
+/* To avoid Mac SET_IDLE behaviour.
+ UEDATX = keyboard_report_prev->mods;
+ UEDATX = 0;
+ uint8_t keys = keyboard_protocol ? KBD_REPORT_KEYS : 6;
+ for (uint8_t i=0; i<keys; i++) {
+ UEDATX = keyboard_report_prev->keys[i];
+ }
+ UEINTX = 0x3A;
+*/
+ }
+ }
+ }
+ }
+}
+
+
+
+// Misc functions to wait for ready and send/receive packets
+static inline void usb_wait_in_ready(void)
+{
+ while (!(UEINTX & (1<<TXINI))) ;
+}
+static inline void usb_send_in(void)
+{
+ UEINTX = ~(1<<TXINI);
+}
+static inline void usb_wait_receive_out(void)
+{
+ while (!(UEINTX & (1<<RXOUTI))) ;
+}
+static inline void usb_ack_out(void)
+{
+ UEINTX = ~(1<<RXOUTI);
+}
+
+
+
+// USB Endpoint Interrupt - endpoint 0 is handled here. The
+// other endpoints are manipulated by the user-callable
+// functions, and the start-of-frame interrupt.
+//
+ISR(USB_COM_vect)
+{
+ uint8_t intbits;
+ const uint8_t *list;
+ const uint8_t *cfg;
+ uint8_t i, n, len, en;
+ uint8_t bmRequestType;
+ uint8_t bRequest;
+ uint16_t wValue;
+ uint16_t wIndex;
+ uint16_t wLength;
+ uint16_t desc_val;
+ const uint8_t *desc_addr;
+ uint8_t desc_length;
+
+ UENUM = 0;
+ intbits = UEINTX;
+ if (intbits & (1<<RXSTPI)) {
+ bmRequestType = UEDATX;
+ bRequest = UEDATX;
+ wValue = UEDATX;
+ wValue |= (UEDATX << 8);
+ wIndex = UEDATX;
+ wIndex |= (UEDATX << 8);
+ wLength = UEDATX;
+ wLength |= (UEDATX << 8);
+ UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
+ if (bRequest == GET_DESCRIPTOR) {
+ list = (const uint8_t *)descriptor_list;
+ for (i=0; ; i++) {
+ if (i >= NUM_DESC_LIST) {
+ UECONX = (1<<STALLRQ)|(1<<EPEN); //stall
+ return;
+ }
+ desc_val = pgm_read_word(list);
+ if (desc_val != wValue) {
+ list += sizeof(struct descriptor_list_struct);
+ continue;
+ }
+ list += 2;
+ desc_val = pgm_read_word(list);
+ if (desc_val != wIndex) {
+ list += sizeof(struct descriptor_list_struct)-2;
+ continue;
+ }
+ list += 2;
+ desc_addr = (const uint8_t *)pgm_read_word(list);
+ list += 2;
+ desc_length = pgm_read_byte(list);
+ break;
+ }
+ len = (wLength < 256) ? wLength : 255;
+ if (len > desc_length) len = desc_length;
+ do {
+ // wait for host ready for IN packet
+ do {
+ i = UEINTX;
+ } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
+ if (i & (1<<RXOUTI)) return; // abort
+ // send IN packet
+ n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
+ for (i = n; i; i--) {
+ UEDATX = pgm_read_byte(desc_addr++);
+ }
+ len -= n;
+ usb_send_in();
+ } while (len || n == ENDPOINT0_SIZE);
+ return;
+ }
+ if (bRequest == SET_ADDRESS) {
+ usb_send_in();
+ usb_wait_in_ready();
+ UDADDR = wValue | (1<<ADDEN);
+ return;
+ }
+ if (bRequest == SET_CONFIGURATION && bmRequestType == 0) {
+ usb_configuration = wValue;
+ usb_send_in();
+ cfg = endpoint_config_table;
+ for (i=1; i<=MAX_ENDPOINT; i++) {
+ UENUM = i;
+ en = pgm_read_byte(cfg++);
+ if (en) {
+ UECONX = (1<<EPEN);
+ UECFG0X = pgm_read_byte(cfg++);
+ UECFG1X = pgm_read_byte(cfg++);
+ } else {
+ UECONX = 0;
+ }
+ }
+ UERST = UERST_MASK;
+ UERST = 0;
+ return;
+ }
+ if (bRequest == GET_CONFIGURATION && bmRequestType == 0x80) {
+ usb_wait_in_ready();
+ UEDATX = usb_configuration;
+ usb_send_in();
+ return;
+ }
+
+ if (bRequest == GET_STATUS) {
+ usb_wait_in_ready();
+ i = 0;
+ #ifdef SUPPORT_ENDPOINT_HALT
+ if (bmRequestType == 0x82) {
+ UENUM = wIndex;
+ if (UECONX & (1<<STALLRQ)) i = 1;
+ UENUM = 0;
+ }
+ #endif
+ UEDATX = i;
+ UEDATX = 0;
+ usb_send_in();
+ return;
+ }
+ if (bRequest == CLEAR_FEATURE || bRequest == SET_FEATURE) {
+#ifdef SUPPORT_ENDPOINT_HALT
+ if (bmRequestType == 0x02 && wValue == ENDPOINT_HALT) {
+ i = wIndex & 0x7F;
+ if (i >= 1 && i <= MAX_ENDPOINT) {
+ usb_send_in();
+ UENUM = i;
+ if (bRequest == SET_FEATURE) {
+ UECONX = (1<<STALLRQ)|(1<<EPEN);
+ } else {
+ UECONX = (1<<STALLRQC)|(1<<RSTDT)|(1<<EPEN);
+ UERST = (1 << i);
+ UERST = 0;
+ }
+ return;
+ }
+ }
+#endif
+ if (bmRequestType == 0x00 && wValue == DEVICE_REMOTE_WAKEUP) {
+ if (bRequest == SET_FEATURE) {
+ remote_wakeup = true;
+ } else {
+ remote_wakeup = false;
+ }
+ usb_send_in();
+ return;
+ }
+ }
+ if (wIndex == KBD_INTERFACE) {
+ if (bmRequestType == 0xA1) {
+ if (bRequest == HID_GET_REPORT) {
+ usb_wait_in_ready();
+ UEDATX = keyboard_report->mods;
+ UEDATX = 0;
+ for (i=0; i<6; i++) {
+ UEDATX = keyboard_report->keys[i];
+ }
+ usb_send_in();
+ return;
+ }
+ if (bRequest == HID_GET_IDLE) {
+ usb_wait_in_ready();
+ UEDATX = keyboard_idle;
+ usb_send_in();
+ return;
+ }
+ if (bRequest == HID_GET_PROTOCOL) {
+ usb_wait_in_ready();
+ UEDATX = keyboard_protocol;
+ usb_send_in();
+ return;
+ }
+ }
+ if (bmRequestType == 0x21) {
+ if (bRequest == HID_SET_REPORT) {
+ usb_wait_receive_out();
+ usb_keyboard_leds = UEDATX;
+ usb_ack_out();
+ usb_send_in();
+ return;
+ }
+ if (bRequest == HID_SET_IDLE) {
+ keyboard_idle = (wValue >> 8);
+ usb_keyboard_idle_count = 0;
+ //usb_wait_in_ready();
+ usb_send_in();
+ return;
+ }
+ if (bRequest == HID_SET_PROTOCOL) {
+ keyboard_protocol = wValue;
+#ifdef NKRO_ENABLE
+ keymap_config.nkro = !!keyboard_protocol;
+#endif
+ clear_keyboard();
+ //usb_wait_in_ready();
+ usb_send_in();
+ return;
+ }
+ }
+ }
+#ifdef MOUSE_ENABLE
+ if (wIndex == MOUSE_INTERFACE) {
+ if (bmRequestType == 0xA1) {
+ if (bRequest == HID_GET_REPORT) {
+ if (wValue == HID_REPORT_INPUT) {
+ usb_wait_in_ready();
+ UEDATX = 0;
+ UEDATX = 0;
+ UEDATX = 0;
+ UEDATX = 0;
+ usb_send_in();
+ return;
+ }
+ if (wValue == HID_REPORT_FEATURE) {
+ usb_wait_in_ready();
+ UEDATX = 0x05;
+ usb_send_in();
+ return;
+ }
+ }
+ if (bRequest == HID_GET_PROTOCOL) {
+ usb_wait_in_ready();
+ UEDATX = usb_mouse_protocol;
+ usb_send_in();
+ return;
+ }
+ }
+ if (bmRequestType == 0x21) {
+ if (bRequest == HID_SET_PROTOCOL) {
+ usb_mouse_protocol = wValue;
+ usb_send_in();
+ return;
+ }
+ }
+ }
+#endif
+ if (wIndex == DEBUG_INTERFACE) {
+ if (bRequest == HID_GET_REPORT && bmRequestType == 0xA1) {
+ len = wLength;
+ do {
+ // wait for host ready for IN packet
+ do {
+ i = UEINTX;
+ } while (!(i & ((1<<TXINI)|(1<<RXOUTI))));
+ if (i & (1<<RXOUTI)) return; // abort
+ // send IN packet
+ n = len < ENDPOINT0_SIZE ? len : ENDPOINT0_SIZE;
+ for (i = n; i; i--) {
+ UEDATX = 0;
+ }
+ len -= n;
+ usb_send_in();
+ } while (len || n == ENDPOINT0_SIZE);
+ return;
+ }
+ }
+ }
+ UECONX = (1<<STALLRQ) | (1<<EPEN); // stall
+}
diff --git a/tmk_core/protocol/pjrc/usb.h b/tmk_core/protocol/pjrc/usb.h
new file mode 100644
index 000000000..a195b671d
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb.h
@@ -0,0 +1,137 @@
+/* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef USB_H
+#define USB_H 1
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <avr/io.h>
+
+
+extern bool remote_wakeup;
+extern bool suspend;
+
+void usb_init(void); // initialize everything
+uint8_t usb_configured(void); // is the USB port configured
+void usb_remote_wakeup(void);
+
+
+#define EP_TYPE_CONTROL 0x00
+#define EP_TYPE_BULK_IN 0x81
+#define EP_TYPE_BULK_OUT 0x80
+#define EP_TYPE_INTERRUPT_IN 0xC1
+#define EP_TYPE_INTERRUPT_OUT 0xC0
+#define EP_TYPE_ISOCHRONOUS_IN 0x41
+#define EP_TYPE_ISOCHRONOUS_OUT 0x40
+
+#define EP_SINGLE_BUFFER 0x02
+#define EP_DOUBLE_BUFFER 0x06
+
+#define EP_SIZE(s) ((s) == 64 ? 0x30 : \
+ ((s) == 32 ? 0x20 : \
+ ((s) == 16 ? 0x10 : \
+ 0x00)))
+
+#if defined (__AVR_AT90USB162__) || defined (__AVR_AT90USB82__)
+# define MAX_ENDPOINT 4
+# define UERST_MASK 0x1E
+#else
+# define MAX_ENDPOINT 6
+# define UERST_MASK 0x7E
+#endif
+
+#define LSB(n) (n & 255)
+#define MSB(n) ((n >> 8) & 255)
+
+#if defined(__AVR_AT90USB162__)
+#define HW_CONFIG()
+#define PLL_CONFIG() (PLLCSR = ((1<<PLLE)|(1<<PLLP0)))
+#define USB_CONFIG() (USBCON = (1<<USBE))
+#define USB_FREEZE() (USBCON = ((1<<USBE)|(1<<FRZCLK)))
+#elif defined(__AVR_ATmega32U4__)
+#define HW_CONFIG() (UHWCON = 0x01)
+#define PLL_CONFIG() (PLLCSR = 0x12)
+#define USB_CONFIG() (USBCON = ((1<<USBE)|(1<<OTGPADE)))
+#define USB_FREEZE() (USBCON = ((1<<USBE)|(1<<FRZCLK)))
+#elif defined(__AVR_AT90USB646__)
+#define HW_CONFIG() (UHWCON = 0x81)
+#define PLL_CONFIG() (PLLCSR = 0x1A)
+#define USB_CONFIG() (USBCON = ((1<<USBE)|(1<<OTGPADE)))
+#define USB_FREEZE() (USBCON = ((1<<USBE)|(1<<FRZCLK)))
+#elif defined(__AVR_AT90USB1286__)
+#define HW_CONFIG() (UHWCON = 0x81)
+#define PLL_CONFIG() (PLLCSR = 0x16)
+#define USB_CONFIG() (USBCON = ((1<<USBE)|(1<<OTGPADE)))
+#define USB_FREEZE() (USBCON = ((1<<USBE)|(1<<FRZCLK)))
+#endif
+
+// standard control endpoint request types
+#define GET_STATUS 0
+#define CLEAR_FEATURE 1
+#define SET_FEATURE 3
+#define SET_ADDRESS 5
+#define GET_DESCRIPTOR 6
+#define GET_CONFIGURATION 8
+#define SET_CONFIGURATION 9
+#define GET_INTERFACE 10
+#define SET_INTERFACE 11
+// HID (human interface device)
+#define HID_GET_REPORT 1
+#define HID_GET_IDLE 2
+#define HID_GET_PROTOCOL 3
+#define HID_SET_REPORT 9
+#define HID_SET_IDLE 10
+#define HID_SET_PROTOCOL 11
+#define HID_REPORT_INPUT 1
+#define HID_REPORT_OUTPUT 2
+#define HID_REPORT_FEATURE 3
+// CDC (communication class device)
+#define CDC_SET_LINE_CODING 0x20
+#define CDC_GET_LINE_CODING 0x21
+#define CDC_SET_CONTROL_LINE_STATE 0x22
+// HID feature selectors
+#define DEVICE_REMOTE_WAKEUP 1
+#define ENDPOINT_HALT 0
+#define TEST_MODE 2
+
+
+/*------------------------------------------------------------------*
+ * Keyboard descriptor setting
+ *------------------------------------------------------------------*/
+#define KBD_INTERFACE 0
+#define KBD_ENDPOINT 1
+#define KBD_SIZE 8
+#define KBD_BUFFER EP_SINGLE_BUFFER
+#define KBD_REPORT_KEYS (KBD_SIZE - 2)
+
+// secondary keyboard
+#ifdef NKRO_ENABLE
+#define KBD2_INTERFACE 4
+#define KBD2_ENDPOINT 5
+#define KBD2_SIZE 16
+#define KBD2_BUFFER EP_DOUBLE_BUFFER
+#define KBD2_REPORT_KEYS (KBD2_SIZE - 1)
+#endif
+
+#endif
diff --git a/tmk_core/protocol/pjrc/usb_debug.c b/tmk_core/protocol/pjrc/usb_debug.c
new file mode 100644
index 000000000..c1e6f6544
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb_debug.c
@@ -0,0 +1,102 @@
+/* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <avr/interrupt.h>
+#include "sendchar.h"
+#include "usb_debug.h"
+
+
+// the time remaining before we transmit any partially full
+// packet, or send a zero length packet.
+volatile uint8_t debug_flush_timer=0;
+
+
+int8_t sendchar(uint8_t c)
+{
+ static uint8_t previous_timeout=0;
+ uint8_t timeout, intr_state;
+
+ // if we're not online (enumerated and configured), error
+ if (!usb_configured()) return -1;
+ // interrupts are disabled so these functions can be
+ // used from the main program or interrupt context,
+ // even both in the same program!
+ intr_state = SREG;
+ cli();
+ UENUM = DEBUG_TX_ENDPOINT;
+ // if we gave up due to timeout before, don't wait again
+ if (previous_timeout) {
+ if (!(UEINTX & (1<<RWAL))) {
+ SREG = intr_state;
+ return -1;
+ }
+ previous_timeout = 0;
+ }
+ // wait for the FIFO to be ready to accept data
+ timeout = UDFNUML + 4;
+ while (1) {
+ // are we ready to transmit?
+ if (UEINTX & (1<<RWAL)) break;
+ SREG = intr_state;
+ // have we waited too long?
+ if (UDFNUML == timeout) {
+ previous_timeout = 1;
+ return -1;
+ }
+ // has the USB gone offline?
+ if (!usb_configured()) return -1;
+ // get ready to try checking again
+ intr_state = SREG;
+ cli();
+ UENUM = DEBUG_TX_ENDPOINT;
+ }
+ // actually write the byte into the FIFO
+ UEDATX = c;
+ // if this completed a packet, transmit it now!
+ if (!(UEINTX & (1<<RWAL))) {
+ UEINTX = 0x3A;
+ debug_flush_timer = 0;
+ } else {
+ debug_flush_timer = 2;
+ }
+ SREG = intr_state;
+ return 0;
+}
+
+// immediately transmit any buffered output.
+void usb_debug_flush_output(void)
+{
+ uint8_t intr_state;
+
+ intr_state = SREG;
+ cli();
+ if (debug_flush_timer) {
+ UENUM = DEBUG_TX_ENDPOINT;
+ while ((UEINTX & (1<<RWAL))) {
+ UEDATX = 0;
+ }
+ UEINTX = 0x3A;
+ debug_flush_timer = 0;
+ }
+ SREG = intr_state;
+}
diff --git a/tmk_core/protocol/pjrc/usb_debug.h b/tmk_core/protocol/pjrc/usb_debug.h
new file mode 100644
index 000000000..e70f4ca3a
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb_debug.h
@@ -0,0 +1,42 @@
+/* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef USB_DEBUG_H
+#define USB_DEBUG_H 1
+
+#include <stdint.h>
+#include "usb.h"
+
+
+#define DEBUG_INTERFACE 2
+#define DEBUG_TX_ENDPOINT 3
+#define DEBUG_TX_SIZE 32
+#define DEBUG_TX_BUFFER EP_DOUBLE_BUFFER
+
+
+extern volatile uint8_t debug_flush_timer;
+
+
+void usb_debug_flush_output(void); // immediately transmit any buffered output
+
+#endif
diff --git a/tmk_core/protocol/pjrc/usb_extra.c b/tmk_core/protocol/pjrc/usb_extra.c
new file mode 100644
index 000000000..fe1f422c0
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb_extra.c
@@ -0,0 +1,70 @@
+/* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <util/delay.h>
+#include <avr/interrupt.h>
+#include "host.h"
+#include "usb_extra.h"
+
+
+int8_t usb_extra_send(uint8_t report_id, uint16_t data)
+{
+ uint8_t intr_state, timeout;
+
+ if (!usb_configured()) return -1;
+ intr_state = SREG;
+ cli();
+ UENUM = EXTRA_ENDPOINT;
+ timeout = UDFNUML + 50;
+ while (1) {
+ // are we ready to transmit?
+ if (UEINTX & (1<<RWAL)) break;
+ SREG = intr_state;
+ // has the USB gone offline?
+ if (!usb_configured()) return -1;
+ // have we waited too long?
+ if (UDFNUML == timeout) return -1;
+ // get ready to try checking again
+ intr_state = SREG;
+ cli();
+ UENUM = EXTRA_ENDPOINT;
+ }
+
+ UEDATX = report_id;
+ UEDATX = data&0xFF;
+ UEDATX = (data>>8)&0xFF;
+
+ UEINTX = 0x3A;
+ SREG = intr_state;
+ return 0;
+}
+
+int8_t usb_extra_consumer_send(uint16_t bits)
+{
+ return usb_extra_send(REPORT_ID_CONSUMER, bits);
+}
+
+int8_t usb_extra_system_send(uint16_t bits)
+{
+ return usb_extra_send(REPORT_ID_SYSTEM, bits);
+}
diff --git a/tmk_core/protocol/pjrc/usb_extra.h b/tmk_core/protocol/pjrc/usb_extra.h
new file mode 100644
index 000000000..042ac4837
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb_extra.h
@@ -0,0 +1,46 @@
+/* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef USB_EXTRA_H
+#define USB_EXTRA_H 1
+/*
+ * Enhanced keyboard features for Windows:
+ * Audio control and System control
+ *
+ * http://www.microsoft.com/whdc/archive/w2kbd.mspx
+ */
+
+#include <stdint.h>
+#include "usb.h"
+
+
+#define EXTRA_INTERFACE 3
+#define EXTRA_ENDPOINT 4
+#define EXTRA_SIZE 8
+#define EXTRA_BUFFER EP_DOUBLE_BUFFER
+
+
+int8_t usb_extra_consumer_send(uint16_t bits);
+int8_t usb_extra_system_send(uint16_t bits);
+
+#endif
diff --git a/tmk_core/protocol/pjrc/usb_keyboard.c b/tmk_core/protocol/pjrc/usb_keyboard.c
new file mode 100644
index 000000000..05f479734
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb_keyboard.c
@@ -0,0 +1,116 @@
+/* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <avr/interrupt.h>
+#include <avr/pgmspace.h>
+#include "keycode.h"
+#include "usb_keyboard.h"
+#include "print.h"
+#include "debug.h"
+#include "util.h"
+#include "host.h"
+
+#ifdef NKRO_ENABLE
+ #include "keycode_config.h"
+
+ extern keymap_config_t keymap_config;
+#endif
+
+
+// protocol setting from the host. We use exactly the same report
+// either way, so this variable only stores the setting since we
+// are required to be able to report which setting is in use.
+uint8_t keyboard_protocol=1;
+
+// the idle configuration, how often we send the report to the
+// host (ms * 4) even when it hasn't changed
+// Windows and Linux set 0 while OS X sets 6(24ms) by SET_IDLE request.
+uint8_t keyboard_idle=125;
+
+// count until idle timeout
+uint8_t usb_keyboard_idle_count=0;
+
+// 1=num lock, 2=caps lock, 4=scroll lock, 8=compose, 16=kana
+volatile uint8_t usb_keyboard_leds=0;
+
+
+static inline int8_t send_report(report_keyboard_t *report, uint8_t endpoint, uint8_t keys_start, uint8_t keys_end);
+
+
+int8_t usb_keyboard_send_report(report_keyboard_t *report)
+{
+ int8_t result = 0;
+
+#ifdef NKRO_ENABLE
+ if (keymap_config.nkro)
+ result = send_report(report, KBD2_ENDPOINT, 0, KBD2_SIZE);
+ else
+#endif
+ {
+ result = send_report(report, KBD_ENDPOINT, 0, KBD_SIZE);
+ }
+
+ if (result) return result;
+ usb_keyboard_idle_count = 0;
+ usb_keyboard_print_report(report);
+ return 0;
+}
+
+void usb_keyboard_print_report(report_keyboard_t *report)
+{
+ if (!debug_keyboard) return;
+ print("keys: ");
+ for (int i = 0; i < KEYBOARD_REPORT_KEYS; i++) { phex(report->keys[i]); print(" "); }
+ print(" mods: "); phex(report->mods); print("\n");
+}
+
+
+static inline int8_t send_report(report_keyboard_t *report, uint8_t endpoint, uint8_t keys_start, uint8_t keys_end)
+{
+ uint8_t intr_state, timeout;
+
+ if (!usb_configured()) return -1;
+ intr_state = SREG;
+ cli();
+ UENUM = endpoint;
+ timeout = UDFNUML + 50;
+ while (1) {
+ // are we ready to transmit?
+ if (UEINTX & (1<<RWAL)) break;
+ SREG = intr_state;
+ // has the USB gone offline?
+ if (!usb_configured()) return -1;
+ // have we waited too long?
+ if (UDFNUML == timeout) return -1;
+ // get ready to try checking again
+ intr_state = SREG;
+ cli();
+ UENUM = endpoint;
+ }
+ for (uint8_t i = keys_start; i < keys_end; i++) {
+ UEDATX = report->raw[i];
+ }
+ UEINTX = 0x3A;
+ SREG = intr_state;
+ return 0;
+}
diff --git a/tmk_core/protocol/pjrc/usb_keyboard.h b/tmk_core/protocol/pjrc/usb_keyboard.h
new file mode 100644
index 000000000..9b798e9a8
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb_keyboard.h
@@ -0,0 +1,40 @@
+/* USB Keyboard Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_keyboard.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef USB_KEYBOARD_H
+#define USB_KEYBOARD_H 1
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "usb.h"
+#include "host.h"
+
+
+extern uint8_t usb_keyboard_idle_count;
+extern volatile uint8_t usb_keyboard_leds;
+
+
+int8_t usb_keyboard_send_report(report_keyboard_t *report);
+void usb_keyboard_print_report(report_keyboard_t *report);
+
+#endif
diff --git a/tmk_core/protocol/pjrc/usb_mouse.c b/tmk_core/protocol/pjrc/usb_mouse.c
new file mode 100644
index 000000000..d81db756f
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb_mouse.c
@@ -0,0 +1,81 @@
+/* USB Mouse Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_mouse.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#include <avr/interrupt.h>
+#include <util/delay.h>
+#include "usb_mouse.h"
+#include "print.h"
+#include "debug.h"
+
+
+uint8_t usb_mouse_protocol=1;
+
+
+int8_t usb_mouse_send(int8_t x, int8_t y, int8_t wheel_v, int8_t wheel_h, uint8_t buttons)
+{
+ uint8_t intr_state, timeout;
+
+ if (!usb_configured()) return -1;
+ if (x == -128) x = -127;
+ if (y == -128) y = -127;
+ if (wheel_v == -128) wheel_v = -127;
+ if (wheel_h == -128) wheel_h = -127;
+ intr_state = SREG;
+ cli();
+ UENUM = MOUSE_ENDPOINT;
+ timeout = UDFNUML + 50;
+ while (1) {
+ // are we ready to transmit?
+ if (UEINTX & (1<<RWAL)) break;
+ SREG = intr_state;
+ // has the USB gone offline?
+ if (!usb_configured()) return -1;
+ // have we waited too long?
+ if (UDFNUML == timeout) return -1;
+ // get ready to try checking again
+ intr_state = SREG;
+ cli();
+ UENUM = MOUSE_ENDPOINT;
+ }
+ UEDATX = buttons;
+ UEDATX = x;
+ UEDATX = y;
+ if (usb_mouse_protocol) {
+ UEDATX = wheel_v;
+ UEDATX = wheel_h;
+ }
+
+ UEINTX = 0x3A;
+ SREG = intr_state;
+ return 0;
+}
+
+void usb_mouse_print(int8_t x, int8_t y, int8_t wheel_v, int8_t wheel_h, uint8_t buttons) {
+ if (!debug_mouse) return;
+ print("usb_mouse[btn|x y v h]: ");
+ phex(buttons); print("|");
+ phex(x); print(" ");
+ phex(y); print(" ");
+ phex(wheel_v); print(" ");
+ phex(wheel_h); print("\n");
+}
diff --git a/tmk_core/protocol/pjrc/usb_mouse.h b/tmk_core/protocol/pjrc/usb_mouse.h
new file mode 100644
index 000000000..ce26887c9
--- /dev/null
+++ b/tmk_core/protocol/pjrc/usb_mouse.h
@@ -0,0 +1,50 @@
+/* USB Mouse Plus Debug Channel Example for Teensy USB Development Board
+ * http://www.pjrc.com/teensy/usb_mouse.html
+ * Copyright (c) 2009 PJRC.COM, LLC
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+#ifndef USB_MOUSE_H
+#define USB_MOUSE_H 1
+
+#include <stdint.h>
+#include <stdbool.h>
+#include "usb.h"
+
+
+#define MOUSE_INTERFACE 1
+#define MOUSE_ENDPOINT 2
+#define MOUSE_SIZE 8
+#define MOUSE_BUFFER EP_SINGLE_BUFFER
+
+#define MOUSE_BTN1 (1<<0)
+#define MOUSE_BTN2 (1<<1)
+#define MOUSE_BTN3 (1<<2)
+#define MOUSE_BTN4 (1<<3)
+#define MOUSE_BTN5 (1<<4)
+
+
+extern uint8_t usb_mouse_protocol;
+
+
+int8_t usb_mouse_send(int8_t x, int8_t y, int8_t wheel_v, int8_t wheel_h, uint8_t buttons);
+void usb_mouse_print(int8_t x, int8_t y, int8_t wheel_v, int8_t wheel_h, uint8_t buttons);
+
+#endif
diff --git a/tmk_core/protocol/ps2.h b/tmk_core/protocol/ps2.h
new file mode 100644
index 000000000..acde679cf
--- /dev/null
+++ b/tmk_core/protocol/ps2.h
@@ -0,0 +1,134 @@
+/*
+Copyright 2010,2011,2012,2013 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef PS2_H
+#define PS2_H
+
+#include <stdbool.h>
+#include "wait.h"
+#include "ps2_io.h"
+#include "print.h"
+
+/*
+ * Primitive PS/2 Library for AVR
+ *
+ * PS/2 Resources
+ * --------------
+ * [1] The PS/2 Mouse/Keyboard Protocol
+ * http://www.computer-engineering.org/ps2protocol/
+ * Concise and thorough primer of PS/2 protocol.
+ *
+ * [2] Keyboard and Auxiliary Device Controller
+ * http://www.mcamafia.de/pdf/ibm_hitrc07.pdf
+ * Signal Timing and Format
+ *
+ * [3] Keyboards(101- and 102-key)
+ * http://www.mcamafia.de/pdf/ibm_hitrc11.pdf
+ * Keyboard Layout, Scan Code Set, POR, and Commands.
+ *
+ * [4] PS/2 Reference Manuals
+ * http://www.mcamafia.de/pdf/ibm_hitrc07.pdf
+ * Collection of IBM Personal System/2 documents.
+ *
+ * [5] TrackPoint Engineering Specifications for version 3E
+ * https://web.archive.org/web/20100526161812/http://wwwcssrv.almaden.ibm.com/trackpoint/download.html
+ */
+#define PS2_ACK 0xFA
+#define PS2_RESEND 0xFE
+#define PS2_SET_LED 0xED
+
+// TODO: error numbers
+#define PS2_ERR_NONE 0
+#define PS2_ERR_STARTBIT1 1
+#define PS2_ERR_STARTBIT2 2
+#define PS2_ERR_STARTBIT3 3
+#define PS2_ERR_PARITY 0x10
+#define PS2_ERR_NODATA 0x20
+
+#define PS2_LED_SCROLL_LOCK 0
+#define PS2_LED_NUM_LOCK 1
+#define PS2_LED_CAPS_LOCK 2
+
+
+extern uint8_t ps2_error;
+
+void ps2_host_init(void);
+uint8_t ps2_host_send(uint8_t data);
+uint8_t ps2_host_recv_response(void);
+uint8_t ps2_host_recv(void);
+void ps2_host_set_led(uint8_t usb_led);
+
+
+/*--------------------------------------------------------------------
+ * static functions
+ *------------------------------------------------------------------*/
+static inline uint16_t wait_clock_lo(uint16_t us)
+{
+ while (clock_in() && us) { asm(""); wait_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_clock_hi(uint16_t us)
+{
+ while (!clock_in() && us) { asm(""); wait_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_data_lo(uint16_t us)
+{
+ while (data_in() && us) { asm(""); wait_us(1); us--; }
+ return us;
+}
+static inline uint16_t wait_data_hi(uint16_t us)
+{
+ while (!data_in() && us) { asm(""); wait_us(1); us--; }
+ return us;
+}
+
+/* idle state that device can send */
+static inline void idle(void)
+{
+ clock_hi();
+ data_hi();
+}
+
+/* inhibit device to send */
+static inline void inhibit(void)
+{
+ clock_lo();
+ data_hi();
+}
+
+#endif
diff --git a/tmk_core/protocol/ps2_busywait.c b/tmk_core/protocol/ps2_busywait.c
new file mode 100644
index 000000000..a64933219
--- /dev/null
+++ b/tmk_core/protocol/ps2_busywait.c
@@ -0,0 +1,189 @@
+/*
+Copyright 2010,2011,2012,2013 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * PS/2 protocol busywait version
+ */
+
+#include <stdbool.h>
+#include "wait.h"
+#include "ps2.h"
+#include "ps2_io.h"
+#include "debug.h"
+
+
+#define WAIT(stat, us, err) do { \
+ if (!wait_##stat(us)) { \
+ ps2_error = err; \
+ goto ERROR; \
+ } \
+} while (0)
+
+
+uint8_t ps2_error = PS2_ERR_NONE;
+
+
+void ps2_host_init(void)
+{
+ clock_init();
+ data_init();
+
+ // POR(150-2000ms) plus BAT(300-500ms) may take 2.5sec([3]p.20)
+ wait_ms(2500);
+
+ inhibit();
+}
+
+uint8_t ps2_host_send(uint8_t data)
+{
+ bool parity = true;
+ ps2_error = PS2_ERR_NONE;
+
+ /* terminate a transmission if we have */
+ inhibit();
+ wait_us(100); // 100us [4]p.13, [5]p.50
+
+ /* 'Request to Send' and Start bit */
+ data_lo();
+ clock_hi();
+ WAIT(clock_lo, 10000, 10); // 10ms [5]p.50
+
+ /* Data bit */
+ for (uint8_t i = 0; i < 8; i++) {
+ wait_us(15);
+ if (data&(1<<i)) {
+ parity = !parity;
+ data_hi();
+ } else {
+ data_lo();
+ }
+ WAIT(clock_hi, 50, 2);
+ WAIT(clock_lo, 50, 3);
+ }
+
+ /* Parity bit */
+ wait_us(15);
+ if (parity) { data_hi(); } else { data_lo(); }
+ WAIT(clock_hi, 50, 4);
+ WAIT(clock_lo, 50, 5);
+
+ /* Stop bit */
+ wait_us(15);
+ data_hi();
+
+ /* Ack */
+ WAIT(data_lo, 50, 6);
+ WAIT(clock_lo, 50, 7);
+
+ /* wait for idle state */
+ WAIT(clock_hi, 50, 8);
+ WAIT(data_hi, 50, 9);
+
+ inhibit();
+ return ps2_host_recv_response();
+ERROR:
+ inhibit();
+ return 0;
+}
+
+/* receive data when host want else inhibit communication */
+uint8_t ps2_host_recv_response(void)
+{
+ // Command may take 25ms/20ms at most([5]p.46, [3]p.21)
+ // 250 * 100us(wait for start bit in ps2_host_recv)
+ uint8_t data = 0;
+ uint8_t try = 250;
+ do {
+ data = ps2_host_recv();
+ } while (try-- && ps2_error);
+ return data;
+}
+
+/* called after start bit comes */
+uint8_t ps2_host_recv(void)
+{
+ uint8_t data = 0;
+ bool parity = true;
+ ps2_error = PS2_ERR_NONE;
+
+ /* release lines(idle state) */
+ idle();
+
+ /* start bit [1] */
+ WAIT(clock_lo, 100, 1); // TODO: this is enough?
+ WAIT(data_lo, 1, 2);
+ WAIT(clock_hi, 50, 3);
+
+ /* data [2-9] */
+ for (uint8_t i = 0; i < 8; i++) {
+ WAIT(clock_lo, 50, 4);
+ if (data_in()) {
+ parity = !parity;
+ data |= (1<<i);
+ }
+ WAIT(clock_hi, 50, 5);
+ }
+
+ /* parity [10] */
+ WAIT(clock_lo, 50, 6);
+ if (data_in() != parity) {
+ ps2_error = PS2_ERR_PARITY;
+ goto ERROR;
+ }
+ WAIT(clock_hi, 50, 7);
+
+ /* stop bit [11] */
+ WAIT(clock_lo, 50, 8);
+ WAIT(data_hi, 1, 9);
+ WAIT(clock_hi, 50, 10);
+
+ inhibit();
+ return data;
+ERROR:
+ if (ps2_error > PS2_ERR_STARTBIT3) {
+ xprintf("x%02X\n", ps2_error);
+ }
+ inhibit();
+ return 0;
+}
+
+/* send LED state to keyboard */
+void ps2_host_set_led(uint8_t led)
+{
+ ps2_host_send(0xED);
+ ps2_host_send(led);
+}
diff --git a/tmk_core/protocol/ps2_interrupt.c b/tmk_core/protocol/ps2_interrupt.c
new file mode 100644
index 000000000..8114442ba
--- /dev/null
+++ b/tmk_core/protocol/ps2_interrupt.c
@@ -0,0 +1,279 @@
+/*
+Copyright 2010,2011,2012,2013 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * PS/2 protocol Pin interrupt version
+ */
+
+#include <stdbool.h>
+#include <avr/interrupt.h>
+#include <util/delay.h>
+#include "ps2.h"
+#include "ps2_io.h"
+#include "print.h"
+
+
+#define WAIT(stat, us, err) do { \
+ if (!wait_##stat(us)) { \
+ ps2_error = err; \
+ goto ERROR; \
+ } \
+} while (0)
+
+
+uint8_t ps2_error = PS2_ERR_NONE;
+
+
+static inline uint8_t pbuf_dequeue(void);
+static inline void pbuf_enqueue(uint8_t data);
+static inline bool pbuf_has_data(void);
+static inline void pbuf_clear(void);
+
+
+void ps2_host_init(void)
+{
+ idle();
+ PS2_INT_INIT();
+ PS2_INT_ON();
+ // POR(150-2000ms) plus BAT(300-500ms) may take 2.5sec([3]p.20)
+ //_delay_ms(2500);
+}
+
+uint8_t ps2_host_send(uint8_t data)
+{
+ bool parity = true;
+ ps2_error = PS2_ERR_NONE;
+
+ PS2_INT_OFF();
+
+ /* terminate a transmission if we have */
+ inhibit();
+ _delay_us(100); // 100us [4]p.13, [5]p.50
+
+ /* 'Request to Send' and Start bit */
+ data_lo();
+ clock_hi();
+ WAIT(clock_lo, 10000, 10); // 10ms [5]p.50
+
+ /* Data bit[2-9] */
+ for (uint8_t i = 0; i < 8; i++) {
+ _delay_us(15);
+ if (data&(1<<i)) {
+ parity = !parity;
+ data_hi();
+ } else {
+ data_lo();
+ }
+ WAIT(clock_hi, 50, 2);
+ WAIT(clock_lo, 50, 3);
+ }
+
+ /* Parity bit */
+ _delay_us(15);
+ if (parity) { data_hi(); } else { data_lo(); }
+ WAIT(clock_hi, 50, 4);
+ WAIT(clock_lo, 50, 5);
+
+ /* Stop bit */
+ _delay_us(15);
+ data_hi();
+
+ /* Ack */
+ WAIT(data_lo, 50, 6);
+ WAIT(clock_lo, 50, 7);
+
+ /* wait for idle state */
+ WAIT(clock_hi, 50, 8);
+ WAIT(data_hi, 50, 9);
+
+ idle();
+ PS2_INT_ON();
+ return ps2_host_recv_response();
+ERROR:
+ idle();
+ PS2_INT_ON();
+ return 0;
+}
+
+uint8_t ps2_host_recv_response(void)
+{
+ // Command may take 25ms/20ms at most([5]p.46, [3]p.21)
+ uint8_t retry = 25;
+ while (retry-- && !pbuf_has_data()) {
+ _delay_ms(1);
+ }
+ return pbuf_dequeue();
+}
+
+/* get data received by interrupt */
+uint8_t ps2_host_recv(void)
+{
+ if (pbuf_has_data()) {
+ ps2_error = PS2_ERR_NONE;
+ return pbuf_dequeue();
+ } else {
+ ps2_error = PS2_ERR_NODATA;
+ return 0;
+ }
+}
+
+ISR(PS2_INT_VECT)
+{
+ static enum {
+ INIT,
+ START,
+ BIT0, BIT1, BIT2, BIT3, BIT4, BIT5, BIT6, BIT7,
+ PARITY,
+ STOP,
+ } state = INIT;
+ static uint8_t data = 0;
+ static uint8_t parity = 1;
+
+ // TODO: abort if elapse 100us from previous interrupt
+
+ // return unless falling edge
+ if (clock_in()) {
+ goto RETURN;
+ }
+
+ state++;
+ switch (state) {
+ case START:
+ if (data_in())
+ goto ERROR;
+ break;
+ case BIT0:
+ case BIT1:
+ case BIT2:
+ case BIT3:
+ case BIT4:
+ case BIT5:
+ case BIT6:
+ case BIT7:
+ data >>= 1;
+ if (data_in()) {
+ data |= 0x80;
+ parity++;
+ }
+ break;
+ case PARITY:
+ if (data_in()) {
+ if (!(parity & 0x01))
+ goto ERROR;
+ } else {
+ if (parity & 0x01)
+ goto ERROR;
+ }
+ break;
+ case STOP:
+ if (!data_in())
+ goto ERROR;
+ pbuf_enqueue(data);
+ goto DONE;
+ break;
+ default:
+ goto ERROR;
+ }
+ goto RETURN;
+ERROR:
+ ps2_error = state;
+DONE:
+ state = INIT;
+ data = 0;
+ parity = 1;
+RETURN:
+ return;
+}
+
+/* send LED state to keyboard */
+void ps2_host_set_led(uint8_t led)
+{
+ ps2_host_send(0xED);
+ ps2_host_send(led);
+}
+
+
+/*--------------------------------------------------------------------
+ * Ring buffer to store scan codes from keyboard
+ *------------------------------------------------------------------*/
+#define PBUF_SIZE 32
+static uint8_t pbuf[PBUF_SIZE];
+static uint8_t pbuf_head = 0;
+static uint8_t pbuf_tail = 0;
+static inline void pbuf_enqueue(uint8_t data)
+{
+ uint8_t sreg = SREG;
+ cli();
+ uint8_t next = (pbuf_head + 1) % PBUF_SIZE;
+ if (next != pbuf_tail) {
+ pbuf[pbuf_head] = data;
+ pbuf_head = next;
+ } else {
+ print("pbuf: full\n");
+ }
+ SREG = sreg;
+}
+static inline uint8_t pbuf_dequeue(void)
+{
+ uint8_t val = 0;
+
+ uint8_t sreg = SREG;
+ cli();
+ if (pbuf_head != pbuf_tail) {
+ val = pbuf[pbuf_tail];
+ pbuf_tail = (pbuf_tail + 1) % PBUF_SIZE;
+ }
+ SREG = sreg;
+
+ return val;
+}
+static inline bool pbuf_has_data(void)
+{
+ uint8_t sreg = SREG;
+ cli();
+ bool has_data = (pbuf_head != pbuf_tail);
+ SREG = sreg;
+ return has_data;
+}
+static inline void pbuf_clear(void)
+{
+ uint8_t sreg = SREG;
+ cli();
+ pbuf_head = pbuf_tail = 0;
+ SREG = sreg;
+}
+
diff --git a/tmk_core/protocol/ps2_io.h b/tmk_core/protocol/ps2_io.h
new file mode 100644
index 000000000..a46a358e7
--- /dev/null
+++ b/tmk_core/protocol/ps2_io.h
@@ -0,0 +1,15 @@
+#ifndef PS2_IO_H
+#define PS2_IO_H
+
+
+void clock_init(void);
+void clock_lo(void);
+void clock_hi(void);
+bool clock_in(void);
+
+void data_init(void);
+void data_lo(void);
+void data_hi(void);
+bool data_in(void);
+
+#endif
diff --git a/tmk_core/protocol/ps2_io_avr.c b/tmk_core/protocol/ps2_io_avr.c
new file mode 100644
index 000000000..ed462345b
--- /dev/null
+++ b/tmk_core/protocol/ps2_io_avr.c
@@ -0,0 +1,75 @@
+#include <stdbool.h>
+#include <avr/io.h>
+#include <util/delay.h>
+
+/* Check port settings for clock and data line */
+#if !(defined(PS2_CLOCK_PORT) && \
+ defined(PS2_CLOCK_PIN) && \
+ defined(PS2_CLOCK_DDR) && \
+ defined(PS2_CLOCK_BIT))
+# error "PS/2 clock port setting is required in config.h"
+#endif
+
+#if !(defined(PS2_DATA_PORT) && \
+ defined(PS2_DATA_PIN) && \
+ defined(PS2_DATA_DDR) && \
+ defined(PS2_DATA_BIT))
+# error "PS/2 data port setting is required in config.h"
+#endif
+
+
+/*
+ * Clock
+ */
+void clock_init(void)
+{
+}
+
+void clock_lo(void)
+{
+ PS2_CLOCK_PORT &= ~(1<<PS2_CLOCK_BIT);
+ PS2_CLOCK_DDR |= (1<<PS2_CLOCK_BIT);
+}
+
+void clock_hi(void)
+{
+ /* input with pull up */
+ PS2_CLOCK_DDR &= ~(1<<PS2_CLOCK_BIT);
+ PS2_CLOCK_PORT |= (1<<PS2_CLOCK_BIT);
+}
+
+bool clock_in(void)
+{
+ PS2_CLOCK_DDR &= ~(1<<PS2_CLOCK_BIT);
+ PS2_CLOCK_PORT |= (1<<PS2_CLOCK_BIT);
+ _delay_us(1);
+ return PS2_CLOCK_PIN&(1<<PS2_CLOCK_BIT);
+}
+
+/*
+ * Data
+ */
+void data_init(void)
+{
+}
+
+void data_lo(void)
+{
+ PS2_DATA_PORT &= ~(1<<PS2_DATA_BIT);
+ PS2_DATA_DDR |= (1<<PS2_DATA_BIT);
+}
+
+void data_hi(void)
+{
+ /* input with pull up */
+ PS2_DATA_DDR &= ~(1<<PS2_DATA_BIT);
+ PS2_DATA_PORT |= (1<<PS2_DATA_BIT);
+}
+
+bool data_in(void)
+{
+ PS2_DATA_DDR &= ~(1<<PS2_DATA_BIT);
+ PS2_DATA_PORT |= (1<<PS2_DATA_BIT);
+ _delay_us(1);
+ return PS2_DATA_PIN&(1<<PS2_DATA_BIT);
+}
diff --git a/tmk_core/protocol/ps2_io_mbed.c b/tmk_core/protocol/ps2_io_mbed.c
new file mode 100644
index 000000000..83bdcef7f
--- /dev/null
+++ b/tmk_core/protocol/ps2_io_mbed.c
@@ -0,0 +1,60 @@
+#include <stdbool.h>
+#include "ps2_io.h"
+#include "gpio_api.h"
+
+
+static gpio_t clock;
+static gpio_t data;
+
+/*
+ * Clock
+ */
+void clock_init(void)
+{
+ gpio_init(&clock, P0_9);
+ gpio_mode(&clock, OpenDrain|PullNone);
+}
+
+void clock_lo(void)
+{
+ gpio_dir(&clock, PIN_OUTPUT);
+ gpio_write(&clock, 0);
+}
+void clock_hi(void)
+{
+ gpio_dir(&clock, PIN_OUTPUT);
+ gpio_write(&clock, 1);
+}
+
+bool clock_in(void)
+{
+ gpio_dir(&clock, PIN_INPUT);
+ return gpio_read(&clock);
+}
+
+/*
+ * Data
+ */
+void data_init(void)
+{
+ gpio_init(&data, P0_8);
+ gpio_mode(&data, OpenDrain|PullNone);
+}
+
+void data_lo(void)
+{
+ gpio_dir(&data, PIN_OUTPUT);
+ gpio_write(&data, 0);
+}
+
+void data_hi(void)
+{
+ gpio_dir(&data, PIN_OUTPUT);
+ gpio_write(&data, 1);
+}
+
+bool data_in(void)
+{
+ gpio_dir(&data, PIN_INPUT);
+ return gpio_read(&data);
+}
diff --git a/tmk_core/protocol/ps2_mouse.c b/tmk_core/protocol/ps2_mouse.c
new file mode 100644
index 000000000..4ed3cae1f
--- /dev/null
+++ b/tmk_core/protocol/ps2_mouse.c
@@ -0,0 +1,247 @@
+/*
+Copyright 2011,2013 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdbool.h>
+#include<avr/io.h>
+#include<util/delay.h>
+#include "ps2_mouse.h"
+#include "host.h"
+#include "timer.h"
+#include "print.h"
+#include "report.h"
+#include "debug.h"
+#include "ps2.h"
+
+/* ============================= MACROS ============================ */
+
+static report_mouse_t mouse_report = {};
+
+static inline void ps2_mouse_print_report(report_mouse_t *mouse_report);
+static inline void ps2_mouse_convert_report_to_hid(report_mouse_t *mouse_report);
+static inline void ps2_mouse_clear_report(report_mouse_t *mouse_report);
+static inline void ps2_mouse_enable_scrolling(void);
+static inline void ps2_mouse_scroll_button_task(report_mouse_t *mouse_report);
+
+/* ============================= IMPLEMENTATION ============================ */
+
+/* supports only 3 button mouse at this time */
+void ps2_mouse_init(void) {
+ ps2_host_init();
+
+ _delay_ms(PS2_MOUSE_INIT_DELAY); // wait for powering up
+
+ PS2_MOUSE_SEND(PS2_MOUSE_RESET, "ps2_mouse_init: sending reset");
+
+ PS2_MOUSE_RECEIVE("ps2_mouse_init: read BAT");
+ PS2_MOUSE_RECEIVE("ps2_mouse_init: read DevID");
+
+#ifdef PS2_MOUSE_USE_REMOTE_MODE
+ ps2_mouse_set_remote_mode();
+#else
+ ps2_mouse_enable_data_reporting();
+#endif
+
+#ifdef PS2_MOUSE_ENABLE_SCROLLING
+ ps2_mouse_enable_scrolling();
+#endif
+
+#ifdef PS2_MOUSE_USE_2_1_SCALING
+ ps2_mouse_set_scaling_2_1();
+#endif
+
+ ps2_mouse_init_user();
+}
+
+__attribute__((weak))
+void ps2_mouse_init_user(void) {
+}
+
+void ps2_mouse_task(void) {
+ static uint8_t buttons_prev = 0;
+ extern int tp_buttons;
+
+ /* receives packet from mouse */
+ uint8_t rcv;
+ rcv = ps2_host_send(PS2_MOUSE_READ_DATA);
+ if (rcv == PS2_ACK) {
+ mouse_report.buttons = ps2_host_recv_response() | tp_buttons;
+ mouse_report.x = ps2_host_recv_response() * PS2_MOUSE_X_MULTIPLIER;
+ mouse_report.y = ps2_host_recv_response() * PS2_MOUSE_Y_MULTIPLIER;
+#ifdef PS2_MOUSE_ENABLE_SCROLLING
+ mouse_report.v = -(ps2_host_recv_response() & PS2_MOUSE_SCROLL_MASK) * PS2_MOUSE_V_MULTIPLIER;
+#endif
+ } else {
+ if (debug_mouse) print("ps2_mouse: fail to get mouse packet\n");
+ return;
+ }
+
+ /* if mouse moves or buttons state changes */
+ if (mouse_report.x || mouse_report.y || mouse_report.v ||
+ ((mouse_report.buttons ^ buttons_prev) & PS2_MOUSE_BTN_MASK)) {
+#ifdef PS2_MOUSE_DEBUG_RAW
+ // Used to debug raw ps2 bytes from mouse
+ ps2_mouse_print_report(&mouse_report);
+#endif
+ buttons_prev = mouse_report.buttons;
+ ps2_mouse_convert_report_to_hid(&mouse_report);
+#if PS2_MOUSE_SCROLL_BTN_MASK
+ ps2_mouse_scroll_button_task(&mouse_report);
+#endif
+#ifdef PS2_MOUSE_DEBUG_HID
+ // Used to debug the bytes sent to the host
+ ps2_mouse_print_report(&mouse_report);
+#endif
+ host_mouse_send(&mouse_report);
+ }
+
+ ps2_mouse_clear_report(&mouse_report);
+}
+
+void ps2_mouse_disable_data_reporting(void) {
+ PS2_MOUSE_SEND(PS2_MOUSE_DISABLE_DATA_REPORTING, "ps2 mouse disable data reporting");
+}
+
+void ps2_mouse_enable_data_reporting(void) {
+ PS2_MOUSE_SEND(PS2_MOUSE_ENABLE_DATA_REPORTING, "ps2 mouse enable data reporting");
+}
+
+void ps2_mouse_set_remote_mode(void) {
+ PS2_MOUSE_SEND_SAFE(PS2_MOUSE_SET_REMOTE_MODE, "ps2 mouse set remote mode");
+ ps2_mouse_mode = PS2_MOUSE_REMOTE_MODE;
+}
+
+void ps2_mouse_set_stream_mode(void) {
+ PS2_MOUSE_SEND_SAFE(PS2_MOUSE_SET_STREAM_MODE, "ps2 mouse set stream mode");
+ ps2_mouse_mode = PS2_MOUSE_STREAM_MODE;
+}
+
+void ps2_mouse_set_scaling_2_1(void) {
+ PS2_MOUSE_SEND_SAFE(PS2_MOUSE_SET_SCALING_2_1, "ps2 mouse set scaling 2:1");
+}
+
+void ps2_mouse_set_scaling_1_1(void) {
+ PS2_MOUSE_SEND_SAFE(PS2_MOUSE_SET_SCALING_1_1, "ps2 mouse set scaling 1:1");
+}
+
+void ps2_mouse_set_resolution(ps2_mouse_resolution_t resolution) {
+ PS2_MOUSE_SET_SAFE(PS2_MOUSE_SET_RESOLUTION, resolution, "ps2 mouse set resolution");
+}
+
+void ps2_mouse_set_sample_rate(ps2_mouse_sample_rate_t sample_rate) {
+ PS2_MOUSE_SET_SAFE(PS2_MOUSE_SET_SAMPLE_RATE, sample_rate, "ps2 mouse set sample rate");
+}
+
+/* ============================= HELPERS ============================ */
+
+#define X_IS_NEG (mouse_report->buttons & (1<<PS2_MOUSE_X_SIGN))
+#define Y_IS_NEG (mouse_report->buttons & (1<<PS2_MOUSE_Y_SIGN))
+#define X_IS_OVF (mouse_report->buttons & (1<<PS2_MOUSE_X_OVFLW))
+#define Y_IS_OVF (mouse_report->buttons & (1<<PS2_MOUSE_Y_OVFLW))
+static inline void ps2_mouse_convert_report_to_hid(report_mouse_t *mouse_report) {
+ // PS/2 mouse data is '9-bit integer'(-256 to 255) which is comprised of sign-bit and 8-bit value.
+ // bit: 8 7 ... 0
+ // sign \8-bit/
+ //
+ // Meanwhile USB HID mouse indicates 8bit data(-127 to 127), note that -128 is not used.
+ //
+ // This converts PS/2 data into HID value. Use only -127-127 out of PS/2 9-bit.
+ mouse_report->x = X_IS_NEG ?
+ ((!X_IS_OVF && -127 <= mouse_report->x && mouse_report->x <= -1) ? mouse_report->x : -127) :
+ ((!X_IS_OVF && 0 <= mouse_report->x && mouse_report->x <= 127) ? mouse_report->x : 127);
+ mouse_report->y = Y_IS_NEG ?
+ ((!Y_IS_OVF && -127 <= mouse_report->y && mouse_report->y <= -1) ? mouse_report->y : -127) :
+ ((!Y_IS_OVF && 0 <= mouse_report->y && mouse_report->y <= 127) ? mouse_report->y : 127);
+
+ // remove sign and overflow flags
+ mouse_report->buttons &= PS2_MOUSE_BTN_MASK;
+
+ // invert coordinate of y to conform to USB HID mouse
+ mouse_report->y = -mouse_report->y;
+}
+
+static inline void ps2_mouse_clear_report(report_mouse_t *mouse_report) {
+ mouse_report->x = 0;
+ mouse_report->y = 0;
+ mouse_report->v = 0;
+ mouse_report->h = 0;
+ mouse_report->buttons = 0;
+}
+
+static inline void ps2_mouse_print_report(report_mouse_t *mouse_report) {
+ if (!debug_mouse) return;
+ print("ps2_mouse: [");
+ phex(mouse_report->buttons); print("|");
+ print_hex8((uint8_t)mouse_report->x); print(" ");
+ print_hex8((uint8_t)mouse_report->y); print(" ");
+ print_hex8((uint8_t)mouse_report->v); print(" ");
+ print_hex8((uint8_t)mouse_report->h); print("]\n");
+}
+
+static inline void ps2_mouse_enable_scrolling(void) {
+ PS2_MOUSE_SEND(PS2_MOUSE_SET_SAMPLE_RATE, "Initiaing scroll wheel enable: Set sample rate");
+ PS2_MOUSE_SEND(200, "200");
+ PS2_MOUSE_SEND(PS2_MOUSE_SET_SAMPLE_RATE, "Set sample rate");
+ PS2_MOUSE_SEND(100, "100");
+ PS2_MOUSE_SEND(PS2_MOUSE_SET_SAMPLE_RATE, "Set sample rate");
+ PS2_MOUSE_SEND(80, "80");
+ PS2_MOUSE_SEND(PS2_MOUSE_GET_DEVICE_ID, "Finished enabling scroll wheel");
+ _delay_ms(20);
+}
+
+#define PRESS_SCROLL_BUTTONS mouse_report->buttons |= (PS2_MOUSE_SCROLL_BTN_MASK)
+#define RELEASE_SCROLL_BUTTONS mouse_report->buttons &= ~(PS2_MOUSE_SCROLL_BTN_MASK)
+static inline void ps2_mouse_scroll_button_task(report_mouse_t *mouse_report) {
+ static enum {
+ SCROLL_NONE,
+ SCROLL_BTN,
+ SCROLL_SENT,
+ } scroll_state = SCROLL_NONE;
+ static uint16_t scroll_button_time = 0;
+
+ if (PS2_MOUSE_SCROLL_BTN_MASK == (mouse_report->buttons & (PS2_MOUSE_SCROLL_BTN_MASK))) {
+ // All scroll buttons are pressed
+
+ if (scroll_state == SCROLL_NONE) {
+ scroll_button_time = timer_read();
+ scroll_state = SCROLL_BTN;
+ }
+
+ // If the mouse has moved, update the report to scroll instead of move the mouse
+ if (mouse_report->x || mouse_report->y) {
+ scroll_state = SCROLL_SENT;
+ mouse_report->v = -mouse_report->y/(PS2_MOUSE_SCROLL_DIVISOR_V);
+ mouse_report->h = mouse_report->x/(PS2_MOUSE_SCROLL_DIVISOR_H);
+ mouse_report->x = 0;
+ mouse_report->y = 0;
+ }
+ } else if (0 == (PS2_MOUSE_SCROLL_BTN_MASK & mouse_report->buttons)) {
+ // None of the scroll buttons are pressed
+
+#if PS2_MOUSE_SCROLL_BTN_SEND
+ if (scroll_state == SCROLL_BTN
+ && timer_elapsed(scroll_button_time) < PS2_MOUSE_SCROLL_BTN_SEND) {
+ PRESS_SCROLL_BUTTONS;
+ host_mouse_send(mouse_report);
+ _delay_ms(100);
+ RELEASE_SCROLL_BUTTONS;
+ }
+#endif
+ scroll_state = SCROLL_NONE;
+ }
+
+ RELEASE_SCROLL_BUTTONS;
+}
diff --git a/tmk_core/protocol/ps2_mouse.h b/tmk_core/protocol/ps2_mouse.h
new file mode 100644
index 000000000..eeeffe4d8
--- /dev/null
+++ b/tmk_core/protocol/ps2_mouse.h
@@ -0,0 +1,178 @@
+/*
+Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef PS2_MOUSE_H
+#define PS2_MOUSE_H
+
+#include <stdbool.h>
+#include "debug.h"
+
+#define PS2_MOUSE_SEND(command, message) \
+do { \
+ __attribute__ ((unused)) uint8_t rcv = ps2_host_send(command); \
+ if (debug_mouse) { \
+ print((message)); \
+ xprintf(" command: %X, result: %X, error: %X \n", command, rcv, ps2_error); \
+ } \
+} while(0)
+
+#define PS2_MOUSE_SEND_SAFE(command, message) \
+do { \
+ if (PS2_MOUSE_STREAM_MODE == ps2_mouse_mode) { \
+ ps2_mouse_disable_data_reporting(); \
+ } \
+ PS2_MOUSE_SEND(command, message); \
+ if (PS2_MOUSE_STREAM_MODE == ps2_mouse_mode) { \
+ ps2_mouse_enable_data_reporting(); \
+ } \
+} while(0)
+
+#define PS2_MOUSE_SET_SAFE(command, value, message) \
+do { \
+ if (PS2_MOUSE_STREAM_MODE == ps2_mouse_mode) { \
+ ps2_mouse_disable_data_reporting(); \
+ } \
+ PS2_MOUSE_SEND(command, message); \
+ PS2_MOUSE_SEND(value, "Sending value"); \
+ if (PS2_MOUSE_STREAM_MODE == ps2_mouse_mode) { \
+ ps2_mouse_enable_data_reporting(); \
+ } \
+} while(0)
+
+#define PS2_MOUSE_RECEIVE(message) \
+do { \
+ __attribute__ ((unused)) uint8_t rcv = ps2_host_recv_response(); \
+ if (debug_mouse) { \
+ print((message)); \
+ xprintf(" result: %X, error: %X \n", rcv, ps2_error); \
+ } \
+} while(0)
+
+__attribute__ ((unused))
+static enum ps2_mouse_mode_e {
+ PS2_MOUSE_STREAM_MODE,
+ PS2_MOUSE_REMOTE_MODE,
+} ps2_mouse_mode = PS2_MOUSE_STREAM_MODE;
+
+/*
+ * Data format:
+ * byte|7 6 5 4 3 2 1 0
+ * ----+----------------------------------------------------------------
+ * 0|[Yovflw][Xovflw][Ysign ][Xsign ][ 1 ][Middle][Right ][Left ]
+ * 1|[ X movement(0-255) ]
+ * 2|[ Y movement(0-255) ]
+ */
+#define PS2_MOUSE_BTN_MASK 0x07
+#define PS2_MOUSE_BTN_LEFT 0
+#define PS2_MOUSE_BTN_RIGHT 1
+#define PS2_MOUSE_BTN_MIDDLE 2
+#define PS2_MOUSE_X_SIGN 4
+#define PS2_MOUSE_Y_SIGN 5
+#define PS2_MOUSE_X_OVFLW 6
+#define PS2_MOUSE_Y_OVFLW 7
+
+/* mouse button to start scrolling; set 0 to disable scroll */
+#ifndef PS2_MOUSE_SCROLL_BTN_MASK
+#define PS2_MOUSE_SCROLL_BTN_MASK (1<<PS2_MOUSE_BTN_MIDDLE)
+#endif
+/* send button event when button is released within this value(ms); set 0 to disable */
+#ifndef PS2_MOUSE_SCROLL_BTN_SEND
+#define PS2_MOUSE_SCROLL_BTN_SEND 300
+#endif
+/* divide virtical and horizontal mouse move by this to convert to scroll move */
+#ifndef PS2_MOUSE_SCROLL_DIVISOR_V
+#define PS2_MOUSE_SCROLL_DIVISOR_V 2
+#endif
+#ifndef PS2_MOUSE_SCROLL_DIVISOR_H
+#define PS2_MOUSE_SCROLL_DIVISOR_H 2
+#endif
+/* multiply reported mouse values by these */
+#ifndef PS2_MOUSE_X_MULTIPLIER
+#define PS2_MOUSE_X_MULTIPLIER 1
+#endif
+#ifndef PS2_MOUSE_Y_MULTIPLIER
+#define PS2_MOUSE_Y_MULTIPLIER 1
+#endif
+#ifndef PS2_MOUSE_V_MULTIPLIER
+#define PS2_MOUSE_V_MULTIPLIER 1
+#endif
+/* For some mice this will need to be 0x0F */
+#ifndef PS2_MOUSE_SCROLL_MASK
+#define PS2_MOUSE_SCROLL_MASK 0xFF
+#endif
+#ifndef PS2_MOUSE_INIT_DELAY
+#define PS2_MOUSE_INIT_DELAY 1000
+#endif
+
+enum ps2_mouse_command_e {
+ PS2_MOUSE_RESET = 0xFF,
+ PS2_MOUSE_RESEND = 0xFE,
+ PS2_MOSUE_SET_DEFAULTS = 0xF6,
+ PS2_MOUSE_DISABLE_DATA_REPORTING = 0xF5,
+ PS2_MOUSE_ENABLE_DATA_REPORTING = 0xF4,
+ PS2_MOUSE_SET_SAMPLE_RATE = 0xF3,
+ PS2_MOUSE_GET_DEVICE_ID = 0xF2,
+ PS2_MOUSE_SET_REMOTE_MODE = 0xF0,
+ PS2_MOUSE_SET_WRAP_MODE = 0xEC,
+ PS2_MOUSE_READ_DATA = 0xEB,
+ PS2_MOUSE_SET_STREAM_MODE = 0xEA,
+ PS2_MOUSE_STATUS_REQUEST = 0xE9,
+ PS2_MOUSE_SET_RESOLUTION = 0xE8,
+ PS2_MOUSE_SET_SCALING_2_1 = 0xE7,
+ PS2_MOUSE_SET_SCALING_1_1 = 0xE6,
+};
+
+typedef enum ps2_mouse_resolution_e {
+ PS2_MOUSE_1_COUNT_MM,
+ PS2_MOUSE_2_COUNT_MM,
+ PS2_MOUSE_4_COUNT_MM,
+ PS2_MOUSE_8_COUNT_MM,
+} ps2_mouse_resolution_t;
+
+typedef enum ps2_mouse_sample_rate_e {
+ PS2_MOUSE_10_SAMPLES_SEC = 10,
+ PS2_MOUSE_20_SAMPLES_SEC = 20,
+ PS2_MOUSE_40_SAMPLES_SEC = 40,
+ PS2_MOUSE_60_SAMPLES_SEC = 60,
+ PS2_MOUSE_80_SAMPLES_SEC = 80,
+ PS2_MOUSE_100_SAMPLES_SEC = 100,
+ PS2_MOUSE_200_SAMPLES_SEC = 200,
+} ps2_mouse_sample_rate_t;
+
+void ps2_mouse_init(void);
+
+void ps2_mouse_init_user(void);
+
+void ps2_mouse_task(void);
+
+void ps2_mouse_disable_data_reporting(void);
+
+void ps2_mouse_enable_data_reporting(void);
+
+void ps2_mouse_set_remote_mode(void);
+
+void ps2_mouse_set_stream_mode(void);
+
+void ps2_mouse_set_scaling_2_1(void);
+
+void ps2_mouse_set_scaling_1_1(void);
+
+void ps2_mouse_set_resolution(ps2_mouse_resolution_t resolution);
+
+void ps2_mouse_set_sample_rate(ps2_mouse_sample_rate_t sample_rate);
+
+#endif
diff --git a/tmk_core/protocol/ps2_usart.c b/tmk_core/protocol/ps2_usart.c
new file mode 100644
index 000000000..6936ca7b8
--- /dev/null
+++ b/tmk_core/protocol/ps2_usart.c
@@ -0,0 +1,223 @@
+/*
+Copyright 2010,2011,2012,2013 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*
+ * PS/2 protocol USART version
+ */
+
+#include <stdbool.h>
+#include <avr/interrupt.h>
+#include <util/delay.h>
+#include "ps2.h"
+#include "ps2_io.h"
+#include "print.h"
+
+
+#define WAIT(stat, us, err) do { \
+ if (!wait_##stat(us)) { \
+ ps2_error = err; \
+ goto ERROR; \
+ } \
+} while (0)
+
+
+uint8_t ps2_error = PS2_ERR_NONE;
+
+
+static inline uint8_t pbuf_dequeue(void);
+static inline void pbuf_enqueue(uint8_t data);
+static inline bool pbuf_has_data(void);
+static inline void pbuf_clear(void);
+
+
+void ps2_host_init(void)
+{
+ idle(); // without this many USART errors occur when cable is disconnected
+ PS2_USART_INIT();
+ PS2_USART_RX_INT_ON();
+ // POR(150-2000ms) plus BAT(300-500ms) may take 2.5sec([3]p.20)
+ //_delay_ms(2500);
+}
+
+uint8_t ps2_host_send(uint8_t data)
+{
+ bool parity = true;
+ ps2_error = PS2_ERR_NONE;
+
+ PS2_USART_OFF();
+
+ /* terminate a transmission if we have */
+ inhibit();
+ _delay_us(100); // [4]p.13
+
+ /* 'Request to Send' and Start bit */
+ data_lo();
+ clock_hi();
+ WAIT(clock_lo, 10000, 10); // 10ms [5]p.50
+
+ /* Data bit[2-9] */
+ for (uint8_t i = 0; i < 8; i++) {
+ _delay_us(15);
+ if (data&(1<<i)) {
+ parity = !parity;
+ data_hi();
+ } else {
+ data_lo();
+ }
+ WAIT(clock_hi, 50, 2);
+ WAIT(clock_lo, 50, 3);
+ }
+
+ /* Parity bit */
+ _delay_us(15);
+ if (parity) { data_hi(); } else { data_lo(); }
+ WAIT(clock_hi, 50, 4);
+ WAIT(clock_lo, 50, 5);
+
+ /* Stop bit */
+ _delay_us(15);
+ data_hi();
+
+ /* Ack */
+ WAIT(data_lo, 50, 6);
+ WAIT(clock_lo, 50, 7);
+
+ /* wait for idle state */
+ WAIT(clock_hi, 50, 8);
+ WAIT(data_hi, 50, 9);
+
+ idle();
+ PS2_USART_INIT();
+ PS2_USART_RX_INT_ON();
+ return ps2_host_recv_response();
+ERROR:
+ idle();
+ PS2_USART_INIT();
+ PS2_USART_RX_INT_ON();
+ return 0;
+}
+
+uint8_t ps2_host_recv_response(void)
+{
+ // Command may take 25ms/20ms at most([5]p.46, [3]p.21)
+ uint8_t retry = 25;
+ while (retry-- && !pbuf_has_data()) {
+ _delay_ms(1);
+ }
+ return pbuf_dequeue();
+}
+
+uint8_t ps2_host_recv(void)
+{
+ if (pbuf_has_data()) {
+ ps2_error = PS2_ERR_NONE;
+ return pbuf_dequeue();
+ } else {
+ ps2_error = PS2_ERR_NODATA;
+ return 0;
+ }
+}
+
+ISR(PS2_USART_RX_VECT)
+{
+ // TODO: request RESEND when error occurs?
+ uint8_t error = PS2_USART_ERROR; // USART error should be read before data
+ uint8_t data = PS2_USART_RX_DATA;
+ if (!error) {
+ pbuf_enqueue(data);
+ } else {
+ xprintf("PS2 USART error: %02X data: %02X\n", error, data);
+ }
+}
+
+/* send LED state to keyboard */
+void ps2_host_set_led(uint8_t led)
+{
+ ps2_host_send(0xED);
+ ps2_host_send(led);
+}
+
+
+/*--------------------------------------------------------------------
+ * Ring buffer to store scan codes from keyboard
+ *------------------------------------------------------------------*/
+#define PBUF_SIZE 32
+static uint8_t pbuf[PBUF_SIZE];
+static uint8_t pbuf_head = 0;
+static uint8_t pbuf_tail = 0;
+static inline void pbuf_enqueue(uint8_t data)
+{
+ uint8_t sreg = SREG;
+ cli();
+ uint8_t next = (pbuf_head + 1) % PBUF_SIZE;
+ if (next != pbuf_tail) {
+ pbuf[pbuf_head] = data;
+ pbuf_head = next;
+ } else {
+ print("pbuf: full\n");
+ }
+ SREG = sreg;
+}
+static inline uint8_t pbuf_dequeue(void)
+{
+ uint8_t val = 0;
+
+ uint8_t sreg = SREG;
+ cli();
+ if (pbuf_head != pbuf_tail) {
+ val = pbuf[pbuf_tail];
+ pbuf_tail = (pbuf_tail + 1) % PBUF_SIZE;
+ }
+ SREG = sreg;
+
+ return val;
+}
+static inline bool pbuf_has_data(void)
+{
+ uint8_t sreg = SREG;
+ cli();
+ bool has_data = (pbuf_head != pbuf_tail);
+ SREG = sreg;
+ return has_data;
+}
+static inline void pbuf_clear(void)
+{
+ uint8_t sreg = SREG;
+ cli();
+ pbuf_head = pbuf_tail = 0;
+ SREG = sreg;
+}
diff --git a/tmk_core/protocol/serial.h b/tmk_core/protocol/serial.h
new file mode 100644
index 000000000..96913c867
--- /dev/null
+++ b/tmk_core/protocol/serial.h
@@ -0,0 +1,47 @@
+/*
+Copyright 2012 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#ifndef SERIAL_H
+#define SERIAL_H
+
+/* host role */
+void serial_init(void);
+uint8_t serial_recv(void);
+int16_t serial_recv2(void);
+void serial_send(uint8_t data);
+
+#endif
diff --git a/tmk_core/protocol/serial_mouse.h b/tmk_core/protocol/serial_mouse.h
new file mode 100644
index 000000000..226314fc0
--- /dev/null
+++ b/tmk_core/protocol/serial_mouse.h
@@ -0,0 +1,33 @@
+/*
+Copyright 2014 Robin Haberkorn <robin.haberkorn@googlemail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef SERIAL_MOUSE_H
+#define SERIAL_MOUSE_H
+
+#include <stdint.h>
+
+#include "serial.h"
+
+static inline uint8_t serial_mouse_init(void)
+{
+ serial_init();
+ return 0;
+}
+
+void serial_mouse_task(void);
+
+#endif
diff --git a/tmk_core/protocol/serial_mouse_microsoft.c b/tmk_core/protocol/serial_mouse_microsoft.c
new file mode 100644
index 000000000..ab74b7cdd
--- /dev/null
+++ b/tmk_core/protocol/serial_mouse_microsoft.c
@@ -0,0 +1,124 @@
+/*
+Copyright 2014 Robin Haberkorn <robin.haberkorn@googlemail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdint.h>
+#include <avr/io.h>
+#include <util/delay.h>
+
+#include "serial.h"
+#include "serial_mouse.h"
+#include "report.h"
+#include "host.h"
+#include "timer.h"
+#include "print.h"
+#include "debug.h"
+
+#ifdef MAX
+#undef MAX
+#endif
+#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
+
+static void print_usb_data(const report_mouse_t *report);
+
+void serial_mouse_task(void)
+{
+ /* 3 byte ring buffer */
+ static uint8_t buffer[3];
+ static int buffer_cur = 0;
+
+ static report_mouse_t report = {};
+
+ int16_t rcv;
+
+ rcv = serial_recv2();
+ if (rcv < 0)
+ /* no new data */
+ return;
+
+ if (debug_mouse)
+ xprintf("serial_mouse: byte: %04X\n", rcv);
+
+ /*
+ * If bit 6 is one, this signals the beginning
+ * of a 3 byte sequence/packet.
+ */
+ if (rcv & (1 << 6))
+ buffer_cur = 0;
+
+ buffer[buffer_cur] = (uint8_t)rcv;
+
+ if (buffer_cur == 0 && buffer[buffer_cur] == 0x20) {
+ /*
+ * Logitech extension: This must be a follow-up on
+ * the last 3-byte packet signaling a middle button click
+ */
+ report.buttons |= MOUSE_BTN3;
+ report.x = report.y = 0;
+
+ print_usb_data(&report);
+ host_mouse_send(&report);
+ return;
+ }
+
+ buffer_cur++;
+
+ if (buffer_cur < 3)
+ return;
+ buffer_cur = 0;
+
+ /*
+ * parse 3 byte packet.
+ * NOTE: We only get a complete packet
+ * if the mouse moved or the button states
+ * change.
+ */
+ report.buttons = 0;
+ if (buffer[0] & (1 << 5))
+ report.buttons |= MOUSE_BTN1;
+ if (buffer[0] & (1 << 4))
+ report.buttons |= MOUSE_BTN2;
+
+ report.x = (buffer[0] << 6) | buffer[1];
+ report.y = ((buffer[0] << 4) & 0xC0) | buffer[2];
+
+ /* USB HID uses values from -127 to 127 only */
+ report.x = MAX(report.x, -127);
+ report.y = MAX(report.y, -127);
+
+#if 0
+ if (!report.buttons && !report.x && !report.y) {
+ /*
+ * Microsoft extension: Middle mouse button pressed
+ * FIXME: I don't know how exactly this extension works.
+ */
+ report.buttons |= MOUSE_BTN3;
+ }
+#endif
+
+ print_usb_data(&report);
+ host_mouse_send(&report);
+}
+
+static void print_usb_data(const report_mouse_t *report)
+{
+ if (!debug_mouse)
+ return;
+
+ xprintf("serial_mouse usb: [%02X|%d %d %d %d]\n",
+ report->buttons, report->x, report->y,
+ report->v, report->h);
+}
diff --git a/tmk_core/protocol/serial_mouse_mousesystems.c b/tmk_core/protocol/serial_mouse_mousesystems.c
new file mode 100644
index 000000000..cfe899621
--- /dev/null
+++ b/tmk_core/protocol/serial_mouse_mousesystems.c
@@ -0,0 +1,131 @@
+/*
+Copyright 2014 Robin Haberkorn <robin.haberkorn@googlemail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <stdint.h>
+#include <avr/io.h>
+#include <util/delay.h>
+
+#include "serial.h"
+#include "serial_mouse.h"
+#include "report.h"
+#include "host.h"
+#include "timer.h"
+#include "print.h"
+#include "debug.h"
+
+#ifdef MAX
+#undef MAX
+#endif
+#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
+
+//#define SERIAL_MOUSE_CENTER_SCROLL
+
+static void print_usb_data(const report_mouse_t *report);
+
+void serial_mouse_task(void)
+{
+ /* 5 byte ring buffer */
+ static uint8_t buffer[5];
+ static int buffer_cur = 0;
+
+ int16_t rcv;
+
+ report_mouse_t report = {0, 0, 0, 0, 0};
+
+ rcv = serial_recv2();
+ if (rcv < 0)
+ /* no new data */
+ return;
+
+ if (debug_mouse)
+ xprintf("serial_mouse: byte: %04X\n", rcv);
+
+ /*
+ * Synchronization: mouse(4) says that all
+ * bytes but the first one in the packet have
+ * bit 7 == 0, but this is untrue.
+ * Therefore we discard all bytes up to the
+ * first one with the characteristic bit pattern.
+ */
+ if (buffer_cur == 0 && (rcv >> 3) != 0x10)
+ return;
+
+ buffer[buffer_cur++] = (uint8_t)rcv;
+
+ if (buffer_cur < 5)
+ return;
+ buffer_cur = 0;
+
+#ifdef SERIAL_MOUSE_CENTER_SCROLL
+ if ((buffer[0] & 0x7) == 0x5 && (buffer[1] || buffer[2])) {
+ /* USB HID uses only values from -127 to 127 */
+ report.h = MAX((int8_t)buffer[1], -127);
+ report.v = MAX((int8_t)buffer[2], -127);
+
+ print_usb_data(&report);
+ host_mouse_send(&report);
+
+ if (buffer[3] || buffer[4]) {
+ report.h = MAX((int8_t)buffer[3], -127);
+ report.v = MAX((int8_t)buffer[4], -127);
+
+ print_usb_data(&report);
+ host_mouse_send(&report);
+ }
+
+ return;
+ }
+#endif
+
+ /*
+ * parse 5 byte packet.
+ * NOTE: We only get a complete packet
+ * if the mouse moved or the button states
+ * change.
+ */
+ if (!(buffer[0] & (1 << 2)))
+ report.buttons |= MOUSE_BTN1;
+ if (!(buffer[0] & (1 << 1)))
+ report.buttons |= MOUSE_BTN3;
+ if (!(buffer[0] & (1 << 0)))
+ report.buttons |= MOUSE_BTN2;
+
+ /* USB HID uses only values from -127 to 127 */
+ report.x = MAX((int8_t)buffer[1], -127);
+ report.y = MAX(-(int8_t)buffer[2], -127);
+
+ print_usb_data(&report);
+ host_mouse_send(&report);
+
+ if (buffer[3] || buffer[4]) {
+ report.x = MAX((int8_t)buffer[3], -127);
+ report.y = MAX(-(int8_t)buffer[4], -127);
+
+ print_usb_data(&report);
+ host_mouse_send(&report);
+ }
+}
+
+static void print_usb_data(const report_mouse_t *report)
+{
+ if (!debug_mouse)
+ return;
+
+ xprintf("serial_mouse usb: [%02X|%d %d %d %d]\n",
+ report->buttons, report->x, report->y,
+ report->v, report->h);
+}
diff --git a/tmk_core/protocol/serial_soft.c b/tmk_core/protocol/serial_soft.c
new file mode 100644
index 000000000..44822b7e4
--- /dev/null
+++ b/tmk_core/protocol/serial_soft.c
@@ -0,0 +1,240 @@
+/*
+Copyright 2012 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <stdbool.h>
+#include <avr/io.h>
+#include <avr/interrupt.h>
+#include <util/delay.h>
+#include "serial.h"
+
+/*
+ * Stupid Inefficient Busy-wait Software Serial
+ * which is still useful for negative logic signal like Sun protocol
+ * if it is not supported by hardware UART.
+ *
+ * TODO: delay is not accurate enough. Instruction cycle should be counted and inline assemby is needed.
+ */
+
+#define WAIT_US (1000000L/SERIAL_SOFT_BAUD)
+
+#ifdef SERIAL_SOFT_LOGIC_NEGATIVE
+ #define SERIAL_SOFT_RXD_IN() !(SERIAL_SOFT_RXD_READ())
+ #define SERIAL_SOFT_TXD_ON() SERIAL_SOFT_TXD_LO()
+ #define SERIAL_SOFT_TXD_OFF() SERIAL_SOFT_TXD_HI()
+#else
+ #define SERIAL_SOFT_RXD_IN() !!(SERIAL_SOFT_RXD_READ())
+ #define SERIAL_SOFT_TXD_ON() SERIAL_SOFT_TXD_HI()
+ #define SERIAL_SOFT_TXD_OFF() SERIAL_SOFT_TXD_LO()
+#endif
+
+#ifdef SERIAL_SOFT_PARITY_EVEN
+ #define SERIAL_SOFT_PARITY_VAL 0
+#elif defined(SERIAL_SOFT_PARITY_ODD)
+ #define SERIAL_SOFT_PARITY_VAL 1
+#endif
+
+/* debug for signal timing, see debug pin with oscilloscope */
+#define SERIAL_SOFT_DEBUG
+#ifdef SERIAL_SOFT_DEBUG
+ #define SERIAL_SOFT_DEBUG_INIT() (DDRD |= 1<<7)
+ #define SERIAL_SOFT_DEBUG_TGL() (PORTD ^= 1<<7)
+#else
+ #define SERIAL_SOFT_DEBUG_INIT()
+ #define SERIAL_SOFT_DEBUG_TGL()
+#endif
+
+
+void serial_init(void)
+{
+ SERIAL_SOFT_DEBUG_INIT();
+
+ SERIAL_SOFT_RXD_INIT();
+ SERIAL_SOFT_TXD_INIT();
+}
+
+/* RX ring buffer */
+#define RBUF_SIZE 8
+static uint8_t rbuf[RBUF_SIZE];
+static uint8_t rbuf_head = 0;
+static uint8_t rbuf_tail = 0;
+
+
+uint8_t serial_recv(void)
+{
+ uint8_t data = 0;
+ if (rbuf_head == rbuf_tail) {
+ return 0;
+ }
+
+ data = rbuf[rbuf_tail];
+ rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
+ return data;
+}
+
+int16_t serial_recv2(void)
+{
+ uint8_t data = 0;
+ if (rbuf_head == rbuf_tail) {
+ return -1;
+ }
+
+ data = rbuf[rbuf_tail];
+ rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
+ return data;
+}
+
+void serial_send(uint8_t data)
+{
+ /* signal state: IDLE: ON, START: OFF, STOP: ON, DATA0: OFF, DATA1: ON */
+
+#ifdef SERIAL_SOFT_BIT_ORDER_MSB
+ #ifdef SERIAL_SOFT_DATA_7BIT
+ uint8_t mask = 0x40;
+ #else
+ uint8_t mask = 0x80;
+ #endif
+#else
+ uint8_t mask = 0x01;
+#endif
+
+ uint8_t parity = 0;
+
+ /* start bit */
+ SERIAL_SOFT_TXD_OFF();
+ _delay_us(WAIT_US);
+
+#ifdef SERIAL_SOFT_DATA_7BIT
+ while (mask&0x7F) {
+#else
+ while (mask&0xFF) {
+#endif
+ if (data&mask) {
+ SERIAL_SOFT_TXD_ON();
+ parity ^= 1;
+ } else {
+ SERIAL_SOFT_TXD_OFF();
+ }
+ _delay_us(WAIT_US);
+
+#ifdef SERIAL_SOFT_BIT_ORDER_MSB
+ mask >>= 1;
+#else
+ mask <<= 1;
+#endif
+ }
+
+#if defined(SERIAL_SOFT_PARITY_EVEN) || defined(SERIAL_SOFT_PARITY_ODD)
+ /* to center of parity bit */
+ if (parity != SERIAL_SOFT_PARITY_VAL) {
+ SERIAL_SOFT_TXD_ON();
+ } else {
+ SERIAL_SOFT_TXD_OFF();
+ }
+ _delay_us(WAIT_US);
+#endif
+
+ /* stop bit */
+ SERIAL_SOFT_TXD_ON();
+ _delay_us(WAIT_US);
+}
+
+/* detect edge of start bit */
+ISR(SERIAL_SOFT_RXD_VECT)
+{
+ SERIAL_SOFT_DEBUG_TGL();
+ SERIAL_SOFT_RXD_INT_ENTER()
+
+ uint8_t data = 0;
+
+#ifdef SERIAL_SOFT_BIT_ORDER_MSB
+ #ifdef SERIAL_SOFT_DATA_7BIT
+ uint8_t mask = 0x40;
+ #else
+ uint8_t mask = 0x80;
+ #endif
+#else
+ uint8_t mask = 0x01;
+#endif
+
+ uint8_t parity = 0;
+
+ /* to center of start bit */
+ _delay_us(WAIT_US/2);
+ SERIAL_SOFT_DEBUG_TGL();
+ do {
+ /* to center of next bit */
+ _delay_us(WAIT_US);
+
+ SERIAL_SOFT_DEBUG_TGL();
+ if (SERIAL_SOFT_RXD_IN()) {
+ data |= mask;
+ parity ^= 1;
+ }
+#ifdef SERIAL_SOFT_BIT_ORDER_MSB
+ mask >>= 1;
+#else
+ mask <<= 1;
+#endif
+#ifdef SERIAL_SOFT_DATA_7BIT
+ } while (mask&0x7F);
+#else
+ } while (mask&0xFF);
+#endif
+
+#if defined(SERIAL_SOFT_PARITY_EVEN) || defined(SERIAL_SOFT_PARITY_ODD)
+ /* to center of parity bit */
+ _delay_us(WAIT_US);
+ if (SERIAL_SOFT_RXD_IN()) { parity ^= 1; }
+ SERIAL_SOFT_DEBUG_TGL();
+#endif
+
+ /* to center of stop bit */
+ _delay_us(WAIT_US);
+
+ uint8_t next = (rbuf_head + 1) % RBUF_SIZE;
+#if defined(SERIAL_SOFT_PARITY_EVEN) || defined(SERIAL_SOFT_PARITY_ODD)
+ if ((parity == SERIAL_SOFT_PARITY_VAL) && next != rbuf_tail) {
+#else
+ if (next != rbuf_tail) {
+#endif
+ rbuf[rbuf_head] = data;
+ rbuf_head = next;
+ }
+
+ SERIAL_SOFT_RXD_INT_EXIT();
+ SERIAL_SOFT_DEBUG_TGL();
+}
diff --git a/tmk_core/protocol/serial_uart.c b/tmk_core/protocol/serial_uart.c
new file mode 100644
index 000000000..35df27fd6
--- /dev/null
+++ b/tmk_core/protocol/serial_uart.c
@@ -0,0 +1,112 @@
+/*
+Copyright 2013 Jun WAKO <wakojun@gmail.com>
+
+This software is licensed with a Modified BSD License.
+All of this is supposed to be Free Software, Open Source, DFSG-free,
+GPL-compatible, and OK to use in both free and proprietary applications.
+Additions and corrections to this file are welcome.
+
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+* Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+* Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in
+ the documentation and/or other materials provided with the
+ distribution.
+
+* Neither the name of the copyright holders nor the names of
+ contributors may be used to endorse or promote products derived
+ from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
+*/
+
+#include <stdbool.h>
+#include <avr/io.h>
+#include <avr/interrupt.h>
+#include "serial.h"
+
+
+#if defined(SERIAL_UART_RTS_LO) && defined(SERIAL_UART_RTS_HI)
+ // Buffer state
+ // Empty: RBUF_SPACE == RBUF_SIZE(head==tail)
+ // Last 1 space: RBUF_SPACE == 2
+ // Full: RBUF_SPACE == 1(last cell of rbuf be never used.)
+ #define RBUF_SPACE() (rbuf_head < rbuf_tail ? (rbuf_tail - rbuf_head) : (RBUF_SIZE - rbuf_head + rbuf_tail))
+ // allow to send
+ #define rbuf_check_rts_lo() do { if (RBUF_SPACE() > 2) SERIAL_UART_RTS_LO(); } while (0)
+ // prohibit to send
+ #define rbuf_check_rts_hi() do { if (RBUF_SPACE() <= 2) SERIAL_UART_RTS_HI(); } while (0)
+#else
+ #define rbuf_check_rts_lo()
+ #define rbuf_check_rts_hi()
+#endif
+
+
+void serial_init(void)
+{
+ SERIAL_UART_INIT();
+}
+
+// RX ring buffer
+#define RBUF_SIZE 256
+static uint8_t rbuf[RBUF_SIZE];
+static uint8_t rbuf_head = 0;
+static uint8_t rbuf_tail = 0;
+
+uint8_t serial_recv(void)
+{
+ uint8_t data = 0;
+ if (rbuf_head == rbuf_tail) {
+ return 0;
+ }
+
+ data = rbuf[rbuf_tail];
+ rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
+ rbuf_check_rts_lo();
+ return data;
+}
+
+int16_t serial_recv2(void)
+{
+ uint8_t data = 0;
+ if (rbuf_head == rbuf_tail) {
+ return -1;
+ }
+
+ data = rbuf[rbuf_tail];
+ rbuf_tail = (rbuf_tail + 1) % RBUF_SIZE;
+ rbuf_check_rts_lo();
+ return data;
+}
+
+void serial_send(uint8_t data)
+{
+ while (!SERIAL_UART_TXD_READY) ;
+ SERIAL_UART_DATA = data;
+}
+
+// USART RX complete interrupt
+ISR(SERIAL_UART_RXD_VECT)
+{
+ uint8_t next = (rbuf_head + 1) % RBUF_SIZE;
+ if (next != rbuf_tail) {
+ rbuf[rbuf_head] = SERIAL_UART_DATA;
+ rbuf_head = next;
+ }
+ rbuf_check_rts_hi();
+}
diff --git a/tmk_core/protocol/usb_hid.mk b/tmk_core/protocol/usb_hid.mk
new file mode 100644
index 000000000..1f79bda3b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid.mk
@@ -0,0 +1,74 @@
+USB_HID_DIR = protocol/usb_hid
+
+
+#
+# USB Host Shield
+#
+USB_HOST_SHIELD_DIR = $(USB_HID_DIR)/USB_Host_Shield_2.0
+USB_HOST_SHIELD_SRC = \
+ $(USB_HOST_SHIELD_DIR)/Usb.cpp \
+ $(USB_HOST_SHIELD_DIR)/hid.cpp \
+ $(USB_HOST_SHIELD_DIR)/usbhub.cpp \
+ $(USB_HOST_SHIELD_DIR)/parsetools.cpp \
+ $(USB_HOST_SHIELD_DIR)/message.cpp
+
+
+
+#
+# Arduino
+#
+ARDUINO_DIR = $(USB_HID_DIR)/arduino-1.0.1
+ARDUINO_CORES_DIR = $(ARDUINO_DIR)/cores/arduino
+ARDUINO_CORES_SRC = \
+ $(ARDUINO_CORES_DIR)/Print.cpp \
+ $(ARDUINO_CORES_DIR)/Stream.cpp
+
+# replaced with override_Serial.c
+# $(ARDUINO_CORES_DIR)/CDC.cpp \
+# $(ARDUINO_CORES_DIR)/HID.cpp \
+# $(ARDUINO_CORES_DIR)/USBCore.cpp \
+
+# replaced with override_wiring.c and common/timer.c
+# $(ARDUINO_CORES_DIR)/wiring.c \
+
+
+
+#
+# HID parser
+#
+SRC += $(USB_HID_DIR)/parser.cpp
+
+# replace arduino/CDC.cpp
+SRC += $(USB_HID_DIR)/override_Serial.cpp
+
+# replace arduino/wiring.c
+SRC += $(USB_HID_DIR)/override_wiring.c
+SRC += common/avr/timer.c
+
+SRC += $(USB_HOST_SHIELD_SRC)
+SRC += $(ARDUINO_CORES_SRC)
+
+
+OPT_DEFS += -DARDUINO=101
+# Arduino USBCore needs USB_VID and USB_PID.
+#OPT_DEFS += -DARDUINO=101 -DUSB_VID=0x2341 -DUSB_PID=0x8036
+
+
+
+#
+# Search Path
+#
+VPATH += $(TMK_DIR)/$(USB_HID_DIR)
+VPATH += $(TMK_DIR)/$(USB_HOST_SHIELD_DIR)
+
+# for #include "Arduino.h"
+VPATH += $(TMK_DIR)/$(ARDUINO_CORES_DIR)
+
+# for #include "pins_arduino.h"
+VPATH += $(TMK_DIR)/$(ARDUINO_DIR)/variants/leonardo
+
+# ad hoc workaround for compile problem on Windows:
+# Windows doesn't know difference between common/print.h and arduino/Print.h.
+# On Linux no problem.
+# Change file name common/print.h to console.h ?
+VPATH := $(TMK_DIR)/common $(VPATH)
diff --git a/tmk_core/protocol/usb_hid/README b/tmk_core/protocol/usb_hid/README
new file mode 100644
index 000000000..0d2efc2aa
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/README
@@ -0,0 +1,47 @@
+USB HID protocol
+================
+Host side of USB HID keyboard protocol implementation.
+Only standard HID Boot mode is supported at this time. This means most of normal keyboards are supported while proprietary >6KRO and NKRO is not.
+
+Third party Libraries
+---------------------
+USB_Host_Shield_2.0
+ Circuits@Home repository is git-submoduled. Do git submodule init & update to get the content.
+ https://github.com/felis/USB_Host_Shield_2.0
+
+arduino-1.0.1
+ Arduino files copied from:
+ https://github.com/arduino/Arduino/hardware/arduino/{cores,variants}
+
+
+Test build
+----------
+In test directory;
+ $ make
+ $ DEV=/dev/ttyACM0 make program
+
+You can see HID keyboard reports on debug output.
+
+
+Restriction and Bug
+-------------------
+Not supported/confirmed yet.
+ Hub, suspend, keyboard LED
+
+Switching power on VBUS:
+ To power reset device.
+ http://www.circuitsathome.com/camera-control/simulating-cable-disconnect-on-usb-host-shield-2-0
+ This is needed for a device which are not initilized with 'USB Bus Reset'(long SE0)
+
+Can't bus-reset a keyboard which already attached on bus properly.
+ Slow start up of Leonardo's bootloader causes this?
+ Need to unplug/plug a keyboard after firmware starts up.
+ MAX3421E doesn't work SAMPLEBUS well to know whether device connected or not.
+
+Keyboard with other endpoints than boot keyboard may go wrong.
+ On my keyboard with mouse key the converter locks up when using mouse key function.
+
+Can't compile on Windows filesystem.
+ On Linux no problem.
+ Windows doesn't know difference between common/print.h and arduino/Print.h.
+ Change file name common/print.h to console.h ?
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitattributes b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitattributes
new file mode 100644
index 000000000..6238b035a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitattributes
@@ -0,0 +1,23 @@
+# Auto detect text files and perform LF normalization
+* text=auto
+* text eol=lf
+
+# Custom for Visual Studio
+*.cs diff=csharp
+*.sln merge=union
+*.csproj merge=union
+*.vbproj merge=union
+*.fsproj merge=union
+*.dbproj merge=union
+
+# Standard to msysgit
+*.doc diff=astextplain
+*.DOC diff=astextplain
+*.docx diff=astextplain
+*.DOCX diff=astextplain
+*.dot diff=astextplain
+*.DOT diff=astextplain
+*.pdf diff=astextplain
+*.PDF diff=astextplain
+*.rtf diff=astextplain
+*.RTF diff=astextplain
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitignore b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitignore
new file mode 100644
index 000000000..7e69f457b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitignore
@@ -0,0 +1,4 @@
+*.bak
+*.zip
+*.rar
+build/ \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitmodules b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitmodules
new file mode 100644
index 000000000..32a0783a8
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/.gitmodules
@@ -0,0 +1,12 @@
+[submodule "examples/testusbhostFAT/generic_storage"]
+ path = examples/testusbhostFAT/generic_storage
+ url = https://github.com/xxxajk/generic_storage
+[submodule "examples/testusbhostFAT/xmem2"]
+ path = examples/testusbhostFAT/xmem2
+ url = https://github.com/xxxajk/xmem2
+[submodule "examples/testusbhostFAT/Arduino_Makefile_master"]
+ path = examples/testusbhostFAT/Arduino_Makefile_master
+ url = https://github.com/xxxajk/Arduino_Makefile_master
+[submodule "examples/testusbhostFAT/RTClib"]
+ path = examples/testusbhostFAT/RTClib
+ url = https://github.com/xxxajk/RTClib
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTD.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTD.cpp
new file mode 100755
index 000000000..bcfba14b2
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTD.cpp
@@ -0,0 +1,1364 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "BTD.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+
+const uint8_t BTD::BTD_CONTROL_PIPE = 0;
+const uint8_t BTD::BTD_EVENT_PIPE = 1;
+const uint8_t BTD::BTD_DATAIN_PIPE = 2;
+const uint8_t BTD::BTD_DATAOUT_PIPE = 3;
+
+BTD::BTD(USB *p) :
+connectToWii(false),
+pairWithWii(false),
+connectToHIDDevice(false),
+pairWithHIDDevice(false),
+pUsb(p), // Pointer to USB class instance - mandatory
+bAddress(0), // Device address - mandatory
+bNumEP(1), // If config descriptor needs to be parsed
+qNextPollTime(0), // Reset NextPollTime
+pollInterval(0),
+bPollEnable(false) // Don't start polling before dongle is connected
+{
+ for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
+ btService[i] = NULL;
+
+ Initialize(); // Set all variables, endpoint structs etc. to default values
+
+ if(pUsb) // Register in USB subsystem
+ pUsb->RegisterDeviceClass(this); // Set devConfig[] entry
+}
+
+uint8_t BTD::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+ uint8_t buf[constBufSize];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+
+ Initialize(); // Set all variables, endpoint structs etc. to default values
+
+ AddressPool &addrPool = pUsb->GetAddressPool(); // Get memory address of USB device address pool
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nBTD ConfigureDevice"), 0x80);
+#endif
+
+ if(bAddress) { // Check if address has already been assigned to an instance
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress in use"), 0x80);
+#endif
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+ }
+
+ p = addrPool.GetUsbDevicePtr(0); // Get pointer to pseudo device with address 0 assigned
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ if(!p->epinfo) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nepinfo is null"), 0x80);
+#endif
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ oldep_ptr = p->epinfo; // Save old pointer to EP_RECORD of address 0
+ p->epinfo = epInfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->lowspeed = lowspeed;
+ rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
+
+ p->epinfo = oldep_ptr; // Restore p->epinfo
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ bAddress = addrPool.AllocAddress(parent, false, port); // Allocate new address according to device class
+
+ if(!bAddress) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nOut of address space"), 0x80);
+#endif
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+ }
+
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Extract Max Packet Size from device descriptor
+ epInfo[1].epAddr = udd->bNumConfigurations; // Steal and abuse from epInfo structure to save memory
+
+ VID = udd->idVendor;
+ PID = udd->idProduct;
+
+ return USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET;
+
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr(rcode);
+#endif
+ if(rcode != hrJERR)
+ rcode = USB_ERROR_FailGetDevDescr;
+ Release();
+ return rcode;
+};
+
+uint8_t BTD::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t rcode;
+ uint8_t num_of_conf = epInfo[1].epAddr; // Number of configurations
+ epInfo[1].epAddr = 0;
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nBTD Init"), 0x80);
+#endif
+ UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
+
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ delay(300); // Assign new address to the device
+
+ rcode = pUsb->setAddr(0, 0, bAddress); // Assign new address to the device
+ if(rcode) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nsetAddr: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+#endif
+ p->lowspeed = false;
+ goto Fail;
+ }
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nAddr: "), 0x80);
+ D_PrintHex<uint8_t > (bAddress, 0x80);
+#endif
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ p->lowspeed = lowspeed;
+
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); // Assign epInfo to epinfo pointer - only EP0 is known
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ if(VID == PS3_VID && (PID == PS3_PID || PID == PS3NAVIGATION_PID || PID == PS3MOVE_PID)) {
+ delay(100);
+ rcode = pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, 1); // We only need the Control endpoint, so we don't have to initialize the other endpoints of device
+ if(rcode)
+ goto FailSetConfDescr;
+
+#ifdef DEBUG_USB_HOST
+ if(PID == PS3_PID || PID == PS3NAVIGATION_PID) {
+ if(PID == PS3_PID)
+ Notify(PSTR("\r\nDualshock 3 Controller Connected"), 0x80);
+ else // It must be a navigation controller
+ Notify(PSTR("\r\nNavigation Controller Connected"), 0x80);
+ } else // It must be a Motion controller
+ Notify(PSTR("\r\nMotion Controller Connected"), 0x80);
+#endif
+
+ if(my_bdaddr[0] == 0x00 && my_bdaddr[1] == 0x00 && my_bdaddr[2] == 0x00 && my_bdaddr[3] == 0x00 && my_bdaddr[4] == 0x00 && my_bdaddr[5] == 0x00) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nPlease plug in the dongle before trying to pair with the PS3 Controller\r\nor set the Bluetooth address in the constructor of the PS3BT class"), 0x80);
+#endif
+ } else {
+ if(PID == PS3_PID || PID == PS3NAVIGATION_PID)
+ setBdaddr(my_bdaddr); // Set internal Bluetooth address
+ else
+ setMoveBdaddr(my_bdaddr); // Set internal Bluetooth address
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nBluetooth Address was set to: "), 0x80);
+ for(int8_t i = 5; i > 0; i--) {
+ D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
+ Notify(PSTR(":"), 0x80);
+ }
+ D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
+#endif
+ }
+
+ pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, 0); // Reset configuration value
+ pUsb->setAddr(bAddress, 0, 0); // Reset address
+ Release(); // Release device
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED; // Return
+ } else {
+ // Check if attached device is a Bluetooth dongle and fill endpoint data structure
+ // First interface in the configuration must have Bluetooth assigned Class/Subclass/Protocol
+ // And 3 endpoints - interrupt-IN, bulk-IN, bulk-OUT, not necessarily in this order
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ if(VID == IOGEAR_GBU521_VID && PID == IOGEAR_GBU521_PID) {
+ ConfigDescParser<USB_CLASS_VENDOR_SPECIFIC, WI_SUBCLASS_RF, WI_PROTOCOL_BT, CP_MASK_COMPARE_ALL> confDescrParser(this); // Needed for the IOGEAR GBU521
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
+ } else {
+ ConfigDescParser<USB_CLASS_WIRELESS_CTRL, WI_SUBCLASS_RF, WI_PROTOCOL_BT, CP_MASK_COMPARE_ALL> confDescrParser(this);
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
+ }
+ if(rcode) // Check error code
+ goto FailGetConfDescr;
+ if(bNumEP >= BTD_MAX_ENDPOINTS) // All endpoints extracted
+ break;
+ }
+
+ if(bNumEP < BTD_MAX_ENDPOINTS)
+ goto FailUnknownDevice;
+
+ // Assign epInfo to epinfo pointer - this time all 3 endpoins
+ rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bConfNum);
+ if(rcode)
+ goto FailSetConfDescr;
+
+ hci_num_reset_loops = 100; // only loop 100 times before trying to send the hci reset command
+ hci_counter = 0;
+ hci_state = HCI_INIT_STATE;
+ watingForConnection = false;
+ bPollEnable = true;
+
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nBluetooth Dongle Initialized"), 0x80);
+#endif
+ }
+ return 0; // Successful configuration
+
+ /* Diagnostic messages */
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailGetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetConfDescr();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+#endif
+ goto Fail;
+
+FailUnknownDevice:
+#ifdef DEBUG_USB_HOST
+ NotifyFailUnknownDevice(VID, PID);
+#endif
+ pUsb->setAddr(bAddress, 0, 0); // Reset address
+ rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+Fail:
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nBTD Init Failed, error code: "), 0x80);
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+void BTD::Initialize() {
+ uint8_t i;
+ for(i = 0; i < BTD_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }
+ for(i = 0; i < BTD_NUM_SERVICES; i++) {
+ if(btService[i])
+ btService[i]->Reset(); // Reset all Bluetooth services
+ }
+
+ connectToWii = false;
+ incomingWii = false;
+ connectToHIDDevice = false;
+ incomingHIDDevice = false;
+ incomingPS4 = false;
+ bAddress = 0; // Clear device address
+ bNumEP = 1; // Must have to be reset to 1
+ qNextPollTime = 0; // Reset next poll time
+ pollInterval = 0;
+ bPollEnable = false; // Don't start polling before dongle is connected
+}
+
+/* Extracts interrupt-IN, bulk-IN, bulk-OUT endpoint information from config descriptor */
+void BTD::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) {
+ //ErrorMessage<uint8_t>(PSTR("Conf.Val"),conf);
+ //ErrorMessage<uint8_t>(PSTR("Iface Num"),iface);
+ //ErrorMessage<uint8_t>(PSTR("Alt.Set"),alt);
+
+ if(alt) // Wrong interface - by BT spec, no alt setting
+ return;
+
+ bConfNum = conf;
+ uint8_t index;
+
+ if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) { // Interrupt In endpoint found
+ index = BTD_EVENT_PIPE;
+ epInfo[index].bmNakPower = USB_NAK_NOWAIT;
+ } else {
+ if((pep->bmAttributes & 0x02) == 2) // Bulk endpoint found
+ index = ((pep->bEndpointAddress & 0x80) == 0x80) ? BTD_DATAIN_PIPE : BTD_DATAOUT_PIPE;
+ else
+ return;
+ }
+
+ // Fill the rest of endpoint data structure
+ epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
+ epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
+#ifdef EXTRADEBUG
+ PrintEndpointDescriptor(pep);
+#endif
+ if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints
+ pollInterval = pep->bInterval;
+ bNumEP++;
+}
+
+void BTD::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nEndpoint descriptor:"), 0x80);
+ Notify(PSTR("\r\nLength:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
+ Notify(PSTR("\r\nType:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
+ Notify(PSTR("\r\nAddress:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
+ Notify(PSTR("\r\nAttributes:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
+ Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
+ D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
+ Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
+#endif
+}
+
+/* Performs a cleanup after failed Init() attempt */
+uint8_t BTD::Release() {
+ Initialize(); // Set all variables, endpoint structs etc. to default values
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+ return 0;
+}
+
+uint8_t BTD::Poll() {
+ if(!bPollEnable)
+ return 0;
+ if((long)(millis() - qNextPollTime) >= 0L) { // Don't poll if shorter than polling interval
+ qNextPollTime = millis() + pollInterval; // Set new poll time
+ HCI_event_task(); // Poll the HCI event pipe
+ HCI_task(); // HCI state machine
+ ACL_event_task(); // Poll the ACL input pipe too
+ }
+ return 0;
+}
+
+void BTD::disconnect() {
+ for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
+ if(btService[i])
+ btService[i]->disconnect();
+};
+
+void BTD::HCI_event_task() {
+ uint16_t length = BULK_MAXPKTSIZE; // Request more than 16 bytes anyway, the inTransfer routine will take care of this
+ uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_EVENT_PIPE ].epAddr, &length, hcibuf); // Input on endpoint 1
+
+ if(!rcode || rcode == hrNAK) { // Check for errors
+ switch(hcibuf[0]) { // Switch on event type
+ case EV_COMMAND_COMPLETE:
+ if(!hcibuf[5]) { // Check if command succeeded
+ hci_set_flag(HCI_FLAG_CMD_COMPLETE); // Set command complete flag
+ if((hcibuf[3] == 0x01) && (hcibuf[4] == 0x10)) { // Parameters from read local version information
+ hci_version = hcibuf[6]; // Used to check if it supports 2.0+EDR - see http://www.bluetooth.org/Technical/AssignedNumbers/hci.htm
+ hci_set_flag(HCI_FLAG_READ_VERSION);
+ } else if((hcibuf[3] == 0x09) && (hcibuf[4] == 0x10)) { // Parameters from read local bluetooth address
+ for(uint8_t i = 0; i < 6; i++)
+ my_bdaddr[i] = hcibuf[6 + i];
+ hci_set_flag(HCI_FLAG_READ_BDADDR);
+ }
+ }
+ break;
+
+ case EV_COMMAND_STATUS:
+ if(hcibuf[2]) { // Show status on serial if not OK
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHCI Command Failed: "), 0x80);
+ D_PrintHex<uint8_t > (hcibuf[2], 0x80);
+#endif
+ }
+ break;
+
+ case EV_INQUIRY_COMPLETE:
+ if(inquiry_counter >= 5 && (pairWithWii || pairWithHIDDevice)) {
+ inquiry_counter = 0;
+#ifdef DEBUG_USB_HOST
+ if(pairWithWii)
+ Notify(PSTR("\r\nCouldn't find Wiimote"), 0x80);
+ else
+ Notify(PSTR("\r\nCouldn't find HID device"), 0x80);
+#endif
+ connectToWii = false;
+ pairWithWii = false;
+ connectToHIDDevice = false;
+ pairWithHIDDevice = false;
+ hci_state = HCI_SCANNING_STATE;
+ }
+ inquiry_counter++;
+ break;
+
+ case EV_INQUIRY_RESULT:
+ if(hcibuf[2]) { // Check that there is more than zero responses
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nNumber of responses: "), 0x80);
+ Notify(hcibuf[2], 0x80);
+#endif
+ for(uint8_t i = 0; i < hcibuf[2]; i++) {
+ uint8_t offset = 8 * hcibuf[2] + 3 * i;
+
+ for(uint8_t j = 0; j < 3; j++)
+ classOfDevice[j] = hcibuf[j + 4 + offset];
+
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nClass of device: "), 0x80);
+ D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
+#endif
+
+ if(pairWithWii && classOfDevice[2] == 0x00 && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0x0C)) { // See http://wiibrew.org/wiki/Wiimote#SDP_information
+ checkRemoteName = true; // Check remote name to distinguish between the different controllers
+
+ for(uint8_t j = 0; j < 6; j++)
+ disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
+
+ hci_set_flag(HCI_FLAG_DEVICE_FOUND);
+ break;
+ } else if(pairWithHIDDevice && (classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad - see: http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html
+#ifdef DEBUG_USB_HOST
+ if(classOfDevice[0] & 0x80)
+ Notify(PSTR("\r\nMouse found"), 0x80);
+ if(classOfDevice[0] & 0x40)
+ Notify(PSTR("\r\nKeyboard found"), 0x80);
+ if(classOfDevice[0] & 0x08)
+ Notify(PSTR("\r\nGamepad found"), 0x80);
+#endif
+
+ for(uint8_t j = 0; j < 6; j++)
+ disc_bdaddr[j] = hcibuf[j + 3 + 6 * i];
+
+ hci_set_flag(HCI_FLAG_DEVICE_FOUND);
+ break;
+ }
+ }
+ }
+ break;
+
+ case EV_CONNECT_COMPLETE:
+ hci_set_flag(HCI_FLAG_CONNECT_EVENT);
+ if(!hcibuf[2]) { // Check if connected OK
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nConnection established"), 0x80);
+#endif
+ hci_handle = hcibuf[3] | ((hcibuf[4] & 0x0F) << 8); // Store the handle for the ACL connection
+ hci_set_flag(HCI_FLAG_CONNECT_COMPLETE); // Set connection complete flag
+ } else {
+ hci_state = HCI_CHECK_DEVICE_SERVICE;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nConnection Failed: "), 0x80);
+ D_PrintHex<uint8_t > (hcibuf[2], 0x80);
+#endif
+ }
+ break;
+
+ case EV_DISCONNECT_COMPLETE:
+ if(!hcibuf[2]) { // Check if disconnected OK
+ hci_set_flag(HCI_FLAG_DISCONNECT_COMPLETE); // Set disconnect command complete flag
+ hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE); // Clear connection complete flag
+ }
+ break;
+
+ case EV_REMOTE_NAME_COMPLETE:
+ if(!hcibuf[2]) { // Check if reading is OK
+ for(uint8_t i = 0; i < min(sizeof (remote_name), sizeof (hcibuf) - 9); i++) {
+ remote_name[i] = hcibuf[9 + i];
+ if(remote_name[i] == '\0') // End of string
+ break;
+ }
+ // TODO: Altid sæt '\0' i remote name!
+ hci_set_flag(HCI_FLAG_REMOTE_NAME_COMPLETE);
+ }
+ break;
+
+ case EV_INCOMING_CONNECT:
+ for(uint8_t i = 0; i < 6; i++)
+ disc_bdaddr[i] = hcibuf[i + 2];
+
+ for(uint8_t i = 0; i < 3; i++)
+ classOfDevice[i] = hcibuf[i + 8];
+
+ if((classOfDevice[1] & 0x05) && (classOfDevice[0] & 0xC8)) { // Check if it is a mouse, keyboard or a gamepad
+#ifdef DEBUG_USB_HOST
+ if(classOfDevice[0] & 0x80)
+ Notify(PSTR("\r\nMouse is connecting"), 0x80);
+ if(classOfDevice[0] & 0x40)
+ Notify(PSTR("\r\nKeyboard is connecting"), 0x80);
+ if(classOfDevice[0] & 0x08)
+ Notify(PSTR("\r\nGamepad is connecting"), 0x80);
+#endif
+ incomingHIDDevice = true;
+ }
+
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nClass of device: "), 0x80);
+ D_PrintHex<uint8_t > (classOfDevice[2], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (classOfDevice[1], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (classOfDevice[0], 0x80);
+#endif
+ hci_set_flag(HCI_FLAG_INCOMING_REQUEST);
+ break;
+
+ case EV_PIN_CODE_REQUEST:
+ if(pairWithWii) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nPairing with Wiimote"), 0x80);
+#endif
+ hci_pin_code_request_reply();
+ } else if(btdPin != NULL) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nBluetooth pin is set too: "), 0x80);
+ NotifyStr(btdPin, 0x80);
+#endif
+ hci_pin_code_request_reply();
+ } else {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nNo pin was set"), 0x80);
+#endif
+ hci_pin_code_negative_request_reply();
+ }
+ break;
+
+ case EV_LINK_KEY_REQUEST:
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReceived Key Request"), 0x80);
+#endif
+ hci_link_key_request_negative_reply();
+ break;
+
+ case EV_AUTHENTICATION_COMPLETE:
+ if(pairWithWii && !connectToWii) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nPairing successful with Wiimote"), 0x80);
+#endif
+ connectToWii = true; // Used to indicate to the Wii service, that it should connect to this device
+ } else if(pairWithHIDDevice && !connectToHIDDevice) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nPairing successful with HID device"), 0x80);
+#endif
+ connectToHIDDevice = true; // Used to indicate to the BTHID service, that it should connect to this device
+ }
+ break;
+ /* We will just ignore the following events */
+ case EV_NUM_COMPLETE_PKT:
+ case EV_ROLE_CHANGED:
+ case EV_PAGE_SCAN_REP_MODE:
+ case EV_LOOPBACK_COMMAND:
+ case EV_DATA_BUFFER_OVERFLOW:
+ case EV_CHANGE_CONNECTION_LINK:
+ case EV_MAX_SLOTS_CHANGE:
+ case EV_QOS_SETUP_COMPLETE:
+ case EV_LINK_KEY_NOTIFICATION:
+ case EV_ENCRYPTION_CHANGE:
+ case EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE:
+ break;
+#ifdef EXTRADEBUG
+ default:
+ if(hcibuf[0] != 0x00) {
+ Notify(PSTR("\r\nUnmanaged HCI Event: "), 0x80);
+ D_PrintHex<uint8_t > (hcibuf[0], 0x80);
+ }
+ break;
+#endif
+ } // Switch
+ }
+#ifdef EXTRADEBUG
+ else {
+ Notify(PSTR("\r\nHCI event error: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+ }
+#endif
+}
+
+/* Poll Bluetooth and print result */
+void BTD::HCI_task() {
+ switch(hci_state) {
+ case HCI_INIT_STATE:
+ hci_counter++;
+ if(hci_counter > hci_num_reset_loops) { // wait until we have looped x times to clear any old events
+ hci_reset();
+ hci_state = HCI_RESET_STATE;
+ hci_counter = 0;
+ }
+ break;
+
+ case HCI_RESET_STATE:
+ hci_counter++;
+ if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) {
+ hci_counter = 0;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHCI Reset complete"), 0x80);
+#endif
+ hci_state = HCI_CLASS_STATE;
+ hci_write_class_of_device();
+ } else if(hci_counter > hci_num_reset_loops) {
+ hci_num_reset_loops *= 10;
+ if(hci_num_reset_loops > 2000)
+ hci_num_reset_loops = 2000;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nNo response to HCI Reset"), 0x80);
+#endif
+ hci_state = HCI_INIT_STATE;
+ hci_counter = 0;
+ }
+ break;
+
+ case HCI_CLASS_STATE:
+ if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWrite class of device"), 0x80);
+#endif
+ hci_state = HCI_BDADDR_STATE;
+ hci_read_bdaddr();
+ }
+ break;
+
+ case HCI_BDADDR_STATE:
+ if(hci_check_flag(HCI_FLAG_READ_BDADDR)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nLocal Bluetooth Address: "), 0x80);
+ for(int8_t i = 5; i > 0; i--) {
+ D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
+ Notify(PSTR(":"), 0x80);
+ }
+ D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
+#endif
+ hci_read_local_version_information();
+ hci_state = HCI_LOCAL_VERSION_STATE;
+ }
+ break;
+
+ case HCI_LOCAL_VERSION_STATE: // The local version is used by the PS3BT class
+ if(hci_check_flag(HCI_FLAG_READ_VERSION)) {
+ if(btdName != NULL) {
+ hci_set_local_name(btdName);
+ hci_state = HCI_SET_NAME_STATE;
+ } else
+ hci_state = HCI_CHECK_DEVICE_SERVICE;
+ }
+ break;
+
+ case HCI_SET_NAME_STATE:
+ if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nThe name is set to: "), 0x80);
+ NotifyStr(btdName, 0x80);
+#endif
+ hci_state = HCI_CHECK_DEVICE_SERVICE;
+ }
+ break;
+
+ case HCI_CHECK_DEVICE_SERVICE:
+ if(pairWithHIDDevice || pairWithWii) { // Check if it should try to connect to a Wiimote
+#ifdef DEBUG_USB_HOST
+ if(pairWithWii)
+ Notify(PSTR("\r\nStarting inquiry\r\nPress 1 & 2 on the Wiimote\r\nOr press the SYNC button if you are using a Wii U Pro Controller or a Wii Balance Board"), 0x80);
+ else
+ Notify(PSTR("\r\nPlease enable discovery of your device"), 0x80);
+#endif
+ hci_inquiry();
+ hci_state = HCI_INQUIRY_STATE;
+ } else
+ hci_state = HCI_SCANNING_STATE; // Don't try to connect to a Wiimote
+ break;
+
+ case HCI_INQUIRY_STATE:
+ if(hci_check_flag(HCI_FLAG_DEVICE_FOUND)) {
+ hci_inquiry_cancel(); // Stop inquiry
+#ifdef DEBUG_USB_HOST
+ if(pairWithWii)
+ Notify(PSTR("\r\nWiimote found"), 0x80);
+ else
+ Notify(PSTR("\r\nHID device found"), 0x80);
+
+ Notify(PSTR("\r\nNow just create the instance like so:"), 0x80);
+ if(pairWithWii)
+ Notify(PSTR("\r\nWII Wii(&Btd);"), 0x80);
+ else
+ Notify(PSTR("\r\nBTHID bthid(&Btd);"), 0x80);
+
+ Notify(PSTR("\r\nAnd then press any button on the "), 0x80);
+ if(pairWithWii)
+ Notify(PSTR("Wiimote"), 0x80);
+ else
+ Notify(PSTR("device"), 0x80);
+#endif
+ if(checkRemoteName) {
+ hci_remote_name(); // We need to know the name to distinguish between the Wiimote, the new Wiimote with Motion Plus inside, a Wii U Pro Controller and a Wii Balance Board
+ hci_state = HCI_REMOTE_NAME_STATE;
+ } else
+ hci_state = HCI_CONNECT_DEVICE_STATE;
+ }
+ break;
+
+ case HCI_CONNECT_DEVICE_STATE:
+ if(hci_check_flag(HCI_FLAG_CMD_COMPLETE)) {
+#ifdef DEBUG_USB_HOST
+ if(pairWithWii)
+ Notify(PSTR("\r\nConnecting to Wiimote"), 0x80);
+ else
+ Notify(PSTR("\r\nConnecting to HID device"), 0x80);
+#endif
+ checkRemoteName = false;
+ hci_connect();
+ hci_state = HCI_CONNECTED_DEVICE_STATE;
+ }
+ break;
+
+ case HCI_CONNECTED_DEVICE_STATE:
+ if(hci_check_flag(HCI_FLAG_CONNECT_EVENT)) {
+ if(hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) {
+#ifdef DEBUG_USB_HOST
+ if(pairWithWii)
+ Notify(PSTR("\r\nConnected to Wiimote"), 0x80);
+ else
+ Notify(PSTR("\r\nConnected to HID device"), 0x80);
+#endif
+ hci_authentication_request(); // This will start the pairing with the Wiimote
+ hci_state = HCI_SCANNING_STATE;
+ } else {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nTrying to connect one more time..."), 0x80);
+#endif
+ hci_connect(); // Try to connect one more time
+ }
+ }
+ break;
+
+ case HCI_SCANNING_STATE:
+ if(!connectToWii && !pairWithWii && !connectToHIDDevice && !pairWithHIDDevice) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWait For Incoming Connection Request"), 0x80);
+#endif
+ hci_write_scan_enable();
+ watingForConnection = true;
+ hci_state = HCI_CONNECT_IN_STATE;
+ }
+ break;
+
+ case HCI_CONNECT_IN_STATE:
+ if(hci_check_flag(HCI_FLAG_INCOMING_REQUEST)) {
+ watingForConnection = false;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nIncoming Connection Request"), 0x80);
+#endif
+ hci_remote_name();
+ hci_state = HCI_REMOTE_NAME_STATE;
+ } else if(hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE))
+ hci_state = HCI_DISCONNECT_STATE;
+ break;
+
+ case HCI_REMOTE_NAME_STATE:
+ if(hci_check_flag(HCI_FLAG_REMOTE_NAME_COMPLETE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nRemote Name: "), 0x80);
+ for(uint8_t i = 0; i < strlen(remote_name); i++)
+ Notifyc(remote_name[i], 0x80);
+#endif
+ if(strncmp((const char*)remote_name, "Nintendo", 8) == 0) {
+ incomingWii = true;
+ motionPlusInside = false;
+ wiiUProController = false;
+ pairWiiUsingSync = false;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWiimote is connecting"), 0x80);
+#endif
+ if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-TR", 22) == 0) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR(" with Motion Plus Inside"), 0x80);
+#endif
+ motionPlusInside = true;
+ } else if(strncmp((const char*)remote_name, "Nintendo RVL-CNT-01-UC", 22) == 0) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR(" - Wii U Pro Controller"), 0x80);
+#endif
+ wiiUProController = motionPlusInside = pairWiiUsingSync = true;
+ } else if(strncmp((const char*)remote_name, "Nintendo RVL-WBC-01", 19) == 0) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR(" - Wii Balance Board"), 0x80);
+#endif
+ pairWiiUsingSync = true;
+ }
+ }
+ if(classOfDevice[2] == 0 && classOfDevice[1] == 0x25 && classOfDevice[0] == 0x08 && strncmp((const char*)remote_name, "Wireless Controller", 19) == 0) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nPS4 controller is connecting"), 0x80);
+#endif
+ incomingPS4 = true;
+ }
+ if(pairWithWii && checkRemoteName)
+ hci_state = HCI_CONNECT_DEVICE_STATE;
+ else {
+ hci_accept_connection();
+ hci_state = HCI_CONNECTED_STATE;
+ }
+ }
+ break;
+
+ case HCI_CONNECTED_STATE:
+ if(hci_check_flag(HCI_FLAG_CONNECT_COMPLETE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nConnected to Device: "), 0x80);
+ for(int8_t i = 5; i > 0; i--) {
+ D_PrintHex<uint8_t > (disc_bdaddr[i], 0x80);
+ Notify(PSTR(":"), 0x80);
+ }
+ D_PrintHex<uint8_t > (disc_bdaddr[0], 0x80);
+#endif
+ if(incomingPS4)
+ connectToHIDDevice = true; // We should always connect to the PS4 controller
+
+ // Clear these flags for a new connection
+ l2capConnectionClaimed = false;
+ sdpConnectionClaimed = false;
+ rfcommConnectionClaimed = false;
+
+ hci_event_flag = 0;
+ hci_state = HCI_DONE_STATE;
+ }
+ break;
+
+ case HCI_DONE_STATE:
+ hci_counter++;
+ if(hci_counter > 1000) { // Wait until we have looped 1000 times to make sure that the L2CAP connection has been started
+ hci_counter = 0;
+ hci_state = HCI_SCANNING_STATE;
+ }
+ break;
+
+ case HCI_DISCONNECT_STATE:
+ if(hci_check_flag(HCI_FLAG_DISCONNECT_COMPLETE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHCI Disconnected from Device"), 0x80);
+#endif
+ hci_event_flag = 0; // Clear all flags
+
+ // Reset all buffers
+ memset(hcibuf, 0, BULK_MAXPKTSIZE);
+ memset(l2capinbuf, 0, BULK_MAXPKTSIZE);
+
+ connectToWii = incomingWii = pairWithWii = false;
+ connectToHIDDevice = incomingHIDDevice = pairWithHIDDevice = checkRemoteName = false;
+ incomingPS4 = false;
+
+ hci_state = HCI_SCANNING_STATE;
+ }
+ break;
+ default:
+ break;
+ }
+}
+
+void BTD::ACL_event_task() {
+ uint16_t length = BULK_MAXPKTSIZE;
+ uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ BTD_DATAIN_PIPE ].epAddr, &length, l2capinbuf); // Input on endpoint 2
+
+ if(!rcode) { // Check for errors
+ if(length > 0) { // Check if any data was read
+ for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
+ if(btService[i])
+ btService[i]->ACLData(l2capinbuf);
+ }
+ }
+ }
+#ifdef EXTRADEBUG
+ else if(rcode != hrNAK) {
+ Notify(PSTR("\r\nACL data in error: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+ }
+#endif
+ for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++)
+ if(btService[i])
+ btService[i]->Run();
+}
+
+/************************************************************/
+/* HCI Commands */
+
+/************************************************************/
+void BTD::HCI_Command(uint8_t* data, uint16_t nbytes) {
+ hci_clear_flag(HCI_FLAG_CMD_COMPLETE);
+ pUsb->ctrlReq(bAddress, epInfo[ BTD_CONTROL_PIPE ].epAddr, bmREQ_HCI_OUT, 0x00, 0x00, 0x00, 0x00, nbytes, nbytes, data, NULL);
+}
+
+void BTD::hci_reset() {
+ hci_event_flag = 0; // Clear all the flags
+ hcibuf[0] = 0x03; // HCI OCF = 3
+ hcibuf[1] = 0x03 << 2; // HCI OGF = 3
+ hcibuf[2] = 0x00;
+
+ HCI_Command(hcibuf, 3);
+}
+
+void BTD::hci_write_scan_enable() {
+ hci_clear_flag(HCI_FLAG_INCOMING_REQUEST);
+ hcibuf[0] = 0x1A; // HCI OCF = 1A
+ hcibuf[1] = 0x03 << 2; // HCI OGF = 3
+ hcibuf[2] = 0x01; // parameter length = 1
+ if(btdName != NULL)
+ hcibuf[3] = 0x03; // Inquiry Scan enabled. Page Scan enabled.
+ else
+ hcibuf[3] = 0x02; // Inquiry Scan disabled. Page Scan enabled.
+
+ HCI_Command(hcibuf, 4);
+}
+
+void BTD::hci_write_scan_disable() {
+ hcibuf[0] = 0x1A; // HCI OCF = 1A
+ hcibuf[1] = 0x03 << 2; // HCI OGF = 3
+ hcibuf[2] = 0x01; // parameter length = 1
+ hcibuf[3] = 0x00; // Inquiry Scan disabled. Page Scan disabled.
+
+ HCI_Command(hcibuf, 4);
+}
+
+void BTD::hci_read_bdaddr() {
+ hci_clear_flag(HCI_FLAG_READ_BDADDR);
+ hcibuf[0] = 0x09; // HCI OCF = 9
+ hcibuf[1] = 0x04 << 2; // HCI OGF = 4
+ hcibuf[2] = 0x00;
+
+ HCI_Command(hcibuf, 3);
+}
+
+void BTD::hci_read_local_version_information() {
+ hci_clear_flag(HCI_FLAG_READ_VERSION);
+ hcibuf[0] = 0x01; // HCI OCF = 1
+ hcibuf[1] = 0x04 << 2; // HCI OGF = 4
+ hcibuf[2] = 0x00;
+
+ HCI_Command(hcibuf, 3);
+}
+
+void BTD::hci_accept_connection() {
+ hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE);
+ hcibuf[0] = 0x09; // HCI OCF = 9
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x07; // parameter length 7
+ hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
+ hcibuf[4] = disc_bdaddr[1];
+ hcibuf[5] = disc_bdaddr[2];
+ hcibuf[6] = disc_bdaddr[3];
+ hcibuf[7] = disc_bdaddr[4];
+ hcibuf[8] = disc_bdaddr[5];
+ hcibuf[9] = 0x00; // Switch role to master
+
+ HCI_Command(hcibuf, 10);
+}
+
+void BTD::hci_remote_name() {
+ hci_clear_flag(HCI_FLAG_REMOTE_NAME_COMPLETE);
+ hcibuf[0] = 0x19; // HCI OCF = 19
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x0A; // parameter length = 10
+ hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
+ hcibuf[4] = disc_bdaddr[1];
+ hcibuf[5] = disc_bdaddr[2];
+ hcibuf[6] = disc_bdaddr[3];
+ hcibuf[7] = disc_bdaddr[4];
+ hcibuf[8] = disc_bdaddr[5];
+ hcibuf[9] = 0x01; // Page Scan Repetition Mode
+ hcibuf[10] = 0x00; // Reserved
+ hcibuf[11] = 0x00; // Clock offset - low byte
+ hcibuf[12] = 0x00; // Clock offset - high byte
+
+ HCI_Command(hcibuf, 13);
+}
+
+void BTD::hci_set_local_name(const char* name) {
+ hcibuf[0] = 0x13; // HCI OCF = 13
+ hcibuf[1] = 0x03 << 2; // HCI OGF = 3
+ hcibuf[2] = strlen(name) + 1; // parameter length = the length of the string + end byte
+ uint8_t i;
+ for(i = 0; i < strlen(name); i++)
+ hcibuf[i + 3] = name[i];
+ hcibuf[i + 3] = 0x00; // End of string
+
+ HCI_Command(hcibuf, 4 + strlen(name));
+}
+
+void BTD::hci_inquiry() {
+ hci_clear_flag(HCI_FLAG_DEVICE_FOUND);
+ hcibuf[0] = 0x01;
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x05; // Parameter Total Length = 5
+ hcibuf[3] = 0x33; // LAP: Genera/Unlimited Inquiry Access Code (GIAC = 0x9E8B33) - see https://www.bluetooth.org/Technical/AssignedNumbers/baseband.htm
+ hcibuf[4] = 0x8B;
+ hcibuf[5] = 0x9E;
+ hcibuf[6] = 0x30; // Inquiry time = 61.44 sec (maximum)
+ hcibuf[7] = 0x0A; // 10 number of responses
+
+ HCI_Command(hcibuf, 8);
+}
+
+void BTD::hci_inquiry_cancel() {
+ hcibuf[0] = 0x02;
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x00; // Parameter Total Length = 0
+
+ HCI_Command(hcibuf, 3);
+}
+
+void BTD::hci_connect() {
+ hci_connect(disc_bdaddr); // Use last discovered device
+}
+
+void BTD::hci_connect(uint8_t *bdaddr) {
+ hci_clear_flag(HCI_FLAG_CONNECT_COMPLETE | HCI_FLAG_CONNECT_EVENT);
+ hcibuf[0] = 0x05;
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x0D; // parameter Total Length = 13
+ hcibuf[3] = bdaddr[0]; // 6 octet bdaddr (LSB)
+ hcibuf[4] = bdaddr[1];
+ hcibuf[5] = bdaddr[2];
+ hcibuf[6] = bdaddr[3];
+ hcibuf[7] = bdaddr[4];
+ hcibuf[8] = bdaddr[5];
+ hcibuf[9] = 0x18; // DM1 or DH1 may be used
+ hcibuf[10] = 0xCC; // DM3, DH3, DM5, DH5 may be used
+ hcibuf[11] = 0x01; // Page repetition mode R1
+ hcibuf[12] = 0x00; // Reserved
+ hcibuf[13] = 0x00; // Clock offset
+ hcibuf[14] = 0x00; // Invalid clock offset
+ hcibuf[15] = 0x00; // Do not allow role switch
+
+ HCI_Command(hcibuf, 16);
+}
+
+void BTD::hci_pin_code_request_reply() {
+ hcibuf[0] = 0x0D; // HCI OCF = 0D
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x17; // parameter length 23
+ hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
+ hcibuf[4] = disc_bdaddr[1];
+ hcibuf[5] = disc_bdaddr[2];
+ hcibuf[6] = disc_bdaddr[3];
+ hcibuf[7] = disc_bdaddr[4];
+ hcibuf[8] = disc_bdaddr[5];
+ if(pairWithWii) {
+ hcibuf[9] = 6; // Pin length is the length of the Bluetooth address
+ if(pairWiiUsingSync) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nParing with Wii controller via SYNC"), 0x80);
+#endif
+ for(uint8_t i = 0; i < 6; i++)
+ hcibuf[10 + i] = my_bdaddr[i]; // The pin is the Bluetooth dongles Bluetooth address backwards
+ } else {
+ for(uint8_t i = 0; i < 6; i++)
+ hcibuf[10 + i] = disc_bdaddr[i]; // The pin is the Wiimote's Bluetooth address backwards
+ }
+ for(uint8_t i = 16; i < 26; i++)
+ hcibuf[i] = 0x00; // The rest should be 0
+ } else {
+ hcibuf[9] = strlen(btdPin); // Length of pin
+ uint8_t i;
+ for(i = 0; i < strlen(btdPin); i++) // The maximum size of the pin is 16
+ hcibuf[i + 10] = btdPin[i];
+ for(; i < 16; i++)
+ hcibuf[i + 10] = 0x00; // The rest should be 0
+ }
+
+ HCI_Command(hcibuf, 26);
+}
+
+void BTD::hci_pin_code_negative_request_reply() {
+ hcibuf[0] = 0x0E; // HCI OCF = 0E
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x06; // parameter length 6
+ hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
+ hcibuf[4] = disc_bdaddr[1];
+ hcibuf[5] = disc_bdaddr[2];
+ hcibuf[6] = disc_bdaddr[3];
+ hcibuf[7] = disc_bdaddr[4];
+ hcibuf[8] = disc_bdaddr[5];
+
+ HCI_Command(hcibuf, 9);
+}
+
+void BTD::hci_link_key_request_negative_reply() {
+ hcibuf[0] = 0x0C; // HCI OCF = 0C
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x06; // parameter length 6
+ hcibuf[3] = disc_bdaddr[0]; // 6 octet bdaddr
+ hcibuf[4] = disc_bdaddr[1];
+ hcibuf[5] = disc_bdaddr[2];
+ hcibuf[6] = disc_bdaddr[3];
+ hcibuf[7] = disc_bdaddr[4];
+ hcibuf[8] = disc_bdaddr[5];
+
+ HCI_Command(hcibuf, 9);
+}
+
+void BTD::hci_authentication_request() {
+ hcibuf[0] = 0x11; // HCI OCF = 11
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x02; // parameter length = 2
+ hcibuf[3] = (uint8_t)(hci_handle & 0xFF); //connection handle - low byte
+ hcibuf[4] = (uint8_t)((hci_handle >> 8) & 0x0F); //connection handle - high byte
+
+ HCI_Command(hcibuf, 5);
+}
+
+void BTD::hci_disconnect(uint16_t handle) { // This is called by the different services
+ hci_clear_flag(HCI_FLAG_DISCONNECT_COMPLETE);
+ hcibuf[0] = 0x06; // HCI OCF = 6
+ hcibuf[1] = 0x01 << 2; // HCI OGF = 1
+ hcibuf[2] = 0x03; // parameter length = 3
+ hcibuf[3] = (uint8_t)(handle & 0xFF); //connection handle - low byte
+ hcibuf[4] = (uint8_t)((handle >> 8) & 0x0F); //connection handle - high byte
+ hcibuf[5] = 0x13; // reason
+
+ HCI_Command(hcibuf, 6);
+}
+
+void BTD::hci_write_class_of_device() { // See http://bluetooth-pentest.narod.ru/software/bluetooth_class_of_device-service_generator.html
+ hcibuf[0] = 0x24; // HCI OCF = 24
+ hcibuf[1] = 0x03 << 2; // HCI OGF = 3
+ hcibuf[2] = 0x03; // parameter length = 3
+ hcibuf[3] = 0x04; // Robot
+ hcibuf[4] = 0x08; // Toy
+ hcibuf[5] = 0x00;
+
+ HCI_Command(hcibuf, 6);
+}
+/*******************************************************************
+ * *
+ * HCI ACL Data Packet *
+ * *
+ * buf[0] buf[1] buf[2] buf[3]
+ * 0 4 8 11 12 16 24 31 MSB
+ * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
+ * | HCI Handle |PB |BC | Data Total Length | HCI ACL Data Packet
+ * .-+-+-+-+-+-+-+-|-+-+-+-|-+-|-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
+ *
+ * buf[4] buf[5] buf[6] buf[7]
+ * 0 8 16 31 MSB
+ * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
+ * | Length | Channel ID | Basic L2CAP header
+ * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
+ *
+ * buf[8] buf[9] buf[10] buf[11]
+ * 0 8 16 31 MSB
+ * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-.
+ * | Code | Identifier | Length | Control frame (C-frame)
+ * .-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-|-+-+-+-+-+-+-+-. (signaling packet format)
+ */
+/************************************************************/
+/* L2CAP Commands */
+
+/************************************************************/
+void BTD::L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow, uint8_t channelHigh) {
+ uint8_t buf[8 + nbytes];
+ buf[0] = (uint8_t)(handle & 0xff); // HCI handle with PB,BC flag
+ buf[1] = (uint8_t)(((handle >> 8) & 0x0f) | 0x20);
+ buf[2] = (uint8_t)((4 + nbytes) & 0xff); // HCI ACL total data length
+ buf[3] = (uint8_t)((4 + nbytes) >> 8);
+ buf[4] = (uint8_t)(nbytes & 0xff); // L2CAP header: Length
+ buf[5] = (uint8_t)(nbytes >> 8);
+ buf[6] = channelLow;
+ buf[7] = channelHigh;
+
+ for(uint16_t i = 0; i < nbytes; i++) // L2CAP C-frame
+ buf[8 + i] = data[i];
+
+ uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ BTD_DATAOUT_PIPE ].epAddr, (8 + nbytes), buf);
+ if(rcode) {
+ delay(100); // This small delay prevents it from overflowing if it fails
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nError sending L2CAP message: 0x"), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+ Notify(PSTR(" - Channel ID: "), 0x80);
+ D_PrintHex<uint8_t > (channelHigh, 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (channelLow, 0x80);
+#endif
+ }
+}
+
+void BTD::l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm) {
+ l2capoutbuf[0] = L2CAP_CMD_CONNECTION_REQUEST; // Code
+ l2capoutbuf[1] = rxid; // Identifier
+ l2capoutbuf[2] = 0x04; // Length
+ l2capoutbuf[3] = 0x00;
+ l2capoutbuf[4] = (uint8_t)(psm & 0xff); // PSM
+ l2capoutbuf[5] = (uint8_t)(psm >> 8);
+ l2capoutbuf[6] = scid[0]; // Source CID
+ l2capoutbuf[7] = scid[1];
+
+ L2CAP_Command(handle, l2capoutbuf, 8);
+}
+
+void BTD::l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result) {
+ l2capoutbuf[0] = L2CAP_CMD_CONNECTION_RESPONSE; // Code
+ l2capoutbuf[1] = rxid; // Identifier
+ l2capoutbuf[2] = 0x08; // Length
+ l2capoutbuf[3] = 0x00;
+ l2capoutbuf[4] = dcid[0]; // Destination CID
+ l2capoutbuf[5] = dcid[1];
+ l2capoutbuf[6] = scid[0]; // Source CID
+ l2capoutbuf[7] = scid[1];
+ l2capoutbuf[8] = result; // Result: Pending or Success
+ l2capoutbuf[9] = 0x00;
+ l2capoutbuf[10] = 0x00; // No further information
+ l2capoutbuf[11] = 0x00;
+
+ L2CAP_Command(handle, l2capoutbuf, 12);
+}
+
+void BTD::l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid) {
+ l2capoutbuf[0] = L2CAP_CMD_CONFIG_REQUEST; // Code
+ l2capoutbuf[1] = rxid; // Identifier
+ l2capoutbuf[2] = 0x08; // Length
+ l2capoutbuf[3] = 0x00;
+ l2capoutbuf[4] = dcid[0]; // Destination CID
+ l2capoutbuf[5] = dcid[1];
+ l2capoutbuf[6] = 0x00; // Flags
+ l2capoutbuf[7] = 0x00;
+ l2capoutbuf[8] = 0x01; // Config Opt: type = MTU (Maximum Transmission Unit) - Hint
+ l2capoutbuf[9] = 0x02; // Config Opt: length
+ l2capoutbuf[10] = 0xFF; // MTU
+ l2capoutbuf[11] = 0xFF;
+
+ L2CAP_Command(handle, l2capoutbuf, 12);
+}
+
+void BTD::l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid) {
+ l2capoutbuf[0] = L2CAP_CMD_CONFIG_RESPONSE; // Code
+ l2capoutbuf[1] = rxid; // Identifier
+ l2capoutbuf[2] = 0x0A; // Length
+ l2capoutbuf[3] = 0x00;
+ l2capoutbuf[4] = scid[0]; // Source CID
+ l2capoutbuf[5] = scid[1];
+ l2capoutbuf[6] = 0x00; // Flag
+ l2capoutbuf[7] = 0x00;
+ l2capoutbuf[8] = 0x00; // Result
+ l2capoutbuf[9] = 0x00;
+ l2capoutbuf[10] = 0x01; // Config
+ l2capoutbuf[11] = 0x02;
+ l2capoutbuf[12] = 0xA0;
+ l2capoutbuf[13] = 0x02;
+
+ L2CAP_Command(handle, l2capoutbuf, 14);
+}
+
+void BTD::l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
+ l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_REQUEST; // Code
+ l2capoutbuf[1] = rxid; // Identifier
+ l2capoutbuf[2] = 0x04; // Length
+ l2capoutbuf[3] = 0x00;
+ l2capoutbuf[4] = dcid[0];
+ l2capoutbuf[5] = dcid[1];
+ l2capoutbuf[6] = scid[0];
+ l2capoutbuf[7] = scid[1];
+
+ L2CAP_Command(handle, l2capoutbuf, 8);
+}
+
+void BTD::l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid) {
+ l2capoutbuf[0] = L2CAP_CMD_DISCONNECT_RESPONSE; // Code
+ l2capoutbuf[1] = rxid; // Identifier
+ l2capoutbuf[2] = 0x04; // Length
+ l2capoutbuf[3] = 0x00;
+ l2capoutbuf[4] = dcid[0];
+ l2capoutbuf[5] = dcid[1];
+ l2capoutbuf[6] = scid[0];
+ l2capoutbuf[7] = scid[1];
+
+ L2CAP_Command(handle, l2capoutbuf, 8);
+}
+
+void BTD::l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh) {
+ l2capoutbuf[0] = L2CAP_CMD_INFORMATION_RESPONSE; // Code
+ l2capoutbuf[1] = rxid; // Identifier
+ l2capoutbuf[2] = 0x08; // Length
+ l2capoutbuf[3] = 0x00;
+ l2capoutbuf[4] = infoTypeLow;
+ l2capoutbuf[5] = infoTypeHigh;
+ l2capoutbuf[6] = 0x00; // Result = success
+ l2capoutbuf[7] = 0x00; // Result = success
+ l2capoutbuf[8] = 0x00;
+ l2capoutbuf[9] = 0x00;
+ l2capoutbuf[10] = 0x00;
+ l2capoutbuf[11] = 0x00;
+
+ L2CAP_Command(handle, l2capoutbuf, 12);
+}
+
+/* PS3 Commands - only set Bluetooth address is implemented in this library */
+void BTD::setBdaddr(uint8_t* bdaddr) {
+ /* Set the internal Bluetooth address */
+ uint8_t buf[8];
+ buf[0] = 0x01;
+ buf[1] = 0x00;
+
+ for(uint8_t i = 0; i < 6; i++)
+ buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first
+
+ // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0xF5), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
+ pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
+}
+
+void BTD::setMoveBdaddr(uint8_t* bdaddr) {
+ /* Set the internal Bluetooth address */
+ uint8_t buf[11];
+ buf[0] = 0x05;
+ buf[7] = 0x10;
+ buf[8] = 0x01;
+ buf[9] = 0x02;
+ buf[10] = 0x12;
+
+ for(uint8_t i = 0; i < 6; i++)
+ buf[i + 1] = bdaddr[i];
+
+ // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x05), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
+ pUsb->ctrlReq(bAddress, epInfo[BTD_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x05, 0x03, 0x00, 11, 11, buf, NULL);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTD.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTD.h
new file mode 100755
index 000000000..6549c30c9
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTD.h
@@ -0,0 +1,620 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _btd_h_
+#define _btd_h_
+
+#include "Usb.h"
+#include "hid.h"
+
+//PID and VID of the Sony PS3 devices
+#define PS3_VID 0x054C // Sony Corporation
+#define PS3_PID 0x0268 // PS3 Controller DualShock 3
+#define PS3NAVIGATION_PID 0x042F // Navigation controller
+#define PS3MOVE_PID 0x03D5 // Motion controller
+
+#define IOGEAR_GBU521_VID 0x0A5C // The IOGEAR GBU521 dongle does not presents itself correctly, so we have to check for it manually
+#define IOGEAR_GBU521_PID 0x21E8
+
+/* Bluetooth dongle data taken from descriptors */
+#define BULK_MAXPKTSIZE 64 // Max size for ACL data
+
+// Used in control endpoint header for HCI Commands
+#define bmREQ_HCI_OUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE
+
+/* Bluetooth HCI states for hci_task() */
+#define HCI_INIT_STATE 0
+#define HCI_RESET_STATE 1
+#define HCI_CLASS_STATE 2
+#define HCI_BDADDR_STATE 3
+#define HCI_LOCAL_VERSION_STATE 4
+#define HCI_SET_NAME_STATE 5
+#define HCI_CHECK_DEVICE_SERVICE 6
+
+#define HCI_INQUIRY_STATE 7 // These three states are only used if it should pair and connect to a device
+#define HCI_CONNECT_DEVICE_STATE 8
+#define HCI_CONNECTED_DEVICE_STATE 9
+
+#define HCI_SCANNING_STATE 10
+#define HCI_CONNECT_IN_STATE 11
+#define HCI_REMOTE_NAME_STATE 12
+#define HCI_CONNECTED_STATE 13
+#define HCI_DISABLE_SCAN_STATE 14
+#define HCI_DONE_STATE 15
+#define HCI_DISCONNECT_STATE 16
+
+/* HCI event flags*/
+#define HCI_FLAG_CMD_COMPLETE (1UL << 0)
+#define HCI_FLAG_CONNECT_COMPLETE (1UL << 1)
+#define HCI_FLAG_DISCONNECT_COMPLETE (1UL << 2)
+#define HCI_FLAG_REMOTE_NAME_COMPLETE (1UL << 3)
+#define HCI_FLAG_INCOMING_REQUEST (1UL << 4)
+#define HCI_FLAG_READ_BDADDR (1UL << 5)
+#define HCI_FLAG_READ_VERSION (1UL << 6)
+#define HCI_FLAG_DEVICE_FOUND (1UL << 7)
+#define HCI_FLAG_CONNECT_EVENT (1UL << 8)
+
+/* Macros for HCI event flag tests */
+#define hci_check_flag(flag) (hci_event_flag & (flag))
+#define hci_set_flag(flag) (hci_event_flag |= (flag))
+#define hci_clear_flag(flag) (hci_event_flag &= ~(flag))
+
+/* HCI Events managed */
+#define EV_INQUIRY_COMPLETE 0x01
+#define EV_INQUIRY_RESULT 0x02
+#define EV_CONNECT_COMPLETE 0x03
+#define EV_INCOMING_CONNECT 0x04
+#define EV_DISCONNECT_COMPLETE 0x05
+#define EV_AUTHENTICATION_COMPLETE 0x06
+#define EV_REMOTE_NAME_COMPLETE 0x07
+#define EV_ENCRYPTION_CHANGE 0x08
+#define EV_CHANGE_CONNECTION_LINK 0x09
+#define EV_ROLE_CHANGED 0x12
+#define EV_NUM_COMPLETE_PKT 0x13
+#define EV_PIN_CODE_REQUEST 0x16
+#define EV_LINK_KEY_REQUEST 0x17
+#define EV_LINK_KEY_NOTIFICATION 0x18
+#define EV_DATA_BUFFER_OVERFLOW 0x1A
+#define EV_MAX_SLOTS_CHANGE 0x1B
+#define EV_READ_REMOTE_VERSION_INFORMATION_COMPLETE 0x0C
+#define EV_QOS_SETUP_COMPLETE 0x0D
+#define EV_COMMAND_COMPLETE 0x0E
+#define EV_COMMAND_STATUS 0x0F
+#define EV_LOOPBACK_COMMAND 0x19
+#define EV_PAGE_SCAN_REP_MODE 0x20
+
+/* Bluetooth states for the different Bluetooth drivers */
+#define L2CAP_WAIT 0
+#define L2CAP_DONE 1
+
+/* Used for HID Control channel */
+#define L2CAP_CONTROL_CONNECT_REQUEST 2
+#define L2CAP_CONTROL_CONFIG_REQUEST 3
+#define L2CAP_CONTROL_SUCCESS 4
+#define L2CAP_CONTROL_DISCONNECT 5
+
+/* Used for HID Interrupt channel */
+#define L2CAP_INTERRUPT_SETUP 6
+#define L2CAP_INTERRUPT_CONNECT_REQUEST 7
+#define L2CAP_INTERRUPT_CONFIG_REQUEST 8
+#define L2CAP_INTERRUPT_DISCONNECT 9
+
+/* Used for SDP channel */
+#define L2CAP_SDP_WAIT 10
+#define L2CAP_SDP_SUCCESS 11
+
+/* Used for RFCOMM channel */
+#define L2CAP_RFCOMM_WAIT 12
+#define L2CAP_RFCOMM_SUCCESS 13
+
+#define L2CAP_DISCONNECT_RESPONSE 14 // Used for both SDP and RFCOMM channel
+
+/* Bluetooth states used by some drivers */
+#define TURN_ON_LED 17
+#define PS3_ENABLE_SIXAXIS 18
+#define WII_CHECK_MOTION_PLUS_STATE 19
+#define WII_CHECK_EXTENSION_STATE 20
+#define WII_INIT_MOTION_PLUS_STATE 21
+
+/* L2CAP event flags for HID Control channel */
+#define L2CAP_FLAG_CONNECTION_CONTROL_REQUEST (1UL << 0)
+#define L2CAP_FLAG_CONFIG_CONTROL_SUCCESS (1UL << 1)
+#define L2CAP_FLAG_CONTROL_CONNECTED (1UL << 2)
+#define L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE (1UL << 3)
+
+/* L2CAP event flags for HID Interrupt channel */
+#define L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST (1UL << 4)
+#define L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS (1UL << 5)
+#define L2CAP_FLAG_INTERRUPT_CONNECTED (1UL << 6)
+#define L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE (1UL << 7)
+
+/* L2CAP event flags for SDP channel */
+#define L2CAP_FLAG_CONNECTION_SDP_REQUEST (1UL << 8)
+#define L2CAP_FLAG_CONFIG_SDP_SUCCESS (1UL << 9)
+#define L2CAP_FLAG_DISCONNECT_SDP_REQUEST (1UL << 10)
+
+/* L2CAP event flags for RFCOMM channel */
+#define L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST (1UL << 11)
+#define L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS (1UL << 12)
+#define L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST (1UL << 13)
+
+#define L2CAP_FLAG_DISCONNECT_RESPONSE (1UL << 14)
+
+/* Macros for L2CAP event flag tests */
+#define l2cap_check_flag(flag) (l2cap_event_flag & (flag))
+#define l2cap_set_flag(flag) (l2cap_event_flag |= (flag))
+#define l2cap_clear_flag(flag) (l2cap_event_flag &= ~(flag))
+
+/* L2CAP signaling commands */
+#define L2CAP_CMD_COMMAND_REJECT 0x01
+#define L2CAP_CMD_CONNECTION_REQUEST 0x02
+#define L2CAP_CMD_CONNECTION_RESPONSE 0x03
+#define L2CAP_CMD_CONFIG_REQUEST 0x04
+#define L2CAP_CMD_CONFIG_RESPONSE 0x05
+#define L2CAP_CMD_DISCONNECT_REQUEST 0x06
+#define L2CAP_CMD_DISCONNECT_RESPONSE 0x07
+#define L2CAP_CMD_INFORMATION_REQUEST 0x0A
+#define L2CAP_CMD_INFORMATION_RESPONSE 0x0B
+
+// Used For Connection Response - Remember to Include High Byte
+#define PENDING 0x01
+#define SUCCESSFUL 0x00
+
+/* Bluetooth L2CAP PSM - see http://www.bluetooth.org/Technical/AssignedNumbers/logical_link.htm */
+#define SDP_PSM 0x01 // Service Discovery Protocol PSM Value
+#define RFCOMM_PSM 0x03 // RFCOMM PSM Value
+#define HID_CTRL_PSM 0x11 // HID_Control PSM Value
+#define HID_INTR_PSM 0x13 // HID_Interrupt PSM Value
+
+// Used to determine if it is a Bluetooth dongle
+#define WI_SUBCLASS_RF 0x01 // RF Controller
+#define WI_PROTOCOL_BT 0x01 // Bluetooth Programming Interface
+
+#define BTD_MAX_ENDPOINTS 4
+#define BTD_NUM_SERVICES 4 // Max number of Bluetooth services - if you need more than 4 simply increase this number
+
+#define PAIR 1
+
+class BluetoothService;
+
+/**
+ * The Bluetooth Dongle class will take care of all the USB communication
+ * and then pass the data to the BluetoothService classes.
+ */
+class BTD : public USBDeviceConfig, public UsbConfigXtracter {
+public:
+ /**
+ * Constructor for the BTD class.
+ * @param p Pointer to USB class instance.
+ */
+ BTD(USB *p);
+
+ /** @name USBDeviceConfig implementation */
+ /**
+ * Address assignment and basic initialization is done here.
+ * @param parent Hub number.
+ * @param port Port number on the hub.
+ * @param lowspeed Speed of the device.
+ * @return 0 on success.
+ */
+ uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed);
+ /**
+ * Initialize the Bluetooth dongle.
+ * @param parent Hub number.
+ * @param port Port number on the hub.
+ * @param lowspeed Speed of the device.
+ * @return 0 on success.
+ */
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ /**
+ * Release the USB device.
+ * @return 0 on success.
+ */
+ uint8_t Release();
+ /**
+ * Poll the USB Input endpoints and run the state machines.
+ * @return 0 on success.
+ */
+ uint8_t Poll();
+
+ /**
+ * Get the device address.
+ * @return The device address.
+ */
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ /**
+ * Used to check if the dongle has been initialized.
+ * @return True if it's ready.
+ */
+ virtual bool isReady() {
+ return bPollEnable;
+ };
+
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param klass The device's USB class.
+ * @return Returns true if the device's USB class matches this driver.
+ */
+ virtual bool DEVCLASSOK(uint8_t klass) {
+ return (klass == USB_CLASS_WIRELESS_CTRL);
+ };
+
+ /**
+ * Used by the USB core to check what this driver support.
+ * Used to set the Bluetooth address into the PS3 controllers.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ if(vid == IOGEAR_GBU521_VID && pid == IOGEAR_GBU521_PID)
+ return true;
+ if(my_bdaddr[0] != 0x00 || my_bdaddr[1] != 0x00 || my_bdaddr[2] != 0x00 || my_bdaddr[3] != 0x00 || my_bdaddr[4] != 0x00 || my_bdaddr[5] != 0x00) { // Check if Bluetooth address is set
+ if(vid == PS3_VID && (pid == PS3_PID || pid == PS3NAVIGATION_PID || pid == PS3MOVE_PID))
+ return true;
+ }
+ return false;
+ };
+ /**@}*/
+
+ /** @name UsbConfigXtracter implementation */
+ /**
+ * UsbConfigXtracter implementation, used to extract endpoint information.
+ * @param conf Configuration value.
+ * @param iface Interface number.
+ * @param alt Alternate setting.
+ * @param proto Interface Protocol.
+ * @param ep Endpoint Descriptor.
+ */
+ void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
+ /**@}*/
+
+ /** Disconnects both the L2CAP Channel and the HCI Connection for all Bluetooth services. */
+ void disconnect();
+
+ /**
+ * Register Bluetooth dongle members/services.
+ * @param pService Pointer to BluetoothService class instance.
+ * @return The service ID on success or -1 on fail.
+ */
+ int8_t registerBluetoothService(BluetoothService *pService) {
+ for(uint8_t i = 0; i < BTD_NUM_SERVICES; i++) {
+ if(!btService[i]) {
+ btService[i] = pService;
+ return i; // Return ID
+ }
+ }
+ return -1; // Error registering BluetoothService
+ };
+
+ /** @name HCI Commands */
+ /**
+ * Used to send a HCI Command.
+ * @param data Data to send.
+ * @param nbytes Number of bytes to send.
+ */
+ void HCI_Command(uint8_t* data, uint16_t nbytes);
+ /** Reset the Bluetooth dongle. */
+ void hci_reset();
+ /** Read the Bluetooth address of the dongle. */
+ void hci_read_bdaddr();
+ /** Read the HCI Version of the Bluetooth dongle. */
+ void hci_read_local_version_information();
+ /**
+ * Set the local name of the Bluetooth dongle.
+ * @param name Desired name.
+ */
+ void hci_set_local_name(const char* name);
+ /** Enable visibility to other Bluetooth devices. */
+ void hci_write_scan_enable();
+ /** Disable visibility to other Bluetooth devices. */
+ void hci_write_scan_disable();
+ /** Read the remote devices name. */
+ void hci_remote_name();
+ /** Accept the connection with the Bluetooth device. */
+ void hci_accept_connection();
+ /**
+ * Disconnect the HCI connection.
+ * @param handle The HCI Handle for the connection.
+ */
+ void hci_disconnect(uint16_t handle);
+ /**
+ * Respond with the pin for the connection.
+ * The pin is automatically set for the Wii library,
+ * but can be customized for the SPP library.
+ */
+ void hci_pin_code_request_reply();
+ /** Respons when no pin was set. */
+ void hci_pin_code_negative_request_reply();
+ /**
+ * Command is used to reply to a Link Key Request event from the BR/EDR Controller
+ * if the Host does not have a stored Link Key for the connection.
+ */
+ void hci_link_key_request_negative_reply();
+ /** Used to try to authenticate with the remote device. */
+ void hci_authentication_request();
+ /** Start a HCI inquiry. */
+ void hci_inquiry();
+ /** Cancel a HCI inquiry. */
+ void hci_inquiry_cancel();
+ /** Connect to last device communicated with. */
+ void hci_connect();
+ /**
+ * Connect to device.
+ * @param bdaddr Bluetooth address of the device.
+ */
+ void hci_connect(uint8_t *bdaddr);
+ /** Used to a set the class of the device. */
+ void hci_write_class_of_device();
+ /**@}*/
+
+ /** @name L2CAP Commands */
+ /**
+ * Used to send L2CAP Commands.
+ * @param handle HCI Handle.
+ * @param data Data to send.
+ * @param nbytes Number of bytes to send.
+ * @param channelLow,channelHigh Low and high byte of channel to send to.
+ * If argument is omitted then the Standard L2CAP header: Channel ID (0x01) for ACL-U will be used.
+ */
+ void L2CAP_Command(uint16_t handle, uint8_t* data, uint8_t nbytes, uint8_t channelLow = 0x01, uint8_t channelHigh = 0x00);
+ /**
+ * L2CAP Connection Request.
+ * @param handle HCI handle.
+ * @param rxid Identifier.
+ * @param scid Source Channel Identifier.
+ * @param psm Protocol/Service Multiplexer - see: https://www.bluetooth.org/Technical/AssignedNumbers/logical_link.htm.
+ */
+ void l2cap_connection_request(uint16_t handle, uint8_t rxid, uint8_t* scid, uint16_t psm);
+ /**
+ * L2CAP Connection Response.
+ * @param handle HCI handle.
+ * @param rxid Identifier.
+ * @param dcid Destination Channel Identifier.
+ * @param scid Source Channel Identifier.
+ * @param result Result - First send ::PENDING and then ::SUCCESSFUL.
+ */
+ void l2cap_connection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid, uint8_t result);
+ /**
+ * L2CAP Config Request.
+ * @param handle HCI Handle.
+ * @param rxid Identifier.
+ * @param dcid Destination Channel Identifier.
+ */
+ void l2cap_config_request(uint16_t handle, uint8_t rxid, uint8_t* dcid);
+ /**
+ * L2CAP Config Response.
+ * @param handle HCI Handle.
+ * @param rxid Identifier.
+ * @param scid Source Channel Identifier.
+ */
+ void l2cap_config_response(uint16_t handle, uint8_t rxid, uint8_t* scid);
+ /**
+ * L2CAP Disconnection Request.
+ * @param handle HCI Handle.
+ * @param rxid Identifier.
+ * @param dcid Device Channel Identifier.
+ * @param scid Source Channel Identifier.
+ */
+ void l2cap_disconnection_request(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid);
+ /**
+ * L2CAP Disconnection Response.
+ * @param handle HCI Handle.
+ * @param rxid Identifier.
+ * @param dcid Device Channel Identifier.
+ * @param scid Source Channel Identifier.
+ */
+ void l2cap_disconnection_response(uint16_t handle, uint8_t rxid, uint8_t* dcid, uint8_t* scid);
+ /**
+ * L2CAP Information Response.
+ * @param handle HCI Handle.
+ * @param rxid Identifier.
+ * @param infoTypeLow,infoTypeHigh Infotype.
+ */
+ void l2cap_information_response(uint16_t handle, uint8_t rxid, uint8_t infoTypeLow, uint8_t infoTypeHigh);
+ /**@}*/
+
+ /** Use this to see if it is waiting for a incoming connection. */
+ bool watingForConnection;
+ /** This is used by the service to know when to store the device information. */
+ bool l2capConnectionClaimed;
+ /** This is used by the SPP library to claim the current SDP incoming request. */
+ bool sdpConnectionClaimed;
+ /** This is used by the SPP library to claim the current RFCOMM incoming request. */
+ bool rfcommConnectionClaimed;
+
+ /** The name you wish to make the dongle show up as. It is set automatically by the SPP library. */
+ const char* btdName;
+ /** The pin you wish to make the dongle use for authentication. It is set automatically by the SPP and BTHID library. */
+ const char* btdPin;
+
+ /** The bluetooth dongles Bluetooth address. */
+ uint8_t my_bdaddr[6];
+ /** HCI handle for the last connection. */
+ uint16_t hci_handle;
+ /** Last incoming devices Bluetooth address. */
+ uint8_t disc_bdaddr[6];
+ /** First 30 chars of last remote name. */
+ char remote_name[30];
+ /**
+ * The supported HCI Version read from the Bluetooth dongle.
+ * Used by the PS3BT library to check the HCI Version of the Bluetooth dongle,
+ * it should be at least 3 to work properly with the library.
+ */
+ uint8_t hci_version;
+
+ /** Call this function to pair with a Wiimote */
+ void pairWithWiimote() {
+ pairWithWii = true;
+ hci_state = HCI_CHECK_DEVICE_SERVICE;
+ };
+ /** Used to only send the ACL data to the Wiimote. */
+ bool connectToWii;
+ /** True if a Wiimote is connecting. */
+ bool incomingWii;
+ /** True when it should pair with a Wiimote. */
+ bool pairWithWii;
+ /** True if it's the new Wiimote with the Motion Plus Inside or a Wii U Pro Controller. */
+ bool motionPlusInside;
+ /** True if it's a Wii U Pro Controller. */
+ bool wiiUProController;
+
+ /** Call this function to pair with a Wiimote */
+ void pairWithHID() {
+ pairWithHIDDevice = true;
+ hci_state = HCI_CHECK_DEVICE_SERVICE;
+ };
+ /** Used to only send the ACL data to the Wiimote. */
+ bool connectToHIDDevice;
+ /** True if a Wiimote is connecting. */
+ bool incomingHIDDevice;
+ /** True when it should pair with a device like a mouse or keyboard. */
+ bool pairWithHIDDevice;
+
+ /**
+ * Read the poll interval taken from the endpoint descriptors.
+ * @return The poll interval in ms.
+ */
+ uint8_t readPollInterval() {
+ return pollInterval;
+ };
+
+protected:
+ /** Pointer to USB class instance. */
+ USB *pUsb;
+ /** Device address. */
+ uint8_t bAddress;
+ /** Endpoint info structure. */
+ EpInfo epInfo[BTD_MAX_ENDPOINTS];
+
+ /** Configuration number. */
+ uint8_t bConfNum;
+ /** Total number of endpoints in the configuration. */
+ uint8_t bNumEP;
+ /** Next poll time based on poll interval taken from the USB descriptor. */
+ uint32_t qNextPollTime;
+
+ /** Bluetooth dongle control endpoint. */
+ static const uint8_t BTD_CONTROL_PIPE;
+ /** HCI event endpoint index. */
+ static const uint8_t BTD_EVENT_PIPE;
+ /** ACL In endpoint index. */
+ static const uint8_t BTD_DATAIN_PIPE;
+ /** ACL Out endpoint index. */
+ static const uint8_t BTD_DATAOUT_PIPE;
+
+ /**
+ * Used to print the USB Endpoint Descriptor.
+ * @param ep_ptr Pointer to USB Endpoint Descriptor.
+ */
+ void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
+
+private:
+ void Initialize(); // Set all variables, endpoint structs etc. to default values
+ BluetoothService *btService[BTD_NUM_SERVICES];
+
+ uint16_t PID, VID; // PID and VID of device connected
+
+ uint8_t pollInterval;
+ bool bPollEnable;
+
+ bool pairWiiUsingSync; // True if paring was done using the Wii SYNC button.
+ bool checkRemoteName; // Used to check remote device's name before connecting.
+ bool incomingPS4; // True if a PS4 controller is connecting
+ uint8_t classOfDevice[3]; // Class of device of last device
+
+ /* Variables used by high level HCI task */
+ uint8_t hci_state; // Current state of Bluetooth HCI connection
+ uint16_t hci_counter; // Counter used for Bluetooth HCI reset loops
+ uint16_t hci_num_reset_loops; // This value indicate how many times it should read before trying to reset
+ uint16_t hci_event_flag; // HCI flags of received Bluetooth events
+ uint8_t inquiry_counter;
+
+ uint8_t hcibuf[BULK_MAXPKTSIZE]; // General purpose buffer for HCI data
+ uint8_t l2capinbuf[BULK_MAXPKTSIZE]; // General purpose buffer for L2CAP in data
+ uint8_t l2capoutbuf[14]; // General purpose buffer for L2CAP out data
+
+ /* State machines */
+ void HCI_event_task(); // Poll the HCI event pipe
+ void HCI_task(); // HCI state machine
+ void ACL_event_task(); // ACL input pipe
+
+ /* Used to set the Bluetooth Address internally to the PS3 Controllers */
+ void setBdaddr(uint8_t* BDADDR);
+ void setMoveBdaddr(uint8_t* BDADDR);
+};
+
+/** All Bluetooth services should inherit this class. */
+class BluetoothService {
+public:
+ BluetoothService(BTD *p) : pBtd(p) {
+ if(pBtd)
+ pBtd->registerBluetoothService(this); // Register it as a Bluetooth service
+ };
+ /**
+ * Used to pass acldata to the Bluetooth service.
+ * @param ACLData Pointer to the incoming acldata.
+ */
+ virtual void ACLData(uint8_t* ACLData) = 0;
+ /** Used to run the different state machines in the Bluetooth service. */
+ virtual void Run() = 0;
+ /** Used to reset the Bluetooth service. */
+ virtual void Reset() = 0;
+ /** Used to disconnect both the L2CAP Channel and the HCI Connection for the Bluetooth service. */
+ virtual void disconnect() = 0;
+
+ /**
+ * Used to call your own function when the device is successfully initialized.
+ * @param funcOnInit Function to call.
+ */
+ void attachOnInit(void (*funcOnInit)(void)) {
+ pFuncOnInit = funcOnInit; // TODO: This really belong in a class of it's own as it is repeated several times
+ };
+
+protected:
+ /**
+ * Called when a device is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ virtual void onInit() = 0;
+
+ /** Used to check if the incoming L2CAP data matches the HCI Handle */
+ bool checkHciHandle(uint8_t *buf, uint16_t handle) {
+ return (buf[0] == (handle & 0xFF)) && (buf[1] == ((handle >> 8) | 0x20));
+ }
+
+ /** Pointer to function called in onInit(). */
+ void (*pFuncOnInit)(void);
+
+ /** Pointer to BTD instance. */
+ BTD *pBtd;
+
+ /** The HCI Handle for the connection. */
+ uint16_t hci_handle;
+
+ /** L2CAP flags of received Bluetooth events. */
+ uint32_t l2cap_event_flag;
+
+ /** Identifier for L2CAP commands. */
+ uint8_t identifier;
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTHID.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTHID.cpp
new file mode 100644
index 000000000..bfa9202c3
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTHID.cpp
@@ -0,0 +1,399 @@
+/* Copyright (C) 2013 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "BTHID.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report send by the HID device
+
+BTHID::BTHID(BTD *p, bool pair, const char *pin) :
+BluetoothService(p), // Pointer to USB class instance - mandatory
+protocolMode(HID_BOOT_PROTOCOL) {
+ for(uint8_t i = 0; i < NUM_PARSERS; i++)
+ pRptParser[i] = NULL;
+
+ pBtd->pairWithHIDDevice = pair;
+ pBtd->btdPin = pin;
+
+ /* Set device cid for the control and intterrupt channelse - LSB */
+ control_dcid[0] = 0x70; // 0x0070
+ control_dcid[1] = 0x00;
+ interrupt_dcid[0] = 0x71; // 0x0071
+ interrupt_dcid[1] = 0x00;
+
+ Reset();
+}
+
+void BTHID::Reset() {
+ connected = false;
+ activeConnection = false;
+ l2cap_event_flag = 0; // Reset flags
+ l2cap_state = L2CAP_WAIT;
+ ResetBTHID();
+}
+
+void BTHID::disconnect() { // Use this void to disconnect the device
+ // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection
+ pBtd->l2cap_disconnection_request(hci_handle, ++identifier, interrupt_scid, interrupt_dcid);
+ Reset();
+ l2cap_state = L2CAP_INTERRUPT_DISCONNECT;
+}
+
+void BTHID::ACLData(uint8_t* l2capinbuf) {
+ if(!pBtd->l2capConnectionClaimed && pBtd->incomingHIDDevice && !connected && !activeConnection) {
+ if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
+ if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
+ pBtd->incomingHIDDevice = false;
+ pBtd->l2capConnectionClaimed = true; // Claim that the incoming connection belongs to this service
+ activeConnection = true;
+ hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
+ l2cap_state = L2CAP_WAIT;
+ }
+ }
+ }
+
+ if(checkHciHandle(l2capinbuf, hci_handle)) { // acl_handle_ok
+ if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U
+ if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+#endif
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_RESPONSE) {
+ if(((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) && ((l2capinbuf[18] | (l2capinbuf[19] << 8)) == SUCCESSFUL)) { // Success
+ if(l2capinbuf[14] == control_dcid[0] && l2capinbuf[15] == control_dcid[1]) {
+ //Notify(PSTR("\r\nHID Control Connection Complete"), 0x80);
+ identifier = l2capinbuf[9];
+ control_scid[0] = l2capinbuf[12];
+ control_scid[1] = l2capinbuf[13];
+ l2cap_set_flag(L2CAP_FLAG_CONTROL_CONNECTED);
+ } else if(l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) {
+ //Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80);
+ identifier = l2capinbuf[9];
+ interrupt_scid[0] = l2capinbuf[12];
+ interrupt_scid[1] = l2capinbuf[13];
+ l2cap_set_flag(L2CAP_FLAG_INTERRUPT_CONNECTED);
+ }
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ Notify(PSTR(" SCID: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+ Notify(PSTR(" Identifier: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
+#endif
+ if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
+ identifier = l2capinbuf[9];
+ control_scid[0] = l2capinbuf[14];
+ control_scid[1] = l2capinbuf[15];
+ l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST);
+ } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) {
+ identifier = l2capinbuf[9];
+ interrupt_scid[0] = l2capinbuf[14];
+ interrupt_scid[1] = l2capinbuf[15];
+ l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) {
+ if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+ //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS);
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+ //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS);
+ }
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) {
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+ //Notify(PSTR("\r\nHID Control Configuration Request"), 0x80);
+ pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], control_scid);
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+ //Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80);
+ pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], interrupt_scid);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) {
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnect Request: Control Channel"), 0x80);
+#endif
+ identifier = l2capinbuf[9];
+ pBtd->l2cap_disconnection_response(hci_handle, identifier, control_dcid, control_scid);
+ Reset();
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80);
+#endif
+ identifier = l2capinbuf[9];
+ pBtd->l2cap_disconnection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid);
+ Reset();
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) {
+ if(l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) {
+ //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE);
+ } else if(l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) {
+ //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE);
+ }
+ }
+#ifdef EXTRADEBUG
+ else {
+ identifier = l2capinbuf[9];
+ Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
+ }
+#endif
+ } else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt
+#ifdef PRINTREPORT
+ Notify(PSTR("\r\nL2CAP Interrupt: "), 0x80);
+ for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
+ D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+#endif
+ if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT
+ uint16_t length = ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]);
+ ParseBTHIDData((uint8_t)(length - 1), &l2capinbuf[9]);
+
+ switch(l2capinbuf[9]) {
+ case 0x01: // Keyboard or Joystick events
+ if(pRptParser[KEYBOARD_PARSER_ID])
+ pRptParser[KEYBOARD_PARSER_ID]->Parse(reinterpret_cast<HID *>(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance
+ break;
+
+ case 0x02: // Mouse events
+ if(pRptParser[MOUSE_PARSER_ID])
+ pRptParser[MOUSE_PARSER_ID]->Parse(reinterpret_cast<HID *>(this), 0, (uint8_t)(length - 2), &l2capinbuf[10]); // Use reinterpret_cast again to extract the instance
+ break;
+#ifdef EXTRADEBUG
+ default:
+ Notify(PSTR("\r\nUnknown Report type: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
+ break;
+#endif
+ }
+ }
+ } else if(l2capinbuf[6] == control_dcid[0] && l2capinbuf[7] == control_dcid[1]) { // l2cap_control
+#ifdef PRINTREPORT
+ Notify(PSTR("\r\nL2CAP Control: "), 0x80);
+ for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
+ D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+#endif
+ }
+#ifdef EXTRADEBUG
+ else {
+ Notify(PSTR("\r\nUnsupported L2CAP Data - Channel ID: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[7], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[6], 0x80);
+
+ Notify(PSTR("\r\nData: "), 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+ for(uint16_t i = 0; i < ((uint16_t)l2capinbuf[5] << 8 | l2capinbuf[4]); i++) {
+ D_PrintHex<uint8_t > (l2capinbuf[i + 8], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ }
+#endif
+ L2CAP_task();
+ }
+}
+
+void BTHID::L2CAP_task() {
+ switch(l2cap_state) {
+ /* These states are used if the HID device is the host */
+ case L2CAP_CONTROL_SUCCESS:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80);
+#endif
+ setProtocol(); // Set protocol before establishing HID interrupt channel
+ l2cap_state = L2CAP_INTERRUPT_SETUP;
+ }
+ break;
+
+ case L2CAP_INTERRUPT_SETUP:
+ if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80);
+#endif
+ pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, PENDING);
+ delay(1);
+ pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, SUCCESSFUL);
+ identifier++;
+ delay(1);
+ pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid);
+
+ l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
+ }
+ break;
+
+ /* These states are used if the Arduino is the host */
+ case L2CAP_CONTROL_CONNECT_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend HID Control Config Request"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_config_request(hci_handle, identifier, control_scid);
+ l2cap_state = L2CAP_CONTROL_CONFIG_REQUEST;
+ }
+ break;
+
+ case L2CAP_CONTROL_CONFIG_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) {
+ setProtocol(); // Set protocol before establishing HID interrupt channel
+ delay(1); // Short delay between commands - just to be sure
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend HID Interrupt Connection Request"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_connection_request(hci_handle, identifier, interrupt_dcid, HID_INTR_PSM);
+ l2cap_state = L2CAP_INTERRUPT_CONNECT_REQUEST;
+ }
+ break;
+
+ case L2CAP_INTERRUPT_CONNECT_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid);
+ l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
+ }
+ break;
+
+ case L2CAP_INTERRUPT_CONFIG_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Channels Established"), 0x80);
+#endif
+ pBtd->connectToHIDDevice = false;
+ pBtd->pairWithHIDDevice = false;
+ connected = true;
+ onInit();
+ l2cap_state = L2CAP_DONE;
+ }
+ break;
+
+ case L2CAP_DONE:
+ break;
+
+ case L2CAP_INTERRUPT_DISCONNECT:
+ if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_disconnection_request(hci_handle, identifier, control_scid, control_dcid);
+ l2cap_state = L2CAP_CONTROL_DISCONNECT;
+ }
+ break;
+
+ case L2CAP_CONTROL_DISCONNECT:
+ if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected Control Channel"), 0x80);
+#endif
+ pBtd->hci_disconnect(hci_handle);
+ hci_handle = -1; // Reset handle
+ l2cap_event_flag = 0; // Reset flags
+ l2cap_state = L2CAP_WAIT;
+ }
+ break;
+ }
+}
+
+void BTHID::Run() {
+ switch(l2cap_state) {
+ case L2CAP_WAIT:
+ if(pBtd->connectToHIDDevice && !pBtd->l2capConnectionClaimed && !connected && !activeConnection) {
+ pBtd->l2capConnectionClaimed = true;
+ activeConnection = true;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend HID Control Connection Request"), 0x80);
+#endif
+ hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
+ l2cap_event_flag = 0; // Reset flags
+ identifier = 0;
+ pBtd->l2cap_connection_request(hci_handle, identifier, control_dcid, HID_CTRL_PSM);
+ l2cap_state = L2CAP_CONTROL_CONNECT_REQUEST;
+ } else if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80);
+#endif
+ pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, PENDING);
+ delay(1);
+ pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, SUCCESSFUL);
+ identifier++;
+ delay(1);
+ pBtd->l2cap_config_request(hci_handle, identifier, control_scid);
+ l2cap_state = L2CAP_CONTROL_SUCCESS;
+ }
+ break;
+ }
+}
+
+/************************************************************/
+/* HID Commands */
+
+/************************************************************/
+void BTHID::setProtocol() {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSet protocol mode: "), 0x80);
+ D_PrintHex<uint8_t > (protocolMode, 0x80);
+#endif
+ if (protocolMode != HID_BOOT_PROTOCOL && protocolMode != HID_RPT_PROTOCOL) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nNot a valid protocol mode. Using Boot protocol instead."), 0x80);
+#endif
+ protocolMode = HID_BOOT_PROTOCOL; // Use Boot Protocol by default
+ }
+ uint8_t command = 0x70 | protocolMode; // Set Protocol, see Bluetooth HID specs page 33
+ pBtd->L2CAP_Command(hci_handle, &command, 1, control_scid[0], control_scid[1]);
+}
+
+void BTHID::setLeds(uint8_t data) {
+ uint8_t buf[3];
+ buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+ buf[1] = 0x01; // Report ID
+ buf[2] = data;
+ pBtd->L2CAP_Command(hci_handle, buf, 3, interrupt_scid[0], interrupt_scid[1]);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTHID.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTHID.h
new file mode 100644
index 000000000..1a7d8687c
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/BTHID.h
@@ -0,0 +1,155 @@
+/* Copyright (C) 2013 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _bthid_h_
+#define _bthid_h_
+
+#include "BTD.h"
+#include "hidboot.h"
+
+#define KEYBOARD_PARSER_ID 0
+#define MOUSE_PARSER_ID 1
+#define NUM_PARSERS 2
+
+/** This BluetoothService class implements support for Bluetooth HID devices. */
+class BTHID : public BluetoothService {
+public:
+ /**
+ * Constructor for the BTHID class.
+ * @param p Pointer to the BTD class instance.
+ * @param pair Set this to true in order to pair with the device. If the argument is omitted then it will not pair with it. One can use ::PAIR to set it to true.
+ * @param pin Write the pin to BTD#btdPin. If argument is omitted, then "0000" will be used.
+ */
+ BTHID(BTD *p, bool pair = false, const char *pin = "0000");
+
+ /** @name BluetoothService implementation */
+ /** Used this to disconnect the devices. */
+ void disconnect();
+ /**@}*/
+
+ /**
+ * Get HIDReportParser.
+ * @param id ID of parser.
+ * @return Returns the corresponding HIDReportParser. Returns NULL if id is not valid.
+ */
+ HIDReportParser *GetReportParser(uint8_t id) {
+ if (id >= NUM_PARSERS)
+ return NULL;
+ return pRptParser[id];
+ };
+
+ /**
+ * Set HIDReportParser to be used.
+ * @param id Id of parser.
+ * @param prs Pointer to HIDReportParser.
+ * @return Returns true if the HIDReportParser is set. False otherwise.
+ */
+ bool SetReportParser(uint8_t id, HIDReportParser *prs) {
+ if (id >= NUM_PARSERS)
+ return false;
+ pRptParser[id] = prs;
+ return true;
+ };
+
+ /**
+ * Set HID protocol mode.
+ * @param mode HID protocol to use. Either HID_BOOT_PROTOCOL or HID_RPT_PROTOCOL.
+ */
+ void setProtocolMode(uint8_t mode) {
+ protocolMode = mode;
+ };
+
+ /**
+ * Used to set the leds on a keyboard.
+ * @param data See KBDLEDS in hidboot.h
+ */
+ void setLeds(uint8_t data);
+
+ /** True if a device is connected */
+ bool connected;
+
+ /** Call this to start the paring sequence with a device */
+ void pair(void) {
+ if(pBtd)
+ pBtd->pairWithHID();
+ };
+
+protected:
+ /** @name BluetoothService implementation */
+ /**
+ * Used to pass acldata to the services.
+ * @param ACLData Incoming acldata.
+ */
+ void ACLData(uint8_t* ACLData);
+ /** Used to run part of the state machine. */
+ void Run();
+ /** Use this to reset the service. */
+ void Reset();
+ /**
+ * Called when a device is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ void onInit() {
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ OnInitBTHID();
+ };
+ /**@}*/
+
+ /** @name Overridable functions */
+ /**
+ * Used to parse Bluetooth HID data to any class that inherits this class.
+ * @param len The length of the incoming data.
+ * @param buf Pointer to the data buffer.
+ */
+ virtual void ParseBTHIDData(uint8_t len, uint8_t *buf) {
+ return;
+ };
+ /** Called when a device is connected */
+ virtual void OnInitBTHID() {
+ return;
+ };
+ /** Used to reset any buffers in the class that inherits this */
+ virtual void ResetBTHID() {
+ return;
+ }
+ /**@}*/
+
+ /** L2CAP source CID for HID_Control */
+ uint8_t control_scid[2];
+
+ /** L2CAP source CID for HID_Interrupt */
+ uint8_t interrupt_scid[2];
+
+private:
+ HIDReportParser *pRptParser[NUM_PARSERS]; // Pointer to HIDReportParsers.
+
+ /** Set report protocol. */
+ void setProtocol();
+ uint8_t protocolMode;
+
+ void L2CAP_task(); // L2CAP state machine
+
+ bool activeConnection; // Used to indicate if it already has established a connection
+
+ /* Variables used for L2CAP communication */
+ uint8_t control_dcid[2]; // L2CAP device CID for HID_Control - Always 0x0070
+ uint8_t interrupt_dcid[2]; // L2CAP device CID for HID_Interrupt - Always 0x0071
+ uint8_t l2cap_state;
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3BT.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3BT.cpp
new file mode 100644
index 000000000..235092e0a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3BT.cpp
@@ -0,0 +1,634 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "PS3BT.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report send by the PS3 Controllers
+
+PS3BT::PS3BT(BTD *p, uint8_t btadr5, uint8_t btadr4, uint8_t btadr3, uint8_t btadr2, uint8_t btadr1, uint8_t btadr0) :
+BluetoothService(p) // Pointer to USB class instance - mandatory
+{
+ pBtd->my_bdaddr[5] = btadr5; // Change to your dongle's Bluetooth address instead
+ pBtd->my_bdaddr[4] = btadr4;
+ pBtd->my_bdaddr[3] = btadr3;
+ pBtd->my_bdaddr[2] = btadr2;
+ pBtd->my_bdaddr[1] = btadr1;
+ pBtd->my_bdaddr[0] = btadr0;
+
+ HIDBuffer[0] = 0x52; // HID BT Set_report (0x50) | Report Type (Output 0x02)
+ HIDBuffer[1] = 0x01; // Report ID
+
+ // Needed for PS3 Move Controller commands to work via bluetooth
+ HIDMoveBuffer[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+ HIDMoveBuffer[1] = 0x02; // Report ID
+
+ /* Set device cid for the control and intterrupt channelse - LSB */
+ control_dcid[0] = 0x40; // 0x0040
+ control_dcid[1] = 0x00;
+ interrupt_dcid[0] = 0x41; // 0x0041
+ interrupt_dcid[1] = 0x00;
+
+ Reset();
+}
+
+bool PS3BT::getButtonPress(ButtonEnum b) {
+ return (ButtonState & pgm_read_dword(&PS3_BUTTONS[(uint8_t)b]));
+}
+
+bool PS3BT::getButtonClick(ButtonEnum b) {
+ uint32_t button = pgm_read_dword(&PS3_BUTTONS[(uint8_t)b]);
+ bool click = (ButtonClickState & button);
+ ButtonClickState &= ~button; // Clear "click" event
+ return click;
+}
+
+uint8_t PS3BT::getAnalogButton(ButtonEnum a) {
+ return (uint8_t)(l2capinbuf[pgm_read_byte(&PS3_ANALOG_BUTTONS[(uint8_t)a])]);
+}
+
+uint8_t PS3BT::getAnalogHat(AnalogHatEnum a) {
+ return (uint8_t)(l2capinbuf[(uint8_t)a + 15]);
+}
+
+int16_t PS3BT::getSensor(SensorEnum a) {
+ if(PS3Connected) {
+ if(a == aX || a == aY || a == aZ || a == gZ)
+ return ((l2capinbuf[(uint16_t)a] << 8) | l2capinbuf[(uint16_t)a + 1]);
+ else
+ return 0;
+ } else if(PS3MoveConnected) {
+ if(a == mXmove || a == mYmove) // These are all 12-bits long
+ return (((l2capinbuf[(uint16_t)a] & 0x0F) << 8) | (l2capinbuf[(uint16_t)a + 1]));
+ else if(a == mZmove || a == tempMove) // The tempearature is also 12 bits long
+ return ((l2capinbuf[(uint16_t)a] << 4) | ((l2capinbuf[(uint16_t)a + 1] & 0xF0) >> 4));
+ else // aXmove, aYmove, aZmove, gXmove, gYmove and gZmove
+ return (l2capinbuf[(uint16_t)a] | (l2capinbuf[(uint16_t)a + 1] << 8));
+ } else
+ return 0;
+}
+
+double PS3BT::getAngle(AngleEnum a) {
+ double accXval, accYval, accZval;
+
+ if(PS3Connected) {
+ // Data for the Kionix KXPC4 used in the DualShock 3
+ const double zeroG = 511.5; // 1.65/3.3*1023 (1.65V)
+ accXval = -((double)getSensor(aX) - zeroG);
+ accYval = -((double)getSensor(aY) - zeroG);
+ accZval = -((double)getSensor(aZ) - zeroG);
+ } else if(PS3MoveConnected) {
+ // It's a Kionix KXSC4 inside the Motion controller
+ const uint16_t zeroG = 0x8000;
+ accXval = -(int16_t)(getSensor(aXmove) - zeroG);
+ accYval = (int16_t)(getSensor(aYmove) - zeroG);
+ accZval = (int16_t)(getSensor(aZmove) - zeroG);
+ } else
+ return 0;
+
+ // Convert to 360 degrees resolution
+ // atan2 outputs the value of -π to π (radians)
+ // We are then converting it to 0 to 2π and then to degrees
+ if(a == Pitch)
+ return (atan2(accYval, accZval) + PI) * RAD_TO_DEG;
+ else
+ return (atan2(accXval, accZval) + PI) * RAD_TO_DEG;
+}
+
+double PS3BT::get9DOFValues(SensorEnum a) { // Thanks to Manfred Piendl
+ if(!PS3MoveConnected)
+ return 0;
+ int16_t value = getSensor(a);
+ if(a == mXmove || a == mYmove || a == mZmove) {
+ if(value > 2047)
+ value -= 0x1000;
+ return (double)value / 3.2; // unit: muT = 10^(-6) Tesla
+ } else if(a == aXmove || a == aYmove || a == aZmove) {
+ if(value < 0)
+ value += 0x8000;
+ else
+ value -= 0x8000;
+ return (double)value / 442.0; // unit: m/(s^2)
+ } else if(a == gXmove || a == gYmove || a == gZmove) {
+ if(value < 0)
+ value += 0x8000;
+ else
+ value -= 0x8000;
+ if(a == gXmove)
+ return (double)value / 11.6; // unit: deg/s
+ else if(a == gYmove)
+ return (double)value / 11.2; // unit: deg/s
+ else // gZmove
+ return (double)value / 9.6; // unit: deg/s
+ } else
+ return 0;
+}
+
+String PS3BT::getTemperature() {
+ if(PS3MoveConnected) {
+ int16_t input = getSensor(tempMove);
+
+ String output = String(input / 100);
+ output += ".";
+ if(input % 100 < 10)
+ output += "0";
+ output += String(input % 100);
+
+ return output;
+ } else
+ return "Error";
+}
+
+bool PS3BT::getStatus(StatusEnum c) {
+ return (l2capinbuf[(uint16_t)c >> 8] == ((uint8_t)c & 0xff));
+}
+
+void PS3BT::printStatusString() {
+ char statusOutput[100]; // Max string length plus null character
+ if(PS3Connected || PS3NavigationConnected) {
+ strcpy_P(statusOutput, PSTR("ConnectionStatus: "));
+
+ if(getStatus(Plugged)) strcat_P(statusOutput, PSTR("Plugged"));
+ else if(getStatus(Unplugged)) strcat_P(statusOutput, PSTR("Unplugged"));
+ else strcat_P(statusOutput, PSTR("Error"));
+
+ strcat_P(statusOutput, PSTR(" - PowerRating: "));
+
+ if(getStatus(Charging)) strcat_P(statusOutput, PSTR("Charging"));
+ else if(getStatus(NotCharging)) strcat_P(statusOutput, PSTR("Not Charging"));
+ else if(getStatus(Shutdown)) strcat_P(statusOutput, PSTR("Shutdown"));
+ else if(getStatus(Dying)) strcat_P(statusOutput, PSTR("Dying"));
+ else if(getStatus(Low)) strcat_P(statusOutput, PSTR("Low"));
+ else if(getStatus(High)) strcat_P(statusOutput, PSTR("High"));
+ else if(getStatus(Full)) strcat_P(statusOutput, PSTR("Full"));
+ else strcat_P(statusOutput, PSTR("Error"));
+
+ strcat_P(statusOutput, PSTR(" - WirelessStatus: "));
+
+ if(getStatus(CableRumble)) strcat_P(statusOutput, PSTR("Cable - Rumble is on"));
+ else if(getStatus(Cable)) strcat_P(statusOutput, PSTR("Cable - Rumble is off"));
+ else if(getStatus(BluetoothRumble)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is on"));
+ else if(getStatus(Bluetooth)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is off"));
+ else strcat_P(statusOutput, PSTR("Error"));
+ } else if(PS3MoveConnected) {
+ strcpy_P(statusOutput, PSTR("PowerRating: "));
+
+ if(getStatus(MoveCharging)) strcat_P(statusOutput, PSTR("Charging"));
+ else if(getStatus(MoveNotCharging)) strcat_P(statusOutput, PSTR("Not Charging"));
+ else if(getStatus(MoveShutdown)) strcat_P(statusOutput, PSTR("Shutdown"));
+ else if(getStatus(MoveDying)) strcat_P(statusOutput, PSTR("Dying"));
+ else if(getStatus(MoveLow)) strcat_P(statusOutput, PSTR("Low"));
+ else if(getStatus(MoveHigh)) strcat_P(statusOutput, PSTR("High"));
+ else if(getStatus(MoveFull)) strcat_P(statusOutput, PSTR("Full"));
+ else strcat_P(statusOutput, PSTR("Error"));
+ } else
+ strcpy_P(statusOutput, PSTR("Error"));
+
+ USB_HOST_SERIAL.write(statusOutput);
+}
+
+void PS3BT::Reset() {
+ PS3Connected = false;
+ PS3MoveConnected = false;
+ PS3NavigationConnected = false;
+ activeConnection = false;
+ l2cap_event_flag = 0; // Reset flags
+ l2cap_state = L2CAP_WAIT;
+
+ // Needed for PS3 Dualshock Controller commands to work via Bluetooth
+ for(uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++)
+ HIDBuffer[i + 2] = pgm_read_byte(&PS3_REPORT_BUFFER[i]); // First two bytes reserved for report type and ID
+}
+
+void PS3BT::disconnect() { // Use this void to disconnect any of the controllers
+ // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection
+ pBtd->l2cap_disconnection_request(hci_handle, ++identifier, interrupt_scid, interrupt_dcid);
+ Reset();
+ l2cap_state = L2CAP_INTERRUPT_DISCONNECT;
+}
+
+void PS3BT::ACLData(uint8_t* ACLData) {
+ if(!pBtd->l2capConnectionClaimed && !PS3Connected && !PS3MoveConnected && !PS3NavigationConnected && !activeConnection && !pBtd->connectToWii && !pBtd->incomingWii && !pBtd->pairWithWii) {
+ if(ACLData[8] == L2CAP_CMD_CONNECTION_REQUEST) {
+ if((ACLData[12] | (ACLData[13] << 8)) == HID_CTRL_PSM) {
+ pBtd->l2capConnectionClaimed = true; // Claim that the incoming connection belongs to this service
+ activeConnection = true;
+ hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
+ l2cap_state = L2CAP_WAIT;
+ remote_name_first = pBtd->remote_name[0]; // Store the first letter in remote name for the connection
+#ifdef DEBUG_USB_HOST
+ if(pBtd->hci_version < 3) { // Check the HCI Version of the Bluetooth dongle
+ Notify(PSTR("\r\nYour dongle may not support reading the analog buttons, sensors and status\r\nYour HCI Version is: "), 0x80);
+ Notify(pBtd->hci_version, 0x80);
+ Notify(PSTR("\r\nBut should be at least 3\r\nThis means that it doesn't support Bluetooth Version 2.0+EDR"), 0x80);
+ }
+#endif
+ }
+ }
+ }
+
+ if(checkHciHandle(ACLData, hci_handle)) { // acl_handle_ok
+ memcpy(l2capinbuf, ACLData, BULK_MAXPKTSIZE);
+ if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U
+ if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ Notify(PSTR(" Data: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+#endif
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ Notify(PSTR(" SCID: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+ Notify(PSTR(" Identifier: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
+#endif
+ if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
+ identifier = l2capinbuf[9];
+ control_scid[0] = l2capinbuf[14];
+ control_scid[1] = l2capinbuf[15];
+ l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST);
+ } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) {
+ identifier = l2capinbuf[9];
+ interrupt_scid[0] = l2capinbuf[14];
+ interrupt_scid[1] = l2capinbuf[15];
+ l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) {
+ if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+ //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80);
+ l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS);
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+ //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80);
+ l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS);
+ }
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) {
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+ //Notify(PSTR("\r\nHID Control Configuration Request"), 0x80);
+ pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], control_scid);
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+ //Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80);
+ pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], interrupt_scid);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) {
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnect Request: Control Channel"), 0x80);
+#endif
+ identifier = l2capinbuf[9];
+ pBtd->l2cap_disconnection_response(hci_handle, identifier, control_dcid, control_scid);
+ Reset();
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80);
+#endif
+ identifier = l2capinbuf[9];
+ pBtd->l2cap_disconnection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid);
+ Reset();
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) {
+ if(l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) {
+ //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE);
+ } else if(l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) {
+ //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE);
+ }
+ }
+#ifdef EXTRADEBUG
+ else {
+ Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
+ }
+#endif
+ } else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt
+ //Notify(PSTR("\r\nL2CAP Interrupt"), 0x80);
+ if(PS3Connected || PS3MoveConnected || PS3NavigationConnected) {
+ /* Read Report */
+ if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT
+ lastMessageTime = millis(); // Store the last message time
+
+ if(PS3Connected || PS3NavigationConnected)
+ ButtonState = (uint32_t)(l2capinbuf[11] | ((uint16_t)l2capinbuf[12] << 8) | ((uint32_t)l2capinbuf[13] << 16));
+ else if(PS3MoveConnected)
+ ButtonState = (uint32_t)(l2capinbuf[10] | ((uint16_t)l2capinbuf[11] << 8) | ((uint32_t)l2capinbuf[12] << 16));
+
+ //Notify(PSTR("\r\nButtonState", 0x80);
+ //PrintHex<uint32_t>(ButtonState, 0x80);
+
+ if(ButtonState != OldButtonState) {
+ ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
+ OldButtonState = ButtonState;
+ }
+
+#ifdef PRINTREPORT // Uncomment "#define PRINTREPORT" to print the report send by the PS3 Controllers
+ for(uint8_t i = 10; i < 58; i++) {
+ D_PrintHex<uint8_t > (l2capinbuf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+ }
+ }
+ }
+ L2CAP_task();
+ }
+}
+
+void PS3BT::L2CAP_task() {
+ switch(l2cap_state) {
+ case L2CAP_WAIT:
+ if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80);
+#endif
+ pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, PENDING);
+ delay(1);
+ pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, SUCCESSFUL);
+ identifier++;
+ delay(1);
+ pBtd->l2cap_config_request(hci_handle, identifier, control_scid);
+ l2cap_state = L2CAP_CONTROL_SUCCESS;
+ }
+ break;
+
+ case L2CAP_CONTROL_SUCCESS:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80);
+#endif
+ l2cap_state = L2CAP_INTERRUPT_SETUP;
+ }
+ break;
+
+ case L2CAP_INTERRUPT_SETUP:
+ if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80);
+#endif
+ pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, PENDING);
+ delay(1);
+ pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, SUCCESSFUL);
+ identifier++;
+ delay(1);
+ pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid);
+
+ l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
+ }
+ break;
+
+ case L2CAP_INTERRUPT_CONFIG_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Interrupt Successfully Configured"), 0x80);
+#endif
+ if(remote_name_first == 'M') { // First letter in Motion Controller ('M')
+ memset(l2capinbuf, 0, BULK_MAXPKTSIZE); // Reset l2cap in buffer as it sometimes read it as a button has been pressed
+ l2cap_state = TURN_ON_LED;
+ } else
+ l2cap_state = PS3_ENABLE_SIXAXIS;
+ timer = millis();
+ }
+ break;
+
+ /* These states are handled in Run() */
+
+ case L2CAP_INTERRUPT_DISCONNECT:
+ if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_disconnection_request(hci_handle, identifier, control_scid, control_dcid);
+ l2cap_state = L2CAP_CONTROL_DISCONNECT;
+ }
+ break;
+
+ case L2CAP_CONTROL_DISCONNECT:
+ if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected Control Channel"), 0x80);
+#endif
+ pBtd->hci_disconnect(hci_handle);
+ hci_handle = -1; // Reset handle
+ l2cap_event_flag = 0; // Reset flags
+ l2cap_state = L2CAP_WAIT;
+ }
+ break;
+ }
+}
+
+void PS3BT::Run() {
+ switch(l2cap_state) {
+ case PS3_ENABLE_SIXAXIS:
+ if(millis() - timer > 1000) { // loop 1 second before sending the command
+ memset(l2capinbuf, 0, BULK_MAXPKTSIZE); // Reset l2cap in buffer as it sometimes read it as a button has been pressed
+ for(uint8_t i = 15; i < 19; i++)
+ l2capinbuf[i] = 0x7F; // Set the analog joystick values to center position
+ enable_sixaxis();
+ l2cap_state = TURN_ON_LED;
+ timer = millis();
+ }
+ break;
+
+ case TURN_ON_LED:
+ if(millis() - timer > 1000) { // loop 1 second before sending the command
+ if(remote_name_first == 'P') { // First letter in PLAYSTATION(R)3 Controller ('P')
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDualshock 3 Controller Enabled\r\n"), 0x80);
+#endif
+ PS3Connected = true;
+ } else if(remote_name_first == 'N') { // First letter in Navigation Controller ('N')
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nNavigation Controller Enabled\r\n"), 0x80);
+#endif
+ PS3NavigationConnected = true;
+ } else if(remote_name_first == 'M') { // First letter in Motion Controller ('M')
+ timer = millis();
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nMotion Controller Enabled\r\n"), 0x80);
+#endif
+ PS3MoveConnected = true;
+ }
+ ButtonState = 0; // Clear all values
+ OldButtonState = 0;
+ ButtonClickState = 0;
+
+ onInit(); // Turn on the LED on the controller
+ l2cap_state = L2CAP_DONE;
+ }
+ break;
+
+ case L2CAP_DONE:
+ if(PS3MoveConnected) { // The Bulb and rumble values, has to be send at approximately every 5th second for it to stay on
+ if(millis() - timer > 4000) { // Send at least every 4th second
+ HIDMove_Command(HIDMoveBuffer, HID_BUFFERSIZE); // The Bulb and rumble values, has to be written again and again, for it to stay turned on
+ timer = millis();
+ }
+ }
+ break;
+ }
+}
+
+/************************************************************/
+/* HID Commands */
+/************************************************************/
+
+// Playstation Sixaxis Dualshock and Navigation Controller commands
+
+void PS3BT::HID_Command(uint8_t* data, uint8_t nbytes) {
+ if(millis() - timerHID <= 150) // Check if is has been more than 150ms since last command
+ delay((uint32_t)(150 - (millis() - timerHID))); // There have to be a delay between commands
+ pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]); // Both the Navigation and Dualshock controller sends data via the control channel
+ timerHID = millis();
+}
+
+void PS3BT::setAllOff() {
+ HIDBuffer[3] = 0x00; // Rumble bytes
+ HIDBuffer[4] = 0x00;
+ HIDBuffer[5] = 0x00;
+ HIDBuffer[6] = 0x00;
+
+ HIDBuffer[11] = 0x00; // LED byte
+
+ HID_Command(HIDBuffer, HID_BUFFERSIZE);
+}
+
+void PS3BT::setRumbleOff() {
+ HIDBuffer[3] = 0x00;
+ HIDBuffer[4] = 0x00;
+ HIDBuffer[5] = 0x00;
+ HIDBuffer[6] = 0x00;
+
+ HID_Command(HIDBuffer, HID_BUFFERSIZE);
+}
+
+void PS3BT::setRumbleOn(RumbleEnum mode) {
+ uint8_t power[2] = {0xff, 0x00}; // Defaults to RumbleLow
+ if(mode == RumbleHigh) {
+ power[0] = 0x00;
+ power[1] = 0xff;
+ }
+ setRumbleOn(0xfe, power[0], 0xfe, power[1]);
+}
+
+void PS3BT::setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower) {
+ HIDBuffer[3] = rightDuration;
+ HIDBuffer[4] = rightPower;
+ HIDBuffer[5] = leftDuration;
+ HIDBuffer[6] = leftPower;
+ HID_Command(HIDBuffer, HID_BUFFERSIZE);
+}
+
+void PS3BT::setLedRaw(uint8_t value) {
+ HIDBuffer[11] = value << 1;
+ HID_Command(HIDBuffer, HID_BUFFERSIZE);
+}
+
+void PS3BT::setLedOff(LEDEnum a) {
+ HIDBuffer[11] &= ~((uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1));
+ HID_Command(HIDBuffer, HID_BUFFERSIZE);
+}
+
+void PS3BT::setLedOn(LEDEnum a) {
+ if(a == OFF)
+ setLedRaw(0);
+ else {
+ HIDBuffer[11] |= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1);
+ HID_Command(HIDBuffer, HID_BUFFERSIZE);
+ }
+}
+
+void PS3BT::setLedToggle(LEDEnum a) {
+ HIDBuffer[11] ^= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1);
+ HID_Command(HIDBuffer, HID_BUFFERSIZE);
+}
+
+void PS3BT::enable_sixaxis() { // Command used to enable the Dualshock 3 and Navigation controller to send data via Bluetooth
+ uint8_t cmd_buf[6];
+ cmd_buf[0] = 0x53; // HID BT Set_report (0x50) | Report Type (Feature 0x03)
+ cmd_buf[1] = 0xF4; // Report ID
+ cmd_buf[2] = 0x42; // Special PS3 Controller enable commands
+ cmd_buf[3] = 0x03;
+ cmd_buf[4] = 0x00;
+ cmd_buf[5] = 0x00;
+
+ HID_Command(cmd_buf, 6);
+}
+
+// Playstation Move Controller commands
+
+void PS3BT::HIDMove_Command(uint8_t* data, uint8_t nbytes) {
+ if(millis() - timerHID <= 150)// Check if is has been less than 150ms since last command
+ delay((uint32_t)(150 - (millis() - timerHID))); // There have to be a delay between commands
+ pBtd->L2CAP_Command(hci_handle, data, nbytes, interrupt_scid[0], interrupt_scid[1]); // The Move controller sends it's data via the intterrupt channel
+ timerHID = millis();
+}
+
+void PS3BT::moveSetBulb(uint8_t r, uint8_t g, uint8_t b) { // Use this to set the Color using RGB values
+ // Set the Bulb's values into the write buffer
+ HIDMoveBuffer[3] = r;
+ HIDMoveBuffer[4] = g;
+ HIDMoveBuffer[5] = b;
+
+ HIDMove_Command(HIDMoveBuffer, HID_BUFFERSIZE);
+}
+
+void PS3BT::moveSetBulb(ColorsEnum color) { // Use this to set the Color using the predefined colors in enum
+ moveSetBulb((uint8_t)(color >> 16), (uint8_t)(color >> 8), (uint8_t)(color));
+}
+
+void PS3BT::moveSetRumble(uint8_t rumble) {
+#ifdef DEBUG_USB_HOST
+ if(rumble < 64 && rumble != 0) // The rumble value has to at least 64, or approximately 25% (64/255*100)
+ Notify(PSTR("\r\nThe rumble value has to at least 64, or approximately 25%"), 0x80);
+#endif
+ // Set the rumble value into the write buffer
+ HIDMoveBuffer[7] = rumble;
+
+ HIDMove_Command(HIDMoveBuffer, HID_BUFFERSIZE);
+}
+
+void PS3BT::onInit() {
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ else {
+ if(PS3MoveConnected)
+ moveSetBulb(Red);
+ else // Dualshock 3 or Navigation controller
+ setLedOn(LED1);
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3BT.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3BT.h
new file mode 100644
index 000000000..c25ac5e59
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3BT.h
@@ -0,0 +1,240 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _ps3bt_h_
+#define _ps3bt_h_
+
+#include "BTD.h"
+#include "PS3Enums.h"
+
+#define HID_BUFFERSIZE 50 // Size of the buffer for the Playstation Motion Controller
+
+/**
+ * This BluetoothService class implements support for all the official PS3 Controllers:
+ * Dualshock 3, Navigation or a Motion controller via Bluetooth.
+ *
+ * Information about the protocol can be found at the wiki: https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information.
+ */
+class PS3BT : public BluetoothService {
+public:
+ /**
+ * Constructor for the PS3BT class.
+ * @param pBtd Pointer to BTD class instance.
+ * @param btadr5,btadr4,btadr3,btadr2,btadr1,btadr0
+ * Pass your dongles Bluetooth address into the constructor,
+ * This will set BTD#my_bdaddr, so you don't have to plug in the dongle before pairing with your controller.
+ */
+ PS3BT(BTD *pBtd, uint8_t btadr5 = 0, uint8_t btadr4 = 0, uint8_t btadr3 = 0, uint8_t btadr2 = 0, uint8_t btadr1 = 0, uint8_t btadr0 = 0);
+
+ /** @name BluetoothService implementation */
+ /** Used this to disconnect any of the controllers. */
+ void disconnect();
+ /**@}*/
+
+ /** @name PS3 Controller functions */
+ /**
+ * getButtonPress(ButtonEnum b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(ButtonEnum b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b),
+ * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b).
+ * @param b ::ButtonEnum to read.
+ * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press.
+ */
+ bool getButtonPress(ButtonEnum b);
+ bool getButtonClick(ButtonEnum b);
+ /**@}*/
+ /** @name PS3 Controller functions */
+ /**
+ * Used to get the analog value from button presses.
+ * @param a The ::ButtonEnum to read.
+ * The supported buttons are:
+ * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2,
+ * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T.
+ * @return Analog value in the range of 0-255.
+ */
+ uint8_t getAnalogButton(ButtonEnum a);
+ /**
+ * Used to read the analog joystick.
+ * @param a ::LeftHatX, ::LeftHatY, ::RightHatX, and ::RightHatY.
+ * @return Return the analog value in the range of 0-255.
+ */
+ uint8_t getAnalogHat(AnalogHatEnum a);
+ /**
+ * Used to read the sensors inside the Dualshock 3 and Move controller.
+ * @param a
+ * The Dualshock 3 has a 3-axis accelerometer and a 1-axis gyro inside.
+ * The Move controller has a 3-axis accelerometer, a 3-axis gyro, a 3-axis magnetometer
+ * and a temperature sensor inside.
+ * @return Return the raw sensor value.
+ */
+ int16_t getSensor(SensorEnum a);
+ /**
+ * Use this to get ::Pitch and ::Roll calculated using the accelerometer.
+ * @param a Either ::Pitch or ::Roll.
+ * @return Return the angle in the range of 0-360.
+ */
+ double getAngle(AngleEnum a);
+ /**
+ * Read the sensors inside the Move controller.
+ * @param a ::aXmove, ::aYmove, ::aZmove, ::gXmove, ::gYmove, ::gZmove, ::mXmove, ::mYmove, and ::mXmove.
+ * @return The value in SI units.
+ */
+ double get9DOFValues(SensorEnum a);
+ /**
+ * Get the status from the controller.
+ * @param c The ::StatusEnum you want to read.
+ * @return True if correct and false if not.
+ */
+ bool getStatus(StatusEnum c);
+ /** Read all the available statuses from the controller and prints it as a nice formated string. */
+ void printStatusString();
+ /**
+ * Read the temperature from the Move controller.
+ * @return The temperature in degrees Celsius.
+ */
+ String getTemperature();
+
+ /** Used to set all LEDs and rumble off. */
+ void setAllOff();
+ /** Turn off rumble. */
+ void setRumbleOff();
+ /**
+ * Turn on rumble.
+ * @param mode Either ::RumbleHigh or ::RumbleLow.
+ */
+ void setRumbleOn(RumbleEnum mode);
+ /**
+ * Turn on rumble using custom duration and power.
+ * @param rightDuration The duration of the right/low rumble effect.
+ * @param rightPower The intensity of the right/low rumble effect.
+ * @param leftDuration The duration of the left/high rumble effect.
+ * @param leftPower The intensity of the left/high rumble effect.
+ */
+ void setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower);
+
+ /**
+ * Set LED value without using ::LEDEnum.
+ * @param value See: ::LEDEnum.
+ */
+ void setLedRaw(uint8_t value);
+
+ /** Turn all LEDs off. */
+ void setLedOff() {
+ setLedRaw(0);
+ };
+ /**
+ * Turn the specific LED off.
+ * @param a The ::LEDEnum to turn off.
+ */
+ void setLedOff(LEDEnum a);
+ /**
+ * Turn the specific LED on.
+ * @param a The ::LEDEnum to turn on.
+ */
+ void setLedOn(LEDEnum a);
+ /**
+ * Toggle the specific LED.
+ * @param a The ::LEDEnum to toggle.
+ */
+ void setLedToggle(LEDEnum a);
+
+ /**
+ * Use this to set the Color using RGB values.
+ * @param r,g,b RGB value.
+ */
+ void moveSetBulb(uint8_t r, uint8_t g, uint8_t b);
+ /**
+ * Use this to set the color using the predefined colors in ::ColorsEnum.
+ * @param color The desired color.
+ */
+ void moveSetBulb(ColorsEnum color);
+ /**
+ * Set the rumble value inside the Move controller.
+ * @param rumble The desired value in the range from 64-255.
+ */
+ void moveSetRumble(uint8_t rumble);
+
+ /** Used to get the millis() of the last message */
+ uint32_t getLastMessageTime() {
+ return lastMessageTime;
+ };
+ /**@}*/
+
+ /** Variable used to indicate if the normal Playstation controller is successfully connected. */
+ bool PS3Connected;
+ /** Variable used to indicate if the Move controller is successfully connected. */
+ bool PS3MoveConnected;
+ /** Variable used to indicate if the Navigation controller is successfully connected. */
+ bool PS3NavigationConnected;
+
+protected:
+ /** @name BluetoothService implementation */
+ /**
+ * Used to pass acldata to the services.
+ * @param ACLData Incoming acldata.
+ */
+ void ACLData(uint8_t* ACLData);
+ /** Used to run part of the state machine. */
+ void Run();
+ /** Use this to reset the service. */
+ void Reset();
+ /**
+ * Called when the controller is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ void onInit();
+ /**@}*/
+
+private:
+
+ void L2CAP_task(); // L2CAP state machine
+
+ /* Variables filled from HCI event management */
+ char remote_name_first; // First letter in remote name
+ bool activeConnection; // Used to indicate if it's already has established a connection
+
+ /* Variables used by high level L2CAP task */
+ uint8_t l2cap_state;
+
+ uint32_t lastMessageTime; // Variable used to store the millis value of the last message.
+
+ uint32_t ButtonState;
+ uint32_t OldButtonState;
+ uint32_t ButtonClickState;
+
+ uint32_t timer; // Timer used to limit time between messages and also used to continuously set PS3 Move controller Bulb and rumble values
+ uint32_t timerHID; // Timer used see if there has to be a delay before a new HID command
+
+ uint8_t l2capinbuf[BULK_MAXPKTSIZE]; // General purpose buffer for L2CAP in data
+ uint8_t HIDBuffer[HID_BUFFERSIZE]; // Used to store HID commands
+ uint8_t HIDMoveBuffer[HID_BUFFERSIZE]; // Used to store HID commands for the Move controller
+
+ /* L2CAP Channels */
+ uint8_t control_scid[2]; // L2CAP source CID for HID_Control
+ uint8_t control_dcid[2]; // 0x0040
+ uint8_t interrupt_scid[2]; // L2CAP source CID for HID_Interrupt
+ uint8_t interrupt_dcid[2]; // 0x0041
+
+ /* HID Commands */
+ void HID_Command(uint8_t* data, uint8_t nbytes);
+ void HIDMove_Command(uint8_t* data, uint8_t nbytes);
+ void enable_sixaxis(); // Command used to enable the Dualshock 3 and Navigation controller to send data via Bluetooth
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3Enums.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3Enums.h
new file mode 100644
index 000000000..77801945f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3Enums.h
@@ -0,0 +1,141 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _ps3enums_h
+#define _ps3enums_h
+
+#include "controllerEnums.h"
+
+/** Size of the output report buffer for the Dualshock and Navigation controllers */
+#define PS3_REPORT_BUFFER_SIZE 48
+
+/** Report buffer for all PS3 commands */
+const uint8_t PS3_REPORT_BUFFER[PS3_REPORT_BUFFER_SIZE] PROGMEM = {
+ 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0xff, 0x27, 0x10, 0x00, 0x32,
+ 0xff, 0x27, 0x10, 0x00, 0x32,
+ 0xff, 0x27, 0x10, 0x00, 0x32,
+ 0xff, 0x27, 0x10, 0x00, 0x32,
+ 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00,
+ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
+};
+
+/** Size of the output report buffer for the Move Controller */
+#define MOVE_REPORT_BUFFER_SIZE 7
+
+/** Used to set the LEDs on the controllers */
+const uint8_t PS3_LEDS[] PROGMEM = {
+ 0x00, // OFF
+ 0x01, // LED1
+ 0x02, // LED2
+ 0x04, // LED3
+ 0x08, // LED4
+
+ 0x09, // LED5
+ 0x0A, // LED6
+ 0x0C, // LED7
+ 0x0D, // LED8
+ 0x0E, // LED9
+ 0x0F, // LED10
+};
+
+/**
+ * Buttons on the controllers.
+ * <B>Note:</B> that the location is shifted 9 when it's connected via USB.
+ */
+const uint32_t PS3_BUTTONS[] PROGMEM = {
+ 0x10, // UP
+ 0x20, // RIGHT
+ 0x40, // DOWN
+ 0x80, // LEFT
+
+ 0x01, // SELECT
+ 0x08, // START
+ 0x02, // L3
+ 0x04, // R3
+
+ 0x0100, // L2
+ 0x0200, // R2
+ 0x0400, // L1
+ 0x0800, // R1
+
+ 0x1000, // TRIANGLE
+ 0x2000, // CIRCLE
+ 0x4000, // CROSS
+ 0x8000, // SQUARE
+
+ 0x010000, // PS
+ 0x080000, // MOVE - covers 12 bits - we only need to read the top 8
+ 0x100000, // T - covers 12 bits - we only need to read the top 8
+};
+
+/**
+ * Analog buttons on the controllers.
+ * <B>Note:</B> that the location is shifted 9 when it's connected via USB.
+ */
+const uint8_t PS3_ANALOG_BUTTONS[] PROGMEM = {
+ 23, // UP_ANALOG
+ 24, // RIGHT_ANALOG
+ 25, // DOWN_ANALOG
+ 26, // LEFT_ANALOG
+ 0, 0, 0, 0, // Skip SELECT, L3, R3 and START
+
+ 27, // L2_ANALOG
+ 28, // R2_ANALOG
+ 29, // L1_ANALOG
+ 30, // R1_ANALOG
+ 31, // TRIANGLE_ANALOG
+ 32, // CIRCLE_ANALOG
+ 33, // CROSS_ANALOG
+ 34, // SQUARE_ANALOG
+ 0, 0, // Skip PS and MOVE
+
+ // Playstation Move Controller
+ 15, // T_ANALOG - Both at byte 14 (last reading) and byte 15 (current reading)
+};
+
+enum StatusEnum {
+ // Note that the location is shifted 9 when it's connected via USB
+ // Byte location | bit location
+ Plugged = (38 << 8) | 0x02,
+ Unplugged = (38 << 8) | 0x03,
+
+ Charging = (39 << 8) | 0xEE,
+ NotCharging = (39 << 8) | 0xF1,
+ Shutdown = (39 << 8) | 0x01,
+ Dying = (39 << 8) | 0x02,
+ Low = (39 << 8) | 0x03,
+ High = (39 << 8) | 0x04,
+ Full = (39 << 8) | 0x05,
+
+ MoveCharging = (21 << 8) | 0xEE,
+ MoveNotCharging = (21 << 8) | 0xF1,
+ MoveShutdown = (21 << 8) | 0x01,
+ MoveDying = (21 << 8) | 0x02,
+ MoveLow = (21 << 8) | 0x03,
+ MoveHigh = (21 << 8) | 0x04,
+ MoveFull = (21 << 8) | 0x05,
+
+ CableRumble = (40 << 8) | 0x10, // Operating by USB and rumble is turned on
+ Cable = (40 << 8) | 0x12, // Operating by USB and rumble is turned off
+ BluetoothRumble = (40 << 8) | 0x14, // Operating by Bluetooth and rumble is turned on
+ Bluetooth = (40 << 8) | 0x16, // Operating by Bluetooth and rumble is turned off
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3USB.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3USB.cpp
new file mode 100755
index 000000000..c32175389
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3USB.cpp
@@ -0,0 +1,572 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "PS3USB.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report send by the PS3 Controllers
+
+PS3USB::PS3USB(USB *p, uint8_t btadr5, uint8_t btadr4, uint8_t btadr3, uint8_t btadr2, uint8_t btadr1, uint8_t btadr0) :
+pUsb(p), // pointer to USB class instance - mandatory
+bAddress(0), // device address - mandatory
+bPollEnable(false) // don't start polling before dongle is connected
+{
+ for(uint8_t i = 0; i < PS3_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }
+
+ if(pUsb) // register in USB subsystem
+ pUsb->RegisterDeviceClass(this); //set devConfig[] entry
+
+ my_bdaddr[5] = btadr5; // Change to your dongle's Bluetooth address instead
+ my_bdaddr[4] = btadr4;
+ my_bdaddr[3] = btadr3;
+ my_bdaddr[2] = btadr2;
+ my_bdaddr[1] = btadr1;
+ my_bdaddr[0] = btadr0;
+}
+
+uint8_t PS3USB::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint16_t PID;
+ uint16_t VID;
+
+ // get memory address of USB device address pool
+ AddressPool &addrPool = pUsb->GetAddressPool();
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nPS3USB Init"), 0x80);
+#endif
+ // check if address has already been assigned to an instance
+ if(bAddress) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress in use"), 0x80);
+#endif
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+ }
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ if(!p->epinfo) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nepinfo is null"), 0x80);
+#endif
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ VID = udd->idVendor;
+ PID = udd->idProduct;
+
+ if(VID != PS3_VID || (PID != PS3_PID && PID != PS3NAVIGATION_PID && PID != PS3MOVE_PID))
+ goto FailUnknownDevice;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nsetAddr: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+#endif
+ return rcode;
+ }
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nAddr: "), 0x80);
+ D_PrintHex<uint8_t > (bAddress, 0x80);
+#endif
+ //delay(300); // Spec says you should wait at least 200ms
+
+ p->lowspeed = false;
+
+ //get pointer to assigned address record
+ p = addrPool.GetUsbDevicePtr(bAddress);
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ // Assign epInfo to epinfo pointer - only EP0 is known
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+
+ /* The application will work in reduced host mode, so we can save program and data
+ memory space. After verifying the PID and VID we will use known values for the
+ configuration values for device, interface, endpoints and HID for the PS3 Controllers */
+
+ /* Initialize data structures for endpoints of device */
+ epInfo[ PS3_OUTPUT_PIPE ].epAddr = 0x02; // PS3 output endpoint
+ epInfo[ PS3_OUTPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ PS3_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ PS3_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ PS3_OUTPUT_PIPE ].bmSndToggle = 0;
+ epInfo[ PS3_OUTPUT_PIPE ].bmRcvToggle = 0;
+ epInfo[ PS3_INPUT_PIPE ].epAddr = 0x01; // PS3 report endpoint
+ epInfo[ PS3_INPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ PS3_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ PS3_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ PS3_INPUT_PIPE ].bmSndToggle = 0;
+ epInfo[ PS3_INPUT_PIPE ].bmRcvToggle = 0;
+
+ rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ delay(200); //Give time for address change
+
+ rcode = pUsb->setConf(bAddress, epInfo[ PS3_CONTROL_PIPE ].epAddr, 1);
+ if(rcode)
+ goto FailSetConfDescr;
+
+ if(PID == PS3_PID || PID == PS3NAVIGATION_PID) {
+ if(PID == PS3_PID) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDualshock 3 Controller Connected"), 0x80);
+#endif
+ PS3Connected = true;
+ } else { // must be a navigation controller
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nNavigation Controller Connected"), 0x80);
+#endif
+ PS3NavigationConnected = true;
+ }
+ enable_sixaxis(); // The PS3 controller needs a special command before it starts sending data
+
+ // Needed for PS3 Dualshock and Navigation commands to work
+ for(uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++)
+ writeBuf[i] = pgm_read_byte(&PS3_REPORT_BUFFER[i]);
+
+ for(uint8_t i = 6; i < 10; i++)
+ readBuf[i] = 0x7F; // Set the analog joystick values to center position
+ } else { // must be a Motion controller
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nMotion Controller Connected"), 0x80);
+#endif
+ PS3MoveConnected = true;
+ writeBuf[0] = 0x02; // Set report ID, this is needed for Move commands to work
+ }
+ if(my_bdaddr[0] != 0x00 || my_bdaddr[1] != 0x00 || my_bdaddr[2] != 0x00 || my_bdaddr[3] != 0x00 || my_bdaddr[4] != 0x00 || my_bdaddr[5] != 0x00) {
+ if(PS3MoveConnected)
+ setMoveBdaddr(my_bdaddr); // Set internal Bluetooth address
+ else
+ setBdaddr(my_bdaddr); // Set internal Bluetooth address
+
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nBluetooth Address was set to: "), 0x80);
+ for(int8_t i = 5; i > 0; i--) {
+ D_PrintHex<uint8_t > (my_bdaddr[i], 0x80);
+ Notify(PSTR(":"), 0x80);
+ }
+ D_PrintHex<uint8_t > (my_bdaddr[0], 0x80);
+#endif
+ }
+ onInit();
+
+ bPollEnable = true;
+ Notify(PSTR("\r\n"), 0x80);
+ timer = millis();
+ return 0; // Successful configuration
+
+ /* Diagnostic messages */
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+#endif
+ goto Fail;
+
+FailUnknownDevice:
+#ifdef DEBUG_USB_HOST
+ NotifyFailUnknownDevice(VID, PID);
+#endif
+ rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+Fail:
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nPS3 Init Failed, error code: "), 0x80);
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+/* Performs a cleanup after failed Init() attempt */
+uint8_t PS3USB::Release() {
+ PS3Connected = false;
+ PS3MoveConnected = false;
+ PS3NavigationConnected = false;
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+ bAddress = 0;
+ bPollEnable = false;
+ return 0;
+}
+
+uint8_t PS3USB::Poll() {
+ if(!bPollEnable)
+ return 0;
+
+ if(PS3Connected || PS3NavigationConnected) {
+ uint16_t BUFFER_SIZE = EP_MAXPKTSIZE;
+ pUsb->inTransfer(bAddress, epInfo[ PS3_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf); // input on endpoint 1
+ if(millis() - timer > 100) { // Loop 100ms before processing data
+ readReport();
+#ifdef PRINTREPORT
+ printReport(); // Uncomment "#define PRINTREPORT" to print the report send by the PS3 Controllers
+#endif
+ }
+ } else if(PS3MoveConnected) { // One can only set the color of the bulb, set the rumble, set and get the bluetooth address and calibrate the magnetometer via USB
+ if(millis() - timer > 4000) { // Send at least every 4th second
+ Move_Command(writeBuf, MOVE_REPORT_BUFFER_SIZE); // The Bulb and rumble values, has to be written again and again, for it to stay turned on
+ timer = millis();
+ }
+ }
+ return 0;
+}
+
+void PS3USB::readReport() {
+ ButtonState = (uint32_t)(readBuf[2] | ((uint16_t)readBuf[3] << 8) | ((uint32_t)readBuf[4] << 16));
+
+ //Notify(PSTR("\r\nButtonState", 0x80);
+ //PrintHex<uint32_t>(ButtonState, 0x80);
+
+ if(ButtonState != OldButtonState) {
+ ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
+ OldButtonState = ButtonState;
+ }
+}
+
+void PS3USB::printReport() { // Uncomment "#define PRINTREPORT" to print the report send by the PS3 Controllers
+#ifdef PRINTREPORT
+ for(uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++) {
+ D_PrintHex<uint8_t > (readBuf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+}
+
+bool PS3USB::getButtonPress(ButtonEnum b) {
+ return (ButtonState & pgm_read_dword(&PS3_BUTTONS[(uint8_t)b]));
+}
+
+bool PS3USB::getButtonClick(ButtonEnum b) {
+ uint32_t button = pgm_read_dword(&PS3_BUTTONS[(uint8_t)b]);
+ bool click = (ButtonClickState & button);
+ ButtonClickState &= ~button; // Clear "click" event
+ return click;
+}
+
+uint8_t PS3USB::getAnalogButton(ButtonEnum a) {
+ return (uint8_t)(readBuf[(pgm_read_byte(&PS3_ANALOG_BUTTONS[(uint8_t)a])) - 9]);
+}
+
+uint8_t PS3USB::getAnalogHat(AnalogHatEnum a) {
+ return (uint8_t)(readBuf[((uint8_t)a + 6)]);
+}
+
+uint16_t PS3USB::getSensor(SensorEnum a) {
+ return ((readBuf[((uint16_t)a) - 9] << 8) | readBuf[((uint16_t)a + 1) - 9]);
+}
+
+double PS3USB::getAngle(AngleEnum a) {
+ if(PS3Connected) {
+ double accXval;
+ double accYval;
+ double accZval;
+
+ // Data for the Kionix KXPC4 used in the DualShock 3
+ const double zeroG = 511.5; // 1.65/3.3*1023 (1,65V)
+ accXval = -((double)getSensor(aX) - zeroG);
+ accYval = -((double)getSensor(aY) - zeroG);
+ accZval = -((double)getSensor(aZ) - zeroG);
+
+ // Convert to 360 degrees resolution
+ // atan2 outputs the value of -π to π (radians)
+ // We are then converting it to 0 to 2π and then to degrees
+ if(a == Pitch)
+ return (atan2(accYval, accZval) + PI) * RAD_TO_DEG;
+ else
+ return (atan2(accXval, accZval) + PI) * RAD_TO_DEG;
+ } else
+ return 0;
+}
+
+bool PS3USB::getStatus(StatusEnum c) {
+ return (readBuf[((uint16_t)c >> 8) - 9] == ((uint8_t)c & 0xff));
+}
+
+void PS3USB::printStatusString() {
+ char statusOutput[100]; // Max string length plus null character
+ if(PS3Connected || PS3NavigationConnected) {
+ strcpy_P(statusOutput, PSTR("ConnectionStatus: "));
+
+ if(getStatus(Plugged)) strcat_P(statusOutput, PSTR("Plugged"));
+ else if(getStatus(Unplugged)) strcat_P(statusOutput, PSTR("Unplugged"));
+ else strcat_P(statusOutput, PSTR("Error"));
+
+ strcat_P(statusOutput, PSTR(" - PowerRating: "));
+
+ if(getStatus(Charging)) strcat_P(statusOutput, PSTR("Charging"));
+ else if(getStatus(NotCharging)) strcat_P(statusOutput, PSTR("Not Charging"));
+ else if(getStatus(Shutdown)) strcat_P(statusOutput, PSTR("Shutdown"));
+ else if(getStatus(Dying)) strcat_P(statusOutput, PSTR("Dying"));
+ else if(getStatus(Low)) strcat_P(statusOutput, PSTR("Low"));
+ else if(getStatus(High)) strcat_P(statusOutput, PSTR("High"));
+ else if(getStatus(Full)) strcat_P(statusOutput, PSTR("Full"));
+ else strcat_P(statusOutput, PSTR("Error"));
+
+ strcat_P(statusOutput, PSTR(" - WirelessStatus: "));
+
+ if(getStatus(CableRumble)) strcat_P(statusOutput, PSTR("Cable - Rumble is on"));
+ else if(getStatus(Cable)) strcat_P(statusOutput, PSTR("Cable - Rumble is off"));
+ else if(getStatus(BluetoothRumble)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is on"));
+ else if(getStatus(Bluetooth)) strcat_P(statusOutput, PSTR("Bluetooth - Rumble is off"));
+ else strcat_P(statusOutput, PSTR("Error"));
+ } else
+ strcpy_P(statusOutput, PSTR("Error"));
+
+ USB_HOST_SERIAL.write(statusOutput);
+}
+
+/* Playstation Sixaxis Dualshock and Navigation Controller commands */
+void PS3USB::PS3_Command(uint8_t *data, uint16_t nbytes) {
+ // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x01), Report Type (Output 0x02), interface (0x00), datalength, datalength, data)
+ pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x01, 0x02, 0x00, nbytes, nbytes, data, NULL);
+}
+
+void PS3USB::setAllOff() {
+ for(uint8_t i = 0; i < PS3_REPORT_BUFFER_SIZE; i++)
+ writeBuf[i] = pgm_read_byte(&PS3_REPORT_BUFFER[i]); // Reset buffer
+
+ PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE);
+}
+
+void PS3USB::setRumbleOff() {
+ writeBuf[1] = 0x00;
+ writeBuf[2] = 0x00; // Low mode off
+ writeBuf[3] = 0x00;
+ writeBuf[4] = 0x00; // High mode off
+
+ PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE);
+}
+
+void PS3USB::setRumbleOn(RumbleEnum mode) {
+ if((mode & 0x30) > 0x00) {
+ uint8_t power[2] = {0xff, 0x00}; // Defaults to RumbleLow
+ if(mode == RumbleHigh) {
+ power[0] = 0x00;
+ power[1] = 0xff;
+ }
+ setRumbleOn(0xfe, power[0], 0xfe, power[1]);
+ }
+}
+
+void PS3USB::setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower) {
+ writeBuf[1] = rightDuration;
+ writeBuf[2] = rightPower;
+ writeBuf[3] = leftDuration;
+ writeBuf[4] = leftPower;
+ PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE);
+}
+
+void PS3USB::setLedRaw(uint8_t value) {
+ writeBuf[9] = value << 1;
+ PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE);
+}
+
+void PS3USB::setLedOff(LEDEnum a) {
+ writeBuf[9] &= ~((uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1));
+ PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE);
+}
+
+void PS3USB::setLedOn(LEDEnum a) {
+ if(a == OFF)
+ setLedRaw(0);
+ else {
+ writeBuf[9] |= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1);
+ PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE);
+ }
+}
+
+void PS3USB::setLedToggle(LEDEnum a) {
+ writeBuf[9] ^= (uint8_t)((pgm_read_byte(&PS3_LEDS[(uint8_t)a]) & 0x0f) << 1);
+ PS3_Command(writeBuf, PS3_REPORT_BUFFER_SIZE);
+}
+
+void PS3USB::setBdaddr(uint8_t *bdaddr) {
+ /* Set the internal Bluetooth address */
+ uint8_t buf[8];
+ buf[0] = 0x01;
+ buf[1] = 0x00;
+
+ for(uint8_t i = 0; i < 6; i++)
+ buf[i + 2] = bdaddr[5 - i]; // Copy into buffer, has to be written reversed, so it is MSB first
+
+ // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0xF5), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
+ pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
+}
+
+void PS3USB::getBdaddr(uint8_t *bdaddr) {
+ uint8_t buf[8];
+
+ // bmRequest = Device to host (0x80) | Class (0x20) | Interface (0x01) = 0xA1, bRequest = Get Report (0x01), Report ID (0xF5), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
+ pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_IN, HID_REQUEST_GET_REPORT, 0xF5, 0x03, 0x00, 8, 8, buf, NULL);
+
+ for(uint8_t i = 0; i < 6; i++)
+ bdaddr[5 - i] = buf[i + 2]; // Copy into buffer reversed, so it is LSB first
+}
+
+void PS3USB::enable_sixaxis() { // Command used to enable the Dualshock 3 and Navigation controller to send data via USB
+ uint8_t cmd_buf[4];
+ cmd_buf[0] = 0x42; // Special PS3 Controller enable commands
+ cmd_buf[1] = 0x0c;
+ cmd_buf[2] = 0x00;
+ cmd_buf[3] = 0x00;
+
+ // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0xF4), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data)
+ pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0xF4, 0x03, 0x00, 4, 4, cmd_buf, NULL);
+}
+
+/* Playstation Move Controller commands */
+void PS3USB::Move_Command(uint8_t *data, uint16_t nbytes) {
+ pUsb->outTransfer(bAddress, epInfo[ PS3_OUTPUT_PIPE ].epAddr, nbytes, data);
+}
+
+void PS3USB::moveSetBulb(uint8_t r, uint8_t g, uint8_t b) { // Use this to set the Color using RGB values
+ // Set the Bulb's values into the write buffer
+ writeBuf[2] = r;
+ writeBuf[3] = g;
+ writeBuf[4] = b;
+
+ Move_Command(writeBuf, MOVE_REPORT_BUFFER_SIZE);
+}
+
+void PS3USB::moveSetBulb(ColorsEnum color) { // Use this to set the Color using the predefined colors in "enums.h"
+ moveSetBulb((uint8_t)(color >> 16), (uint8_t)(color >> 8), (uint8_t)(color));
+}
+
+void PS3USB::moveSetRumble(uint8_t rumble) {
+#ifdef DEBUG_USB_HOST
+ if(rumble < 64 && rumble != 0) // The rumble value has to at least 64, or approximately 25% (64/255*100)
+ Notify(PSTR("\r\nThe rumble value has to at least 64, or approximately 25%"), 0x80);
+#endif
+ writeBuf[6] = rumble; // Set the rumble value into the write buffer
+
+ Move_Command(writeBuf, MOVE_REPORT_BUFFER_SIZE);
+}
+
+void PS3USB::setMoveBdaddr(uint8_t *bdaddr) {
+ /* Set the internal Bluetooth address */
+ uint8_t buf[11];
+ buf[0] = 0x05;
+ buf[7] = 0x10;
+ buf[8] = 0x01;
+ buf[9] = 0x02;
+ buf[10] = 0x12;
+
+ for(uint8_t i = 0; i < 6; i++)
+ buf[i + 1] = bdaddr[i];
+
+ // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x05), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
+ pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x05, 0x03, 0x00, 11, 11, buf, NULL);
+}
+
+void PS3USB::getMoveBdaddr(uint8_t *bdaddr) {
+ uint8_t buf[16];
+
+ // bmRequest = Device to host (0x80) | Class (0x20) | Interface (0x01) = 0xA1, bRequest = Get Report (0x01), Report ID (0x04), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
+ pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_IN, HID_REQUEST_GET_REPORT, 0x04, 0x03, 0x00, 16, 16, buf, NULL);
+
+ for(uint8_t i = 0; i < 6; i++)
+ bdaddr[i] = buf[10 + i];
+}
+
+void PS3USB::getMoveCalibration(uint8_t *data) {
+ uint8_t buf[49];
+
+ for(uint8_t i = 0; i < 3; i++) {
+ // bmRequest = Device to host (0x80) | Class (0x20) | Interface (0x01) = 0xA1, bRequest = Get Report (0x01), Report ID (0x10), Report Type (Feature 0x03), interface (0x00), datalength, datalength, data
+ pUsb->ctrlReq(bAddress, epInfo[PS3_CONTROL_PIPE].epAddr, bmREQ_HID_IN, HID_REQUEST_GET_REPORT, 0x10, 0x03, 0x00, 49, 49, buf, NULL);
+
+ for(byte j = 0; j < 49; j++)
+ data[49 * i + j] = buf[j];
+ }
+}
+
+void PS3USB::onInit() {
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ else {
+ if(PS3MoveConnected)
+ moveSetBulb(Red);
+ else // Dualshock 3 or Navigation controller
+ setLedOn(LED1);
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3USB.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3USB.h
new file mode 100644
index 000000000..2eba9258c
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS3USB.h
@@ -0,0 +1,303 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _ps3usb_h_
+#define _ps3usb_h_
+
+#include "Usb.h"
+#include "hid.h"
+#include "PS3Enums.h"
+
+/* PS3 data taken from descriptors */
+#define EP_MAXPKTSIZE 64 // max size for data via USB
+
+/* Names we give to the 3 ps3 pipes - this is only used for setting the bluetooth address into the ps3 controllers */
+#define PS3_CONTROL_PIPE 0
+#define PS3_OUTPUT_PIPE 1
+#define PS3_INPUT_PIPE 2
+
+//PID and VID of the different devices
+#define PS3_VID 0x054C // Sony Corporation
+#define PS3_PID 0x0268 // PS3 Controller DualShock 3
+#define PS3NAVIGATION_PID 0x042F // Navigation controller
+#define PS3MOVE_PID 0x03D5 // Motion controller
+
+#define PS3_MAX_ENDPOINTS 3
+
+/**
+ * This class implements support for all the official PS3 Controllers:
+ * Dualshock 3, Navigation or a Motion controller via USB.
+ *
+ * One can only set the color of the bulb, set the rumble, set and get the bluetooth address and calibrate the magnetometer via USB on the Move controller.
+ *
+ * Information about the protocol can be found at the wiki: https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information.
+ */
+class PS3USB : public USBDeviceConfig {
+public:
+ /**
+ * Constructor for the PS3USB class.
+ * @param pUsb Pointer to USB class instance.
+ * @param btadr5,btadr4,btadr3,btadr2,btadr1,btadr0
+ * Pass your dongles Bluetooth address into the constructor,
+ * so you are able to pair the controller with a Bluetooth dongle.
+ */
+ PS3USB(USB *pUsb, uint8_t btadr5 = 0, uint8_t btadr4 = 0, uint8_t btadr3 = 0, uint8_t btadr2 = 0, uint8_t btadr1 = 0, uint8_t btadr0 = 0);
+
+ /** @name USBDeviceConfig implementation */
+ /**
+ * Initialize the PS3 Controller.
+ * @param parent Hub number.
+ * @param port Port number on the hub.
+ * @param lowspeed Speed of the device.
+ * @return 0 on success.
+ */
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ /**
+ * Release the USB device.
+ * @return 0 on success.
+ */
+ uint8_t Release();
+ /**
+ * Poll the USB Input endpoins and run the state machines.
+ * @return 0 on success.
+ */
+ uint8_t Poll();
+
+ /**
+ * Get the device address.
+ * @return The device address.
+ */
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ /**
+ * Used to check if the controller has been initialized.
+ * @return True if it's ready.
+ */
+ virtual bool isReady() {
+ return bPollEnable;
+ };
+
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return (vid == PS3_VID && (pid == PS3_PID || pid == PS3NAVIGATION_PID || pid == PS3MOVE_PID));
+ };
+ /**@}*/
+
+ /**
+ * Used to set the Bluetooth address inside the Dualshock 3 and Navigation controller.
+ * Set using LSB first.
+ * @param bdaddr Your dongles Bluetooth address.
+ */
+ void setBdaddr(uint8_t *bdaddr);
+ /**
+ * Used to get the Bluetooth address inside the Dualshock 3 and Navigation controller.
+ * Will return LSB first.
+ * @param bdaddr Your dongles Bluetooth address.
+ */
+ void getBdaddr(uint8_t *bdaddr);
+
+ /**
+ * Used to set the Bluetooth address inside the Move controller.
+ * Set using LSB first.
+ * @param bdaddr Your dongles Bluetooth address.
+ */
+ void setMoveBdaddr(uint8_t *bdaddr);
+ /**
+ * Used to get the Bluetooth address inside the Move controller.
+ * Will return LSB first.
+ * @param bdaddr Your dongles Bluetooth address.
+ */
+ void getMoveBdaddr(uint8_t *bdaddr);
+ /**
+ * Used to get the calibration data inside the Move controller.
+ * @param data Buffer to store data in. Must be at least 147 bytes
+ */
+ void getMoveCalibration(uint8_t *data);
+
+ /** @name PS3 Controller functions */
+ /**
+ * getButtonPress(ButtonEnum b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(ButtonEnum b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b),
+ * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b).
+ * @param b ::ButtonEnum to read.
+ * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press.
+ */
+ bool getButtonPress(ButtonEnum b);
+ bool getButtonClick(ButtonEnum b);
+ /**@}*/
+ /** @name PS3 Controller functions */
+ /**
+ * Used to get the analog value from button presses.
+ * @param a The ::ButtonEnum to read.
+ * The supported buttons are:
+ * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2,
+ * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T.
+ * @return Analog value in the range of 0-255.
+ */
+ uint8_t getAnalogButton(ButtonEnum a);
+ /**
+ * Used to read the analog joystick.
+ * @param a ::LeftHatX, ::LeftHatY, ::RightHatX, and ::RightHatY.
+ * @return Return the analog value in the range of 0-255.
+ */
+ uint8_t getAnalogHat(AnalogHatEnum a);
+ /**
+ * Used to read the sensors inside the Dualshock 3 controller.
+ * @param a
+ * The Dualshock 3 has a 3-axis accelerometer and a 1-axis gyro inside.
+ * @return Return the raw sensor value.
+ */
+ uint16_t getSensor(SensorEnum a);
+ /**
+ * Use this to get ::Pitch and ::Roll calculated using the accelerometer.
+ * @param a Either ::Pitch or ::Roll.
+ * @return Return the angle in the range of 0-360.
+ */
+ double getAngle(AngleEnum a);
+ /**
+ * Get the ::StatusEnum from the controller.
+ * @param c The ::StatusEnum you want to read.
+ * @return True if correct and false if not.
+ */
+ bool getStatus(StatusEnum c);
+ /** Read all the available statuses from the controller and prints it as a nice formated string. */
+ void printStatusString();
+
+ /** Used to set all LEDs and rumble off. */
+ void setAllOff();
+ /** Turn off rumble. */
+ void setRumbleOff();
+ /**
+ * Turn on rumble.
+ * @param mode Either ::RumbleHigh or ::RumbleLow.
+ */
+ void setRumbleOn(RumbleEnum mode);
+ /**
+ * Turn on rumble using custom duration and power.
+ * @param rightDuration The duration of the right/low rumble effect.
+ * @param rightPower The intensity of the right/low rumble effect.
+ * @param leftDuration The duration of the left/high rumble effect.
+ * @param leftPower The intensity of the left/high rumble effect.
+ */
+ void setRumbleOn(uint8_t rightDuration, uint8_t rightPower, uint8_t leftDuration, uint8_t leftPower);
+
+ /**
+ * Set LED value without using the ::LEDEnum.
+ * @param value See: ::LEDEnum.
+ */
+ void setLedRaw(uint8_t value);
+
+ /** Turn all LEDs off. */
+ void setLedOff() {
+ setLedRaw(0);
+ }
+ /**
+ * Turn the specific ::LEDEnum off.
+ * @param a The ::LEDEnum to turn off.
+ */
+ void setLedOff(LEDEnum a);
+ /**
+ * Turn the specific ::LEDEnum on.
+ * @param a The ::LEDEnum to turn on.
+ */
+ void setLedOn(LEDEnum a);
+ /**
+ * Toggle the specific ::LEDEnum.
+ * @param a The ::LEDEnum to toggle.
+ */
+ void setLedToggle(LEDEnum a);
+
+ /**
+ * Use this to set the Color using RGB values.
+ * @param r,g,b RGB value.
+ */
+ void moveSetBulb(uint8_t r, uint8_t g, uint8_t b);
+ /**
+ * Use this to set the color using the predefined colors in ::ColorsEnum.
+ * @param color The desired color.
+ */
+ void moveSetBulb(ColorsEnum color);
+ /**
+ * Set the rumble value inside the Move controller.
+ * @param rumble The desired value in the range from 64-255.
+ */
+ void moveSetRumble(uint8_t rumble);
+
+ /**
+ * Used to call your own function when the controller is successfully initialized.
+ * @param funcOnInit Function to call.
+ */
+ void attachOnInit(void (*funcOnInit)(void)) {
+ pFuncOnInit = funcOnInit;
+ };
+ /**@}*/
+
+ /** Variable used to indicate if the normal playstation controller is successfully connected. */
+ bool PS3Connected;
+ /** Variable used to indicate if the move controller is successfully connected. */
+ bool PS3MoveConnected;
+ /** Variable used to indicate if the navigation controller is successfully connected. */
+ bool PS3NavigationConnected;
+
+protected:
+ /** Pointer to USB class instance. */
+ USB *pUsb;
+ /** Device address. */
+ uint8_t bAddress;
+ /** Endpoint info structure. */
+ EpInfo epInfo[PS3_MAX_ENDPOINTS];
+
+private:
+ /**
+ * Called when the controller is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ void onInit();
+ void (*pFuncOnInit)(void); // Pointer to function called in onInit()
+
+ bool bPollEnable;
+
+ uint32_t timer; // used to continuously set PS3 Move controller Bulb and rumble values
+
+ uint32_t ButtonState;
+ uint32_t OldButtonState;
+ uint32_t ButtonClickState;
+
+ uint8_t my_bdaddr[6]; // Change to your dongles Bluetooth address in the constructor
+ uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
+ uint8_t writeBuf[EP_MAXPKTSIZE]; // General purpose buffer for output data
+
+ void readReport(); // read incoming data
+ void printReport(); // print incoming date - Uncomment for debugging
+
+ /* Private commands */
+ void PS3_Command(uint8_t *data, uint16_t nbytes);
+ void enable_sixaxis(); // Command used to enable the Dualshock 3 and Navigation controller to send data via USB
+ void Move_Command(uint8_t *data, uint16_t nbytes);
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4BT.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4BT.h
new file mode 100644
index 000000000..b7eb4b5a9
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4BT.h
@@ -0,0 +1,121 @@
+/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _ps4bt_h_
+#define _ps4bt_h_
+
+#include "BTHID.h"
+#include "PS4Parser.h"
+
+/**
+ * This class implements support for the PS4 controller via Bluetooth.
+ * It uses the BTHID class for all the Bluetooth communication.
+ */
+class PS4BT : public BTHID, public PS4Parser {
+public:
+ /**
+ * Constructor for the PS4BT class.
+ * @param p Pointer to the BTD class instance.
+ * @param pair Set this to true in order to pair with the device. If the argument is omitted then it will not pair with it. One can use ::PAIR to set it to true.
+ * @param pin Write the pin to BTD#btdPin. If argument is omitted, then "0000" will be used.
+ */
+ PS4BT(BTD *p, bool pair = false, const char *pin = "0000") :
+ BTHID(p, pair, pin) {
+ PS4Parser::Reset();
+ };
+
+ /**
+ * Used to check if a PS4 controller is connected.
+ * @return Returns true if it is connected.
+ */
+ bool connected() {
+ return BTHID::connected;
+ };
+
+protected:
+ /** @name BTHID implementation */
+ /**
+ * Used to parse Bluetooth HID data.
+ * @param len The length of the incoming data.
+ * @param buf Pointer to the data buffer.
+ */
+ virtual void ParseBTHIDData(uint8_t len, uint8_t *buf) {
+ PS4Parser::Parse(len, buf);
+ };
+
+ /**
+ * Called when a device is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ virtual void OnInitBTHID() {
+ PS4Parser::Reset();
+ enable_sixaxis(); // Make the controller send out the entire output report
+ if (pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ else
+ setLed(Blue);
+ };
+
+ /** Used to reset the different buffers to there default values */
+ virtual void ResetBTHID() {
+ PS4Parser::Reset();
+ };
+ /**@}*/
+
+ /** @name PS4Parser implementation */
+ virtual void sendOutputReport(PS4Output *output) { // Source: https://github.com/chrippa/ds4drv
+ uint8_t buf[79];
+ memset(buf, 0, sizeof(buf));
+
+ buf[0] = 0x52; // HID BT Set_report (0x50) | Report Type (Output 0x02)
+ buf[1] = 0x11; // Report ID
+ buf[2] = 0x80;
+ buf[4]= 0xFF;
+
+ buf[7] = output->smallRumble; // Small Rumble
+ buf[8] = output->bigRumble; // Big rumble
+
+ buf[9] = output->r; // Red
+ buf[10] = output->g; // Green
+ buf[11] = output->b; // Blue
+
+ buf[12] = output->flashOn; // Time to flash bright (255 = 2.5 seconds)
+ buf[13] = output->flashOff; // Time to flash dark (255 = 2.5 seconds)
+
+ output->reportChanged = false;
+
+ // The PS4 console actually set the four last bytes to a CRC32 checksum, but it seems like it is actually not needed
+
+ HID_Command(buf, sizeof(buf));
+ };
+ /**@}*/
+
+private:
+ void enable_sixaxis() { // Command used to make the PS4 controller send out the entire output report
+ uint8_t buf[2];
+ buf[0] = 0x43; // HID BT Get_report (0x40) | Report Type (Feature 0x03)
+ buf[1] = 0x02; // Report ID
+
+ HID_Command(buf, 2);
+ };
+
+ void HID_Command(uint8_t *data, uint8_t nbytes) {
+ pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]);
+ };
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4Parser.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4Parser.cpp
new file mode 100644
index 000000000..ca6adce40
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4Parser.cpp
@@ -0,0 +1,116 @@
+/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "PS4Parser.h"
+
+// To enable serial debugging see "settings.h"
+//#define PRINTREPORT // Uncomment to print the report send by the PS4 Controller
+
+bool PS4Parser::checkDpad(ButtonEnum b) {
+ switch (b) {
+ case UP:
+ return ps4Data.btn.dpad == DPAD_LEFT_UP || ps4Data.btn.dpad == DPAD_UP || ps4Data.btn.dpad == DPAD_UP_RIGHT;
+ case RIGHT:
+ return ps4Data.btn.dpad == DPAD_UP_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT || ps4Data.btn.dpad == DPAD_RIGHT_DOWN;
+ case DOWN:
+ return ps4Data.btn.dpad == DPAD_RIGHT_DOWN || ps4Data.btn.dpad == DPAD_DOWN || ps4Data.btn.dpad == DPAD_DOWN_LEFT;
+ case LEFT:
+ return ps4Data.btn.dpad == DPAD_DOWN_LEFT || ps4Data.btn.dpad == DPAD_LEFT || ps4Data.btn.dpad == DPAD_LEFT_UP;
+ default:
+ return false;
+ }
+}
+
+bool PS4Parser::getButtonPress(ButtonEnum b) {
+ if (b <= LEFT) // Dpad
+ return checkDpad(b);
+ else
+ return ps4Data.btn.val & (1UL << pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]));
+}
+
+bool PS4Parser::getButtonClick(ButtonEnum b) {
+ uint32_t mask = 1UL << pgm_read_byte(&PS4_BUTTONS[(uint8_t)b]);
+ bool click = buttonClickState.val & mask;
+ buttonClickState.val &= ~mask; // Clear "click" event
+ return click;
+}
+
+uint8_t PS4Parser::getAnalogButton(ButtonEnum b) {
+ if (b == L2) // These are the only analog buttons on the controller
+ return ps4Data.trigger[0];
+ else if (b == R2)
+ return ps4Data.trigger[1];
+ return 0;
+}
+
+uint8_t PS4Parser::getAnalogHat(AnalogHatEnum a) {
+ return ps4Data.hatValue[(uint8_t)a];
+}
+
+void PS4Parser::Parse(uint8_t len, uint8_t *buf) {
+ if (len > 1 && buf) {
+#ifdef PRINTREPORT
+ Notify(PSTR("\r\n"), 0x80);
+ for (uint8_t i = 0; i < len; i++) {
+ D_PrintHex<uint8_t > (buf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+#endif
+
+ if (buf[0] == 0x01) // Check report ID
+ memcpy(&ps4Data, buf + 1, min((uint8_t)(len - 1), sizeof(ps4Data)));
+ else if (buf[0] == 0x11) { // This report is send via Bluetooth, it has an offset of 2 compared to the USB data
+ if (len < 4) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReport is too short: "), 0x80);
+ D_PrintHex<uint8_t > (len, 0x80);
+#endif
+ return;
+ }
+ memcpy(&ps4Data, buf + 3, min((uint8_t)(len - 3), sizeof(ps4Data)));
+ } else {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nUnknown report id: "), 0x80);
+ D_PrintHex<uint8_t > (buf[0], 0x80);
+#endif
+ return;
+ }
+
+ if (ps4Data.btn.val != oldButtonState.val) { // Check if anything has changed
+ buttonClickState.val = ps4Data.btn.val & ~oldButtonState.val; // Update click state variable
+ oldButtonState.val = ps4Data.btn.val;
+
+ // The DPAD buttons does not set the different bits, but set a value corresponding to the buttons pressed, we will simply set the bits ourself
+ uint8_t newDpad = 0;
+ if (checkDpad(UP))
+ newDpad |= 1 << UP;
+ if (checkDpad(RIGHT))
+ newDpad |= 1 << RIGHT;
+ if (checkDpad(DOWN))
+ newDpad |= 1 << DOWN;
+ if (checkDpad(LEFT))
+ newDpad |= 1 << LEFT;
+ if (newDpad != oldDpad) {
+ buttonClickState.dpad = newDpad & ~oldDpad; // Override values
+ oldDpad = newDpad;
+ }
+ }
+ }
+
+ if (ps4Output.reportChanged)
+ sendOutputReport(&ps4Output); // Send output report
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4Parser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4Parser.h
new file mode 100644
index 000000000..51f080636
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4Parser.h
@@ -0,0 +1,407 @@
+/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _ps4parser_h_
+#define _ps4parser_h_
+
+#include "Usb.h"
+#include "controllerEnums.h"
+
+/** Buttons on the controller */
+const uint8_t PS4_BUTTONS[] PROGMEM = {
+ UP, // UP
+ RIGHT, // RIGHT
+ DOWN, // DOWN
+ LEFT, // LEFT
+
+ 0x0C, // SHARE
+ 0x0D, // OPTIONS
+ 0x0E, // L3
+ 0x0F, // R3
+
+ 0x0A, // L2
+ 0x0B, // R2
+ 0x08, // L1
+ 0x09, // R1
+
+ 0x07, // TRIANGLE
+ 0x06, // CIRCLE
+ 0x05, // CROSS
+ 0x04, // SQUARE
+
+ 0x10, // PS
+ 0x11, // TOUCHPAD
+};
+
+union PS4Buttons {
+ struct {
+ uint8_t dpad : 4;
+ uint8_t square : 1;
+ uint8_t cross : 1;
+ uint8_t circle : 1;
+ uint8_t triangle : 1;
+
+ uint8_t l1 : 1;
+ uint8_t r1 : 1;
+ uint8_t l2 : 1;
+ uint8_t r2 : 1;
+ uint8_t share : 1;
+ uint8_t options : 1;
+ uint8_t l3 : 1;
+ uint8_t r3 : 1;
+
+ uint8_t ps : 1;
+ uint8_t touchpad : 1;
+ uint8_t reportCounter : 6;
+ } __attribute__((packed));
+ uint32_t val : 24;
+} __attribute__((packed));
+
+struct touchpadXY {
+ uint8_t dummy; // I can not figure out what this data is for, it seems to change randomly, maybe a timestamp?
+ struct {
+ uint8_t counter : 7; // Increments every time a finger is touching the touchpad
+ uint8_t touching : 1; // The top bit is cleared if the finger is touching the touchpad
+ uint16_t x : 12;
+ uint16_t y : 12;
+ } __attribute__((packed)) finger[2]; // 0 = first finger, 1 = second finger
+} __attribute__((packed));
+
+struct PS4Status {
+ uint8_t battery : 4;
+ uint8_t usb : 1;
+ uint8_t audio : 1;
+ uint8_t mic : 1;
+ uint8_t unknown : 1; // Extension port?
+} __attribute__((packed));
+
+struct PS4Data {
+ /* Button and joystick values */
+ uint8_t hatValue[4];
+ PS4Buttons btn;
+ uint8_t trigger[2];
+
+ /* Gyro and accelerometer values */
+ uint8_t dummy[3]; // First two looks random, while the third one might be some kind of status - it increments once in a while
+ int16_t gyroY, gyroZ, gyroX;
+ int16_t accX, accZ, accY;
+
+ uint8_t dummy2[5];
+ PS4Status status;
+ uint8_t dummy3[3];
+
+ /* The rest is data for the touchpad */
+ touchpadXY xy[3]; // It looks like it sends out three coordinates each time, this might be because the microcontroller inside the PS4 controller is much faster than the Bluetooth connection.
+ // The last data is read from the last position in the array while the oldest measurement is from the first position.
+ // The first position will also keep it's value after the finger is released, while the other two will set them to zero.
+ // Note that if you read fast enough from the device, then only the first one will contain any data.
+
+ // The last three bytes are always: 0x00, 0x80, 0x00
+} __attribute__((packed));
+
+struct PS4Output {
+ uint8_t bigRumble, smallRumble; // Rumble
+ uint8_t r, g, b; // RGB
+ uint8_t flashOn, flashOff; // Time to flash bright/dark (255 = 2.5 seconds)
+ bool reportChanged; // The data is send when data is received from the controller
+} __attribute__((packed));
+
+enum DPADEnum {
+ DPAD_UP = 0x0,
+ DPAD_UP_RIGHT = 0x1,
+ DPAD_RIGHT = 0x2,
+ DPAD_RIGHT_DOWN = 0x3,
+ DPAD_DOWN = 0x4,
+ DPAD_DOWN_LEFT = 0x5,
+ DPAD_LEFT = 0x6,
+ DPAD_LEFT_UP = 0x7,
+ DPAD_OFF = 0x8,
+};
+
+/** This class parses all the data sent by the PS4 controller */
+class PS4Parser {
+public:
+ /** Constructor for the PS4Parser class. */
+ PS4Parser() {
+ Reset();
+ };
+
+ /** @name PS4 Controller functions */
+ /**
+ * getButtonPress(ButtonEnum b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(ButtonEnum b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b),
+ * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b).
+ * @param b ::ButtonEnum to read.
+ * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press.
+ */
+ bool getButtonPress(ButtonEnum b);
+ bool getButtonClick(ButtonEnum b);
+ /**@}*/
+ /** @name PS4 Controller functions */
+ /**
+ * Used to get the analog value from button presses.
+ * @param b The ::ButtonEnum to read.
+ * The supported buttons are:
+ * ::UP, ::RIGHT, ::DOWN, ::LEFT, ::L1, ::L2, ::R1, ::R2,
+ * ::TRIANGLE, ::CIRCLE, ::CROSS, ::SQUARE, and ::T.
+ * @return Analog value in the range of 0-255.
+ */
+ uint8_t getAnalogButton(ButtonEnum b);
+
+ /**
+ * Used to read the analog joystick.
+ * @param a ::LeftHatX, ::LeftHatY, ::RightHatX, and ::RightHatY.
+ * @return Return the analog value in the range of 0-255.
+ */
+ uint8_t getAnalogHat(AnalogHatEnum a);
+
+ /**
+ * Get the x-coordinate of the touchpad. Position 0 is in the top left.
+ * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used.
+ * @param xyId The controller sends out three packets with the same structure.
+ * The third one will contain the last measure, but if you read from the controller then there is only be data in the first one.
+ * For that reason it will be set to 0 if the argument is omitted.
+ * @return Returns the x-coordinate of the finger.
+ */
+ uint16_t getX(uint8_t finger = 0, uint8_t xyId = 0) {
+ return ps4Data.xy[xyId].finger[finger].x;
+ };
+
+ /**
+ * Get the y-coordinate of the touchpad. Position 0 is in the top left.
+ * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used.
+ * @param xyId The controller sends out three packets with the same structure.
+ * The third one will contain the last measure, but if you read from the controller then there is only be data in the first one.
+ * For that reason it will be set to 0 if the argument is omitted.
+ * @return Returns the y-coordinate of the finger.
+ */
+ uint16_t getY(uint8_t finger = 0, uint8_t xyId = 0) {
+ return ps4Data.xy[xyId].finger[finger].y;
+ };
+
+ /**
+ * Returns whenever the user is toucing the touchpad.
+ * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used.
+ * @param xyId The controller sends out three packets with the same structure.
+ * The third one will contain the last measure, but if you read from the controller then there is only be data in the first one.
+ * For that reason it will be set to 0 if the argument is omitted.
+ * @return Returns true if the specific finger is touching the touchpad.
+ */
+ bool isTouching(uint8_t finger = 0, uint8_t xyId = 0) {
+ return !(ps4Data.xy[xyId].finger[finger].touching); // The bit is cleared when a finger is touching the touchpad
+ };
+
+ /**
+ * This counter increments every time a finger touches the touchpad.
+ * @param finger 0 = first finger, 1 = second finger. If omitted, then 0 will be used.
+ * @param xyId The controller sends out three packets with the same structure.
+ * The third one will contain the last measure, but if you read from the controller then there is only be data in the first one.
+ * For that reason it will be set to 0 if the argument is omitted.
+ * @return Return the value of the counter, note that it is only a 7-bit value.
+ */
+ uint8_t getTouchCounter(uint8_t finger = 0, uint8_t xyId = 0) {
+ return ps4Data.xy[xyId].finger[finger].counter;
+ };
+
+ /**
+ * Get the angle of the controller calculated using the accelerometer.
+ * @param a Either ::Pitch or ::Roll.
+ * @return Return the angle in the range of 0-360.
+ */
+ double getAngle(AngleEnum a) {
+ if (a == Pitch)
+ return (atan2(ps4Data.accY, ps4Data.accZ) + PI) * RAD_TO_DEG;
+ else
+ return (atan2(ps4Data.accX, ps4Data.accZ) + PI) * RAD_TO_DEG;
+ };
+
+ /**
+ * Used to get the raw values from the 3-axis gyroscope and 3-axis accelerometer inside the PS4 controller.
+ * @param s The sensor to read.
+ * @return Returns the raw sensor reading.
+ */
+ int16_t getSensor(SensorEnum s) {
+ switch(s) {
+ case gX:
+ return ps4Data.gyroX;
+ case gY:
+ return ps4Data.gyroY;
+ case gZ:
+ return ps4Data.gyroZ;
+ case aX:
+ return ps4Data.accX;
+ case aY:
+ return ps4Data.accY;
+ case aZ:
+ return ps4Data.accZ;
+ default:
+ return 0;
+ }
+ };
+
+ /**
+ * Return the battery level of the PS4 controller.
+ * @return The battery level in the range 0-15.
+ */
+ uint8_t getBatteryLevel() {
+ return ps4Data.status.battery;
+ };
+
+ /**
+ * Use this to check if an USB cable is connected to the PS4 controller.
+ * @return Returns true if an USB cable is connected.
+ */
+ bool getUsbStatus() {
+ return ps4Data.status.usb;
+ };
+
+ /**
+ * Use this to check if an audio jack cable is connected to the PS4 controller.
+ * @return Returns true if an audio jack cable is connected.
+ */
+ bool getAudioStatus() {
+ return ps4Data.status.audio;
+ };
+
+ /**
+ * Use this to check if a microphone is connected to the PS4 controller.
+ * @return Returns true if a microphone is connected.
+ */
+ bool getMicStatus() {
+ return ps4Data.status.mic;
+ };
+
+ /** Turn both rumble and the LEDs off. */
+ void setAllOff() {
+ setRumbleOff();
+ setLedOff();
+ };
+
+ /** Set rumble off. */
+ void setRumbleOff() {
+ setRumbleOn(0, 0);
+ };
+
+ /**
+ * Turn on rumble.
+ * @param mode Either ::RumbleHigh or ::RumbleLow.
+ */
+ void setRumbleOn(RumbleEnum mode) {
+ if (mode == RumbleLow)
+ setRumbleOn(0x00, 0xFF);
+ else
+ setRumbleOn(0xFF, 0x00);
+ };
+
+ /**
+ * Turn on rumble.
+ * @param bigRumble Value for big motor.
+ * @param smallRumble Value for small motor.
+ */
+ void setRumbleOn(uint8_t bigRumble, uint8_t smallRumble) {
+ ps4Output.bigRumble = bigRumble;
+ ps4Output.smallRumble = smallRumble;
+ ps4Output.reportChanged = true;
+ };
+
+ /** Turn all LEDs off. */
+ void setLedOff() {
+ setLed(0, 0, 0);
+ };
+
+ /**
+ * Use this to set the color using RGB values.
+ * @param r,g,b RGB value.
+ */
+ void setLed(uint8_t r, uint8_t g, uint8_t b) {
+ ps4Output.r = r;
+ ps4Output.g = g;
+ ps4Output.b = b;
+ ps4Output.reportChanged = true;
+ };
+
+ /**
+ * Use this to set the color using the predefined colors in ::ColorsEnum.
+ * @param color The desired color.
+ */
+ void setLed(ColorsEnum color) {
+ setLed((uint8_t)(color >> 16), (uint8_t)(color >> 8), (uint8_t)(color));
+ };
+
+ /**
+ * Set the LEDs flash time.
+ * @param flashOn Time to flash bright (255 = 2.5 seconds).
+ * @param flashOff Time to flash dark (255 = 2.5 seconds).
+ */
+ void setLedFlash(uint8_t flashOn, uint8_t flashOff) {
+ ps4Output.flashOn = flashOn;
+ ps4Output.flashOff = flashOff;
+ ps4Output.reportChanged = true;
+ };
+ /**@}*/
+
+protected:
+ /**
+ * Used to parse data sent from the PS4 controller.
+ * @param len Length of the data.
+ * @param buf Pointer to the data buffer.
+ */
+ void Parse(uint8_t len, uint8_t *buf);
+
+ /** Used to reset the different buffers to their default values */
+ void Reset() {
+ uint8_t i;
+ for (i = 0; i < sizeof(ps4Data.hatValue); i++)
+ ps4Data.hatValue[i] = 127; // Center value
+ ps4Data.btn.val = 0;
+ oldButtonState.val = 0;
+ for (i = 0; i < sizeof(ps4Data.trigger); i++)
+ ps4Data.trigger[i] = 0;
+ for (i = 0; i < sizeof(ps4Data.xy)/sizeof(ps4Data.xy[0]); i++) {
+ for (uint8_t j = 0; j < sizeof(ps4Data.xy[0].finger)/sizeof(ps4Data.xy[0].finger[0]); j++)
+ ps4Data.xy[i].finger[j].touching = 1; // The bit is cleared if the finger is touching the touchpad
+ }
+
+ ps4Data.btn.dpad = DPAD_OFF;
+ oldButtonState.dpad = DPAD_OFF;
+ buttonClickState.dpad = 0;
+ oldDpad = 0;
+
+ ps4Output.bigRumble = ps4Output.smallRumble = 0;
+ ps4Output.r = ps4Output.g = ps4Output.b = 0;
+ ps4Output.flashOn = ps4Output.flashOff = 0;
+ ps4Output.reportChanged = false;
+ };
+
+ /**
+ * Send the output to the PS4 controller. This is implemented in PS4BT.h and PS4USB.h.
+ * @param output Pointer to PS4Output buffer;
+ */
+ virtual void sendOutputReport(PS4Output *output) = 0;
+
+private:
+ bool checkDpad(ButtonEnum b); // Used to check PS4 DPAD buttons
+
+ PS4Data ps4Data;
+ PS4Buttons oldButtonState, buttonClickState;
+ PS4Output ps4Output;
+ uint8_t oldDpad;
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4USB.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4USB.h
new file mode 100644
index 000000000..b43079a6e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PS4USB.h
@@ -0,0 +1,130 @@
+/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _ps4usb_h_
+#define _ps4usb_h_
+
+#include "hiduniversal.h"
+#include "PS4Parser.h"
+
+#define PS4_VID 0x054C // Sony Corporation
+#define PS4_PID 0x05C4 // PS4 Controller
+
+/**
+ * This class implements support for the PS4 controller via USB.
+ * It uses the HIDUniversal class for all the USB communication.
+ */
+class PS4USB : public HIDUniversal, public PS4Parser {
+public:
+ /**
+ * Constructor for the PS4USB class.
+ * @param p Pointer to the USB class instance.
+ */
+ PS4USB(USB *p) :
+ HIDUniversal(p) {
+ PS4Parser::Reset();
+ };
+
+ /**
+ * Used to check if a PS4 controller is connected.
+ * @return Returns true if it is connected.
+ */
+ bool connected() {
+ return HIDUniversal::isReady() && HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID;
+ };
+
+ /**
+ * Used to call your own function when the device is successfully initialized.
+ * @param funcOnInit Function to call.
+ */
+ void attachOnInit(void (*funcOnInit)(void)) {
+ pFuncOnInit = funcOnInit;
+ };
+
+protected:
+ /** @name HIDUniversal implementation */
+ /**
+ * Used to parse USB HID data.
+ * @param hid Pointer to the HID class.
+ * @param is_rpt_id Only used for Hubs.
+ * @param len The length of the incoming data.
+ * @param buf Pointer to the data buffer.
+ */
+ virtual void ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
+ if (HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID)
+ PS4Parser::Parse(len, buf);
+ };
+
+ /**
+ * Called when a device is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ virtual uint8_t OnInitSuccessful() {
+ if (HIDUniversal::VID == PS4_VID && HIDUniversal::PID == PS4_PID) {
+ PS4Parser::Reset();
+ if (pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ else
+ setLed(Blue);
+ };
+ return 0;
+ };
+ /**@}*/
+
+ /** @name PS4Parser implementation */
+ virtual void sendOutputReport(PS4Output *output) { // Source: https://github.com/chrippa/ds4drv
+ uint8_t buf[32];
+ memset(buf, 0, sizeof(buf));
+
+ buf[0] = 0x05; // Report ID
+ buf[1]= 0xFF;
+
+ buf[4] = output->smallRumble; // Small Rumble
+ buf[5] = output->bigRumble; // Big rumble
+
+ buf[6] = output->r; // Red
+ buf[7] = output->g; // Green
+ buf[8] = output->b; // Blue
+
+ buf[9] = output->flashOn; // Time to flash bright (255 = 2.5 seconds)
+ buf[10] = output->flashOff; // Time to flash dark (255 = 2.5 seconds)
+
+ output->reportChanged = false;
+
+ // The PS4 console actually set the four last bytes to a CRC32 checksum, but it seems like it is actually not needed
+
+ pUsb->outTransfer(bAddress, epInfo[ hidInterfaces[0].epIndex[epInterruptOutIndex] ].epAddr, sizeof(buf), buf);
+ };
+ /**@}*/
+
+ /** @name USBDeviceConfig implementation */
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return (vid == PS4_VID && pid == PS4_PID);
+ };
+ /**@}*/
+
+private:
+ void (*pFuncOnInit)(void); // Pointer to function called in onInit()
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PSBuzz.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PSBuzz.cpp
new file mode 100644
index 000000000..498164d5a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PSBuzz.cpp
@@ -0,0 +1,82 @@
+/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "PSBuzz.h"
+
+// To enable serial debugging see "settings.h"
+//#define PRINTREPORT // Uncomment to print the report send by the PS Buzz Controllers
+
+void PSBuzz::ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
+ if (HIDUniversal::VID == PSBUZZ_VID && HIDUniversal::PID == PSBUZZ_PID && len > 2 && buf) {
+#ifdef PRINTREPORT
+ Notify(PSTR("\r\n"), 0x80);
+ for (uint8_t i = 0; i < len; i++) {
+ D_PrintHex<uint8_t > (buf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+#endif
+ memcpy(&psbuzzButtons, buf + 2, min((uint8_t)(len - 2), sizeof(psbuzzButtons)));
+
+ if (psbuzzButtons.val != oldButtonState.val) { // Check if anything has changed
+ buttonClickState.val = psbuzzButtons.val & ~oldButtonState.val; // Update click state variable
+ oldButtonState.val = psbuzzButtons.val;
+ }
+ }
+};
+
+uint8_t PSBuzz::OnInitSuccessful() {
+ if (HIDUniversal::VID == PSBUZZ_VID && HIDUniversal::PID == PSBUZZ_PID) {
+ Reset();
+ if (pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ else
+ setLedOnAll(); // Turn the LED on, on all four controllers
+ };
+ return 0;
+};
+
+bool PSBuzz::getButtonPress(ButtonEnum b, uint8_t controller) {
+ return psbuzzButtons.val & (1UL << (b + 5 * controller)); // Each controller uses 5 bits, so the value is shifted 5 for each controller
+};
+
+bool PSBuzz::getButtonClick(ButtonEnum b, uint8_t controller) {
+ uint32_t mask = (1UL << (b + 5 * controller)); // Each controller uses 5 bits, so the value is shifted 5 for each controller
+ bool click = buttonClickState.val & mask;
+ buttonClickState.val &= ~mask; // Clear "click" event
+ return click;
+};
+
+// Source: http://www.developerfusion.com/article/84338/making-usb-c-friendly/ and https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c
+void PSBuzz::setLedRaw(bool value, uint8_t controller) {
+ ledState[controller] = value; // Save value for next time it is called
+
+ uint8_t buf[7];
+ buf[0] = 0x00;
+ buf[1] = ledState[0] ? 0xFF : 0x00;
+ buf[2] = ledState[1] ? 0xFF : 0x00;
+ buf[3] = ledState[2] ? 0xFF : 0x00;
+ buf[4] = ledState[3] ? 0xFF : 0x00;
+ buf[5] = 0x00;
+ buf[6] = 0x00;
+
+ PSBuzz_Command(buf, sizeof(buf));
+};
+
+void PSBuzz::PSBuzz_Command(uint8_t *data, uint16_t nbytes) {
+ // bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x00), Report Type (Output 0x02), interface (0x00), datalength, datalength, data)
+ pUsb->ctrlReq(bAddress, epInfo[0].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x00, 0x02, 0x00, nbytes, nbytes, data, NULL);
+};
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PSBuzz.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PSBuzz.h
new file mode 100644
index 000000000..8880d9e50
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/PSBuzz.h
@@ -0,0 +1,185 @@
+/* Copyright (C) 2014 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _psbuzz_h_
+#define _psbuzz_h_
+
+#include "hiduniversal.h"
+#include "controllerEnums.h"
+
+#define PSBUZZ_VID 0x054C // Sony Corporation
+#define PSBUZZ_PID 0x1000 // PS Buzz Controller
+
+/** Struct used to easily read the different buttons on the controllers */
+union PSBUZZButtons {
+ struct {
+ uint8_t red : 1;
+ uint8_t yellow : 1;
+ uint8_t green : 1;
+ uint8_t orange : 1;
+ uint8_t blue : 1;
+ } __attribute__((packed)) btn[4];
+ uint32_t val : 20;
+} __attribute__((packed));
+
+/**
+ * This class implements support for the PS Buzz controllers via USB.
+ * It uses the HIDUniversal class for all the USB communication.
+ */
+class PSBuzz : public HIDUniversal {
+public:
+ /**
+ * Constructor for the PSBuzz class.
+ * @param p Pointer to the USB class instance.
+ */
+ PSBuzz(USB *p) :
+ HIDUniversal(p) {
+ Reset();
+ };
+
+ /**
+ * Used to check if a PS Buzz controller is connected.
+ * @return Returns true if it is connected.
+ */
+ bool connected() {
+ return HIDUniversal::isReady() && HIDUniversal::VID == PSBUZZ_VID && HIDUniversal::PID == PSBUZZ_PID;
+ };
+
+ /**
+ * Used to call your own function when the device is successfully initialized.
+ * @param funcOnInit Function to call.
+ */
+ void attachOnInit(void (*funcOnInit)(void)) {
+ pFuncOnInit = funcOnInit;
+ };
+
+ /** @name PS Buzzer Controller functions */
+ /**
+ * getButtonPress(ButtonEnum b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(ButtonEnum b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b),
+ * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b).
+ * @param b ::ButtonEnum to read.
+ * @param controller The controller to read from. Default to 0.
+ * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press.
+ */
+ bool getButtonPress(ButtonEnum b, uint8_t controller = 0);
+ bool getButtonClick(ButtonEnum b, uint8_t controller = 0);
+ /**@}*/
+ /** @name PS Buzzer Controller functions */
+ /**
+ * Set LED value without using ::LEDEnum.
+ * @param value See: ::LEDEnum.
+ */
+ /**
+ * Set LED values directly.
+ * @param value Used to set whenever the LED should be on or off
+ * @param controller The controller to control. Defaults to 0.
+ */
+ void setLedRaw(bool value, uint8_t controller = 0);
+
+ /** Turn all LEDs off. */
+ void setLedOffAll() {
+ for (uint8_t i = 1; i < 4; i++) // Skip first as it will be set in setLedRaw
+ ledState[i] = false; // Just an easy way to set all four off at the same time
+ setLedRaw(false); // Turn the LED off, on all four controllers
+ };
+
+ /**
+ * Turn the LED off on a specific controller.
+ * @param controller The controller to turn off. Defaults to 0.
+ */
+ void setLedOff(uint8_t controller = 0) {
+ setLedRaw(false, controller);
+ };
+
+
+ /** Turn all LEDs on. */
+ void setLedOnAll() {
+ for (uint8_t i = 1; i < 4; i++) // Skip first as it will be set in setLedRaw
+ ledState[i] = true; // Just an easy way to set all four off at the same time
+ setLedRaw(true); // Turn the LED on, on all four controllers
+ };
+
+ /**
+ * Turn the LED on on a specific controller.
+ * @param controller The controller to turn off. Defaults to 0.
+ */
+ void setLedOn(uint8_t controller = 0) {
+ setLedRaw(true, controller);
+ };
+
+ /**
+ * Toggle the LED on a specific controller.
+ * @param controller The controller to turn off. Defaults to 0.
+ */
+ void setLedToggle(uint8_t controller = 0) {
+ setLedRaw(!ledState[controller], controller);
+ };
+ /**@}*/
+
+protected:
+ /** @name HIDUniversal implementation */
+ /**
+ * Used to parse USB HID data.
+ * @param hid Pointer to the HID class.
+ * @param is_rpt_id Only used for Hubs.
+ * @param len The length of the incoming data.
+ * @param buf Pointer to the data buffer.
+ */
+ void ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
+
+ /**
+ * Called when a device is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ uint8_t OnInitSuccessful();
+ /**@}*/
+
+ /** Used to reset the different buffers to their default values */
+ void Reset() {
+ psbuzzButtons.val = 0;
+ oldButtonState.val = 0;
+ buttonClickState.val = 0;
+ for (uint8_t i = 0; i < sizeof(ledState); i++)
+ ledState[i] = 0;
+ };
+
+ /** @name USBDeviceConfig implementation */
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return (vid == PSBUZZ_VID && pid == PSBUZZ_PID);
+ };
+ /**@}*/
+
+private:
+ void (*pFuncOnInit)(void); // Pointer to function called in onInit()
+
+ void PSBuzz_Command(uint8_t *data, uint16_t nbytes);
+
+ PSBUZZButtons psbuzzButtons, oldButtonState, buttonClickState;
+ bool ledState[4];
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/SPP.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/SPP.cpp
new file mode 100644
index 000000000..0f4ee5e98
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/SPP.cpp
@@ -0,0 +1,829 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "SPP.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report sent to the Arduino
+
+/*
+ * CRC (reversed crc) lookup table as calculated by the table generator in ETSI TS 101 369 V6.3.0.
+ */
+const uint8_t rfcomm_crc_table[256] PROGMEM = {/* reversed, 8-bit, poly=0x07 */
+ 0x00, 0x91, 0xE3, 0x72, 0x07, 0x96, 0xE4, 0x75, 0x0E, 0x9F, 0xED, 0x7C, 0x09, 0x98, 0xEA, 0x7B,
+ 0x1C, 0x8D, 0xFF, 0x6E, 0x1B, 0x8A, 0xF8, 0x69, 0x12, 0x83, 0xF1, 0x60, 0x15, 0x84, 0xF6, 0x67,
+ 0x38, 0xA9, 0xDB, 0x4A, 0x3F, 0xAE, 0xDC, 0x4D, 0x36, 0xA7, 0xD5, 0x44, 0x31, 0xA0, 0xD2, 0x43,
+ 0x24, 0xB5, 0xC7, 0x56, 0x23, 0xB2, 0xC0, 0x51, 0x2A, 0xBB, 0xC9, 0x58, 0x2D, 0xBC, 0xCE, 0x5F,
+ 0x70, 0xE1, 0x93, 0x02, 0x77, 0xE6, 0x94, 0x05, 0x7E, 0xEF, 0x9D, 0x0C, 0x79, 0xE8, 0x9A, 0x0B,
+ 0x6C, 0xFD, 0x8F, 0x1E, 0x6B, 0xFA, 0x88, 0x19, 0x62, 0xF3, 0x81, 0x10, 0x65, 0xF4, 0x86, 0x17,
+ 0x48, 0xD9, 0xAB, 0x3A, 0x4F, 0xDE, 0xAC, 0x3D, 0x46, 0xD7, 0xA5, 0x34, 0x41, 0xD0, 0xA2, 0x33,
+ 0x54, 0xC5, 0xB7, 0x26, 0x53, 0xC2, 0xB0, 0x21, 0x5A, 0xCB, 0xB9, 0x28, 0x5D, 0xCC, 0xBE, 0x2F,
+ 0xE0, 0x71, 0x03, 0x92, 0xE7, 0x76, 0x04, 0x95, 0xEE, 0x7F, 0x0D, 0x9C, 0xE9, 0x78, 0x0A, 0x9B,
+ 0xFC, 0x6D, 0x1F, 0x8E, 0xFB, 0x6A, 0x18, 0x89, 0xF2, 0x63, 0x11, 0x80, 0xF5, 0x64, 0x16, 0x87,
+ 0xD8, 0x49, 0x3B, 0xAA, 0xDF, 0x4E, 0x3C, 0xAD, 0xD6, 0x47, 0x35, 0xA4, 0xD1, 0x40, 0x32, 0xA3,
+ 0xC4, 0x55, 0x27, 0xB6, 0xC3, 0x52, 0x20, 0xB1, 0xCA, 0x5B, 0x29, 0xB8, 0xCD, 0x5C, 0x2E, 0xBF,
+ 0x90, 0x01, 0x73, 0xE2, 0x97, 0x06, 0x74, 0xE5, 0x9E, 0x0F, 0x7D, 0xEC, 0x99, 0x08, 0x7A, 0xEB,
+ 0x8C, 0x1D, 0x6F, 0xFE, 0x8B, 0x1A, 0x68, 0xF9, 0x82, 0x13, 0x61, 0xF0, 0x85, 0x14, 0x66, 0xF7,
+ 0xA8, 0x39, 0x4B, 0xDA, 0xAF, 0x3E, 0x4C, 0xDD, 0xA6, 0x37, 0x45, 0xD4, 0xA1, 0x30, 0x42, 0xD3,
+ 0xB4, 0x25, 0x57, 0xC6, 0xB3, 0x22, 0x50, 0xC1, 0xBA, 0x2B, 0x59, 0xC8, 0xBD, 0x2C, 0x5E, 0xCF
+};
+
+SPP::SPP(BTD *p, const char* name, const char* pin) :
+BluetoothService(p) // Pointer to BTD class instance - mandatory
+{
+ pBtd->btdName = name;
+ pBtd->btdPin = pin;
+
+ /* Set device cid for the SDP and RFCOMM channelse */
+ sdp_dcid[0] = 0x50; // 0x0050
+ sdp_dcid[1] = 0x00;
+ rfcomm_dcid[0] = 0x51; // 0x0051
+ rfcomm_dcid[1] = 0x00;
+
+ Reset();
+}
+
+void SPP::Reset() {
+ connected = false;
+ RFCOMMConnected = false;
+ SDPConnected = false;
+ waitForLastCommand = false;
+ l2cap_sdp_state = L2CAP_SDP_WAIT;
+ l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT;
+ l2cap_event_flag = 0;
+ sppIndex = 0;
+ creditSent = false;
+}
+
+void SPP::disconnect() {
+ connected = false;
+ // First the two L2CAP channels has to be disconnected and then the HCI connection
+ if(RFCOMMConnected)
+ pBtd->l2cap_disconnection_request(hci_handle, ++identifier, rfcomm_scid, rfcomm_dcid);
+ if(RFCOMMConnected && SDPConnected)
+ delay(1); // Add delay between commands
+ if(SDPConnected)
+ pBtd->l2cap_disconnection_request(hci_handle, ++identifier, sdp_scid, sdp_dcid);
+ l2cap_sdp_state = L2CAP_DISCONNECT_RESPONSE;
+}
+
+void SPP::ACLData(uint8_t* l2capinbuf) {
+ if(!connected) {
+ if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
+ if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM && !pBtd->sdpConnectionClaimed) {
+ pBtd->sdpConnectionClaimed = true;
+ hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
+ l2cap_sdp_state = L2CAP_SDP_WAIT; // Reset state
+ } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == RFCOMM_PSM && !pBtd->rfcommConnectionClaimed) {
+ pBtd->rfcommConnectionClaimed = true;
+ hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
+ l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT; // Reset state
+ }
+ }
+ }
+
+ if(checkHciHandle(l2capinbuf, hci_handle)) { // acl_handle_ok
+ if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U
+ if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ Notify(PSTR(" Data: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+#endif
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ Notify(PSTR(" SCID: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+ Notify(PSTR(" Identifier: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
+#endif
+ if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == SDP_PSM) { // It doesn't matter if it receives another reqeust, since it waits for the channel to disconnect in the L2CAP_SDP_DONE state, and the l2cap_event_flag will be cleared if so
+ identifier = l2capinbuf[9];
+ sdp_scid[0] = l2capinbuf[14];
+ sdp_scid[1] = l2capinbuf[15];
+ l2cap_set_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST);
+ } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == RFCOMM_PSM) { // ----- || -----
+ identifier = l2capinbuf[9];
+ rfcomm_scid[0] = l2capinbuf[14];
+ rfcomm_scid[1] = l2capinbuf[15];
+ l2cap_set_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) {
+ if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success
+ if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
+ //Notify(PSTR("\r\nSDP Configuration Complete"), 0x80);
+ l2cap_set_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS);
+ } else if(l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) {
+ //Notify(PSTR("\r\nRFCOMM Configuration Complete"), 0x80);
+ l2cap_set_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS);
+ }
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) {
+ if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
+ //Notify(PSTR("\r\nSDP Configuration Request"), 0x80);
+ pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], sdp_scid);
+ } else if(l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) {
+ //Notify(PSTR("\r\nRFCOMM Configuration Request"), 0x80);
+ pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], rfcomm_scid);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) {
+ if(l2capinbuf[12] == sdp_dcid[0] && l2capinbuf[13] == sdp_dcid[1]) {
+ //Notify(PSTR("\r\nDisconnect Request: SDP Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST);
+ } else if(l2capinbuf[12] == rfcomm_dcid[0] && l2capinbuf[13] == rfcomm_dcid[1]) {
+ //Notify(PSTR("\r\nDisconnect Request: RFCOMM Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) {
+ if(l2capinbuf[12] == sdp_scid[0] && l2capinbuf[13] == sdp_scid[1]) {
+ //Notify(PSTR("\r\nDisconnect Response: SDP Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RESPONSE);
+ } else if(l2capinbuf[12] == rfcomm_scid[0] && l2capinbuf[13] == rfcomm_scid[1]) {
+ //Notify(PSTR("\r\nDisconnect Response: RFCOMM Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_RESPONSE);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_INFORMATION_REQUEST) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nInformation request"), 0x80);
+#endif
+ identifier = l2capinbuf[9];
+ pBtd->l2cap_information_response(hci_handle, identifier, l2capinbuf[12], l2capinbuf[13]);
+ }
+#ifdef EXTRADEBUG
+ else {
+ Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
+ }
+#endif
+ } else if(l2capinbuf[6] == sdp_dcid[0] && l2capinbuf[7] == sdp_dcid[1]) { // SDP
+ if(l2capinbuf[8] == SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST_PDU) {
+ if(((l2capinbuf[16] << 8 | l2capinbuf[17]) == SERIALPORT_UUID) || ((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000 && (l2capinbuf[18] << 8 | l2capinbuf[19]) == SERIALPORT_UUID)) { // Check if it's sending the full UUID, see: https://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm, we will just check the first four bytes
+ if(firstMessage) {
+ serialPortResponse1(l2capinbuf[9], l2capinbuf[10]);
+ firstMessage = false;
+ } else {
+ serialPortResponse2(l2capinbuf[9], l2capinbuf[10]); // Serialport continuation state
+ firstMessage = true;
+ }
+ } else if(((l2capinbuf[16] << 8 | l2capinbuf[17]) == L2CAP_UUID) || ((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000 && (l2capinbuf[18] << 8 | l2capinbuf[19]) == L2CAP_UUID)) {
+ if(firstMessage) {
+ l2capResponse1(l2capinbuf[9], l2capinbuf[10]);
+ firstMessage = false;
+ } else {
+ l2capResponse2(l2capinbuf[9], l2capinbuf[10]); // L2CAP continuation state
+ firstMessage = true;
+ }
+ } else
+ serviceNotSupported(l2capinbuf[9], l2capinbuf[10]); // The service is not supported
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nUUID: "), 0x80);
+ uint16_t uuid;
+ if((l2capinbuf[16] << 8 | l2capinbuf[17]) == 0x0000) // Check if it's sending the UUID as a 128-bit UUID
+ uuid = (l2capinbuf[18] << 8 | l2capinbuf[19]);
+ else // Short UUID
+ uuid = (l2capinbuf[16] << 8 | l2capinbuf[17]);
+ D_PrintHex<uint16_t > (uuid, 0x80);
+
+ Notify(PSTR("\r\nLength: "), 0x80);
+ uint16_t length = l2capinbuf[11] << 8 | l2capinbuf[12];
+ D_PrintHex<uint16_t > (length, 0x80);
+ Notify(PSTR("\r\nData: "), 0x80);
+ for(uint8_t i = 0; i < length; i++) {
+ D_PrintHex<uint8_t > (l2capinbuf[13 + i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+#endif
+ }
+#ifdef EXTRADEBUG
+ else {
+ Notify(PSTR("\r\nUnknown PDU: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
+ }
+#endif
+ } else if(l2capinbuf[6] == rfcomm_dcid[0] && l2capinbuf[7] == rfcomm_dcid[1]) { // RFCOMM
+ rfcommChannel = l2capinbuf[8] & 0xF8;
+ rfcommDirection = l2capinbuf[8] & 0x04;
+ rfcommCommandResponse = l2capinbuf[8] & 0x02;
+ rfcommChannelType = l2capinbuf[9] & 0xEF;
+ rfcommPfBit = l2capinbuf[9] & 0x10;
+
+ if(rfcommChannel >> 3 != 0x00)
+ rfcommChannelConnection = rfcommChannel;
+
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nRFCOMM Channel: "), 0x80);
+ D_PrintHex<uint8_t > (rfcommChannel >> 3, 0x80);
+ Notify(PSTR(" Direction: "), 0x80);
+ D_PrintHex<uint8_t > (rfcommDirection >> 2, 0x80);
+ Notify(PSTR(" CommandResponse: "), 0x80);
+ D_PrintHex<uint8_t > (rfcommCommandResponse >> 1, 0x80);
+ Notify(PSTR(" ChannelType: "), 0x80);
+ D_PrintHex<uint8_t > (rfcommChannelType, 0x80);
+ Notify(PSTR(" PF_BIT: "), 0x80);
+ D_PrintHex<uint8_t > (rfcommPfBit, 0x80);
+#endif
+ if(rfcommChannelType == RFCOMM_DISC) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReceived Disconnect RFCOMM Command on channel: "), 0x80);
+ D_PrintHex<uint8_t > (rfcommChannel >> 3, 0x80);
+#endif
+ connected = false;
+ sendRfcomm(rfcommChannel, rfcommDirection, rfcommCommandResponse, RFCOMM_UA, rfcommPfBit, rfcommbuf, 0x00); // UA Command
+ }
+ if(connected) {
+ /* Read the incoming message */
+ if(rfcommChannelType == RFCOMM_UIH && rfcommChannel == rfcommChannelConnection) {
+ uint8_t length = l2capinbuf[10] >> 1; // Get length
+ uint8_t offset = l2capinbuf[4] - length - 4; // Check if there is credit
+ if(checkFcs(&l2capinbuf[8], l2capinbuf[11 + length + offset])) {
+ uint8_t i = 0;
+ for(; i < length; i++) {
+ if(rfcommAvailable + i >= sizeof (rfcommDataBuffer)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWarning: Buffer is full!"), 0x80);
+#endif
+ break;
+ }
+ rfcommDataBuffer[rfcommAvailable + i] = l2capinbuf[11 + i + offset];
+ }
+ rfcommAvailable += i;
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nRFCOMM Data Available: "), 0x80);
+ Notify(rfcommAvailable, 0x80);
+ if(offset) {
+ Notify(PSTR(" - Credit: 0x"), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[11], 0x80);
+ }
+#endif
+ }
+#ifdef DEBUG_USB_HOST
+ else
+ Notify(PSTR("\r\nError in FCS checksum!"), 0x80);
+#endif
+#ifdef PRINTREPORT // Uncomment "#define PRINTREPORT" to print the report send to the Arduino via Bluetooth
+ for(uint8_t i = 0; i < length; i++)
+ Notifyc(l2capinbuf[i + 11 + offset], 0x80);
+#endif
+ } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_RPN_CMD) { // UIH Remote Port Negotiation Command
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReceived UIH Remote Port Negotiation Command"), 0x80);
+#endif
+ rfcommbuf[0] = BT_RFCOMM_RPN_RSP; // Command
+ rfcommbuf[1] = l2capinbuf[12]; // Length and shiftet like so: length << 1 | 1
+ rfcommbuf[2] = l2capinbuf[13]; // Channel: channel << 1 | 1
+ rfcommbuf[3] = l2capinbuf[14]; // Pre difined for Bluetooth, see 5.5.3 of TS 07.10 Adaption for RFCOMM
+ rfcommbuf[4] = l2capinbuf[15]; // Priority
+ rfcommbuf[5] = l2capinbuf[16]; // Timer
+ rfcommbuf[6] = l2capinbuf[17]; // Max Fram Size LSB
+ rfcommbuf[7] = l2capinbuf[18]; // Max Fram Size MSB
+ rfcommbuf[8] = l2capinbuf[19]; // MaxRatransm.
+ rfcommbuf[9] = l2capinbuf[20]; // Number of Frames
+ sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x0A); // UIH Remote Port Negotiation Response
+ } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_CMD) { // UIH Modem Status Command
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend UIH Modem Status Response"), 0x80);
+#endif
+ rfcommbuf[0] = BT_RFCOMM_MSC_RSP; // UIH Modem Status Response
+ rfcommbuf[1] = 2 << 1 | 1; // Length and shiftet like so: length << 1 | 1
+ rfcommbuf[2] = l2capinbuf[13]; // Channel: (1 << 0) | (1 << 1) | (0 << 2) | (channel << 3)
+ rfcommbuf[3] = l2capinbuf[14];
+ sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x04);
+ }
+ } else {
+ if(rfcommChannelType == RFCOMM_SABM) { // SABM Command - this is sent twice: once for channel 0 and then for the channel to establish
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReceived SABM Command"), 0x80);
+#endif
+ sendRfcomm(rfcommChannel, rfcommDirection, rfcommCommandResponse, RFCOMM_UA, rfcommPfBit, rfcommbuf, 0x00); // UA Command
+ } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_PN_CMD) { // UIH Parameter Negotiation Command
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReceived UIH Parameter Negotiation Command"), 0x80);
+#endif
+ rfcommbuf[0] = BT_RFCOMM_PN_RSP; // UIH Parameter Negotiation Response
+ rfcommbuf[1] = l2capinbuf[12]; // Length and shiftet like so: length << 1 | 1
+ rfcommbuf[2] = l2capinbuf[13]; // Channel: channel << 1 | 1
+ rfcommbuf[3] = 0xE0; // Pre difined for Bluetooth, see 5.5.3 of TS 07.10 Adaption for RFCOMM
+ rfcommbuf[4] = 0x00; // Priority
+ rfcommbuf[5] = 0x00; // Timer
+ rfcommbuf[6] = BULK_MAXPKTSIZE - 14; // Max Fram Size LSB - set to the size of received data (50)
+ rfcommbuf[7] = 0x00; // Max Fram Size MSB
+ rfcommbuf[8] = 0x00; // MaxRatransm.
+ rfcommbuf[9] = 0x00; // Number of Frames
+ sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x0A);
+ } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_CMD) { // UIH Modem Status Command
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend UIH Modem Status Response"), 0x80);
+#endif
+ rfcommbuf[0] = BT_RFCOMM_MSC_RSP; // UIH Modem Status Response
+ rfcommbuf[1] = 2 << 1 | 1; // Length and shiftet like so: length << 1 | 1
+ rfcommbuf[2] = l2capinbuf[13]; // Channel: (1 << 0) | (1 << 1) | (0 << 2) | (channel << 3)
+ rfcommbuf[3] = l2capinbuf[14];
+ sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x04);
+
+ delay(1);
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend UIH Modem Status Command"), 0x80);
+#endif
+ rfcommbuf[0] = BT_RFCOMM_MSC_CMD; // UIH Modem Status Command
+ rfcommbuf[1] = 2 << 1 | 1; // Length and shiftet like so: length << 1 | 1
+ rfcommbuf[2] = l2capinbuf[13]; // Channel: (1 << 0) | (1 << 1) | (0 << 2) | (channel << 3)
+ rfcommbuf[3] = 0x8D; // Can receive frames (YES), Ready to Communicate (YES), Ready to Receive (YES), Incomig Call (NO), Data is Value (YES)
+
+ sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x04);
+ } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_MSC_RSP) { // UIH Modem Status Response
+ if(!creditSent) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend UIH Command with credit"), 0x80);
+#endif
+ sendRfcommCredit(rfcommChannelConnection, rfcommDirection, 0, RFCOMM_UIH, 0x10, sizeof (rfcommDataBuffer)); // Send credit
+ creditSent = true;
+ timer = millis();
+ waitForLastCommand = true;
+ }
+ } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[10] == 0x01) { // UIH Command with credit
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReceived UIH Command with credit"), 0x80);
+#endif
+ } else if(rfcommChannelType == RFCOMM_UIH && l2capinbuf[11] == BT_RFCOMM_RPN_CMD) { // UIH Remote Port Negotiation Command
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReceived UIH Remote Port Negotiation Command"), 0x80);
+#endif
+ rfcommbuf[0] = BT_RFCOMM_RPN_RSP; // Command
+ rfcommbuf[1] = l2capinbuf[12]; // Length and shiftet like so: length << 1 | 1
+ rfcommbuf[2] = l2capinbuf[13]; // Channel: channel << 1 | 1
+ rfcommbuf[3] = l2capinbuf[14]; // Pre difined for Bluetooth, see 5.5.3 of TS 07.10 Adaption for RFCOMM
+ rfcommbuf[4] = l2capinbuf[15]; // Priority
+ rfcommbuf[5] = l2capinbuf[16]; // Timer
+ rfcommbuf[6] = l2capinbuf[17]; // Max Fram Size LSB
+ rfcommbuf[7] = l2capinbuf[18]; // Max Fram Size MSB
+ rfcommbuf[8] = l2capinbuf[19]; // MaxRatransm.
+ rfcommbuf[9] = l2capinbuf[20]; // Number of Frames
+ sendRfcomm(rfcommChannel, rfcommDirection, 0, RFCOMM_UIH, rfcommPfBit, rfcommbuf, 0x0A); // UIH Remote Port Negotiation Response
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nRFCOMM Connection is now established\r\n"), 0x80);
+#endif
+ onInit();
+ }
+#ifdef EXTRADEBUG
+ else if(rfcommChannelType != RFCOMM_DISC) {
+ Notify(PSTR("\r\nUnsupported RFCOMM Data - ChannelType: "), 0x80);
+ D_PrintHex<uint8_t > (rfcommChannelType, 0x80);
+ Notify(PSTR(" Command: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[11], 0x80);
+ }
+#endif
+ }
+ }
+#ifdef EXTRADEBUG
+ else {
+ Notify(PSTR("\r\nUnsupported L2CAP Data - Channel ID: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[7], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[6], 0x80);
+ }
+#endif
+ SDP_task();
+ RFCOMM_task();
+ }
+}
+
+void SPP::Run() {
+ if(waitForLastCommand && (millis() - timer) > 100) { // We will only wait 100ms and see if the UIH Remote Port Negotiation Command is send, as some deviced don't send it
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nRFCOMM Connection is now established - Automatic\r\n"), 0x80);
+#endif
+ onInit();
+ }
+ send(); // Send all bytes currently in the buffer
+}
+
+void SPP::onInit() {
+ creditSent = false;
+ waitForLastCommand = false;
+ connected = true; // The RFCOMM channel is now established
+ sppIndex = 0;
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+};
+
+void SPP::SDP_task() {
+ switch(l2cap_sdp_state) {
+ case L2CAP_SDP_WAIT:
+ if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST)) {
+ l2cap_clear_flag(L2CAP_FLAG_CONNECTION_SDP_REQUEST); // Clear flag
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSDP Incoming Connection Request"), 0x80);
+#endif
+ pBtd->l2cap_connection_response(hci_handle, identifier, sdp_dcid, sdp_scid, PENDING);
+ delay(1);
+ pBtd->l2cap_connection_response(hci_handle, identifier, sdp_dcid, sdp_scid, SUCCESSFUL);
+ identifier++;
+ delay(1);
+ pBtd->l2cap_config_request(hci_handle, identifier, sdp_scid);
+ l2cap_sdp_state = L2CAP_SDP_SUCCESS;
+ } else if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST)) {
+ l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_SDP_REQUEST); // Clear flag
+ SDPConnected = false;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected SDP Channel"), 0x80);
+#endif
+ pBtd->l2cap_disconnection_response(hci_handle, identifier, sdp_dcid, sdp_scid);
+ }
+ break;
+ case L2CAP_SDP_SUCCESS:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS)) {
+ l2cap_clear_flag(L2CAP_FLAG_CONFIG_SDP_SUCCESS); // Clear flag
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSDP Successfully Configured"), 0x80);
+#endif
+ firstMessage = true; // Reset bool
+ SDPConnected = true;
+ l2cap_sdp_state = L2CAP_SDP_WAIT;
+ }
+ break;
+
+ case L2CAP_DISCONNECT_RESPONSE: // This is for both disconnection response from the RFCOMM and SDP channel if they were connected
+ if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RESPONSE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected L2CAP Connection"), 0x80);
+#endif
+ pBtd->hci_disconnect(hci_handle);
+ hci_handle = -1; // Reset handle
+ Reset();
+ }
+ break;
+ }
+}
+
+void SPP::RFCOMM_task() {
+ switch(l2cap_rfcomm_state) {
+ case L2CAP_RFCOMM_WAIT:
+ if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST)) {
+ l2cap_clear_flag(L2CAP_FLAG_CONNECTION_RFCOMM_REQUEST); // Clear flag
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nRFCOMM Incoming Connection Request"), 0x80);
+#endif
+ pBtd->l2cap_connection_response(hci_handle, identifier, rfcomm_dcid, rfcomm_scid, PENDING);
+ delay(1);
+ pBtd->l2cap_connection_response(hci_handle, identifier, rfcomm_dcid, rfcomm_scid, SUCCESSFUL);
+ identifier++;
+ delay(1);
+ pBtd->l2cap_config_request(hci_handle, identifier, rfcomm_scid);
+ l2cap_rfcomm_state = L2CAP_RFCOMM_SUCCESS;
+ } else if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST)) {
+ l2cap_clear_flag(L2CAP_FLAG_DISCONNECT_RFCOMM_REQUEST); // Clear flag
+ RFCOMMConnected = false;
+ connected = false;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected RFCOMM Channel"), 0x80);
+#endif
+ pBtd->l2cap_disconnection_response(hci_handle, identifier, rfcomm_dcid, rfcomm_scid);
+ }
+ break;
+ case L2CAP_RFCOMM_SUCCESS:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS)) {
+ l2cap_clear_flag(L2CAP_FLAG_CONFIG_RFCOMM_SUCCESS); // Clear flag
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nRFCOMM Successfully Configured"), 0x80);
+#endif
+ rfcommAvailable = 0; // Reset number of bytes available
+ bytesRead = 0; // Reset number of bytes received
+ RFCOMMConnected = true;
+ l2cap_rfcomm_state = L2CAP_RFCOMM_WAIT;
+ }
+ break;
+ }
+}
+/************************************************************/
+/* SDP Commands */
+
+/************************************************************/
+void SPP::SDP_Command(uint8_t* data, uint8_t nbytes) { // See page 223 in the Bluetooth specs
+ pBtd->L2CAP_Command(hci_handle, data, nbytes, sdp_scid[0], sdp_scid[1]);
+}
+
+void SPP::serviceNotSupported(uint8_t transactionIDHigh, uint8_t transactionIDLow) { // See page 235 in the Bluetooth specs
+ l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU;
+ l2capoutbuf[1] = transactionIDHigh;
+ l2capoutbuf[2] = transactionIDLow;
+ l2capoutbuf[3] = 0x00; // MSB Parameter Length
+ l2capoutbuf[4] = 0x05; // LSB Parameter Length = 5
+ l2capoutbuf[5] = 0x00; // MSB AttributeListsByteCount
+ l2capoutbuf[6] = 0x02; // LSB AttributeListsByteCount = 2
+
+ /* Attribute ID/Value Sequence: */
+ l2capoutbuf[7] = 0x35; // Data element sequence - length in next byte
+ l2capoutbuf[8] = 0x00; // Length = 0
+ l2capoutbuf[9] = 0x00; // No continuation state
+
+ SDP_Command(l2capoutbuf, 10);
+}
+
+void SPP::serialPortResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLow) {
+ l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU;
+ l2capoutbuf[1] = transactionIDHigh;
+ l2capoutbuf[2] = transactionIDLow;
+ l2capoutbuf[3] = 0x00; // MSB Parameter Length
+ l2capoutbuf[4] = 0x2B; // LSB Parameter Length = 43
+ l2capoutbuf[5] = 0x00; // MSB AttributeListsByteCount
+ l2capoutbuf[6] = 0x26; // LSB AttributeListsByteCount = 38
+
+ /* Attribute ID/Value Sequence: */
+ l2capoutbuf[7] = 0x36; // Data element sequence - length in next two bytes
+ l2capoutbuf[8] = 0x00; // MSB Length
+ l2capoutbuf[9] = 0x3C; // LSB Length = 60
+
+ l2capoutbuf[10] = 0x36; // Data element sequence - length in next two bytes
+ l2capoutbuf[11] = 0x00; // MSB Length
+ l2capoutbuf[12] = 0x39; // LSB Length = 57
+
+ l2capoutbuf[13] = 0x09; // Unsigned Integer - length 2 bytes
+ l2capoutbuf[14] = 0x00; // MSB ServiceRecordHandle
+ l2capoutbuf[15] = 0x00; // LSB ServiceRecordHandle
+ l2capoutbuf[16] = 0x0A; // Unsigned int - length 4 bytes
+ l2capoutbuf[17] = 0x00; // ServiceRecordHandle value - TODO: Is this related to HCI_Handle?
+ l2capoutbuf[18] = 0x01;
+ l2capoutbuf[19] = 0x00;
+ l2capoutbuf[20] = 0x06;
+
+ l2capoutbuf[21] = 0x09; // Unsigned Integer - length 2 bytes
+ l2capoutbuf[22] = 0x00; // MSB ServiceClassIDList
+ l2capoutbuf[23] = 0x01; // LSB ServiceClassIDList
+ l2capoutbuf[24] = 0x35; // Data element sequence - length in next byte
+ l2capoutbuf[25] = 0x03; // Length = 3
+ l2capoutbuf[26] = 0x19; // UUID (universally unique identifier) - length = 2 bytes
+ l2capoutbuf[27] = 0x11; // MSB SerialPort
+ l2capoutbuf[28] = 0x01; // LSB SerialPort
+
+ l2capoutbuf[29] = 0x09; // Unsigned Integer - length 2 bytes
+ l2capoutbuf[30] = 0x00; // MSB ProtocolDescriptorList
+ l2capoutbuf[31] = 0x04; // LSB ProtocolDescriptorList
+ l2capoutbuf[32] = 0x35; // Data element sequence - length in next byte
+ l2capoutbuf[33] = 0x0C; // Length = 12
+
+ l2capoutbuf[34] = 0x35; // Data element sequence - length in next byte
+ l2capoutbuf[35] = 0x03; // Length = 3
+ l2capoutbuf[36] = 0x19; // UUID (universally unique identifier) - length = 2 bytes
+ l2capoutbuf[37] = 0x01; // MSB L2CAP
+ l2capoutbuf[38] = 0x00; // LSB L2CAP
+
+ l2capoutbuf[39] = 0x35; // Data element sequence - length in next byte
+ l2capoutbuf[40] = 0x05; // Length = 5
+ l2capoutbuf[41] = 0x19; // UUID (universally unique identifier) - length = 2 bytes
+ l2capoutbuf[42] = 0x00; // MSB RFCOMM
+ l2capoutbuf[43] = 0x03; // LSB RFCOMM
+ l2capoutbuf[44] = 0x08; // Unsigned Integer - length 1 byte
+
+ l2capoutbuf[45] = 0x02; // ContinuationState - Two more bytes
+ l2capoutbuf[46] = 0x00; // MSB length
+ l2capoutbuf[47] = 0x19; // LSB length = 25 more bytes to come
+
+ SDP_Command(l2capoutbuf, 48);
+}
+
+void SPP::serialPortResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLow) {
+ l2capoutbuf[0] = SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU;
+ l2capoutbuf[1] = transactionIDHigh;
+ l2capoutbuf[2] = transactionIDLow;
+ l2capoutbuf[3] = 0x00; // MSB Parameter Length
+ l2capoutbuf[4] = 0x1C; // LSB Parameter Length = 28
+ l2capoutbuf[5] = 0x00; // MSB AttributeListsByteCount
+ l2capoutbuf[6] = 0x19; // LSB AttributeListsByteCount = 25
+
+ /* Attribute ID/Value Sequence: */
+ l2capoutbuf[7] = 0x01; // Channel 1 - TODO: Try different values, so multiple servers can be used at once
+
+ l2capoutbuf[8] = 0x09; // Unsigned Integer - length 2 bytes
+ l2capoutbuf[9] = 0x00; // MSB LanguageBaseAttributeIDList
+ l2capoutbuf[10] = 0x06; // LSB LanguageBaseAttributeIDList
+ l2capoutbuf[11] = 0x35; // Data element sequence - length in next byte
+ l2capoutbuf[12] = 0x09; // Length = 9
+
+ // Identifier representing the natural language = en = English - see: "ISO 639:1988"
+ l2capoutbuf[13] = 0x09; // Unsigned Integer - length 2 bytes
+ l2capoutbuf[14] = 0x65; // 'e'
+ l2capoutbuf[15] = 0x6E; // 'n'
+
+ // "The second element of each triplet contains an identifier that specifies a character encoding used for the language"
+ // Encoding is set to 106 (UTF-8) - see: http://www.iana.org/assignments/character-sets/character-sets.xhtml
+ l2capoutbuf[16] = 0x09; // Unsigned Integer - length 2 bytes
+ l2capoutbuf[17] = 0x00; // MSB of character encoding
+ l2capoutbuf[18] = 0x6A; // LSB of character encoding (106)
+
+ // Attribute ID that serves as the base attribute ID for the natural language in the service record
+ // "To facilitate the retrieval of human-readable universal attributes in a principal language, the base attribute ID value for the primary language supported by a service record shall be 0x0100"
+ l2capoutbuf[19] = 0x09; // Unsigned Integer - length 2 bytes
+ l2capoutbuf[20] = 0x01;
+ l2capoutbuf[21] = 0x00;
+
+ l2capoutbuf[22] = 0x09; // Unsigned Integer - length 2 bytes
+ l2capoutbuf[23] = 0x01; // MSB ServiceDescription
+ l2capoutbuf[24] = 0x00; // LSB ServiceDescription
+
+ l2capoutbuf[25] = 0x25; // Text string - length in next byte
+ l2capoutbuf[26] = 0x05; // Name length
+ l2capoutbuf[27] = 'T';
+ l2capoutbuf[28] = 'K';
+ l2capoutbuf[29] = 'J';
+ l2capoutbuf[30] = 'S';
+ l2capoutbuf[31] = 'P';
+ l2capoutbuf[32] = 0x00; // No continuation state
+
+ SDP_Command(l2capoutbuf, 33);
+}
+
+void SPP::l2capResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLow) {
+ serialPortResponse1(transactionIDHigh, transactionIDLow); // These has to send all the supported functions, since it only supports virtual serialport it just sends the message again
+}
+
+void SPP::l2capResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLow) {
+ serialPortResponse2(transactionIDHigh, transactionIDLow); // Same data as serialPortResponse2
+}
+/************************************************************/
+/* RFCOMM Commands */
+
+/************************************************************/
+void SPP::RFCOMM_Command(uint8_t* data, uint8_t nbytes) {
+ pBtd->L2CAP_Command(hci_handle, data, nbytes, rfcomm_scid[0], rfcomm_scid[1]);
+}
+
+void SPP::sendRfcomm(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t channelType, uint8_t pfBit, uint8_t* data, uint8_t length) {
+ l2capoutbuf[0] = channel | direction | CR | extendAddress; // RFCOMM Address
+ l2capoutbuf[1] = channelType | pfBit; // RFCOMM Control
+ l2capoutbuf[2] = length << 1 | 0x01; // Length and format (always 0x01 bytes format)
+ uint8_t i = 0;
+ for(; i < length; i++)
+ l2capoutbuf[i + 3] = data[i];
+ l2capoutbuf[i + 3] = calcFcs(l2capoutbuf);
+#ifdef EXTRADEBUG
+ Notify(PSTR(" - RFCOMM Data: "), 0x80);
+ for(i = 0; i < length + 4; i++) {
+ D_PrintHex<uint8_t > (l2capoutbuf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+#endif
+ RFCOMM_Command(l2capoutbuf, length + 4);
+}
+
+void SPP::sendRfcommCredit(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t channelType, uint8_t pfBit, uint8_t credit) {
+ l2capoutbuf[0] = channel | direction | CR | extendAddress; // RFCOMM Address
+ l2capoutbuf[1] = channelType | pfBit; // RFCOMM Control
+ l2capoutbuf[2] = 0x01; // Length = 0
+ l2capoutbuf[3] = credit; // Credit
+ l2capoutbuf[4] = calcFcs(l2capoutbuf);
+#ifdef EXTRADEBUG
+ Notify(PSTR(" - RFCOMM Credit Data: "), 0x80);
+ for(uint8_t i = 0; i < 5; i++) {
+ D_PrintHex<uint8_t > (l2capoutbuf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+#endif
+ RFCOMM_Command(l2capoutbuf, 5);
+}
+
+/* CRC on 2 bytes */
+uint8_t SPP::crc(uint8_t *data) {
+ return (pgm_read_byte(&rfcomm_crc_table[pgm_read_byte(&rfcomm_crc_table[0xFF ^ data[0]]) ^ data[1]]));
+}
+
+/* Calculate FCS */
+uint8_t SPP::calcFcs(uint8_t *data) {
+ uint8_t temp = crc(data);
+ if((data[1] & 0xEF) == RFCOMM_UIH)
+ return (0xFF - temp); // FCS on 2 bytes
+ else
+ return (0xFF - pgm_read_byte(&rfcomm_crc_table[temp ^ data[2]])); // FCS on 3 bytes
+}
+
+/* Check FCS */
+bool SPP::checkFcs(uint8_t *data, uint8_t fcs) {
+ uint8_t temp = crc(data);
+ if((data[1] & 0xEF) != RFCOMM_UIH)
+ temp = pgm_read_byte(&rfcomm_crc_table[temp ^ data[2]]); // FCS on 3 bytes
+ return (pgm_read_byte(&rfcomm_crc_table[temp ^ fcs]) == 0xCF);
+}
+
+/* Serial commands */
+#if defined(ARDUINO) && ARDUINO >=100
+
+size_t SPP::write(uint8_t data) {
+ return write(&data, 1);
+}
+#else
+
+void SPP::write(uint8_t data) {
+ write(&data, 1);
+}
+#endif
+
+#if defined(ARDUINO) && ARDUINO >=100
+
+size_t SPP::write(const uint8_t *data, size_t size) {
+#else
+
+void SPP::write(const uint8_t *data, size_t size) {
+#endif
+ for(uint8_t i = 0; i < size; i++) {
+ if(sppIndex >= sizeof (sppOutputBuffer) / sizeof (sppOutputBuffer[0]))
+ send(); // Send the current data in the buffer
+ sppOutputBuffer[sppIndex++] = data[i]; // All the bytes are put into a buffer and then send using the send() function
+ }
+#if defined(ARDUINO) && ARDUINO >=100
+ return size;
+#endif
+}
+
+void SPP::send() {
+ if(!connected || !sppIndex)
+ return;
+ uint8_t length; // This is the length of the string we are sending
+ uint8_t offset = 0; // This is used to keep track of where we are in the string
+
+ l2capoutbuf[0] = rfcommChannelConnection | 0 | 0 | extendAddress; // RFCOMM Address
+ l2capoutbuf[1] = RFCOMM_UIH; // RFCOMM Control
+
+ while(sppIndex) { // We will run this while loop until this variable is 0
+ if(sppIndex > (sizeof (l2capoutbuf) - 4)) // Check if the string is larger than the outgoing buffer
+ length = sizeof (l2capoutbuf) - 4;
+ else
+ length = sppIndex;
+
+ l2capoutbuf[2] = length << 1 | 1; // Length
+ uint8_t i = 0;
+ for(; i < length; i++)
+ l2capoutbuf[i + 3] = sppOutputBuffer[i + offset];
+ l2capoutbuf[i + 3] = calcFcs(l2capoutbuf); // Calculate checksum
+
+ RFCOMM_Command(l2capoutbuf, length + 4);
+
+ sppIndex -= length;
+ offset += length; // Increment the offset
+ }
+}
+
+int SPP::available(void) {
+ return rfcommAvailable;
+};
+
+void SPP::discard(void) {
+ rfcommAvailable = 0;
+}
+
+int SPP::peek(void) {
+ if(rfcommAvailable == 0) // Don't read if there is nothing in the buffer
+ return -1;
+ return rfcommDataBuffer[0];
+}
+
+int SPP::read(void) {
+ if(rfcommAvailable == 0) // Don't read if there is nothing in the buffer
+ return -1;
+ uint8_t output = rfcommDataBuffer[0];
+ for(uint8_t i = 1; i < rfcommAvailable; i++)
+ rfcommDataBuffer[i - 1] = rfcommDataBuffer[i]; // Shift the buffer one left
+ rfcommAvailable--;
+ bytesRead++;
+ if(bytesRead > (sizeof (rfcommDataBuffer) - 5)) { // We will send the command just before it runs out of credit
+ bytesRead = 0;
+ sendRfcommCredit(rfcommChannelConnection, rfcommDirection, 0, RFCOMM_UIH, 0x10, sizeof (rfcommDataBuffer)); // Send more credit
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nSent "), 0x80);
+ Notify((uint8_t)sizeof (rfcommDataBuffer), 0x80);
+ Notify(PSTR(" more credit"), 0x80);
+#endif
+ }
+ return output;
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/SPP.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/SPP.h
new file mode 100644
index 000000000..233ac611f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/SPP.h
@@ -0,0 +1,225 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _spp_h_
+#define _spp_h_
+
+#include "BTD.h"
+
+/* Used for SDP */
+#define SDP_SERVICE_SEARCH_ATTRIBUTE_REQUEST_PDU 0x06 // See the RFCOMM specs
+#define SDP_SERVICE_SEARCH_ATTRIBUTE_RESPONSE_PDU 0x07 // See the RFCOMM specs
+#define SERIALPORT_UUID 0x1101 // See http://www.bluetooth.org/Technical/AssignedNumbers/service_discovery.htm
+#define L2CAP_UUID 0x0100
+
+/* Used for RFCOMM */
+#define RFCOMM_SABM 0x2F
+#define RFCOMM_UA 0x63
+#define RFCOMM_UIH 0xEF
+//#define RFCOMM_DM 0x0F
+#define RFCOMM_DISC 0x43
+
+#define extendAddress 0x01 // Always 1
+
+// Multiplexer message types
+#define BT_RFCOMM_PN_CMD 0x83
+#define BT_RFCOMM_PN_RSP 0x81
+#define BT_RFCOMM_MSC_CMD 0xE3
+#define BT_RFCOMM_MSC_RSP 0xE1
+#define BT_RFCOMM_RPN_CMD 0x93
+#define BT_RFCOMM_RPN_RSP 0x91
+/*
+#define BT_RFCOMM_TEST_CMD 0x23
+#define BT_RFCOMM_TEST_RSP 0x21
+#define BT_RFCOMM_FCON_CMD 0xA3
+#define BT_RFCOMM_FCON_RSP 0xA1
+#define BT_RFCOMM_FCOFF_CMD 0x63
+#define BT_RFCOMM_FCOFF_RSP 0x61
+#define BT_RFCOMM_RLS_CMD 0x53
+#define BT_RFCOMM_RLS_RSP 0x51
+#define BT_RFCOMM_NSC_RSP 0x11
+ */
+
+/**
+ * This BluetoothService class implements the Serial Port Protocol (SPP).
+ * It inherits the Arduino Stream class. This allows it to use all the standard Arduino print and stream functions.
+ */
+class SPP : public BluetoothService, public Stream {
+public:
+ /**
+ * Constructor for the SPP class.
+ * @param p Pointer to BTD class instance.
+ * @param name Set the name to BTD#btdName. If argument is omitted, then "Arduino" will be used.
+ * @param pin Write the pin to BTD#btdPin. If argument is omitted, then "0000" will be used.
+ */
+ SPP(BTD *p, const char *name = "Arduino", const char *pin = "0000");
+
+ /** @name BluetoothService implementation */
+ /** Used this to disconnect the virtual serial port. */
+ void disconnect();
+ /**@}*/
+
+ /**
+ * Used to provide Boolean tests for the class.
+ * @return Return true if SPP communication is connected.
+ */
+ operator bool() {
+ return connected;
+ }
+ /** Variable used to indicate if the connection is established. */
+ bool connected;
+
+ /** @name Serial port profile (SPP) Print functions */
+ /**
+ * Get number of bytes waiting to be read.
+ * @return Return the number of bytes ready to be read.
+ */
+ int available(void);
+
+ /** Send out all bytes in the buffer. */
+ void flush(void) {
+ send();
+ };
+ /**
+ * Used to read the next value in the buffer without advancing to the next one.
+ * @return Return the byte. Will return -1 if no bytes are available.
+ */
+ int peek(void);
+ /**
+ * Used to read the buffer.
+ * @return Return the byte. Will return -1 if no bytes are available.
+ */
+ int read(void);
+
+#if defined(ARDUINO) && ARDUINO >=100
+ /**
+ * Writes the byte to send to a buffer. The message is send when either send() or after Usb.Task() is called.
+ * @param data The byte to write.
+ * @return Return the number of bytes written.
+ */
+ size_t write(uint8_t data);
+ /**
+ * Writes the bytes to send to a buffer. The message is send when either send() or after Usb.Task() is called.
+ * @param data The data array to send.
+ * @param size Size of the data.
+ * @return Return the number of bytes written.
+ */
+ size_t write(const uint8_t* data, size_t size);
+ /** Pull in write(const char *str) from Print */
+ using Print::write;
+#else
+ /**
+ * Writes the byte to send to a buffer. The message is send when either send() or after Usb.Task() is called.
+ * @param data The byte to write.
+ */
+ void write(uint8_t data);
+ /**
+ * Writes the bytes to send to a buffer. The message is send when either send() or after Usb.Task() is called.
+ * @param data The data array to send.
+ * @param size Size of the data.
+ */
+ void write(const uint8_t* data, size_t size);
+#endif
+
+ /** Discard all the bytes in the buffer. */
+ void discard(void);
+ /**
+ * This will send all the bytes in the buffer.
+ * This is called whenever Usb.Task() is called,
+ * but can also be called via this function.
+ */
+ void send(void);
+ /**@}*/
+
+protected:
+ /** @name BluetoothService implementation */
+ /**
+ * Used to pass acldata to the services.
+ * @param ACLData Incoming acldata.
+ */
+ void ACLData(uint8_t* ACLData);
+ /** Used to establish the connection automatically. */
+ void Run();
+ /** Use this to reset the service. */
+ void Reset();
+ /**
+ * Called when a device is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ void onInit();
+ /**@}*/
+
+private:
+ /* Set true when a channel is created */
+ bool SDPConnected;
+ bool RFCOMMConnected;
+
+ /* Variables used by L2CAP state machines */
+ uint8_t l2cap_sdp_state;
+ uint8_t l2cap_rfcomm_state;
+
+ uint8_t l2capoutbuf[BULK_MAXPKTSIZE]; // General purpose buffer for l2cap out data
+ uint8_t rfcommbuf[10]; // Buffer for RFCOMM Commands
+
+ /* L2CAP Channels */
+ uint8_t sdp_scid[2]; // L2CAP source CID for SDP
+ uint8_t sdp_dcid[2]; // 0x0050
+ uint8_t rfcomm_scid[2]; // L2CAP source CID for RFCOMM
+ uint8_t rfcomm_dcid[2]; // 0x0051
+
+ /* RFCOMM Variables */
+ uint8_t rfcommChannel;
+ uint8_t rfcommChannelConnection; // This is the channel the SPP channel will be running at
+ uint8_t rfcommDirection;
+ uint8_t rfcommCommandResponse;
+ uint8_t rfcommChannelType;
+ uint8_t rfcommPfBit;
+
+ uint32_t timer;
+ bool waitForLastCommand;
+ bool creditSent;
+
+ uint8_t rfcommDataBuffer[100]; // Create a 100 sized buffer for incoming data
+ uint8_t sppOutputBuffer[100]; // Create a 100 sized buffer for outgoing SPP data
+ uint8_t sppIndex;
+ uint8_t rfcommAvailable;
+
+ bool firstMessage; // Used to see if it's the first SDP request received
+ uint8_t bytesRead; // Counter to see when it's time to send more credit
+
+ /* State machines */
+ void SDP_task(); // SDP state machine
+ void RFCOMM_task(); // RFCOMM state machine
+
+ /* SDP Commands */
+ void SDP_Command(uint8_t *data, uint8_t nbytes);
+ void serviceNotSupported(uint8_t transactionIDHigh, uint8_t transactionIDLow);
+ void serialPortResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLow);
+ void serialPortResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLow);
+ void l2capResponse1(uint8_t transactionIDHigh, uint8_t transactionIDLow);
+ void l2capResponse2(uint8_t transactionIDHigh, uint8_t transactionIDLow);
+
+ /* RFCOMM Commands */
+ void RFCOMM_Command(uint8_t *data, uint8_t nbytes);
+ void sendRfcomm(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t channelType, uint8_t pfBit, uint8_t *data, uint8_t length);
+ void sendRfcommCredit(uint8_t channel, uint8_t direction, uint8_t CR, uint8_t channelType, uint8_t pfBit, uint8_t credit);
+ uint8_t calcFcs(uint8_t *data);
+ bool checkFcs(uint8_t *data, uint8_t fcs);
+ uint8_t crc(uint8_t *data);
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Usb.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Usb.cpp
new file mode 100644
index 000000000..14272588a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Usb.cpp
@@ -0,0 +1,812 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+/* USB functions */
+
+#include "Usb.h"
+
+static uint8_t usb_error = 0;
+static uint8_t usb_task_state;
+
+/* constructor */
+USB::USB() : bmHubPre(0) {
+ usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE; //set up state machine
+ init();
+}
+
+/* Initialize data structures */
+void USB::init() {
+ //devConfigIndex = 0;
+ bmHubPre = 0;
+}
+
+uint8_t USB::getUsbTaskState(void) {
+ return ( usb_task_state);
+}
+
+void USB::setUsbTaskState(uint8_t state) {
+ usb_task_state = state;
+}
+
+EpInfo* USB::getEpInfoEntry(uint8_t addr, uint8_t ep) {
+ UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
+
+ if(!p || !p->epinfo)
+ return NULL;
+
+ EpInfo *pep = p->epinfo;
+
+ for(uint8_t i = 0; i < p->epcount; i++) {
+ if((pep)->epAddr == ep)
+ return pep;
+
+ pep++;
+ }
+ return NULL;
+}
+
+/* set device table entry */
+
+/* each device is different and has different number of endpoints. This function plugs endpoint record structure, defined in application, to devtable */
+uint8_t USB::setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr) {
+ if(!eprecord_ptr)
+ return USB_ERROR_INVALID_ARGUMENT;
+
+ UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->address.devAddress = addr;
+ p->epinfo = eprecord_ptr;
+ p->epcount = epcount;
+
+ return 0;
+}
+
+uint8_t USB::SetAddress(uint8_t addr, uint8_t ep, EpInfo **ppep, uint16_t *nak_limit) {
+ UsbDevice *p = addrPool.GetUsbDevicePtr(addr);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p->epinfo)
+ return USB_ERROR_EPINFO_IS_NULL;
+
+ *ppep = getEpInfoEntry(addr, ep);
+
+ if(!*ppep)
+ return USB_ERROR_EP_NOT_FOUND_IN_TBL;
+
+ *nak_limit = (0x0001UL << (((*ppep)->bmNakPower > USB_NAK_MAX_POWER) ? USB_NAK_MAX_POWER : (*ppep)->bmNakPower));
+ (*nak_limit)--;
+ /*
+ USBTRACE2("\r\nAddress: ", addr);
+ USBTRACE2(" EP: ", ep);
+ USBTRACE2(" NAK Power: ",(*ppep)->bmNakPower);
+ USBTRACE2(" NAK Limit: ", nak_limit);
+ USBTRACE("\r\n");
+ */
+ regWr(rPERADDR, addr); //set peripheral address
+
+ uint8_t mode = regRd(rMODE);
+
+ //Serial.print("\r\nMode: ");
+ //Serial.println( mode, HEX);
+ //Serial.print("\r\nLS: ");
+ //Serial.println(p->lowspeed, HEX);
+
+
+
+ // Set bmLOWSPEED and bmHUBPRE in case of low-speed device, reset them otherwise
+ regWr(rMODE, (p->lowspeed) ? mode | bmLOWSPEED | bmHubPre : mode & ~(bmHUBPRE | bmLOWSPEED));
+
+ return 0;
+}
+
+/* Control transfer. Sets address, endpoint, fills control packet with necessary data, dispatches control packet, and initiates bulk IN transfer, */
+/* depending on request. Actual requests are defined as inlines */
+/* return codes: */
+/* 00 = success */
+
+/* 01-0f = non-zero HRSLT */
+uint8_t USB::ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi,
+ uint16_t wInd, uint16_t total, uint16_t nbytes, uint8_t* dataptr, USBReadParser *p) {
+ bool direction = false; //request direction, IN or OUT
+ uint8_t rcode;
+ SETUP_PKT setup_pkt;
+
+ EpInfo *pep = NULL;
+ uint16_t nak_limit = 0;
+
+ rcode = SetAddress(addr, ep, &pep, &nak_limit);
+
+ if(rcode)
+ return rcode;
+
+ direction = ((bmReqType & 0x80) > 0);
+
+ /* fill in setup packet */
+ setup_pkt.ReqType_u.bmRequestType = bmReqType;
+ setup_pkt.bRequest = bRequest;
+ setup_pkt.wVal_u.wValueLo = wValLo;
+ setup_pkt.wVal_u.wValueHi = wValHi;
+ setup_pkt.wIndex = wInd;
+ setup_pkt.wLength = total;
+
+ bytesWr(rSUDFIFO, 8, (uint8_t*) & setup_pkt); //transfer to setup packet FIFO
+
+ rcode = dispatchPkt(tokSETUP, ep, nak_limit); //dispatch packet
+
+ if(rcode) //return HRSLT if not zero
+ return ( rcode);
+
+ if(dataptr != NULL) //data stage, if present
+ {
+ if(direction) //IN transfer
+ {
+ uint16_t left = total;
+
+ pep->bmRcvToggle = 1; //bmRCVTOG1;
+
+ while(left) {
+ // Bytes read into buffer
+ uint16_t read = nbytes;
+ //uint16_t read = (left<nbytes) ? left : nbytes;
+
+ rcode = InTransfer(pep, nak_limit, &read, dataptr);
+ if(rcode == hrTOGERR) {
+ // yes, we flip it wrong here so that next time it is actually correct!
+ pep->bmRcvToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
+ continue;
+ }
+
+ if(rcode)
+ return rcode;
+
+ // Invoke callback function if inTransfer completed successfully and callback function pointer is specified
+ if(!rcode && p)
+ ((USBReadParser*)p)->Parse(read, dataptr, total - left);
+
+ left -= read;
+
+ if(read < nbytes)
+ break;
+ }
+ } else //OUT transfer
+ {
+ pep->bmSndToggle = 1; //bmSNDTOG1;
+ rcode = OutTransfer(pep, nak_limit, nbytes, dataptr);
+ }
+ if(rcode) //return error
+ return ( rcode);
+ }
+ // Status stage
+ return dispatchPkt((direction) ? tokOUTHS : tokINHS, ep, nak_limit); //GET if direction
+}
+
+/* IN transfer to arbitrary endpoint. Assumes PERADDR is set. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */
+/* Keep sending INs and writes data to memory area pointed by 'data' */
+
+/* rcode 0 if no errors. rcode 01-0f is relayed from dispatchPkt(). Rcode f0 means RCVDAVIRQ error,
+ fe USB xfer timeout */
+uint8_t USB::inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t* data) {
+ EpInfo *pep = NULL;
+ uint16_t nak_limit = 0;
+
+ uint8_t rcode = SetAddress(addr, ep, &pep, &nak_limit);
+
+ if(rcode) {
+ USBTRACE3("(USB::InTransfer) SetAddress Failed ", rcode, 0x81);
+ USBTRACE3("(USB::InTransfer) addr requested ", addr, 0x81);
+ USBTRACE3("(USB::InTransfer) ep requested ", ep, 0x81);
+ return rcode;
+ }
+ return InTransfer(pep, nak_limit, nbytesptr, data);
+}
+
+uint8_t USB::InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t* data) {
+ uint8_t rcode = 0;
+ uint8_t pktsize;
+
+ uint16_t nbytes = *nbytesptr;
+ //printf("Requesting %i bytes ", nbytes);
+ uint8_t maxpktsize = pep->maxPktSize;
+
+ *nbytesptr = 0;
+ regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); //set toggle value
+
+ // use a 'break' to exit this loop
+ while(1) {
+ rcode = dispatchPkt(tokIN, pep->epAddr, nak_limit); //IN packet to EP-'endpoint'. Function takes care of NAKS.
+ if(rcode == hrTOGERR) {
+ // yes, we flip it wrong here so that next time it is actually correct!
+ pep->bmRcvToggle = (regRd(rHRSL) & bmRCVTOGRD) ? 0 : 1;
+ regWr(rHCTL, (pep->bmRcvToggle) ? bmRCVTOG1 : bmRCVTOG0); //set toggle value
+ continue;
+ }
+ if(rcode) {
+ //printf(">>>>>>>> Problem! dispatchPkt %2.2x\r\n", rcode);
+ break; //should be 0, indicating ACK. Else return error code.
+ }
+ /* check for RCVDAVIRQ and generate error if not present */
+ /* the only case when absence of RCVDAVIRQ makes sense is when toggle error occurred. Need to add handling for that */
+ if((regRd(rHIRQ) & bmRCVDAVIRQ) == 0) {
+ //printf(">>>>>>>> Problem! NO RCVDAVIRQ!\r\n");
+ rcode = 0xf0; //receive error
+ break;
+ }
+ pktsize = regRd(rRCVBC); //number of received bytes
+ //printf("Got %i bytes \r\n", pktsize);
+ // This would be OK, but...
+ //assert(pktsize <= nbytes);
+ if(pktsize > nbytes) {
+ // This can happen. Use of assert on Arduino locks up the Arduino.
+ // So I will trim the value, and hope for the best.
+ //printf(">>>>>>>> Problem! Wanted %i bytes but got %i.\r\n", nbytes, pktsize);
+ pktsize = nbytes;
+ }
+
+ int16_t mem_left = (int16_t)nbytes - *((int16_t*)nbytesptr);
+
+ if(mem_left < 0)
+ mem_left = 0;
+
+ data = bytesRd(rRCVFIFO, ((pktsize > mem_left) ? mem_left : pktsize), data);
+
+ regWr(rHIRQ, bmRCVDAVIRQ); // Clear the IRQ & free the buffer
+ *nbytesptr += pktsize; // add this packet's byte count to total transfer length
+
+ /* The transfer is complete under two conditions: */
+ /* 1. The device sent a short packet (L.T. maxPacketSize) */
+ /* 2. 'nbytes' have been transferred. */
+ if((pktsize < maxpktsize) || (*nbytesptr >= nbytes)) // have we transferred 'nbytes' bytes?
+ {
+ // Save toggle value
+ pep->bmRcvToggle = ((regRd(rHRSL) & bmRCVTOGRD)) ? 1 : 0;
+ //printf("\r\n");
+ rcode = 0;
+ break;
+ } // if
+ } //while( 1 )
+ return ( rcode);
+}
+
+/* OUT transfer to arbitrary endpoint. Handles multiple packets if necessary. Transfers 'nbytes' bytes. */
+/* Handles NAK bug per Maxim Application Note 4000 for single buffer transfer */
+
+/* rcode 0 if no errors. rcode 01-0f is relayed from HRSL */
+uint8_t USB::outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* data) {
+ EpInfo *pep = NULL;
+ uint16_t nak_limit = 0;
+
+ uint8_t rcode = SetAddress(addr, ep, &pep, &nak_limit);
+
+ if(rcode)
+ return rcode;
+
+ return OutTransfer(pep, nak_limit, nbytes, data);
+}
+
+uint8_t USB::OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data) {
+ uint8_t rcode = hrSUCCESS, retry_count;
+ uint8_t *data_p = data; //local copy of the data pointer
+ uint16_t bytes_tosend, nak_count;
+ uint16_t bytes_left = nbytes;
+
+ uint8_t maxpktsize = pep->maxPktSize;
+
+ if(maxpktsize < 1 || maxpktsize > 64)
+ return USB_ERROR_INVALID_MAX_PKT_SIZE;
+
+ unsigned long timeout = millis() + USB_XFER_TIMEOUT;
+
+ regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); //set toggle value
+
+ while(bytes_left) {
+ retry_count = 0;
+ nak_count = 0;
+ bytes_tosend = (bytes_left >= maxpktsize) ? maxpktsize : bytes_left;
+ bytesWr(rSNDFIFO, bytes_tosend, data_p); //filling output FIFO
+ regWr(rSNDBC, bytes_tosend); //set number of bytes
+ regWr(rHXFR, (tokOUT | pep->epAddr)); //dispatch packet
+ while(!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ
+ regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ
+ rcode = (regRd(rHRSL) & 0x0f);
+
+ while(rcode && ((long)(millis() - timeout) < 0L)) {
+ switch(rcode) {
+ case hrNAK:
+ nak_count++;
+ if(nak_limit && (nak_count == nak_limit))
+ goto breakout;
+ //return ( rcode);
+ break;
+ case hrTIMEOUT:
+ retry_count++;
+ if(retry_count == USB_RETRY_LIMIT)
+ goto breakout;
+ //return ( rcode);
+ break;
+ case hrTOGERR:
+ // yes, we flip it wrong here so that next time it is actually correct!
+ pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 0 : 1;
+ regWr(rHCTL, (pep->bmSndToggle) ? bmSNDTOG1 : bmSNDTOG0); //set toggle value
+ break;
+ default:
+ goto breakout;
+ }//switch( rcode
+
+ /* process NAK according to Host out NAK bug */
+ regWr(rSNDBC, 0);
+ regWr(rSNDFIFO, *data_p);
+ regWr(rSNDBC, bytes_tosend);
+ regWr(rHXFR, (tokOUT | pep->epAddr)); //dispatch packet
+ while(!(regRd(rHIRQ) & bmHXFRDNIRQ)); //wait for the completion IRQ
+ regWr(rHIRQ, bmHXFRDNIRQ); //clear IRQ
+ rcode = (regRd(rHRSL) & 0x0f);
+ }//while( rcode && ....
+ bytes_left -= bytes_tosend;
+ data_p += bytes_tosend;
+ }//while( bytes_left...
+breakout:
+
+ pep->bmSndToggle = (regRd(rHRSL) & bmSNDTOGRD) ? 1 : 0; //bmSNDTOG1 : bmSNDTOG0; //update toggle
+ return ( rcode); //should be 0 in all cases
+}
+/* dispatch USB packet. Assumes peripheral address is set and relevant buffer is loaded/empty */
+/* If NAK, tries to re-send up to nak_limit times */
+/* If nak_limit == 0, do not count NAKs, exit after timeout */
+/* If bus timeout, re-sends up to USB_RETRY_LIMIT times */
+
+/* return codes 0x00-0x0f are HRSLT( 0x00 being success ), 0xff means timeout */
+uint8_t USB::dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit) {
+ unsigned long timeout = millis() + USB_XFER_TIMEOUT;
+ uint8_t tmpdata;
+ uint8_t rcode = hrSUCCESS;
+ uint8_t retry_count = 0;
+ uint16_t nak_count = 0;
+
+ while((long)(millis() - timeout) < 0L) {
+ regWr(rHXFR, (token | ep)); //launch the transfer
+ rcode = USB_ERROR_TRANSFER_TIMEOUT;
+
+ while((long)(millis() - timeout) < 0L) //wait for transfer completion
+ {
+ tmpdata = regRd(rHIRQ);
+
+ if(tmpdata & bmHXFRDNIRQ) {
+ regWr(rHIRQ, bmHXFRDNIRQ); //clear the interrupt
+ rcode = 0x00;
+ break;
+ }//if( tmpdata & bmHXFRDNIRQ
+
+ }//while ( millis() < timeout
+
+ //if (rcode != 0x00) //exit if timeout
+ // return ( rcode);
+
+ rcode = (regRd(rHRSL) & 0x0f); //analyze transfer result
+
+ switch(rcode) {
+ case hrNAK:
+ nak_count++;
+ if(nak_limit && (nak_count == nak_limit))
+ return (rcode);
+ break;
+ case hrTIMEOUT:
+ retry_count++;
+ if(retry_count == USB_RETRY_LIMIT)
+ return (rcode);
+ break;
+ default:
+ return (rcode);
+ }//switch( rcode
+
+ }//while( timeout > millis()
+ return ( rcode);
+}
+
+/* USB main task. Performs enumeration/cleanup */
+void USB::Task(void) //USB state machine
+{
+ uint8_t rcode;
+ uint8_t tmpdata;
+ static unsigned long delay = 0;
+ //USB_DEVICE_DESCRIPTOR buf;
+ bool lowspeed = false;
+
+ MAX3421E::Task();
+
+ tmpdata = getVbusState();
+
+ /* modify USB task state if Vbus changed */
+ switch(tmpdata) {
+ case SE1: //illegal state
+ usb_task_state = USB_DETACHED_SUBSTATE_ILLEGAL;
+ lowspeed = false;
+ break;
+ case SE0: //disconnected
+ if((usb_task_state & USB_STATE_MASK) != USB_STATE_DETACHED)
+ usb_task_state = USB_DETACHED_SUBSTATE_INITIALIZE;
+ lowspeed = false;
+ break;
+ case LSHOST:
+
+ lowspeed = true;
+ //intentional fallthrough
+ case FSHOST: //attached
+ if((usb_task_state & USB_STATE_MASK) == USB_STATE_DETACHED) {
+ delay = millis() + USB_SETTLE_DELAY;
+ usb_task_state = USB_ATTACHED_SUBSTATE_SETTLE;
+ }
+ break;
+ }// switch( tmpdata
+
+ for(uint8_t i = 0; i < USB_NUMDEVICES; i++)
+ if(devConfig[i])
+ rcode = devConfig[i]->Poll();
+
+ switch(usb_task_state) {
+ case USB_DETACHED_SUBSTATE_INITIALIZE:
+ init();
+
+ for(uint8_t i = 0; i < USB_NUMDEVICES; i++)
+ if(devConfig[i])
+ rcode = devConfig[i]->Release();
+
+ usb_task_state = USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE;
+ break;
+ case USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE: //just sit here
+ break;
+ case USB_DETACHED_SUBSTATE_ILLEGAL: //just sit here
+ break;
+ case USB_ATTACHED_SUBSTATE_SETTLE: //settle time for just attached device
+ if((long)(millis() - delay) >= 0L)
+ usb_task_state = USB_ATTACHED_SUBSTATE_RESET_DEVICE;
+ else break; // don't fall through
+ case USB_ATTACHED_SUBSTATE_RESET_DEVICE:
+ regWr(rHCTL, bmBUSRST); //issue bus reset
+ usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE;
+ break;
+ case USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE:
+ if((regRd(rHCTL) & bmBUSRST) == 0) {
+ tmpdata = regRd(rMODE) | bmSOFKAENAB; //start SOF generation
+ regWr(rMODE, tmpdata);
+ usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_SOF;
+ //delay = millis() + 20; //20ms wait after reset per USB spec
+ }
+ break;
+ case USB_ATTACHED_SUBSTATE_WAIT_SOF: //todo: change check order
+ if(regRd(rHIRQ) & bmFRAMEIRQ) {
+ //when first SOF received _and_ 20ms has passed we can continue
+ /*
+ if (delay < millis()) //20ms passed
+ usb_task_state = USB_STATE_CONFIGURING;
+ */
+ usb_task_state = USB_ATTACHED_SUBSTATE_WAIT_RESET;
+ delay = millis() + 20;
+ }
+ break;
+ case USB_ATTACHED_SUBSTATE_WAIT_RESET:
+ if((long)(millis() - delay) >= 0L) usb_task_state = USB_STATE_CONFIGURING;
+ else break; // don't fall through
+ case USB_STATE_CONFIGURING:
+
+ //Serial.print("\r\nConf.LS: ");
+ //Serial.println(lowspeed, HEX);
+
+ rcode = Configuring(0, 0, lowspeed);
+
+ if(rcode) {
+ if(rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE) {
+ usb_error = rcode;
+ usb_task_state = USB_STATE_ERROR;
+ }
+ } else
+ usb_task_state = USB_STATE_RUNNING;
+ break;
+ case USB_STATE_RUNNING:
+ break;
+ case USB_STATE_ERROR:
+ //MAX3421E::Init();
+ break;
+ } // switch( usb_task_state )
+}
+
+uint8_t USB::DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed) {
+ //uint8_t buf[12];
+ uint8_t rcode;
+ UsbDevice *p0 = NULL, *p = NULL;
+
+ // Get pointer to pseudo device with address 0 assigned
+ p0 = addrPool.GetUsbDevicePtr(0);
+
+ if(!p0)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p0->epinfo)
+ return USB_ERROR_EPINFO_IS_NULL;
+
+ p0->lowspeed = (lowspeed) ? true : false;
+
+ // Allocate new address according to device class
+ uint8_t bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ // Assign new address to the device
+ rcode = setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ return rcode;
+ }
+ return 0;
+};
+
+uint8_t USB::AttemptConfig(uint8_t driver, uint8_t parent, uint8_t port, bool lowspeed) {
+ //printf("AttemptConfig: parent = %i, port = %i\r\n", parent, port);
+ uint8_t retries = 0;
+
+again:
+ uint8_t rcode = devConfig[driver]->ConfigureDevice(parent, port, lowspeed);
+ if(rcode == USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET) {
+ if(parent == 0) {
+ // Send a bus reset on the root interface.
+ regWr(rHCTL, bmBUSRST); //issue bus reset
+ delay(102); // delay 102ms, compensate for clock inaccuracy.
+ } else {
+ // reset parent port
+ devConfig[parent]->ResetHubPort(port);
+ }
+ } else if(rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works
+ delay(100);
+ retries++;
+ goto again;
+ } else if(rcode)
+ return rcode;
+
+ rcode = devConfig[driver]->Init(parent, port, lowspeed);
+ if(rcode == hrJERR && retries < 3) { // Some devices returns this when plugged in - trying to initialize the device again usually works
+ delay(100);
+ retries++;
+ goto again;
+ }
+ if(rcode) {
+ // Issue a bus reset, because the device may be in a limbo state
+ if(parent == 0) {
+ // Send a bus reset on the root interface.
+ regWr(rHCTL, bmBUSRST); //issue bus reset
+ delay(102); // delay 102ms, compensate for clock inaccuracy.
+ } else {
+ // reset parent port
+ devConfig[parent]->ResetHubPort(port);
+ }
+ }
+ return rcode;
+}
+
+/*
+ * This is broken. We need to enumerate differently.
+ * It causes major problems with several devices if detected in an unexpected order.
+ *
+ *
+ * Oleg - I wouldn't do anything before the newly connected device is considered sane.
+ * i.e.(delays are not indicated for brevity):
+ * 1. reset
+ * 2. GetDevDescr();
+ * 3a. If ACK, continue with allocating address, addressing, etc.
+ * 3b. Else reset again, count resets, stop at some number (5?).
+ * 4. When max.number of resets is reached, toggle power/fail
+ * If desired, this could be modified by performing two resets with GetDevDescr() in the middle - however, from my experience, if a device answers to GDD()
+ * it doesn't need to be reset again
+ * New steps proposal:
+ * 1: get address pool instance. exit on fail
+ * 2: pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf). exit on fail.
+ * 3: bus reset, 100ms delay
+ * 4: set address
+ * 5: pUsb->setEpInfoEntry(bAddress, 1, epInfo), exit on fail
+ * 6: while (configurations) {
+ * for(each configuration) {
+ * for (each driver) {
+ * 6a: Ask device if it likes configuration. Returns 0 on OK.
+ * If successful, the driver configured device.
+ * The driver now owns the endpoints, and takes over managing them.
+ * The following will need codes:
+ * Everything went well, instance consumed, exit with success.
+ * Instance already in use, ignore it, try next driver.
+ * Not a supported device, ignore it, try next driver.
+ * Not a supported configuration for this device, ignore it, try next driver.
+ * Could not configure device, fatal, exit with fail.
+ * }
+ * }
+ * }
+ * 7: for(each driver) {
+ * 7a: Ask device if it knows this VID/PID. Acts exactly like 6a, but using VID/PID
+ * 8: if we get here, no driver likes the device plugged in, so exit failure.
+ *
+ */
+uint8_t USB::Configuring(uint8_t parent, uint8_t port, bool lowspeed) {
+ //uint8_t bAddress = 0;
+ //printf("Configuring: parent = %i, port = %i\r\n", parent, port);
+ uint8_t devConfigIndex;
+ uint8_t rcode = 0;
+ uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
+ USB_DEVICE_DESCRIPTOR *udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR *>(buf);
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ EpInfo epInfo;
+
+ epInfo.epAddr = 0;
+ epInfo.maxPktSize = 8;
+ epInfo.epAttribs = 0;
+ epInfo.bmNakPower = USB_NAK_MAX_POWER;
+
+ //delay(2000);
+ AddressPool &addrPool = GetAddressPool();
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+ if(!p) {
+ //printf("Configuring error: USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL\r\n");
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to
+ // avoid toggle inconsistence
+
+ p->epinfo = &epInfo;
+
+ p->lowspeed = lowspeed;
+ // Get device descriptor
+ rcode = getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf);
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode) {
+ //printf("Configuring error: Can't get USB_DEVICE_DESCRIPTOR\r\n");
+ return rcode;
+ }
+
+ // to-do?
+ // Allocate new address according to device class
+ //bAddress = addrPool.AllocAddress(parent, false, port);
+
+ uint16_t vid = udd->idVendor;
+ uint16_t pid = udd->idProduct;
+ uint8_t klass = udd->bDeviceClass;
+ uint8_t subklass = udd->bDeviceSubClass;
+ // Attempt to configure if VID/PID or device class matches with a driver
+ // Qualify with subclass too.
+ //
+ // VID/PID & class tests default to false for drivers not yet ported
+ // subclass defaults to true, so you don't have to define it if you don't have to.
+ //
+ for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) {
+ if(!devConfig[devConfigIndex]) continue; // no driver
+ if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed
+ if(devConfig[devConfigIndex]->DEVSUBCLASSOK(subklass) && (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass))) {
+ rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed);
+ if(rcode != USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED)
+ break;
+ }
+ }
+
+ if(devConfigIndex < USB_NUMDEVICES) {
+ return rcode;
+ }
+
+
+ // blindly attempt to configure
+ for(devConfigIndex = 0; devConfigIndex < USB_NUMDEVICES; devConfigIndex++) {
+ if(!devConfig[devConfigIndex]) continue;
+ if(devConfig[devConfigIndex]->GetAddress()) continue; // consumed
+ if(devConfig[devConfigIndex]->DEVSUBCLASSOK(subklass) && (devConfig[devConfigIndex]->VIDPIDOK(vid, pid) || devConfig[devConfigIndex]->DEVCLASSOK(klass))) continue; // If this is true it means it must have returned USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED above
+ rcode = AttemptConfig(devConfigIndex, parent, port, lowspeed);
+
+ //printf("ERROR ENUMERATING %2.2x\r\n", rcode);
+ if(!(rcode == USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED || rcode == USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE)) {
+ // in case of an error dev_index should be reset to 0
+ // in order to start from the very beginning the
+ // next time the program gets here
+ //if (rcode != USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE)
+ // devConfigIndex = 0;
+ return rcode;
+ }
+ }
+ // if we get here that means that the device class is not supported by any of registered classes
+ rcode = DefaultAddressing(parent, port, lowspeed);
+
+ return rcode;
+}
+
+uint8_t USB::ReleaseDevice(uint8_t addr) {
+ if(!addr)
+ return 0;
+
+ for(uint8_t i = 0; i < USB_NUMDEVICES; i++) {
+ if(!devConfig[i]) continue;
+ if(devConfig[i]->GetAddress() == addr)
+ return devConfig[i]->Release();
+ }
+ return 0;
+}
+
+#if 1 //!defined(USB_METHODS_INLINE)
+//get device descriptor
+
+uint8_t USB::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr) {
+ return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, nbytes, dataptr, NULL));
+}
+//get configuration descriptor
+
+uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr) {
+ return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, nbytes, dataptr, NULL));
+}
+
+/* Requests Configuration Descriptor. Sends two Get Conf Descr requests. The first one gets the total length of all descriptors, then the second one requests this
+ total length. The length of the first request can be shorter ( 4 bytes ), however, there are devices which won't work unless this length is set to 9 */
+uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser *p) {
+ const uint8_t bufSize = 64;
+ uint8_t buf[bufSize];
+ USB_CONFIGURATION_DESCRIPTOR *ucd = reinterpret_cast<USB_CONFIGURATION_DESCRIPTOR *>(buf);
+
+ uint8_t ret = getConfDescr(addr, ep, 9, conf, buf);
+
+ if(ret)
+ return ret;
+
+ uint16_t total = ucd->wTotalLength;
+
+ //USBTRACE2("\r\ntotal conf.size:", total);
+
+ return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, total, bufSize, buf, p));
+}
+
+//get string descriptor
+
+uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t ns, uint8_t index, uint16_t langid, uint8_t* dataptr) {
+ return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, ns, ns, dataptr, NULL));
+}
+//set address
+
+uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) {
+ uint8_t rcode = ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL);
+ //delay(2); //per USB 2.0 sect.9.2.6.3
+ delay(300); // Older spec says you should wait at least 200ms
+ return rcode;
+ //return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL));
+}
+//set configuration
+
+uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) {
+ return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, 0x0000, NULL, NULL));
+}
+
+#endif // defined(USB_METHODS_INLINE)
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Usb.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Usb.h
new file mode 100644
index 000000000..47bd626cc
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Usb.h
@@ -0,0 +1,41 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+/* USB functions */
+#ifndef _usb_h_
+#define _usb_h_
+
+// WARNING: Do not change the order of includes, or stuff will break!
+#include <inttypes.h>
+#include <stddef.h>
+#include <stdio.h>
+
+// None of these should ever be included by a driver, or a user's sketch.
+#include "settings.h"
+#include "printhex.h"
+#include "message.h"
+#include "hexdump.h"
+#include "sink_parser.h"
+#include "max3421e.h"
+#include "address.h"
+#include "avrpins.h"
+#include "usb_ch9.h"
+#include "usbhost.h"
+#include "UsbCore.h"
+#include "parsetools.h"
+#include "confdescparser.h"
+
+#endif //_usb_h_
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/UsbCore.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/UsbCore.h
new file mode 100644
index 000000000..5c6c77101
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/UsbCore.h
@@ -0,0 +1,298 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#if !defined(_usb_h_) || defined(USBCORE_H)
+#error "Never include UsbCore.h directly; include Usb.h instead"
+#else
+#define USBCORE_H
+
+// Not used anymore? If anyone uses this, please let us know so that this may be
+// moved to the proper place, settings.h.
+//#define USB_METHODS_INLINE
+
+/* shield pins. First parameter - SS pin, second parameter - INT pin */
+#ifdef BOARD_BLACK_WIDDOW
+typedef MAX3421e<P6, P3> MAX3421E; // Black Widow
+#elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__))
+#if EXT_RAM
+typedef MAX3421e<P20, P7> MAX3421E; // Teensy++ 2.0 with XMEM2
+#else
+typedef MAX3421e<P9, P8> MAX3421E; // Teensy++ 1.0 and 2.0
+#endif
+#elif defined(BOARD_MEGA_ADK)
+typedef MAX3421e<P53, P54> MAX3421E; // Arduino Mega ADK
+#elif defined(ARDUINO_AVR_BALANDUINO)
+typedef MAX3421e<P20, P19> MAX3421E; // Balanduino
+#elif defined(__ARDUINO_X86__) && PLATFORM_ID == 0x06
+typedef MAX3421e<P3, P2> MAX3421E; // The Intel Galileo supports much faster read and write speed at pin 2 and 3
+#else
+typedef MAX3421e<P10, P9> MAX3421E; // Official Arduinos (UNO, Duemilanove, Mega, 2560, Leonardo, Due etc.), Intel Edison, Intel Galileo 2 or Teensy 2.0 and 3.0
+#endif
+
+/* Common setup data constant combinations */
+#define bmREQ_GET_DESCR USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //get descriptor request type
+#define bmREQ_SET USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_DEVICE //set request type for all but 'set feature' and 'set interface'
+#define bmREQ_CL_GET_INTF USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE //get interface request type
+
+// D7 data transfer direction (0 - host-to-device, 1 - device-to-host)
+// D6-5 Type (0- standard, 1 - class, 2 - vendor, 3 - reserved)
+// D4-0 Recipient (0 - device, 1 - interface, 2 - endpoint, 3 - other, 4..31 - reserved)
+
+// USB Device Classes
+#define USB_CLASS_USE_CLASS_INFO 0x00 // Use Class Info in the Interface Descriptors
+#define USB_CLASS_AUDIO 0x01 // Audio
+#define USB_CLASS_COM_AND_CDC_CTRL 0x02 // Communications and CDC Control
+#define USB_CLASS_HID 0x03 // HID
+#define USB_CLASS_PHYSICAL 0x05 // Physical
+#define USB_CLASS_IMAGE 0x06 // Image
+#define USB_CLASS_PRINTER 0x07 // Printer
+#define USB_CLASS_MASS_STORAGE 0x08 // Mass Storage
+#define USB_CLASS_HUB 0x09 // Hub
+#define USB_CLASS_CDC_DATA 0x0a // CDC-Data
+#define USB_CLASS_SMART_CARD 0x0b // Smart-Card
+#define USB_CLASS_CONTENT_SECURITY 0x0d // Content Security
+#define USB_CLASS_VIDEO 0x0e // Video
+#define USB_CLASS_PERSONAL_HEALTH 0x0f // Personal Healthcare
+#define USB_CLASS_DIAGNOSTIC_DEVICE 0xdc // Diagnostic Device
+#define USB_CLASS_WIRELESS_CTRL 0xe0 // Wireless Controller
+#define USB_CLASS_MISC 0xef // Miscellaneous
+#define USB_CLASS_APP_SPECIFIC 0xfe // Application Specific
+#define USB_CLASS_VENDOR_SPECIFIC 0xff // Vendor Specific
+
+// Additional Error Codes
+#define USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED 0xD1
+#define USB_DEV_CONFIG_ERROR_DEVICE_INIT_INCOMPLETE 0xD2
+#define USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS 0xD3
+#define USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL 0xD4
+#define USB_ERROR_HUB_ADDRESS_OVERFLOW 0xD5
+#define USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL 0xD6
+#define USB_ERROR_EPINFO_IS_NULL 0xD7
+#define USB_ERROR_INVALID_ARGUMENT 0xD8
+#define USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE 0xD9
+#define USB_ERROR_INVALID_MAX_PKT_SIZE 0xDA
+#define USB_ERROR_EP_NOT_FOUND_IN_TBL 0xDB
+#define USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET 0xE0
+#define USB_ERROR_FailGetDevDescr 0xE1
+#define USB_ERROR_FailSetDevTblEntry 0xE2
+#define USB_ERROR_FailGetConfDescr 0xE3
+#define USB_ERROR_TRANSFER_TIMEOUT 0xFF
+
+#define USB_XFER_TIMEOUT 5000 // (5000) USB transfer timeout in milliseconds, per section 9.2.6.1 of USB 2.0 spec
+//#define USB_NAK_LIMIT 32000 // NAK limit for a transfer. 0 means NAKs are not counted
+#define USB_RETRY_LIMIT 3 // 3 retry limit for a transfer
+#define USB_SETTLE_DELAY 200 // settle delay in milliseconds
+
+#define USB_NUMDEVICES 16 //number of USB devices
+//#define HUB_MAX_HUBS 7 // maximum number of hubs that can be attached to the host controller
+#define HUB_PORT_RESET_DELAY 20 // hub port reset delay 10 ms recomended, can be up to 20 ms
+
+/* USB state machine states */
+#define USB_STATE_MASK 0xf0
+
+#define USB_STATE_DETACHED 0x10
+#define USB_DETACHED_SUBSTATE_INITIALIZE 0x11
+#define USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE 0x12
+#define USB_DETACHED_SUBSTATE_ILLEGAL 0x13
+#define USB_ATTACHED_SUBSTATE_SETTLE 0x20
+#define USB_ATTACHED_SUBSTATE_RESET_DEVICE 0x30
+#define USB_ATTACHED_SUBSTATE_WAIT_RESET_COMPLETE 0x40
+#define USB_ATTACHED_SUBSTATE_WAIT_SOF 0x50
+#define USB_ATTACHED_SUBSTATE_WAIT_RESET 0x51
+#define USB_ATTACHED_SUBSTATE_GET_DEVICE_DESCRIPTOR_SIZE 0x60
+#define USB_STATE_ADDRESSING 0x70
+#define USB_STATE_CONFIGURING 0x80
+#define USB_STATE_RUNNING 0x90
+#define USB_STATE_ERROR 0xa0
+
+class USBDeviceConfig {
+public:
+
+ virtual uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ return 0;
+ }
+
+ virtual uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
+ return 0;
+ }
+
+ virtual uint8_t Release() {
+ return 0;
+ }
+
+ virtual uint8_t Poll() {
+ return 0;
+ }
+
+ virtual uint8_t GetAddress() {
+ return 0;
+ }
+
+ virtual void ResetHubPort(uint8_t port) {
+ return;
+ } // Note used for hubs only!
+
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return false;
+ }
+
+ virtual bool DEVCLASSOK(uint8_t klass) {
+ return false;
+ }
+
+ virtual bool DEVSUBCLASSOK(uint8_t subklass) {
+ return true;
+ }
+
+};
+
+/* USB Setup Packet Structure */
+typedef struct {
+
+ union { // offset description
+ uint8_t bmRequestType; // 0 Bit-map of request type
+
+ struct {
+ uint8_t recipient : 5; // Recipient of the request
+ uint8_t type : 2; // Type of request
+ uint8_t direction : 1; // Direction of data X-fer
+ } __attribute__((packed));
+ } ReqType_u;
+ uint8_t bRequest; // 1 Request
+
+ union {
+ uint16_t wValue; // 2 Depends on bRequest
+
+ struct {
+ uint8_t wValueLo;
+ uint8_t wValueHi;
+ } __attribute__((packed));
+ } wVal_u;
+ uint16_t wIndex; // 4 Depends on bRequest
+ uint16_t wLength; // 6 Depends on bRequest
+} __attribute__((packed)) SETUP_PKT, *PSETUP_PKT;
+
+
+
+// Base class for incoming data parser
+
+class USBReadParser {
+public:
+ virtual void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset) = 0;
+};
+
+class USB : public MAX3421E {
+ AddressPoolImpl<USB_NUMDEVICES> addrPool;
+ USBDeviceConfig* devConfig[USB_NUMDEVICES];
+ uint8_t bmHubPre;
+
+public:
+ USB(void);
+
+ void SetHubPreMask() {
+ bmHubPre |= bmHUBPRE;
+ };
+
+ void ResetHubPreMask() {
+ bmHubPre &= (~bmHUBPRE);
+ };
+
+ AddressPool& GetAddressPool() {
+ return (AddressPool&)addrPool;
+ };
+
+ uint8_t RegisterDeviceClass(USBDeviceConfig *pdev) {
+ for(uint8_t i = 0; i < USB_NUMDEVICES; i++) {
+ if(!devConfig[i]) {
+ devConfig[i] = pdev;
+ return 0;
+ }
+ }
+ return USB_ERROR_UNABLE_TO_REGISTER_DEVICE_CLASS;
+ };
+
+ void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) {
+ addrPool.ForEachUsbDevice(pfunc);
+ };
+ uint8_t getUsbTaskState(void);
+ void setUsbTaskState(uint8_t state);
+
+ EpInfo* getEpInfoEntry(uint8_t addr, uint8_t ep);
+ uint8_t setEpInfoEntry(uint8_t addr, uint8_t epcount, EpInfo* eprecord_ptr);
+
+ /* Control requests */
+ uint8_t getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr);
+ uint8_t getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr);
+
+ uint8_t getConfDescr(uint8_t addr, uint8_t ep, uint8_t conf, USBReadParser *p);
+
+ uint8_t getStrDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t index, uint16_t langid, uint8_t* dataptr);
+ uint8_t setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr);
+ uint8_t setConf(uint8_t addr, uint8_t ep, uint8_t conf_value);
+ /**/
+ uint8_t ctrlData(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr, bool direction);
+ uint8_t ctrlStatus(uint8_t ep, bool direction, uint16_t nak_limit);
+ uint8_t inTransfer(uint8_t addr, uint8_t ep, uint16_t *nbytesptr, uint8_t* data);
+ uint8_t outTransfer(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* data);
+ uint8_t dispatchPkt(uint8_t token, uint8_t ep, uint16_t nak_limit);
+
+ void Task(void);
+
+ uint8_t DefaultAddressing(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t Configuring(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t ReleaseDevice(uint8_t addr);
+
+ uint8_t ctrlReq(uint8_t addr, uint8_t ep, uint8_t bmReqType, uint8_t bRequest, uint8_t wValLo, uint8_t wValHi,
+ uint16_t wInd, uint16_t total, uint16_t nbytes, uint8_t* dataptr, USBReadParser *p);
+
+private:
+ void init();
+ uint8_t SetAddress(uint8_t addr, uint8_t ep, EpInfo **ppep, uint16_t *nak_limit);
+ uint8_t OutTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t nbytes, uint8_t *data);
+ uint8_t InTransfer(EpInfo *pep, uint16_t nak_limit, uint16_t *nbytesptr, uint8_t *data);
+ uint8_t AttemptConfig(uint8_t driver, uint8_t parent, uint8_t port, bool lowspeed);
+};
+
+#if 0 //defined(USB_METHODS_INLINE)
+//get device descriptor
+
+inline uint8_t USB::getDevDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t* dataptr) {
+ return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, USB_DESCRIPTOR_DEVICE, 0x0000, nbytes, dataptr));
+}
+//get configuration descriptor
+
+inline uint8_t USB::getConfDescr(uint8_t addr, uint8_t ep, uint16_t nbytes, uint8_t conf, uint8_t* dataptr) {
+ return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, conf, USB_DESCRIPTOR_CONFIGURATION, 0x0000, nbytes, dataptr));
+}
+//get string descriptor
+
+inline uint8_t USB::getStrDescr(uint8_t addr, uint8_t ep, uint16_t nuint8_ts, uint8_t index, uint16_t langid, uint8_t* dataptr) {
+ return ( ctrlReq(addr, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, index, USB_DESCRIPTOR_STRING, langid, nuint8_ts, dataptr));
+}
+//set address
+
+inline uint8_t USB::setAddr(uint8_t oldaddr, uint8_t ep, uint8_t newaddr) {
+ return ( ctrlReq(oldaddr, ep, bmREQ_SET, USB_REQUEST_SET_ADDRESS, newaddr, 0x00, 0x0000, 0x0000, NULL));
+}
+//set configuration
+
+inline uint8_t USB::setConf(uint8_t addr, uint8_t ep, uint8_t conf_value) {
+ return ( ctrlReq(addr, ep, bmREQ_SET, USB_REQUEST_SET_CONFIGURATION, conf_value, 0x00, 0x0000, 0x0000, NULL));
+}
+
+#endif // defined(USB_METHODS_INLINE)
+
+#endif /* USBCORE_H */
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Wii.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Wii.cpp
new file mode 100755
index 000000000..4bbf4c91c
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Wii.cpp
@@ -0,0 +1,1268 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+
+ IR camera support added by Allan Glover (adglover9.81@gmail.com) and Kristian Lauszus
+ */
+
+#include "Wii.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report send by the Wii controllers
+
+const uint8_t WII_LEDS[] PROGMEM = {
+ 0x00, // OFF
+ 0x10, // LED1
+ 0x20, // LED2
+ 0x40, // LED3
+ 0x80, // LED4
+
+ 0x90, // LED5
+ 0xA0, // LED6
+ 0xC0, // LED7
+ 0xD0, // LED8
+ 0xE0, // LED9
+ 0xF0, // LED10
+};
+
+const uint32_t WII_BUTTONS[] PROGMEM = {
+ 0x00008, // UP
+ 0x00002, // RIGHT
+ 0x00004, // DOWN
+ 0x00001, // LEFT
+
+ 0, // Skip
+ 0x00010, // PLUS
+ 0x00100, // TWO
+ 0x00200, // ONE
+
+ 0x01000, // MINUS
+ 0x08000, // HOME
+ 0x10000, // Z
+ 0x20000, // C
+
+ 0x00400, // B
+ 0x00800, // A
+};
+const uint32_t WII_PROCONTROLLER_BUTTONS[] PROGMEM = {
+ 0x00100, // UP
+ 0x00080, // RIGHT
+ 0x00040, // DOWN
+ 0x00200, // LEFT
+
+ 0, // Skip
+ 0x00004, // PLUS
+ 0x20000, // L3
+ 0x10000, // R3
+
+ 0x00010, // MINUS
+ 0x00008, // HOME
+ 0, 0, // Skip
+
+ 0x04000, // B
+ 0x01000, // A
+ 0x00800, // X
+ 0x02000, // Y
+
+ 0x00020, // L
+ 0x00002, // R
+ 0x08000, // ZL
+ 0x00400, // ZR
+};
+
+WII::WII(BTD *p, bool pair) :
+BluetoothService(p) // Pointer to USB class instance - mandatory
+{
+ pBtd->pairWithWii = pair;
+
+ HIDBuffer[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+
+ /* Set device cid for the control and intterrupt channelse - LSB */
+ control_dcid[0] = 0x60; // 0x0060
+ control_dcid[1] = 0x00;
+ interrupt_dcid[0] = 0x61; // 0x0061
+ interrupt_dcid[1] = 0x00;
+
+ Reset();
+}
+
+void WII::Reset() {
+ wiimoteConnected = false;
+ nunchuckConnected = false;
+ motionPlusConnected = false;
+ activateNunchuck = false;
+ motionValuesReset = false;
+ activeConnection = false;
+ motionPlusInside = false;
+ pBtd->wiiUProController = false;
+ wiiUProControllerConnected = false;
+ wiiBalanceBoardConnected = false;
+ l2cap_event_flag = 0; // Reset flags
+ l2cap_state = L2CAP_WAIT;
+}
+
+void WII::disconnect() { // Use this void to disconnect any of the controllers
+ if(!motionPlusInside) { // The old Wiimote needs a delay after the first command or it will automatically reconnect
+ if(motionPlusConnected) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDeactivating Motion Plus"), 0x80);
+#endif
+ initExtension1(); // This will disable the Motion Plus extension
+ }
+ timer = millis() + 1000; // We have to wait for the message before the rest of the channels can be deactivated
+ } else
+ timer = millis(); // Don't wait
+ // First the HID interrupt channel has to be disconnected, then the HID control channel and finally the HCI connection
+ pBtd->l2cap_disconnection_request(hci_handle, ++identifier, interrupt_scid, interrupt_dcid);
+ Reset();
+ l2cap_state = L2CAP_INTERRUPT_DISCONNECT;
+}
+
+void WII::ACLData(uint8_t* l2capinbuf) {
+ if(!pBtd->l2capConnectionClaimed && pBtd->incomingWii && !wiimoteConnected && !activeConnection) {
+ if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
+ if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
+ motionPlusInside = pBtd->motionPlusInside;
+ pBtd->incomingWii = false;
+ pBtd->l2capConnectionClaimed = true; // Claim that the incoming connection belongs to this service
+ activeConnection = true;
+ hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
+ l2cap_state = L2CAP_WAIT;
+ }
+ }
+ }
+
+ if(checkHciHandle(l2capinbuf, hci_handle)) { // acl_handle_ok
+ if((l2capinbuf[6] | (l2capinbuf[7] << 8)) == 0x0001U) { // l2cap_control - Channel ID for ACL-U
+ if(l2capinbuf[8] == L2CAP_CMD_COMMAND_REJECT) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nL2CAP Command Rejected - Reason: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[17], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[16], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+#endif
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_RESPONSE) {
+ if(((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) && ((l2capinbuf[18] | (l2capinbuf[19] << 8)) == SUCCESSFUL)) { // Success
+ if(l2capinbuf[14] == control_dcid[0] && l2capinbuf[15] == control_dcid[1]) {
+ //Notify(PSTR("\r\nHID Control Connection Complete"), 0x80);
+ identifier = l2capinbuf[9];
+ control_scid[0] = l2capinbuf[12];
+ control_scid[1] = l2capinbuf[13];
+ l2cap_set_flag(L2CAP_FLAG_CONTROL_CONNECTED);
+ } else if(l2capinbuf[14] == interrupt_dcid[0] && l2capinbuf[15] == interrupt_dcid[1]) {
+ //Notify(PSTR("\r\nHID Interrupt Connection Complete"), 0x80);
+ identifier = l2capinbuf[9];
+ interrupt_scid[0] = l2capinbuf[12];
+ interrupt_scid[1] = l2capinbuf[13];
+ l2cap_set_flag(L2CAP_FLAG_INTERRUPT_CONNECTED);
+ }
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONNECTION_REQUEST) {
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nL2CAP Connection Request - PSM: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ Notify(PSTR(" SCID: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[15], 0x80);
+ Notify(PSTR(" "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+ Notify(PSTR(" Identifier: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
+#endif
+ if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_CTRL_PSM) {
+ identifier = l2capinbuf[9];
+ control_scid[0] = l2capinbuf[14];
+ control_scid[1] = l2capinbuf[15];
+ l2cap_set_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST);
+ } else if((l2capinbuf[12] | (l2capinbuf[13] << 8)) == HID_INTR_PSM) {
+ identifier = l2capinbuf[9];
+ interrupt_scid[0] = l2capinbuf[14];
+ interrupt_scid[1] = l2capinbuf[15];
+ l2cap_set_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_RESPONSE) {
+ if((l2capinbuf[16] | (l2capinbuf[17] << 8)) == 0x0000) { // Success
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+ //Notify(PSTR("\r\nHID Control Configuration Complete"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS);
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+ //Notify(PSTR("\r\nHID Interrupt Configuration Complete"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS);
+ }
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_CONFIG_REQUEST) {
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+ //Notify(PSTR("\r\nHID Control Configuration Request"), 0x80);
+ pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], control_scid);
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+ //Notify(PSTR("\r\nHID Interrupt Configuration Request"), 0x80);
+ pBtd->l2cap_config_response(hci_handle, l2capinbuf[9], interrupt_scid);
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_REQUEST) {
+ if(l2capinbuf[12] == control_dcid[0] && l2capinbuf[13] == control_dcid[1]) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnect Request: Control Channel"), 0x80);
+#endif
+ identifier = l2capinbuf[9];
+ pBtd->l2cap_disconnection_response(hci_handle, identifier, control_dcid, control_scid);
+ Reset();
+ } else if(l2capinbuf[12] == interrupt_dcid[0] && l2capinbuf[13] == interrupt_dcid[1]) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnect Request: Interrupt Channel"), 0x80);
+#endif
+ identifier = l2capinbuf[9];
+ pBtd->l2cap_disconnection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid);
+ Reset();
+ }
+ } else if(l2capinbuf[8] == L2CAP_CMD_DISCONNECT_RESPONSE) {
+ if(l2capinbuf[12] == control_scid[0] && l2capinbuf[13] == control_scid[1]) {
+ //Notify(PSTR("\r\nDisconnect Response: Control Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE);
+ } else if(l2capinbuf[12] == interrupt_scid[0] && l2capinbuf[13] == interrupt_scid[1]) {
+ //Notify(PSTR("\r\nDisconnect Response: Interrupt Channel"), 0x80);
+ identifier = l2capinbuf[9];
+ l2cap_set_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE);
+ }
+ }
+#ifdef EXTRADEBUG
+ else {
+ identifier = l2capinbuf[9];
+ Notify(PSTR("\r\nL2CAP Unknown Signaling Command: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[8], 0x80);
+ }
+#endif
+ } else if(l2capinbuf[6] == interrupt_dcid[0] && l2capinbuf[7] == interrupt_dcid[1]) { // l2cap_interrupt
+ //Notify(PSTR("\r\nL2CAP Interrupt"), 0x80);
+ if(l2capinbuf[8] == 0xA1) { // HID_THDR_DATA_INPUT
+ if((l2capinbuf[9] >= 0x20 && l2capinbuf[9] <= 0x22) || (l2capinbuf[9] >= 0x30 && l2capinbuf[9] <= 0x37) || l2capinbuf[9] == 0x3e || l2capinbuf[9] == 0x3f) { // These reports include the buttons
+ if((l2capinbuf[9] >= 0x20 && l2capinbuf[9] <= 0x22) || l2capinbuf[9] == 0x31 || l2capinbuf[9] == 0x33) // These reports have no extensions bytes
+ ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8));
+ else if(wiiUProControllerConnected)
+ ButtonState = (uint32_t)(((~l2capinbuf[23]) & 0xFE) | ((uint16_t)(~l2capinbuf[24]) << 8) | ((uint32_t)((~l2capinbuf[25]) & 0x03) << 16));
+ else if(motionPlusConnected) {
+ if(l2capinbuf[20] & 0x02) // Only update the Wiimote buttons, since the extension bytes are from the Motion Plus
+ ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8) | ((uint32_t)(ButtonState & 0xFFFF0000)));
+ else if(nunchuckConnected) // Update if it's a report from the Nunchuck
+ ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8) | ((uint32_t)((~l2capinbuf[20]) & 0x0C) << 14));
+ //else if(classicControllerConnected) // Update if it's a report from the Classic Controller
+ } else if(nunchuckConnected) // The Nunchuck is directly connected
+ ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8) | ((uint32_t)((~l2capinbuf[20]) & 0x03) << 16));
+ //else if(classicControllerConnected) // The Classic Controller is directly connected
+ else if(!unknownExtensionConnected)
+ ButtonState = (uint32_t)((l2capinbuf[10] & 0x1F) | ((uint16_t)(l2capinbuf[11] & 0x9F) << 8));
+#ifdef PRINTREPORT
+ Notify(PSTR("ButtonState: "), 0x80);
+ D_PrintHex<uint32_t > (ButtonState, 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+ if(ButtonState != OldButtonState) {
+ ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
+ OldButtonState = ButtonState;
+ }
+ }
+ if(l2capinbuf[9] == 0x31 || l2capinbuf[9] == 0x33 || l2capinbuf[9] == 0x35 || l2capinbuf[9] == 0x37) { // Read the accelerometer
+ accXwiimote = ((l2capinbuf[12] << 2) | (l2capinbuf[10] & 0x60 >> 5)) - 500;
+ accYwiimote = ((l2capinbuf[13] << 2) | (l2capinbuf[11] & 0x20 >> 4)) - 500;
+ accZwiimote = ((l2capinbuf[14] << 2) | (l2capinbuf[11] & 0x40 >> 5)) - 500;
+ }
+ switch(l2capinbuf[9]) {
+ case 0x20: // Status Information - (a1) 20 BB BB LF 00 00 VV
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nStatus report was received"), 0x80);
+#endif
+ wiiState = l2capinbuf[12]; // (0x01: Battery is nearly empty), (0x02: An Extension Controller is connected), (0x04: Speaker enabled), (0x08: IR enabled), (0x10: LED1, 0x20: LED2, 0x40: LED3, 0x80: LED4)
+ batteryLevel = l2capinbuf[15]; // Update battery level
+
+ if(!checkBatteryLevel) { // If this is true it means that the user must have called getBatteryLevel()
+ if(l2capinbuf[12] & 0x02) { // Check if a extension is connected
+#ifdef DEBUG_USB_HOST
+ if(!unknownExtensionConnected)
+ Notify(PSTR("\r\nExtension connected"), 0x80);
+#endif
+ unknownExtensionConnected = true;
+#ifdef WIICAMERA
+ if(!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera
+#endif
+ setReportMode(false, 0x35); // Also read the extension
+ } else {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nExtension disconnected"), 0x80);
+#endif
+ if(motionPlusConnected) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR(" - from Motion Plus"), 0x80);
+#endif
+ wii_clear_flag(WII_FLAG_NUNCHUCK_CONNECTED);
+ if(!activateNunchuck) // If it's already trying to initialize the Nunchuck don't set it to false
+ nunchuckConnected = false;
+ //else if(classicControllerConnected)
+ } else if(nunchuckConnected) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR(" - Nunchuck"), 0x80);
+#endif
+ nunchuckConnected = false; // It must be the Nunchuck controller then
+ wii_clear_flag(WII_FLAG_NUNCHUCK_CONNECTED);
+ onInit();
+ setReportMode(false, 0x31); // If there is no extension connected we will read the buttons and accelerometer
+ } else
+ setReportMode(false, 0x31); // If there is no extension connected we will read the buttons and accelerometer
+ }
+ }
+ else {
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nChecking battery level"), 0x80);
+#endif
+ checkBatteryLevel = false; // Check for extensions by default
+ }
+#ifdef DEBUG_USB_HOST
+ if(l2capinbuf[12] & 0x01)
+ Notify(PSTR("\r\nWARNING: Battery is nearly empty"), 0x80);
+#endif
+
+ break;
+ case 0x21: // Read Memory Data
+ if((l2capinbuf[12] & 0x0F) == 0) { // No error
+ uint8_t reportLength = (l2capinbuf[12] >> 4) + 1; // // Bit 4-7 is the length - 1
+ // See: http://wiibrew.org/wiki/Wiimote/Extension_Controllers
+ if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x00 && l2capinbuf[20] == 0x00) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nNunchuck connected"), 0x80);
+#endif
+ wii_set_flag(WII_FLAG_NUNCHUCK_CONNECTED);
+ } else if(l2capinbuf[16] == 0x00 && (l2capinbuf[17] == 0xA6 || l2capinbuf[17] == 0xA4) && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x00 && l2capinbuf[20] == 0x05) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nMotion Plus connected"), 0x80);
+#endif
+ wii_set_flag(WII_FLAG_MOTION_PLUS_CONNECTED);
+ } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x04 && l2capinbuf[20] == 0x05) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nMotion Plus activated in normal mode"), 0x80);
+#endif
+ motionPlusConnected = true;
+#ifdef WIICAMERA
+ if(!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera
+#endif
+ setReportMode(false, 0x35); // Also read the extension
+ } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x05 && l2capinbuf[20] == 0x05) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nMotion Plus activated in Nunchuck pass-through mode"), 0x80);
+#endif
+ activateNunchuck = false;
+ motionPlusConnected = true;
+ nunchuckConnected = true;
+#ifdef WIICAMERA
+ if(!isIRCameraEnabled()) // Don't activate the Motion Plus if we are trying to initialize the IR camera
+#endif
+ setReportMode(false, 0x35); // Also read the extension
+ } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA6 && l2capinbuf[18] == 0x20 && (l2capinbuf[19] == 0x00 || l2capinbuf[19] == 0x04 || l2capinbuf[19] == 0x05 || l2capinbuf[19] == 0x07) && l2capinbuf[20] == 0x05) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nInactive Wii Motion Plus"), 0x80);
+ Notify(PSTR("\r\nPlease unplug the Motion Plus, disconnect the Wiimote and then replug the Motion Plus Extension"), 0x80);
+#endif
+ stateCounter = 300; // Skip the rest in "WII_CHECK_MOTION_PLUS_STATE"
+ } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x01 && l2capinbuf[20] == 0x20) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWii U Pro Controller connected"), 0x80);
+#endif
+ wiiUProControllerConnected = true;
+ } else if(l2capinbuf[16] == 0x00 && l2capinbuf[17] == 0xA4 && l2capinbuf[18] == 0x20 && l2capinbuf[19] == 0x04 && l2capinbuf[20] == 0x02) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWii Balance Board connected"), 0x80);
+#endif
+ setReportMode(false, 0x32); // Read the Wii Balance Board extension
+ wii_set_flag(WII_FLAG_CALIBRATE_BALANCE_BOARD);
+ }
+ // Wii Balance Board calibration reports (24 bits in total)
+ else if(l2capinbuf[13] == 0x00 && l2capinbuf[14] == 0x24 && reportLength == 16) { // First 16-bit
+ for(uint8_t i = 0; i < 2; i++) {
+ for(uint8_t j = 0; j < 4; j++)
+ wiiBalanceBoardCal[i][j] = l2capinbuf[16 + 8 * i + 2 * j] | l2capinbuf[15 + 8 * i + 2 * j] << 8;
+ }
+ } else if(l2capinbuf[13] == 0x00 && l2capinbuf[14] == 0x34 && reportLength == 8) { // Last 8-bit
+ for(uint8_t j = 0; j < 4; j++)
+ wiiBalanceBoardCal[2][j] = l2capinbuf[16 + 2 * j] | l2capinbuf[15 + 2 * j] << 8;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWii Balance Board calibration values read successfully"), 0x80);
+#endif
+ wii_clear_flag(WII_FLAG_CALIBRATE_BALANCE_BOARD);
+ wiiBalanceBoardConnected = true;
+ }
+#ifdef DEBUG_USB_HOST
+ else {
+ Notify(PSTR("\r\nUnknown Device: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+ Notify(PSTR("\r\nData: "), 0x80);
+ for(uint8_t i = 0; i < reportLength; i++) {
+ D_PrintHex<uint8_t > (l2capinbuf[15 + i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ }
+#endif
+ }
+#ifdef EXTRADEBUG
+ else {
+ Notify(PSTR("\r\nReport Error: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[13], 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[14], 0x80);
+ }
+#endif
+ break;
+ case 0x22: // Acknowledge output report, return function result
+#ifdef DEBUG_USB_HOST
+ if(l2capinbuf[13] != 0x00) { // Check if there is an error
+ Notify(PSTR("\r\nCommand failed: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[12], 0x80);
+ }
+#endif
+ break;
+ case 0x30: // Core buttons - (a1) 30 BB BB
+ break;
+ case 0x31: // Core Buttons and Accelerometer - (a1) 31 BB BB AA AA AA
+ break;
+ case 0x32: // Core Buttons with 8 Extension bytes - (a1) 32 BB BB EE EE EE EE EE EE EE EE
+ // See: http://wiibrew.org/wiki/Wii_Balance_Board#Data_Format
+ wiiBalanceBoardRaw[TopRight] = l2capinbuf[13] | l2capinbuf[12] << 8; // Top right
+ wiiBalanceBoardRaw[BotRight] = l2capinbuf[15] | l2capinbuf[14] << 8; // Bottom right
+ wiiBalanceBoardRaw[TopLeft] = l2capinbuf[17] | l2capinbuf[16] << 8; // Top left
+ wiiBalanceBoardRaw[BotLeft] = l2capinbuf[19] | l2capinbuf[18] << 8; // Bottom left
+ break;
+ case 0x33: // Core Buttons with Accelerometer and 12 IR bytes - (a1) 33 BB BB AA AA AA II II II II II II II II II II II II
+#ifdef WIICAMERA
+ // Read the IR data
+ IR_object_x1 = (l2capinbuf[15] | ((uint16_t)(l2capinbuf[17] & 0x30) << 4)); // x position
+ IR_object_y1 = (l2capinbuf[16] | ((uint16_t)(l2capinbuf[17] & 0xC0) << 2)); // y position
+ IR_object_s1 = (l2capinbuf[17] & 0x0F); // Size value, 0-15
+
+ IR_object_x2 = (l2capinbuf[18] | ((uint16_t)(l2capinbuf[20] & 0x30) << 4));
+ IR_object_y2 = (l2capinbuf[19] | ((uint16_t)(l2capinbuf[20] & 0xC0) << 2));
+ IR_object_s2 = (l2capinbuf[20] & 0x0F);
+
+ IR_object_x3 = (l2capinbuf[21] | ((uint16_t)(l2capinbuf[23] & 0x30) << 4));
+ IR_object_y3 = (l2capinbuf[22] | ((uint16_t)(l2capinbuf[23] & 0xC0) << 2));
+ IR_object_s3 = (l2capinbuf[23] & 0x0F);
+
+ IR_object_x4 = (l2capinbuf[24] | ((uint16_t)(l2capinbuf[26] & 0x30) << 4));
+ IR_object_y4 = (l2capinbuf[25] | ((uint16_t)(l2capinbuf[26] & 0xC0) << 2));
+ IR_object_s4 = (l2capinbuf[26] & 0x0F);
+#endif
+ break;
+ case 0x34: // Core Buttons with 19 Extension bytes - (a1) 34 BB BB EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE
+ break;
+ /* 0x3e and 0x3f both give unknown report types when report mode is 0x3e or 0x3f with mode number 0x05 */
+ case 0x3E: // Core Buttons with Accelerometer and 32 IR bytes
+ // (a1) 31 BB BB AA AA AA II II II II II II II II II II II II II II II II II II II II II II II II II II II II II II II II
+ // corresponds to output report mode 0x3e
+
+ /**** for reading in full mode: DOES NOT WORK YET ****/
+ /* When it works it will also have intensity and bounding box data */
+ /*
+ IR_object_x1 = (l2capinbuf[13] | ((uint16_t)(l2capinbuf[15] & 0x30) << 4));
+ IR_object_y1 = (l2capinbuf[14] | ((uint16_t)(l2capinbuf[15] & 0xC0) << 2));
+ IR_object_s1 = (l2capinbuf[15] & 0x0F);
+ */
+ break;
+ case 0x3F:
+ /*
+ IR_object_x1 = (l2capinbuf[13] | ((uint16_t)(l2capinbuf[15] & 0x30) << 4));
+ IR_object_y1 = (l2capinbuf[14] | ((uint16_t)(l2capinbuf[15] & 0xC0) << 2));
+ IR_object_s1 = (l2capinbuf[15] & 0x0F);
+ */
+ break;
+ case 0x35: // Core Buttons and Accelerometer with 16 Extension Bytes
+ // (a1) 35 BB BB AA AA AA EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE EE
+#if 1 // Set this to 0 if you don't want to use an extension, this reduceds the size of the library a lot!
+ if(motionPlusConnected) {
+ if(l2capinbuf[20] & 0x02) { // Check if it's a report from the Motion controller or the extension
+ if(motionValuesReset) { // We will only use the values when the gyro value has been set
+ gyroYawRaw = ((l2capinbuf[15] | ((l2capinbuf[18] & 0xFC) << 6)) - gyroYawZero);
+ gyroRollRaw = ((l2capinbuf[16] | ((l2capinbuf[19] & 0xFC) << 6)) - gyroRollZero);
+ gyroPitchRaw = ((l2capinbuf[17] | ((l2capinbuf[20] & 0xFC) << 6)) - gyroPitchZero);
+
+ yawGyroSpeed = (double)gyroYawRaw / ((double)gyroYawZero / yawGyroScale);
+ rollGyroSpeed = -(double)gyroRollRaw / ((double)gyroRollZero / rollGyroScale); // We invert these values so they will fit the acc values
+ pitchGyroSpeed = (double)gyroPitchRaw / ((double)gyroPitchZero / pitchGyroScale);
+
+ /* The onboard gyro has two ranges for slow and fast mode */
+ if(!(l2capinbuf[18] & 0x02)) // Check if fast mode is used
+ yawGyroSpeed *= 4.545;
+ if(!(l2capinbuf[18] & 0x01)) // Check if fast mode is used
+ pitchGyroSpeed *= 4.545;
+ if(!(l2capinbuf[19] & 0x02)) // Check if fast mode is used
+ rollGyroSpeed *= 4.545;
+
+ compPitch = (0.93 * (compPitch + (pitchGyroSpeed * (double)(micros() - timer) / 1000000)))+(0.07 * getWiimotePitch()); // Use a complimentary filter to calculate the angle
+ compRoll = (0.93 * (compRoll + (rollGyroSpeed * (double)(micros() - timer) / 1000000)))+(0.07 * getWiimoteRoll());
+
+ gyroYaw += (yawGyroSpeed * ((double)(micros() - timer) / 1000000));
+ gyroRoll += (rollGyroSpeed * ((double)(micros() - timer) / 1000000));
+ gyroPitch += (pitchGyroSpeed * ((double)(micros() - timer) / 1000000));
+ timer = micros();
+ /*
+ // Uncomment these lines to tune the gyro scale variabels
+ Notify(PSTR("\r\ngyroYaw: "), 0x80);
+ Notify(gyroYaw, 0x80);
+ Notify(PSTR("\tgyroRoll: "), 0x80);
+ Notify(gyroRoll, 0x80);
+ Notify(PSTR("\tgyroPitch: "), 0x80);
+ Notify(gyroPitch, 0x80);
+ */
+ /*
+ Notify(PSTR("\twiimoteRoll: "), 0x80);
+ Notify(wiimoteRoll, 0x80);
+ Notify(PSTR("\twiimotePitch: "), 0x80);
+ Notify(wiimotePitch, 0x80);
+ */
+ } else {
+ if((micros() - timer) > 1000000) { // Loop for 1 sec before resetting the values
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nThe gyro values has been reset"), 0x80);
+#endif
+ gyroYawZero = (l2capinbuf[15] | ((l2capinbuf[18] & 0xFC) << 6));
+ gyroRollZero = (l2capinbuf[16] | ((l2capinbuf[19] & 0xFC) << 6));
+ gyroPitchZero = (l2capinbuf[17] | ((l2capinbuf[20] & 0xFC) << 6));
+
+ rollGyroScale = 500; // You might need to adjust these
+ pitchGyroScale = 400;
+ yawGyroScale = 415;
+
+ gyroYaw = 0;
+ gyroRoll = 0;
+ gyroPitch = 0;
+
+ motionValuesReset = true;
+ timer = micros();
+ }
+ }
+ } else {
+ if(nunchuckConnected) {
+ hatValues[HatX] = l2capinbuf[15];
+ hatValues[HatY] = l2capinbuf[16];
+ accXnunchuck = ((l2capinbuf[17] << 2) | (l2capinbuf[20] & 0x10 >> 3)) - 416;
+ accYnunchuck = ((l2capinbuf[18] << 2) | (l2capinbuf[20] & 0x20 >> 4)) - 416;
+ accZnunchuck = (((l2capinbuf[19] & 0xFE) << 2) | (l2capinbuf[20] & 0xC0 >> 5)) - 416;
+ }
+ //else if(classicControllerConnected) { }
+ }
+ if(l2capinbuf[19] & 0x01) {
+ if(!extensionConnected) {
+ extensionConnected = true;
+ unknownExtensionConnected = true;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nExtension connected to Motion Plus"), 0x80);
+#endif
+ }
+ } else {
+ if(extensionConnected && !unknownExtensionConnected) {
+ extensionConnected = false;
+ unknownExtensionConnected = true;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nExtension disconnected from Motion Plus"), 0x80);
+#endif
+ nunchuckConnected = false; // There is no extension connected to the Motion Plus if this report is sent
+ }
+ }
+
+ } else if(nunchuckConnected) {
+ hatValues[HatX] = l2capinbuf[15];
+ hatValues[HatY] = l2capinbuf[16];
+ accXnunchuck = ((l2capinbuf[17] << 2) | (l2capinbuf[20] & 0x0C >> 2)) - 416;
+ accYnunchuck = ((l2capinbuf[18] << 2) | (l2capinbuf[20] & 0x30 >> 4)) - 416;
+ accZnunchuck = ((l2capinbuf[19] << 2) | (l2capinbuf[20] & 0xC0 >> 6)) - 416;
+ } else if(wiiUProControllerConnected) {
+ hatValues[LeftHatX] = (l2capinbuf[15] | l2capinbuf[16] << 8);
+ hatValues[RightHatX] = (l2capinbuf[17] | l2capinbuf[18] << 8);
+ hatValues[LeftHatY] = (l2capinbuf[19] | l2capinbuf[20] << 8);
+ hatValues[RightHatY] = (l2capinbuf[21] | l2capinbuf[22] << 8);
+ }
+#endif
+ break;
+#ifdef DEBUG_USB_HOST
+ default:
+ Notify(PSTR("\r\nUnknown Report type: "), 0x80);
+ D_PrintHex<uint8_t > (l2capinbuf[9], 0x80);
+ break;
+#endif
+ }
+ }
+ }
+ L2CAP_task();
+ }
+}
+
+void WII::L2CAP_task() {
+ switch(l2cap_state) {
+ /* These states are used if the Wiimote is the host */
+ case L2CAP_CONTROL_SUCCESS:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Control Successfully Configured"), 0x80);
+#endif
+ l2cap_state = L2CAP_INTERRUPT_SETUP;
+ }
+ break;
+
+ case L2CAP_INTERRUPT_SETUP:
+ if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_INTERRUPT_REQUEST)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Interrupt Incoming Connection Request"), 0x80);
+#endif
+ pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, PENDING);
+ delay(1);
+ pBtd->l2cap_connection_response(hci_handle, identifier, interrupt_dcid, interrupt_scid, SUCCESSFUL);
+ identifier++;
+ delay(1);
+ pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid);
+
+ l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
+ }
+ break;
+
+ /* These states are used if the Arduino is the host */
+ case L2CAP_CONTROL_CONNECT_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_CONTROL_CONNECTED)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend HID Control Config Request"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_config_request(hci_handle, identifier, control_scid);
+ l2cap_state = L2CAP_CONTROL_CONFIG_REQUEST;
+ }
+ break;
+
+ case L2CAP_CONTROL_CONFIG_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_CONTROL_SUCCESS)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend HID Interrupt Connection Request"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_connection_request(hci_handle, identifier, interrupt_dcid, HID_INTR_PSM);
+ l2cap_state = L2CAP_INTERRUPT_CONNECT_REQUEST;
+ }
+ break;
+
+ case L2CAP_INTERRUPT_CONNECT_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_INTERRUPT_CONNECTED)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend HID Interrupt Config Request"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_config_request(hci_handle, identifier, interrupt_scid);
+ l2cap_state = L2CAP_INTERRUPT_CONFIG_REQUEST;
+ }
+ break;
+
+ case L2CAP_INTERRUPT_CONFIG_REQUEST:
+ if(l2cap_check_flag(L2CAP_FLAG_CONFIG_INTERRUPT_SUCCESS)) { // Now the HID channels is established
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Channels Established"), 0x80);
+#endif
+ pBtd->connectToWii = false;
+ pBtd->pairWithWii = false;
+ stateCounter = 0;
+ l2cap_state = WII_CHECK_MOTION_PLUS_STATE;
+ }
+ break;
+
+ /* The next states are in run() */
+
+ case L2CAP_INTERRUPT_DISCONNECT:
+ if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_INTERRUPT_RESPONSE) && ((long)(millis() - timer) >= 0L)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected Interrupt Channel"), 0x80);
+#endif
+ identifier++;
+ pBtd->l2cap_disconnection_request(hci_handle, identifier, control_scid, control_dcid);
+ l2cap_state = L2CAP_CONTROL_DISCONNECT;
+ }
+ break;
+
+ case L2CAP_CONTROL_DISCONNECT:
+ if(l2cap_check_flag(L2CAP_FLAG_DISCONNECT_CONTROL_RESPONSE)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nDisconnected Control Channel"), 0x80);
+#endif
+ pBtd->hci_disconnect(hci_handle);
+ hci_handle = -1; // Reset handle
+ l2cap_event_flag = 0; // Reset flags
+ l2cap_state = L2CAP_WAIT;
+ }
+ break;
+ }
+}
+
+void WII::Run() {
+ if(l2cap_state == L2CAP_INTERRUPT_DISCONNECT && ((long)(millis() - timer) >= 0L))
+ L2CAP_task(); // Call the rest of the disconnection routine after we have waited long enough
+
+ switch(l2cap_state) {
+ case L2CAP_WAIT:
+ if(pBtd->connectToWii && !pBtd->l2capConnectionClaimed && !wiimoteConnected && !activeConnection) {
+ pBtd->l2capConnectionClaimed = true;
+ activeConnection = true;
+ motionPlusInside = pBtd->motionPlusInside;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSend HID Control Connection Request"), 0x80);
+#endif
+ hci_handle = pBtd->hci_handle; // Store the HCI Handle for the connection
+ l2cap_event_flag = 0; // Reset flags
+ identifier = 0;
+ pBtd->l2cap_connection_request(hci_handle, identifier, control_dcid, HID_CTRL_PSM);
+ l2cap_state = L2CAP_CONTROL_CONNECT_REQUEST;
+ } else if(l2cap_check_flag(L2CAP_FLAG_CONNECTION_CONTROL_REQUEST)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nHID Control Incoming Connection Request"), 0x80);
+#endif
+ pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, PENDING);
+ delay(1);
+ pBtd->l2cap_connection_response(hci_handle, identifier, control_dcid, control_scid, SUCCESSFUL);
+ identifier++;
+ delay(1);
+ pBtd->l2cap_config_request(hci_handle, identifier, control_scid);
+ l2cap_state = L2CAP_CONTROL_SUCCESS;
+ }
+ break;
+
+ case WII_CHECK_MOTION_PLUS_STATE:
+#ifdef DEBUG_USB_HOST
+ if(stateCounter == 0) // Only print onnce
+ Notify(PSTR("\r\nChecking if a Motion Plus is connected"), 0x80);
+#endif
+ stateCounter++;
+ if(stateCounter % 200 == 0)
+ checkMotionPresent(); // Check if there is a motion plus connected
+ if(wii_check_flag(WII_FLAG_MOTION_PLUS_CONNECTED)) {
+ stateCounter = 0;
+ l2cap_state = WII_INIT_MOTION_PLUS_STATE;
+ timer = micros();
+
+ if(unknownExtensionConnected) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nA extension is also connected"), 0x80);
+#endif
+ activateNunchuck = true; // For we will just set this to true as this the only extension supported so far
+ }
+
+ } else if(stateCounter == 601) { // We will try three times to check for the motion plus
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nNo Motion Plus was detected"), 0x80);
+#endif
+ stateCounter = 0;
+ l2cap_state = WII_CHECK_EXTENSION_STATE;
+ }
+ break;
+
+ case WII_CHECK_EXTENSION_STATE: // This is used to check if there is anything plugged in to the extension port
+#ifdef DEBUG_USB_HOST
+ if(stateCounter == 0) // Only print onnce
+ Notify(PSTR("\r\nChecking if there is any extension connected"), 0x80);
+#endif
+ stateCounter++; // We use this counter as there has to be a short delay between the commands
+ if(stateCounter == 1)
+ statusRequest(); // See if a new device has connected
+ if(stateCounter == 100) {
+ if(unknownExtensionConnected) // Check if there is a extension is connected to the port
+ initExtension1();
+ else
+ stateCounter = 499;
+ } else if(stateCounter == 200)
+ initExtension2();
+ else if(stateCounter == 300) {
+ readExtensionType();
+ unknownExtensionConnected = false;
+ } else if(stateCounter == 400) {
+ if(wii_check_flag(WII_FLAG_CALIBRATE_BALANCE_BOARD)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReading Wii Balance Board calibration values"), 0x80);
+#endif
+ readWiiBalanceBoardCalibration();
+ } else
+ stateCounter = 499;
+ } else if(stateCounter == 500) {
+ stateCounter = 0;
+ l2cap_state = TURN_ON_LED;
+ }
+ break;
+
+ case WII_INIT_MOTION_PLUS_STATE:
+ stateCounter++;
+ if(stateCounter == 1)
+ initMotionPlus();
+ else if(stateCounter == 100)
+ activateMotionPlus();
+ else if(stateCounter == 200)
+ readExtensionType(); // Check if it has been activated
+ else if(stateCounter == 300) {
+ stateCounter = 0;
+ unknownExtensionConnected = false; // The motion plus will send a status report when it's activated, we will set this to false so it doesn't reinitialize the Motion Plus
+ l2cap_state = TURN_ON_LED;
+ }
+ break;
+
+ case TURN_ON_LED:
+ if(wii_check_flag(WII_FLAG_NUNCHUCK_CONNECTED))
+ nunchuckConnected = true;
+ wiimoteConnected = true;
+ onInit();
+ l2cap_state = L2CAP_DONE;
+ break;
+
+ case L2CAP_DONE:
+ if(unknownExtensionConnected) {
+#ifdef DEBUG_USB_HOST
+ if(stateCounter == 0) // Only print once
+ Notify(PSTR("\r\nChecking extension port"), 0x80);
+#endif
+ stateCounter++; // We will use this counter as there has to be a short delay between the commands
+ if(stateCounter == 50)
+ statusRequest();
+ else if(stateCounter == 100)
+ initExtension1();
+ else if(stateCounter == 150)
+ if((extensionConnected && motionPlusConnected) || (unknownExtensionConnected && !motionPlusConnected))
+ initExtension2();
+ else
+ stateCounter = 299; // There is no extension connected
+ else if(stateCounter == 200)
+ readExtensionType();
+ else if(stateCounter == 250) {
+ if(wii_check_flag(WII_FLAG_NUNCHUCK_CONNECTED)) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nNunchuck was reconnected"), 0x80);
+#endif
+ activateNunchuck = true;
+ nunchuckConnected = true;
+ }
+ if(!motionPlusConnected)
+ stateCounter = 449;
+ } else if(stateCounter == 300) {
+ if(motionPlusConnected) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nReactivating the Motion Plus"), 0x80);
+#endif
+ initMotionPlus();
+ } else
+ stateCounter = 449;
+ } else if(stateCounter == 350)
+ activateMotionPlus();
+ else if(stateCounter == 400)
+ readExtensionType(); // Check if it has been activated
+ else if(stateCounter == 450) {
+ onInit();
+ stateCounter = 0;
+ unknownExtensionConnected = false;
+ }
+ } else
+ stateCounter = 0;
+ break;
+ }
+}
+
+/************************************************************/
+/* HID Commands */
+/************************************************************/
+
+void WII::HID_Command(uint8_t* data, uint8_t nbytes) {
+ if(motionPlusInside)
+ pBtd->L2CAP_Command(hci_handle, data, nbytes, interrupt_scid[0], interrupt_scid[1]); // It's the new Wiimote with the Motion Plus Inside or Wii U Pro controller
+ else
+ pBtd->L2CAP_Command(hci_handle, data, nbytes, control_scid[0], control_scid[1]);
+}
+
+void WII::setAllOff() {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] = 0x00;
+ HID_Command(HIDBuffer, 3);
+}
+
+void WII::setRumbleOff() {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] &= ~0x01; // Bit 0 control the rumble
+ HID_Command(HIDBuffer, 3);
+}
+
+void WII::setRumbleOn() {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] |= 0x01; // Bit 0 control the rumble
+ HID_Command(HIDBuffer, 3);
+}
+
+void WII::setRumbleToggle() {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] ^= 0x01; // Bit 0 control the rumble
+ HID_Command(HIDBuffer, 3);
+}
+
+void WII::setLedRaw(uint8_t value) {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] = value | (HIDBuffer[2] & 0x01); // Keep the rumble bit
+ HID_Command(HIDBuffer, 3);
+}
+
+void WII::setLedOff(LEDEnum a) {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] &= ~(pgm_read_byte(&WII_LEDS[(uint8_t)a]));
+ HID_Command(HIDBuffer, 3);
+}
+
+void WII::setLedOn(LEDEnum a) {
+ if(a == OFF)
+ setLedRaw(0);
+ else {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] |= pgm_read_byte(&WII_LEDS[(uint8_t)a]);
+ HID_Command(HIDBuffer, 3);
+ }
+}
+
+void WII::setLedToggle(LEDEnum a) {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] ^= pgm_read_byte(&WII_LEDS[(uint8_t)a]);
+ HID_Command(HIDBuffer, 3);
+}
+
+void WII::setLedStatus() {
+ HIDBuffer[1] = 0x11;
+ HIDBuffer[2] = (HIDBuffer[2] & 0x01); // Keep the rumble bit
+ if(wiimoteConnected)
+ HIDBuffer[2] |= 0x10; // If it's connected LED1 will light up
+ if(motionPlusConnected)
+ HIDBuffer[2] |= 0x20; // If it's connected LED2 will light up
+ if(nunchuckConnected)
+ HIDBuffer[2] |= 0x40; // If it's connected LED3 will light up
+
+ HID_Command(HIDBuffer, 3);
+}
+
+uint8_t WII::getBatteryLevel() {
+ checkBatteryLevel = true; // This is needed so the library knows that the status response is a response to this function
+ statusRequest(); // This will update the battery level
+ return batteryLevel;
+};
+
+void WII::setReportMode(bool continuous, uint8_t mode) {
+ uint8_t cmd_buf[4];
+ cmd_buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+ cmd_buf[1] = 0x12;
+ if(continuous)
+ cmd_buf[2] = 0x04 | (HIDBuffer[2] & 0x01); // Keep the rumble bit
+ else
+ cmd_buf[2] = 0x00 | (HIDBuffer[2] & 0x01); // Keep the rumble bit
+ cmd_buf[3] = mode;
+ HID_Command(cmd_buf, 4);
+}
+
+void WII::statusRequest() {
+ uint8_t cmd_buf[3];
+ cmd_buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+ cmd_buf[1] = 0x15;
+ cmd_buf[2] = (HIDBuffer[2] & 0x01); // Keep the rumble bit
+ HID_Command(cmd_buf, 3);
+}
+
+/************************************************************/
+/* Memmory Commands */
+/************************************************************/
+
+void WII::writeData(uint32_t offset, uint8_t size, uint8_t* data) {
+ uint8_t cmd_buf[23];
+ cmd_buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+ cmd_buf[1] = 0x16; // Write data
+ cmd_buf[2] = 0x04 | (HIDBuffer[2] & 0x01); // Write to memory, clear bit 2 to write to EEPROM
+ cmd_buf[3] = (uint8_t)((offset & 0xFF0000) >> 16);
+ cmd_buf[4] = (uint8_t)((offset & 0xFF00) >> 8);
+ cmd_buf[5] = (uint8_t)(offset & 0xFF);
+ cmd_buf[6] = size;
+ uint8_t i = 0;
+ for(; i < size; i++)
+ cmd_buf[7 + i] = data[i];
+ for(; i < 16; i++) // Set the rest to zero
+ cmd_buf[7 + i] = 0x00;
+ HID_Command(cmd_buf, 23);
+}
+
+void WII::initExtension1() {
+ uint8_t buf[1];
+ buf[0] = 0x55;
+ writeData(0xA400F0, 1, buf);
+}
+
+void WII::initExtension2() {
+ uint8_t buf[1];
+ buf[0] = 0x00;
+ writeData(0xA400FB, 1, buf);
+}
+
+void WII::initMotionPlus() {
+ uint8_t buf[1];
+ buf[0] = 0x55;
+ writeData(0xA600F0, 1, buf);
+}
+
+void WII::activateMotionPlus() {
+ uint8_t buf[1];
+ if(pBtd->wiiUProController) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nActivating Wii U Pro Controller"), 0x80);
+#endif
+ buf[0] = 0x00; // It seems like you can send anything but 0x04, 0x05, and 0x07
+ } else if(activateNunchuck) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nActivating Motion Plus in pass-through mode"), 0x80);
+#endif
+ buf[0] = 0x05; // Activate nunchuck pass-through mode
+ }//else if(classicControllerConnected && extensionConnected)
+ //buf[0] = 0x07;
+ else {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nActivating Motion Plus in normal mode"), 0x80);
+#endif
+ buf[0] = 0x04; // Don't use any extension
+ }
+ writeData(0xA600FE, 1, buf);
+}
+
+void WII::readData(uint32_t offset, uint16_t size, bool EEPROM) {
+ uint8_t cmd_buf[8];
+ cmd_buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+ cmd_buf[1] = 0x17; // Read data
+ if(EEPROM)
+ cmd_buf[2] = 0x00 | (HIDBuffer[2] & 0x01); // Read from EEPROM
+ else
+ cmd_buf[2] = 0x04 | (HIDBuffer[2] & 0x01); // Read from memory
+ cmd_buf[3] = (uint8_t)((offset & 0xFF0000) >> 16);
+ cmd_buf[4] = (uint8_t)((offset & 0xFF00) >> 8);
+ cmd_buf[5] = (uint8_t)(offset & 0xFF);
+ cmd_buf[6] = (uint8_t)((size & 0xFF00) >> 8);
+ cmd_buf[7] = (uint8_t)(size & 0xFF);
+
+ HID_Command(cmd_buf, 8);
+}
+
+void WII::readExtensionType() {
+ readData(0xA400FA, 6, false);
+}
+
+void WII::readCalData() {
+ readData(0x0016, 8, true);
+}
+
+void WII::checkMotionPresent() {
+ readData(0xA600FA, 6, false);
+}
+
+void WII::readWiiBalanceBoardCalibration() {
+ readData(0xA40024, 24, false);
+}
+
+/************************************************************/
+/* WII Commands */
+/************************************************************/
+
+bool WII::getButtonPress(ButtonEnum b) { // Return true when a button is pressed
+ if(wiiUProControllerConnected)
+ return (ButtonState & pgm_read_dword(&WII_PROCONTROLLER_BUTTONS[(uint8_t)b]));
+ else
+ return (ButtonState & pgm_read_dword(&WII_BUTTONS[(uint8_t)b]));
+}
+
+bool WII::getButtonClick(ButtonEnum b) { // Only return true when a button is clicked
+ uint32_t button;
+ if(wiiUProControllerConnected)
+ button = pgm_read_dword(&WII_PROCONTROLLER_BUTTONS[(uint8_t)b]);
+ else
+ button = pgm_read_dword(&WII_BUTTONS[(uint8_t)b]);
+ bool click = (ButtonClickState & button);
+ ButtonClickState &= ~button; // clear "click" event
+ return click;
+}
+
+uint8_t WII::getAnalogHat(HatEnum a) {
+ if(!nunchuckConnected)
+ return 127; // Return center position
+ else {
+ uint8_t output = hatValues[(uint8_t)a];
+ if(output == 0xFF || output == 0x00) // The joystick will only read 255 or 0 when the cable is unplugged or initializing, so we will just return the center position
+ return 127;
+ else
+ return output;
+ }
+}
+
+uint16_t WII::getAnalogHat(AnalogHatEnum a) {
+ if(!wiiUProControllerConnected)
+ return 2000;
+ else {
+ uint16_t output = hatValues[(uint8_t)a];
+ if(output == 0x00) // The joystick will only read 0 when it is first initializing, so we will just return the center position
+ return 2000;
+ else
+ return output;
+ }
+}
+
+void WII::onInit() {
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ else
+ setLedStatus();
+}
+
+/************************************************************/
+/* Wii Balance Board Commands */
+/************************************************************/
+
+float WII::getWeight(BalanceBoardEnum pos) {
+ // Use interpolating between two points - based on: https://github.com/skorokithakis/gr8w8upd8m8/blob/master/gr8w8upd8m8.py
+ // wiiBalanceBoardCal[pos][0] is calibration values for 0 kg
+ // wiiBalanceBoardCal[pos][1] is calibration values for 17 kg
+ // wiiBalanceBoardCal[pos][2] is calibration values for 34 kg
+ if(wiiBalanceBoardRaw[pos] < wiiBalanceBoardCal[0][pos])
+ return 0.0f; // Below 0 kg
+ else if(wiiBalanceBoardRaw[pos] < wiiBalanceBoardCal[1][pos]) // Between 0 and 17 kg
+ return 17.0f * (float)(wiiBalanceBoardRaw[pos] - wiiBalanceBoardCal[0][pos]) / (float)(wiiBalanceBoardCal[1][pos] - wiiBalanceBoardCal[0][pos]);
+ else // More than 17 kg
+ return 17.0f + 17.0f * (float)(wiiBalanceBoardRaw[pos] - wiiBalanceBoardCal[1][pos]) / (float)(wiiBalanceBoardCal[2][pos] - wiiBalanceBoardCal[1][pos]);
+};
+
+float WII::getTotalWeight() {
+ return getWeight(TopRight) + getWeight(BotRight) + getWeight(TopLeft) + getWeight(BotLeft);
+};
+
+/************************************************************/
+/* The following functions are for the IR camera */
+/************************************************************/
+
+#ifdef WIICAMERA
+
+void WII::IRinitialize() { // Turns on and initialises the IR camera
+
+ enableIRCamera1();
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nEnable IR Camera1 Complete"), 0x80);
+#endif
+ delay(80);
+
+ enableIRCamera2();
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nEnable IR Camera2 Complete"), 0x80);
+#endif
+ delay(80);
+
+ write0x08Value();
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWrote hex number 0x08"), 0x80);
+#endif
+ delay(80);
+
+ writeSensitivityBlock1();
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWrote Sensitivity Block 1"), 0x80);
+#endif
+ delay(80);
+
+ writeSensitivityBlock2();
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWrote Sensitivity Block 2"), 0x80);
+#endif
+ delay(80);
+
+ uint8_t mode_num = 0x03;
+ setWiiModeNumber(mode_num); // Change input for whatever mode you want i.e. 0x01, 0x03, or 0x05
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSet Wii Mode Number To 0x"), 0x80);
+ D_PrintHex<uint8_t > (mode_num, 0x80);
+#endif
+ delay(80);
+
+ write0x08Value();
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nWrote Hex Number 0x08"), 0x80);
+#endif
+ delay(80);
+
+ setReportMode(false, 0x33);
+ //setReportMode(false, 0x3f); // For full reporting mode, doesn't work yet
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nSet Report Mode to 0x33"), 0x80);
+#endif
+ delay(80);
+
+ statusRequest(); // Used to update wiiState - call isIRCameraEnabled() afterwards to check if it actually worked
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nIR Initialized"), 0x80);
+#endif
+}
+
+void WII::enableIRCamera1() {
+ uint8_t cmd_buf[3];
+ cmd_buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+ cmd_buf[1] = 0x13; // Output report 13
+ cmd_buf[2] = 0x04 | (HIDBuffer[2] & 0x01); // Keep the rumble bit and sets bit 2
+ HID_Command(cmd_buf, 3);
+}
+
+void WII::enableIRCamera2() {
+ uint8_t cmd_buf[3];
+ cmd_buf[0] = 0xA2; // HID BT DATA_request (0xA0) | Report Type (Output 0x02)
+ cmd_buf[1] = 0x1A; // Output report 1A
+ cmd_buf[2] = 0x04 | (HIDBuffer[2] & 0x01); // Keep the rumble bit and sets bit 2
+ HID_Command(cmd_buf, 3);
+}
+
+void WII::writeSensitivityBlock1() {
+ uint8_t buf[9];
+ buf[0] = 0x00;
+ buf[1] = 0x00;
+ buf[2] = 0x00;
+ buf[3] = 0x00;
+ buf[4] = 0x00;
+ buf[5] = 0x00;
+ buf[6] = 0x90;
+ buf[7] = 0x00;
+ buf[8] = 0x41;
+
+ writeData(0xB00000, 9, buf);
+}
+
+void WII::writeSensitivityBlock2() {
+ uint8_t buf[2];
+ buf[0] = 0x40;
+ buf[1] = 0x00;
+
+ writeData(0xB0001A, 2, buf);
+}
+
+void WII::write0x08Value() {
+ uint8_t cmd = 0x08;
+ writeData(0xb00030, 1, &cmd);
+}
+
+void WII::setWiiModeNumber(uint8_t mode_number) { // mode_number in hex i.e. 0x03 for extended mode
+ writeData(0xb00033, 1, &mode_number);
+}
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Wii.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Wii.h
new file mode 100755
index 000000000..960f2273d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/Wii.h
@@ -0,0 +1,518 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+
+ IR camera support added by Allan Glover (adglover9.81@gmail.com) and Kristian Lauszus
+ */
+
+#ifndef _wii_h_
+#define _wii_h_
+
+#include "BTD.h"
+#include "controllerEnums.h"
+
+/* Wii event flags */
+#define WII_FLAG_MOTION_PLUS_CONNECTED (1 << 0)
+#define WII_FLAG_NUNCHUCK_CONNECTED (1 << 1)
+#define WII_FLAG_CALIBRATE_BALANCE_BOARD (1 << 2)
+
+#define wii_check_flag(flag) (wii_event_flag & (flag))
+#define wii_set_flag(flag) (wii_event_flag |= (flag))
+#define wii_clear_flag(flag) (wii_event_flag &= ~(flag))
+
+/** Enum used to read the joystick on the Nunchuck. */
+enum HatEnum {
+ /** Read the x-axis on the Nunchuck joystick. */
+ HatX = 0,
+ /** Read the y-axis on the Nunchuck joystick. */
+ HatY = 1,
+};
+
+/** Enum used to read the weight on Wii Balance Board. */
+enum BalanceBoardEnum {
+ TopRight = 0,
+ BotRight = 1,
+ TopLeft = 2,
+ BotLeft = 3,
+};
+
+/**
+ * This BluetoothService class implements support for the Wiimote including the Nunchuck and Motion Plus extension.
+ *
+ * It also support the Wii U Pro Controller.
+ */
+class WII : public BluetoothService {
+public:
+ /**
+ * Constructor for the WII class.
+ * @param p Pointer to BTD class instance.
+ * @param pair Set this to true in order to pair with the Wiimote. If the argument is omitted then it won't pair with it.
+ * One can use ::PAIR to set it to true.
+ */
+ WII(BTD *p, bool pair = false);
+
+ /** @name BluetoothService implementation */
+ /** Used this to disconnect any of the controllers. */
+ void disconnect();
+ /**@}*/
+
+ /** @name Wii Controller functions */
+ /**
+ * getButtonPress(Button b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(Button b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(Button b),
+ * but if you need to drive a robot forward you would use getButtonPress(Button b).
+ * @param b ::ButtonEnum to read.
+ * @return getButtonPress(ButtonEnum b) will return a true as long as a button is held down, while getButtonClick(ButtonEnum b) will return true once for each button press.
+ */
+ bool getButtonPress(ButtonEnum b);
+ bool getButtonClick(ButtonEnum b);
+ /**@}*/
+
+ /** @name Wii Controller functions */
+
+ /** Call this to start the paring sequence with a controller */
+ void pair(void) {
+ if(pBtd)
+ pBtd->pairWithWiimote();
+ };
+ /**
+ * Used to read the joystick of the Nunchuck.
+ * @param a Either ::HatX or ::HatY.
+ * @return Return the analog value in the range from approximately 25-230.
+ */
+ uint8_t getAnalogHat(HatEnum a);
+ /**
+ * Used to read the joystick of the Wii U Pro Controller.
+ * @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
+ * @return Return the analog value in the range from approximately 800-3200.
+ */
+ uint16_t getAnalogHat(AnalogHatEnum a);
+
+ /**
+ * Pitch calculated from the Wiimote. A complimentary filter is used if the Motion Plus is connected.
+ * @return Pitch in the range from 0-360.
+ */
+ double getPitch() {
+ if(motionPlusConnected)
+ return compPitch;
+ return getWiimotePitch();
+ };
+
+ /**
+ * Roll calculated from the Wiimote. A complimentary filter is used if the Motion Plus is connected.
+ * @return Roll in the range from 0-360.
+ */
+ double getRoll() {
+ if(motionPlusConnected)
+ return compRoll;
+ return getWiimoteRoll();
+ };
+
+ /**
+ * This is the yaw calculated by the gyro.
+ *
+ * <B>NOTE:</B> This angle will drift a lot and is only available if the Motion Plus extension is connected.
+ * @return The angle calculated using the gyro.
+ */
+ double getYaw() {
+ return gyroYaw;
+ };
+
+ /** Used to set all LEDs and rumble off. */
+ void setAllOff();
+ /** Turn off rumble. */
+ void setRumbleOff();
+ /** Turn on rumble. */
+ void setRumbleOn();
+ /** Toggle rumble. */
+ void setRumbleToggle();
+
+ /**
+ * Set LED value without using the ::LEDEnum.
+ * @param value See: ::LEDEnum.
+ */
+ void setLedRaw(uint8_t value);
+
+ /** Turn all LEDs off. */
+ void setLedOff() {
+ setLedRaw(0);
+ };
+ /**
+ * Turn the specific ::LEDEnum off.
+ * @param a The ::LEDEnum to turn off.
+ */
+ void setLedOff(LEDEnum a);
+ /**
+ * Turn the specific ::LEDEnum on.
+ * @param a The ::LEDEnum to turn on.
+ */
+ void setLedOn(LEDEnum a);
+ /**
+ * Toggle the specific ::LEDEnum.
+ * @param a The ::LEDEnum to toggle.
+ */
+ void setLedToggle(LEDEnum a);
+ /**
+ * This will set the LEDs, so the user can see which connections are active.
+ *
+ * The first ::LEDEnum indicate that the Wiimote is connected,
+ * the second ::LEDEnum indicate indicate that a Motion Plus is also connected
+ * the third ::LEDEnum will indicate that a Nunchuck controller is also connected.
+ */
+ void setLedStatus();
+
+ /**
+ * Return the battery level of the Wiimote.
+ * @return The battery level in the range 0-255.
+ */
+ uint8_t getBatteryLevel();
+
+ /**
+ * Return the Wiimote state.
+ * @return See: http://wiibrew.org/wiki/Wiimote#0x20:_Status.
+ */
+ uint8_t getWiiState() {
+ return wiiState;
+ };
+ /**@}*/
+
+ /**@{*/
+ /** Variable used to indicate if a Wiimote is connected. */
+ bool wiimoteConnected;
+ /** Variable used to indicate if a Nunchuck controller is connected. */
+ bool nunchuckConnected;
+ /** Variable used to indicate if a Nunchuck controller is connected. */
+ bool motionPlusConnected;
+ /** Variable used to indicate if a Wii U Pro controller is connected. */
+ bool wiiUProControllerConnected;
+ /** Variable used to indicate if a Wii Balance Board is connected. */
+ bool wiiBalanceBoardConnected;
+ /**@}*/
+
+ /* IMU Data, might be usefull if you need to do something more advanced than just calculating the angle */
+
+ /**@{*/
+
+ /** Pitch and roll calculated from the accelerometer inside the Wiimote. */
+ double getWiimotePitch() {
+ return (atan2(accYwiimote, accZwiimote) + PI) * RAD_TO_DEG;
+ };
+
+ double getWiimoteRoll() {
+ return (atan2(accXwiimote, accZwiimote) + PI) * RAD_TO_DEG;
+ };
+ /**@}*/
+
+ /**@{*/
+
+ /** Pitch and roll calculated from the accelerometer inside the Nunchuck. */
+ double getNunchuckPitch() {
+ return (atan2(accYnunchuck, accZnunchuck) + PI) * RAD_TO_DEG;
+ };
+
+ double getNunchuckRoll() {
+ return (atan2(accXnunchuck, accZnunchuck) + PI) * RAD_TO_DEG;
+ };
+ /**@}*/
+
+ /**@{*/
+ /** Accelerometer values used to calculate pitch and roll. */
+ int16_t accXwiimote, accYwiimote, accZwiimote;
+ int16_t accXnunchuck, accYnunchuck, accZnunchuck;
+ /**@}*/
+
+ /* Variables for the gyro inside the Motion Plus */
+ /** This is the pitch calculated by the gyro - use this to tune WII#pitchGyroScale. */
+ double gyroPitch;
+ /** This is the roll calculated by the gyro - use this to tune WII#rollGyroScale. */
+ double gyroRoll;
+ /** This is the yaw calculated by the gyro - use this to tune WII#yawGyroScale. */
+ double gyroYaw;
+
+ /**@{*/
+ /** The speed in deg/s from the gyro. */
+ double pitchGyroSpeed;
+ double rollGyroSpeed;
+ double yawGyroSpeed;
+ /**@}*/
+
+ /**@{*/
+ /** You might need to fine-tune these values. */
+ uint16_t pitchGyroScale;
+ uint16_t rollGyroScale;
+ uint16_t yawGyroScale;
+ /**@}*/
+
+ /**@{*/
+ /** Raw value read directly from the Motion Plus. */
+ int16_t gyroYawRaw;
+ int16_t gyroRollRaw;
+ int16_t gyroPitchRaw;
+ /**@}*/
+
+ /**@{*/
+ /** These values are set when the controller is first initialized. */
+ int16_t gyroYawZero;
+ int16_t gyroRollZero;
+ int16_t gyroPitchZero;
+ /**@}*/
+
+ /** @name Wii Balance Board functions */
+
+ /**
+ * Used to get the weight at the specific position on the Wii Balance Board.
+ * @param ::BalanceBoardEnum to read from.
+ * @return Returns the weight in kg.
+ */
+ float getWeight(BalanceBoardEnum pos);
+
+ /**
+ * Used to get total weight on the Wii Balance Board.
+ * @returnReturns the weight in kg.
+ */
+ float getTotalWeight();
+
+ /**
+ * Used to get the raw reading at the specific position on the Wii Balance Board.
+ * @param ::BalanceBoardEnum to read from.
+ * @return Returns the raw reading.
+ */
+ uint16_t getWeightRaw(BalanceBoardEnum pos) {
+ return wiiBalanceBoardRaw[pos];
+ };
+ /**@}*/
+
+#ifdef WIICAMERA
+ /** @name Wiimote IR camera functions
+ * You will have to set ::ENABLE_WII_IR_CAMERA in settings.h to 1 in order use the IR camera.
+ */
+ /** Initialises the camera as per the steps from: http://wiibrew.org/wiki/Wiimote#IR_Camera */
+ void IRinitialize();
+
+ /**
+ * IR object 1 x-position read from the Wii IR camera.
+ * @return The x-position of the object in the range 0-1023.
+ */
+ uint16_t getIRx1() {
+ return IR_object_x1;
+ };
+
+ /**
+ * IR object 1 y-position read from the Wii IR camera.
+ * @return The y-position of the object in the range 0-767.
+ */
+ uint16_t getIRy1() {
+ return IR_object_y1;
+ };
+
+ /**
+ * IR object 1 size read from the Wii IR camera.
+ * @return The size of the object in the range 0-15.
+ */
+ uint8_t getIRs1() {
+ return IR_object_s1;
+ };
+
+ /**
+ * IR object 2 x-position read from the Wii IR camera.
+ * @return The x-position of the object in the range 0-1023.
+ */
+ uint16_t getIRx2() {
+ return IR_object_x2;
+ };
+
+ /**
+ * IR object 2 y-position read from the Wii IR camera.
+ * @return The y-position of the object in the range 0-767.
+ */
+ uint16_t getIRy2() {
+ return IR_object_y2;
+ };
+
+ /**
+ * IR object 2 size read from the Wii IR camera.
+ * @return The size of the object in the range 0-15.
+ */
+ uint8_t getIRs2() {
+ return IR_object_s2;
+ };
+
+ /**
+ * IR object 3 x-position read from the Wii IR camera.
+ * @return The x-position of the object in the range 0-1023.
+ */
+ uint16_t getIRx3() {
+ return IR_object_x3;
+ };
+
+ /**
+ * IR object 3 y-position read from the Wii IR camera.
+ * @return The y-position of the object in the range 0-767.
+ */
+ uint16_t getIRy3() {
+ return IR_object_y3;
+ };
+
+ /**
+ * IR object 3 size read from the Wii IR camera.
+ * @return The size of the object in the range 0-15.
+ */
+ uint8_t getIRs3() {
+ return IR_object_s3;
+ };
+
+ /**
+ * IR object 4 x-position read from the Wii IR camera.
+ * @return The x-position of the object in the range 0-1023.
+ */
+ uint16_t getIRx4() {
+ return IR_object_x4;
+ };
+
+ /**
+ * IR object 4 y-position read from the Wii IR camera.
+ * @return The y-position of the object in the range 0-767.
+ */
+ uint16_t getIRy4() {
+ return IR_object_y4;
+ };
+
+ /**
+ * IR object 4 size read from the Wii IR camera.
+ * @return The size of the object in the range 0-15.
+ */
+ uint8_t getIRs4() {
+ return IR_object_s4;
+ };
+
+ /**
+ * Use this to check if the camera is enabled or not.
+ * If not call WII#IRinitialize to initialize the IR camera.
+ * @return True if it's enabled, false if not.
+ */
+ bool isIRCameraEnabled() {
+ return (wiiState & 0x08);
+ };
+ /**@}*/
+#endif
+
+protected:
+ /** @name BluetoothService implementation */
+ /**
+ * Used to pass acldata to the services.
+ * @param ACLData Incoming acldata.
+ */
+ void ACLData(uint8_t* ACLData);
+ /** Used to run part of the state machine. */
+ void Run();
+ /** Use this to reset the service. */
+ void Reset();
+ /**
+ * Called when the controller is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ void onInit();
+ /**@}*/
+
+private:
+
+ void L2CAP_task(); // L2CAP state machine
+
+ /* Variables filled from HCI event management */
+ bool activeConnection; // Used to indicate if it's already has established a connection
+
+ /* Variables used by high level L2CAP task */
+ uint8_t l2cap_state;
+ uint8_t wii_event_flag; // Used for Wii flags
+
+ uint32_t ButtonState;
+ uint32_t OldButtonState;
+ uint32_t ButtonClickState;
+ uint16_t hatValues[4];
+
+ uint8_t HIDBuffer[3]; // Used to store HID commands
+
+ uint16_t stateCounter;
+ bool unknownExtensionConnected;
+ bool extensionConnected;
+ bool checkBatteryLevel; // Set to true when getBatteryLevel() is called otherwise if should be false
+ bool motionPlusInside; // True if it's a new Wiimote with the Motion Plus extension build into it
+
+ /* L2CAP Channels */
+ uint8_t control_scid[2]; // L2CAP source CID for HID_Control
+ uint8_t control_dcid[2]; // 0x0060
+ uint8_t interrupt_scid[2]; // L2CAP source CID for HID_Interrupt
+ uint8_t interrupt_dcid[2]; // 0x0061
+
+ /* HID Commands */
+ void HID_Command(uint8_t* data, uint8_t nbytes);
+ void setReportMode(bool continuous, uint8_t mode);
+
+ void writeData(uint32_t offset, uint8_t size, uint8_t* data);
+ void initExtension1();
+ void initExtension2();
+
+ void statusRequest(); // Used to update the Wiimote state and battery level
+
+ void readData(uint32_t offset, uint16_t size, bool EEPROM);
+ void readExtensionType();
+ void readCalData();
+ void readWiiBalanceBoardCalibration(); // Used by the library to read the Wii Balance Board calibration values
+
+ void checkMotionPresent(); // Used to see if a Motion Plus is connected to the Wiimote
+ void initMotionPlus();
+ void activateMotionPlus();
+
+ uint16_t wiiBalanceBoardRaw[4]; // Wii Balance Board raw values
+ uint16_t wiiBalanceBoardCal[3][4]; // Wii Balance Board calibration values
+
+ double compPitch; // Fusioned angle using a complimentary filter if the Motion Plus is connected
+ double compRoll; // Fusioned angle using a complimentary filter if the Motion Plus is connected
+
+ bool activateNunchuck;
+ bool motionValuesReset; // This bool is true when the gyro values has been reset
+ uint32_t timer;
+
+ uint8_t wiiState; // Stores the value in l2capinbuf[12] - (0x01: Battery is nearly empty), (0x02: An Extension Controller is connected), (0x04: Speaker enabled), (0x08: IR enabled), (0x10: LED1, 0x20: LED2, 0x40: LED3, 0x80: LED4)
+ uint8_t batteryLevel;
+
+#ifdef WIICAMERA
+ /* Private function and variables for the readings from the IR Camera */
+ void enableIRCamera1(); // Sets bit 2 of output report 13
+ void enableIRCamera2(); // Sets bit 2 of output report 1A
+ void writeSensitivityBlock1();
+ void writeSensitivityBlock2();
+ void write0x08Value();
+ void setWiiModeNumber(uint8_t mode_number);
+
+ uint16_t IR_object_x1; // IR x position 10 bits
+ uint16_t IR_object_y1; // IR y position 10 bits
+ uint8_t IR_object_s1; // IR size value
+ uint16_t IR_object_x2;
+ uint16_t IR_object_y2;
+ uint8_t IR_object_s2;
+ uint16_t IR_object_x3; // IR x position 10 bits
+ uint16_t IR_object_y3; // IR y position 10 bits
+ uint8_t IR_object_s3; // IR size value
+ uint16_t IR_object_x4;
+ uint16_t IR_object_y4;
+ uint8_t IR_object_s4;
+#endif
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/WiiCameraReadme.md b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/WiiCameraReadme.md
new file mode 100644
index 000000000..8577d73fb
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/WiiCameraReadme.md
@@ -0,0 +1,13 @@
+Please see <http://wiibrew.org/wiki/Wiimote#IR_Camera> for the complete capabilities of the Wii camera. The IR camera code was written based on the above website and with support from Kristian Lauszus.
+
+This library is large, if you run into memory problems when uploading to the Arduino, disable serial debugging.
+
+To enable the IR camera code, simply set ```ENABLE_WII_IR_CAMERA``` to 1 in [settings.h](settings.h).
+
+This library implements the following settings:
+
+* Report sensitivity mode: 00 00 00 00 00 00 90 00 41 40 00 Suggested by inio (high sensitivity)
+* Data Format: Extended mode (0x03). Full mode is not working yet. The output reports 0x3e and 0x3f need tampering with
+ * In this mode the camera outputs x and y coordinates and a size dimension for the 4 brightest points.
+
+Again, read through <http://wiibrew.org/wiki/Wiimote#IR_Camera> to get an understanding of the camera and its settings.
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXOLD.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXOLD.cpp
new file mode 100644
index 000000000..78e6e9a5f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXOLD.cpp
@@ -0,0 +1,337 @@
+/* Copyright (C) 2013 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "XBOXOLD.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report send by the Xbox controller
+
+/** Buttons on the controllers */
+const uint8_t XBOXOLD_BUTTONS[] PROGMEM = {
+ 0x01, // UP
+ 0x08, // RIGHT
+ 0x02, // DOWN
+ 0x04, // LEFT
+
+ 0x20, // BACK
+ 0x10, // START
+ 0x40, // L3
+ 0x80, // R3
+
+ // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons
+ 4, // BLACK
+ 5, // WHTIE
+ 6, // L1
+ 7, // R1
+
+ 1, // B
+ 0, // A
+ 2, // X
+ 3, // Y
+};
+
+XBOXOLD::XBOXOLD(USB *p) :
+pUsb(p), // pointer to USB class instance - mandatory
+bAddress(0), // device address - mandatory
+bPollEnable(false) { // don't start polling before dongle is connected
+ for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }
+
+ if(pUsb) // register in USB subsystem
+ pUsb->RegisterDeviceClass(this); //set devConfig[] entry
+}
+
+uint8_t XBOXOLD::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint16_t PID;
+ uint16_t VID;
+
+ // get memory address of USB device address pool
+ AddressPool &addrPool = pUsb->GetAddressPool();
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nXBOXUSB Init"), 0x80);
+#endif
+ // check if address has already been assigned to an instance
+ if(bAddress) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress in use"), 0x80);
+#endif
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+ }
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ if(!p->epinfo) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nepinfo is null"), 0x80);
+#endif
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ VID = udd->idVendor;
+ PID = udd->idProduct;
+
+ if((VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID) || (PID != XBOX_OLD_PID1 && PID != XBOX_OLD_PID2 && PID != XBOX_OLD_PID3 && PID != XBOX_OLD_PID4)) // Check if VID and PID match
+ goto FailUnknownDevice;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nsetAddr: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+#endif
+ return rcode;
+ }
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nAddr: "), 0x80);
+ D_PrintHex<uint8_t > (bAddress, 0x80);
+#endif
+ //delay(300); // Spec says you should wait at least 200ms
+
+ p->lowspeed = false;
+
+ //get pointer to assigned address record
+ p = addrPool.GetUsbDevicePtr(bAddress);
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ // Assign epInfo to epinfo pointer - only EP0 is known
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ /* The application will work in reduced host mode, so we can save program and data
+ memory space. After verifying the VID we will use known values for the
+ configuration values for device, interface, endpoints and HID for the XBOX controllers */
+
+ /* Initialize data structures for endpoints of device */
+ epInfo[ XBOX_INPUT_PIPE ].epAddr = 0x01; // XBOX report endpoint
+ epInfo[ XBOX_INPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = 0;
+ epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE ].epAddr = 0x02; // XBOX output endpoint
+ epInfo[ XBOX_OUTPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = 0;
+
+ rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ delay(200); // Give time for address change
+
+ rcode = pUsb->setConf(bAddress, epInfo[ XBOX_CONTROL_PIPE ].epAddr, 1);
+ if(rcode)
+ goto FailSetConfDescr;
+
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox Controller Connected\r\n"), 0x80);
+#endif
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ XboxConnected = true;
+ bPollEnable = true;
+ return 0; // Successful configuration
+
+ /* Diagnostic messages */
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+#endif
+ goto Fail;
+
+FailUnknownDevice:
+#ifdef DEBUG_USB_HOST
+ NotifyFailUnknownDevice(VID, PID);
+#endif
+ rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+Fail:
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox Init Failed, error code: "), 0x80);
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+/* Performs a cleanup after failed Init() attempt */
+uint8_t XBOXOLD::Release() {
+ XboxConnected = false;
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+ bAddress = 0;
+ bPollEnable = false;
+ return 0;
+}
+
+uint8_t XBOXOLD::Poll() {
+ if(!bPollEnable)
+ return 0;
+ uint16_t BUFFER_SIZE = EP_MAXPKTSIZE;
+ pUsb->inTransfer(bAddress, epInfo[ XBOX_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf); // input on endpoint 1
+ readReport();
+#ifdef PRINTREPORT
+ printReport(BUFFER_SIZE); // Uncomment "#define PRINTREPORT" to print the report send by the Xbox controller
+#endif
+ return 0;
+}
+
+void XBOXOLD::readReport() {
+ ButtonState = readBuf[2];
+
+ for(uint8_t i = 0; i < sizeof (buttonValues); i++)
+ buttonValues[i] = readBuf[i + 4]; // A, B, X, Y, BLACK, WHITE, L1, and R1
+
+ hatValue[LeftHatX] = (int16_t)(((uint16_t)readBuf[12] << 8) | readBuf[13]);
+ hatValue[LeftHatY] = (int16_t)(((uint16_t)readBuf[14] << 8) | readBuf[15]);
+ hatValue[RightHatX] = (int16_t)(((uint16_t)readBuf[16] << 8) | readBuf[17]);
+ hatValue[RightHatY] = (int16_t)(((uint16_t)readBuf[18] << 8) | readBuf[19]);
+
+ //Notify(PSTR("\r\nButtonState"), 0x80);
+ //PrintHex<uint8_t>(ButtonState, 0x80);
+
+ if(ButtonState != OldButtonState || memcmp(buttonValues, oldButtonValues, sizeof (buttonValues)) != 0) {
+ ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
+ OldButtonState = ButtonState;
+
+ for(uint8_t i = 0; i < sizeof (buttonValues); i++) {
+ if(oldButtonValues[i] == 0 && buttonValues[i] != 0)
+ buttonClicked[i] = true; // Update A, B, X, Y, BLACK, WHITE, L1, and R1 click state
+ oldButtonValues[i] = buttonValues[i];
+ }
+ }
+}
+
+void XBOXOLD::printReport(uint16_t length) { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox controller
+#ifdef PRINTREPORT
+ if(readBuf == NULL)
+ return;
+ for(uint8_t i = 0; i < length; i++) {
+ D_PrintHex<uint8_t > (readBuf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+}
+
+uint8_t XBOXOLD::getButtonPress(ButtonEnum b) {
+ uint8_t button = pgm_read_byte(&XBOXOLD_BUTTONS[(uint8_t)b]);
+ if(b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons
+ return buttonValues[button]; // Analog buttons
+ return (ButtonState & button); // Digital buttons
+}
+
+bool XBOXOLD::getButtonClick(ButtonEnum b) {
+ uint8_t button = pgm_read_byte(&XBOXOLD_BUTTONS[(uint8_t)b]);
+ if(b == A || b == B || b == X || b == Y || b == BLACK || b == WHITE || b == L1 || b == R1) { // A, B, X, Y, BLACK, WHITE, L1, and R1 are analog buttons
+ if(buttonClicked[button]) {
+ buttonClicked[button] = false;
+ return true;
+ }
+ return false;
+ }
+
+ bool click = (ButtonClickState & button);
+ ButtonClickState &= ~button; // clear "click" event
+ return click;
+}
+
+int16_t XBOXOLD::getAnalogHat(AnalogHatEnum a) {
+ return hatValue[a];
+}
+
+/* Xbox Controller commands */
+void XBOXOLD::XboxCommand(uint8_t* data, uint16_t nbytes) {
+ //bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x00), Report Type (Output 0x02), interface (0x00), datalength, datalength, data)
+ pUsb->ctrlReq(bAddress, epInfo[XBOX_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x00, 0x02, 0x00, nbytes, nbytes, data, NULL);
+}
+
+void XBOXOLD::setRumbleOn(uint8_t lValue, uint8_t rValue) {
+ uint8_t writeBuf[6];
+
+ writeBuf[0] = 0x00;
+ writeBuf[1] = 0x06;
+ writeBuf[2] = 0x00;
+ writeBuf[3] = rValue; // small weight
+ writeBuf[4] = 0x00;
+ writeBuf[5] = lValue; // big weight
+
+ XboxCommand(writeBuf, 6);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXOLD.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXOLD.h
new file mode 100644
index 000000000..9a36b5cca
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXOLD.h
@@ -0,0 +1,185 @@
+/* Copyright (C) 2013 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _xboxold_h_
+#define _xboxold_h_
+
+#include "Usb.h"
+#include "hid.h"
+#include "controllerEnums.h"
+
+/* Data Xbox taken from descriptors */
+#define EP_MAXPKTSIZE 32 // Max size for data via USB
+
+/* Names we give to the 3 Xbox pipes */
+#define XBOX_CONTROL_PIPE 0
+#define XBOX_INPUT_PIPE 1
+#define XBOX_OUTPUT_PIPE 2
+
+// PID and VID of the different devices
+#define XBOX_VID 0x045E // Microsoft Corporation
+#define MADCATZ_VID 0x1BAD // For unofficial Mad Catz controllers
+#define JOYTECH_VID 0x162E // For unofficial Joytech controllers
+
+#define XBOX_OLD_PID1 0x0202 // Original Microsoft Xbox controller (US)
+#define XBOX_OLD_PID2 0x0285 // Original Microsoft Xbox controller (Japan)
+#define XBOX_OLD_PID3 0x0287 // Microsoft Microsoft Xbox Controller S
+#define XBOX_OLD_PID4 0x0289 // Smaller Microsoft Xbox controller (US)
+
+#define XBOX_MAX_ENDPOINTS 3
+
+/** This class implements support for a the original Xbox controller via USB. */
+class XBOXOLD : public USBDeviceConfig {
+public:
+ /**
+ * Constructor for the XBOXOLD class.
+ * @param pUsb Pointer to USB class instance.
+ */
+ XBOXOLD(USB *pUsb);
+
+ /** @name USBDeviceConfig implementation */
+ /**
+ * Initialize the Xbox Controller.
+ * @param parent Hub number.
+ * @param port Port number on the hub.
+ * @param lowspeed Speed of the device.
+ * @return 0 on success.
+ */
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ /**
+ * Release the USB device.
+ * @return 0 on success.
+ */
+ uint8_t Release();
+ /**
+ * Poll the USB Input endpoins and run the state machines.
+ * @return 0 on success.
+ */
+ uint8_t Poll();
+
+ /**
+ * Get the device address.
+ * @return The device address.
+ */
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ /**
+ * Used to check if the controller has been initialized.
+ * @return True if it's ready.
+ */
+ virtual bool isReady() {
+ return bPollEnable;
+ };
+
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return ((vid == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID) && (pid == XBOX_OLD_PID1 || pid == XBOX_OLD_PID2 || pid == XBOX_OLD_PID3 || pid == XBOX_OLD_PID4));
+ };
+ /**@}*/
+
+ /** @name Xbox Controller functions */
+ /**
+ * getButtonPress(ButtonEnum b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(ButtonEnum b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b),
+ * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b).
+ * @param b ::ButtonEnum to read.
+ * @return getButtonClick(ButtonEnum b) will return a bool, while getButtonPress(ButtonEnum b) will return a byte if reading ::L2 or ::R2.
+ */
+ uint8_t getButtonPress(ButtonEnum b);
+ bool getButtonClick(ButtonEnum b);
+ /**@}*/
+
+ /** @name Xbox Controller functions */
+ /**
+ * Return the analog value from the joysticks on the controller.
+ * @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
+ * @return Returns a signed 16-bit integer.
+ */
+ int16_t getAnalogHat(AnalogHatEnum a);
+
+ /** Turn rumble off the controller. */
+ void setRumbleOff() {
+ setRumbleOn(0, 0);
+ };
+ /**
+ * Turn rumble on.
+ * @param lValue Left motor (big weight) inside the controller.
+ * @param rValue Right motor (small weight) inside the controller.
+ */
+ void setRumbleOn(uint8_t lValue, uint8_t rValue);
+
+ /**
+ * Used to call your own function when the controller is successfully initialized.
+ * @param funcOnInit Function to call.
+ */
+ void attachOnInit(void (*funcOnInit)(void)) {
+ pFuncOnInit = funcOnInit;
+ };
+ /**@}*/
+
+ /** True if a Xbox controller is connected. */
+ bool XboxConnected;
+
+protected:
+ /** Pointer to USB class instance. */
+ USB *pUsb;
+ /** Device address. */
+ uint8_t bAddress;
+ /** Endpoint info structure. */
+ EpInfo epInfo[XBOX_MAX_ENDPOINTS];
+
+private:
+ /**
+ * Called when the controller is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ void (*pFuncOnInit)(void); // Pointer to function called in onInit()
+
+ bool bPollEnable;
+
+ /* Variables to store the digital buttons */
+ uint8_t ButtonState;
+ uint8_t OldButtonState;
+ uint8_t ButtonClickState;
+
+ /* Variables to store the analog buttons */
+ uint8_t buttonValues[8]; // A, B, X, Y, BLACK, WHITE, L1, and R1
+ uint8_t oldButtonValues[8];
+ bool buttonClicked[8];
+
+ int16_t hatValue[4]; // Joystick values
+
+ uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
+
+ void readReport(); // Read incoming data
+ void printReport(uint16_t length); // Print incoming date
+
+ /* Private commands */
+ void XboxCommand(uint8_t* data, uint16_t nbytes);
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXONE.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXONE.cpp
new file mode 100644
index 000000000..2159c0528
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXONE.cpp
@@ -0,0 +1,374 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+ Copyright (C) 2015 guruthree
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+
+ guruthree
+ Web : https://github.com/guruthree/
+ */
+
+#include "XBOXONE.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report send by the Xbox ONE Controller
+
+XBOXONE::XBOXONE(USB *p) :
+pUsb(p), // pointer to USB class instance - mandatory
+bAddress(0), // device address - mandatory
+bPollEnable(false) { // don't start polling before dongle is connected
+ for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }
+
+ if(pUsb) // register in USB subsystem
+ pUsb->RegisterDeviceClass(this); //set devConfig[] entry
+}
+
+uint8_t XBOXONE::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint16_t PID;
+ uint16_t VID;
+
+ // get memory address of USB device address pool
+ AddressPool &addrPool = pUsb->GetAddressPool();
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nXBOXONE Init"), 0x80);
+#endif
+ // check if address has already been assigned to an instance
+ if(bAddress) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress in use"), 0x80);
+#endif
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+ }
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ if(!p->epinfo) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nepinfo is null"), 0x80);
+#endif
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ VID = udd->idVendor;
+ PID = udd->idProduct;
+
+ if(!VIDPIDOK(VID, PID)) // Check VID
+ goto FailUnknownDevice;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nsetAddr: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+#endif
+ return rcode;
+ }
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nAddr: "), 0x80);
+ D_PrintHex<uint8_t > (bAddress, 0x80);
+#endif
+ //delay(300); // Spec says you should wait at least 200ms
+
+ p->lowspeed = false;
+
+ //get pointer to assigned address record
+ p = addrPool.GetUsbDevicePtr(bAddress);
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ // Assign epInfo to epinfo pointer - only EP0 is known
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ /* The application will work in reduced host mode, so we can save program and data
+ memory space. After verifying the VID we will use known values for the
+ configuration values for device, interface, endpoints and HID for the XBOXONE Controllers */
+
+ /* Initialize data structures for endpoints of device */
+ epInfo[ XBOX_OUTPUT_PIPE ].epAddr = 0x01; // XBOX one output endpoint
+ epInfo[ XBOX_OUTPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = 0;
+ epInfo[ XBOX_INPUT_PIPE ].epAddr = 0x01; // XBOX one input endpoint
+ epInfo[ XBOX_INPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = 0;
+ epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = 0;
+
+ rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ delay(200); // Give time for address change
+
+ rcode = pUsb->setConf(bAddress, epInfo[ XBOX_CONTROL_PIPE ].epAddr, 1);
+ if(rcode)
+ goto FailSetConfDescr;
+
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox One Controller Connected\r\n"), 0x80);
+#endif
+
+ delay(200); // let things settle
+
+ // initialize the controller for input
+ writeBuf[0] = 0x05;
+ writeBuf[1] = 0x20;
+ rcode = XboxCommand(writeBuf, 2);
+ if (rcode)
+ goto Fail;
+
+ onInit();
+ XboxOneConnected = true;
+ bPollEnable = true;
+ return 0; // Successful configuration
+
+ /* Diagnostic messages */
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+#endif
+ goto Fail;
+
+FailUnknownDevice:
+#ifdef DEBUG_USB_HOST
+ NotifyFailUnknownDevice(VID, PID);
+#endif
+ rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+Fail:
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox One Init Failed, error code: "), 0x80);
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+/* Performs a cleanup after failed Init() attempt */
+uint8_t XBOXONE::Release() {
+ XboxOneConnected = false;
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+ bAddress = 0;
+ bPollEnable = false;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox One Controller Disconnected\r\n"), 0x80);
+#endif
+ return 0;
+}
+
+uint8_t XBOXONE::Poll() {
+ if(!bPollEnable)
+ return 0;
+ uint16_t BUFFER_SIZE = EP_MAXPKTSIZE;
+ uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[ XBOX_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf);
+ if (!rcode) {
+ readReport();
+#ifdef PRINTREPORT
+ printReport(); // Uncomment "#define PRINTREPORT" to print the report send by the Xbox ONE Controller
+#endif
+ }
+#ifdef DEBUG_USB_HOST
+ else if (rcode != 0x04) { // not a matter of no update to send
+ Notify(PSTR("\r\nXbox One Poll Failed, error code: "), 0x80);
+ NotifyFail(rcode);
+ }
+#endif
+ return rcode;
+}
+
+void XBOXONE::readReport() {
+ if(readBuf == NULL)
+ return;
+ if(readBuf[0] == 0x07) {
+ // The XBOX button has a separate message
+ if(readBuf[4] == 1)
+ ButtonState |= XBOX_BUTTONS[XBOX];
+ else
+ ButtonState &= ~XBOX_BUTTONS[XBOX];
+ }
+ if(readBuf[0] != 0x20) { // Check if it's the correct report, otherwise return - the controller also sends different status reports
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nXbox Poll: "), 0x80);
+ D_PrintHex<uint8_t > (readBuf[0], 0x80); // 0x03 is a heart beat report!
+#endif
+ return;
+ }
+
+ uint16_t xbox = ButtonState & XBOX_BUTTONS[XBOX]; // Since the XBOX button is separate, save it and add it back in
+ // xbox button from before, dpad, abxy, start/back, sync, stick click, shoulder buttons
+ ButtonState = xbox | (((uint16_t)readBuf[5] & 0xF) << 8) | (readBuf[4] & 0xF0) | (((uint16_t)readBuf[4] & 0x0C) << 10) | ((readBuf[4] & 0x01) << 3) | (((uint16_t)readBuf[5] & 0xC0) << 8) | ((readBuf[5] & 0x30) >> 4);
+
+ triggerValue[0] = (uint16_t)(((uint16_t)readBuf[7] << 8) | readBuf[6]);
+ triggerValue[1] = (uint16_t)(((uint16_t)readBuf[9] << 8) | readBuf[8]);
+
+ hatValue[LeftHatX] = (int16_t)(((uint16_t)readBuf[11] << 8) | readBuf[10]);
+ hatValue[LeftHatY] = (int16_t)(((uint16_t)readBuf[13] << 8) | readBuf[12]);
+ hatValue[RightHatX] = (int16_t)(((uint16_t)readBuf[15] << 8) | readBuf[14]);
+ hatValue[RightHatY] = (int16_t)(((uint16_t)readBuf[17] << 8) | readBuf[16]);
+
+ //Notify(PSTR("\r\nButtonState"), 0x80);
+ //PrintHex<uint16_t>(ButtonState, 0x80);
+
+ if(ButtonState != OldButtonState) {
+ ButtonClickState = ButtonState & ~OldButtonState; // Update click state variable
+ OldButtonState = ButtonState;
+ }
+
+ // Handle click detection for triggers
+ if(triggerValue[0] != 0 && triggerValueOld[0] == 0)
+ L2Clicked = true;
+ triggerValueOld[0] = triggerValue[0];
+ if(triggerValue[1] != 0 && triggerValueOld[1] == 0)
+ R2Clicked = true;
+ triggerValueOld[1] = triggerValue[1];
+}
+
+void XBOXONE::printReport() { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox ONE Controller
+#ifdef PRINTREPORT
+ if(readBuf == NULL)
+ return;
+ for(uint8_t i = 0; i < XBOX_REPORT_BUFFER_SIZE; i++) {
+ D_PrintHex<uint8_t > (readBuf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+}
+
+uint16_t XBOXONE::getButtonPress(ButtonEnum b) {
+ if(b == L2) // These are analog buttons
+ return triggerValue[0];
+ else if(b == R2)
+ return triggerValue[1];
+ return (bool)(ButtonState & ((uint16_t)pgm_read_word(&XBOX_BUTTONS[(uint8_t)b])));
+}
+
+bool XBOXONE::getButtonClick(ButtonEnum b) {
+ if(b == L2) {
+ if(L2Clicked) {
+ L2Clicked = false;
+ return true;
+ }
+ return false;
+ } else if(b == R2) {
+ if(R2Clicked) {
+ R2Clicked = false;
+ return true;
+ }
+ return false;
+ }
+ uint16_t button = pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]);
+ bool click = (ButtonClickState & button);
+ ButtonClickState &= ~button; // clear "click" event
+ return click;
+}
+
+int16_t XBOXONE::getAnalogHat(AnalogHatEnum a) {
+ return hatValue[a];
+}
+
+/* Xbox Controller commands */
+uint8_t XBOXONE::XboxCommand(uint8_t* data, uint16_t nbytes) {
+ uint8_t rcode = pUsb->outTransfer(bAddress, epInfo[ XBOX_OUTPUT_PIPE ].epAddr, nbytes, data);
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXboxCommand, Return: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+#endif
+ return rcode;
+}
+
+void XBOXONE::onInit() {
+ // a short buzz to show the controller is active
+ writeBuf[0] = 0x09;
+ writeBuf[1] = 0x08;
+ writeBuf[2] = 0x00;
+ writeBuf[3] = 0x09;
+ writeBuf[4] = 0x00;
+ writeBuf[5] = 0x0f;
+ writeBuf[6] = 0x04;
+ writeBuf[7] = 0x04;
+ writeBuf[8] = 0x20;
+ writeBuf[9] = 0x20;
+ writeBuf[10] = 0x80;
+ XboxCommand(writeBuf, 11);
+
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXONE.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXONE.h
new file mode 100644
index 000000000..11710fcf1
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXONE.h
@@ -0,0 +1,172 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+ Copyright (C) 2015 guruthree
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+
+ guruthree
+ Web : https://github.com/guruthree/
+ */
+
+
+#ifndef _xboxone_h_
+#define _xboxone_h_
+
+#include "Usb.h"
+#include "xboxEnums.h"
+
+/* Data Xbox ONE taken from descriptors */
+#define EP_MAXPKTSIZE 32 // max size for data via USB
+
+/* Names we give to the 3 XboxONE pipes */
+#define XBOX_CONTROL_PIPE 0
+#define XBOX_OUTPUT_PIPE 1
+#define XBOX_INPUT_PIPE 2
+
+// PID and VID of the different devices
+#define XBOX_VID 0x045E // Microsoft Corporation
+#define XBOX_ONE_PID 0x02D1 // Microsoft One Wired controller
+
+#define XBOX_REPORT_BUFFER_SIZE 14 // Size of the input report buffer
+
+#define XBOX_MAX_ENDPOINTS 3
+
+/** This class implements support for a Xbox ONE controller connected via USB. */
+class XBOXONE : public USBDeviceConfig {
+public:
+ /**
+ * Constructor for the XBOXONE class.
+ * @param pUsb Pointer to USB class instance.
+ */
+ XBOXONE(USB *pUsb);
+
+ /** @name USBDeviceConfig implementation */
+ /**
+ * Initialize the Xbox Controller.
+ * @param parent Hub number.
+ * @param port Port number on the hub.
+ * @param lowspeed Speed of the device.
+ * @return 0 on success.
+ */
+ virtual uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ /**
+ * Release the USB device.
+ * @return 0 on success.
+ */
+ virtual uint8_t Release();
+ /**
+ * Poll the USB Input endpoins and run the state machines.
+ * @return 0 on success.
+ */
+ virtual uint8_t Poll();
+
+ /**
+ * Get the device address.
+ * @return The device address.
+ */
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ /**
+ * Used to check if the controller has been initialized.
+ * @return True if it's ready.
+ */
+ virtual bool isReady() {
+ return bPollEnable;
+ };
+
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return (vid == XBOX_VID && pid == XBOX_ONE_PID);
+ };
+ /**@}*/
+
+ /** @name Xbox Controller functions */
+ /**
+ * getButtonPress(ButtonEnum b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(ButtonEnum b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b),
+ * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b).
+ * @param b ::ButtonEnum to read.
+ * @return getButtonClick(ButtonEnum b) will return a bool, while getButtonPress(ButtonEnum b) will return a word if reading ::L2 or ::R2.
+ */
+ uint16_t getButtonPress(ButtonEnum b);
+ bool getButtonClick(ButtonEnum b);
+
+ /**
+ * Return the analog value from the joysticks on the controller.
+ * @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
+ * @return Returns a signed 16-bit integer.
+ */
+ int16_t getAnalogHat(AnalogHatEnum a);
+
+ /**
+ * Used to call your own function when the controller is successfully initialized.
+ * @param funcOnInit Function to call.
+ */
+ void attachOnInit(void (*funcOnInit)(void)) {
+ pFuncOnInit = funcOnInit;
+ };
+ /**@}*/
+
+ /** True if a Xbox ONE controller is connected. */
+ bool XboxOneConnected;
+
+protected:
+ /** Pointer to USB class instance. */
+ USB *pUsb;
+ /** Device address. */
+ uint8_t bAddress;
+ /** Endpoint info structure. */
+ EpInfo epInfo[XBOX_MAX_ENDPOINTS];
+
+private:
+ /**
+ * Called when the controller is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ */
+ void onInit();
+ void (*pFuncOnInit)(void); // Pointer to function called in onInit()
+
+ bool bPollEnable;
+
+ /* Variables to store the buttons */
+ uint16_t ButtonState;
+ uint16_t OldButtonState;
+ uint16_t ButtonClickState;
+ int16_t hatValue[4];
+ uint16_t triggerValue[2];
+ uint16_t triggerValueOld[2];
+
+ bool L2Clicked; // These buttons are analog, so we use we use these bools to check if they where clicked or not
+ bool R2Clicked;
+
+ uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
+ uint8_t writeBuf[12]; // General purpose buffer for output data
+
+ void readReport(); // read incoming data
+ void printReport(); // print incoming date - Uncomment for debugging
+
+ /* Private commands */
+ uint8_t XboxCommand(uint8_t* data, uint16_t nbytes);
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXRECV.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXRECV.cpp
new file mode 100644
index 000000000..41f1ff581
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXRECV.cpp
@@ -0,0 +1,583 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+
+ getBatteryLevel and checkStatus functions made by timstamp.co.uk found using BusHound from Perisoft.net
+ */
+
+#include "XBOXRECV.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report send by the Xbox 360 Controller
+
+XBOXRECV::XBOXRECV(USB *p) :
+pUsb(p), // pointer to USB class instance - mandatory
+bAddress(0), // device address - mandatory
+bPollEnable(false) { // don't start polling before dongle is connected
+ for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }
+
+ if(pUsb) // register in USB subsystem
+ pUsb->RegisterDeviceClass(this); //set devConfig[] entry
+}
+
+uint8_t XBOXRECV::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+ uint8_t buf[constBufSize];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint16_t PID, VID;
+
+ AddressPool &addrPool = pUsb->GetAddressPool(); // Get memory address of USB device address pool
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nXBOXRECV Init"), 0x80);
+#endif
+
+ if(bAddress) { // Check if address has already been assigned to an instance
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress in use"), 0x80);
+#endif
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+ }
+
+ p = addrPool.GetUsbDevicePtr(0); // Get pointer to pseudo device with address 0 assigned
+
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ if(!p->epinfo) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nepinfo is null"), 0x80);
+#endif
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ oldep_ptr = p->epinfo; // Save old pointer to EP_RECORD of address 0
+ p->epinfo = epInfo; // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->lowspeed = lowspeed;
+
+ rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
+
+ p->epinfo = oldep_ptr; // Restore p->epinfo
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ VID = udd->idVendor;
+ PID = udd->idProduct;
+
+ if((VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID) || (PID != XBOX_WIRELESS_RECEIVER_PID && PID != XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID)) { // Check if it's a Xbox receiver using the Vendor ID and Product ID
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nYou'll need a wireless receiver for this libary to work"), 0x80);
+#endif
+ goto FailUnknownDevice;
+ }
+
+ bAddress = addrPool.AllocAddress(parent, false, port); // Allocate new address according to device class
+
+ if(!bAddress) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nOut of address space"), 0x80);
+#endif
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+ }
+
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0; // Extract Max Packet Size from device descriptor
+
+ delay(20); // Wait a little before resetting device
+
+ return USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET;
+
+ /* Diagnostic messages */
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr(rcode);
+#endif
+ if(rcode != hrJERR)
+ rcode = USB_ERROR_FailGetDevDescr;
+ goto Fail;
+
+FailUnknownDevice:
+#ifdef DEBUG_USB_HOST
+ NotifyFailUnknownDevice(VID, PID);
+#endif
+ rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+Fail:
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox 360 Init Failed, error code: "), 0x80);
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+};
+
+uint8_t XBOXRECV::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t rcode;
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nBTD Init"), 0x80);
+#endif
+ UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
+
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ delay(300); // Assign new address to the device
+
+ rcode = pUsb->setAddr(0, 0, bAddress); // Assign new address to the device
+ if(rcode) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nsetAddr: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+#endif
+ p->lowspeed = false;
+ goto Fail;
+ }
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nAddr: "), 0x80);
+ D_PrintHex<uint8_t > (bAddress, 0x80);
+#endif
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress); // Get pointer to assigned address record
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ p->lowspeed = lowspeed;
+
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo); // Assign epInfo to epinfo pointer - only EP0 is known
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ /* The application will work in reduced host mode, so we can save program and data
+ memory space. After verifying the VID we will use known values for the
+ configuration values for device, interface, endpoints and HID for the XBOX360 Wireless receiver */
+
+ /* Initialize data structures for endpoints of device */
+ epInfo[ XBOX_INPUT_PIPE_1 ].epAddr = 0x01; // XBOX 360 report endpoint - poll interval 1ms
+ epInfo[ XBOX_INPUT_PIPE_1 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_INPUT_PIPE_1 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_INPUT_PIPE_1 ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_INPUT_PIPE_1 ].bmSndToggle = 0;
+ epInfo[ XBOX_INPUT_PIPE_1 ].bmRcvToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE_1 ].epAddr = 0x01; // XBOX 360 output endpoint - poll interval 8ms
+ epInfo[ XBOX_OUTPUT_PIPE_1 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_OUTPUT_PIPE_1 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_OUTPUT_PIPE_1 ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_OUTPUT_PIPE_1 ].bmSndToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE_1 ].bmRcvToggle = 0;
+
+ epInfo[ XBOX_INPUT_PIPE_2 ].epAddr = 0x03; // XBOX 360 report endpoint - poll interval 1ms
+ epInfo[ XBOX_INPUT_PIPE_2 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_INPUT_PIPE_2 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_INPUT_PIPE_2 ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_INPUT_PIPE_2 ].bmSndToggle = 0;
+ epInfo[ XBOX_INPUT_PIPE_2 ].bmRcvToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE_2 ].epAddr = 0x03; // XBOX 360 output endpoint - poll interval 8ms
+ epInfo[ XBOX_OUTPUT_PIPE_2 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_OUTPUT_PIPE_2 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_OUTPUT_PIPE_2 ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_OUTPUT_PIPE_2 ].bmSndToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE_2 ].bmRcvToggle = 0;
+
+ epInfo[ XBOX_INPUT_PIPE_3 ].epAddr = 0x05; // XBOX 360 report endpoint - poll interval 1ms
+ epInfo[ XBOX_INPUT_PIPE_3 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_INPUT_PIPE_3 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_INPUT_PIPE_3 ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_INPUT_PIPE_3 ].bmSndToggle = 0;
+ epInfo[ XBOX_INPUT_PIPE_3 ].bmRcvToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE_3 ].epAddr = 0x05; // XBOX 360 output endpoint - poll interval 8ms
+ epInfo[ XBOX_OUTPUT_PIPE_3 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_OUTPUT_PIPE_3 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_OUTPUT_PIPE_3 ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_OUTPUT_PIPE_3 ].bmSndToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE_3 ].bmRcvToggle = 0;
+
+ epInfo[ XBOX_INPUT_PIPE_4 ].epAddr = 0x07; // XBOX 360 report endpoint - poll interval 1ms
+ epInfo[ XBOX_INPUT_PIPE_4 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_INPUT_PIPE_4 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_INPUT_PIPE_4 ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_INPUT_PIPE_4 ].bmSndToggle = 0;
+ epInfo[ XBOX_INPUT_PIPE_4 ].bmRcvToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE_4 ].epAddr = 0x07; // XBOX 360 output endpoint - poll interval 8ms
+ epInfo[ XBOX_OUTPUT_PIPE_4 ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_OUTPUT_PIPE_4 ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_OUTPUT_PIPE_4 ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_OUTPUT_PIPE_4 ].bmSndToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE_4 ].bmRcvToggle = 0;
+
+ rcode = pUsb->setEpInfoEntry(bAddress, 9, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ delay(200); //Give time for address change
+
+ rcode = pUsb->setConf(bAddress, epInfo[ XBOX_CONTROL_PIPE ].epAddr, 1);
+ if(rcode)
+ goto FailSetConfDescr;
+
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox Wireless Receiver Connected\r\n"), 0x80);
+#endif
+ XboxReceiverConnected = true;
+ bPollEnable = true;
+ checkStatusTimer = 0; // Reset timer
+ return 0; // Successful configuration
+
+ /* Diagnostic messages */
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+#endif
+
+Fail:
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox 360 Init Failed, error code: "), 0x80);
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+/* Performs a cleanup after failed Init() attempt */
+uint8_t XBOXRECV::Release() {
+ XboxReceiverConnected = false;
+ for(uint8_t i = 0; i < 4; i++)
+ Xbox360Connected[i] = 0x00;
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+ bAddress = 0;
+ bPollEnable = false;
+ return 0;
+}
+
+uint8_t XBOXRECV::Poll() {
+ if(!bPollEnable)
+ return 0;
+ if(!checkStatusTimer || ((millis() - checkStatusTimer) > 3000)) { // Run checkStatus every 3 seconds
+ checkStatusTimer = millis();
+ checkStatus();
+ }
+
+ uint8_t inputPipe;
+ uint16_t bufferSize;
+ for(uint8_t i = 0; i < 4; i++) {
+ if(i == 0)
+ inputPipe = XBOX_INPUT_PIPE_1;
+ else if(i == 1)
+ inputPipe = XBOX_INPUT_PIPE_2;
+ else if(i == 2)
+ inputPipe = XBOX_INPUT_PIPE_3;
+ else
+ inputPipe = XBOX_INPUT_PIPE_4;
+
+ bufferSize = EP_MAXPKTSIZE; // This is the maximum number of bytes we want to receive
+ pUsb->inTransfer(bAddress, epInfo[ inputPipe ].epAddr, &bufferSize, readBuf);
+ if(bufferSize > 0) { // The number of received bytes
+#ifdef EXTRADEBUG
+ Notify(PSTR("Bytes Received: "), 0x80);
+ D_PrintHex<uint16_t > (bufferSize, 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+ readReport(i);
+#ifdef PRINTREPORT
+ printReport(i, bufferSize); // Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller
+#endif
+ }
+ }
+ return 0;
+}
+
+void XBOXRECV::readReport(uint8_t controller) {
+ if(readBuf == NULL)
+ return;
+ // This report is send when a controller is connected and disconnected
+ if(readBuf[0] == 0x08 && readBuf[1] != Xbox360Connected[controller]) {
+ Xbox360Connected[controller] = readBuf[1];
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("Controller "), 0x80);
+ Notify(controller, 0x80);
+#endif
+ if(Xbox360Connected[controller]) {
+#ifdef DEBUG_USB_HOST
+ const char* str = 0;
+ switch(readBuf[1]) {
+ case 0x80: str = PSTR(" as controller\r\n");
+ break;
+ case 0x40: str = PSTR(" as headset\r\n");
+ break;
+ case 0xC0: str = PSTR(" as controller+headset\r\n");
+ break;
+ }
+ Notify(PSTR(": connected"), 0x80);
+ Notify(str, 0x80);
+#endif
+ onInit(controller);
+ }
+#ifdef DEBUG_USB_HOST
+ else
+ Notify(PSTR(": disconnected\r\n"), 0x80);
+#endif
+ return;
+ }
+ // Controller status report
+ if(readBuf[1] == 0x00 && readBuf[3] & 0x13 && readBuf[4] >= 0x22) {
+ controllerStatus[controller] = ((uint16_t)readBuf[3] << 8) | readBuf[4];
+ return;
+ }
+ if(readBuf[1] != 0x01) // Check if it's the correct report - the receiver also sends different status reports
+ return;
+
+ // A controller must be connected if it's sending data
+ if(!Xbox360Connected[controller])
+ Xbox360Connected[controller] |= 0x80;
+
+ ButtonState[controller] = (uint32_t)(readBuf[9] | ((uint16_t)readBuf[8] << 8) | ((uint32_t)readBuf[7] << 16) | ((uint32_t)readBuf[6] << 24));
+
+ hatValue[controller][LeftHatX] = (int16_t)(((uint16_t)readBuf[11] << 8) | readBuf[10]);
+ hatValue[controller][LeftHatY] = (int16_t)(((uint16_t)readBuf[13] << 8) | readBuf[12]);
+ hatValue[controller][RightHatX] = (int16_t)(((uint16_t)readBuf[15] << 8) | readBuf[14]);
+ hatValue[controller][RightHatY] = (int16_t)(((uint16_t)readBuf[17] << 8) | readBuf[16]);
+
+ //Notify(PSTR("\r\nButtonState: "), 0x80);
+ //PrintHex<uint32_t>(ButtonState[controller], 0x80);
+
+ if(ButtonState[controller] != OldButtonState[controller]) {
+ buttonStateChanged[controller] = true;
+ ButtonClickState[controller] = (ButtonState[controller] >> 16) & ((~OldButtonState[controller]) >> 16); // Update click state variable, but don't include the two trigger buttons L2 and R2
+ if(((uint8_t)OldButtonState[controller]) == 0 && ((uint8_t)ButtonState[controller]) != 0) // The L2 and R2 buttons are special as they are analog buttons
+ R2Clicked[controller] = true;
+ if((uint8_t)(OldButtonState[controller] >> 8) == 0 && (uint8_t)(ButtonState[controller] >> 8) != 0)
+ L2Clicked[controller] = true;
+ OldButtonState[controller] = ButtonState[controller];
+ }
+}
+
+void XBOXRECV::printReport(uint8_t controller, uint8_t nBytes) { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller
+#ifdef PRINTREPORT
+ if(readBuf == NULL)
+ return;
+ Notify(PSTR("Controller "), 0x80);
+ Notify(controller, 0x80);
+ Notify(PSTR(": "), 0x80);
+ for(uint8_t i = 0; i < nBytes; i++) {
+ D_PrintHex<uint8_t > (readBuf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+}
+
+uint8_t XBOXRECV::getButtonPress(ButtonEnum b, uint8_t controller) {
+ if(b == L2) // These are analog buttons
+ return (uint8_t)(ButtonState[controller] >> 8);
+ else if(b == R2)
+ return (uint8_t)ButtonState[controller];
+ return (bool)(ButtonState[controller] & ((uint32_t)pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]) << 16));
+}
+
+bool XBOXRECV::getButtonClick(ButtonEnum b, uint8_t controller) {
+ if(b == L2) {
+ if(L2Clicked[controller]) {
+ L2Clicked[controller] = false;
+ return true;
+ }
+ return false;
+ } else if(b == R2) {
+ if(R2Clicked[controller]) {
+ R2Clicked[controller] = false;
+ return true;
+ }
+ return false;
+ }
+ uint16_t button = pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]);
+ bool click = (ButtonClickState[controller] & button);
+ ButtonClickState[controller] &= ~button; // clear "click" event
+ return click;
+}
+
+int16_t XBOXRECV::getAnalogHat(AnalogHatEnum a, uint8_t controller) {
+ return hatValue[controller][a];
+}
+
+bool XBOXRECV::buttonChanged(uint8_t controller) {
+ bool state = buttonStateChanged[controller];
+ buttonStateChanged[controller] = false;
+ return state;
+}
+
+/*
+ControllerStatus Breakdown
+ControllerStatus[controller] & 0x0001 // 0
+ControllerStatus[controller] & 0x0002 // normal batteries, no rechargeable battery pack
+ControllerStatus[controller] & 0x0004 // controller starting up / settling
+ControllerStatus[controller] & 0x0008 // headset adapter plugged in, but no headphones connected (mute?)
+ControllerStatus[controller] & 0x0010 // 0
+ControllerStatus[controller] & 0x0020 // 1
+ControllerStatus[controller] & 0x0040 // battery level (high bit)
+ControllerStatus[controller] & 0x0080 // battery level (low bit)
+ControllerStatus[controller] & 0x0100 // 1
+ControllerStatus[controller] & 0x0200 // 1
+ControllerStatus[controller] & 0x0400 // headset adapter plugged in
+ControllerStatus[controller] & 0x0800 // 0
+ControllerStatus[controller] & 0x1000 // 1
+ControllerStatus[controller] & 0x2000 // 0
+ControllerStatus[controller] & 0x4000 // 0
+ControllerStatus[controller] & 0x8000 // 0
+ */
+uint8_t XBOXRECV::getBatteryLevel(uint8_t controller) {
+ return ((controllerStatus[controller] & 0x00C0) >> 6);
+}
+
+void XBOXRECV::XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes) {
+#ifdef EXTRADEBUG
+ uint8_t rcode;
+#endif
+ uint8_t outputPipe;
+ switch(controller) {
+ case 0: outputPipe = XBOX_OUTPUT_PIPE_1;
+ break;
+ case 1: outputPipe = XBOX_OUTPUT_PIPE_2;
+ break;
+ case 2: outputPipe = XBOX_OUTPUT_PIPE_3;
+ break;
+ case 3: outputPipe = XBOX_OUTPUT_PIPE_4;
+ break;
+ default:
+ return;
+ }
+#ifdef EXTRADEBUG
+ rcode =
+#endif
+ pUsb->outTransfer(bAddress, epInfo[ outputPipe ].epAddr, nbytes, data);
+#ifdef EXTRADEBUG
+ if(rcode)
+ Notify(PSTR("Error sending Xbox message\r\n"), 0x80);
+#endif
+}
+
+void XBOXRECV::disconnect(uint8_t controller) {
+ writeBuf[0] = 0x00;
+ writeBuf[1] = 0x00;
+ writeBuf[2] = 0x08;
+ writeBuf[3] = 0xC0;
+
+ XboxCommand(controller, writeBuf, 4);
+}
+
+void XBOXRECV::setLedRaw(uint8_t value, uint8_t controller) {
+ writeBuf[0] = 0x00;
+ writeBuf[1] = 0x00;
+ writeBuf[2] = 0x08;
+ writeBuf[3] = value | 0x40;
+
+ XboxCommand(controller, writeBuf, 4);
+}
+
+void XBOXRECV::setLedOn(LEDEnum led, uint8_t controller) {
+ if(led == OFF)
+ setLedRaw(0, controller);
+ else if(led != ALL) // All LEDs can't be on a the same time
+ setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]) + 4, controller);
+}
+
+void XBOXRECV::setLedBlink(LEDEnum led, uint8_t controller) {
+ setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]), controller);
+}
+
+void XBOXRECV::setLedMode(LEDModeEnum ledMode, uint8_t controller) { // This function is used to do some speciel LED stuff the controller supports
+ setLedRaw((uint8_t)ledMode, controller);
+}
+
+/* PC runs this at interval of approx 2 seconds
+Thanks to BusHound from Perisoft.net for the Windows USB Analysis output
+Found by timstamp.co.uk
+ */
+void XBOXRECV::checkStatus() {
+ if(!bPollEnable)
+ return;
+ // Get controller info
+ writeBuf[0] = 0x08;
+ writeBuf[1] = 0x00;
+ writeBuf[2] = 0x0f;
+ writeBuf[3] = 0xc0;
+ for(uint8_t i = 0; i < 4; i++) {
+ XboxCommand(i, writeBuf, 4);
+ }
+ // Get battery status
+ writeBuf[0] = 0x00;
+ writeBuf[1] = 0x00;
+ writeBuf[2] = 0x00;
+ writeBuf[3] = 0x40;
+ for(uint8_t i = 0; i < 4; i++) {
+ if(Xbox360Connected[i])
+ XboxCommand(i, writeBuf, 4);
+ }
+}
+
+void XBOXRECV::setRumbleOn(uint8_t lValue, uint8_t rValue, uint8_t controller) {
+ writeBuf[0] = 0x00;
+ writeBuf[1] = 0x01;
+ writeBuf[2] = 0x0f;
+ writeBuf[3] = 0xc0;
+ writeBuf[4] = 0x00;
+ writeBuf[5] = lValue; // big weight
+ writeBuf[6] = rValue; // small weight
+
+ XboxCommand(controller, writeBuf, 7);
+}
+
+void XBOXRECV::onInit(uint8_t controller) {
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ else {
+ LEDEnum led;
+ if(controller == 0)
+ led = LED1;
+ else if(controller == 1)
+ led = LED2;
+ else if(controller == 2)
+ led = LED3;
+ else
+ led = LED4;
+ setLedOn(led, controller);
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXRECV.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXRECV.h
new file mode 100644
index 000000000..4f9214653
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXRECV.h
@@ -0,0 +1,276 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+
+ getBatteryLevel and checkStatus functions made by timstamp.co.uk found using BusHound from Perisoft.net
+ */
+
+#ifndef _xboxrecv_h_
+#define _xboxrecv_h_
+
+#include "Usb.h"
+#include "xboxEnums.h"
+
+/* Data Xbox 360 taken from descriptors */
+#define EP_MAXPKTSIZE 32 // max size for data via USB
+
+/* Names we give to the 9 Xbox360 pipes */
+#define XBOX_CONTROL_PIPE 0
+#define XBOX_INPUT_PIPE_1 1
+#define XBOX_OUTPUT_PIPE_1 2
+#define XBOX_INPUT_PIPE_2 3
+#define XBOX_OUTPUT_PIPE_2 4
+#define XBOX_INPUT_PIPE_3 5
+#define XBOX_OUTPUT_PIPE_3 6
+#define XBOX_INPUT_PIPE_4 7
+#define XBOX_OUTPUT_PIPE_4 8
+
+// PID and VID of the different devices
+#define XBOX_VID 0x045E // Microsoft Corporation
+#define MADCATZ_VID 0x1BAD // For unofficial Mad Catz receivers
+#define JOYTECH_VID 0x162E // For unofficial Joytech controllers
+
+#define XBOX_WIRELESS_RECEIVER_PID 0x0719 // Microsoft Wireless Gaming Receiver
+#define XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID 0x0291 // Third party Wireless Gaming Receiver
+
+#define XBOX_MAX_ENDPOINTS 9
+
+/**
+ * This class implements support for a Xbox Wireless receiver.
+ *
+ * Up to four controllers can connect to one receiver, if more is needed one can use a second receiver via the USBHub class.
+ */
+class XBOXRECV : public USBDeviceConfig {
+public:
+ /**
+ * Constructor for the XBOXRECV class.
+ * @param pUsb Pointer to USB class instance.
+ */
+ XBOXRECV(USB *pUsb);
+
+ /** @name USBDeviceConfig implementation */
+ /**
+ * Address assignment and basic initilization is done here.
+ * @param parent Hub number.
+ * @param port Port number on the hub.
+ * @param lowspeed Speed of the device.
+ * @return 0 on success.
+ */
+ uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed);
+ /**
+ * Initialize the Xbox wireless receiver.
+ * @param parent Hub number.
+ * @param port Port number on the hub.
+ * @param lowspeed Speed of the device.
+ * @return 0 on success.
+ */
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ /**
+ * Release the USB device.
+ * @return 0 on success.
+ */
+ uint8_t Release();
+ /**
+ * Poll the USB Input endpoins and run the state machines.
+ * @return 0 on success.
+ */
+ uint8_t Poll();
+
+ /**
+ * Get the device address.
+ * @return The device address.
+ */
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ /**
+ * Used to check if the controller has been initialized.
+ * @return True if it's ready.
+ */
+ virtual bool isReady() {
+ return bPollEnable;
+ };
+
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return ((vid == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID) && (pid == XBOX_WIRELESS_RECEIVER_PID || pid == XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID));
+ };
+ /**@}*/
+
+ /** @name Xbox Controller functions */
+ /**
+ * getButtonPress(uint8_t controller, ButtonEnum b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(uint8_t controller, ButtonEnum b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(uint8_t controller, ButtonEnum b),
+ * but if you need to drive a robot forward you would use getButtonPress(uint8_t controller, ButtonEnum b).
+ * @param b ::ButtonEnum to read.
+ * @param controller The controller to read from. Default to 0.
+ * @return getButtonClick(uint8_t controller, ButtonEnum b) will return a bool, while getButtonPress(uint8_t controller, ButtonEnum b) will return a byte if reading ::L2 or ::R2.
+ */
+ uint8_t getButtonPress(ButtonEnum b, uint8_t controller = 0);
+ bool getButtonClick(ButtonEnum b, uint8_t controller = 0);
+ /**@}*/
+
+ /** @name Xbox Controller functions */
+ /**
+ * Return the analog value from the joysticks on the controller.
+ * @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
+ * @param controller The controller to read from. Default to 0.
+ * @return Returns a signed 16-bit integer.
+ */
+ int16_t getAnalogHat(AnalogHatEnum a, uint8_t controller = 0);
+
+ /**
+ * Used to disconnect any of the controllers.
+ * @param controller The controller to disconnect. Default to 0.
+ */
+ void disconnect(uint8_t controller = 0);
+
+ /**
+ * Turn rumble off and all the LEDs on the specific controller.
+ * @param controller The controller to write to. Default to 0.
+ */
+ void setAllOff(uint8_t controller = 0) {
+ setRumbleOn(0, 0, controller);
+ setLedOff(controller);
+ };
+
+ /**
+ * Turn rumble off the specific controller.
+ * @param controller The controller to write to. Default to 0.
+ */
+ void setRumbleOff(uint8_t controller = 0) {
+ setRumbleOn(0, 0, controller);
+ };
+ /**
+ * Turn rumble on.
+ * @param lValue Left motor (big weight) inside the controller.
+ * @param rValue Right motor (small weight) inside the controller.
+ * @param controller The controller to write to. Default to 0.
+ */
+ void setRumbleOn(uint8_t lValue, uint8_t rValue, uint8_t controller = 0);
+ /**
+ * Set LED value. Without using the ::LEDEnum or ::LEDModeEnum.
+ * @param value See:
+ * setLedOff(uint8_t controller), setLedOn(uint8_t controller, LED l),
+ * setLedBlink(uint8_t controller, LED l), and setLedMode(uint8_t controller, LEDMode lm).
+ * @param controller The controller to write to. Default to 0.
+ */
+ void setLedRaw(uint8_t value, uint8_t controller = 0);
+
+ /**
+ * Turn all LEDs off the specific controller.
+ * @param controller The controller to write to. Default to 0.
+ */
+ void setLedOff(uint8_t controller = 0) {
+ setLedRaw(0, controller);
+ };
+ /**
+ * Turn on a LED by using ::LEDEnum.
+ * @param l ::OFF, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller.
+ * @param controller The controller to write to. Default to 0.
+ */
+ void setLedOn(LEDEnum l, uint8_t controller = 0);
+ /**
+ * Turn on a LED by using ::LEDEnum.
+ * @param l ::ALL, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller.
+ * @param controller The controller to write to. Default to 0.
+ */
+ void setLedBlink(LEDEnum l, uint8_t controller = 0);
+ /**
+ * Used to set special LED modes supported by the Xbox controller.
+ * @param lm See ::LEDModeEnum.
+ * @param controller The controller to write to. Default to 0.
+ */
+ void setLedMode(LEDModeEnum lm, uint8_t controller = 0);
+ /**
+ * Used to get the battery level from the controller.
+ * @param controller The controller to read from. Default to 0.
+ * @return Returns the battery level as an integer in the range of 0-3.
+ */
+ uint8_t getBatteryLevel(uint8_t controller = 0);
+ /**
+ * Used to check if a button has changed.
+ * @param controller The controller to read from. Default to 0.
+ * @return True if a button has changed.
+ */
+ bool buttonChanged(uint8_t controller = 0);
+
+ /**
+ * Used to call your own function when the controller is successfully initialized.
+ * @param funcOnInit Function to call.
+ */
+ void attachOnInit(void (*funcOnInit)(void)) {
+ pFuncOnInit = funcOnInit;
+ };
+ /**@}*/
+
+ /** True if a wireless receiver is connected. */
+ bool XboxReceiverConnected;
+ /** Variable used to indicate if the XBOX 360 controller is successfully connected. */
+ uint8_t Xbox360Connected[4];
+
+protected:
+ /** Pointer to USB class instance. */
+ USB *pUsb;
+ /** Device address. */
+ uint8_t bAddress;
+ /** Endpoint info structure. */
+ EpInfo epInfo[XBOX_MAX_ENDPOINTS];
+
+private:
+ /**
+ * Called when the controller is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ * @param controller The initialized controller.
+ */
+ void onInit(uint8_t controller);
+ void (*pFuncOnInit)(void); // Pointer to function called in onInit()
+
+ bool bPollEnable;
+
+ /* Variables to store the buttons */
+ uint32_t ButtonState[4];
+ uint32_t OldButtonState[4];
+ uint16_t ButtonClickState[4];
+ int16_t hatValue[4][4];
+ uint16_t controllerStatus[4];
+ bool buttonStateChanged[4]; // True if a button has changed
+
+ bool L2Clicked[4]; // These buttons are analog, so we use we use these bools to check if they where clicked or not
+ bool R2Clicked[4];
+
+ uint32_t checkStatusTimer; // Timing for checkStatus() signals
+
+ uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
+ uint8_t writeBuf[7]; // General purpose buffer for output data
+
+ void readReport(uint8_t controller); // read incoming data
+ void printReport(uint8_t controller, uint8_t nBytes); // print incoming date - Uncomment for debugging
+
+ /* Private commands */
+ void XboxCommand(uint8_t controller, uint8_t* data, uint16_t nbytes);
+ void checkStatus();
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXUSB.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXUSB.cpp
new file mode 100644
index 000000000..ddece21b4
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXUSB.cpp
@@ -0,0 +1,361 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#include "XBOXUSB.h"
+// To enable serial debugging see "settings.h"
+//#define EXTRADEBUG // Uncomment to get even more debugging data
+//#define PRINTREPORT // Uncomment to print the report send by the Xbox 360 Controller
+
+XBOXUSB::XBOXUSB(USB *p) :
+pUsb(p), // pointer to USB class instance - mandatory
+bAddress(0), // device address - mandatory
+bPollEnable(false) { // don't start polling before dongle is connected
+ for(uint8_t i = 0; i < XBOX_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }
+
+ if(pUsb) // register in USB subsystem
+ pUsb->RegisterDeviceClass(this); //set devConfig[] entry
+}
+
+uint8_t XBOXUSB::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint16_t PID;
+ uint16_t VID;
+
+ // get memory address of USB device address pool
+ AddressPool &addrPool = pUsb->GetAddressPool();
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nXBOXUSB Init"), 0x80);
+#endif
+ // check if address has already been assigned to an instance
+ if(bAddress) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress in use"), 0x80);
+#endif
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+ }
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nAddress not found"), 0x80);
+#endif
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ if(!p->epinfo) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nepinfo is null"), 0x80);
+#endif
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf); // Get device descriptor - addr, ep, nbytes, data
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ VID = udd->idVendor;
+ PID = udd->idProduct;
+
+ if(VID != XBOX_VID && VID != MADCATZ_VID && VID != JOYTECH_VID && VID != GAMESTOP_VID) // Check VID
+ goto FailUnknownDevice;
+ if(PID == XBOX_WIRELESS_PID) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nYou have plugged in a wireless Xbox 360 controller - it doesn't support USB communication"), 0x80);
+#endif
+ goto FailUnknownDevice;
+ } else if(PID == XBOX_WIRELESS_RECEIVER_PID || PID == XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID) {
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nThis library only supports Xbox 360 controllers via USB"), 0x80);
+#endif
+ goto FailUnknownDevice;
+ } else if(PID != XBOX_WIRED_PID && PID != MADCATZ_WIRED_PID && PID != GAMESTOP_WIRED_PID && PID != AFTERGLOW_WIRED_PID && PID != JOYTECH_WIRED_PID) // Check PID
+ goto FailUnknownDevice;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nsetAddr: "), 0x80);
+ D_PrintHex<uint8_t > (rcode, 0x80);
+#endif
+ return rcode;
+ }
+#ifdef EXTRADEBUG
+ Notify(PSTR("\r\nAddr: "), 0x80);
+ D_PrintHex<uint8_t > (bAddress, 0x80);
+#endif
+ //delay(300); // Spec says you should wait at least 200ms
+
+ p->lowspeed = false;
+
+ //get pointer to assigned address record
+ p = addrPool.GetUsbDevicePtr(bAddress);
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ // Assign epInfo to epinfo pointer - only EP0 is known
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ /* The application will work in reduced host mode, so we can save program and data
+ memory space. After verifying the VID we will use known values for the
+ configuration values for device, interface, endpoints and HID for the XBOX360 Controllers */
+
+ /* Initialize data structures for endpoints of device */
+ epInfo[ XBOX_INPUT_PIPE ].epAddr = 0x01; // XBOX 360 report endpoint
+ epInfo[ XBOX_INPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_INPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_INPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_INPUT_PIPE ].bmSndToggle = 0;
+ epInfo[ XBOX_INPUT_PIPE ].bmRcvToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE ].epAddr = 0x02; // XBOX 360 output endpoint
+ epInfo[ XBOX_OUTPUT_PIPE ].epAttribs = USB_TRANSFER_TYPE_INTERRUPT;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmNakPower = USB_NAK_NOWAIT; // Only poll once for interrupt endpoints
+ epInfo[ XBOX_OUTPUT_PIPE ].maxPktSize = EP_MAXPKTSIZE;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmSndToggle = 0;
+ epInfo[ XBOX_OUTPUT_PIPE ].bmRcvToggle = 0;
+
+ rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo);
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ delay(200); // Give time for address change
+
+ rcode = pUsb->setConf(bAddress, epInfo[ XBOX_CONTROL_PIPE ].epAddr, 1);
+ if(rcode)
+ goto FailSetConfDescr;
+
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox 360 Controller Connected\r\n"), 0x80);
+#endif
+ onInit();
+ Xbox360Connected = true;
+ bPollEnable = true;
+ return 0; // Successful configuration
+
+ /* Diagnostic messages */
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+#endif
+ goto Fail;
+
+FailUnknownDevice:
+#ifdef DEBUG_USB_HOST
+ NotifyFailUnknownDevice(VID, PID);
+#endif
+ rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+Fail:
+#ifdef DEBUG_USB_HOST
+ Notify(PSTR("\r\nXbox 360 Init Failed, error code: "), 0x80);
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+/* Performs a cleanup after failed Init() attempt */
+uint8_t XBOXUSB::Release() {
+ Xbox360Connected = false;
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+ bAddress = 0;
+ bPollEnable = false;
+ return 0;
+}
+
+uint8_t XBOXUSB::Poll() {
+ if(!bPollEnable)
+ return 0;
+ uint16_t BUFFER_SIZE = EP_MAXPKTSIZE;
+ pUsb->inTransfer(bAddress, epInfo[ XBOX_INPUT_PIPE ].epAddr, &BUFFER_SIZE, readBuf); // input on endpoint 1
+ readReport();
+#ifdef PRINTREPORT
+ printReport(); // Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller
+#endif
+ return 0;
+}
+
+void XBOXUSB::readReport() {
+ if(readBuf == NULL)
+ return;
+ if(readBuf[0] != 0x00 || readBuf[1] != 0x14) { // Check if it's the correct report - the controller also sends different status reports
+ return;
+ }
+
+ ButtonState = (uint32_t)(readBuf[5] | ((uint16_t)readBuf[4] << 8) | ((uint32_t)readBuf[3] << 16) | ((uint32_t)readBuf[2] << 24));
+
+ hatValue[LeftHatX] = (int16_t)(((uint16_t)readBuf[7] << 8) | readBuf[6]);
+ hatValue[LeftHatY] = (int16_t)(((uint16_t)readBuf[9] << 8) | readBuf[8]);
+ hatValue[RightHatX] = (int16_t)(((uint16_t)readBuf[11] << 8) | readBuf[10]);
+ hatValue[RightHatY] = (int16_t)(((uint16_t)readBuf[13] << 8) | readBuf[12]);
+
+ //Notify(PSTR("\r\nButtonState"), 0x80);
+ //PrintHex<uint32_t>(ButtonState, 0x80);
+
+ if(ButtonState != OldButtonState) {
+ ButtonClickState = (ButtonState >> 16) & ((~OldButtonState) >> 16); // Update click state variable, but don't include the two trigger buttons L2 and R2
+ if(((uint8_t)OldButtonState) == 0 && ((uint8_t)ButtonState) != 0) // The L2 and R2 buttons are special as they are analog buttons
+ R2Clicked = true;
+ if((uint8_t)(OldButtonState >> 8) == 0 && (uint8_t)(ButtonState >> 8) != 0)
+ L2Clicked = true;
+ OldButtonState = ButtonState;
+ }
+}
+
+void XBOXUSB::printReport() { //Uncomment "#define PRINTREPORT" to print the report send by the Xbox 360 Controller
+#ifdef PRINTREPORT
+ if(readBuf == NULL)
+ return;
+ for(uint8_t i = 0; i < XBOX_REPORT_BUFFER_SIZE; i++) {
+ D_PrintHex<uint8_t > (readBuf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+}
+
+uint8_t XBOXUSB::getButtonPress(ButtonEnum b) {
+ if(b == L2) // These are analog buttons
+ return (uint8_t)(ButtonState >> 8);
+ else if(b == R2)
+ return (uint8_t)ButtonState;
+ return (bool)(ButtonState & ((uint32_t)pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]) << 16));
+}
+
+bool XBOXUSB::getButtonClick(ButtonEnum b) {
+ if(b == L2) {
+ if(L2Clicked) {
+ L2Clicked = false;
+ return true;
+ }
+ return false;
+ } else if(b == R2) {
+ if(R2Clicked) {
+ R2Clicked = false;
+ return true;
+ }
+ return false;
+ }
+ uint16_t button = pgm_read_word(&XBOX_BUTTONS[(uint8_t)b]);
+ bool click = (ButtonClickState & button);
+ ButtonClickState &= ~button; // clear "click" event
+ return click;
+}
+
+int16_t XBOXUSB::getAnalogHat(AnalogHatEnum a) {
+ return hatValue[a];
+}
+
+/* Xbox Controller commands */
+void XBOXUSB::XboxCommand(uint8_t* data, uint16_t nbytes) {
+ //bmRequest = Host to device (0x00) | Class (0x20) | Interface (0x01) = 0x21, bRequest = Set Report (0x09), Report ID (0x00), Report Type (Output 0x02), interface (0x00), datalength, datalength, data)
+ pUsb->ctrlReq(bAddress, epInfo[XBOX_CONTROL_PIPE].epAddr, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, 0x00, 0x02, 0x00, nbytes, nbytes, data, NULL);
+}
+
+void XBOXUSB::setLedRaw(uint8_t value) {
+ writeBuf[0] = 0x01;
+ writeBuf[1] = 0x03;
+ writeBuf[2] = value;
+
+ XboxCommand(writeBuf, 3);
+}
+
+void XBOXUSB::setLedOn(LEDEnum led) {
+ if(led == OFF)
+ setLedRaw(0);
+ else if(led != ALL) // All LEDs can't be on a the same time
+ setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]) + 4);
+}
+
+void XBOXUSB::setLedBlink(LEDEnum led) {
+ setLedRaw(pgm_read_byte(&XBOX_LEDS[(uint8_t)led]));
+}
+
+void XBOXUSB::setLedMode(LEDModeEnum ledMode) { // This function is used to do some special LED stuff the controller supports
+ setLedRaw((uint8_t)ledMode);
+}
+
+void XBOXUSB::setRumbleOn(uint8_t lValue, uint8_t rValue) {
+ writeBuf[0] = 0x00;
+ writeBuf[1] = 0x08;
+ writeBuf[2] = 0x00;
+ writeBuf[3] = lValue; // big weight
+ writeBuf[4] = rValue; // small weight
+ writeBuf[5] = 0x00;
+ writeBuf[6] = 0x00;
+ writeBuf[7] = 0x00;
+
+ XboxCommand(writeBuf, 8);
+}
+
+void XBOXUSB::onInit() {
+ if(pFuncOnInit)
+ pFuncOnInit(); // Call the user function
+ else
+ setLedOn(LED1);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXUSB.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXUSB.h
new file mode 100644
index 000000000..1ab37851a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/XBOXUSB.h
@@ -0,0 +1,225 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _xboxusb_h_
+#define _xboxusb_h_
+
+#include "Usb.h"
+#include "hid.h"
+#include "xboxEnums.h"
+
+/* Data Xbox 360 taken from descriptors */
+#define EP_MAXPKTSIZE 32 // max size for data via USB
+
+/* Names we give to the 3 Xbox360 pipes */
+#define XBOX_CONTROL_PIPE 0
+#define XBOX_INPUT_PIPE 1
+#define XBOX_OUTPUT_PIPE 2
+
+// PID and VID of the different devices
+#define XBOX_VID 0x045E // Microsoft Corporation
+#define MADCATZ_VID 0x1BAD // For unofficial Mad Catz controllers
+#define JOYTECH_VID 0x162E // For unofficial Joytech controllers
+#define GAMESTOP_VID 0x0E6F // Gamestop controller
+
+#define XBOX_WIRED_PID 0x028E // Microsoft 360 Wired controller
+#define XBOX_WIRELESS_PID 0x028F // Wireless controller only support charging
+#define XBOX_WIRELESS_RECEIVER_PID 0x0719 // Microsoft Wireless Gaming Receiver
+#define XBOX_WIRELESS_RECEIVER_THIRD_PARTY_PID 0x0291 // Third party Wireless Gaming Receiver
+#define MADCATZ_WIRED_PID 0xF016 // Mad Catz wired controller
+#define JOYTECH_WIRED_PID 0xBEEF // For Joytech wired controller
+#define GAMESTOP_WIRED_PID 0x0401 // Gamestop wired controller
+#define AFTERGLOW_WIRED_PID 0x0213 // Afterglow wired controller - it uses the same VID as a Gamestop controller
+
+#define XBOX_REPORT_BUFFER_SIZE 14 // Size of the input report buffer
+
+#define XBOX_MAX_ENDPOINTS 3
+
+/** This class implements support for a Xbox wired controller via USB. */
+class XBOXUSB : public USBDeviceConfig {
+public:
+ /**
+ * Constructor for the XBOXUSB class.
+ * @param pUsb Pointer to USB class instance.
+ */
+ XBOXUSB(USB *pUsb);
+
+ /** @name USBDeviceConfig implementation */
+ /**
+ * Initialize the Xbox Controller.
+ * @param parent Hub number.
+ * @param port Port number on the hub.
+ * @param lowspeed Speed of the device.
+ * @return 0 on success.
+ */
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ /**
+ * Release the USB device.
+ * @return 0 on success.
+ */
+ uint8_t Release();
+ /**
+ * Poll the USB Input endpoins and run the state machines.
+ * @return 0 on success.
+ */
+ uint8_t Poll();
+
+ /**
+ * Get the device address.
+ * @return The device address.
+ */
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ /**
+ * Used to check if the controller has been initialized.
+ * @return True if it's ready.
+ */
+ virtual bool isReady() {
+ return bPollEnable;
+ };
+
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return ((vid == XBOX_VID || vid == MADCATZ_VID || vid == JOYTECH_VID || vid == GAMESTOP_VID) && (pid == XBOX_WIRED_PID || pid == MADCATZ_WIRED_PID || pid == GAMESTOP_WIRED_PID || pid == AFTERGLOW_WIRED_PID || pid == JOYTECH_WIRED_PID));
+ };
+ /**@}*/
+
+ /** @name Xbox Controller functions */
+ /**
+ * getButtonPress(ButtonEnum b) will return true as long as the button is held down.
+ *
+ * While getButtonClick(ButtonEnum b) will only return it once.
+ *
+ * So you instance if you need to increase a variable once you would use getButtonClick(ButtonEnum b),
+ * but if you need to drive a robot forward you would use getButtonPress(ButtonEnum b).
+ * @param b ::ButtonEnum to read.
+ * @return getButtonClick(ButtonEnum b) will return a bool, while getButtonPress(ButtonEnum b) will return a byte if reading ::L2 or ::R2.
+ */
+ uint8_t getButtonPress(ButtonEnum b);
+ bool getButtonClick(ButtonEnum b);
+ /**@}*/
+
+ /** @name Xbox Controller functions */
+ /**
+ * Return the analog value from the joysticks on the controller.
+ * @param a Either ::LeftHatX, ::LeftHatY, ::RightHatX or ::RightHatY.
+ * @return Returns a signed 16-bit integer.
+ */
+ int16_t getAnalogHat(AnalogHatEnum a);
+
+ /** Turn rumble off and all the LEDs on the controller. */
+ void setAllOff() {
+ setRumbleOn(0, 0);
+ setLedRaw(0);
+ };
+
+ /** Turn rumble off the controller. */
+ void setRumbleOff() {
+ setRumbleOn(0, 0);
+ };
+ /**
+ * Turn rumble on.
+ * @param lValue Left motor (big weight) inside the controller.
+ * @param rValue Right motor (small weight) inside the controller.
+ */
+ void setRumbleOn(uint8_t lValue, uint8_t rValue);
+ /**
+ * Set LED value. Without using the ::LEDEnum or ::LEDModeEnum.
+ * @param value See:
+ * setLedOff(), setLedOn(LEDEnum l),
+ * setLedBlink(LEDEnum l), and setLedMode(LEDModeEnum lm).
+ */
+ void setLedRaw(uint8_t value);
+
+ /** Turn all LEDs off the controller. */
+ void setLedOff() {
+ setLedRaw(0);
+ };
+ /**
+ * Turn on a LED by using ::LEDEnum.
+ * @param l ::OFF, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller.
+ */
+ void setLedOn(LEDEnum l);
+ /**
+ * Turn on a LED by using ::LEDEnum.
+ * @param l ::ALL, ::LED1, ::LED2, ::LED3 and ::LED4 is supported by the Xbox controller.
+ */
+ void setLedBlink(LEDEnum l);
+ /**
+ * Used to set special LED modes supported by the Xbox controller.
+ * @param lm See ::LEDModeEnum.
+ */
+ void setLedMode(LEDModeEnum lm);
+
+ /**
+ * Used to call your own function when the controller is successfully initialized.
+ * @param funcOnInit Function to call.
+ */
+ void attachOnInit(void (*funcOnInit)(void)) {
+ pFuncOnInit = funcOnInit;
+ };
+ /**@}*/
+
+ /** True if a Xbox 360 controller is connected. */
+ bool Xbox360Connected;
+
+protected:
+ /** Pointer to USB class instance. */
+ USB *pUsb;
+ /** Device address. */
+ uint8_t bAddress;
+ /** Endpoint info structure. */
+ EpInfo epInfo[XBOX_MAX_ENDPOINTS];
+
+private:
+ /**
+ * Called when the controller is successfully initialized.
+ * Use attachOnInit(void (*funcOnInit)(void)) to call your own function.
+ * This is useful for instance if you want to set the LEDs in a specific way.
+ */
+ void onInit();
+ void (*pFuncOnInit)(void); // Pointer to function called in onInit()
+
+ bool bPollEnable;
+
+ /* Variables to store the buttons */
+ uint32_t ButtonState;
+ uint32_t OldButtonState;
+ uint16_t ButtonClickState;
+ int16_t hatValue[4];
+ uint16_t controllerStatus;
+
+ bool L2Clicked; // These buttons are analog, so we use we use these bools to check if they where clicked or not
+ bool R2Clicked;
+
+ uint8_t readBuf[EP_MAXPKTSIZE]; // General purpose buffer for input data
+ uint8_t writeBuf[8]; // General purpose buffer for output data
+
+ void readReport(); // read incoming data
+ void printReport(); // print incoming date - Uncomment for debugging
+
+ /* Private commands */
+ void XboxCommand(uint8_t* data, uint16_t nbytes);
+};
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/address.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/address.h
new file mode 100644
index 000000000..c3e1b3141
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/address.h
@@ -0,0 +1,282 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#if !defined(_usb_h_) || defined(__ADDRESS_H__)
+#error "Never include address.h directly; include Usb.h instead"
+#else
+#define __ADDRESS_H__
+
+
+
+/* NAK powers. To save space in endpoint data structure, amount of retries before giving up and returning 0x4 is stored in */
+/* bmNakPower as a power of 2. The actual nak_limit is then calculated as nak_limit = ( 2^bmNakPower - 1) */
+#define USB_NAK_MAX_POWER 15 //NAK binary order maximum value
+#define USB_NAK_DEFAULT 14 //default 32K-1 NAKs before giving up
+#define USB_NAK_NOWAIT 1 //Single NAK stops transfer
+#define USB_NAK_NONAK 0 //Do not count NAKs, stop retrying after USB Timeout
+
+struct EpInfo {
+ uint8_t epAddr; // Endpoint address
+ uint8_t maxPktSize; // Maximum packet size
+
+ union {
+ uint8_t epAttribs;
+
+ struct {
+ uint8_t bmSndToggle : 1; // Send toggle, when zero bmSNDTOG0, bmSNDTOG1 otherwise
+ uint8_t bmRcvToggle : 1; // Send toggle, when zero bmRCVTOG0, bmRCVTOG1 otherwise
+ uint8_t bmNakPower : 6; // Binary order for NAK_LIMIT value
+ } __attribute__((packed));
+ };
+} __attribute__((packed));
+
+// 7 6 5 4 3 2 1 0
+// ---------------------------------
+// | | H | P | P | P | A | A | A |
+// ---------------------------------
+//
+// H - if 1 the address is a hub address
+// P - parent hub address
+// A - device address / port number in case of hub
+//
+
+struct UsbDeviceAddress {
+
+ union {
+
+ struct {
+ uint8_t bmAddress : 3; // device address/port number
+ uint8_t bmParent : 3; // parent hub address
+ uint8_t bmHub : 1; // hub flag
+ uint8_t bmReserved : 1; // reserved, must be zero
+ } __attribute__((packed));
+ uint8_t devAddress;
+ };
+} __attribute__((packed));
+
+#define bmUSB_DEV_ADDR_ADDRESS 0x07
+#define bmUSB_DEV_ADDR_PARENT 0x38
+#define bmUSB_DEV_ADDR_HUB 0x40
+
+struct UsbDevice {
+ EpInfo *epinfo; // endpoint info pointer
+ UsbDeviceAddress address;
+ uint8_t epcount; // number of endpoints
+ bool lowspeed; // indicates if a device is the low speed one
+ // uint8_t devclass; // device class
+} __attribute__((packed));
+
+class AddressPool {
+public:
+ virtual UsbDevice* GetUsbDevicePtr(uint8_t addr) = 0;
+ virtual uint8_t AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 0) = 0;
+ virtual void FreeAddress(uint8_t addr) = 0;
+};
+
+typedef void (*UsbDeviceHandleFunc)(UsbDevice *pdev);
+
+#define ADDR_ERROR_INVALID_INDEX 0xFF
+#define ADDR_ERROR_INVALID_ADDRESS 0xFF
+
+template <const uint8_t MAX_DEVICES_ALLOWED>
+class AddressPoolImpl : public AddressPool {
+ EpInfo dev0ep; //Endpoint data structure used during enumeration for uninitialized device
+
+ uint8_t hubCounter; // hub counter is kept
+ // in order to avoid hub address duplication
+
+ UsbDevice thePool[MAX_DEVICES_ALLOWED];
+
+ // Initializes address pool entry
+
+ void InitEntry(uint8_t index) {
+ thePool[index].address.devAddress = 0;
+ thePool[index].epcount = 1;
+ thePool[index].lowspeed = 0;
+ thePool[index].epinfo = &dev0ep;
+ };
+
+ // Returns thePool index for a given address
+
+ uint8_t FindAddressIndex(uint8_t address = 0) {
+ for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++) {
+ if(thePool[i].address.devAddress == address)
+ return i;
+ }
+ return 0;
+ };
+
+ // Returns thePool child index for a given parent
+
+ uint8_t FindChildIndex(UsbDeviceAddress addr, uint8_t start = 1) {
+ for(uint8_t i = (start < 1 || start >= MAX_DEVICES_ALLOWED) ? 1 : start; i < MAX_DEVICES_ALLOWED; i++) {
+ if(thePool[i].address.bmParent == addr.bmAddress)
+ return i;
+ }
+ return 0;
+ };
+
+ // Frees address entry specified by index parameter
+
+ void FreeAddressByIndex(uint8_t index) {
+ // Zero field is reserved and should not be affected
+ if(index == 0)
+ return;
+
+ UsbDeviceAddress uda = thePool[index].address;
+ // If a hub was switched off all port addresses should be freed
+ if(uda.bmHub == 1) {
+ for(uint8_t i = 1; (i = FindChildIndex(uda, i));)
+ FreeAddressByIndex(i);
+
+ // If the hub had the last allocated address, hubCounter should be decremented
+ if(hubCounter == uda.bmAddress)
+ hubCounter--;
+ }
+ InitEntry(index);
+ }
+
+ // Initializes the whole address pool at once
+
+ void InitAllAddresses() {
+ for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++)
+ InitEntry(i);
+
+ hubCounter = 0;
+ };
+
+public:
+
+ AddressPoolImpl() : hubCounter(0) {
+ // Zero address is reserved
+ InitEntry(0);
+
+ thePool[0].address.devAddress = 0;
+ thePool[0].epinfo = &dev0ep;
+ dev0ep.epAddr = 0;
+ dev0ep.maxPktSize = 8;
+ dev0ep.epAttribs = 0; //set DATA0/1 toggles to 0
+ dev0ep.bmNakPower = USB_NAK_MAX_POWER;
+
+ InitAllAddresses();
+ };
+
+ // Returns a pointer to a specified address entry
+
+ virtual UsbDevice* GetUsbDevicePtr(uint8_t addr) {
+ if(!addr)
+ return thePool;
+
+ uint8_t index = FindAddressIndex(addr);
+
+ return (!index) ? NULL : thePool + index;
+ };
+
+ // Performs an operation specified by pfunc for each addressed device
+
+ void ForEachUsbDevice(UsbDeviceHandleFunc pfunc) {
+ if(!pfunc)
+ return;
+
+ for(uint8_t i = 1; i < MAX_DEVICES_ALLOWED; i++)
+ if(thePool[i].address.devAddress)
+ pfunc(thePool + i);
+ };
+
+ // Allocates new address
+
+ virtual uint8_t AllocAddress(uint8_t parent, bool is_hub = false, uint8_t port = 0) {
+ /* if (parent != 0 && port == 0)
+ USB_HOST_SERIAL.println("PRT:0"); */
+ UsbDeviceAddress _parent;
+ _parent.devAddress = parent;
+ if(_parent.bmReserved || port > 7)
+ //if(parent > 127 || port > 7)
+ return 0;
+
+ if(is_hub && hubCounter == 7)
+ return 0;
+
+ // finds first empty address entry starting from one
+ uint8_t index = FindAddressIndex(0);
+
+ if(!index) // if empty entry is not found
+ return 0;
+
+ if(_parent.devAddress == 0) {
+ if(is_hub) {
+ thePool[index].address.devAddress = 0x41;
+ hubCounter++;
+ } else
+ thePool[index].address.devAddress = 1;
+
+ return thePool[index].address.devAddress;
+ }
+
+ UsbDeviceAddress addr;
+ addr.devAddress = 0; // Ensure all bits are zero
+ addr.bmParent = _parent.bmAddress;
+ if(is_hub) {
+ addr.bmHub = 1;
+ addr.bmAddress = ++hubCounter;
+ } else {
+ addr.bmHub = 0;
+ addr.bmAddress = port;
+ }
+ thePool[index].address = addr;
+ /*
+ USB_HOST_SERIAL.print("Addr:");
+ USB_HOST_SERIAL.print(addr.bmHub, HEX);
+ USB_HOST_SERIAL.print(".");
+ USB_HOST_SERIAL.print(addr.bmParent, HEX);
+ USB_HOST_SERIAL.print(".");
+ USB_HOST_SERIAL.println(addr.bmAddress, HEX);
+ */
+ return thePool[index].address.devAddress;
+ };
+
+ // Empties pool entry
+
+ virtual void FreeAddress(uint8_t addr) {
+ // if the root hub is disconnected all the addresses should be initialized
+ if(addr == 0x41) {
+ InitAllAddresses();
+ return;
+ }
+ uint8_t index = FindAddressIndex(addr);
+ FreeAddressByIndex(index);
+ };
+
+ // Returns number of hubs attached
+ // It can be rather helpfull to find out if there are hubs attached than getting the exact number of hubs.
+ //uint8_t GetNumHubs()
+ //{
+ // return hubCounter;
+ //};
+ //uint8_t GetNumDevices()
+ //{
+ // uint8_t counter = 0;
+
+ // for (uint8_t i=1; i<MAX_DEVICES_ALLOWED; i++)
+ // if (thePool[i].address != 0);
+ // counter ++;
+
+ // return counter;
+ //};
+};
+
+#endif // __ADDRESS_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/adk.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/adk.cpp
new file mode 100644
index 000000000..9e4e0c8d8
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/adk.cpp
@@ -0,0 +1,371 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+/* Google ADK interface */
+
+#include "adk.h"
+
+const uint8_t ADK::epDataInIndex = 1;
+const uint8_t ADK::epDataOutIndex = 2;
+
+ADK::ADK(USB *p, const char* manufacturer,
+ const char* model,
+ const char* description,
+ const char* version,
+ const char* uri,
+ const char* serial) :
+
+/* ADK ID Strings */
+manufacturer(manufacturer),
+model(model),
+description(description),
+version(version),
+uri(uri),
+serial(serial),
+pUsb(p), //pointer to USB class instance - mandatory
+bAddress(0), //device address - mandatory
+bConfNum(0), //configuration number
+bNumEP(1), //if config descriptor needs to be parsed
+ready(false) {
+ // initialize endpoint data structures
+ for(uint8_t i = 0; i < ADK_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }//for(uint8_t i=0; i<ADK_MAX_ENDPOINTS; i++...
+
+ // register in USB subsystem
+ if(pUsb) {
+ pUsb->RegisterDeviceClass(this); //set devConfig[] entry
+ }
+}
+
+uint8_t ADK::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
+ return Init(parent, port, lowspeed); // Just call Init. Yes, really!
+}
+
+/* Connection initialization of an Android phone */
+uint8_t ADK::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t buf[sizeof (USB_DEVICE_DESCRIPTOR)];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ uint8_t num_of_conf; // number of configurations
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+
+ // get memory address of USB device address pool
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+ USBTRACE("\r\nADK Init");
+
+ // check if address has already been assigned to an instance
+ if(bAddress) {
+ USBTRACE("\r\nAddress in use");
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+ }
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p) {
+ USBTRACE("\r\nAddress not found");
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ if(!p->epinfo) {
+ USBTRACE("epinfo is null\r\n");
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf);
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode) {
+ goto FailGetDevDescr;
+ }
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ // Extract Max Packet Size from device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ //USBTRACE2("setAddr:",rcode);
+ return rcode;
+ }//if (rcode...
+
+ //USBTRACE2("\r\nAddr:", bAddress);
+ // Spec says you should wait at least 200ms.
+ //delay(300);
+
+ p->lowspeed = false;
+
+ //get pointer to assigned address record
+ p = addrPool.GetUsbDevicePtr(bAddress);
+ if(!p) {
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ p->lowspeed = lowspeed;
+
+ // Assign epInfo to epinfo pointer - only EP0 is known
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+ if(rcode) {
+ goto FailSetDevTblEntry;
+ }
+
+ //check if ADK device is already in accessory mode; if yes, configure and exit
+ if(udd->idVendor == ADK_VID &&
+ (udd->idProduct == ADK_PID || udd->idProduct == ADB_PID)) {
+ USBTRACE("\r\nAcc.mode device detected");
+ /* go through configurations, find first bulk-IN, bulk-OUT EP, fill epInfo and quit */
+ num_of_conf = udd->bNumConfigurations;
+
+ //USBTRACE2("\r\nNC:",num_of_conf);
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ ConfigDescParser < 0, 0, 0, 0 > confDescrParser(this);
+ delay(1);
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
+#if defined(XOOM)
+ //added by Jaylen Scott Vanorden
+ if(rcode) {
+ USBTRACE2("\r\nGot 1st bad code for config: ", rcode);
+ // Try once more
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
+ }
+#endif
+ if(rcode) {
+ goto FailGetConfDescr;
+ }
+ if(bNumEP > 2) {
+ break;
+ }
+ } // for (uint8_t i=0; i<num_of_conf; i++...
+
+ if(bNumEP == 3) {
+ // Assign epInfo to epinfo pointer - this time all 3 endpoins
+ rcode = pUsb->setEpInfoEntry(bAddress, 3, epInfo);
+ if(rcode) {
+ goto FailSetDevTblEntry;
+ }
+ }
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, bConfNum);
+ if(rcode) {
+ goto FailSetConfDescr;
+ }
+ /* print endpoint structure */
+ /*
+ USBTRACE("\r\nEndpoint Structure:");
+ USBTRACE("\r\nEP0:");
+ USBTRACE2("\r\nAddr: ", epInfo[0].epAddr);
+ USBTRACE2("\r\nMax.pkt.size: ", epInfo[0].maxPktSize);
+ USBTRACE2("\r\nAttr: ", epInfo[0].epAttribs);
+ USBTRACE("\r\nEpout:");
+ USBTRACE2("\r\nAddr: ", epInfo[epDataOutIndex].epAddr);
+ USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataOutIndex].maxPktSize);
+ USBTRACE2("\r\nAttr: ", epInfo[epDataOutIndex].epAttribs);
+ USBTRACE("\r\nEpin:");
+ USBTRACE2("\r\nAddr: ", epInfo[epDataInIndex].epAddr);
+ USBTRACE2("\r\nMax.pkt.size: ", epInfo[epDataInIndex].maxPktSize);
+ USBTRACE2("\r\nAttr: ", epInfo[epDataInIndex].epAttribs);
+ */
+
+ USBTRACE("\r\nConfiguration successful");
+ ready = true;
+ return 0; //successful configuration
+ }//if( buf->idVendor == ADK_VID...
+
+ //probe device - get accessory protocol revision
+ {
+ uint16_t adkproto = -1;
+ delay(1);
+ rcode = getProto((uint8_t*) & adkproto);
+#if defined(XOOM)
+ //added by Jaylen Scott Vanorden
+ if(rcode) {
+ USBTRACE2("\r\nGot 1st bad code for proto: ", rcode);
+ // Try once more
+ rcode = getProto((uint8_t*) & adkproto);
+ }
+#endif
+ if(rcode) {
+ goto FailGetProto; //init fails
+ }
+ USBTRACE2("\r\nADK protocol rev. ", adkproto);
+ }
+
+ delay(100);
+
+ //sending ID strings
+ sendStr(ACCESSORY_STRING_MANUFACTURER, manufacturer);
+ delay(10);
+ sendStr(ACCESSORY_STRING_MODEL, model);
+ delay(10);
+ sendStr(ACCESSORY_STRING_DESCRIPTION, description);
+ delay(10);
+ sendStr(ACCESSORY_STRING_VERSION, version);
+ delay(10);
+ sendStr(ACCESSORY_STRING_URI, uri);
+ delay(10);
+ sendStr(ACCESSORY_STRING_SERIAL, serial);
+
+ delay(100);
+
+ //switch to accessory mode
+ //the Android phone will reset
+ rcode = switchAcc();
+ if(rcode) {
+ goto FailSwAcc; //init fails
+ }
+ rcode = USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET;
+ delay(100); // Give Android a chance to do its reset. This is a guess, and possibly could be lower.
+ goto SwAttempt; //switch to accessory mode attempted
+
+ /* diagnostic messages */
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr(rcode);
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry(rcode);
+ goto Fail;
+#endif
+
+FailGetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetConfDescr(rcode);
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr(rcode);
+ goto Fail;
+#endif
+
+FailGetProto:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("\r\ngetProto:");
+ goto Fail;
+#endif
+
+FailSwAcc:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("\r\nswAcc:");
+ goto Fail;
+#endif
+
+ //FailOnInit:
+ // USBTRACE("OnInit:");
+ // goto Fail;
+ //
+SwAttempt:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("\r\nAccessory mode switch attempt");
+Fail:
+#endif
+ //USBTRACE2("\r\nADK Init Failed, error code: ", rcode);
+ //NotifyFail(rcode);
+ Release();
+ return rcode;
+}
+
+/* Extracts bulk-IN and bulk-OUT endpoint information from config descriptor */
+void ADK::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) {
+ //ErrorMessage<uint8_t>(PSTR("Conf.Val"), conf);
+ //ErrorMessage<uint8_t>(PSTR("Iface Num"), iface);
+ //ErrorMessage<uint8_t>(PSTR("Alt.Set"), alt);
+
+ //added by Yuuichi Akagawa
+ if(bNumEP == 3) {
+ return;
+ }
+
+ bConfNum = conf;
+
+ if((pep->bmAttributes & 0x02) == 2) {
+ uint8_t index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
+ // Fill in the endpoint info structure
+ epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
+ epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
+
+ bNumEP++;
+
+ //PrintEndpointDescriptor(pep);
+ }
+}
+
+/* Performs a cleanup after failed Init() attempt */
+uint8_t ADK::Release() {
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+
+ bNumEP = 1; //must have to be reset to 1
+
+ bAddress = 0;
+ ready = false;
+ return 0;
+}
+
+uint8_t ADK::RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr) {
+ //USBTRACE2("\r\nAddr: ", bAddress );
+ //USBTRACE2("\r\nEP: ",epInfo[epDataInIndex].epAddr);
+ return pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr);
+}
+
+uint8_t ADK::SndData(uint16_t nbytes, uint8_t *dataptr) {
+ return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, nbytes, dataptr);
+}
+
+void ADK::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
+ Notify(PSTR("Endpoint descriptor:"), 0x80);
+ Notify(PSTR("\r\nLength:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
+ Notify(PSTR("\r\nType:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
+ Notify(PSTR("\r\nAddress:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
+ Notify(PSTR("\r\nAttributes:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
+ Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
+ D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
+ Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/adk.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/adk.h
new file mode 100644
index 000000000..4a2920b88
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/adk.h
@@ -0,0 +1,140 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+/* Google ADK interface support header */
+
+#if !defined(_ADK_H_)
+#define _ADK_H_
+
+#include "Usb.h"
+
+#define ADK_VID 0x18D1
+#define ADK_PID 0x2D00
+#define ADB_PID 0x2D01
+
+#define XOOM //enables repeating getProto() and getConf() attempts
+//necessary for slow devices such as Motorola XOOM
+//defined by default, can be commented out to save memory
+
+/* requests */
+
+#define ADK_GETPROTO 51 //check USB accessory protocol version
+#define ADK_SENDSTR 52 //send identifying string
+#define ADK_ACCSTART 53 //start device in accessory mode
+
+#define bmREQ_ADK_GET USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_VENDOR|USB_SETUP_RECIPIENT_DEVICE
+#define bmREQ_ADK_SEND USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_VENDOR|USB_SETUP_RECIPIENT_DEVICE
+
+#define ACCESSORY_STRING_MANUFACTURER 0
+#define ACCESSORY_STRING_MODEL 1
+#define ACCESSORY_STRING_DESCRIPTION 2
+#define ACCESSORY_STRING_VERSION 3
+#define ACCESSORY_STRING_URI 4
+#define ACCESSORY_STRING_SERIAL 5
+
+#define ADK_MAX_ENDPOINTS 3 //endpoint 0, bulk_IN, bulk_OUT
+
+class ADK;
+
+class ADK : public USBDeviceConfig, public UsbConfigXtracter {
+private:
+ /* ID strings */
+ const char* manufacturer;
+ const char* model;
+ const char* description;
+ const char* version;
+ const char* uri;
+ const char* serial;
+
+ /* ADK proprietary requests */
+ uint8_t getProto(uint8_t* adkproto);
+ uint8_t sendStr(uint8_t index, const char* str);
+ uint8_t switchAcc(void);
+
+protected:
+ static const uint8_t epDataInIndex; // DataIn endpoint index
+ static const uint8_t epDataOutIndex; // DataOUT endpoint index
+
+ /* mandatory members */
+ USB *pUsb;
+ uint8_t bAddress;
+ uint8_t bConfNum; // configuration number
+
+ uint8_t bNumEP; // total number of EP in the configuration
+ bool ready;
+
+ /* Endpoint data structure */
+ EpInfo epInfo[ADK_MAX_ENDPOINTS];
+
+ void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
+
+public:
+ ADK(USB *pUsb, const char* manufacturer,
+ const char* model,
+ const char* description,
+ const char* version,
+ const char* uri,
+ const char* serial);
+
+ // Methods for receiving and sending data
+ uint8_t RcvData(uint16_t *nbytesptr, uint8_t *dataptr);
+ uint8_t SndData(uint16_t nbytes, uint8_t *dataptr);
+
+
+ // USBDeviceConfig implementation
+ uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t Release();
+
+ virtual uint8_t Poll() {
+ return 0;
+ };
+
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ virtual bool isReady() {
+ return ready;
+ };
+
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return (vid == ADK_VID && (pid == ADK_PID || pid == ADB_PID));
+ };
+
+ //UsbConfigXtracter implementation
+ void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
+}; //class ADK : public USBDeviceConfig ...
+
+/* get ADK protocol version */
+
+/* returns 2 bytes in *adkproto */
+inline uint8_t ADK::getProto(uint8_t* adkproto) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_GET, ADK_GETPROTO, 0, 0, 0, 2, 2, adkproto, NULL));
+}
+
+/* send ADK string */
+inline uint8_t ADK::sendStr(uint8_t index, const char* str) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_SENDSTR, 0, 0, index, strlen(str) + 1, strlen(str) + 1, (uint8_t*)str, NULL));
+}
+
+/* switch to accessory mode */
+inline uint8_t ADK::switchAcc(void) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_ADK_SEND, ADK_ACCSTART, 0, 0, 0, 0, 0, NULL, NULL));
+}
+
+#endif // _ADK_H_
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/avrpins.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/avrpins.h
new file mode 100644
index 000000000..4e60e3a22
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/avrpins.h
@@ -0,0 +1,1130 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+/* derived from Konstantin Chizhov's AVR port templates */
+
+#if !defined(_usb_h_) || defined(_avrpins_h_)
+#error "Never include avrpins.h directly; include Usb.h instead"
+#else
+#define _avrpins_h_
+
+#if defined(__AVR__)
+
+// pointers are 16 bits on AVR
+#define pgm_read_pointer(p) pgm_read_word(p)
+
+// Support for these boards needs to be manually activated in settings.h or in a makefile
+#if !defined(BOARD_MEGA_ADK) && defined(__AVR_ATmega2560__) && (USE_UHS_MEGA_ADK || defined(ARDUINO_AVR_ADK))
+#define BOARD_MEGA_ADK
+#elif !defined(BOARD_BLACK_WIDDOW) && USE_UHS_BLACK_WIDDOW
+#define BOARD_BLACK_WIDDOW
+#endif
+
+#ifdef PORTA
+#define USE_PORTA
+#endif
+#ifdef PORTB
+#define USE_PORTB
+#endif
+#ifdef PORTC
+#define USE_PORTC
+#endif
+#ifdef PORTD
+#define USE_PORTD
+#endif
+#ifdef PORTE
+#define USE_PORTE
+#endif
+#ifdef PORTF
+#define USE_PORTF
+#endif
+#ifdef PORTG
+#define USE_PORTG
+#endif
+#ifdef PORTH
+#define USE_PORTH
+#endif
+#ifdef PORTJ
+#define USE_PORTJ
+#endif
+#ifdef PORTK
+#define USE_PORTK
+#endif
+#ifdef PORTL
+#define USE_PORTL
+#endif
+#ifdef PORTQ
+#define USE_PORTQ
+#endif
+#ifdef PORTR
+#define USE_PORTR
+#endif
+
+#ifdef TCCR0A
+#define USE_TCCR0A
+#endif
+#ifdef TCCR1A
+#define USE_TCCR1A
+#endif
+#ifdef TCCR2A
+#define USE_TCCR2A
+#endif
+
+//Port definitions for AtTiny, AtMega families.
+
+#define MAKE_PORT(portName, ddrName, pinName, className, ID) \
+ class className{\
+ public:\
+ typedef uint8_t DataT;\
+ public:\
+ static void Write(DataT value){portName = value;}\
+ static void ClearAndSet(DataT clearMask, DataT value){portName = (portName & ~clearMask) | value;}\
+ static DataT Read(){return portName;}\
+ static void DirWrite(DataT value){ddrName = value;}\
+ static DataT DirRead(){return ddrName;}\
+ static void Set(DataT value){portName |= value;}\
+ static void Clear(DataT value){portName &= ~value;}\
+ static void Toggle(DataT value){portName ^= value;}\
+ static void DirSet(DataT value){ddrName |= value;}\
+ static void DirClear(DataT value){ddrName &= ~value;}\
+ static void DirToggle(DataT value){ddrName ^= value;}\
+ static DataT PinRead(){return pinName;}\
+ enum{Id = ID};\
+ enum{Width=sizeof(DataT)*8};\
+ };
+
+// TCCR registers to set/clear Arduino PWM
+#define MAKE_TCCR(TccrName, className) \
+ class className{\
+ public:\
+ typedef uint8_t DataT;\
+ public:\
+ static void Write(DataT value){TccrName = value;}\
+ static void ClearAndSet(DataT clearMask, DataT value){TccrName = (TccrName & ~clearMask) | value;}\
+ static DataT Read(){return TccrName;}\
+ static void Set(DataT value){TccrName |= value;}\
+ static void Clear(DataT value){TccrName &= ~value;}\
+ static void Toggle(DataT value){TccrName ^= value;}\
+ enum{Width=sizeof(DataT)*8};\
+ };
+
+#ifdef USE_PORTA
+
+MAKE_PORT(PORTA, DDRA, PINA, Porta, 'A')
+#endif
+#ifdef USE_PORTB
+MAKE_PORT(PORTB, DDRB, PINB, Portb, 'B')
+#endif
+#ifdef USE_PORTC
+MAKE_PORT(PORTC, DDRC, PINC, Portc, 'C')
+#endif
+#ifdef USE_PORTD
+MAKE_PORT(PORTD, DDRD, PIND, Portd, 'D')
+#endif
+#ifdef USE_PORTE
+MAKE_PORT(PORTE, DDRE, PINE, Porte, 'E')
+#endif
+#ifdef USE_PORTF
+MAKE_PORT(PORTF, DDRF, PINF, Portf, 'F')
+#endif
+#ifdef USE_PORTG
+MAKE_PORT(PORTG, DDRG, PING, Portg, 'G')
+#endif
+#ifdef USE_PORTH
+MAKE_PORT(PORTH, DDRH, PINH, Porth, 'H')
+#endif
+#ifdef USE_PORTJ
+MAKE_PORT(PORTJ, DDRJ, PINJ, Portj, 'J')
+#endif
+#ifdef USE_PORTK
+MAKE_PORT(PORTK, DDRK, PINK, Portk, 'K')
+#endif
+#ifdef USE_PORTL
+MAKE_PORT(PORTL, DDRL, PINL, Portl, 'L')
+#endif
+#ifdef USE_PORTQ
+MAKE_PORT(PORTQ, DDRQ, PINQ, Portq, 'Q')
+#endif
+#ifdef USE_PORTR
+MAKE_PORT(PORTR, DDRR, PINR, Portr, 'R')
+#endif
+
+#ifdef USE_TCCR0A
+MAKE_TCCR(TCCR0A, Tccr0a)
+#endif
+#ifdef USE_TCCR1A
+MAKE_TCCR(TCCR1A, Tccr1a)
+#endif
+#ifdef USE_TCCR2A
+MAKE_TCCR(TCCR2A, Tccr2a)
+#endif
+
+// this class represents one pin in a IO port.
+// It is fully static.
+template<typename PORT, uint8_t PIN>
+class TPin {
+ // BOOST_STATIC_ASSERT(PIN < PORT::Width);
+public:
+ typedef PORT Port;
+
+ enum {
+ Number = PIN
+ };
+
+ static void Set() {
+ PORT::Set(1 << PIN);
+ }
+
+ static void Set(uint8_t val) {
+ if(val)
+ Set();
+ else Clear();
+ }
+
+ static void SetDir(uint8_t val) {
+ if(val)
+ SetDirWrite();
+ else SetDirRead();
+ }
+
+ static void Clear() {
+ PORT::Clear(1 << PIN);
+ }
+
+ static void Toggle() {
+ PORT::Toggle(1 << PIN);
+ }
+
+ static void SetDirRead() {
+ PORT::DirClear(1 << PIN);
+ }
+
+ static void SetDirWrite() {
+ PORT::DirSet(1 << PIN);
+ }
+
+ static uint8_t IsSet() {
+ return PORT::PinRead() & (uint8_t)(1 << PIN);
+ }
+
+ static void WaiteForSet() {
+ while(IsSet() == 0) {
+ }
+ }
+
+ static void WaiteForClear() {
+ while(IsSet()) {
+ }
+ }
+}; //class TPin...
+
+// this class represents one bit in TCCR port.
+// used to set/clear TCCRx bits
+// It is fully static.
+
+template<typename TCCR, uint8_t COM>
+class TCom {
+ // BOOST_STATIC_ASSERT(PIN < PORT::Width);
+public:
+ typedef TCCR Tccr;
+
+ enum {
+ Com = COM
+ };
+
+ static void Set() {
+ TCCR::Set(1 << COM);
+ }
+
+ static void Clear() {
+ TCCR::Clear(1 << COM);
+ }
+
+ static void Toggle() {
+ TCCR::Toggle(1 << COM);
+ }
+}; //class TCom...
+
+//Short pin definitions
+#ifdef USE_PORTA
+typedef TPin<Porta, 0 > Pa0;
+typedef TPin<Porta, 1 > Pa1;
+typedef TPin<Porta, 2 > Pa2;
+typedef TPin<Porta, 3 > Pa3;
+typedef TPin<Porta, 4 > Pa4;
+typedef TPin<Porta, 5 > Pa5;
+typedef TPin<Porta, 6 > Pa6;
+typedef TPin<Porta, 7 > Pa7;
+#endif
+
+#ifdef USE_PORTB
+typedef TPin<Portb, 0 > Pb0;
+typedef TPin<Portb, 1 > Pb1;
+typedef TPin<Portb, 2 > Pb2;
+typedef TPin<Portb, 3 > Pb3;
+typedef TPin<Portb, 4 > Pb4;
+typedef TPin<Portb, 5 > Pb5;
+typedef TPin<Portb, 6 > Pb6;
+typedef TPin<Portb, 7 > Pb7;
+#endif
+
+#ifdef USE_PORTC
+typedef TPin<Portc, 0 > Pc0;
+typedef TPin<Portc, 1 > Pc1;
+typedef TPin<Portc, 2 > Pc2;
+typedef TPin<Portc, 3 > Pc3;
+typedef TPin<Portc, 4 > Pc4;
+typedef TPin<Portc, 5 > Pc5;
+typedef TPin<Portc, 6 > Pc6;
+typedef TPin<Portc, 7 > Pc7;
+#endif
+
+#ifdef USE_PORTD
+typedef TPin<Portd, 0 > Pd0;
+typedef TPin<Portd, 1 > Pd1;
+typedef TPin<Portd, 2 > Pd2;
+typedef TPin<Portd, 3 > Pd3;
+typedef TPin<Portd, 4 > Pd4;
+typedef TPin<Portd, 5 > Pd5;
+typedef TPin<Portd, 6 > Pd6;
+typedef TPin<Portd, 7 > Pd7;
+#endif
+
+#ifdef USE_PORTE
+typedef TPin<Porte, 0 > Pe0;
+typedef TPin<Porte, 1 > Pe1;
+typedef TPin<Porte, 2 > Pe2;
+typedef TPin<Porte, 3 > Pe3;
+typedef TPin<Porte, 4 > Pe4;
+typedef TPin<Porte, 5 > Pe5;
+typedef TPin<Porte, 6 > Pe6;
+typedef TPin<Porte, 7 > Pe7;
+#endif
+
+#ifdef USE_PORTF
+typedef TPin<Portf, 0 > Pf0;
+typedef TPin<Portf, 1 > Pf1;
+typedef TPin<Portf, 2 > Pf2;
+typedef TPin<Portf, 3 > Pf3;
+typedef TPin<Portf, 4 > Pf4;
+typedef TPin<Portf, 5 > Pf5;
+typedef TPin<Portf, 6 > Pf6;
+typedef TPin<Portf, 7 > Pf7;
+#endif
+
+#ifdef USE_PORTG
+typedef TPin<Portg, 0 > Pg0;
+typedef TPin<Portg, 1 > Pg1;
+typedef TPin<Portg, 2 > Pg2;
+typedef TPin<Portg, 3 > Pg3;
+typedef TPin<Portg, 4 > Pg4;
+typedef TPin<Portg, 5 > Pg5;
+typedef TPin<Portg, 6 > Pg6;
+typedef TPin<Portg, 7 > Pg7;
+#endif
+
+#ifdef USE_PORTH
+typedef TPin<Porth, 0 > Ph0;
+typedef TPin<Porth, 1 > Ph1;
+typedef TPin<Porth, 2 > Ph2;
+typedef TPin<Porth, 3 > Ph3;
+typedef TPin<Porth, 4 > Ph4;
+typedef TPin<Porth, 5 > Ph5;
+typedef TPin<Porth, 6 > Ph6;
+typedef TPin<Porth, 7 > Ph7;
+#endif
+
+#ifdef USE_PORTJ
+typedef TPin<Portj, 0 > Pj0;
+typedef TPin<Portj, 1 > Pj1;
+typedef TPin<Portj, 2 > Pj2;
+typedef TPin<Portj, 3 > Pj3;
+typedef TPin<Portj, 4 > Pj4;
+typedef TPin<Portj, 5 > Pj5;
+typedef TPin<Portj, 6 > Pj6;
+typedef TPin<Portj, 7 > Pj7;
+#endif
+
+#ifdef USE_PORTK
+typedef TPin<Portk, 0 > Pk0;
+typedef TPin<Portk, 1 > Pk1;
+typedef TPin<Portk, 2 > Pk2;
+typedef TPin<Portk, 3 > Pk3;
+typedef TPin<Portk, 4 > Pk4;
+typedef TPin<Portk, 5 > Pk5;
+typedef TPin<Portk, 6 > Pk6;
+typedef TPin<Portk, 7 > Pk7;
+#endif
+
+#ifdef USE_PORTL
+typedef TPin<Portl, 0 > Pl0;
+typedef TPin<Portl, 1 > Pl1;
+typedef TPin<Portl, 2 > Pl2;
+typedef TPin<Portl, 3 > Pl3;
+typedef TPin<Portl, 4 > Pl4;
+typedef TPin<Portl, 5 > Pl5;
+typedef TPin<Portl, 6 > Pl6;
+typedef TPin<Portl, 7 > Pl7;
+#endif
+
+#ifdef USE_PORTQ
+typedef TPin<Portq, 0 > Pq0;
+typedef TPin<Portq, 1 > Pq1;
+typedef TPin<Portq, 2 > Pq2;
+typedef TPin<Portq, 3 > Pq3;
+typedef TPin<Portq, 4 > Pq4;
+typedef TPin<Portq, 5 > Pq5;
+typedef TPin<Portq, 6 > Pq6;
+typedef TPin<Portq, 7 > Pq7;
+#endif
+
+#ifdef USE_PORTR
+typedef TPin<Portr, 0 > Pr0;
+typedef TPin<Portr, 1 > Pr1;
+typedef TPin<Portr, 2 > Pr2;
+typedef TPin<Portr, 3 > Pr3;
+typedef TPin<Portr, 4 > Pr4;
+typedef TPin<Portr, 5 > Pr5;
+typedef TPin<Portr, 6 > Pr6;
+typedef TPin<Portr, 7 > Pr7;
+#endif
+
+#ifdef USE_TCCR0A
+typedef TCom<Tccr0a, COM0A1> Tc0a; //P6
+typedef TCom<Tccr0a, COM0B1> Tc0b; //P5
+#endif
+
+#ifdef USE_TCCR1A
+typedef TCom<Tccr1a, COM1A1> Tc1a; //P9
+typedef TCom<Tccr1a, COM1B1> Tc1b; //P10
+#endif
+
+#ifdef USE_TCCR2A
+typedef TCom<Tccr2a, COM2A1> Tc2a; //P11
+typedef TCom<Tccr2a, COM2B1> Tc2b; //P3
+#endif
+
+template<typename Tp_pin, typename Tc_bit>
+class Tp_Tc {
+public:
+
+ static void SetDir(uint8_t val) {
+ if(val)
+ SetDirWrite();
+ else SetDirRead();
+ }
+
+ static void SetDirRead() {
+ Tp_pin::SetDirRead(); //set pin direction
+ Tc_bit::Clear(); //disconnect pin from PWM
+ }
+
+ static void SetDirWrite() {
+ Tp_pin::SetDirWrite();
+ Tc_bit::Clear();
+ }
+};
+
+/* pin definitions for cases where it's necessary to clear compare output mode bits */
+
+//typedef Tp_Tc<Pd3, Tc2b> P3; //Arduino pin 3
+//typedef Tp_Tc<Pd5, Tc0b> P5; //Arduino pin 5
+//typedef Tp_Tc<Pd6, Tc0a> P6; //Arduino pin 6
+//typedef Tp_Tc<Pb1, Tc1a> P9; //Arduino pin 9
+//typedef Tp_Tc<Pb2, Tc1b> P10; //Arduino pin 10
+//typedef Tp_Tc<Pb3, Tc2a> P11; //Arduino pin 11
+
+/* Arduino pin definitions */
+#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+// "Mega" Arduino pin numbers
+
+#define P0 Pe0
+#define P1 Pe1
+#define P2 Pe4
+#define P3 Pe5
+#define P4 Pg5
+#define P5 Pe3
+#define P6 Ph3
+#define P7 Ph4
+
+#define P8 Ph5
+#define P9 Ph6
+#define P10 Pb4
+#define P11 Pb5
+#define P12 Pb6
+#define P13 Pb7
+
+#define P14 Pj1
+#define P15 Pj0
+#define P16 Ph1
+#define P17 Ph0
+#define P18 Pd3
+#define P19 Pd2
+#define P20 Pd1
+#define P21 Pd0
+
+#define P22 Pa0
+#define P23 Pa1
+#define P24 Pa2
+#define P25 Pa3
+#define P26 Pa4
+#define P27 Pa5
+#define P28 Pa6
+#define P29 Pa7
+#define P30 Pc7
+#define P31 Pc6
+#define P32 Pc5
+#define P33 Pc4
+#define P34 Pc3
+#define P35 Pc2
+#define P36 Pc1
+#define P37 Pc0
+
+#define P38 Pd7
+#define P39 Pg2
+#define P40 Pg1
+#define P41 Pg0
+#define P42 Pl7
+#define P43 Pl6
+#define P44 Pl5
+#define P45 Pl4
+#define P46 Pl3
+#define P47 Pl2
+#define P48 Pl1
+#define P49 Pl0
+#define P50 Pb3
+#define P51 Pb2
+#define P52 Pb1
+#define P53 Pb0
+
+#ifdef BOARD_MEGA_ADK // These pins are not broken out on the Arduino ADK
+#define P54 Pe6 // INT on Arduino ADK
+#define P55 Pj2 // MAX_RESET on Arduino ADK
+#endif
+
+// "Mega" pin numbers
+
+#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
+// "Classic" Arduino pin numbers
+
+#define P0 Pd0
+#define P1 Pd1
+#define P2 Pd2
+#define P3 Pd3
+#define P4 Pd4
+#define P5 Pd5
+#define P6 Pd6
+#define P7 Pd7
+
+#define P8 Pb0
+#define P9 Pb1
+#define P10 Pb2
+#define P11 Pb3
+#define P12 Pb4
+#define P13 Pb5
+
+#define P14 Pc0
+#define P15 Pc1
+#define P16 Pc2
+#define P17 Pc3
+#define P18 Pc4
+#define P19 Pc5
+
+// "Classic" Arduino pin numbers
+
+#elif defined(CORE_TEENSY) && defined(__AVR_ATmega32U4__)
+// Teensy 2.0 pin numbers
+// http://www.pjrc.com/teensy/pinout.html
+#define P0 Pb0
+#define P1 Pb1
+#define P2 Pb2
+#define P3 Pb3
+#define P4 Pb7
+#define P5 Pd0
+#define P6 Pd1
+#define P7 Pd2
+#define P8 Pd3
+#define P9 Pc6
+#define P10 Pc7
+#define P11 Pd6
+#define P12 Pd7
+#define P13 Pb4
+#define P14 Pb5
+#define P15 Pb6
+#define P16 Pf7
+#define P17 Pf6
+#define P18 Pf5
+#define P19 Pf4
+#define P20 Pf1
+#define P21 Pf0
+#define P22 Pd4
+#define P23 Pd5
+#define P24 Pe6
+// Teensy 2.0
+
+#elif defined(__AVR_ATmega32U4__)
+// Arduino Leonardo pin numbers
+
+#define P0 Pd2 // D0 - PD2
+#define P1 Pd3 // D1 - PD3
+#define P2 Pd1 // D2 - PD1
+#define P3 Pd0 // D3 - PD0
+#define P4 Pd4 // D4 - PD4
+#define P5 Pc6 // D5 - PC6
+#define P6 Pd7 // D6 - PD7
+#define P7 Pe6 // D7 - PE6
+
+#define P8 Pb4 // D8 - PB4
+#define P9 Pb5 // D9 - PB5
+#define P10 Pb6 // D10 - PB6
+#define P11 Pb7 // D11 - PB7
+#define P12 Pd6 // D12 - PD6
+#define P13 Pc7 // D13 - PC7
+
+#define P14 Pb3 // D14 - MISO - PB3
+#define P15 Pb1 // D15 - SCK - PB1
+#define P16 Pb2 // D16 - MOSI - PB2
+#define P17 Pb0 // D17 - SS - PB0
+
+#define P18 Pf7 // D18 - A0 - PF7
+#define P19 Pf6 // D19 - A1 - PF6
+#define P20 Pf5 // D20 - A2 - PF5
+#define P21 Pf4 // D21 - A3 - PF4
+#define P22 Pf1 // D22 - A4 - PF1
+#define P23 Pf0 // D23 - A5 - PF0
+
+#define P24 Pd4 // D24 / D4 - A6 - PD4
+#define P25 Pd7 // D25 / D6 - A7 - PD7
+#define P26 Pb4 // D26 / D8 - A8 - PB4
+#define P27 Pb5 // D27 / D9 - A9 - PB5
+#define P28 Pb6 // D28 / D10 - A10 - PB6
+#define P29 Pd6 // D29 / D12 - A11 - PD6
+
+// Arduino Leonardo pin numbers
+
+#elif defined(CORE_TEENSY) && (defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__))
+// Teensy++ 1.0 and 2.0 pin numbers
+// http://www.pjrc.com/teensy/pinout.html
+#define P0 Pd0
+#define P1 Pd1
+#define P2 Pd2
+#define P3 Pd3
+#define P4 Pd4
+#define P5 Pd5
+#define P6 Pd6
+#define P7 Pd7
+#define P8 Pe0
+#define P9 Pe1
+#define P10 Pc0
+#define P11 Pc1
+#define P12 Pc2
+#define P13 Pc3
+#define P14 Pc4
+#define P15 Pc5
+#define P16 Pc6
+#define P17 Pc7
+#define P18 Pe6
+#define P19 Pe7
+#define P20 Pb0
+#define P21 Pb1
+#define P22 Pb2
+#define P23 Pb3
+#define P24 Pb4
+#define P25 Pb5
+#define P26 Pb6
+#define P27 Pb7
+#define P28 Pa0
+#define P29 Pa1
+#define P30 Pa2
+#define P31 Pa3
+#define P32 Pa4
+#define P33 Pa5
+#define P34 Pa6
+#define P35 Pa7
+#define P36 Pe4
+#define P37 Pe5
+#define P38 Pf0
+#define P39 Pf1
+#define P40 Pf2
+#define P41 Pf3
+#define P42 Pf4
+#define P43 Pf5
+#define P44 Pf6
+#define P45 Pf7
+// Teensy++ 1.0 and 2.0
+
+#elif defined(ARDUINO_AVR_BALANDUINO) && (defined(__AVR_ATmega644__) || defined(__AVR_ATmega1284P__))
+// Balanduino pin numbers
+// http://balanduino.net/
+#define P0 Pd0 /* 0 - PD0 */
+#define P1 Pd1 /* 1 - PD1 */
+
+#if BALANDUINO_REVISION < 13
+ #define P2 Pb2 /* 2 - PB2 */
+ #define P3 Pd6 /* 3 - PD6 */
+ #define P4 Pd7 /* 4 - PD7 */
+ #define P5 Pb3 /* 5 - PB3 */
+#else
+ #define P2 Pd2 /* 2 - PD2 */
+ #define P3 Pd3 /* 3 - PD3 */
+ #define P4 Pd6 /* 4 - PD6 */
+ #define P5 Pd7 /* 5 - PD7 */
+#endif
+
+#define P6 Pb4 /* 6 - PB4 */
+#define P7 Pa0 /* 7 - PA0 */
+#define P8 Pa1 /* 8 - PA1 */
+#define P9 Pa2 /* 9 - PA2 */
+#define P10 Pa3 /* 10 - PA3 */
+#define P11 Pa4 /* 11 - PA4 */
+#define P12 Pa5 /* 12 - PA5 */
+#define P13 Pc1 /* 13 - PC1 */
+#define P14 Pc0 /* 14 - PC0 */
+
+#if BALANDUINO_REVISION < 13
+ #define P15 Pd2 /* 15 - PD2 */
+ #define P16 Pd3 /* 16 - PD3 */
+#else
+ #define P15 Pb2 /* 15 - PB2 */
+ #define P16 Pb3 /* 16 - PB2 */
+#endif
+
+#define P17 Pd4 /* 17 - PD4 */
+#define P18 Pd5 /* 18 - PD5 */
+#define P19 Pc2 /* 19 - PC2 */
+#define P20 Pc3 /* 20 - PC3 */
+#define P21 Pc4 /* 21 - PC4 */
+#define P22 Pc5 /* 22 - PC5 */
+#define P23 Pc6 /* 23 - PC6 */
+#define P24 Pc7 /* 24 - PC7 */
+#define P25 Pb0 /* 25 - PB0 */
+#define P26 Pb1 /* 26 - PB1 */
+#define P27 Pb5 /* 27 - PB5 */
+#define P28 Pb6 /* 28 - PB6 */
+#define P29 Pb7 /* 29 - PB7 */
+#define P30 Pa6 /* 30 - PA6 */
+#define P31 Pa7 /* 31 - PA7 */
+// Balanduino
+
+#elif defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__)
+// Sanguino pin numbers
+// Homepage: http://sanguino.cc/hardware
+// Hardware add-on: https://github.com/Lauszus/Sanguino
+#define P0 Pb0
+#define P1 Pb1
+#define P2 Pb2
+#define P3 Pb3
+#define P4 Pb4
+#define P5 Pb5
+#define P6 Pb6
+#define P7 Pb7
+#define P8 Pd0
+#define P9 Pd1
+#define P10 Pd2
+#define P11 Pd3
+#define P12 Pd4
+#define P13 Pd5
+#define P14 Pd6
+#define P15 Pd7
+#define P16 Pc0
+#define P17 Pc1
+#define P18 Pc2
+#define P19 Pc3
+#define P20 Pc4
+#define P21 Pc5
+#define P22 Pc6
+#define P23 Pc7
+#define P24 Pa0
+#define P25 Pa1
+#define P26 Pa2
+#define P27 Pa3
+#define P28 Pa4
+#define P29 Pa5
+#define P30 Pa6
+#define P31 Pa7
+// Sanguino
+
+#else
+#error "Please define board in avrpins.h"
+
+#endif // Arduino pin definitions
+
+#elif defined(__arm__)
+
+// pointers are 32 bits on ARM
+#define pgm_read_pointer(p) pgm_read_dword(p)
+
+#if defined(CORE_TEENSY) && (defined(__MK20DX128__) || defined(__MK20DX256__))
+
+#include "core_pins.h"
+#include "avr_emulation.h"
+
+#define GPIO_BITBAND_ADDR(reg, bit) (((uint32_t)&(reg) - 0x40000000) * 32 + (bit) * 4 + 0x42000000)
+#define GPIO_BITBAND_PTR(reg, bit) ((uint8_t *)GPIO_BITBAND_ADDR((reg), (bit)))
+
+#define MAKE_PIN(className, baseReg, pinNum, configReg) \
+class className { \
+public: \
+ static void Set() { \
+ *GPIO_BITBAND_PTR(baseReg, pinNum) = 1; \
+ } \
+ static void Clear() { \
+ *GPIO_BITBAND_PTR(baseReg, pinNum) = 0; \
+ } \
+ static void SetDirRead() { \
+ configReg = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1); \
+ *(GPIO_BITBAND_PTR(baseReg, pinNum) + 640) = 0; \
+ } \
+ static void SetDirWrite() { \
+ configReg = PORT_PCR_SRE | PORT_PCR_DSE | PORT_PCR_MUX(1); \
+ *(GPIO_BITBAND_PTR(baseReg, pinNum) + 640) = 1; \
+ } \
+ static uint8_t IsSet() { \
+ return *(GPIO_BITBAND_PTR(baseReg, pinNum) + 512); \
+ } \
+};
+
+MAKE_PIN(P0, CORE_PIN0_PORTREG, CORE_PIN0_BIT, CORE_PIN0_CONFIG);
+MAKE_PIN(P1, CORE_PIN1_PORTREG, CORE_PIN1_BIT, CORE_PIN1_CONFIG);
+MAKE_PIN(P2, CORE_PIN2_PORTREG, CORE_PIN2_BIT, CORE_PIN2_CONFIG);
+MAKE_PIN(P3, CORE_PIN3_PORTREG, CORE_PIN3_BIT, CORE_PIN3_CONFIG);
+MAKE_PIN(P4, CORE_PIN4_PORTREG, CORE_PIN4_BIT, CORE_PIN4_CONFIG);
+MAKE_PIN(P5, CORE_PIN5_PORTREG, CORE_PIN5_BIT, CORE_PIN5_CONFIG);
+MAKE_PIN(P6, CORE_PIN6_PORTREG, CORE_PIN6_BIT, CORE_PIN6_CONFIG);
+MAKE_PIN(P7, CORE_PIN7_PORTREG, CORE_PIN7_BIT, CORE_PIN7_CONFIG);
+MAKE_PIN(P8, CORE_PIN8_PORTREG, CORE_PIN8_BIT, CORE_PIN8_CONFIG);
+MAKE_PIN(P9, CORE_PIN9_PORTREG, CORE_PIN9_BIT, CORE_PIN9_CONFIG);
+MAKE_PIN(P10, CORE_PIN10_PORTREG, CORE_PIN10_BIT, CORE_PIN10_CONFIG);
+MAKE_PIN(P11, CORE_PIN11_PORTREG, CORE_PIN11_BIT, CORE_PIN11_CONFIG);
+MAKE_PIN(P12, CORE_PIN12_PORTREG, CORE_PIN12_BIT, CORE_PIN12_CONFIG);
+MAKE_PIN(P13, CORE_PIN13_PORTREG, CORE_PIN13_BIT, CORE_PIN13_CONFIG);
+MAKE_PIN(P14, CORE_PIN14_PORTREG, CORE_PIN14_BIT, CORE_PIN14_CONFIG);
+MAKE_PIN(P15, CORE_PIN15_PORTREG, CORE_PIN15_BIT, CORE_PIN15_CONFIG);
+MAKE_PIN(P16, CORE_PIN16_PORTREG, CORE_PIN16_BIT, CORE_PIN16_CONFIG);
+MAKE_PIN(P17, CORE_PIN17_PORTREG, CORE_PIN17_BIT, CORE_PIN17_CONFIG);
+MAKE_PIN(P18, CORE_PIN18_PORTREG, CORE_PIN18_BIT, CORE_PIN18_CONFIG);
+MAKE_PIN(P19, CORE_PIN19_PORTREG, CORE_PIN19_BIT, CORE_PIN19_CONFIG);
+MAKE_PIN(P20, CORE_PIN20_PORTREG, CORE_PIN20_BIT, CORE_PIN20_CONFIG);
+MAKE_PIN(P21, CORE_PIN21_PORTREG, CORE_PIN21_BIT, CORE_PIN21_CONFIG);
+MAKE_PIN(P22, CORE_PIN22_PORTREG, CORE_PIN22_BIT, CORE_PIN22_CONFIG);
+MAKE_PIN(P23, CORE_PIN23_PORTREG, CORE_PIN23_BIT, CORE_PIN23_CONFIG);
+MAKE_PIN(P24, CORE_PIN24_PORTREG, CORE_PIN24_BIT, CORE_PIN24_CONFIG);
+MAKE_PIN(P25, CORE_PIN25_PORTREG, CORE_PIN25_BIT, CORE_PIN25_CONFIG);
+MAKE_PIN(P26, CORE_PIN26_PORTREG, CORE_PIN26_BIT, CORE_PIN26_CONFIG);
+MAKE_PIN(P27, CORE_PIN27_PORTREG, CORE_PIN27_BIT, CORE_PIN27_CONFIG);
+MAKE_PIN(P28, CORE_PIN28_PORTREG, CORE_PIN28_BIT, CORE_PIN28_CONFIG);
+MAKE_PIN(P29, CORE_PIN29_PORTREG, CORE_PIN29_BIT, CORE_PIN29_CONFIG);
+MAKE_PIN(P30, CORE_PIN30_PORTREG, CORE_PIN30_BIT, CORE_PIN30_CONFIG);
+MAKE_PIN(P31, CORE_PIN31_PORTREG, CORE_PIN31_BIT, CORE_PIN31_CONFIG);
+MAKE_PIN(P32, CORE_PIN32_PORTREG, CORE_PIN32_BIT, CORE_PIN32_CONFIG);
+MAKE_PIN(P33, CORE_PIN33_PORTREG, CORE_PIN33_BIT, CORE_PIN33_CONFIG);
+
+#undef MAKE_PIN
+
+#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__)
+
+// SetDirRead:
+// Disable interrupts
+// Disable the pull up resistor
+// Set to INPUT
+// Enable PIO
+
+// SetDirWrite:
+// Disable interrupts
+// Disable the pull up resistor
+// Set to OUTPUT
+// Enable PIO
+
+#define MAKE_PIN(className, pio, pinMask) \
+class className { \
+public: \
+ static void Set() { \
+ pio->PIO_SODR = pinMask; \
+ } \
+ static void Clear() { \
+ pio->PIO_CODR = pinMask; \
+ } \
+ static void SetDirRead() { \
+ pio->PIO_IDR = pinMask ; \
+ pio->PIO_PUDR = pinMask; \
+ pio->PIO_ODR = pinMask; \
+ pio->PIO_PER = pinMask; \
+ } \
+ static void SetDirWrite() { \
+ pio->PIO_IDR = pinMask ; \
+ pio->PIO_PUDR = pinMask; \
+ pio->PIO_OER = pinMask; \
+ pio->PIO_PER = pinMask; \
+ } \
+ static uint8_t IsSet() { \
+ return pio->PIO_PDSR & pinMask; \
+ } \
+};
+
+// See: http://arduino.cc/en/Hacking/PinMappingSAM3X and variant.cpp
+
+MAKE_PIN(P0, PIOA, PIO_PA8);
+MAKE_PIN(P1, PIOA, PIO_PA9);
+MAKE_PIN(P2, PIOB, PIO_PB25);
+MAKE_PIN(P3, PIOC, PIO_PC28);
+MAKE_PIN(P4, PIOC, PIO_PC26);
+MAKE_PIN(P5, PIOC, PIO_PC25);
+MAKE_PIN(P6, PIOC, PIO_PC24);
+MAKE_PIN(P7, PIOC, PIO_PC23);
+MAKE_PIN(P8, PIOC, PIO_PC22);
+MAKE_PIN(P9, PIOC, PIO_PC21);
+MAKE_PIN(P10, PIOC, PIO_PC29);
+MAKE_PIN(P11, PIOD, PIO_PD7);
+MAKE_PIN(P12, PIOD, PIO_PD8);
+MAKE_PIN(P13, PIOB, PIO_PB27);
+MAKE_PIN(P14, PIOD, PIO_PD4);
+MAKE_PIN(P15, PIOD, PIO_PD5);
+MAKE_PIN(P16, PIOA, PIO_PA13);
+MAKE_PIN(P17, PIOA, PIO_PA12);
+MAKE_PIN(P18, PIOA, PIO_PA11);
+MAKE_PIN(P19, PIOA, PIO_PA10);
+MAKE_PIN(P20, PIOB, PIO_PB12);
+MAKE_PIN(P21, PIOB, PIO_PB13);
+MAKE_PIN(P22, PIOB, PIO_PB26);
+MAKE_PIN(P23, PIOA, PIO_PA14);
+MAKE_PIN(P24, PIOA, PIO_PA15);
+MAKE_PIN(P25, PIOD, PIO_PD0);
+MAKE_PIN(P26, PIOD, PIO_PD1);
+MAKE_PIN(P27, PIOD, PIO_PD2);
+MAKE_PIN(P28, PIOD, PIO_PD3);
+MAKE_PIN(P29, PIOD, PIO_PD6);
+MAKE_PIN(P30, PIOD, PIO_PD9);
+MAKE_PIN(P31, PIOA, PIO_PA7);
+MAKE_PIN(P32, PIOD, PIO_PD10);
+MAKE_PIN(P33, PIOC, PIO_PC1);
+MAKE_PIN(P34, PIOC, PIO_PC2);
+MAKE_PIN(P35, PIOC, PIO_PC3);
+MAKE_PIN(P36, PIOC, PIO_PC4);
+MAKE_PIN(P37, PIOC, PIO_PC5);
+MAKE_PIN(P38, PIOC, PIO_PC6);
+MAKE_PIN(P39, PIOC, PIO_PC7);
+MAKE_PIN(P40, PIOC, PIO_PC8);
+MAKE_PIN(P41, PIOC, PIO_PC9);
+MAKE_PIN(P42, PIOA, PIO_PA19);
+MAKE_PIN(P43, PIOA, PIO_PA20);
+MAKE_PIN(P44, PIOC, PIO_PC19);
+MAKE_PIN(P45, PIOC, PIO_PC18);
+MAKE_PIN(P46, PIOC, PIO_PC17);
+MAKE_PIN(P47, PIOC, PIO_PC16);
+MAKE_PIN(P48, PIOC, PIO_PC15);
+MAKE_PIN(P49, PIOC, PIO_PC14);
+MAKE_PIN(P50, PIOC, PIO_PC13);
+MAKE_PIN(P51, PIOC, PIO_PC12);
+MAKE_PIN(P52, PIOB, PIO_PB21);
+MAKE_PIN(P53, PIOB, PIO_PB14);
+MAKE_PIN(P54, PIOA, PIO_PA16);
+MAKE_PIN(P55, PIOA, PIO_PA24);
+MAKE_PIN(P56, PIOA, PIO_PA23);
+MAKE_PIN(P57, PIOA, PIO_PA22);
+MAKE_PIN(P58, PIOA, PIO_PA6);
+MAKE_PIN(P59, PIOA, PIO_PA4);
+MAKE_PIN(P60, PIOA, PIO_PA3);
+MAKE_PIN(P61, PIOA, PIO_PA2);
+MAKE_PIN(P62, PIOB, PIO_PB17);
+MAKE_PIN(P63, PIOB, PIO_PB18);
+MAKE_PIN(P64, PIOB, PIO_PB19);
+MAKE_PIN(P65, PIOB, PIO_PB20);
+MAKE_PIN(P66, PIOB, PIO_PB15);
+MAKE_PIN(P67, PIOB, PIO_PB16);
+MAKE_PIN(P68, PIOA, PIO_PA1);
+MAKE_PIN(P69, PIOA, PIO_PA0);
+MAKE_PIN(P70, PIOA, PIO_PA17);
+MAKE_PIN(P71, PIOA, PIO_PA18);
+MAKE_PIN(P72, PIOC, PIO_PC30);
+MAKE_PIN(P73, PIOA, PIO_PA21);
+MAKE_PIN(P74, PIOA, PIO_PA25); // MISO
+MAKE_PIN(P75, PIOA, PIO_PA26); // MOSI
+MAKE_PIN(P76, PIOA, PIO_PA27); // CLK
+MAKE_PIN(P77, PIOA, PIO_PA28);
+MAKE_PIN(P78, PIOB, PIO_PB23); // Unconnected
+
+#undef MAKE_PIN
+
+#elif defined(RBL_NRF51822)
+
+#define MAKE_PIN(className, pin) \
+class className { \
+public: \
+ static void Set() { \
+ nrf_gpio_pin_set(pin); \
+ } \
+ static void Clear() { \
+ nrf_gpio_pin_clear(pin); \
+ } \
+ static void SetDirRead() { \
+ nrf_gpio_cfg_input(pin, NRF_GPIO_PIN_NOPULL); \
+ } \
+ static void SetDirWrite() { \
+ nrf_gpio_cfg_output(pin); \
+ } \
+ static uint8_t IsSet() { \
+ return (uint8_t)nrf_gpio_pin_read(pin); \
+ } \
+};
+
+// See: pin_transform.c in RBL nRF51822 SDK
+MAKE_PIN(P0, Pin_nRF51822_to_Arduino(D0));
+MAKE_PIN(P1, Pin_nRF51822_to_Arduino(D1));
+MAKE_PIN(P2, Pin_nRF51822_to_Arduino(D2));
+MAKE_PIN(P3, Pin_nRF51822_to_Arduino(D3));
+MAKE_PIN(P4, Pin_nRF51822_to_Arduino(D4));
+MAKE_PIN(P5, Pin_nRF51822_to_Arduino(D5));
+MAKE_PIN(P6, Pin_nRF51822_to_Arduino(D6));
+MAKE_PIN(P7, Pin_nRF51822_to_Arduino(D7));
+MAKE_PIN(P8, Pin_nRF51822_to_Arduino(D8));
+MAKE_PIN(P9, Pin_nRF51822_to_Arduino(D9)); // INT
+MAKE_PIN(P10, Pin_nRF51822_to_Arduino(D10)); // SS
+MAKE_PIN(P11, Pin_nRF51822_to_Arduino(D11));
+MAKE_PIN(P12, Pin_nRF51822_to_Arduino(D12));
+MAKE_PIN(P13, Pin_nRF51822_to_Arduino(D13));
+MAKE_PIN(P14, Pin_nRF51822_to_Arduino(D14));
+MAKE_PIN(P15, Pin_nRF51822_to_Arduino(D15));
+MAKE_PIN(P17, Pin_nRF51822_to_Arduino(D17)); // MISO
+MAKE_PIN(P18, Pin_nRF51822_to_Arduino(D18)); // MOSI
+MAKE_PIN(P16, Pin_nRF51822_to_Arduino(D16)); // CLK
+MAKE_PIN(P19, Pin_nRF51822_to_Arduino(D19));
+MAKE_PIN(P20, Pin_nRF51822_to_Arduino(D20));
+MAKE_PIN(P21, Pin_nRF51822_to_Arduino(D21));
+MAKE_PIN(P22, Pin_nRF51822_to_Arduino(D22));
+MAKE_PIN(P23, Pin_nRF51822_to_Arduino(D23));
+MAKE_PIN(P24, Pin_nRF51822_to_Arduino(D24));
+
+#undef MAKE_PIN
+
+#else
+#error "Please define board in avrpins.h"
+
+#endif
+
+#elif defined(__ARDUINO_X86__) // Intel Galileo, Intel Galileo 2 and Intel Edison
+
+#include <avr/pgmspace.h>
+
+// Pointers are 32 bits on x86
+#define pgm_read_pointer(p) pgm_read_dword(p)
+
+#if PLATFORM_ID == 0xE1 // Edison platform id
+#define pinToFastPin(pin) 1 // As far as I can tell all pins can be used as fast pins
+#endif
+
+// Pin 2 and 3 on the Intel Galileo supports a higher rate,
+// so it is recommended to use one of these as the SS pin.
+
+#define MAKE_PIN(className, pin) \
+class className { \
+public: \
+ static void Set() { \
+ fastDigitalWrite(pin, HIGH); \
+ } \
+ static void Clear() { \
+ fastDigitalWrite(pin, LOW); \
+ } \
+ static void SetDirRead() { \
+ if (pinToFastPin(pin)) \
+ pinMode(pin, INPUT_FAST); \
+ else \
+ pinMode(pin, INPUT); \
+ } \
+ static void SetDirWrite() { \
+ if (pinToFastPin(pin)) \
+ pinMode(pin, OUTPUT_FAST); \
+ else \
+ pinMode(pin, OUTPUT); \
+ } \
+ static uint8_t IsSet() { \
+ return fastDigitalRead(pin); \
+ } \
+};
+
+MAKE_PIN(P0, 0);
+MAKE_PIN(P1, 1);
+MAKE_PIN(P2, 2);
+MAKE_PIN(P3, 3);
+MAKE_PIN(P4, 4);
+MAKE_PIN(P5, 5);
+MAKE_PIN(P6, 6);
+MAKE_PIN(P7, 7);
+MAKE_PIN(P8, 8);
+MAKE_PIN(P9, 9);
+MAKE_PIN(P10, 10);
+MAKE_PIN(P11, 11);
+MAKE_PIN(P12, 12);
+MAKE_PIN(P13, 13);
+MAKE_PIN(P14, 14); // A0
+MAKE_PIN(P15, 15); // A1
+MAKE_PIN(P16, 16); // A2
+MAKE_PIN(P17, 17); // A3
+MAKE_PIN(P18, 18); // A4
+MAKE_PIN(P19, 19); // A5
+
+#undef MAKE_PIN
+
+#elif defined(__MIPSEL__)
+// MIPSEL (MIPS architecture using a little endian byte order)
+
+// MIPS size_t = 4
+#define pgm_read_pointer(p) pgm_read_dword(p)
+
+#define MAKE_PIN(className, pin) \
+class className { \
+public: \
+ static void Set() { \
+ digitalWrite(pin, HIGH);\
+ } \
+ static void Clear() { \
+ digitalWrite(pin, LOW); \
+ } \
+ static void SetDirRead() { \
+ pinMode(pin, INPUT); \
+ } \
+ static void SetDirWrite() { \
+ pinMode(pin, OUTPUT); \
+ } \
+ static uint8_t IsSet() { \
+ return digitalRead(pin); \
+ } \
+};
+
+// 0 .. 13 - Digital pins
+MAKE_PIN(P0, 0); // RX
+MAKE_PIN(P1, 1); // TX
+MAKE_PIN(P2, 2); //
+MAKE_PIN(P3, 3); //
+MAKE_PIN(P4, 4); //
+MAKE_PIN(P5, 5); //
+MAKE_PIN(P6, 6); //
+MAKE_PIN(P7, 7); //
+MAKE_PIN(P8, 8); //
+MAKE_PIN(P9, 9); //
+MAKE_PIN(P10, 10); //
+MAKE_PIN(P11, 11); //
+MAKE_PIN(P12, 12); //
+MAKE_PIN(P13, 13); //
+
+#undef MAKE_PIN
+
+#else
+#error "Please define board in avrpins.h"
+
+#endif
+
+#endif //_avrpins_h_
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdc_XR21B1411.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdc_XR21B1411.cpp
new file mode 100644
index 000000000..74df8c3bd
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdc_XR21B1411.cpp
@@ -0,0 +1,211 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#include "cdc_XR21B1411.h"
+
+XR21B1411::XR21B1411(USB *p, CDCAsyncOper *pasync) :
+ACM(p, pasync) {
+ // Is this needed??
+ _enhanced_status = enhanced_features(); // Set up features
+}
+
+uint8_t XR21B1411::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+
+ uint8_t buf[constBufSize];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint8_t num_of_conf; // number of configurations
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+ USBTRACE("XR Init\r\n");
+
+ if(bAddress)
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p->epinfo) {
+ USBTRACE("epinfo\r\n");
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf);
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from the device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ USBTRACE2("setAddr:", rcode);
+ return rcode;
+ }
+
+ USBTRACE2("Addr:", bAddress);
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ num_of_conf = udd->bNumConfigurations;
+
+ if((((udd->idVendor != 0x2890U) || (udd->idProduct != 0x0201U)) && ((udd->idVendor != 0x04e2U) || (udd->idProduct != 0x1411U))))
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ USBTRACE2("NC:", num_of_conf);
+
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ ConfigDescParser< USB_CLASS_COM_AND_CDC_CTRL,
+ CDC_SUBCLASS_ACM,
+ CDC_PROTOCOL_ITU_T_V_250,
+ CP_MASK_COMPARE_CLASS |
+ CP_MASK_COMPARE_SUBCLASS |
+ CP_MASK_COMPARE_PROTOCOL > CdcControlParser(this);
+
+ ConfigDescParser<USB_CLASS_CDC_DATA, 0, 0,
+ CP_MASK_COMPARE_CLASS> CdcDataParser(this);
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcControlParser);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcDataParser);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ if(bNumEP > 1)
+ break;
+ } // for
+
+ if(bNumEP < 4)
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
+
+ USBTRACE2("Conf:", bConfNum);
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, bConfNum);
+
+ if(rcode)
+ goto FailSetConfDescr;
+
+ // Set up features status
+ _enhanced_status = enhanced_features();
+ half_duplex(false);
+ autoflowRTS(false);
+ autoflowDSR(false);
+ autoflowXON(false);
+ wide(false); // Always false, because this is only available in custom mode.
+
+ rcode = pAsync->OnInit(this);
+
+ if(rcode)
+ goto FailOnInit;
+
+ USBTRACE("XR configured\r\n");
+
+ ready = true;
+
+ //bPollEnable = true;
+
+ //USBTRACE("Poll enabled\r\n");
+ return 0;
+
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailGetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetConfDescr();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+ goto Fail;
+#endif
+
+FailOnInit:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("OnInit:");
+#endif
+
+#ifdef DEBUG_USB_HOST
+Fail:
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdc_XR21B1411.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdc_XR21B1411.h
new file mode 100644
index 000000000..c32627544
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdc_XR21B1411.h
@@ -0,0 +1,272 @@
+/* Copyright (C) 2015 Andrew J. Kroll
+ and
+ Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__CDC_XR21B1411_H__)
+#define __CDC_XR21B1411_H__
+
+#include "cdcacm.h"
+
+#define XR_REG_CUSTOM_DRIVER (0x020DU) // DRIVER SELECT
+#define XR_REG_CUSTOM_DRIVER_ACTIVE (0x0001U) // 0: CDC 1: CUSTOM
+
+#define XR_REG_ACM_FLOW_CTL (0x0216U) // FLOW CONTROL REGISTER CDCACM MODE
+#define XR_REG_FLOW_CTL (0x0C06U) // FLOW CONTROL REGISTER CUSTOM MODE
+#define XR_REG_FLOW_CTL_HALF_DPLX (0x0008U) // 0:FULL DUPLEX 1:HALF DUPLEX
+#define XR_REG_FLOW_CTL_MODE_MASK (0x0007U) // MODE BITMASK
+#define XR_REG_FLOW_CTL_NONE (0x0000U) // NO FLOW CONTROL
+#define XR_REG_FLOW_CTL_HW (0x0001U) // HARDWARE FLOW CONTROL
+#define XR_REG_FLOW_CTL_SW (0x0002U) // SOFTWARE FLOW CONTROL
+#define XR_REG_FLOW_CTL_MMMRX (0x0003U) // MULTIDROP RX UPON ADDRESS MATCH
+#define XR_REG_FLOW_CTL_MMMRXTX (0x0004U) // MULTIDROP RX/TX UPON ADDRESS MATCH
+
+#define XR_REG_ACM_GPIO_MODE (0x0217U) // GPIO MODE REGISTER IN CDCACM MODE
+#define XR_REG_GPIO_MODE (0x0C0CU) // GPIO MODE REGISTER IN CUSTOM MODE
+#define XR_REG_GPIO_MODE_GPIO (0x0000U) // ALL GPIO PINS ACM PROGRAMMABLE
+#define XR_REG_GPIO_MODE_FC_RTSCTS (0x0001U) // AUTO RTSCTS HW FC (GPIO 4/5)
+#define XR_REG_GPIO_MODE_FC_DTRDSR (0x0002U) // AUTO DTRDSR HW FC (GPIO 2/3)
+#define XR_REG_GPIO_MODE_ATE (0x0003U) // AUTO TRANSCEIVER ENABLE DURING TX (GPIO 5)
+#define XR_REG_GPIO_MODE_ATE_ADDRESS (0x0004U) // AUTO TRANSCEIVER ENABLE ON ADDRESS MATCH (GPIO 5)
+
+#define XR_REG_ACM_GPIO_DIR (0x0218U) // GPIO DIRECTION REGISTER CDCACM MODE, 0:IN 1:OUT
+#define XR_REG_GPIO_DIR (0x0C0DU) // GPIO DIRECTION REGISTER CUSTOM MODE, 0:IN 1:OUT
+
+#define XR_REG_ACM_GPIO_INT (0x0219U) // GPIO PIN CHANGE INTERRUPT ENABLE CDCACM MODE, 0: ENABLED 1: DISABLED
+#define XR_REG_GPIO_INT (0x0C11U) // GPIO PIN CHANGE INTERRUPT ENABLE CUSTOM MODE, 0: ENABLED 1: DISABLED
+#define XR_REG_GPIO_MASK (0x001FU) // GPIO REGISTERS BITMASK
+
+#define XR_REG_UART_ENABLE (0x0C00U) // UART I/O ENABLE REGISTER
+#define XR_REG_UART_ENABLE_RX (0x0002U) // 0:DISABLED 1:ENABLED
+#define XR_REG_UART_ENABLE_TX (0x0001U) // 0:DISABLED 1:ENABLED
+
+#define XR_REG_ERROR_STATUS (0x0C09U) // ERROR STATUS REGISTER
+#define XR_REG_ERROR_STATUS_MASK (0x00F8U) // ERROR STATUS BITMASK
+#define XR_REG_ERROR_STATUS_ERROR (0x0078U) // ERROR STATUS ERROR BITMASK
+#define XR_REG_ERROR_STATUS_BREAK (0x0008U) // BREAK ERROR HAS BEEN DETECTED
+#define XR_REG_ERROR_STATUS_FRAME (0x0010U) // FRAMING ERROR HAS BEEN DETECTED
+#define XR_REG_ERROR_STATUS_PARITY (0x0020U) // PARITY ERROR HAS BEEN DETECTED
+#define XR_REG_ERROR_STATUS_OVERRUN (0x0040U) // RX OVERRUN ERROR HAS BEEN DETECTED
+#define XR_REG_ERROR_STATUS_BREAK_STATUS (0x0080U) // BREAK CONDITION IS CURRENTLY BEING DETECTED
+
+#define XR_REG_TX_BREAK (0x0C0AU) // TRANSMIT BREAK. 0X0001-0XFFE TIME IN MS, 0X0000 STOP, 0X0FFF BREAK ON
+
+#define XR_REG_XCVR_EN_DELAY (0x0C0BU) // TURN-ARROUND DELAY IN BIT-TIMES 0X0000-0X000F
+
+#define XR_REG_GPIO_SET (0x0C0EU) // 1:SET GPIO PIN
+
+#define XR_REG_GPIO_CLR (0x0C0FU) // 1:CLEAR GPIO PIN
+
+#define XR_REG_GPIO_STATUS (0x0C10U) // READ GPIO PINS
+
+#define XR_REG_CUSTOMISED_INT (0x0C12U) // 0:STANDARD 1:CUSTOM SEE DATA SHEET
+
+#define XR_REG_PIN_PULLUP_ENABLE (0x0C14U) // 0:DISABLE 1:ENABLE, BITS 0-5:GPIO, 6:RX 7:TX
+
+#define XR_REG_PIN_PULLDOWN_ENABLE (0x0C15U) // 0:DISABLE 1:ENABLE, BITS 0-5:GPIO, 6:RX 7:TX
+
+#define XR_REG_LOOPBACK (0x0C16U) // 0:DISABLE 1:ENABLE, SEE DATA SHEET
+
+#define XR_REG_RX_FIFO_LATENCY (0x0CC2U) // FIFO LATENCY REGISTER
+#define XR_REG_RX_FIFO_LATENCY_ENABLE (0x0001U) //
+
+#define XR_REG_WIDE_MODE (0x0D02U)
+#define XR_REG_WIDE_MODE_ENABLE (0x0001U)
+
+#define XR_REG_XON_CHAR (0x0C07U)
+#define XR_REG_XOFF_CHAR (0x0C08U)
+
+#define XR_REG_TX_FIFO_RESET (0x0C80U) // 1: RESET, SELF-CLEARING
+#define XR_REG_TX_FIFO_COUNT (0x0C81U) // READ-ONLY
+#define XR_REG_RX_FIFO_RESET (0x0CC0U) // 1: RESET, SELF-CLEARING
+#define XR_REG_RX_FIFO_COUNT (0x0CC1U) // READ-ONLY
+
+#define XR_WRITE_REQUEST_TYPE (0x40U)
+
+#define XR_READ_REQUEST_TYPE (0xC0U)
+
+#define XR_MAX_ENDPOINTS 4
+
+class XR21B1411 : public ACM {
+protected:
+
+public:
+ XR21B1411(USB *pusb, CDCAsyncOper *pasync);
+
+ /**
+ * Used by the USB core to check what this driver support.
+ * @param vid The device's VID.
+ * @param pid The device's PID.
+ * @return Returns true if the device's VID and PID matches this driver.
+ */
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return (((vid == 0x2890U) && (pid == 0x0201U)) || ((vid == 0x04e2U) && (pid == 0x1411U)));
+ };
+
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+
+ virtual tty_features enhanced_features(void) {
+ tty_features rv;
+ rv.enhanced = true;
+ rv.autoflow_RTS = true;
+ rv.autoflow_DSR = true;
+ rv.autoflow_XON = true;
+ rv.half_duplex = true;
+ rv.wide = true;
+ return rv;
+ };
+
+ uint8_t read_register(uint16_t reg, uint16_t *val) {
+ return (pUsb->ctrlReq(bAddress, 0, XR_READ_REQUEST_TYPE, 1, 0, 0, reg, 2, 2, (uint8_t *)val, NULL));
+ }
+
+ uint8_t write_register(uint16_t reg, uint16_t val) {
+ return (pUsb->ctrlReq(bAddress, 0, XR_WRITE_REQUEST_TYPE, 0, BGRAB0(val), BGRAB1(val), reg, 0, 0, NULL, NULL));
+ }
+
+
+ ////////////////////////////////////////////////////////////////////////
+ // The following methods set the CDC-ACM defaults.
+ ////////////////////////////////////////////////////////////////////////
+
+ virtual void autoflowRTS(bool s) {
+ uint16_t val;
+ uint8_t rval;
+ rval = read_register(XR_REG_ACM_FLOW_CTL, &val);
+ if(!rval) {
+ if(s) {
+ val &= XR_REG_FLOW_CTL_HALF_DPLX;
+ val |= XR_REG_FLOW_CTL_HW;
+ } else {
+ val &= XR_REG_FLOW_CTL_HALF_DPLX;
+ }
+ rval = write_register(XR_REG_ACM_FLOW_CTL, val);
+ if(!rval) {
+ rval = write_register(XR_REG_ACM_GPIO_MODE, XR_REG_GPIO_MODE_GPIO);
+ if(!rval) {
+ // ACM commands apply the new settings.
+ LINE_CODING LCT;
+ rval = GetLineCoding(&LCT);
+ if(!rval) {
+ rval = SetLineCoding(&LCT);
+ if(!rval) {
+ _enhanced_status.autoflow_XON = false;
+ _enhanced_status.autoflow_DSR = false;
+ _enhanced_status.autoflow_RTS = s;
+ }
+ }
+ }
+ }
+ }
+ };
+
+ virtual void autoflowDSR(bool s) {
+ uint16_t val;
+ uint8_t rval;
+ rval = read_register(XR_REG_ACM_FLOW_CTL, &val);
+ if(!rval) {
+ if(s) {
+ val &= XR_REG_FLOW_CTL_HALF_DPLX;
+ val |= XR_REG_FLOW_CTL_HW;
+ } else {
+ val &= XR_REG_FLOW_CTL_HALF_DPLX;
+ }
+ rval = write_register(XR_REG_ACM_FLOW_CTL, val);
+ if(!rval) {
+ if(s) {
+ rval = write_register(XR_REG_ACM_GPIO_MODE, XR_REG_GPIO_MODE_FC_DTRDSR);
+ } else {
+ rval = write_register(XR_REG_ACM_GPIO_MODE, XR_REG_GPIO_MODE_GPIO);
+ }
+ if(!rval) {
+ // ACM commands apply the new settings.
+ LINE_CODING LCT;
+ rval = GetLineCoding(&LCT);
+ if(!rval) {
+ rval = SetLineCoding(&LCT);
+ if(!rval) {
+ _enhanced_status.autoflow_XON = false;
+ _enhanced_status.autoflow_RTS = false;
+ _enhanced_status.autoflow_DSR = s;
+ }
+ }
+ }
+ }
+ }
+ };
+
+ virtual void autoflowXON(bool s) {
+ // NOTE: hardware defaults to the normal XON/XOFF
+ uint16_t val;
+ uint8_t rval;
+ rval = read_register(XR_REG_ACM_FLOW_CTL, &val);
+ if(!rval) {
+ if(s) {
+ val &= XR_REG_FLOW_CTL_HALF_DPLX;
+ val |= XR_REG_FLOW_CTL_SW;
+ } else {
+ val &= XR_REG_FLOW_CTL_HALF_DPLX;
+ }
+ rval = write_register(XR_REG_ACM_FLOW_CTL, val);
+ if(!rval) {
+ rval = write_register(XR_REG_ACM_GPIO_MODE, XR_REG_GPIO_MODE_GPIO);
+ if(!rval) {
+ // ACM commands apply the new settings.
+ LINE_CODING LCT;
+ rval = GetLineCoding(&LCT);
+ if(!rval) {
+ rval = SetLineCoding(&LCT);
+ if(!rval) {
+ _enhanced_status.autoflow_RTS = false;
+ _enhanced_status.autoflow_DSR = false;
+ _enhanced_status.autoflow_XON = s;
+ }
+ }
+ }
+ }
+ }
+ };
+
+ virtual void half_duplex(bool s) {
+ uint16_t val;
+ uint8_t rval;
+ rval = read_register(XR_REG_ACM_FLOW_CTL, &val);
+ if(!rval) {
+ if(s) {
+ val |= XR_REG_FLOW_CTL_HALF_DPLX;
+ } else {
+ val &= XR_REG_FLOW_CTL_MODE_MASK;
+ }
+ rval = write_register(XR_REG_ACM_FLOW_CTL, val);
+ if(!rval) {
+ // ACM commands apply the new settings.
+ LINE_CODING LCT;
+ rval = GetLineCoding(&LCT);
+ if(!rval) {
+ rval = SetLineCoding(&LCT);
+ if(!rval) {
+ _enhanced_status.half_duplex = s;
+ }
+ }
+ }
+ }
+ };
+
+
+
+};
+
+#endif // __CDCPROLIFIC_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcacm.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcacm.cpp
new file mode 100644
index 000000000..2cd2c9a82
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcacm.cpp
@@ -0,0 +1,331 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#include "cdcacm.h"
+
+const uint8_t ACM::epDataInIndex = 1;
+const uint8_t ACM::epDataOutIndex = 2;
+const uint8_t ACM::epInterruptInIndex = 3;
+
+ACM::ACM(USB *p, CDCAsyncOper *pasync) :
+pUsb(p),
+pAsync(pasync),
+bAddress(0),
+bControlIface(0),
+bDataIface(0),
+bNumEP(1),
+qNextPollTime(0),
+bPollEnable(false),
+ready(false) {
+ _enhanced_status = enhanced_features(); // Set up features
+ for(uint8_t i = 0; i < ACM_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i == epDataInIndex) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+
+ }
+ if(pUsb)
+ pUsb->RegisterDeviceClass(this);
+}
+
+uint8_t ACM::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+
+ uint8_t buf[constBufSize];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint8_t num_of_conf; // number of configurations
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+ USBTRACE("ACM Init\r\n");
+
+ if(bAddress)
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p->epinfo) {
+ USBTRACE("epinfo\r\n");
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf);
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from the device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ USBTRACE2("setAddr:", rcode);
+ return rcode;
+ }
+
+ USBTRACE2("Addr:", bAddress);
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ num_of_conf = udd->bNumConfigurations;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ USBTRACE2("NC:", num_of_conf);
+
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ ConfigDescParser< USB_CLASS_COM_AND_CDC_CTRL,
+ CDC_SUBCLASS_ACM,
+ CDC_PROTOCOL_ITU_T_V_250,
+ CP_MASK_COMPARE_CLASS |
+ CP_MASK_COMPARE_SUBCLASS |
+ CP_MASK_COMPARE_PROTOCOL > CdcControlParser(this);
+
+ ConfigDescParser<USB_CLASS_CDC_DATA, 0, 0,
+ CP_MASK_COMPARE_CLASS> CdcDataParser(this);
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcControlParser);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &CdcDataParser);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ if(bNumEP > 1)
+ break;
+ } // for
+
+ if(bNumEP < 4)
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
+
+ USBTRACE2("Conf:", bConfNum);
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, bConfNum);
+
+ if(rcode)
+ goto FailSetConfDescr;
+
+ // Set up features status
+ _enhanced_status = enhanced_features();
+ half_duplex(false);
+ autoflowRTS(false);
+ autoflowDSR(false);
+ autoflowXON(false);
+ wide(false); // Always false, because this is only available in custom mode.
+ rcode = pAsync->OnInit(this);
+
+ if(rcode)
+ goto FailOnInit;
+
+ USBTRACE("ACM configured\r\n");
+
+ ready = true;
+
+ //bPollEnable = true;
+
+ //USBTRACE("Poll enabled\r\n");
+ return 0;
+
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailGetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetConfDescr();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+ goto Fail;
+#endif
+
+FailOnInit:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("OnInit:");
+#endif
+
+#ifdef DEBUG_USB_HOST
+Fail:
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+void ACM::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) {
+ //ErrorMessage<uint8_t > (PSTR("Conf.Val"), conf);
+ //ErrorMessage<uint8_t > (PSTR("Iface Num"), iface);
+ //ErrorMessage<uint8_t > (PSTR("Alt.Set"), alt);
+
+ bConfNum = conf;
+
+ uint8_t index;
+
+ if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80)
+ index = epInterruptInIndex;
+ else
+ if((pep->bmAttributes & 0x02) == 2)
+ index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
+ else
+ return;
+
+ // Fill in the endpoint info structure
+ epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
+ epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
+ epInfo[index].epAttribs = 0;
+
+ bNumEP++;
+
+ PrintEndpointDescriptor(pep);
+}
+
+uint8_t ACM::Release() {
+ ready = false;
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+
+ bControlIface = 0;
+ bDataIface = 0;
+ bNumEP = 1;
+
+ bAddress = 0;
+ qNextPollTime = 0;
+ bPollEnable = false;
+ return 0;
+}
+
+uint8_t ACM::Poll() {
+ uint8_t rcode = 0;
+
+ if(!bPollEnable)
+ return 0;
+
+ return rcode;
+}
+
+uint8_t ACM::RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr) {
+ return pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr);
+}
+
+uint8_t ACM::SndData(uint16_t nbytes, uint8_t *dataptr) {
+ return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, nbytes, dataptr);
+}
+
+uint8_t ACM::SetCommFeature(uint16_t fid, uint8_t nbytes, uint8_t *dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_SET_COMM_FEATURE, (fid & 0xff), (fid >> 8), bControlIface, nbytes, nbytes, dataptr, NULL));
+}
+
+uint8_t ACM::GetCommFeature(uint16_t fid, uint8_t nbytes, uint8_t *dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCIN, CDC_GET_COMM_FEATURE, (fid & 0xff), (fid >> 8), bControlIface, nbytes, nbytes, dataptr, NULL));
+}
+
+uint8_t ACM::ClearCommFeature(uint16_t fid) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_CLEAR_COMM_FEATURE, (fid & 0xff), (fid >> 8), bControlIface, 0, 0, NULL, NULL));
+}
+
+uint8_t ACM::SetLineCoding(const LINE_CODING *dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_SET_LINE_CODING, 0x00, 0x00, bControlIface, sizeof (LINE_CODING), sizeof (LINE_CODING), (uint8_t*)dataptr, NULL));
+}
+
+uint8_t ACM::GetLineCoding(LINE_CODING *dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCIN, CDC_GET_LINE_CODING, 0x00, 0x00, bControlIface, sizeof (LINE_CODING), sizeof (LINE_CODING), (uint8_t*)dataptr, NULL));
+}
+
+uint8_t ACM::SetControlLineState(uint8_t state) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_SET_CONTROL_LINE_STATE, state, 0, bControlIface, 0, 0, NULL, NULL));
+}
+
+uint8_t ACM::SendBreak(uint16_t duration) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CDCOUT, CDC_SEND_BREAK, (duration & 0xff), (duration >> 8), bControlIface, 0, 0, NULL, NULL));
+}
+
+void ACM::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
+ Notify(PSTR("Endpoint descriptor:"), 0x80);
+ Notify(PSTR("\r\nLength:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
+ Notify(PSTR("\r\nType:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
+ Notify(PSTR("\r\nAddress:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
+ Notify(PSTR("\r\nAttributes:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
+ Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
+ D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
+ Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcacm.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcacm.h
new file mode 100644
index 000000000..2a38524d8
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcacm.h
@@ -0,0 +1,252 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__CDCACM_H__)
+#define __CDCACM_H__
+
+#include "Usb.h"
+
+#define bmREQ_CDCOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
+#define bmREQ_CDCIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
+
+// CDC Subclass Constants
+#define CDC_SUBCLASS_DLCM 0x01 // Direct Line Control Model
+#define CDC_SUBCLASS_ACM 0x02 // Abstract Control Model
+#define CDC_SUBCLASS_TCM 0x03 // Telephone Control Model
+#define CDC_SUBCLASS_MCCM 0x04 // Multi Channel Control Model
+#define CDC_SUBCLASS_CAPI 0x05 // CAPI Control Model
+#define CDC_SUBCLASS_ETHERNET 0x06 // Ethernet Network Control Model
+#define CDC_SUBCLASS_ATM 0x07 // ATM Network Control Model
+#define CDC_SUBCLASS_WIRELESS_HANDSET 0x08 // Wireless Handset Control Model
+#define CDC_SUBCLASS_DEVICE_MANAGEMENT 0x09 // Device Management
+#define CDC_SUBCLASS_MOBILE_DIRECT_LINE 0x0A // Mobile Direct Line Model
+#define CDC_SUBCLASS_OBEX 0x0B // OBEX
+#define CDC_SUBCLASS_ETHERNET_EMU 0x0C // Ethernet Emulation Model
+
+// Communication Interface Class Control Protocol Codes
+#define CDC_PROTOCOL_ITU_T_V_250 0x01 // AT Commands defined by ITU-T V.250
+#define CDC_PROTOCOL_PCCA_101 0x02 // AT Commands defined by PCCA-101
+#define CDC_PROTOCOL_PCCA_101_O 0x03 // AT Commands defined by PCCA-101 & Annex O
+#define CDC_PROTOCOL_GSM_7_07 0x04 // AT Commands defined by GSM 7.07
+#define CDC_PROTOCOL_3GPP_27_07 0x05 // AT Commands defined by 3GPP 27.007
+#define CDC_PROTOCOL_C_S0017_0 0x06 // AT Commands defined by TIA for CDMA
+#define CDC_PROTOCOL_USB_EEM 0x07 // Ethernet Emulation Model
+
+// CDC Commands defined by CDC 1.2
+#define CDC_SEND_ENCAPSULATED_COMMAND 0x00
+#define CDC_GET_ENCAPSULATED_RESPONSE 0x01
+
+// CDC Commands defined by PSTN 1.2
+#define CDC_SET_COMM_FEATURE 0x02
+#define CDC_GET_COMM_FEATURE 0x03
+#define CDC_CLEAR_COMM_FEATURE 0x04
+#define CDC_SET_AUX_LINE_STATE 0x10
+#define CDC_SET_HOOK_STATE 0x11
+#define CDC_PULSE_SETUP 0x12
+#define CDC_SEND_PULSE 0x13
+#define CDC_SET_PULSE_TIME 0x14
+#define CDC_RING_AUX_JACK 0x15
+#define CDC_SET_LINE_CODING 0x20
+#define CDC_GET_LINE_CODING 0x21
+#define CDC_SET_CONTROL_LINE_STATE 0x22
+#define CDC_SEND_BREAK 0x23
+#define CDC_SET_RINGER_PARMS 0x30
+#define CDC_GET_RINGER_PARMS 0x31
+#define CDC_SET_OPERATION_PARMS 0x32
+#define CDC_GET_OPERATION_PARMS 0x33
+#define CDC_SET_LINE_PARMS 0x34
+#define CDC_GET_LINE_PARMS 0x35
+#define CDC_DIAL_DIGITS 0x36
+
+//Class-Specific Notification Codes
+#define NETWORK_CONNECTION 0x00
+#define RESPONSE_AVAILABLE 0x01
+#define AUX_JACK_HOOK_STATE 0x08
+#define RING_DETECT 0x09
+#define SERIAL_STATE 0x20
+#define CALL_STATE_CHANGE 0x28
+#define LINE_STATE_CHANGE 0x29
+#define CONNECTION_SPEED_CHANGE 0x2a
+
+// CDC Functional Descriptor Structures
+
+typedef struct {
+ uint8_t bFunctionLength;
+ uint8_t bDescriptorType;
+ uint8_t bDescriptorSubtype;
+ uint8_t bmCapabilities;
+ uint8_t bDataInterface;
+} CALL_MGMNT_FUNC_DESCR;
+
+typedef struct {
+ uint8_t bFunctionLength;
+ uint8_t bDescriptorType;
+ uint8_t bDescriptorSubtype;
+ uint8_t bmCapabilities;
+} ACM_FUNC_DESCR, DLM_FUNC_DESCR, TEL_OPER_MODES_FUNC_DESCR,
+TEL_CALL_STATE_REP_CPBL_FUNC_DESCR;
+
+typedef struct {
+ uint8_t bFunctionLength;
+ uint8_t bDescriptorType;
+ uint8_t bDescriptorSubtype;
+ uint8_t bRingerVolSteps;
+ uint8_t bNumRingerPatterns;
+} TEL_RINGER_FUNC_DESCR;
+
+typedef struct {
+ uint32_t dwDTERate; // Data Terminal Rate in bits per second
+ uint8_t bCharFormat; // 0 - 1 stop bit, 1 - 1.5 stop bits, 2 - 2 stop bits
+ uint8_t bParityType; // 0 - None, 1 - Odd, 2 - Even, 3 - Mark, 4 - Space
+ uint8_t bDataBits; // Data bits (5, 6, 7, 8 or 16)
+} LINE_CODING;
+
+typedef struct {
+ uint8_t bmRequestType; // 0xa1 for class-specific notifications
+ uint8_t bNotification;
+ uint16_t wValue;
+ uint16_t wIndex;
+ uint16_t wLength;
+ uint16_t bmState; //UART state bitmap for SERIAL_STATE, other notifications variable length
+} CLASS_NOTIFICATION;
+
+class ACM;
+
+class CDCAsyncOper {
+public:
+
+ virtual uint8_t OnInit(ACM *pacm) {
+ return 0;
+ };
+ //virtual void OnDataRcvd(ACM *pacm, uint8_t nbytes, uint8_t *dataptr) = 0;
+ //virtual void OnDisconnected(ACM *pacm) = 0;
+};
+
+/**
+ * This structure is used to report the extended capabilities of the connected device.
+ * It is also used to report the current status.
+ * Regular CDC-ACM reports all as false.
+ */
+typedef struct {
+
+ union {
+ uint8_t tty;
+
+ struct {
+ bool enhanced : 1; // Do we have the ability to set/clear any features?
+ // Status and 8th bit in data stream.
+ // Presence only indicates feature is available, but this isn't used for CDC-ACM.
+ bool wide : 1;
+ bool autoflow_RTS : 1; // Has autoflow on RTS/CTS
+ bool autoflow_DSR : 1; // Has autoflow on DTR/DSR
+ bool autoflow_XON : 1; // Has autoflow XON/XOFF
+ bool half_duplex : 1; // Has half-duplex capability.
+ } __attribute__((packed));
+ };
+} tty_features;
+
+#define ACM_MAX_ENDPOINTS 4
+
+class ACM : public USBDeviceConfig, public UsbConfigXtracter {
+protected:
+ static const uint8_t epDataInIndex; // DataIn endpoint index
+ static const uint8_t epDataOutIndex; // DataOUT endpoint index
+ static const uint8_t epInterruptInIndex; // InterruptIN endpoint index
+
+ USB *pUsb;
+ CDCAsyncOper *pAsync;
+ uint8_t bAddress;
+ uint8_t bConfNum; // configuration number
+ uint8_t bControlIface; // Control interface value
+ uint8_t bDataIface; // Data interface value
+ uint8_t bNumEP; // total number of EP in the configuration
+ uint32_t qNextPollTime; // next poll time
+ volatile bool bPollEnable; // poll enable flag
+ volatile bool ready; //device ready indicator
+ tty_features _enhanced_status; // current status
+
+ EpInfo epInfo[ACM_MAX_ENDPOINTS];
+
+ void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
+
+public:
+ ACM(USB *pusb, CDCAsyncOper *pasync);
+
+ uint8_t SetCommFeature(uint16_t fid, uint8_t nbytes, uint8_t *dataptr);
+ uint8_t GetCommFeature(uint16_t fid, uint8_t nbytes, uint8_t *dataptr);
+ uint8_t ClearCommFeature(uint16_t fid);
+ uint8_t SetLineCoding(const LINE_CODING *dataptr);
+ uint8_t GetLineCoding(LINE_CODING *dataptr);
+ uint8_t SetControlLineState(uint8_t state);
+ uint8_t SendBreak(uint16_t duration);
+ uint8_t GetNotif(uint16_t *bytes_rcvd, uint8_t *dataptr);
+
+ // Methods for receiving and sending data
+ uint8_t RcvData(uint16_t *nbytesptr, uint8_t *dataptr);
+ uint8_t SndData(uint16_t nbytes, uint8_t *dataptr);
+
+ // USBDeviceConfig implementation
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t Release();
+ uint8_t Poll();
+
+ bool available(void) {
+ return false;
+ };
+
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ virtual bool isReady() {
+ return ready;
+ };
+
+ virtual tty_features enhanced_status(void) {
+ return _enhanced_status;
+ };
+
+ virtual tty_features enhanced_features(void) {
+ tty_features rv;
+ rv.enhanced = false;
+ rv.autoflow_RTS = false;
+ rv.autoflow_DSR = false;
+ rv.autoflow_XON = false;
+ rv.half_duplex = false;
+ rv.wide = false;
+ return rv;
+ };
+
+ virtual void autoflowRTS(bool s) {
+ };
+
+ virtual void autoflowDSR(bool s) {
+ };
+
+ virtual void autoflowXON(bool s) {
+ };
+
+ virtual void half_duplex(bool s) {
+ };
+
+ virtual void wide(bool s) {
+ };
+
+ // UsbConfigXtracter implementation
+ void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
+};
+
+#endif // __CDCACM_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcftdi.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcftdi.cpp
new file mode 100644
index 000000000..80d21d16e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcftdi.cpp
@@ -0,0 +1,334 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#include "cdcftdi.h"
+
+const uint8_t FTDI::epDataInIndex = 1;
+const uint8_t FTDI::epDataOutIndex = 2;
+const uint8_t FTDI::epInterruptInIndex = 3;
+
+FTDI::FTDI(USB *p, FTDIAsyncOper *pasync) :
+pAsync(pasync),
+pUsb(p),
+bAddress(0),
+bNumEP(1),
+wFTDIType(0) {
+ for(uint8_t i = 0; i < FTDI_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i==epDataInIndex) ? USB_NAK_NOWAIT: USB_NAK_MAX_POWER;
+ }
+ if(pUsb)
+ pUsb->RegisterDeviceClass(this);
+}
+
+uint8_t FTDI::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+
+ uint8_t buf[constBufSize];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+
+ uint8_t num_of_conf; // number of configurations
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+ USBTRACE("FTDI Init\r\n");
+
+ if(bAddress)
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p->epinfo) {
+ USBTRACE("epinfo\r\n");
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), buf);
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode)
+ goto FailGetDevDescr;
+ if(udd->idVendor != FTDI_VID || udd->idProduct != FTDI_PID)
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ // Save type of FTDI chip
+ wFTDIType = udd->bcdDevice;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from the device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ USBTRACE2("setAddr:", rcode);
+ return rcode;
+ }
+
+ USBTRACE2("Addr:", bAddress);
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ num_of_conf = udd->bNumConfigurations;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ USBTRACE2("NC:", num_of_conf);
+
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ HexDumper<USBReadParser, uint16_t, uint16_t> HexDump;
+ ConfigDescParser < 0xFF, 0xFF, 0xFF, CP_MASK_COMPARE_ALL> confDescrParser(this);
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ if(bNumEP > 1)
+ break;
+ } // for
+
+ if(bNumEP < 2)
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ USBTRACE2("NumEP:", bNumEP);
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
+
+ USBTRACE2("Conf:", bConfNum);
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, bConfNum);
+
+ if(rcode)
+ goto FailSetConfDescr;
+
+ rcode = pAsync->OnInit(this);
+
+ if(rcode)
+ goto FailOnInit;
+
+ USBTRACE("FTDI configured\r\n");
+
+ bPollEnable = true;
+ return 0;
+
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailGetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetConfDescr();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+ goto Fail;
+#endif
+
+FailOnInit:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("OnInit:");
+
+Fail:
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+void FTDI::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) {
+ ErrorMessage<uint8_t > (PSTR("Conf.Val"), conf);
+ ErrorMessage<uint8_t > (PSTR("Iface Num"), iface);
+ ErrorMessage<uint8_t > (PSTR("Alt.Set"), alt);
+
+ bConfNum = conf;
+
+ uint8_t index;
+
+ if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80)
+ index = epInterruptInIndex;
+ else
+ if((pep->bmAttributes & 0x02) == 2)
+ index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
+ else
+ return;
+
+ // Fill in the endpoint info structure
+ epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
+ epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
+ epInfo[index].epAttribs = 0;
+
+ bNumEP++;
+
+ PrintEndpointDescriptor(pep);
+}
+
+uint8_t FTDI::Release() {
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+
+ bAddress = 0;
+ bNumEP = 1;
+ qNextPollTime = 0;
+ bPollEnable = false;
+ return pAsync->OnRelease(this);
+}
+
+uint8_t FTDI::Poll() {
+ uint8_t rcode = 0;
+
+ //if (!bPollEnable)
+ // return 0;
+
+ //if (qNextPollTime <= millis())
+ //{
+ // USB_HOST_SERIAL.println(bAddress, HEX);
+
+ // qNextPollTime = millis() + 100;
+ //}
+ return rcode;
+}
+
+uint8_t FTDI::SetBaudRate(uint32_t baud) {
+ uint16_t baud_value, baud_index = 0;
+ uint32_t divisor3;
+
+ divisor3 = 48000000 / 2 / baud; // divisor shifted 3 bits to the left
+
+ if(wFTDIType == FT232AM) {
+ if((divisor3 & 0x7) == 7)
+ divisor3++; // round x.7/8 up to x+1
+
+ baud_value = divisor3 >> 3;
+ divisor3 &= 0x7;
+
+ if(divisor3 == 1) baud_value |= 0xc000;
+ else // 0.125
+ if(divisor3 >= 4) baud_value |= 0x4000;
+ else // 0.5
+ if(divisor3 != 0) baud_value |= 0x8000; // 0.25
+ if(baud_value == 1) baud_value = 0; /* special case for maximum baud rate */
+ } else {
+ static const unsigned char divfrac [8] = {0, 3, 2, 0, 1, 1, 2, 3};
+ static const unsigned char divindex[8] = {0, 0, 0, 1, 0, 1, 1, 1};
+
+ baud_value = divisor3 >> 3;
+ baud_value |= divfrac [divisor3 & 0x7] << 14;
+ baud_index = divindex[divisor3 & 0x7];
+
+ /* Deal with special cases for highest baud rates. */
+ if(baud_value == 1) baud_value = 0;
+ else // 1.0
+ if(baud_value == 0x4001) baud_value = 1; // 1.5
+ }
+ USBTRACE2("baud_value:", baud_value);
+ USBTRACE2("baud_index:", baud_index);
+ return pUsb->ctrlReq(bAddress, 0, bmREQ_FTDI_OUT, FTDI_SIO_SET_BAUD_RATE, baud_value & 0xff, baud_value >> 8, baud_index, 0, 0, NULL, NULL);
+}
+
+uint8_t FTDI::SetModemControl(uint16_t signal) {
+ return pUsb->ctrlReq(bAddress, 0, bmREQ_FTDI_OUT, FTDI_SIO_MODEM_CTRL, signal & 0xff, signal >> 8, 0, 0, 0, NULL, NULL);
+}
+
+uint8_t FTDI::SetFlowControl(uint8_t protocol, uint8_t xon, uint8_t xoff) {
+ return pUsb->ctrlReq(bAddress, 0, bmREQ_FTDI_OUT, FTDI_SIO_SET_FLOW_CTRL, xon, xoff, protocol << 8, 0, 0, NULL, NULL);
+}
+
+uint8_t FTDI::SetData(uint16_t databm) {
+ return pUsb->ctrlReq(bAddress, 0, bmREQ_FTDI_OUT, FTDI_SIO_SET_DATA, databm & 0xff, databm >> 8, 0, 0, 0, NULL, NULL);
+}
+
+uint8_t FTDI::RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr) {
+ return pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, bytes_rcvd, dataptr);
+}
+
+uint8_t FTDI::SndData(uint16_t nbytes, uint8_t *dataptr) {
+ return pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, nbytes, dataptr);
+}
+
+void FTDI::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
+ Notify(PSTR("Endpoint descriptor:"), 0x80);
+ Notify(PSTR("\r\nLength:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
+ Notify(PSTR("\r\nType:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
+ Notify(PSTR("\r\nAddress:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
+ Notify(PSTR("\r\nAttributes:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
+ Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
+ D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
+ Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcftdi.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcftdi.h
new file mode 100644
index 000000000..b73125262
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcftdi.h
@@ -0,0 +1,145 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__CDCFTDI_H__)
+#define __CDCFTDI_H__
+
+#include "Usb.h"
+
+#define bmREQ_FTDI_OUT 0x40
+#define bmREQ_FTDI_IN 0xc0
+
+//#define bmREQ_FTDI_OUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
+//#define bmREQ_FTDI_IN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
+
+#define FTDI_VID 0x0403 // FTDI VID
+#define FTDI_PID 0x6001 // FTDI PID
+
+#define FT232AM 0x0200
+#define FT232BM 0x0400
+#define FT2232 0x0500
+#define FT232R 0x0600
+
+// Commands
+#define FTDI_SIO_RESET 0 /* Reset the port */
+#define FTDI_SIO_MODEM_CTRL 1 /* Set the modem control register */
+#define FTDI_SIO_SET_FLOW_CTRL 2 /* Set flow control register */
+#define FTDI_SIO_SET_BAUD_RATE 3 /* Set baud rate */
+#define FTDI_SIO_SET_DATA 4 /* Set the data characteristics of the port */
+#define FTDI_SIO_GET_MODEM_STATUS 5 /* Retrieve current value of modem status register */
+#define FTDI_SIO_SET_EVENT_CHAR 6 /* Set the event character */
+#define FTDI_SIO_SET_ERROR_CHAR 7 /* Set the error character */
+
+#define FTDI_SIO_RESET_SIO 0
+#define FTDI_SIO_RESET_PURGE_RX 1
+#define FTDI_SIO_RESET_PURGE_TX 2
+
+#define FTDI_SIO_SET_DATA_PARITY_NONE (0x0 << 8 )
+#define FTDI_SIO_SET_DATA_PARITY_ODD (0x1 << 8 )
+#define FTDI_SIO_SET_DATA_PARITY_EVEN (0x2 << 8 )
+#define FTDI_SIO_SET_DATA_PARITY_MARK (0x3 << 8 )
+#define FTDI_SIO_SET_DATA_PARITY_SPACE (0x4 << 8 )
+#define FTDI_SIO_SET_DATA_STOP_BITS_1 (0x0 << 11)
+#define FTDI_SIO_SET_DATA_STOP_BITS_15 (0x1 << 11)
+#define FTDI_SIO_SET_DATA_STOP_BITS_2 (0x2 << 11)
+#define FTDI_SIO_SET_BREAK (0x1 << 14)
+
+#define FTDI_SIO_SET_DTR_MASK 0x1
+#define FTDI_SIO_SET_DTR_HIGH ( 1 | ( FTDI_SIO_SET_DTR_MASK << 8))
+#define FTDI_SIO_SET_DTR_LOW ( 0 | ( FTDI_SIO_SET_DTR_MASK << 8))
+#define FTDI_SIO_SET_RTS_MASK 0x2
+#define FTDI_SIO_SET_RTS_HIGH ( 2 | ( FTDI_SIO_SET_RTS_MASK << 8 ))
+#define FTDI_SIO_SET_RTS_LOW ( 0 | ( FTDI_SIO_SET_RTS_MASK << 8 ))
+
+#define FTDI_SIO_DISABLE_FLOW_CTRL 0x0
+#define FTDI_SIO_RTS_CTS_HS (0x1 << 8)
+#define FTDI_SIO_DTR_DSR_HS (0x2 << 8)
+#define FTDI_SIO_XON_XOFF_HS (0x4 << 8)
+
+#define FTDI_SIO_CTS_MASK 0x10
+#define FTDI_SIO_DSR_MASK 0x20
+#define FTDI_SIO_RI_MASK 0x40
+#define FTDI_SIO_RLSD_MASK 0x80
+
+class FTDI;
+
+class FTDIAsyncOper {
+public:
+
+ virtual uint8_t OnInit(FTDI *pftdi) {
+ return 0;
+ };
+
+ virtual uint8_t OnRelease(FTDI *pftdi) {
+ return 0;
+ };
+};
+
+
+// Only single port chips are currently supported by the library,
+// so only three endpoints are allocated.
+#define FTDI_MAX_ENDPOINTS 3
+
+class FTDI : public USBDeviceConfig, public UsbConfigXtracter {
+ static const uint8_t epDataInIndex; // DataIn endpoint index
+ static const uint8_t epDataOutIndex; // DataOUT endpoint index
+ static const uint8_t epInterruptInIndex; // InterruptIN endpoint index
+
+ FTDIAsyncOper *pAsync;
+ USB *pUsb;
+ uint8_t bAddress;
+ uint8_t bConfNum; // configuration number
+ uint8_t bNumIface; // number of interfaces in the configuration
+ uint8_t bNumEP; // total number of EP in the configuration
+ uint32_t qNextPollTime; // next poll time
+ bool bPollEnable; // poll enable flag
+ uint16_t wFTDIType; // Type of FTDI chip
+
+ EpInfo epInfo[FTDI_MAX_ENDPOINTS];
+
+ void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
+
+public:
+ FTDI(USB *pusb, FTDIAsyncOper *pasync);
+
+ uint8_t SetBaudRate(uint32_t baud);
+ uint8_t SetModemControl(uint16_t control);
+ uint8_t SetFlowControl(uint8_t protocol, uint8_t xon = 0x11, uint8_t xoff = 0x13);
+ uint8_t SetData(uint16_t databm);
+
+ // Methods for recieving and sending data
+ uint8_t RcvData(uint16_t *bytes_rcvd, uint8_t *dataptr);
+ uint8_t SndData(uint16_t nbytes, uint8_t *dataptr);
+
+ // USBDeviceConfig implementation
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t Release();
+ uint8_t Poll();
+
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ // UsbConfigXtracter implementation
+ void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
+
+ virtual bool VIDPIDOK(uint16_t vid, uint16_t pid) {
+ return (vid == FTDI_VID && pid == FTDI_PID);
+ }
+
+};
+
+#endif // __CDCFTDI_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcprolific.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcprolific.cpp
new file mode 100644
index 000000000..eceb1df9f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcprolific.cpp
@@ -0,0 +1,247 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#include "cdcprolific.h"
+
+PL2303::PL2303(USB *p, CDCAsyncOper *pasync) :
+ACM(p, pasync),
+wPLType(0) {
+}
+
+uint8_t PL2303::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+
+ uint8_t buf[constBufSize];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint8_t num_of_conf; // number of configurations
+#ifdef PL2303_COMPAT
+ enum pl2303_type pltype = unknown;
+#endif
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+ USBTRACE("PL Init\r\n");
+
+ if(bAddress)
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p->epinfo) {
+ USBTRACE("epinfo\r\n");
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*)buf);
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ if(udd->idVendor != PL_VID && CHECK_PID(udd->idProduct))
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ /* determine chip variant */
+#ifdef PL2303_COMPAT
+ if(udd->bDeviceClass == 0x02 )
+ pltype = type_0;
+ else if(udd->bMaxPacketSize0 == 0x40 )
+ pltype = rev_HX;
+ else if(udd->bDeviceClass == 0x00)
+ pltype = type_1;
+ else if(udd->bDeviceClass == 0xff)
+ pltype = type_1;
+#endif
+
+ // Save type of PL chip
+ wPLType = udd->bcdDevice;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from the device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ USBTRACE2("setAddr:", rcode);
+ return rcode;
+ }
+
+ USBTRACE2("Addr:", bAddress);
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ num_of_conf = udd->bNumConfigurations;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ USBTRACE2("NC:", num_of_conf);
+
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ HexDumper<USBReadParser, uint16_t, uint16_t> HexDump;
+ ConfigDescParser < 0xFF, 0, 0, CP_MASK_COMPARE_CLASS> confDescrParser(this);
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ if(bNumEP > 1)
+ break;
+ } // for
+
+ if(bNumEP < 2)
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
+
+ USBTRACE2("Conf:", bConfNum);
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, bConfNum);
+
+ if(rcode)
+ goto FailSetConfDescr;
+
+#ifdef PL2303_COMPAT
+ /* Shamanic dance - sending Prolific init data as-is */
+ vendorRead( 0x84, 0x84, 0, buf );
+ vendorWrite( 0x04, 0x04, 0 );
+ vendorRead( 0x84, 0x84, 0, buf );
+ vendorRead( 0x83, 0x83, 0, buf );
+ vendorRead( 0x84, 0x84, 0, buf );
+ vendorWrite( 0x04, 0x04, 1 );
+ vendorRead( 0x84, 0x84, 0, buf);
+ vendorRead( 0x83, 0x83, 0, buf);
+ vendorWrite( 0, 0, 1 );
+ vendorWrite( 1, 0, 0 );
+ if( pltype == rev_HX ) {
+ vendorWrite( 2, 0, 0x44 );
+ vendorWrite( 0x06, 0x06, 0 ); // From W7 init
+ }
+ else {
+ vendorWrite( 2, 0, 0x24 );
+ }
+ /* Shamanic dance end */
+#endif
+ /* Calling post-init callback */
+ rcode = pAsync->OnInit(this);
+
+ if(rcode)
+ goto FailOnInit;
+
+ USBTRACE("PL configured\r\n");
+
+ //bPollEnable = true;
+ ready = true;
+ return 0;
+
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailGetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetConfDescr();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+ goto Fail;
+#endif
+
+FailOnInit:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("OnInit:");
+#endif
+
+#ifdef DEBUG_USB_HOST
+Fail:
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+//uint8_t PL::Poll()
+//{
+// uint8_t rcode = 0;
+//
+// //if (!bPollEnable)
+// // return 0;
+//
+// //if (qNextPollTime <= millis())
+// //{
+// // USB_HOST_SERIAL.println(bAddress, HEX);
+//
+// // qNextPollTime = millis() + 100;
+// //}
+// return rcode;
+//}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcprolific.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcprolific.h
new file mode 100644
index 000000000..499146641
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/cdcprolific.h
@@ -0,0 +1,159 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__CDCPROLIFIC_H__)
+#define __CDCPROLIFIC_H__
+
+#include "cdcacm.h"
+
+//#define PL2303_COMPAT // Uncomment it if you have compatibility problems
+
+#define PL_VID 0x067B
+#define CHECK_PID(pid) ( pid != 0x2303 && pid != 0x0609 )
+
+//#define PL_PID 0x0609
+
+#define PROLIFIC_REV_H 0x0202
+#define PROLIFIC_REV_X 0x0300
+#define PROLIFIC_REV_HX_CHIP_D 0x0400
+#define PROLIFIC_REV_1 0x0001
+
+#define kXOnChar '\x11'
+#define kXOffChar '\x13'
+
+#define SPECIAL_SHIFT (5)
+#define SPECIAL_MASK ((1<<SPECIAL_SHIFT) - 1)
+#define STATE_ALL ( PD_RS232_S_MASK | PD_S_MASK )
+#define FLOW_RX_AUTO ( PD_RS232_A_RFR | PD_RS232_A_DTR | PD_RS232_A_RXO )
+#define FLOW_TX_AUTO ( PD_RS232_A_CTS | PD_RS232_A_DSR | PD_RS232_A_TXO | PD_RS232_A_DCD )
+#define CAN_BE_AUTO ( FLOW_RX_AUTO | FLOW_TX_AUTO )
+#define CAN_NOTIFY ( PD_RS232_N_MASK )
+#define EXTERNAL_MASK ( PD_S_MASK | (PD_RS232_S_MASK & ~PD_RS232_S_LOOP) )
+#define INTERNAL_DELAY ( PD_RS232_S_LOOP )
+#define DEFAULT_AUTO ( PD_RS232_A_DTR | PD_RS232_A_RFR | PD_RS232_A_CTS | PD_RS232_A_DSR )
+#define DEFAULT_NOTIFY 0x00
+#define DEFAULT_STATE ( PD_S_TX_ENABLE | PD_S_RX_ENABLE | PD_RS232_A_TXO | PD_RS232_A_RXO )
+
+#define CONTINUE_SEND 1
+#define PAUSE_SEND 2
+
+#define kRxAutoFlow ((UInt32)( PD_RS232_A_RFR | PD_RS232_A_DTR | PD_RS232_A_RXO ))
+#define kTxAutoFlow ((UInt32)( PD_RS232_A_CTS | PD_RS232_A_DSR | PD_RS232_A_TXO | PD_RS232_A_DCD ))
+#define kControl_StateMask ((UInt32)( PD_RS232_S_CTS | PD_RS232_S_DSR | PD_RS232_S_CAR | PD_RS232_S_RI ))
+#define kRxQueueState ((UInt32)( PD_S_RXQ_EMPTY | PD_S_RXQ_LOW_WATER | PD_S_RXQ_HIGH_WATER | PD_S_RXQ_FULL ))
+#define kTxQueueState ((UInt32)( PD_S_TXQ_EMPTY | PD_S_TXQ_LOW_WATER | PD_S_TXQ_HIGH_WATER | PD_S_TXQ_FULL ))
+
+#define kCONTROL_DTR 0x01
+#define kCONTROL_RTS 0x02
+
+#define kStateTransientMask 0x74
+#define kBreakError 0x04
+#define kFrameError 0x10
+#define kParityError 0x20
+#define kOverrunError 0x40
+
+#define kCTS 0x80
+#define kDSR 0x02
+#define kRI 0x08
+#define kDCD 0x01
+#define kHandshakeInMask ((UInt32)( PD_RS232_S_CTS | PD_RS232_S_DSR | PD_RS232_S_CAR | PD_RS232_S_RI ))
+
+#define VENDOR_WRITE_REQUEST_TYPE 0x40
+#define VENDOR_WRITE_REQUEST 0x01
+
+#define VENDOR_READ_REQUEST_TYPE 0xc0
+#define VENDOR_READ_REQUEST 0x01
+
+// Device Configuration Registers (DCR0, DCR1, DCR2)
+#define SET_DCR0 0x00
+#define GET_DCR0 0x80
+#define DCR0_INIT 0x01
+#define DCR0_INIT_H 0x41
+#define DCR0_INIT_X 0x61
+
+#define SET_DCR1 0x01
+#define GET_DCR1 0x81
+#define DCR1_INIT_H 0x80
+#define DCR1_INIT_X 0x00
+
+#define SET_DCR2 0x02
+#define GET_DCR2 0x82
+#define DCR2_INIT_H 0x24
+#define DCR2_INIT_X 0x44
+
+// On-chip Data Buffers:
+#define RESET_DOWNSTREAM_DATA_PIPE 0x08
+#define RESET_UPSTREAM_DATA_PIPE 0x09
+
+
+#define PL_MAX_ENDPOINTS 4
+
+enum tXO_State {
+ kXOnSent = -2,
+ kXOffSent = -1,
+ kXO_Idle = 0,
+ kXOffNeeded = 1,
+ kXOnNeeded = 2
+};
+
+enum pl2303_type {
+ unknown,
+ type_0, /* don't know the difference between type 0 and */
+ type_1, /* type 1, until someone from prolific tells us... */
+ rev_X,
+ rev_HX, /* HX version of the pl2303 chip */
+ rev_H
+};
+
+
+class PL2303 : public ACM {
+ uint16_t wPLType; // Type of chip
+
+public:
+ PL2303(USB *pusb, CDCAsyncOper *pasync);
+
+ // USBDeviceConfig implementation
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ //virtual uint8_t Release();
+ //virtual uint8_t Poll();
+ //virtual uint8_t GetAddress() { return bAddress; };
+
+ //// UsbConfigXtracter implementation
+ //virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
+
+#ifdef PL2303_COMPAT
+private:
+ /* Prolific proprietary requests */
+ uint8_t vendorRead( uint8_t val_lo, uint8_t val_hi, uint16_t index, uint8_t* buf );
+ uint8_t vendorWrite( uint8_t val_lo, uint8_t val_hi, uint8_t index );
+#endif
+};
+
+#ifdef PL2303_COMPAT
+/* vendor read request */
+inline uint8_t PL2303::vendorRead( uint8_t val_lo, uint8_t val_hi, uint16_t index, uint8_t* buf )
+{
+ return( pUsb->ctrlReq(bAddress, 0, VENDOR_READ_REQUEST_TYPE, VENDOR_READ_REQUEST, val_lo, val_hi, index, 1, 1, buf, NULL ));
+}
+
+/* vendor write request */
+inline uint8_t PL2303::vendorWrite( uint8_t val_lo, uint8_t val_hi, uint8_t index )
+{
+ return( pUsb->ctrlReq(bAddress, 0, VENDOR_WRITE_REQUEST_TYPE, VENDOR_WRITE_REQUEST, val_lo, val_hi, index, 0, 0, NULL, NULL ));
+}
+#endif
+
+#endif // __CDCPROLIFIC_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/confdescparser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/confdescparser.h
new file mode 100644
index 000000000..a6806f2ea
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/confdescparser.h
@@ -0,0 +1,213 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(_usb_h_) || defined(__CONFDESCPARSER_H__)
+#error "Never include confdescparser.h directly; include Usb.h instead"
+#else
+
+#define __CONFDESCPARSER_H__
+
+class UsbConfigXtracter {
+public:
+ //virtual void ConfigXtract(const USB_CONFIGURATION_DESCRIPTOR *conf) = 0;
+ //virtual void InterfaceXtract(uint8_t conf, const USB_INTERFACE_DESCRIPTOR *iface) = 0;
+
+ virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep) {
+ };
+};
+
+#define CP_MASK_COMPARE_CLASS 1
+#define CP_MASK_COMPARE_SUBCLASS 2
+#define CP_MASK_COMPARE_PROTOCOL 4
+#define CP_MASK_COMPARE_ALL 7
+
+// Configuration Descriptor Parser Class Template
+
+template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
+class ConfigDescParser : public USBReadParser {
+ UsbConfigXtracter *theXtractor;
+ MultiValueBuffer theBuffer;
+ MultiByteValueParser valParser;
+ ByteSkipper theSkipper;
+ uint8_t varBuffer[16 /*sizeof(USB_CONFIGURATION_DESCRIPTOR)*/];
+
+ uint8_t stateParseDescr; // ParseDescriptor state
+
+ uint8_t dscrLen; // Descriptor length
+ uint8_t dscrType; // Descriptor type
+
+ bool isGoodInterface; // Apropriate interface flag
+ uint8_t confValue; // Configuration value
+ uint8_t protoValue; // Protocol value
+ uint8_t ifaceNumber; // Interface number
+ uint8_t ifaceAltSet; // Interface alternate settings
+
+ bool UseOr;
+ bool ParseDescriptor(uint8_t **pp, uint16_t *pcntdn);
+ void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc);
+
+public:
+
+ void SetOR(void) {
+ UseOr = true;
+ }
+ ConfigDescParser(UsbConfigXtracter *xtractor);
+ void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset);
+};
+
+template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
+ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::ConfigDescParser(UsbConfigXtracter *xtractor) :
+theXtractor(xtractor),
+stateParseDescr(0),
+dscrLen(0),
+dscrType(0),
+UseOr(false) {
+ theBuffer.pValue = varBuffer;
+ valParser.Initialize(&theBuffer);
+ theSkipper.Initialize(&theBuffer);
+};
+
+template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
+void ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset) {
+ uint16_t cntdn = (uint16_t)len;
+ uint8_t *p = (uint8_t*)pbuf;
+
+ while(cntdn)
+ if(!ParseDescriptor(&p, &cntdn))
+ return;
+}
+
+/* Parser for the configuration descriptor. Takes values for class, subclass, protocol fields in interface descriptor and
+ compare masks for them. When the match is found, calls EndpointXtract passing buffer containing endpoint descriptor */
+template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
+bool ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::ParseDescriptor(uint8_t **pp, uint16_t *pcntdn) {
+ USB_CONFIGURATION_DESCRIPTOR* ucd = reinterpret_cast<USB_CONFIGURATION_DESCRIPTOR*>(varBuffer);
+ USB_INTERFACE_DESCRIPTOR* uid = reinterpret_cast<USB_INTERFACE_DESCRIPTOR*>(varBuffer);
+ switch(stateParseDescr) {
+ case 0:
+ theBuffer.valueSize = 2;
+ valParser.Initialize(&theBuffer);
+ stateParseDescr = 1;
+ case 1:
+ if(!valParser.Parse(pp, pcntdn))
+ return false;
+ dscrLen = *((uint8_t*)theBuffer.pValue);
+ dscrType = *((uint8_t*)theBuffer.pValue + 1);
+ stateParseDescr = 2;
+ case 2:
+ // This is a sort of hack. Assuming that two bytes are all ready in the buffer
+ // the pointer is positioned two bytes ahead in order for the rest of descriptor
+ // to be read right after the size and the type fields.
+ // This should be used carefully. varBuffer should be used directly to handle data
+ // in the buffer.
+ theBuffer.pValue = varBuffer + 2;
+ stateParseDescr = 3;
+ case 3:
+ switch(dscrType) {
+ case USB_DESCRIPTOR_INTERFACE:
+ isGoodInterface = false;
+ case USB_DESCRIPTOR_CONFIGURATION:
+ theBuffer.valueSize = sizeof (USB_CONFIGURATION_DESCRIPTOR) - 2;
+ break;
+ case USB_DESCRIPTOR_ENDPOINT:
+ theBuffer.valueSize = sizeof (USB_ENDPOINT_DESCRIPTOR) - 2;
+ break;
+ case HID_DESCRIPTOR_HID:
+ theBuffer.valueSize = dscrLen - 2;
+ break;
+ }
+ valParser.Initialize(&theBuffer);
+ stateParseDescr = 4;
+ case 4:
+ switch(dscrType) {
+ case USB_DESCRIPTOR_CONFIGURATION:
+ if(!valParser.Parse(pp, pcntdn))
+ return false;
+ confValue = ucd->bConfigurationValue;
+ break;
+ case USB_DESCRIPTOR_INTERFACE:
+ if(!valParser.Parse(pp, pcntdn))
+ return false;
+ if((MASK & CP_MASK_COMPARE_CLASS) && uid->bInterfaceClass != CLASS_ID)
+ break;
+ if((MASK & CP_MASK_COMPARE_SUBCLASS) && uid->bInterfaceSubClass != SUBCLASS_ID)
+ break;
+ if(UseOr) {
+ if((!((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol)))
+ break;
+ } else {
+ if((MASK & CP_MASK_COMPARE_PROTOCOL) && uid->bInterfaceProtocol != PROTOCOL_ID)
+ break;
+ }
+ isGoodInterface = true;
+ ifaceNumber = uid->bInterfaceNumber;
+ ifaceAltSet = uid->bAlternateSetting;
+ protoValue = uid->bInterfaceProtocol;
+ break;
+ case USB_DESCRIPTOR_ENDPOINT:
+ if(!valParser.Parse(pp, pcntdn))
+ return false;
+ if(isGoodInterface)
+ if(theXtractor)
+ theXtractor->EndpointXtract(confValue, ifaceNumber, ifaceAltSet, protoValue, (USB_ENDPOINT_DESCRIPTOR*)varBuffer);
+ break;
+ //case HID_DESCRIPTOR_HID:
+ // if (!valParser.Parse(pp, pcntdn))
+ // return false;
+ // PrintHidDescriptor((const USB_HID_DESCRIPTOR*)varBuffer);
+ // break;
+ default:
+ if(!theSkipper.Skip(pp, pcntdn, dscrLen - 2))
+ return false;
+ }
+ theBuffer.pValue = varBuffer;
+ stateParseDescr = 0;
+ }
+ return true;
+}
+
+template <const uint8_t CLASS_ID, const uint8_t SUBCLASS_ID, const uint8_t PROTOCOL_ID, const uint8_t MASK>
+void ConfigDescParser<CLASS_ID, SUBCLASS_ID, PROTOCOL_ID, MASK>::PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc) {
+ Notify(PSTR("\r\n\r\nHID Descriptor:\r\n"), 0x80);
+ Notify(PSTR("bDescLength:\t\t"), 0x80);
+ PrintHex<uint8_t > (pDesc->bLength, 0x80);
+
+ Notify(PSTR("\r\nbDescriptorType:\t"), 0x80);
+ PrintHex<uint8_t > (pDesc->bDescriptorType, 0x80);
+
+ Notify(PSTR("\r\nbcdHID:\t\t\t"), 0x80);
+ PrintHex<uint16_t > (pDesc->bcdHID, 0x80);
+
+ Notify(PSTR("\r\nbCountryCode:\t\t"), 0x80);
+ PrintHex<uint8_t > (pDesc->bCountryCode, 0x80);
+
+ Notify(PSTR("\r\nbNumDescriptors:\t"), 0x80);
+ PrintHex<uint8_t > (pDesc->bNumDescriptors, 0x80);
+
+ for(uint8_t i = 0; i < pDesc->bNumDescriptors; i++) {
+ HID_CLASS_DESCRIPTOR_LEN_AND_TYPE *pLT = (HID_CLASS_DESCRIPTOR_LEN_AND_TYPE*)&(pDesc->bDescrType);
+
+ Notify(PSTR("\r\nbDescrType:\t\t"), 0x80);
+ PrintHex<uint8_t > (pLT[i].bDescrType, 0x80);
+
+ Notify(PSTR("\r\nwDescriptorLength:\t"), 0x80);
+ PrintHex<uint16_t > (pLT[i].wDescriptorLength, 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+}
+
+
+#endif // __CONFDESCPARSER_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/controllerEnums.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/controllerEnums.h
new file mode 100644
index 000000000..0169c763c
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/controllerEnums.h
@@ -0,0 +1,204 @@
+/* Copyright (C) 2013 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _controllerenums_h
+#define _controllerenums_h
+
+/**
+ * This header file is used to store different enums for the controllers,
+ * This is necessary so all the different libraries can be used at once.
+ */
+
+/** Enum used to turn on the LEDs on the different controllers. */
+enum LEDEnum {
+ OFF = 0,
+ LED1 = 1,
+ LED2 = 2,
+ LED3 = 3,
+ LED4 = 4,
+
+ LED5 = 5,
+ LED6 = 6,
+ LED7 = 7,
+ LED8 = 8,
+ LED9 = 9,
+ LED10 = 10,
+ /** Used to blink all LEDs on the Xbox controller */
+ ALL = 5,
+};
+
+/** Used to set the colors of the Move and PS4 controller. */
+enum ColorsEnum {
+ /** r = 255, g = 0, b = 0 */
+ Red = 0xFF0000,
+ /** r = 0, g = 255, b = 0 */
+ Green = 0xFF00,
+ /** r = 0, g = 0, b = 255 */
+ Blue = 0xFF,
+
+ /** r = 255, g = 235, b = 4 */
+ Yellow = 0xFFEB04,
+ /** r = 0, g = 255, b = 255 */
+ Lightblue = 0xFFFF,
+ /** r = 255, g = 0, b = 255 */
+ Purble = 0xFF00FF,
+
+ /** r = 255, g = 255, b = 255 */
+ White = 0xFFFFFF,
+ /** r = 0, g = 0, b = 0 */
+ Off = 0x00,
+};
+
+enum RumbleEnum {
+ RumbleHigh = 0x10,
+ RumbleLow = 0x20,
+};
+
+/** This enum is used to read all the different buttons on the different controllers */
+enum ButtonEnum {
+ /**@{*/
+ /** These buttons are available on all the the controllers */
+ UP = 0,
+ RIGHT = 1,
+ DOWN = 2,
+ LEFT = 3,
+ /**@}*/
+
+ /**@{*/
+ /** Wii buttons */
+ PLUS = 5,
+ TWO = 6,
+ ONE = 7,
+ MINUS = 8,
+ HOME = 9,
+ Z = 10,
+ C = 11,
+ B = 12,
+ A = 13,
+ /**@}*/
+
+ /**@{*/
+ /** These are only available on the Wii U Pro Controller */
+ L = 16,
+ R = 17,
+ ZL = 18,
+ ZR = 19,
+ /**@}*/
+
+ /**@{*/
+ /** PS3 controllers buttons */
+ SELECT = 4,
+ START = 5,
+ L3 = 6,
+ R3 = 7,
+
+ L2 = 8,
+ R2 = 9,
+ L1 = 10,
+ R1 = 11,
+ TRIANGLE = 12,
+ CIRCLE = 13,
+ CROSS = 14,
+ SQUARE = 15,
+
+ PS = 16,
+
+ MOVE = 17, // Covers 12 bits - we only need to read the top 8
+ T = 18, // Covers 12 bits - we only need to read the top 8
+ /**@}*/
+
+ /** PS4 controllers buttons - SHARE and OPTIONS are present instead of SELECT and START */
+ SHARE = 4,
+ OPTIONS = 5,
+ TOUCHPAD = 17,
+ /**@}*/
+
+ /**@{*/
+ /** Xbox buttons */
+ BACK = 4,
+ X = 14,
+ Y = 15,
+ XBOX = 16,
+ SYNC = 17,
+ BLACK = 8, // Available on the original Xbox controller
+ WHITE = 9, // Available on the original Xbox controller
+ /**@}*/
+
+ /** PS Buzz controllers */
+ RED = 0,
+ YELLOW = 1,
+ GREEN = 2,
+ ORANGE = 3,
+ BLUE = 4,
+ /**@}*/
+};
+
+/** Joysticks on the PS3 and Xbox controllers. */
+enum AnalogHatEnum {
+ /** Left joystick x-axis */
+ LeftHatX = 0,
+ /** Left joystick y-axis */
+ LeftHatY = 1,
+ /** Right joystick x-axis */
+ RightHatX = 2,
+ /** Right joystick y-axis */
+ RightHatY = 3,
+};
+
+/**
+ * Sensors inside the Sixaxis Dualshock 3, Move controller and PS4 controller.
+ * <B>Note:</B> that the location is shifted 9 when it's connected via USB on the PS3 controller.
+ */
+enum SensorEnum {
+ /** Accelerometer values */
+ aX = 50, aY = 52, aZ = 54,
+ /** Gyro z-axis */
+ gZ = 56,
+ gX, gY, // These are not available on the PS3 controller
+
+ /** Accelerometer x-axis */
+ aXmove = 28,
+ /** Accelerometer z-axis */
+ aZmove = 30,
+ /** Accelerometer y-axis */
+ aYmove = 32,
+
+ /** Gyro x-axis */
+ gXmove = 40,
+ /** Gyro z-axis */
+ gZmove = 42,
+ /** Gyro y-axis */
+ gYmove = 44,
+
+ /** Temperature sensor */
+ tempMove = 46,
+
+ /** Magnetometer x-axis */
+ mXmove = 47,
+ /** Magnetometer z-axis */
+ mZmove = 49,
+ /** Magnetometer y-axis */
+ mYmove = 50,
+};
+
+/** Used to get the angle calculated using the PS3 controller and PS4 controller. */
+enum AngleEnum {
+ Pitch = 0x01,
+ Roll = 0x02,
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/BTHID.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/BTHID.ino
new file mode 100644
index 000000000..919a56468
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/BTHID.ino
@@ -0,0 +1,55 @@
+/*
+ Example sketch for the HID Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <BTHID.h>
+#include <usbhub.h>
+#include "KeyboardParser.h"
+#include "MouseParser.h"
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+
+/* You can create the instance of the class in two ways */
+// This will start an inquiry and then pair with your device - you only have to do this once
+// If you are using a Bluetooth keyboard, then you should type in the password on the keypad and then press enter
+BTHID bthid(&Btd, PAIR, "0000");
+
+// After that you can simply create the instance like so and then press any button on the device
+//BTHID hid(&Btd);
+
+KbdRptParser keyboardPrs;
+MouseRptParser mousePrs;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); // Halt
+ }
+
+ bthid.SetReportParser(KEYBOARD_PARSER_ID, (HIDReportParser*)&keyboardPrs);
+ bthid.SetReportParser(MOUSE_PARSER_ID, (HIDReportParser*)&mousePrs);
+
+ // If "Boot Protocol Mode" does not work, then try "Report Protocol Mode"
+ // If that does not work either, then uncomment PRINTREPORT in BTHID.cpp to see the raw report
+ bthid.setProtocolMode(HID_BOOT_PROTOCOL); // Boot Protocol Mode
+ //bthid.setProtocolMode(HID_RPT_PROTOCOL); // Report Protocol Mode
+
+ Serial.print(F("\r\nHID Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task();
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/KeyboardParser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/KeyboardParser.h
new file mode 100644
index 000000000..c5394331d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/KeyboardParser.h
@@ -0,0 +1,105 @@
+#ifndef __kbdrptparser_h_
+#define __kbdrptparser_h_
+
+class KbdRptParser : public KeyboardReportParser {
+ protected:
+ virtual uint8_t HandleLockingKeys(HID *hid, uint8_t key);
+ virtual void OnControlKeysChanged(uint8_t before, uint8_t after);
+ virtual void OnKeyDown(uint8_t mod, uint8_t key);
+ virtual void OnKeyUp(uint8_t mod, uint8_t key);
+ virtual void OnKeyPressed(uint8_t key);
+
+ private:
+ void PrintKey(uint8_t mod, uint8_t key);
+};
+
+uint8_t KbdRptParser::HandleLockingKeys(HID *hid, uint8_t key) {
+ uint8_t old_keys = kbdLockingKeys.bLeds;
+
+ switch (key) {
+ case UHS_HID_BOOT_KEY_NUM_LOCK:
+ Serial.println(F("Num lock"));
+ kbdLockingKeys.kbdLeds.bmNumLock = ~kbdLockingKeys.kbdLeds.bmNumLock;
+ break;
+ case UHS_HID_BOOT_KEY_CAPS_LOCK:
+ Serial.println(F("Caps lock"));
+ kbdLockingKeys.kbdLeds.bmCapsLock = ~kbdLockingKeys.kbdLeds.bmCapsLock;
+ break;
+ case UHS_HID_BOOT_KEY_SCROLL_LOCK:
+ Serial.println(F("Scroll lock"));
+ kbdLockingKeys.kbdLeds.bmScrollLock = ~kbdLockingKeys.kbdLeds.bmScrollLock;
+ break;
+ }
+
+ if (old_keys != kbdLockingKeys.bLeds && hid) {
+ BTHID *pBTHID = reinterpret_cast<BTHID *> (hid); // A cast the other way around is done in BTHID.cpp
+ pBTHID->setLeds(kbdLockingKeys.bLeds); // Update the LEDs on the keyboard
+ }
+
+ return 0;
+};
+
+void KbdRptParser::PrintKey(uint8_t m, uint8_t key) {
+ MODIFIERKEYS mod;
+ *((uint8_t*)&mod) = m;
+ Serial.print((mod.bmLeftCtrl == 1) ? F("C") : F(" "));
+ Serial.print((mod.bmLeftShift == 1) ? F("S") : F(" "));
+ Serial.print((mod.bmLeftAlt == 1) ? F("A") : F(" "));
+ Serial.print((mod.bmLeftGUI == 1) ? F("G") : F(" "));
+
+ Serial.print(F(" >"));
+ PrintHex<uint8_t>(key, 0x80);
+ Serial.print(F("< "));
+
+ Serial.print((mod.bmRightCtrl == 1) ? F("C") : F(" "));
+ Serial.print((mod.bmRightShift == 1) ? F("S") : F(" "));
+ Serial.print((mod.bmRightAlt == 1) ? F("A") : F(" "));
+ Serial.println((mod.bmRightGUI == 1) ? F("G") : F(" "));
+};
+
+void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key) {
+ Serial.print(F("DN "));
+ PrintKey(mod, key);
+ uint8_t c = OemToAscii(mod, key);
+
+ if (c)
+ OnKeyPressed(c);
+};
+
+void KbdRptParser::OnControlKeysChanged(uint8_t before, uint8_t after) {
+ MODIFIERKEYS beforeMod;
+ *((uint8_t*)&beforeMod) = before;
+
+ MODIFIERKEYS afterMod;
+ *((uint8_t*)&afterMod) = after;
+
+ if (beforeMod.bmLeftCtrl != afterMod.bmLeftCtrl)
+ Serial.println(F("LeftCtrl changed"));
+ if (beforeMod.bmLeftShift != afterMod.bmLeftShift)
+ Serial.println(F("LeftShift changed"));
+ if (beforeMod.bmLeftAlt != afterMod.bmLeftAlt)
+ Serial.println(F("LeftAlt changed"));
+ if (beforeMod.bmLeftGUI != afterMod.bmLeftGUI)
+ Serial.println(F("LeftGUI changed"));
+
+ if (beforeMod.bmRightCtrl != afterMod.bmRightCtrl)
+ Serial.println(F("RightCtrl changed"));
+ if (beforeMod.bmRightShift != afterMod.bmRightShift)
+ Serial.println(F("RightShift changed"));
+ if (beforeMod.bmRightAlt != afterMod.bmRightAlt)
+ Serial.println(F("RightAlt changed"));
+ if (beforeMod.bmRightGUI != afterMod.bmRightGUI)
+ Serial.println(F("RightGUI changed"));
+};
+
+void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key) {
+ Serial.print(F("UP "));
+ PrintKey(mod, key);
+};
+
+void KbdRptParser::OnKeyPressed(uint8_t key) {
+ Serial.print(F("ASCII: "));
+ Serial.println((char)key);
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/MouseParser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/MouseParser.h
new file mode 100644
index 000000000..a9245ded9
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/BTHID/MouseParser.h
@@ -0,0 +1,46 @@
+#ifndef __mouserptparser_h__
+#define __mouserptparser_h__
+
+class MouseRptParser : public MouseReportParser {
+ protected:
+ virtual void OnMouseMove(MOUSEINFO *mi);
+ virtual void OnLeftButtonUp(MOUSEINFO *mi);
+ virtual void OnLeftButtonDown(MOUSEINFO *mi);
+ virtual void OnRightButtonUp(MOUSEINFO *mi);
+ virtual void OnRightButtonDown(MOUSEINFO *mi);
+ virtual void OnMiddleButtonUp(MOUSEINFO *mi);
+ virtual void OnMiddleButtonDown(MOUSEINFO *mi);
+};
+
+void MouseRptParser::OnMouseMove(MOUSEINFO *mi) {
+ Serial.print(F("dx="));
+ Serial.print(mi->dX, DEC);
+ Serial.print(F(" dy="));
+ Serial.println(mi->dY, DEC);
+};
+
+void MouseRptParser::OnLeftButtonUp(MOUSEINFO *mi) {
+ Serial.println(F("L Butt Up"));
+};
+
+void MouseRptParser::OnLeftButtonDown(MOUSEINFO *mi) {
+ Serial.println(F("L Butt Dn"));
+};
+
+void MouseRptParser::OnRightButtonUp(MOUSEINFO *mi) {
+ Serial.println(F("R Butt Up"));
+};
+
+void MouseRptParser::OnRightButtonDown(MOUSEINFO *mi) {
+ Serial.println(F("R Butt Dn"));
+};
+
+void MouseRptParser::OnMiddleButtonUp(MOUSEINFO *mi) {
+ Serial.println(F("M Butt Up"));
+};
+
+void MouseRptParser::OnMiddleButtonDown(MOUSEINFO *mi) {
+ Serial.println(F("M Butt Dn"));
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3BT/PS3BT.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3BT/PS3BT.ino
new file mode 100644
index 000000000..b89673440
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3BT/PS3BT.ino
@@ -0,0 +1,188 @@
+/*
+ Example sketch for the PS3 Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <PS3BT.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+/* You can create the instance of the class in two ways */
+PS3BT PS3(&Btd); // This will just create the instance
+//PS3BT PS3(&Btd, 0x00, 0x15, 0x83, 0x3D, 0x0A, 0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch
+
+bool printTemperature;
+bool printAngle;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nPS3 Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task();
+
+ if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
+ if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
+ Serial.print(F("\r\nLeftHatX: "));
+ Serial.print(PS3.getAnalogHat(LeftHatX));
+ Serial.print(F("\tLeftHatY: "));
+ Serial.print(PS3.getAnalogHat(LeftHatY));
+ if (PS3.PS3Connected) { // The Navigation controller only have one joystick
+ Serial.print(F("\tRightHatX: "));
+ Serial.print(PS3.getAnalogHat(RightHatX));
+ Serial.print(F("\tRightHatY: "));
+ Serial.print(PS3.getAnalogHat(RightHatY));
+ }
+ }
+
+ // Analog button values can be read from almost all buttons
+ if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
+ Serial.print(F("\r\nL2: "));
+ Serial.print(PS3.getAnalogButton(L2));
+ if (PS3.PS3Connected) {
+ Serial.print(F("\tR2: "));
+ Serial.print(PS3.getAnalogButton(R2));
+ }
+ }
+ if (PS3.getButtonClick(PS)) {
+ Serial.print(F("\r\nPS"));
+ PS3.disconnect();
+ }
+ else {
+ if (PS3.getButtonClick(TRIANGLE))
+ Serial.print(F("\r\nTraingle"));
+ if (PS3.getButtonClick(CIRCLE))
+ Serial.print(F("\r\nCircle"));
+ if (PS3.getButtonClick(CROSS))
+ Serial.print(F("\r\nCross"));
+ if (PS3.getButtonClick(SQUARE))
+ Serial.print(F("\r\nSquare"));
+
+ if (PS3.getButtonClick(UP)) {
+ Serial.print(F("\r\nUp"));
+ if (PS3.PS3Connected) {
+ PS3.setLedOff();
+ PS3.setLedOn(LED4);
+ }
+ }
+ if (PS3.getButtonClick(RIGHT)) {
+ Serial.print(F("\r\nRight"));
+ if (PS3.PS3Connected) {
+ PS3.setLedOff();
+ PS3.setLedOn(LED1);
+ }
+ }
+ if (PS3.getButtonClick(DOWN)) {
+ Serial.print(F("\r\nDown"));
+ if (PS3.PS3Connected) {
+ PS3.setLedOff();
+ PS3.setLedOn(LED2);
+ }
+ }
+ if (PS3.getButtonClick(LEFT)) {
+ Serial.print(F("\r\nLeft"));
+ if (PS3.PS3Connected) {
+ PS3.setLedOff();
+ PS3.setLedOn(LED3);
+ }
+ }
+
+ if (PS3.getButtonClick(L1))
+ Serial.print(F("\r\nL1"));
+ if (PS3.getButtonClick(L3))
+ Serial.print(F("\r\nL3"));
+ if (PS3.getButtonClick(R1))
+ Serial.print(F("\r\nR1"));
+ if (PS3.getButtonClick(R3))
+ Serial.print(F("\r\nR3"));
+
+ if (PS3.getButtonClick(SELECT)) {
+ Serial.print(F("\r\nSelect - "));
+ PS3.printStatusString();
+ }
+ if (PS3.getButtonClick(START)) {
+ Serial.print(F("\r\nStart"));
+ printAngle = !printAngle;
+ }
+ }
+#if 0 // Set this to 1 in order to see the angle of the controller
+ if (printAngle) {
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(PS3.getAngle(Pitch));
+ Serial.print(F("\tRoll: "));
+ Serial.print(PS3.getAngle(Roll));
+ }
+#endif
+ }
+#if 0 // Set this to 1 in order to enable support for the Playstation Move controller
+ else if (PS3.PS3MoveConnected) {
+ if (PS3.getAnalogButton(T)) {
+ Serial.print(F("\r\nT: "));
+ Serial.print(PS3.getAnalogButton(T));
+ }
+ if (PS3.getButtonClick(PS)) {
+ Serial.print(F("\r\nPS"));
+ PS3.disconnect();
+ }
+ else {
+ if (PS3.getButtonClick(SELECT)) {
+ Serial.print(F("\r\nSelect"));
+ printTemperature = !printTemperature;
+ }
+ if (PS3.getButtonClick(START)) {
+ Serial.print(F("\r\nStart"));
+ printAngle = !printAngle;
+ }
+ if (PS3.getButtonClick(TRIANGLE)) {
+ Serial.print(F("\r\nTriangle"));
+ PS3.moveSetBulb(Red);
+ }
+ if (PS3.getButtonClick(CIRCLE)) {
+ Serial.print(F("\r\nCircle"));
+ PS3.moveSetBulb(Green);
+ }
+ if (PS3.getButtonClick(SQUARE)) {
+ Serial.print(F("\r\nSquare"));
+ PS3.moveSetBulb(Blue);
+ }
+ if (PS3.getButtonClick(CROSS)) {
+ Serial.print(F("\r\nCross"));
+ PS3.moveSetBulb(Yellow);
+ }
+ if (PS3.getButtonClick(MOVE)) {
+ PS3.moveSetBulb(Off);
+ Serial.print(F("\r\nMove"));
+ Serial.print(F(" - "));
+ PS3.printStatusString();
+ }
+ }
+ if (printAngle) {
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(PS3.getAngle(Pitch));
+ Serial.print(F("\tRoll: "));
+ Serial.print(PS3.getAngle(Roll));
+ }
+ else if (printTemperature) {
+ Serial.print(F("\r\nTemperature: "));
+ Serial.print(PS3.getTemperature());
+ }
+ }
+#endif
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3Multi/PS3Multi.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3Multi/PS3Multi.ino
new file mode 100644
index 000000000..5ebfd7819
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3Multi/PS3Multi.ino
@@ -0,0 +1,149 @@
+/*
+ Example sketch for the PS3 Bluetooth library - developed by Kristian Lauszus
+ This example show how one can use multiple controllers with the library
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <PS3BT.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+PS3BT *PS3[2]; // We will use this pointer to store the two instance, you can easily make it larger if you like, but it will use a lot of RAM!
+const uint8_t length = sizeof(PS3) / sizeof(PS3[0]); // Get the lenght of the array
+bool printAngle[length];
+bool oldControllerState[length];
+
+void setup() {
+ for (uint8_t i = 0; i < length; i++) {
+ PS3[i] = new PS3BT(&Btd); // Create the instances
+ PS3[i]->attachOnInit(onInit); // onInit() is called upon a new connection - you can call the function whatever you like
+ }
+
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nPS3 Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task();
+
+ for (uint8_t i = 0; i < length; i++) {
+ if (PS3[i]->PS3Connected || PS3[i]->PS3NavigationConnected) {
+ if (PS3[i]->getAnalogHat(LeftHatX) > 137 || PS3[i]->getAnalogHat(LeftHatX) < 117 || PS3[i]->getAnalogHat(LeftHatY) > 137 || PS3[i]->getAnalogHat(LeftHatY) < 117 || PS3[i]->getAnalogHat(RightHatX) > 137 || PS3[i]->getAnalogHat(RightHatX) < 117 || PS3[i]->getAnalogHat(RightHatY) > 137 || PS3[i]->getAnalogHat(RightHatY) < 117) {
+ Serial.print(F("\r\nLeftHatX: "));
+ Serial.print(PS3[i]->getAnalogHat(LeftHatX));
+ Serial.print(F("\tLeftHatY: "));
+ Serial.print(PS3[i]->getAnalogHat(LeftHatY));
+ if (PS3[i]->PS3Connected) { // The Navigation controller only have one joystick
+ Serial.print(F("\tRightHatX: "));
+ Serial.print(PS3[i]->getAnalogHat(RightHatX));
+ Serial.print(F("\tRightHatY: "));
+ Serial.print(PS3[i]->getAnalogHat(RightHatY));
+ }
+ }
+ //Analog button values can be read from almost all buttons
+ if (PS3[i]->getAnalogButton(L2) || PS3[i]->getAnalogButton(R2)) {
+ Serial.print(F("\r\nL2: "));
+ Serial.print(PS3[i]->getAnalogButton(L2));
+ if (PS3[i]->PS3Connected) {
+ Serial.print(F("\tR2: "));
+ Serial.print(PS3[i]->getAnalogButton(R2));
+ }
+ }
+ if (PS3[i]->getButtonClick(PS)) {
+ Serial.print(F("\r\nPS"));
+ PS3[i]->disconnect();
+ oldControllerState[i] = false; // Reset value
+ }
+ else {
+ if (PS3[i]->getButtonClick(TRIANGLE))
+ Serial.print(F("\r\nTraingle"));
+ if (PS3[i]->getButtonClick(CIRCLE))
+ Serial.print(F("\r\nCircle"));
+ if (PS3[i]->getButtonClick(CROSS))
+ Serial.print(F("\r\nCross"));
+ if (PS3[i]->getButtonClick(SQUARE))
+ Serial.print(F("\r\nSquare"));
+
+ if (PS3[i]->getButtonClick(UP)) {
+ Serial.print(F("\r\nUp"));
+ if (PS3[i]->PS3Connected) {
+ PS3[i]->setLedOff();
+ PS3[i]->setLedOn(LED4);
+ }
+ }
+ if (PS3[i]->getButtonClick(RIGHT)) {
+ Serial.print(F("\r\nRight"));
+ if (PS3[i]->PS3Connected) {
+ PS3[i]->setLedOff();
+ PS3[i]->setLedOn(LED1);
+ }
+ }
+ if (PS3[i]->getButtonClick(DOWN)) {
+ Serial.print(F("\r\nDown"));
+ if (PS3[i]->PS3Connected) {
+ PS3[i]->setLedOff();
+ PS3[i]->setLedOn(LED2);
+ }
+ }
+ if (PS3[i]->getButtonClick(LEFT)) {
+ Serial.print(F("\r\nLeft"));
+ if (PS3[i]->PS3Connected) {
+ PS3[i]->setLedOff();
+ PS3[i]->setLedOn(LED3);
+ }
+ }
+
+ if (PS3[i]->getButtonClick(L1))
+ Serial.print(F("\r\nL1"));
+ if (PS3[i]->getButtonClick(L3))
+ Serial.print(F("\r\nL3"));
+ if (PS3[i]->getButtonClick(R1))
+ Serial.print(F("\r\nR1"));
+ if (PS3[i]->getButtonClick(R3))
+ Serial.print(F("\r\nR3"));
+
+ if (PS3[i]->getButtonClick(SELECT)) {
+ Serial.print(F("\r\nSelect - "));
+ PS3[i]->printStatusString();
+ }
+ if (PS3[i]->getButtonClick(START)) {
+ Serial.print(F("\r\nStart"));
+ printAngle[i] = !printAngle[i];
+ }
+ }
+ if (printAngle[i]) {
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(PS3[i]->getAngle(Pitch));
+ Serial.print(F("\tRoll: "));
+ Serial.print(PS3[i]->getAngle(Roll));
+ }
+ }
+ /* I have removed the PS3 Move code as an Uno will run out of RAM if it's included */
+ //else if(PS3[i]->PS3MoveConnected) {
+ }
+}
+
+void onInit() {
+ for (uint8_t i = 0; i < length; i++) {
+ if ((PS3[i]->PS3Connected || PS3[i]->PS3NavigationConnected) && !oldControllerState[i]) {
+ oldControllerState[i] = true; // Used to check which is the new controller
+ PS3[i]->setLedOn((LEDEnum)(i + 1)); // Cast directly to LEDEnum - see: "controllerEnums.h"
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3SPP/PS3SPP.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3SPP/PS3SPP.ino
new file mode 100644
index 000000000..8f234cbd8
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS3SPP/PS3SPP.ino
@@ -0,0 +1,162 @@
+/*
+ Example sketch for the Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+
+ This example show how one can combine all the difference Bluetooth services in one single code.
+ Note:
+ You will need a Arduino Mega 1280/2560 to run this sketch,
+ as a normal Arduino (Uno, Duemilanove etc.) doesn't have enough SRAM and FLASH
+ */
+
+#include <PS3BT.h>
+#include <SPP.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+
+/* You can create the instances of the bluetooth services in two ways */
+SPP SerialBT(&Btd); // This will set the name to the defaults: "Arduino" and the pin to "0000"
+//SPP SerialBTBT(&Btd,"Lauszus's Arduino","0000"); // You can also set the name and pin like so
+PS3BT PS3(&Btd); // This will just create the instance
+//PS3BT PS3(&Btd, 0x00, 0x15, 0x83, 0x3D, 0x0A, 0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch
+
+bool firstMessage = true;
+String output = ""; // We will store the data in this string
+
+void setup() {
+ Serial.begin(115200); // This wil lprint the debugging from the libraries
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nBluetooth Library Started"));
+ output.reserve(200); // Reserve 200 bytes for the output string
+}
+void loop() {
+ Usb.Task(); // The SPP data is actually not send until this is called, one could call SerialBT.send() directly as well
+
+ if (SerialBT.connected) {
+ if (firstMessage) {
+ firstMessage = false;
+ SerialBT.println(F("Hello from Arduino")); // Send welcome message
+ }
+ if (Serial.available())
+ SerialBT.write(Serial.read());
+ if (SerialBT.available())
+ Serial.write(SerialBT.read());
+ }
+ else
+ firstMessage = true;
+
+ if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
+ output = ""; // Reset output string
+ if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
+ output += "LeftHatX: ";
+ output += PS3.getAnalogHat(LeftHatX);
+ output += "\tLeftHatY: ";
+ output += PS3.getAnalogHat(LeftHatY);
+ if (PS3.PS3Connected) { // The Navigation controller only have one joystick
+ output += "\tRightHatX: ";
+ output += PS3.getAnalogHat(RightHatX);
+ output += "\tRightHatY: ";
+ output += PS3.getAnalogHat(RightHatY);
+ }
+ }
+ //Analog button values can be read from almost all buttons
+ if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
+ if (output != "")
+ output += "\r\n";
+ output += "L2: ";
+ output += PS3.getAnalogButton(L2);
+ if (PS3.PS3Connected) {
+ output += "\tR2: ";
+ output += PS3.getAnalogButton(R2);
+ }
+ }
+ if (output != "") {
+ Serial.println(output);
+ if (SerialBT.connected)
+ SerialBT.println(output);
+ output = ""; // Reset output string
+ }
+ if (PS3.getButtonClick(PS)) {
+ output += " - PS";
+ PS3.disconnect();
+ }
+ else {
+ if (PS3.getButtonClick(TRIANGLE))
+ output += " - Traingle";
+ if (PS3.getButtonClick(CIRCLE))
+ output += " - Circle";
+ if (PS3.getButtonClick(CROSS))
+ output += " - Cross";
+ if (PS3.getButtonClick(SQUARE))
+ output += " - Square";
+
+ if (PS3.getButtonClick(UP)) {
+ output += " - Up";
+ if (PS3.PS3Connected) {
+ PS3.setLedOff();
+ PS3.setLedOn(LED4);
+ }
+ }
+ if (PS3.getButtonClick(RIGHT)) {
+ output += " - Right";
+ if (PS3.PS3Connected) {
+ PS3.setLedOff();
+ PS3.setLedOn(LED1);
+ }
+ }
+ if (PS3.getButtonClick(DOWN)) {
+ output += " - Down";
+ if (PS3.PS3Connected) {
+ PS3.setLedOff();
+ PS3.setLedOn(LED2);
+ }
+ }
+ if (PS3.getButtonClick(LEFT)) {
+ output += " - Left";
+ if (PS3.PS3Connected) {
+ PS3.setLedOff();
+ PS3.setLedOn(LED3);
+ }
+ }
+
+ if (PS3.getButtonClick(L1))
+ output += " - L1";
+ if (PS3.getButtonClick(L3))
+ output += " - L3";
+ if (PS3.getButtonClick(R1))
+ output += " - R1";
+ if (PS3.getButtonClick(R3))
+ output += " - R3";
+
+ if (PS3.getButtonClick(SELECT)) {
+ output += " - Select";
+ }
+ if (PS3.getButtonClick(START))
+ output += " - Start";
+
+ if (output != "") {
+ String string = "PS3 Controller" + output;
+ Serial.println(string);
+ if (SerialBT.connected)
+ SerialBT.println(string);
+ }
+ }
+ delay(10);
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS4BT/PS4BT.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS4BT/PS4BT.ino
new file mode 100644
index 000000000..c3ba696bd
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/PS4BT/PS4BT.ino
@@ -0,0 +1,146 @@
+/*
+ Example sketch for the PS4 Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <PS4BT.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+
+/* You can create the instance of the PS4BT class in two ways */
+// This will start an inquiry and then pair with the PS4 controller - you only have to do this once
+// You will need to hold down the PS and Share button at the same time, the PS4 controller will then start to blink rapidly indicating that it is in paring mode
+PS4BT PS4(&Btd, PAIR);
+
+// After that you can simply create the instance like so and then press the PS button on the device
+//PS4BT PS4(&Btd);
+
+bool printAngle, printTouch;
+uint8_t oldL2Value, oldR2Value;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); // Halt
+ }
+ Serial.print(F("\r\nPS4 Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task();
+
+ if (PS4.connected()) {
+ if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117) {
+ Serial.print(F("\r\nLeftHatX: "));
+ Serial.print(PS4.getAnalogHat(LeftHatX));
+ Serial.print(F("\tLeftHatY: "));
+ Serial.print(PS4.getAnalogHat(LeftHatY));
+ Serial.print(F("\tRightHatX: "));
+ Serial.print(PS4.getAnalogHat(RightHatX));
+ Serial.print(F("\tRightHatY: "));
+ Serial.print(PS4.getAnalogHat(RightHatY));
+ }
+
+ if (PS4.getAnalogButton(L2) || PS4.getAnalogButton(R2)) { // These are the only analog buttons on the PS4 controller
+ Serial.print(F("\r\nL2: "));
+ Serial.print(PS4.getAnalogButton(L2));
+ Serial.print(F("\tR2: "));
+ Serial.print(PS4.getAnalogButton(R2));
+ }
+ if (PS4.getAnalogButton(L2) != oldL2Value || PS4.getAnalogButton(R2) != oldR2Value) // Only write value if it's different
+ PS4.setRumbleOn(PS4.getAnalogButton(L2), PS4.getAnalogButton(R2));
+ oldL2Value = PS4.getAnalogButton(L2);
+ oldR2Value = PS4.getAnalogButton(R2);
+
+ if (PS4.getButtonClick(PS)) {
+ Serial.print(F("\r\nPS"));
+ PS4.disconnect();
+ }
+ else {
+ if (PS4.getButtonClick(TRIANGLE)) {
+ Serial.print(F("\r\nTraingle"));
+ PS4.setRumbleOn(RumbleLow);
+ }
+ if (PS4.getButtonClick(CIRCLE)) {
+ Serial.print(F("\r\nCircle"));
+ PS4.setRumbleOn(RumbleHigh);
+ }
+ if (PS4.getButtonClick(CROSS)) {
+ Serial.print(F("\r\nCross"));
+ PS4.setLedFlash(10, 10); // Set it to blink rapidly
+ }
+ if (PS4.getButtonClick(SQUARE)) {
+ Serial.print(F("\r\nSquare"));
+ PS4.setLedFlash(0, 0); // Turn off blinking
+ }
+
+ if (PS4.getButtonClick(UP)) {
+ Serial.print(F("\r\nUp"));
+ PS4.setLed(Red);
+ } if (PS4.getButtonClick(RIGHT)) {
+ Serial.print(F("\r\nRight"));
+ PS4.setLed(Blue);
+ } if (PS4.getButtonClick(DOWN)) {
+ Serial.print(F("\r\nDown"));
+ PS4.setLed(Yellow);
+ } if (PS4.getButtonClick(LEFT)) {
+ Serial.print(F("\r\nLeft"));
+ PS4.setLed(Green);
+ }
+
+ if (PS4.getButtonClick(L1))
+ Serial.print(F("\r\nL1"));
+ if (PS4.getButtonClick(L3))
+ Serial.print(F("\r\nL3"));
+ if (PS4.getButtonClick(R1))
+ Serial.print(F("\r\nR1"));
+ if (PS4.getButtonClick(R3))
+ Serial.print(F("\r\nR3"));
+
+ if (PS4.getButtonClick(SHARE))
+ Serial.print(F("\r\nShare"));
+ if (PS4.getButtonClick(OPTIONS)) {
+ Serial.print(F("\r\nOptions"));
+ printAngle = !printAngle;
+ }
+ if (PS4.getButtonClick(TOUCHPAD)) {
+ Serial.print(F("\r\nTouchpad"));
+ printTouch = !printTouch;
+ }
+
+ if (printAngle) { // Print angle calculated using the accelerometer only
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(PS4.getAngle(Pitch));
+ Serial.print(F("\tRoll: "));
+ Serial.print(PS4.getAngle(Roll));
+ }
+
+ if (printTouch) { // Print the x, y coordinates of the touchpad
+ if (PS4.isTouching(0) || PS4.isTouching(1)) // Print newline and carriage return if any of the fingers are touching the touchpad
+ Serial.print(F("\r\n"));
+ for (uint8_t i = 0; i < 2; i++) { // The touchpad track two fingers
+ if (PS4.isTouching(i)) { // Print the position of the finger if it is touching the touchpad
+ Serial.print(F("X")); Serial.print(i + 1); Serial.print(F(": "));
+ Serial.print(PS4.getX(i));
+ Serial.print(F("\tY")); Serial.print(i + 1); Serial.print(F(": "));
+ Serial.print(PS4.getY(i));
+ Serial.print(F("\t"));
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/SPP/SPP.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/SPP/SPP.ino
new file mode 100644
index 000000000..8fb9c4eca
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/SPP/SPP.ino
@@ -0,0 +1,52 @@
+/*
+ Example sketch for the RFCOMM/SPP Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <SPP.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+/* You can create the instance of the class in two ways */
+SPP SerialBT(&Btd); // This will set the name to the defaults: "Arduino" and the pin to "0000"
+//SPP SerialBT(&Btd, "Lauszus's Arduino", "1234"); // You can also set the name and pin like so
+
+bool firstMessage = true;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nSPP Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task(); // The SPP data is actually not send until this is called, one could call SerialBT.send() directly as well
+
+ if (SerialBT.connected) {
+ if (firstMessage) {
+ firstMessage = false;
+ SerialBT.println(F("Hello from Arduino")); // Send welcome message
+ }
+ if (Serial.available())
+ SerialBT.write(Serial.read());
+ if (SerialBT.available())
+ Serial.write(SerialBT.read());
+ }
+ else
+ firstMessage = true;
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/SPPMulti/SPPMulti.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/SPPMulti/SPPMulti.ino
new file mode 100644
index 000000000..df521d8e1
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/SPPMulti/SPPMulti.ino
@@ -0,0 +1,67 @@
+/*
+ Example sketch for the RFCOMM/SPP Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <SPP.h>
+#include <usbhub.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+
+const uint8_t length = 2; // Set the number of instances here
+SPP *SerialBT[length]; // We will use this pointer to store the instances, you can easily make it larger if you like, but it will use a lot of RAM!
+
+bool firstMessage[length] = { true }; // Set all to true
+
+void setup() {
+ for (uint8_t i = 0; i < length; i++)
+ SerialBT[i] = new SPP(&Btd); // This will set the name to the default: "Arduino" and the pin to "0000" for all connections
+
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); // Halt
+ }
+ Serial.print(F("\r\nSPP Bluetooth Library Started"));
+}
+
+void loop() {
+ Usb.Task(); // The SPP data is actually not send until this is called, one could call SerialBT.send() directly as well
+
+ for (uint8_t i = 0; i < length; i++) {
+ if (SerialBT[i]->connected) {
+ if (firstMessage[i]) {
+ firstMessage[i] = false;
+ SerialBT[i]->println(F("Hello from Arduino")); // Send welcome message
+ }
+ if (SerialBT[i]->available())
+ Serial.write(SerialBT[i]->read());
+ }
+ else
+ firstMessage[i] = true;
+ }
+
+ // Set the connection you want to send to using the first character
+ // For instance "0Hello World" would send "Hello World" to connection 0
+ if (Serial.available()) {
+ delay(10); // Wait for the rest of the data to arrive
+ uint8_t id = Serial.read() - '0'; // Convert from ASCII
+ if (id < length && SerialBT[id]->connected) { // Make sure that the id is valid and make sure that a device is actually connected
+ while (Serial.available()) // Check if data is available
+ SerialBT[id]->write(Serial.read()); // Send the data
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/Wii/Wii.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/Wii/Wii.ino
new file mode 100644
index 000000000..b19356816
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/Wii/Wii.ino
@@ -0,0 +1,118 @@
+/*
+ Example sketch for the Wiimote Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <Wii.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+/* You can create the instance of the class in two ways */
+WII Wii(&Btd, PAIR); // This will start an inquiry and then pair with your Wiimote - you only have to do this once
+//WII Wii(&Btd); // After that you can simply create the instance like so and then press any button on the Wiimote
+
+bool printAngle;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nWiimote Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task();
+ if (Wii.wiimoteConnected) {
+ if (Wii.getButtonClick(HOME)) { // You can use getButtonPress to see if the button is held down
+ Serial.print(F("\r\nHOME"));
+ Wii.disconnect();
+ }
+ else {
+ if (Wii.getButtonClick(LEFT)) {
+ Wii.setLedOff();
+ Wii.setLedOn(LED1);
+ Serial.print(F("\r\nLeft"));
+ }
+ if (Wii.getButtonClick(RIGHT)) {
+ Wii.setLedOff();
+ Wii.setLedOn(LED3);
+ Serial.print(F("\r\nRight"));
+ }
+ if (Wii.getButtonClick(DOWN)) {
+ Wii.setLedOff();
+ Wii.setLedOn(LED4);
+ Serial.print(F("\r\nDown"));
+ }
+ if (Wii.getButtonClick(UP)) {
+ Wii.setLedOff();
+ Wii.setLedOn(LED2);
+ Serial.print(F("\r\nUp"));
+ }
+
+ if (Wii.getButtonClick(PLUS))
+ Serial.print(F("\r\nPlus"));
+ if (Wii.getButtonClick(MINUS))
+ Serial.print(F("\r\nMinus"));
+
+ if (Wii.getButtonClick(ONE))
+ Serial.print(F("\r\nOne"));
+ if (Wii.getButtonClick(TWO))
+ Serial.print(F("\r\nTwo"));
+
+ if (Wii.getButtonClick(A)) {
+ printAngle = !printAngle;
+ Serial.print(F("\r\nA"));
+ }
+ if (Wii.getButtonClick(B)) {
+ Wii.setRumbleToggle();
+ Serial.print(F("\r\nB"));
+ }
+ }
+#if 0 // Set this to 1 in order to see the angle of the controllers
+ if (printAngle) {
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(Wii.getPitch());
+ Serial.print(F("\tRoll: "));
+ Serial.print(Wii.getRoll());
+ if (Wii.motionPlusConnected) {
+ Serial.print(F("\tYaw: "));
+ Serial.print(Wii.getYaw());
+ }
+ if (Wii.nunchuckConnected) {
+ Serial.print(F("\tNunchuck Pitch: "));
+ Serial.print(Wii.getNunchuckPitch());
+ Serial.print(F("\tNunchuck Roll: "));
+ Serial.print(Wii.getNunchuckRoll());
+ }
+ }
+#endif
+ }
+#if 0 // Set this to 1 if you are using a Nunchuck controller
+ if (Wii.nunchuckConnected) {
+ if (Wii.getButtonClick(Z))
+ Serial.print(F("\r\nZ"));
+ if (Wii.getButtonClick(C))
+ Serial.print(F("\r\nC"));
+ if (Wii.getAnalogHat(HatX) > 137 || Wii.getAnalogHat(HatX) < 117 || Wii.getAnalogHat(HatY) > 137 || Wii.getAnalogHat(HatY) < 117) {
+ Serial.print(F("\r\nHatX: "));
+ Serial.print(Wii.getAnalogHat(HatX));
+ Serial.print(F("\tHatY: "));
+ Serial.print(Wii.getAnalogHat(HatY));
+ }
+ }
+#endif
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiBalanceBoard/WiiBalanceBoard.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiBalanceBoard/WiiBalanceBoard.ino
new file mode 100644
index 000000000..18c5b411e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiBalanceBoard/WiiBalanceBoard.ino
@@ -0,0 +1,51 @@
+/*
+ Example sketch for the Wii Balance Board Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <Wii.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+/* You can create the instance of the class in two ways */
+WII Wii(&Btd, PAIR); // This will start an inquiry and then pair with your Wii Balance Board - you only have to do this once
+//WII Wii(&Btd); // After that you can simply create the instance like so and then press the power button on the Wii Balance Board
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nWii Balance Board Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task();
+ if (Wii.wiiBalanceBoardConnected) {
+ Serial.print(F("\r\nWeight: "));
+ for (uint8_t i = 0; i < 4; i++) {
+ Serial.print(Wii.getWeight((BalanceBoardEnum)i));
+ Serial.print(F("\t"));
+ }
+ Serial.print(F("Total Weight: "));
+ Serial.print(Wii.getTotalWeight());
+ if (Wii.getButtonClick(A)) {
+ Serial.print(F("\r\nA"));
+ //Wii.setLedToggle(LED1); // The Wii Balance Board has one LED as well
+ Wii.disconnect();
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino
new file mode 100644
index 000000000..573b8bd48
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino
@@ -0,0 +1,133 @@
+/*
+Example sketch for the Wii libary showing the IR camera functionality. This example
+is for the Bluetooth Wii library developed for the USB shield from Circuits@Home
+
+Created by Allan Glover and Kristian Lauszus.
+Contact Kristian: http://blog.tkjelectronics.dk/ or send an email at kristianl@tkjelectronics.com.
+Contact Allan at adglover9.81@gmail.com
+
+To test the Wiimote IR camera, you will need access to an IR source. Sunlight will work but is not ideal.
+The simpleist solution is to use the Wii sensor bar, i.e. emitter bar, supplied by the Wii system.
+Otherwise, wire up a IR LED yourself.
+*/
+
+#include <Wii.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+#ifndef WIICAMERA // Used to check if WIICAMERA is defined
+#error "Please set ENABLE_WII_IR_CAMERA to 1 in settings.h"
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+/* You can create the instance of the class in two ways */
+WII Wii(&Btd, PAIR); // This will start an inquiry and then pair with your Wiimote - you only have to do this once
+//WII Wii(&Btd); // After the Wiimote pairs once with the line of code above, you can simply create the instance like so and re upload and then press any button on the Wiimote
+
+bool printAngle;
+uint8_t printObjects;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nWiimote Bluetooth Library Started"));
+}
+
+void loop() {
+ Usb.Task();
+ if (Wii.wiimoteConnected) {
+ if (Wii.getButtonClick(HOME)) { // You can use getButtonPress to see if the button is held down
+ Serial.print(F("\r\nHOME"));
+ Wii.disconnect();
+ }
+ else {
+ if (Wii.getButtonClick(ONE))
+ Wii.IRinitialize(); // Run the initialisation sequence
+ if (Wii.getButtonClick(MINUS) || Wii.getButtonClick(PLUS)) {
+ if (!Wii.isIRCameraEnabled())
+ Serial.print(F("\r\nEnable IR camera first"));
+ else {
+ if (Wii.getButtonPress(MINUS)) { // getButtonClick will only return true once
+ if (printObjects > 0)
+ printObjects--;
+ }
+ else {
+ if (printObjects < 4)
+ printObjects++;
+ }
+ Serial.print(F("\r\nTracking "));
+ Serial.print(printObjects);
+ Serial.print(F(" objects"));
+ }
+ }
+ if (Wii.getButtonClick(A)) {
+ printAngle = !printAngle;
+ Serial.print(F("\r\nA"));
+ }
+ if (Wii.getButtonClick(B)) {
+ Serial.print(F("\r\nBattery level: "));
+ Serial.print(Wii.getBatteryLevel()); // You can get the battery level as well
+ }
+ }
+ if (printObjects > 0) {
+ if (Wii.getIRx1() != 0x3FF || Wii.getIRy1() != 0x3FF || Wii.getIRs1() != 0) { // Only print if the IR camera is actually seeing something
+ Serial.print(F("\r\nx1: "));
+ Serial.print(Wii.getIRx1());
+ Serial.print(F("\ty1: "));
+ Serial.print(Wii.getIRy1());
+ Serial.print(F("\ts1:"));
+ Serial.print(Wii.getIRs1());
+ }
+ if (printObjects > 1) {
+ if (Wii.getIRx2() != 0x3FF || Wii.getIRy2() != 0x3FF || Wii.getIRs2() != 0) {
+ Serial.print(F("\r\nx2: "));
+ Serial.print(Wii.getIRx2());
+ Serial.print(F("\ty2: "));
+ Serial.print(Wii.getIRy2());
+ Serial.print(F("\ts2:"));
+ Serial.print(Wii.getIRs2());
+ }
+ if (printObjects > 2) {
+ if (Wii.getIRx3() != 0x3FF || Wii.getIRy3() != 0x3FF || Wii.getIRs3() != 0) {
+ Serial.print(F("\r\nx3: "));
+ Serial.print(Wii.getIRx3());
+ Serial.print(F("\ty3: "));
+ Serial.print(Wii.getIRy3());
+ Serial.print(F("\ts3:"));
+ Serial.print(Wii.getIRs3());
+ }
+ if (printObjects > 3) {
+ if (Wii.getIRx4() != 0x3FF || Wii.getIRy4() != 0x3FF || Wii.getIRs4() != 0) {
+ Serial.print(F("\r\nx4: "));
+ Serial.print(Wii.getIRx4());
+ Serial.print(F("\ty4: "));
+ Serial.print(Wii.getIRy4());
+ Serial.print(F("\ts4:"));
+ Serial.print(Wii.getIRs4());
+ }
+ }
+ }
+ }
+ }
+ if (printAngle) { // There is no extension bytes available, so the MotionPlus or Nunchuck can't be read
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(Wii.getPitch());
+ Serial.print(F("\tRoll: "));
+ Serial.print(Wii.getRoll());
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiMulti/WiiMulti.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiMulti/WiiMulti.ino
new file mode 100644
index 000000000..07c6f13d2
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiMulti/WiiMulti.ino
@@ -0,0 +1,132 @@
+/*
+ Example sketch for the Wiimote Bluetooth library - developed by Kristian Lauszus
+ This example show how one can use multiple controllers with the library
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <Wii.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+WII *Wii[2]; // We will use this pointer to store the two instance, you can easily make it larger if you like, but it will use a lot of RAM!
+const uint8_t length = sizeof(Wii) / sizeof(Wii[0]); // Get the lenght of the array
+bool printAngle[length];
+bool oldControllerState[length];
+
+void setup() {
+ for (uint8_t i = 0; i < length; i++) {
+ Wii[i] = new WII(&Btd); // You will have to pair each controller with the dongle before you can define the instances like so, just add PAIR as the second argument
+ Wii[i]->attachOnInit(onInit); // onInit() is called upon a new connection - you can call the function whatever you like
+ }
+
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nWiimote Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task();
+
+ for (uint8_t i = 0; i < length; i++) {
+ if (Wii[i]->wiimoteConnected) {
+ if (Wii[i]->getButtonClick(HOME)) { // You can use getButtonPress to see if the button is held down
+ Serial.print(F("\r\nHOME"));
+ Wii[i]->disconnect();
+ oldControllerState[i] = false; // Reset value
+ }
+ else {
+ if (Wii[i]->getButtonClick(LEFT)) {
+ Wii[i]->setLedOff();
+ Wii[i]->setLedOn(LED1);
+ Serial.print(F("\r\nLeft"));
+ }
+ if (Wii[i]->getButtonClick(RIGHT)) {
+ Wii[i]->setLedOff();
+ Wii[i]->setLedOn(LED3);
+ Serial.print(F("\r\nRight"));
+ }
+ if (Wii[i]->getButtonClick(DOWN)) {
+ Wii[i]->setLedOff();
+ Wii[i]->setLedOn(LED4);
+ Serial.print(F("\r\nDown"));
+ }
+ if (Wii[i]->getButtonClick(UP)) {
+ Wii[i]->setLedOff();
+ Wii[i]->setLedOn(LED2);
+ Serial.print(F("\r\nUp"));
+ }
+
+ if (Wii[i]->getButtonClick(PLUS))
+ Serial.print(F("\r\nPlus"));
+ if (Wii[i]->getButtonClick(MINUS))
+ Serial.print(F("\r\nMinus"));
+
+ if (Wii[i]->getButtonClick(ONE))
+ Serial.print(F("\r\nOne"));
+ if (Wii[i]->getButtonClick(TWO))
+ Serial.print(F("\r\nTwo"));
+
+ if (Wii[i]->getButtonClick(A)) {
+ printAngle[i] = !printAngle[i];
+ Serial.print(F("\r\nA"));
+ }
+ if (Wii[i]->getButtonClick(B)) {
+ Wii[i]->setRumbleToggle();
+ Serial.print(F("\r\nB"));
+ }
+ }
+ if (printAngle[i]) {
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(Wii[i]->getPitch());
+ Serial.print(F("\tRoll: "));
+ Serial.print(Wii[i]->getRoll());
+ if (Wii[i]->motionPlusConnected) {
+ Serial.print(F("\tYaw: "));
+ Serial.print(Wii[i]->getYaw());
+ }
+ if (Wii[i]->nunchuckConnected) {
+ Serial.print(F("\tNunchuck Pitch: "));
+ Serial.print(Wii[i]->getNunchuckPitch());
+ Serial.print(F("\tNunchuck Roll: "));
+ Serial.print(Wii[i]->getNunchuckRoll());
+ }
+ }
+ }
+ if (Wii[i]->nunchuckConnected) {
+ if (Wii[i]->getButtonClick(Z))
+ Serial.print(F("\r\nZ"));
+ if (Wii[i]->getButtonClick(C))
+ Serial.print(F("\r\nC"));
+ if (Wii[i]->getAnalogHat(HatX) > 137 || Wii[i]->getAnalogHat(HatX) < 117 || Wii[i]->getAnalogHat(HatY) > 137 || Wii[i]->getAnalogHat(HatY) < 117) {
+ Serial.print(F("\r\nHatX: "));
+ Serial.print(Wii[i]->getAnalogHat(HatX));
+ Serial.print(F("\tHatY: "));
+ Serial.print(Wii[i]->getAnalogHat(HatY));
+ }
+ }
+ }
+}
+
+void onInit() {
+ for (uint8_t i = 0; i < length; i++) {
+ if (Wii[i]->wiimoteConnected && !oldControllerState[i]) {
+ oldControllerState[i] = true; // Used to check which is the new controller
+ Wii[i]->setLedOn((LEDEnum)(i + 1)); // Cast directly to LEDEnum - see: "controllerEnums.h"
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiUProController/WiiUProController.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiUProController/WiiUProController.ino
new file mode 100644
index 000000000..ab35a2747
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Bluetooth/WiiUProController/WiiUProController.ino
@@ -0,0 +1,104 @@
+/*
+ Example sketch for the Wiimote Bluetooth library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <Wii.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb); // Some dongles have a hub inside
+
+BTD Btd(&Usb); // You have to create the Bluetooth Dongle instance like so
+/* You can create the instance of the class in two ways */
+WII Wii(&Btd, PAIR); // This will start an inquiry and then pair with your Wiimote - you only have to do this once
+//WII Wii(&Btd); // After that you can simply create the instance like so and then press any button on the Wiimote
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nWiimote Bluetooth Library Started"));
+}
+void loop() {
+ Usb.Task();
+ if (Wii.wiiUProControllerConnected) {
+ if (Wii.getButtonClick(HOME)) { // You can use getButtonPress to see if the button is held down
+ Serial.print(F("\r\nHome"));
+ Wii.disconnect();
+ }
+ else {
+ if (Wii.getButtonClick(LEFT)) {
+ Wii.setLedOff();
+ Wii.setLedOn(LED1);
+ Serial.print(F("\r\nLeft"));
+ }
+ if (Wii.getButtonClick(RIGHT)) {
+ Wii.setLedOff();
+ Wii.setLedOn(LED3);
+ Serial.print(F("\r\nRight"));
+ }
+ if (Wii.getButtonClick(DOWN)) {
+ Wii.setLedOff();
+ Wii.setLedOn(LED4);
+ Serial.print(F("\r\nDown"));
+ }
+ if (Wii.getButtonClick(UP)) {
+ Wii.setLedOff();
+ Wii.setLedOn(LED2);
+ Serial.print(F("\r\nUp"));
+ }
+
+ if (Wii.getButtonClick(PLUS))
+ Serial.print(F("\r\nPlus"));
+ if (Wii.getButtonClick(MINUS))
+ Serial.print(F("\r\nMinus"));
+
+ if (Wii.getButtonClick(A))
+ Serial.print(F("\r\nA"));
+ if (Wii.getButtonClick(B)) {
+ Wii.setRumbleToggle();
+ Serial.print(F("\r\nB"));
+ }
+ if (Wii.getButtonClick(X))
+ Serial.print(F("\r\nX"));
+ if (Wii.getButtonClick(Y))
+ Serial.print(F("\r\nY"));
+
+ if (Wii.getButtonClick(L))
+ Serial.print(F("\r\nL"));
+ if (Wii.getButtonClick(R))
+ Serial.print(F("\r\nR"));
+ if (Wii.getButtonClick(ZL))
+ Serial.print(F("\r\nZL"));
+ if (Wii.getButtonClick(ZR))
+ Serial.print(F("\r\nZR"));
+ if (Wii.getButtonClick(L3))
+ Serial.print(F("\r\nL3"));
+ if (Wii.getButtonClick(R3))
+ Serial.print(F("\r\nR3"));
+ }
+ if (Wii.getAnalogHat(LeftHatX) > 2200 || Wii.getAnalogHat(LeftHatX) < 1800 || Wii.getAnalogHat(LeftHatY) > 2200 || Wii.getAnalogHat(LeftHatY) < 1800 || Wii.getAnalogHat(RightHatX) > 2200 || Wii.getAnalogHat(RightHatX) < 1800 || Wii.getAnalogHat(RightHatY) > 2200 || Wii.getAnalogHat(RightHatY) < 1800) {
+ Serial.print(F("\r\nLeftHatX: "));
+ Serial.print(Wii.getAnalogHat(LeftHatX));
+ Serial.print(F("\tLeftHatY: "));
+ Serial.print(Wii.getAnalogHat(LeftHatY));
+ Serial.print(F("\tRightHatX: "));
+ Serial.print(Wii.getAnalogHat(RightHatX));
+ Serial.print(F("\tRightHatY: "));
+ Serial.print(Wii.getAnalogHat(RightHatY));
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino
new file mode 100644
index 000000000..48b33abfd
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootKbd/USBHIDBootKbd.ino
@@ -0,0 +1,129 @@
+#include <hidboot.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class KbdRptParser : public KeyboardReportParser
+{
+ void PrintKey(uint8_t mod, uint8_t key);
+
+ protected:
+ void OnControlKeysChanged(uint8_t before, uint8_t after);
+
+ void OnKeyDown (uint8_t mod, uint8_t key);
+ void OnKeyUp (uint8_t mod, uint8_t key);
+ void OnKeyPressed(uint8_t key);
+};
+
+void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
+{
+ MODIFIERKEYS mod;
+ *((uint8_t*)&mod) = m;
+ Serial.print((mod.bmLeftCtrl == 1) ? "C" : " ");
+ Serial.print((mod.bmLeftShift == 1) ? "S" : " ");
+ Serial.print((mod.bmLeftAlt == 1) ? "A" : " ");
+ Serial.print((mod.bmLeftGUI == 1) ? "G" : " ");
+
+ Serial.print(" >");
+ PrintHex<uint8_t>(key, 0x80);
+ Serial.print("< ");
+
+ Serial.print((mod.bmRightCtrl == 1) ? "C" : " ");
+ Serial.print((mod.bmRightShift == 1) ? "S" : " ");
+ Serial.print((mod.bmRightAlt == 1) ? "A" : " ");
+ Serial.println((mod.bmRightGUI == 1) ? "G" : " ");
+};
+
+void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
+{
+ Serial.print("DN ");
+ PrintKey(mod, key);
+ uint8_t c = OemToAscii(mod, key);
+
+ if (c)
+ OnKeyPressed(c);
+}
+
+void KbdRptParser::OnControlKeysChanged(uint8_t before, uint8_t after) {
+
+ MODIFIERKEYS beforeMod;
+ *((uint8_t*)&beforeMod) = before;
+
+ MODIFIERKEYS afterMod;
+ *((uint8_t*)&afterMod) = after;
+
+ if (beforeMod.bmLeftCtrl != afterMod.bmLeftCtrl) {
+ Serial.println("LeftCtrl changed");
+ }
+ if (beforeMod.bmLeftShift != afterMod.bmLeftShift) {
+ Serial.println("LeftShift changed");
+ }
+ if (beforeMod.bmLeftAlt != afterMod.bmLeftAlt) {
+ Serial.println("LeftAlt changed");
+ }
+ if (beforeMod.bmLeftGUI != afterMod.bmLeftGUI) {
+ Serial.println("LeftGUI changed");
+ }
+
+ if (beforeMod.bmRightCtrl != afterMod.bmRightCtrl) {
+ Serial.println("RightCtrl changed");
+ }
+ if (beforeMod.bmRightShift != afterMod.bmRightShift) {
+ Serial.println("RightShift changed");
+ }
+ if (beforeMod.bmRightAlt != afterMod.bmRightAlt) {
+ Serial.println("RightAlt changed");
+ }
+ if (beforeMod.bmRightGUI != afterMod.bmRightGUI) {
+ Serial.println("RightGUI changed");
+ }
+
+}
+
+void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
+{
+ Serial.print("UP ");
+ PrintKey(mod, key);
+}
+
+void KbdRptParser::OnKeyPressed(uint8_t key)
+{
+ Serial.print("ASCII: ");
+ Serial.println((char)key);
+};
+
+USB Usb;
+//USBHub Hub(&Usb);
+HIDBoot<HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
+
+uint32_t next_time;
+
+KbdRptParser Prs;
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay( 200 );
+
+ next_time = millis() + 5000;
+
+ HidKeyboard.SetReportParser(0, (HIDReportParser*)&Prs);
+}
+
+void loop()
+{
+ Usb.Task();
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootKbdAndMouse/USBHIDBootKbdAndMouse.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootKbdAndMouse/USBHIDBootKbdAndMouse.ino
new file mode 100644
index 000000000..5fc8c96fc
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootKbdAndMouse/USBHIDBootKbdAndMouse.ino
@@ -0,0 +1,178 @@
+#include <hidboot.h>
+#include <usbhub.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class MouseRptParser : public MouseReportParser
+{
+ protected:
+ void OnMouseMove(MOUSEINFO *mi);
+ void OnLeftButtonUp(MOUSEINFO *mi);
+ void OnLeftButtonDown(MOUSEINFO *mi);
+ void OnRightButtonUp(MOUSEINFO *mi);
+ void OnRightButtonDown(MOUSEINFO *mi);
+ void OnMiddleButtonUp(MOUSEINFO *mi);
+ void OnMiddleButtonDown(MOUSEINFO *mi);
+};
+void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
+{
+ Serial.print("dx=");
+ Serial.print(mi->dX, DEC);
+ Serial.print(" dy=");
+ Serial.println(mi->dY, DEC);
+};
+void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi)
+{
+ Serial.println("L Butt Up");
+};
+void MouseRptParser::OnLeftButtonDown (MOUSEINFO *mi)
+{
+ Serial.println("L Butt Dn");
+};
+void MouseRptParser::OnRightButtonUp (MOUSEINFO *mi)
+{
+ Serial.println("R Butt Up");
+};
+void MouseRptParser::OnRightButtonDown (MOUSEINFO *mi)
+{
+ Serial.println("R Butt Dn");
+};
+void MouseRptParser::OnMiddleButtonUp (MOUSEINFO *mi)
+{
+ Serial.println("M Butt Up");
+};
+void MouseRptParser::OnMiddleButtonDown (MOUSEINFO *mi)
+{
+ Serial.println("M Butt Dn");
+};
+
+class KbdRptParser : public KeyboardReportParser
+{
+ void PrintKey(uint8_t mod, uint8_t key);
+
+ protected:
+ void OnControlKeysChanged(uint8_t before, uint8_t after);
+ void OnKeyDown (uint8_t mod, uint8_t key);
+ void OnKeyUp (uint8_t mod, uint8_t key);
+ void OnKeyPressed(uint8_t key);
+};
+
+void KbdRptParser::PrintKey(uint8_t m, uint8_t key)
+{
+ MODIFIERKEYS mod;
+ *((uint8_t*)&mod) = m;
+ Serial.print((mod.bmLeftCtrl == 1) ? "C" : " ");
+ Serial.print((mod.bmLeftShift == 1) ? "S" : " ");
+ Serial.print((mod.bmLeftAlt == 1) ? "A" : " ");
+ Serial.print((mod.bmLeftGUI == 1) ? "G" : " ");
+
+ Serial.print(" >");
+ PrintHex<uint8_t>(key, 0x80);
+ Serial.print("< ");
+
+ Serial.print((mod.bmRightCtrl == 1) ? "C" : " ");
+ Serial.print((mod.bmRightShift == 1) ? "S" : " ");
+ Serial.print((mod.bmRightAlt == 1) ? "A" : " ");
+ Serial.println((mod.bmRightGUI == 1) ? "G" : " ");
+};
+
+void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
+{
+ Serial.print("DN ");
+ PrintKey(mod, key);
+ uint8_t c = OemToAscii(mod, key);
+
+ if (c)
+ OnKeyPressed(c);
+}
+
+void KbdRptParser::OnControlKeysChanged(uint8_t before, uint8_t after) {
+
+ MODIFIERKEYS beforeMod;
+ *((uint8_t*)&beforeMod) = before;
+
+ MODIFIERKEYS afterMod;
+ *((uint8_t*)&afterMod) = after;
+
+ if (beforeMod.bmLeftCtrl != afterMod.bmLeftCtrl) {
+ Serial.println("LeftCtrl changed");
+ }
+ if (beforeMod.bmLeftShift != afterMod.bmLeftShift) {
+ Serial.println("LeftShift changed");
+ }
+ if (beforeMod.bmLeftAlt != afterMod.bmLeftAlt) {
+ Serial.println("LeftAlt changed");
+ }
+ if (beforeMod.bmLeftGUI != afterMod.bmLeftGUI) {
+ Serial.println("LeftGUI changed");
+ }
+
+ if (beforeMod.bmRightCtrl != afterMod.bmRightCtrl) {
+ Serial.println("RightCtrl changed");
+ }
+ if (beforeMod.bmRightShift != afterMod.bmRightShift) {
+ Serial.println("RightShift changed");
+ }
+ if (beforeMod.bmRightAlt != afterMod.bmRightAlt) {
+ Serial.println("RightAlt changed");
+ }
+ if (beforeMod.bmRightGUI != afterMod.bmRightGUI) {
+ Serial.println("RightGUI changed");
+ }
+
+}
+
+void KbdRptParser::OnKeyUp(uint8_t mod, uint8_t key)
+{
+ Serial.print("UP ");
+ PrintKey(mod, key);
+}
+
+void KbdRptParser::OnKeyPressed(uint8_t key)
+{
+ Serial.print("ASCII: ");
+ Serial.println((char)key);
+};
+
+USB Usb;
+USBHub Hub(&Usb);
+
+HIDBoot < HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE > HidComposite(&Usb);
+HIDBoot<HID_PROTOCOL_KEYBOARD> HidKeyboard(&Usb);
+HIDBoot<HID_PROTOCOL_MOUSE> HidMouse(&Usb);
+
+//uint32_t next_time;
+
+KbdRptParser KbdPrs;
+MouseRptParser MousePrs;
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay( 200 );
+
+ //next_time = millis() + 5000;
+
+ HidComposite.SetReportParser(0, (HIDReportParser*)&KbdPrs);
+ HidComposite.SetReportParser(1, (HIDReportParser*)&MousePrs);
+ HidKeyboard.SetReportParser(0, (HIDReportParser*)&KbdPrs);
+ HidMouse.SetReportParser(0, (HIDReportParser*)&MousePrs);
+}
+
+void loop()
+{
+ Usb.Task();
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino
new file mode 100644
index 000000000..53102512b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDBootMouse/USBHIDBootMouse.ino
@@ -0,0 +1,83 @@
+#include <hidboot.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class MouseRptParser : public MouseReportParser
+{
+protected:
+ void OnMouseMove (MOUSEINFO *mi);
+ void OnLeftButtonUp (MOUSEINFO *mi);
+ void OnLeftButtonDown (MOUSEINFO *mi);
+ void OnRightButtonUp (MOUSEINFO *mi);
+ void OnRightButtonDown (MOUSEINFO *mi);
+ void OnMiddleButtonUp (MOUSEINFO *mi);
+ void OnMiddleButtonDown (MOUSEINFO *mi);
+};
+void MouseRptParser::OnMouseMove(MOUSEINFO *mi)
+{
+ Serial.print("dx=");
+ Serial.print(mi->dX, DEC);
+ Serial.print(" dy=");
+ Serial.println(mi->dY, DEC);
+};
+void MouseRptParser::OnLeftButtonUp (MOUSEINFO *mi)
+{
+ Serial.println("L Butt Up");
+};
+void MouseRptParser::OnLeftButtonDown (MOUSEINFO *mi)
+{
+ Serial.println("L Butt Dn");
+};
+void MouseRptParser::OnRightButtonUp (MOUSEINFO *mi)
+{
+ Serial.println("R Butt Up");
+};
+void MouseRptParser::OnRightButtonDown (MOUSEINFO *mi)
+{
+ Serial.println("R Butt Dn");
+};
+void MouseRptParser::OnMiddleButtonUp (MOUSEINFO *mi)
+{
+ Serial.println("M Butt Up");
+};
+void MouseRptParser::OnMiddleButtonDown (MOUSEINFO *mi)
+{
+ Serial.println("M Butt Dn");
+};
+
+USB Usb;
+USBHub Hub(&Usb);
+HIDBoot<HID_PROTOCOL_MOUSE> HidMouse(&Usb);
+
+uint32_t next_time;
+
+MouseRptParser Prs;
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay( 200 );
+
+ next_time = millis() + 5000;
+
+ HidMouse.SetReportParser(0,(HIDReportParser*)&Prs);
+}
+
+void loop()
+{
+ Usb.Task();
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/USBHIDJoystick.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/USBHIDJoystick.ino
new file mode 100644
index 000000000..956441d67
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/USBHIDJoystick.ino
@@ -0,0 +1,38 @@
+#include <hid.h>
+#include <hiduniversal.h>
+#include <usbhub.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+#include "hidjoystickrptparser.h"
+
+USB Usb;
+USBHub Hub(&Usb);
+HIDUniversal Hid(&Usb);
+JoystickEvents JoyEvents;
+JoystickReportParser Joy(&JoyEvents);
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay(200);
+
+ if (!Hid.SetReportParser(0, &Joy))
+ ErrorMessage<uint8_t > (PSTR("SetReportParser"), 1);
+}
+
+void loop() {
+ Usb.Task();
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/hidjoystickrptparser.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/hidjoystickrptparser.cpp
new file mode 100644
index 000000000..083b95cac
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/hidjoystickrptparser.cpp
@@ -0,0 +1,84 @@
+#include "hidjoystickrptparser.h"
+
+JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
+joyEvents(evt),
+oldHat(0xDE),
+oldButtons(0) {
+ for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++)
+ oldPad[i] = 0xD;
+}
+
+void JoystickReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
+ bool match = true;
+
+ // Checking if there are changes in report since the method was last called
+ for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++)
+ if (buf[i] != oldPad[i]) {
+ match = false;
+ break;
+ }
+
+ // Calling Game Pad event handler
+ if (!match && joyEvents) {
+ joyEvents->OnGamePadChanged((const GamePadEventData*)buf);
+
+ for (uint8_t i = 0; i < RPT_GEMEPAD_LEN; i++) oldPad[i] = buf[i];
+ }
+
+ uint8_t hat = (buf[5] & 0xF);
+
+ // Calling Hat Switch event handler
+ if (hat != oldHat && joyEvents) {
+ joyEvents->OnHatSwitch(hat);
+ oldHat = hat;
+ }
+
+ uint16_t buttons = (0x0000 | buf[6]);
+ buttons <<= 4;
+ buttons |= (buf[5] >> 4);
+ uint16_t changes = (buttons ^ oldButtons);
+
+ // Calling Button Event Handler for every button changed
+ if (changes) {
+ for (uint8_t i = 0; i < 0x0C; i++) {
+ uint16_t mask = (0x0001 << i);
+
+ if (((mask & changes) > 0) && joyEvents)
+ if ((buttons & mask) > 0)
+ joyEvents->OnButtonDn(i + 1);
+ else
+ joyEvents->OnButtonUp(i + 1);
+ }
+ oldButtons = buttons;
+ }
+}
+
+void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt) {
+ Serial.print("X1: ");
+ PrintHex<uint8_t > (evt->X, 0x80);
+ Serial.print("\tY1: ");
+ PrintHex<uint8_t > (evt->Y, 0x80);
+ Serial.print("\tX2: ");
+ PrintHex<uint8_t > (evt->Z1, 0x80);
+ Serial.print("\tY2: ");
+ PrintHex<uint8_t > (evt->Z2, 0x80);
+ Serial.print("\tRz: ");
+ PrintHex<uint8_t > (evt->Rz, 0x80);
+ Serial.println("");
+}
+
+void JoystickEvents::OnHatSwitch(uint8_t hat) {
+ Serial.print("Hat Switch: ");
+ PrintHex<uint8_t > (hat, 0x80);
+ Serial.println("");
+}
+
+void JoystickEvents::OnButtonUp(uint8_t but_id) {
+ Serial.print("Up: ");
+ Serial.println(but_id, DEC);
+}
+
+void JoystickEvents::OnButtonDn(uint8_t but_id) {
+ Serial.print("Dn: ");
+ Serial.println(but_id, DEC);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/hidjoystickrptparser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/hidjoystickrptparser.h
new file mode 100644
index 000000000..733b8f8da
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHIDJoystick/hidjoystickrptparser.h
@@ -0,0 +1,33 @@
+#if !defined(__HIDJOYSTICKRPTPARSER_H__)
+#define __HIDJOYSTICKRPTPARSER_H__
+
+#include <hid.h>
+
+struct GamePadEventData {
+ uint8_t X, Y, Z1, Z2, Rz;
+};
+
+class JoystickEvents {
+public:
+ virtual void OnGamePadChanged(const GamePadEventData *evt);
+ virtual void OnHatSwitch(uint8_t hat);
+ virtual void OnButtonUp(uint8_t but_id);
+ virtual void OnButtonDn(uint8_t but_id);
+};
+
+#define RPT_GEMEPAD_LEN 5
+
+class JoystickReportParser : public HIDReportParser {
+ JoystickEvents *joyEvents;
+
+ uint8_t oldPad[RPT_GEMEPAD_LEN];
+ uint8_t oldHat;
+ uint16_t oldButtons;
+
+public:
+ JoystickReportParser(JoystickEvents *evt);
+
+ virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
+};
+
+#endif // __HIDJOYSTICKRPTPARSER_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHID_desc/USBHID_desc.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHID_desc/USBHID_desc.ino
new file mode 100644
index 000000000..85cfc19a2
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHID_desc/USBHID_desc.ino
@@ -0,0 +1,77 @@
+#include <hid.h>
+#include <hiduniversal.h>
+#include <hidescriptorparser.h>
+#include <usbhub.h>
+#include "pgmstrings.h"
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class HIDUniversal2 : public HIDUniversal
+{
+public:
+ HIDUniversal2(USB *usb) : HIDUniversal(usb) {};
+
+protected:
+ uint8_t OnInitSuccessful();
+};
+
+uint8_t HIDUniversal2::OnInitSuccessful()
+{
+ uint8_t rcode;
+
+ HexDumper<USBReadParser, uint16_t, uint16_t> Hex;
+ ReportDescParser Rpt;
+
+ if ((rcode = GetReportDescr(0, &Hex)))
+ goto FailGetReportDescr1;
+
+ if ((rcode = GetReportDescr(0, &Rpt)))
+ goto FailGetReportDescr2;
+
+ return 0;
+
+FailGetReportDescr1:
+ USBTRACE("GetReportDescr1:");
+ goto Fail;
+
+FailGetReportDescr2:
+ USBTRACE("GetReportDescr2:");
+ goto Fail;
+
+Fail:
+ Serial.println(rcode, HEX);
+ Release();
+ return rcode;
+}
+
+USB Usb;
+//USBHub Hub(&Usb);
+HIDUniversal2 Hid(&Usb);
+UniversalReportParser Uni;
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay( 200 );
+
+ if (!Hid.SetReportParser(0, &Uni))
+ ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1 );
+}
+
+void loop()
+{
+ Usb.Task();
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHID_desc/pgmstrings.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHID_desc/pgmstrings.h
new file mode 100644
index 000000000..bdb0077ec
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/USBHID_desc/pgmstrings.h
@@ -0,0 +1,52 @@
+#if !defined(__PGMSTRINGS_H__)
+#define __PGMSTRINGS_H__
+
+#define LOBYTE(x) ((char*)(&(x)))[0]
+#define HIBYTE(x) ((char*)(&(x)))[1]
+#define BUFSIZE 256 //buffer size
+
+
+/* Print strings in Program Memory */
+const char Gen_Error_str[] PROGMEM = "\r\nRequest error. Error code:\t";
+const char Dev_Header_str[] PROGMEM ="\r\nDevice descriptor: ";
+const char Dev_Length_str[] PROGMEM ="\r\nDescriptor Length:\t";
+const char Dev_Type_str[] PROGMEM ="\r\nDescriptor type:\t";
+const char Dev_Version_str[] PROGMEM ="\r\nUSB version:\t\t";
+const char Dev_Class_str[] PROGMEM ="\r\nDevice class:\t\t";
+const char Dev_Subclass_str[] PROGMEM ="\r\nDevice Subclass:\t";
+const char Dev_Protocol_str[] PROGMEM ="\r\nDevice Protocol:\t";
+const char Dev_Pktsize_str[] PROGMEM ="\r\nMax.packet size:\t";
+const char Dev_Vendor_str[] PROGMEM ="\r\nVendor ID:\t\t";
+const char Dev_Product_str[] PROGMEM ="\r\nProduct ID:\t\t";
+const char Dev_Revision_str[] PROGMEM ="\r\nRevision ID:\t\t";
+const char Dev_Mfg_str[] PROGMEM ="\r\nMfg.string index:\t";
+const char Dev_Prod_str[] PROGMEM ="\r\nProd.string index:\t";
+const char Dev_Serial_str[] PROGMEM ="\r\nSerial number index:\t";
+const char Dev_Nconf_str[] PROGMEM ="\r\nNumber of conf.:\t";
+const char Conf_Trunc_str[] PROGMEM ="Total length truncated to 256 bytes";
+const char Conf_Header_str[] PROGMEM ="\r\nConfiguration descriptor:";
+const char Conf_Totlen_str[] PROGMEM ="\r\nTotal length:\t\t";
+const char Conf_Nint_str[] PROGMEM ="\r\nNum.intf:\t\t";
+const char Conf_Value_str[] PROGMEM ="\r\nConf.value:\t\t";
+const char Conf_String_str[] PROGMEM ="\r\nConf.string:\t\t";
+const char Conf_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char Conf_Pwr_str[] PROGMEM ="\r\nMax.pwr:\t\t";
+const char Int_Header_str[] PROGMEM ="\r\n\r\nInterface descriptor:";
+const char Int_Number_str[] PROGMEM ="\r\nIntf.number:\t\t";
+const char Int_Alt_str[] PROGMEM ="\r\nAlt.:\t\t\t";
+const char Int_Endpoints_str[] PROGMEM ="\r\nEndpoints:\t\t";
+const char Int_Class_str[] PROGMEM ="\r\nIntf. Class:\t\t";
+const char Int_Subclass_str[] PROGMEM ="\r\nIntf. Subclass:\t\t";
+const char Int_Protocol_str[] PROGMEM ="\r\nIntf. Protocol:\t\t";
+const char Int_String_str[] PROGMEM ="\r\nIntf.string:\t\t";
+const char End_Header_str[] PROGMEM ="\r\n\r\nEndpoint descriptor:";
+const char End_Address_str[] PROGMEM ="\r\nEndpoint address:\t";
+const char End_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char End_Pktsize_str[] PROGMEM ="\r\nMax.pkt size:\t\t";
+const char End_Interval_str[] PROGMEM ="\r\nPolling interval:\t";
+const char Unk_Header_str[] PROGMEM = "\r\nUnknown descriptor:";
+const char Unk_Length_str[] PROGMEM ="\r\nLength:\t\t";
+const char Unk_Type_str[] PROGMEM ="\r\nType:\t\t";
+const char Unk_Contents_str[] PROGMEM ="\r\nContents:\t";
+
+#endif // __PGMSTRINGS_H__ \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp.ino
new file mode 100644
index 000000000..837d7f5a7
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp.ino
@@ -0,0 +1,42 @@
+/* Simplified Logitech Extreme 3D Pro Joystick Report Parser */
+
+#include <hid.h>
+#include <hiduniversal.h>
+#include <usbhub.h>
+
+#include "le3dp_rptparser.h"
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+USBHub Hub(&Usb);
+HIDUniversal Hid(&Usb);
+JoystickEvents JoyEvents;
+JoystickReportParser Joy(&JoyEvents);
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay( 200 );
+
+ if (!Hid.SetReportParser(0, &Joy))
+ ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1 );
+}
+
+void loop()
+{
+ Usb.Task();
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp_rptparser.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp_rptparser.cpp
new file mode 100644
index 000000000..baece13b2
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp_rptparser.cpp
@@ -0,0 +1,43 @@
+#include "le3dp_rptparser.h"
+
+JoystickReportParser::JoystickReportParser(JoystickEvents *evt) :
+ joyEvents(evt)
+{}
+
+void JoystickReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
+{
+ bool match = true;
+
+ // Checking if there are changes in report since the method was last called
+ for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) {
+ if( buf[i] != oldPad[i] ) {
+ match = false;
+ break;
+ }
+ }
+ // Calling Game Pad event handler
+ if (!match && joyEvents) {
+ joyEvents->OnGamePadChanged((const GamePadEventData*)buf);
+
+ for (uint8_t i=0; i<RPT_GAMEPAD_LEN; i++) oldPad[i] = buf[i];
+ }
+}
+
+void JoystickEvents::OnGamePadChanged(const GamePadEventData *evt)
+{
+ Serial.print("X: ");
+ PrintHex<uint16_t>(evt->x, 0x80);
+ Serial.print(" Y: ");
+ PrintHex<uint16_t>(evt->y, 0x80);
+ Serial.print(" Hat Switch: ");
+ PrintHex<uint8_t>(evt->hat, 0x80);
+ Serial.print(" Twist: ");
+ PrintHex<uint8_t>(evt->twist, 0x80);
+ Serial.print(" Slider: ");
+ PrintHex<uint8_t>(evt->slider, 0x80);
+ Serial.print(" Buttons A: ");
+ PrintHex<uint8_t>(evt->buttons_a, 0x80);
+ Serial.print(" Buttons B: ");
+ PrintHex<uint8_t>(evt->buttons_b, 0x80);
+ Serial.println("");
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp_rptparser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp_rptparser.h
new file mode 100644
index 000000000..2400364e6
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/le3dp/le3dp_rptparser.h
@@ -0,0 +1,42 @@
+#if !defined(__HIDJOYSTICKRPTPARSER_H__)
+#define __HIDJOYSTICKRPTPARSER_H__
+
+#include <hid.h>
+
+struct GamePadEventData
+{
+ union { //axes and hut switch
+ uint32_t axes;
+ struct {
+ uint32_t x : 10;
+ uint32_t y : 10;
+ uint32_t hat : 4;
+ uint32_t twist : 8;
+ };
+ };
+ uint8_t buttons_a;
+ uint8_t slider;
+ uint8_t buttons_b;
+};
+
+class JoystickEvents
+{
+public:
+ virtual void OnGamePadChanged(const GamePadEventData *evt);
+};
+
+#define RPT_GAMEPAD_LEN sizeof(GamePadEventData)/sizeof(uint8_t)
+
+class JoystickReportParser : public HIDReportParser
+{
+ JoystickEvents *joyEvents;
+
+ uint8_t oldPad[RPT_GAMEPAD_LEN];
+
+public:
+ JoystickReportParser(JoystickEvents *evt);
+
+ virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
+};
+
+#endif // __HIDJOYSTICKRPTPARSER_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale.ino
new file mode 100644
index 000000000..f26ff964d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale.ino
@@ -0,0 +1,51 @@
+/* Digital Scale Output. Written for Stamps.com Model 510 */
+/* 5lb Digital Scale; any HID scale with Usage page 0x8d should work */
+
+#include <hid.h>
+#include <hiduniversal.h>
+#include <usbhub.h>
+
+#include "scale_rptparser.h"
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+USBHub Hub(&Usb);
+HIDUniversal Hid(&Usb);
+Max_LCD LCD(&Usb);
+ScaleEvents ScaleEvents(&LCD);
+ScaleReportParser Scale(&ScaleEvents);
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ // set up the LCD's number of rows and columns:
+ LCD.begin(16, 2);
+ LCD.clear();
+ LCD.home();
+ LCD.setCursor(0,0);
+ LCD.write('R');
+
+ delay( 200 );
+
+ if (!Hid.SetReportParser(0, &Scale))
+ ErrorMessage<uint8_t>(PSTR("SetReportParser"), 1 );
+}
+
+void loop()
+{
+ Usb.Task();
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale_rptparser.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale_rptparser.cpp
new file mode 100644
index 000000000..01ed980cf
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale_rptparser.cpp
@@ -0,0 +1,150 @@
+/* Parser for standard HID scale (usage page 0x8d) data input report (ID 3) */
+#include "scale_rptparser.h"
+
+const char* UNITS[13] = {
+ "units", // unknown unit
+ "mg", // milligram
+ "g", // gram
+ "kg", // kilogram
+ "cd", // carat
+ "taels", // lian
+ "gr", // grain
+ "dwt", // pennyweight
+ "tonnes", // metric tons
+ "tons", // avoir ton
+ "ozt", // troy ounce
+ "oz", // ounce
+ "lbs" // pound
+};
+
+ScaleReportParser::ScaleReportParser(ScaleEvents *evt) :
+ scaleEvents(evt)
+{}
+
+void ScaleReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
+{
+ bool match = true;
+
+ // Checking if there are changes in report since the method was last called
+ for (uint8_t i=0; i<RPT_SCALE_LEN; i++) {
+ if( buf[i] != oldScale[i] ) {
+ match = false;
+ break;
+ }
+ }
+ // Calling Game Pad event handler
+ if (!match && scaleEvents) {
+ scaleEvents->OnScaleChanged((const ScaleEventData*)buf);
+
+ for (uint8_t i=0; i<RPT_SCALE_LEN; i++) oldScale[i] = buf[i];
+ }
+}
+
+ScaleEvents::ScaleEvents( Max_LCD* pLCD ) :
+
+ pLcd( pLCD )
+
+{}
+
+void ScaleEvents::LcdPrint( const char* str )
+{
+
+ while( *str ) {
+
+ pLcd->write( *str++ );
+
+ }
+}
+
+void ScaleEvents::OnScaleChanged(const ScaleEventData *evt)
+{
+
+ pLcd->clear();
+ pLcd->home();
+ pLcd->setCursor(0,0);
+
+ if( evt->reportID != 3 ) {
+
+ const char inv_report[]="Invalid report!";
+
+ Serial.println(inv_report);
+ LcdPrint(inv_report);
+
+ return;
+
+ }//if( evt->reportID != 3...
+
+ switch( evt->status ) {
+
+ case REPORT_FAULT:
+ Serial.println(F("Report fault"));
+ break;
+
+ case ZEROED:
+ Serial.println(F("Scale zero set"));
+ break;
+
+ case WEIGHING: {
+
+ const char progress[] = "Weighing...";
+ Serial.println(progress);
+ LcdPrint(progress);
+ break;
+ }
+
+ case WEIGHT_VALID: {
+
+ char buf[10];
+ double weight = evt->weight * pow( 10, evt->exp );
+
+
+
+ Serial.print(F("Weight: "));
+ Serial.print( weight );
+ Serial.print(F(" "));
+ Serial.println( UNITS[ evt->unit ]);
+
+ LcdPrint("Weight: ");
+ dtostrf( weight, 4, 2, buf );
+ LcdPrint( buf );
+ LcdPrint( UNITS[ evt->unit ]);
+
+ break;
+
+ }//case WEIGHT_VALID...
+
+ case WEIGHT_NEGATIVE: {
+
+ const char negweight[] = "Negative weight";
+ Serial.println(negweight);
+ LcdPrint(negweight);
+ break;
+ }
+
+ case OVERWEIGHT: {
+
+ const char overweight[] = "Max.weight reached";
+ Serial.println(overweight);
+ LcdPrint( overweight );
+ break;
+ }
+
+ case CALIBRATE_ME:
+
+ Serial.println(F("Scale calibration required"));
+ break;
+
+ case ZERO_ME:
+
+ Serial.println(F("Scale zeroing required"));
+ break;
+
+ default:
+
+ Serial.print(F("Undefined status code: "));
+ Serial.println( evt->status );
+ break;
+
+ }//switch( evt->status...
+
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale_rptparser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale_rptparser.h
new file mode 100644
index 000000000..57fbb033b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/HID/scale/scale_rptparser.h
@@ -0,0 +1,55 @@
+#if !defined(__SCALERPTPARSER_H__)
+#define __SCALERPTPARSER_H__
+
+#include <max_LCD.h>
+#include <hid.h>
+
+/* Scale status constants */
+#define REPORT_FAULT 0x01
+#define ZEROED 0x02
+#define WEIGHING 0x03
+#define WEIGHT_VALID 0x04
+#define WEIGHT_NEGATIVE 0x05
+#define OVERWEIGHT 0x06
+#define CALIBRATE_ME 0x07
+#define ZERO_ME 0x08
+
+/* input data report */
+struct ScaleEventData
+{
+ uint8_t reportID; //must be 3
+ uint8_t status;
+ uint8_t unit;
+ int8_t exp; //scale factor for the weight
+ uint16_t weight; //
+};
+
+class ScaleEvents
+{
+
+ Max_LCD* pLcd;
+
+ void LcdPrint( const char* str );
+
+public:
+
+ ScaleEvents( Max_LCD* pLCD );
+
+ virtual void OnScaleChanged(const ScaleEventData *evt);
+};
+
+#define RPT_SCALE_LEN sizeof(ScaleEventData)/sizeof(uint8_t)
+
+class ScaleReportParser : public HIDReportParser
+{
+ ScaleEvents *scaleEvents;
+
+ uint8_t oldScale[RPT_SCALE_LEN];
+
+public:
+ ScaleReportParser(ScaleEvents *evt);
+
+ virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
+};
+
+#endif // __SCALERPTPARSER_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PS3USB/PS3USB.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PS3USB/PS3USB.ino
new file mode 100644
index 000000000..a53dcfbe6
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PS3USB/PS3USB.ino
@@ -0,0 +1,148 @@
+/*
+ Example sketch for the PS3 USB library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <PS3USB.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+/* You can create the instance of the class in two ways */
+PS3USB PS3(&Usb); // This will just create the instance
+//PS3USB PS3(&Usb,0x00,0x15,0x83,0x3D,0x0A,0x57); // This will also store the bluetooth address - this can be obtained from the dongle when running the sketch
+
+bool printAngle;
+uint8_t state = 0;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nPS3 USB Library Started"));
+}
+void loop() {
+ Usb.Task();
+
+ if (PS3.PS3Connected || PS3.PS3NavigationConnected) {
+ if (PS3.getAnalogHat(LeftHatX) > 137 || PS3.getAnalogHat(LeftHatX) < 117 || PS3.getAnalogHat(LeftHatY) > 137 || PS3.getAnalogHat(LeftHatY) < 117 || PS3.getAnalogHat(RightHatX) > 137 || PS3.getAnalogHat(RightHatX) < 117 || PS3.getAnalogHat(RightHatY) > 137 || PS3.getAnalogHat(RightHatY) < 117) {
+ Serial.print(F("\r\nLeftHatX: "));
+ Serial.print(PS3.getAnalogHat(LeftHatX));
+ Serial.print(F("\tLeftHatY: "));
+ Serial.print(PS3.getAnalogHat(LeftHatY));
+ if (PS3.PS3Connected) { // The Navigation controller only have one joystick
+ Serial.print(F("\tRightHatX: "));
+ Serial.print(PS3.getAnalogHat(RightHatX));
+ Serial.print(F("\tRightHatY: "));
+ Serial.print(PS3.getAnalogHat(RightHatY));
+ }
+ }
+ // Analog button values can be read from almost all buttons
+ if (PS3.getAnalogButton(L2) || PS3.getAnalogButton(R2)) {
+ Serial.print(F("\r\nL2: "));
+ Serial.print(PS3.getAnalogButton(L2));
+ if (!PS3.PS3NavigationConnected) {
+ Serial.print(F("\tR2: "));
+ Serial.print(PS3.getAnalogButton(R2));
+ }
+ }
+ if (PS3.getButtonClick(PS))
+ Serial.print(F("\r\nPS"));
+
+ if (PS3.getButtonClick(TRIANGLE))
+ Serial.print(F("\r\nTraingle"));
+ if (PS3.getButtonClick(CIRCLE))
+ Serial.print(F("\r\nCircle"));
+ if (PS3.getButtonClick(CROSS))
+ Serial.print(F("\r\nCross"));
+ if (PS3.getButtonClick(SQUARE))
+ Serial.print(F("\r\nSquare"));
+
+ if (PS3.getButtonClick(UP)) {
+ Serial.print(F("\r\nUp"));
+ PS3.setLedOff();
+ PS3.setLedOn(LED4);
+ }
+ if (PS3.getButtonClick(RIGHT)) {
+ Serial.print(F("\r\nRight"));
+ PS3.setLedOff();
+ PS3.setLedOn(LED1);
+ }
+ if (PS3.getButtonClick(DOWN)) {
+ Serial.print(F("\r\nDown"));
+ PS3.setLedOff();
+ PS3.setLedOn(LED2);
+ }
+ if (PS3.getButtonClick(LEFT)) {
+ Serial.print(F("\r\nLeft"));
+ PS3.setLedOff();
+ PS3.setLedOn(LED3);
+ }
+
+ if (PS3.getButtonClick(L1))
+ Serial.print(F("\r\nL1"));
+ if (PS3.getButtonClick(L3))
+ Serial.print(F("\r\nL3"));
+ if (PS3.getButtonClick(R1))
+ Serial.print(F("\r\nR1"));
+ if (PS3.getButtonClick(R3))
+ Serial.print(F("\r\nR3"));
+
+ if (PS3.getButtonClick(SELECT)) {
+ Serial.print(F("\r\nSelect - "));
+ PS3.printStatusString();
+ }
+ if (PS3.getButtonClick(START)) {
+ Serial.print(F("\r\nStart"));
+ printAngle = !printAngle;
+ }
+ if (printAngle) {
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(PS3.getAngle(Pitch));
+ Serial.print(F("\tRoll: "));
+ Serial.print(PS3.getAngle(Roll));
+ }
+ }
+ else if (PS3.PS3MoveConnected) { // One can only set the color of the bulb, set the rumble, set and get the bluetooth address and calibrate the magnetometer via USB
+ if (state == 0) {
+ PS3.moveSetRumble(0);
+ PS3.moveSetBulb(Off);
+ } else if (state == 1) {
+ PS3.moveSetRumble(75);
+ PS3.moveSetBulb(Red);
+ } else if (state == 2) {
+ PS3.moveSetRumble(125);
+ PS3.moveSetBulb(Green);
+ } else if (state == 3) {
+ PS3.moveSetRumble(150);
+ PS3.moveSetBulb(Blue);
+ } else if (state == 4) {
+ PS3.moveSetRumble(175);
+ PS3.moveSetBulb(Yellow);
+ } else if (state == 5) {
+ PS3.moveSetRumble(200);
+ PS3.moveSetBulb(Lightblue);
+ } else if (state == 6) {
+ PS3.moveSetRumble(225);
+ PS3.moveSetBulb(Purble);
+ } else if (state == 7) {
+ PS3.moveSetRumble(250);
+ PS3.moveSetBulb(White);
+ }
+
+ state++;
+ if (state > 7)
+ state = 0;
+ delay(1000);
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PS4USB/PS4USB.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PS4USB/PS4USB.ino
new file mode 100644
index 000000000..d0d76790e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PS4USB/PS4USB.ino
@@ -0,0 +1,133 @@
+/*
+ Example sketch for the PS4 USB library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <PS4USB.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+PS4USB PS4(&Usb);
+
+bool printAngle, printTouch;
+uint8_t oldL2Value, oldR2Value;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); // Halt
+ }
+ Serial.print(F("\r\nPS4 USB Library Started"));
+}
+
+void loop() {
+ Usb.Task();
+
+ if (PS4.connected()) {
+ if (PS4.getAnalogHat(LeftHatX) > 137 || PS4.getAnalogHat(LeftHatX) < 117 || PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117 || PS4.getAnalogHat(RightHatX) > 137 || PS4.getAnalogHat(RightHatX) < 117 || PS4.getAnalogHat(RightHatY) > 137 || PS4.getAnalogHat(RightHatY) < 117) {
+ Serial.print(F("\r\nLeftHatX: "));
+ Serial.print(PS4.getAnalogHat(LeftHatX));
+ Serial.print(F("\tLeftHatY: "));
+ Serial.print(PS4.getAnalogHat(LeftHatY));
+ Serial.print(F("\tRightHatX: "));
+ Serial.print(PS4.getAnalogHat(RightHatX));
+ Serial.print(F("\tRightHatY: "));
+ Serial.print(PS4.getAnalogHat(RightHatY));
+ }
+
+ if (PS4.getAnalogButton(L2) || PS4.getAnalogButton(R2)) { // These are the only analog buttons on the PS4 controller
+ Serial.print(F("\r\nL2: "));
+ Serial.print(PS4.getAnalogButton(L2));
+ Serial.print(F("\tR2: "));
+ Serial.print(PS4.getAnalogButton(R2));
+ }
+ if (PS4.getAnalogButton(L2) != oldL2Value || PS4.getAnalogButton(R2) != oldR2Value) // Only write value if it's different
+ PS4.setRumbleOn(PS4.getAnalogButton(L2), PS4.getAnalogButton(R2));
+ oldL2Value = PS4.getAnalogButton(L2);
+ oldR2Value = PS4.getAnalogButton(R2);
+
+ if (PS4.getButtonClick(PS))
+ Serial.print(F("\r\nPS"));
+ if (PS4.getButtonClick(TRIANGLE)) {
+ Serial.print(F("\r\nTraingle"));
+ PS4.setRumbleOn(RumbleLow);
+ }
+ if (PS4.getButtonClick(CIRCLE)) {
+ Serial.print(F("\r\nCircle"));
+ PS4.setRumbleOn(RumbleHigh);
+ }
+ if (PS4.getButtonClick(CROSS)) {
+ Serial.print(F("\r\nCross"));
+ PS4.setLedFlash(10, 10); // Set it to blink rapidly
+ }
+ if (PS4.getButtonClick(SQUARE)) {
+ Serial.print(F("\r\nSquare"));
+ PS4.setLedFlash(0, 0); // Turn off blinking
+ }
+
+ if (PS4.getButtonClick(UP)) {
+ Serial.print(F("\r\nUp"));
+ PS4.setLed(Red);
+ } if (PS4.getButtonClick(RIGHT)) {
+ Serial.print(F("\r\nRight"));
+ PS4.setLed(Blue);
+ } if (PS4.getButtonClick(DOWN)) {
+ Serial.print(F("\r\nDown"));
+ PS4.setLed(Yellow);
+ } if (PS4.getButtonClick(LEFT)) {
+ Serial.print(F("\r\nLeft"));
+ PS4.setLed(Green);
+ }
+
+ if (PS4.getButtonClick(L1))
+ Serial.print(F("\r\nL1"));
+ if (PS4.getButtonClick(L3))
+ Serial.print(F("\r\nL3"));
+ if (PS4.getButtonClick(R1))
+ Serial.print(F("\r\nR1"));
+ if (PS4.getButtonClick(R3))
+ Serial.print(F("\r\nR3"));
+
+ if (PS4.getButtonClick(SHARE))
+ Serial.print(F("\r\nShare"));
+ if (PS4.getButtonClick(OPTIONS)) {
+ Serial.print(F("\r\nOptions"));
+ printAngle = !printAngle;
+ }
+ if (PS4.getButtonClick(TOUCHPAD)) {
+ Serial.print(F("\r\nTouchpad"));
+ printTouch = !printTouch;
+ }
+
+ if (printAngle) { // Print angle calculated using the accelerometer only
+ Serial.print(F("\r\nPitch: "));
+ Serial.print(PS4.getAngle(Pitch));
+ Serial.print(F("\tRoll: "));
+ Serial.print(PS4.getAngle(Roll));
+ }
+
+ if (printTouch) { // Print the x, y coordinates of the touchpad
+ if (PS4.isTouching(0) || PS4.isTouching(1)) // Print newline and carriage return if any of the fingers are touching the touchpad
+ Serial.print(F("\r\n"));
+ for (uint8_t i = 0; i < 2; i++) { // The touchpad track two fingers
+ if (PS4.isTouching(i)) { // Print the position of the finger if it is touching the touchpad
+ Serial.print(F("X")); Serial.print(i + 1); Serial.print(F(": "));
+ Serial.print(PS4.getX(i));
+ Serial.print(F("\tY")); Serial.print(i + 1); Serial.print(F(": "));
+ Serial.print(PS4.getY(i));
+ Serial.print(F("\t"));
+ }
+ }
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PSBuzz/PSBuzz.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PSBuzz/PSBuzz.ino
new file mode 100644
index 000000000..6ee462c1e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/PSBuzz/PSBuzz.ino
@@ -0,0 +1,49 @@
+/*
+ Example sketch for the Playstation Buzz library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <PSBuzz.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+PSBuzz Buzz(&Usb);
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); // Halt
+ }
+ Serial.println(F("\r\nPS Buzz Library Started"));
+}
+
+void loop() {
+ Usb.Task();
+
+ if (Buzz.connected()) {
+ for (uint8_t i = 0; i < 4; i++) {
+ if (Buzz.getButtonClick(RED, i)) {
+ Buzz.setLedToggle(i); // Toggle the LED
+ Serial.println(F("RED"));
+ }
+ if (Buzz.getButtonClick(YELLOW, i))
+ Serial.println(F("YELLOW"));
+ if (Buzz.getButtonClick(GREEN, i))
+ Serial.println(F("GREEN"));
+ if (Buzz.getButtonClick(ORANGE, i))
+ Serial.println(F("ORANGE"));
+ if (Buzz.getButtonClick(BLUE, i))
+ Serial.println(F("BLUE"));
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/USB_desc/USB_desc.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/USB_desc/USB_desc.ino
new file mode 100644
index 000000000..acfe57d37
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/USB_desc/USB_desc.ino
@@ -0,0 +1,349 @@
+#include <usbhub.h>
+
+#include "pgmstrings.h"
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub1(&Usb);
+//USBHub Hub2(&Usb);
+//USBHub Hub3(&Usb);
+//USBHub Hub4(&Usb);
+//USBHub Hub5(&Usb);
+//USBHub Hub6(&Usb);
+//USBHub Hub7(&Usb);
+
+uint32_t next_time;
+
+void PrintAllAddresses(UsbDevice *pdev)
+{
+ UsbDeviceAddress adr;
+ adr.devAddress = pdev->address.devAddress;
+ Serial.print("\r\nAddr:");
+ Serial.print(adr.devAddress, HEX);
+ Serial.print("(");
+ Serial.print(adr.bmHub, HEX);
+ Serial.print(".");
+ Serial.print(adr.bmParent, HEX);
+ Serial.print(".");
+ Serial.print(adr.bmAddress, HEX);
+ Serial.println(")");
+}
+
+void PrintAddress(uint8_t addr)
+{
+ UsbDeviceAddress adr;
+ adr.devAddress = addr;
+ Serial.print("\r\nADDR:\t");
+ Serial.println(adr.devAddress, HEX);
+ Serial.print("DEV:\t");
+ Serial.println(adr.bmAddress, HEX);
+ Serial.print("PRNT:\t");
+ Serial.println(adr.bmParent, HEX);
+ Serial.print("HUB:\t");
+ Serial.println(adr.bmHub, HEX);
+}
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay( 200 );
+
+ next_time = millis() + 10000;
+}
+
+byte getdevdescr( byte addr, byte &num_conf );
+
+void PrintDescriptors(uint8_t addr)
+{
+ uint8_t rcode = 0;
+ byte num_conf = 0;
+
+ rcode = getdevdescr( (byte)addr, num_conf );
+ if ( rcode )
+ {
+ printProgStr(Gen_Error_str);
+ print_hex( rcode, 8 );
+ }
+ Serial.print("\r\n");
+
+ for (int i = 0; i < num_conf; i++)
+ {
+ rcode = getconfdescr( addr, i ); // get configuration descriptor
+ if ( rcode )
+ {
+ printProgStr(Gen_Error_str);
+ print_hex(rcode, 8);
+ }
+ Serial.println("\r\n");
+ }
+}
+
+void PrintAllDescriptors(UsbDevice *pdev)
+{
+ Serial.println("\r\n");
+ print_hex(pdev->address.devAddress, 8);
+ Serial.println("\r\n--");
+ PrintDescriptors( pdev->address.devAddress );
+}
+
+void loop()
+{
+ Usb.Task();
+
+ if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
+ {
+ //if (millis() >= next_time)
+ {
+ Usb.ForEachUsbDevice(&PrintAllDescriptors);
+ Usb.ForEachUsbDevice(&PrintAllAddresses);
+
+ while ( 1 ); //stop
+ }
+ }
+}
+
+byte getdevdescr( byte addr, byte &num_conf )
+{
+ USB_DEVICE_DESCRIPTOR buf;
+ byte rcode;
+ rcode = Usb.getDevDescr( addr, 0, 0x12, ( uint8_t *)&buf );
+ if ( rcode ) {
+ return ( rcode );
+ }
+ printProgStr(Dev_Header_str);
+ printProgStr(Dev_Length_str);
+ print_hex( buf.bLength, 8 );
+ printProgStr(Dev_Type_str);
+ print_hex( buf.bDescriptorType, 8 );
+ printProgStr(Dev_Version_str);
+ print_hex( buf.bcdUSB, 16 );
+ printProgStr(Dev_Class_str);
+ print_hex( buf.bDeviceClass, 8 );
+ printProgStr(Dev_Subclass_str);
+ print_hex( buf.bDeviceSubClass, 8 );
+ printProgStr(Dev_Protocol_str);
+ print_hex( buf.bDeviceProtocol, 8 );
+ printProgStr(Dev_Pktsize_str);
+ print_hex( buf.bMaxPacketSize0, 8 );
+ printProgStr(Dev_Vendor_str);
+ print_hex( buf.idVendor, 16 );
+ printProgStr(Dev_Product_str);
+ print_hex( buf.idProduct, 16 );
+ printProgStr(Dev_Revision_str);
+ print_hex( buf.bcdDevice, 16 );
+ printProgStr(Dev_Mfg_str);
+ print_hex( buf.iManufacturer, 8 );
+ printProgStr(Dev_Prod_str);
+ print_hex( buf.iProduct, 8 );
+ printProgStr(Dev_Serial_str);
+ print_hex( buf.iSerialNumber, 8 );
+ printProgStr(Dev_Nconf_str);
+ print_hex( buf.bNumConfigurations, 8 );
+ num_conf = buf.bNumConfigurations;
+ return ( 0 );
+}
+
+void printhubdescr(uint8_t *descrptr, uint8_t addr)
+{
+ HubDescriptor *pHub = (HubDescriptor*) descrptr;
+ uint8_t len = *((uint8_t*)descrptr);
+
+ printProgStr(PSTR("\r\n\r\nHub Descriptor:\r\n"));
+ printProgStr(PSTR("bDescLength:\t\t"));
+ Serial.println(pHub->bDescLength, HEX);
+
+ printProgStr(PSTR("bDescriptorType:\t"));
+ Serial.println(pHub->bDescriptorType, HEX);
+
+ printProgStr(PSTR("bNbrPorts:\t\t"));
+ Serial.println(pHub->bNbrPorts, HEX);
+
+ printProgStr(PSTR("LogPwrSwitchMode:\t"));
+ Serial.println(pHub->LogPwrSwitchMode, BIN);
+
+ printProgStr(PSTR("CompoundDevice:\t\t"));
+ Serial.println(pHub->CompoundDevice, BIN);
+
+ printProgStr(PSTR("OverCurrentProtectMode:\t"));
+ Serial.println(pHub->OverCurrentProtectMode, BIN);
+
+ printProgStr(PSTR("TTThinkTime:\t\t"));
+ Serial.println(pHub->TTThinkTime, BIN);
+
+ printProgStr(PSTR("PortIndicatorsSupported:"));
+ Serial.println(pHub->PortIndicatorsSupported, BIN);
+
+ printProgStr(PSTR("Reserved:\t\t"));
+ Serial.println(pHub->Reserved, HEX);
+
+ printProgStr(PSTR("bPwrOn2PwrGood:\t\t"));
+ Serial.println(pHub->bPwrOn2PwrGood, HEX);
+
+ printProgStr(PSTR("bHubContrCurrent:\t"));
+ Serial.println(pHub->bHubContrCurrent, HEX);
+
+ for (uint8_t i = 7; i < len; i++)
+ print_hex(descrptr[i], 8);
+
+ //for (uint8_t i=1; i<=pHub->bNbrPorts; i++)
+ // PrintHubPortStatus(&Usb, addr, i, 1);
+}
+
+byte getconfdescr( byte addr, byte conf )
+{
+ uint8_t buf[ BUFSIZE ];
+ uint8_t* buf_ptr = buf;
+ byte rcode;
+ byte descr_length;
+ byte descr_type;
+ unsigned int total_length;
+ rcode = Usb.getConfDescr( addr, 0, 4, conf, buf ); //get total length
+ LOBYTE( total_length ) = buf[ 2 ];
+ HIBYTE( total_length ) = buf[ 3 ];
+ if ( total_length > 256 ) { //check if total length is larger than buffer
+ printProgStr(Conf_Trunc_str);
+ total_length = 256;
+ }
+ rcode = Usb.getConfDescr( addr, 0, total_length, conf, buf ); //get the whole descriptor
+ while ( buf_ptr < buf + total_length ) { //parsing descriptors
+ descr_length = *( buf_ptr );
+ descr_type = *( buf_ptr + 1 );
+ switch ( descr_type ) {
+ case ( USB_DESCRIPTOR_CONFIGURATION ):
+ printconfdescr( buf_ptr );
+ break;
+ case ( USB_DESCRIPTOR_INTERFACE ):
+ printintfdescr( buf_ptr );
+ break;
+ case ( USB_DESCRIPTOR_ENDPOINT ):
+ printepdescr( buf_ptr );
+ break;
+ case 0x29:
+ printhubdescr( buf_ptr, addr );
+ break;
+ default:
+ printunkdescr( buf_ptr );
+ break;
+ }//switch( descr_type
+ buf_ptr = ( buf_ptr + descr_length ); //advance buffer pointer
+ }//while( buf_ptr <=...
+ return ( rcode );
+}
+/* prints hex numbers with leading zeroes */
+// copyright, Peter H Anderson, Baltimore, MD, Nov, '07
+// source: http://www.phanderson.com/arduino/arduino_display.html
+void print_hex(int v, int num_places)
+{
+ int mask = 0, n, num_nibbles, digit;
+
+ for (n = 1; n <= num_places; n++) {
+ mask = (mask << 1) | 0x0001;
+ }
+ v = v & mask; // truncate v to specified number of places
+
+ num_nibbles = num_places / 4;
+ if ((num_places % 4) != 0) {
+ ++num_nibbles;
+ }
+ do {
+ digit = ((v >> (num_nibbles - 1) * 4)) & 0x0f;
+ Serial.print(digit, HEX);
+ }
+ while (--num_nibbles);
+}
+/* function to print configuration descriptor */
+void printconfdescr( uint8_t* descr_ptr )
+{
+ USB_CONFIGURATION_DESCRIPTOR* conf_ptr = ( USB_CONFIGURATION_DESCRIPTOR* )descr_ptr;
+ printProgStr(Conf_Header_str);
+ printProgStr(Conf_Totlen_str);
+ print_hex( conf_ptr->wTotalLength, 16 );
+ printProgStr(Conf_Nint_str);
+ print_hex( conf_ptr->bNumInterfaces, 8 );
+ printProgStr(Conf_Value_str);
+ print_hex( conf_ptr->bConfigurationValue, 8 );
+ printProgStr(Conf_String_str);
+ print_hex( conf_ptr->iConfiguration, 8 );
+ printProgStr(Conf_Attr_str);
+ print_hex( conf_ptr->bmAttributes, 8 );
+ printProgStr(Conf_Pwr_str);
+ print_hex( conf_ptr->bMaxPower, 8 );
+ return;
+}
+/* function to print interface descriptor */
+void printintfdescr( uint8_t* descr_ptr )
+{
+ USB_INTERFACE_DESCRIPTOR* intf_ptr = ( USB_INTERFACE_DESCRIPTOR* )descr_ptr;
+ printProgStr(Int_Header_str);
+ printProgStr(Int_Number_str);
+ print_hex( intf_ptr->bInterfaceNumber, 8 );
+ printProgStr(Int_Alt_str);
+ print_hex( intf_ptr->bAlternateSetting, 8 );
+ printProgStr(Int_Endpoints_str);
+ print_hex( intf_ptr->bNumEndpoints, 8 );
+ printProgStr(Int_Class_str);
+ print_hex( intf_ptr->bInterfaceClass, 8 );
+ printProgStr(Int_Subclass_str);
+ print_hex( intf_ptr->bInterfaceSubClass, 8 );
+ printProgStr(Int_Protocol_str);
+ print_hex( intf_ptr->bInterfaceProtocol, 8 );
+ printProgStr(Int_String_str);
+ print_hex( intf_ptr->iInterface, 8 );
+ return;
+}
+/* function to print endpoint descriptor */
+void printepdescr( uint8_t* descr_ptr )
+{
+ USB_ENDPOINT_DESCRIPTOR* ep_ptr = ( USB_ENDPOINT_DESCRIPTOR* )descr_ptr;
+ printProgStr(End_Header_str);
+ printProgStr(End_Address_str);
+ print_hex( ep_ptr->bEndpointAddress, 8 );
+ printProgStr(End_Attr_str);
+ print_hex( ep_ptr->bmAttributes, 8 );
+ printProgStr(End_Pktsize_str);
+ print_hex( ep_ptr->wMaxPacketSize, 16 );
+ printProgStr(End_Interval_str);
+ print_hex( ep_ptr->bInterval, 8 );
+
+ return;
+}
+/*function to print unknown descriptor */
+void printunkdescr( uint8_t* descr_ptr )
+{
+ byte length = *descr_ptr;
+ byte i;
+ printProgStr(Unk_Header_str);
+ printProgStr(Unk_Length_str);
+ print_hex( *descr_ptr, 8 );
+ printProgStr(Unk_Type_str);
+ print_hex( *(descr_ptr + 1 ), 8 );
+ printProgStr(Unk_Contents_str);
+ descr_ptr += 2;
+ for ( i = 0; i < length; i++ ) {
+ print_hex( *descr_ptr, 8 );
+ descr_ptr++;
+ }
+}
+
+
+/* Print a string from Program Memory directly to save RAM */
+void printProgStr(const char* str)
+{
+ char c;
+ if (!str) return;
+ while ((c = pgm_read_byte(str++)))
+ Serial.print(c);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/USB_desc/pgmstrings.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/USB_desc/pgmstrings.h
new file mode 100644
index 000000000..bdb0077ec
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/USB_desc/pgmstrings.h
@@ -0,0 +1,52 @@
+#if !defined(__PGMSTRINGS_H__)
+#define __PGMSTRINGS_H__
+
+#define LOBYTE(x) ((char*)(&(x)))[0]
+#define HIBYTE(x) ((char*)(&(x)))[1]
+#define BUFSIZE 256 //buffer size
+
+
+/* Print strings in Program Memory */
+const char Gen_Error_str[] PROGMEM = "\r\nRequest error. Error code:\t";
+const char Dev_Header_str[] PROGMEM ="\r\nDevice descriptor: ";
+const char Dev_Length_str[] PROGMEM ="\r\nDescriptor Length:\t";
+const char Dev_Type_str[] PROGMEM ="\r\nDescriptor type:\t";
+const char Dev_Version_str[] PROGMEM ="\r\nUSB version:\t\t";
+const char Dev_Class_str[] PROGMEM ="\r\nDevice class:\t\t";
+const char Dev_Subclass_str[] PROGMEM ="\r\nDevice Subclass:\t";
+const char Dev_Protocol_str[] PROGMEM ="\r\nDevice Protocol:\t";
+const char Dev_Pktsize_str[] PROGMEM ="\r\nMax.packet size:\t";
+const char Dev_Vendor_str[] PROGMEM ="\r\nVendor ID:\t\t";
+const char Dev_Product_str[] PROGMEM ="\r\nProduct ID:\t\t";
+const char Dev_Revision_str[] PROGMEM ="\r\nRevision ID:\t\t";
+const char Dev_Mfg_str[] PROGMEM ="\r\nMfg.string index:\t";
+const char Dev_Prod_str[] PROGMEM ="\r\nProd.string index:\t";
+const char Dev_Serial_str[] PROGMEM ="\r\nSerial number index:\t";
+const char Dev_Nconf_str[] PROGMEM ="\r\nNumber of conf.:\t";
+const char Conf_Trunc_str[] PROGMEM ="Total length truncated to 256 bytes";
+const char Conf_Header_str[] PROGMEM ="\r\nConfiguration descriptor:";
+const char Conf_Totlen_str[] PROGMEM ="\r\nTotal length:\t\t";
+const char Conf_Nint_str[] PROGMEM ="\r\nNum.intf:\t\t";
+const char Conf_Value_str[] PROGMEM ="\r\nConf.value:\t\t";
+const char Conf_String_str[] PROGMEM ="\r\nConf.string:\t\t";
+const char Conf_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char Conf_Pwr_str[] PROGMEM ="\r\nMax.pwr:\t\t";
+const char Int_Header_str[] PROGMEM ="\r\n\r\nInterface descriptor:";
+const char Int_Number_str[] PROGMEM ="\r\nIntf.number:\t\t";
+const char Int_Alt_str[] PROGMEM ="\r\nAlt.:\t\t\t";
+const char Int_Endpoints_str[] PROGMEM ="\r\nEndpoints:\t\t";
+const char Int_Class_str[] PROGMEM ="\r\nIntf. Class:\t\t";
+const char Int_Subclass_str[] PROGMEM ="\r\nIntf. Subclass:\t\t";
+const char Int_Protocol_str[] PROGMEM ="\r\nIntf. Protocol:\t\t";
+const char Int_String_str[] PROGMEM ="\r\nIntf.string:\t\t";
+const char End_Header_str[] PROGMEM ="\r\n\r\nEndpoint descriptor:";
+const char End_Address_str[] PROGMEM ="\r\nEndpoint address:\t";
+const char End_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char End_Pktsize_str[] PROGMEM ="\r\nMax.pkt size:\t\t";
+const char End_Interval_str[] PROGMEM ="\r\nPolling interval:\t";
+const char Unk_Header_str[] PROGMEM = "\r\nUnknown descriptor:";
+const char Unk_Length_str[] PROGMEM ="\r\nLength:\t\t";
+const char Unk_Type_str[] PROGMEM ="\r\nType:\t\t";
+const char Unk_Contents_str[] PROGMEM ="\r\nContents:\t";
+
+#endif // __PGMSTRINGS_H__ \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXOLD/XBOXOLD.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXOLD/XBOXOLD.ino
new file mode 100644
index 000000000..64a3ed612
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXOLD/XBOXOLD.ino
@@ -0,0 +1,110 @@
+/*
+ Example sketch for the original Xbox library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <XBOXOLD.h>
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+USBHub Hub1(&Usb); // The controller has a built in hub, so this instance is needed
+XBOXOLD Xbox(&Usb);
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); // halt
+ }
+ Serial.print(F("\r\nXBOX Library Started"));
+}
+void loop() {
+ Usb.Task();
+ if (Xbox.XboxConnected) {
+ if (Xbox.getButtonPress(BLACK) || Xbox.getButtonPress(WHITE)) {
+ Serial.print("BLACK: ");
+ Serial.print(Xbox.getButtonPress(BLACK));
+ Serial.print("\tWHITE: ");
+ Serial.println(Xbox.getButtonPress(WHITE));
+ Xbox.setRumbleOn(Xbox.getButtonPress(BLACK), Xbox.getButtonPress(WHITE));
+ } else
+ Xbox.setRumbleOn(0, 0);
+
+ if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500 || Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500 || Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500 || Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
+ if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500) {
+ Serial.print(F("LeftHatX: "));
+ Serial.print(Xbox.getAnalogHat(LeftHatX));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500) {
+ Serial.print(F("LeftHatY: "));
+ Serial.print(Xbox.getAnalogHat(LeftHatY));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500) {
+ Serial.print(F("RightHatX: "));
+ Serial.print(Xbox.getAnalogHat(RightHatX));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
+ Serial.print(F("RightHatY: "));
+ Serial.print(Xbox.getAnalogHat(RightHatY));
+ }
+ Serial.println();
+ }
+
+ if (Xbox.getButtonClick(UP))
+ Serial.println(F("Up"));
+ if (Xbox.getButtonClick(DOWN))
+ Serial.println(F("Down"));
+ if (Xbox.getButtonClick(LEFT))
+ Serial.println(F("Left"));
+ if (Xbox.getButtonClick(RIGHT))
+ Serial.println(F("Right"));
+
+ if (Xbox.getButtonClick(START))
+ Serial.println(F("Start"));
+ if (Xbox.getButtonClick(BACK))
+ Serial.println(F("Back"));
+ if (Xbox.getButtonClick(L3))
+ Serial.println(F("L3"));
+ if (Xbox.getButtonClick(R3))
+ Serial.println(F("R3"));
+
+ if (Xbox.getButtonPress(A)) {
+ Serial.print(F("A: "));
+ Serial.println(Xbox.getButtonPress(A));
+ }
+ if (Xbox.getButtonPress(B)) {
+ Serial.print(F("B: "));
+ Serial.println(Xbox.getButtonPress(B));
+ }
+ if (Xbox.getButtonPress(X)) {
+ Serial.print(F("X: "));
+ Serial.println(Xbox.getButtonPress(X));
+ }
+ if (Xbox.getButtonPress(Y)) {
+ Serial.print(F("Y: "));
+ Serial.println(Xbox.getButtonPress(Y));
+ }
+ if (Xbox.getButtonPress(L1)) {
+ Serial.print(F("L1: "));
+ Serial.println(Xbox.getButtonPress(L1));
+ }
+ if (Xbox.getButtonPress(R1)) {
+ Serial.print(F("R1: "));
+ Serial.println(Xbox.getButtonPress(R1));
+ }
+ }
+ delay(1);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXONE/XBOXONE.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXONE/XBOXONE.ino
new file mode 100644
index 000000000..9526f53d1
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXONE/XBOXONE.ino
@@ -0,0 +1,106 @@
+/*
+ Example sketch for the Xbox ONE USB library - by guruthree, based on work by
+ Kristian Lauszus.
+ */
+
+#include <XBOXONE.h>
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#endif
+
+USB Usb;
+XBOXONE Xbox(&Usb);
+
+void setup() {
+ Serial.begin(115200);
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nXBOX USB Library Started"));
+}
+void loop() {
+ Usb.Task();
+ if (Xbox.XboxOneConnected) {
+ if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500 || Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500 || Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500 || Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
+ if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500) {
+ Serial.print(F("LeftHatX: "));
+ Serial.print(Xbox.getAnalogHat(LeftHatX));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500) {
+ Serial.print(F("LeftHatY: "));
+ Serial.print(Xbox.getAnalogHat(LeftHatY));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500) {
+ Serial.print(F("RightHatX: "));
+ Serial.print(Xbox.getAnalogHat(RightHatX));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
+ Serial.print(F("RightHatY: "));
+ Serial.print(Xbox.getAnalogHat(RightHatY));
+ }
+ Serial.println();
+ }
+
+ if (Xbox.getButtonPress(L2) > 0 || Xbox.getButtonPress(R2) > 0) {
+ if (Xbox.getButtonPress(L2) > 0) {
+ Serial.print(F("L2: "));
+ Serial.print(Xbox.getButtonPress(L2));
+ Serial.print("\t");
+ }
+ if (Xbox.getButtonPress(R2) > 0) {
+ Serial.print(F("R2: "));
+ Serial.print(Xbox.getButtonPress(R2));
+ Serial.print("\t");
+ }
+ Serial.println();
+ }
+
+ if (Xbox.getButtonClick(UP))
+ Serial.println(F("Up"));
+ if (Xbox.getButtonClick(DOWN))
+ Serial.println(F("Down"));
+ if (Xbox.getButtonClick(LEFT))
+ Serial.println(F("Left"));
+ if (Xbox.getButtonClick(RIGHT))
+ Serial.println(F("Right"));
+
+ if (Xbox.getButtonClick(START))
+ Serial.println(F("Start"));
+ if (Xbox.getButtonClick(BACK))
+ Serial.println(F("Back"));
+ if (Xbox.getButtonClick(XBOX))
+ Serial.println(F("Xbox"));
+ if (Xbox.getButtonClick(SYNC))
+ Serial.println(F("Sync"));
+
+ if (Xbox.getButtonClick(L1))
+ Serial.println(F("L1"));
+ if (Xbox.getButtonClick(R1))
+ Serial.println(F("R1"));
+ if (Xbox.getButtonClick(L2))
+ Serial.println(F("L2"));
+ if (Xbox.getButtonClick(R2))
+ Serial.println(F("R2"));
+ if (Xbox.getButtonClick(L3))
+ Serial.println(F("L3"));
+ if (Xbox.getButtonClick(R3))
+ Serial.println(F("R3"));
+
+
+ if (Xbox.getButtonClick(A))
+ Serial.println(F("A"));
+ if (Xbox.getButtonClick(B))
+ Serial.println(F("B"));
+ if (Xbox.getButtonClick(X))
+ Serial.println(F("X"));
+ if (Xbox.getButtonClick(Y))
+ Serial.println(F("Y"));
+ }
+ delay(1);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXRECV/XBOXRECV.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXRECV/XBOXRECV.ino
new file mode 100644
index 000000000..491b287e4
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXRECV/XBOXRECV.ino
@@ -0,0 +1,122 @@
+/*
+ Example sketch for the Xbox Wireless Reciver library - developed by Kristian Lauszus
+ It supports up to four controllers wirelessly
+ For more information see the blog post: http://blog.tkjelectronics.dk/2012/12/xbox-360-receiver-added-to-the-usb-host-library/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <XBOXRECV.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+XBOXRECV Xbox(&Usb);
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nXbox Wireless Receiver Library Started"));
+}
+void loop() {
+ Usb.Task();
+ if (Xbox.XboxReceiverConnected) {
+ for (uint8_t i = 0; i < 4; i++) {
+ if (Xbox.Xbox360Connected[i]) {
+ if (Xbox.getButtonPress(L2, i) || Xbox.getButtonPress(R2, i)) {
+ Serial.print("L2: ");
+ Serial.print(Xbox.getButtonPress(L2, i));
+ Serial.print("\tR2: ");
+ Serial.println(Xbox.getButtonPress(R2, i));
+ Xbox.setRumbleOn(Xbox.getButtonPress(L2, i), Xbox.getButtonPress(R2, i), i);
+ }
+
+ if (Xbox.getAnalogHat(LeftHatX, i) > 7500 || Xbox.getAnalogHat(LeftHatX, i) < -7500 || Xbox.getAnalogHat(LeftHatY, i) > 7500 || Xbox.getAnalogHat(LeftHatY, i) < -7500 || Xbox.getAnalogHat(RightHatX, i) > 7500 || Xbox.getAnalogHat(RightHatX, i) < -7500 || Xbox.getAnalogHat(RightHatY, i) > 7500 || Xbox.getAnalogHat(RightHatY, i) < -7500) {
+ if (Xbox.getAnalogHat(LeftHatX, i) > 7500 || Xbox.getAnalogHat(LeftHatX, i) < -7500) {
+ Serial.print(F("LeftHatX: "));
+ Serial.print(Xbox.getAnalogHat(LeftHatX, i));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(LeftHatY, i) > 7500 || Xbox.getAnalogHat(LeftHatY, i) < -7500) {
+ Serial.print(F("LeftHatY: "));
+ Serial.print(Xbox.getAnalogHat(LeftHatY, i));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(RightHatX, i) > 7500 || Xbox.getAnalogHat(RightHatX, i) < -7500) {
+ Serial.print(F("RightHatX: "));
+ Serial.print(Xbox.getAnalogHat(RightHatX, i));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(RightHatY, i) > 7500 || Xbox.getAnalogHat(RightHatY, i) < -7500) {
+ Serial.print(F("RightHatY: "));
+ Serial.print(Xbox.getAnalogHat(RightHatY, i));
+ }
+ Serial.println();
+ }
+
+ if (Xbox.getButtonClick(UP, i)) {
+ Xbox.setLedOn(LED1, i);
+ Serial.println(F("Up"));
+ }
+ if (Xbox.getButtonClick(DOWN, i)) {
+ Xbox.setLedOn(LED4, i);
+ Serial.println(F("Down"));
+ }
+ if (Xbox.getButtonClick(LEFT, i)) {
+ Xbox.setLedOn(LED3, i);
+ Serial.println(F("Left"));
+ }
+ if (Xbox.getButtonClick(RIGHT, i)) {
+ Xbox.setLedOn(LED2, i);
+ Serial.println(F("Right"));
+ }
+
+ if (Xbox.getButtonClick(START, i)) {
+ Xbox.setLedMode(ALTERNATING, i);
+ Serial.println(F("Start"));
+ }
+ if (Xbox.getButtonClick(BACK, i)) {
+ Xbox.setLedBlink(ALL, i);
+ Serial.println(F("Back"));
+ }
+ if (Xbox.getButtonClick(L3, i))
+ Serial.println(F("L3"));
+ if (Xbox.getButtonClick(R3, i))
+ Serial.println(F("R3"));
+
+ if (Xbox.getButtonClick(L1, i))
+ Serial.println(F("L1"));
+ if (Xbox.getButtonClick(R1, i))
+ Serial.println(F("R1"));
+ if (Xbox.getButtonClick(XBOX, i)) {
+ Xbox.setLedMode(ROTATING, i);
+ Serial.print(F("Xbox (Battery: "));
+ Serial.print(Xbox.getBatteryLevel(i)); // The battery level in the range 0-3
+ Serial.println(F(")"));
+ }
+ if (Xbox.getButtonClick(SYNC, i)) {
+ Serial.println(F("Sync"));
+ Xbox.disconnect(i);
+ }
+
+ if (Xbox.getButtonClick(A, i))
+ Serial.println(F("A"));
+ if (Xbox.getButtonClick(B, i))
+ Serial.println(F("B"));
+ if (Xbox.getButtonClick(X, i))
+ Serial.println(F("X"));
+ if (Xbox.getButtonClick(Y, i))
+ Serial.println(F("Y"));
+ }
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXUSB/XBOXUSB.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXUSB/XBOXUSB.ino
new file mode 100644
index 000000000..8a5691c6e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/Xbox/XBOXUSB/XBOXUSB.ino
@@ -0,0 +1,113 @@
+/*
+ Example sketch for the Xbox 360 USB library - developed by Kristian Lauszus
+ For more information visit my blog: http://blog.tkjelectronics.dk/ or
+ send me an e-mail: kristianl@tkjelectronics.com
+ */
+
+#include <XBOXUSB.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+XBOXUSB Xbox(&Usb);
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print(F("\r\nOSC did not start"));
+ while (1); //halt
+ }
+ Serial.print(F("\r\nXBOX USB Library Started"));
+}
+void loop() {
+ Usb.Task();
+ if (Xbox.Xbox360Connected) {
+ if (Xbox.getButtonPress(L2) || Xbox.getButtonPress(R2)) {
+ Serial.print("L2: ");
+ Serial.print(Xbox.getButtonPress(L2));
+ Serial.print("\tR2: ");
+ Serial.println(Xbox.getButtonPress(R2));
+ Xbox.setRumbleOn(Xbox.getButtonPress(L2), Xbox.getButtonPress(R2));
+ } else
+ Xbox.setRumbleOn(0, 0);
+
+ if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500 || Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500 || Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500 || Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
+ if (Xbox.getAnalogHat(LeftHatX) > 7500 || Xbox.getAnalogHat(LeftHatX) < -7500) {
+ Serial.print(F("LeftHatX: "));
+ Serial.print(Xbox.getAnalogHat(LeftHatX));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(LeftHatY) > 7500 || Xbox.getAnalogHat(LeftHatY) < -7500) {
+ Serial.print(F("LeftHatY: "));
+ Serial.print(Xbox.getAnalogHat(LeftHatY));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(RightHatX) > 7500 || Xbox.getAnalogHat(RightHatX) < -7500) {
+ Serial.print(F("RightHatX: "));
+ Serial.print(Xbox.getAnalogHat(RightHatX));
+ Serial.print("\t");
+ }
+ if (Xbox.getAnalogHat(RightHatY) > 7500 || Xbox.getAnalogHat(RightHatY) < -7500) {
+ Serial.print(F("RightHatY: "));
+ Serial.print(Xbox.getAnalogHat(RightHatY));
+ }
+ Serial.println();
+ }
+
+ if (Xbox.getButtonClick(UP)) {
+ Xbox.setLedOn(LED1);
+ Serial.println(F("Up"));
+ }
+ if (Xbox.getButtonClick(DOWN)) {
+ Xbox.setLedOn(LED4);
+ Serial.println(F("Down"));
+ }
+ if (Xbox.getButtonClick(LEFT)) {
+ Xbox.setLedOn(LED3);
+ Serial.println(F("Left"));
+ }
+ if (Xbox.getButtonClick(RIGHT)) {
+ Xbox.setLedOn(LED2);
+ Serial.println(F("Right"));
+ }
+
+ if (Xbox.getButtonClick(START)) {
+ Xbox.setLedMode(ALTERNATING);
+ Serial.println(F("Start"));
+ }
+ if (Xbox.getButtonClick(BACK)) {
+ Xbox.setLedBlink(ALL);
+ Serial.println(F("Back"));
+ }
+ if (Xbox.getButtonClick(L3))
+ Serial.println(F("L3"));
+ if (Xbox.getButtonClick(R3))
+ Serial.println(F("R3"));
+
+ if (Xbox.getButtonClick(L1))
+ Serial.println(F("L1"));
+ if (Xbox.getButtonClick(R1))
+ Serial.println(F("R1"));
+ if (Xbox.getButtonClick(XBOX)) {
+ Xbox.setLedMode(ROTATING);
+ Serial.println(F("Xbox"));
+ }
+
+ if (Xbox.getButtonClick(A))
+ Serial.println(F("A"));
+ if (Xbox.getButtonClick(B))
+ Serial.println(F("B"));
+ if (Xbox.getButtonClick(X))
+ Serial.println(F("X"));
+ if (Xbox.getButtonClick(Y))
+ Serial.println(F("Y"));
+ }
+ delay(1);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/acm/acm_terminal/acm_terminal.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/acm/acm_terminal/acm_terminal.ino
new file mode 100644
index 000000000..f509cda89
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/acm/acm_terminal/acm_terminal.ino
@@ -0,0 +1,100 @@
+#include <cdcacm.h>
+#include <usbhub.h>
+
+#include "pgmstrings.h"
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class ACMAsyncOper : public CDCAsyncOper
+{
+public:
+ uint8_t OnInit(ACM *pacm);
+};
+
+uint8_t ACMAsyncOper::OnInit(ACM *pacm)
+{
+ uint8_t rcode;
+ // Set DTR = 1 RTS=1
+ rcode = pacm->SetControlLineState(3);
+
+ if (rcode)
+ {
+ ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
+ return rcode;
+ }
+
+ LINE_CODING lc;
+ lc.dwDTERate = 115200;
+ lc.bCharFormat = 0;
+ lc.bParityType = 0;
+ lc.bDataBits = 8;
+
+ rcode = pacm->SetLineCoding(&lc);
+
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
+
+ return rcode;
+}
+
+USB Usb;
+//USBHub Hub(&Usb);
+ACMAsyncOper AsyncOper;
+ACM Acm(&Usb, &AsyncOper);
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSCOKIRQ failed to assert");
+
+ delay( 200 );
+}
+
+void loop()
+{
+ Usb.Task();
+
+ if( Acm.isReady()) {
+ uint8_t rcode;
+
+ /* reading the keyboard */
+ if(Serial.available()) {
+ uint8_t data= Serial.read();
+ /* sending to the phone */
+ rcode = Acm.SndData(1, &data);
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
+ }//if(Serial.available()...
+
+ delay(50);
+
+ /* reading the phone */
+ /* buffer size must be greater or equal to max.packet size */
+ /* it it set to 64 (largest possible max.packet size) here, can be tuned down
+ for particular endpoint */
+ uint8_t buf[64];
+ uint16_t rcvd = 64;
+ rcode = Acm.RcvData(&rcvd, buf);
+ if (rcode && rcode != hrNAK)
+ ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
+
+ if( rcvd ) { //more than zero bytes received
+ for(uint16_t i=0; i < rcvd; i++ ) {
+ Serial.print((char)buf[i]); //printing on the screen
+ }
+ }
+ delay(10);
+ }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING..
+}
+
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/acm/acm_terminal/pgmstrings.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/acm/acm_terminal/pgmstrings.h
new file mode 100644
index 000000000..bdb0077ec
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/acm/acm_terminal/pgmstrings.h
@@ -0,0 +1,52 @@
+#if !defined(__PGMSTRINGS_H__)
+#define __PGMSTRINGS_H__
+
+#define LOBYTE(x) ((char*)(&(x)))[0]
+#define HIBYTE(x) ((char*)(&(x)))[1]
+#define BUFSIZE 256 //buffer size
+
+
+/* Print strings in Program Memory */
+const char Gen_Error_str[] PROGMEM = "\r\nRequest error. Error code:\t";
+const char Dev_Header_str[] PROGMEM ="\r\nDevice descriptor: ";
+const char Dev_Length_str[] PROGMEM ="\r\nDescriptor Length:\t";
+const char Dev_Type_str[] PROGMEM ="\r\nDescriptor type:\t";
+const char Dev_Version_str[] PROGMEM ="\r\nUSB version:\t\t";
+const char Dev_Class_str[] PROGMEM ="\r\nDevice class:\t\t";
+const char Dev_Subclass_str[] PROGMEM ="\r\nDevice Subclass:\t";
+const char Dev_Protocol_str[] PROGMEM ="\r\nDevice Protocol:\t";
+const char Dev_Pktsize_str[] PROGMEM ="\r\nMax.packet size:\t";
+const char Dev_Vendor_str[] PROGMEM ="\r\nVendor ID:\t\t";
+const char Dev_Product_str[] PROGMEM ="\r\nProduct ID:\t\t";
+const char Dev_Revision_str[] PROGMEM ="\r\nRevision ID:\t\t";
+const char Dev_Mfg_str[] PROGMEM ="\r\nMfg.string index:\t";
+const char Dev_Prod_str[] PROGMEM ="\r\nProd.string index:\t";
+const char Dev_Serial_str[] PROGMEM ="\r\nSerial number index:\t";
+const char Dev_Nconf_str[] PROGMEM ="\r\nNumber of conf.:\t";
+const char Conf_Trunc_str[] PROGMEM ="Total length truncated to 256 bytes";
+const char Conf_Header_str[] PROGMEM ="\r\nConfiguration descriptor:";
+const char Conf_Totlen_str[] PROGMEM ="\r\nTotal length:\t\t";
+const char Conf_Nint_str[] PROGMEM ="\r\nNum.intf:\t\t";
+const char Conf_Value_str[] PROGMEM ="\r\nConf.value:\t\t";
+const char Conf_String_str[] PROGMEM ="\r\nConf.string:\t\t";
+const char Conf_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char Conf_Pwr_str[] PROGMEM ="\r\nMax.pwr:\t\t";
+const char Int_Header_str[] PROGMEM ="\r\n\r\nInterface descriptor:";
+const char Int_Number_str[] PROGMEM ="\r\nIntf.number:\t\t";
+const char Int_Alt_str[] PROGMEM ="\r\nAlt.:\t\t\t";
+const char Int_Endpoints_str[] PROGMEM ="\r\nEndpoints:\t\t";
+const char Int_Class_str[] PROGMEM ="\r\nIntf. Class:\t\t";
+const char Int_Subclass_str[] PROGMEM ="\r\nIntf. Subclass:\t\t";
+const char Int_Protocol_str[] PROGMEM ="\r\nIntf. Protocol:\t\t";
+const char Int_String_str[] PROGMEM ="\r\nIntf.string:\t\t";
+const char End_Header_str[] PROGMEM ="\r\n\r\nEndpoint descriptor:";
+const char End_Address_str[] PROGMEM ="\r\nEndpoint address:\t";
+const char End_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char End_Pktsize_str[] PROGMEM ="\r\nMax.pkt size:\t\t";
+const char End_Interval_str[] PROGMEM ="\r\nPolling interval:\t";
+const char Unk_Header_str[] PROGMEM = "\r\nUnknown descriptor:";
+const char Unk_Length_str[] PROGMEM ="\r\nLength:\t\t";
+const char Unk_Type_str[] PROGMEM ="\r\nType:\t\t";
+const char Unk_Contents_str[] PROGMEM ="\r\nContents:\t";
+
+#endif // __PGMSTRINGS_H__ \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino
new file mode 100644
index 000000000..d59b9bb3d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/ArduinoBlinkLED/ArduinoBlinkLED.ino
@@ -0,0 +1,89 @@
+// The source for the Android application can be found at the following link: https://github.com/Lauszus/ArduinoBlinkLED
+// The code for the Android application is heavily based on this guide: http://allaboutee.com/2011/12/31/arduino-adk-board-blink-an-led-with-your-phone-code-and-explanation/ by Miguel
+#include <adk.h>
+
+//
+// CAUTION! WARNING! ATTENTION! VORSICHT! ADVARSEL! ¡CUIDADO! ВНИМАНИЕ!
+//
+// Pin 13 is occupied by the SCK pin on various Arduino boards,
+// including Uno, Duemilanove, etc., so use a different pin for those boards.
+//
+// CAUTION! WARNING! ATTENTION! VORSICHT! ADVARSEL! ¡CUIDADO! ВНИМАНИЕ!
+//
+#if defined(LED_BUILTIN)
+#define LED LED_BUILTIN // Use built in LED
+#else
+#define LED 9 // Set to something here that makes sense for your board.
+#endif
+
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+ADK adk(&Usb, "TKJElectronics", // Manufacturer Name
+ "ArduinoBlinkLED", // Model Name
+ "Example sketch for the USB Host Shield", // Description (user-visible string)
+ "1.0", // Version
+ "http://www.tkjelectronics.dk/uploads/ArduinoBlinkLED.apk", // URL (web page to visit if no installed apps support the accessory)
+ "123456789"); // Serial Number (optional)
+
+uint32_t timer;
+bool connected;
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ if (Usb.Init() == -1) {
+ Serial.print("\r\nOSCOKIRQ failed to assert");
+ while (1); // halt
+ }
+ pinMode(LED, OUTPUT);
+ Serial.print("\r\nArduino Blink LED Started");
+}
+
+void loop() {
+ Usb.Task();
+
+ if (adk.isReady()) {
+ if (!connected) {
+ connected = true;
+ Serial.print(F("\r\nConnected to accessory"));
+ }
+
+ uint8_t msg[1];
+ uint16_t len = sizeof(msg);
+ uint8_t rcode = adk.RcvData(&len, msg);
+ if (rcode && rcode != hrNAK) {
+ Serial.print(F("\r\nData rcv: "));
+ Serial.print(rcode, HEX);
+ } else if (len > 0) {
+ Serial.print(F("\r\nData Packet: "));
+ Serial.print(msg[0]);
+ digitalWrite(LED, msg[0] ? HIGH : LOW);
+ }
+
+ if (millis() - timer >= 1000) { // Send data every 1s
+ timer = millis();
+ rcode = adk.SndData(sizeof(timer), (uint8_t*)&timer);
+ if (rcode && rcode != hrNAK) {
+ Serial.print(F("\r\nData send: "));
+ Serial.print(rcode, HEX);
+ } else if (rcode != hrNAK) {
+ Serial.print(F("\r\nTimer: "));
+ Serial.print(timer);
+ }
+ }
+ } else {
+ if (connected) {
+ connected = false;
+ Serial.print(F("\r\nDisconnected from accessory"));
+ digitalWrite(LED, LOW);
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/adk_barcode/adk_barcode.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/adk_barcode/adk_barcode.ino
new file mode 100644
index 000000000..a308ff0f8
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/adk_barcode/adk_barcode.ino
@@ -0,0 +1,91 @@
+/**/
+/* A sketch demonstrating data exchange between two USB devices - a HID barcode scanner and ADK-compatible Android phone */
+/**/
+#include <adk.h>
+#include <hidboot.h>
+#include <usbhub.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+USBHub Hub1(&Usb);
+USBHub Hub2(&Usb);
+HIDBoot<HID_PROTOCOL_KEYBOARD> Keyboard(&Usb);
+
+ADK adk(&Usb,"Circuits@Home, ltd.",
+ "USB Host Shield",
+ "Arduino Terminal for Android",
+ "1.0",
+ "http://www.circuitsathome.com",
+ "0000000000000001");
+
+
+class KbdRptParser : public KeyboardReportParser
+{
+
+protected:
+ void OnKeyDown (uint8_t mod, uint8_t key);
+ void OnKeyPressed(uint8_t key);
+};
+
+void KbdRptParser::OnKeyDown(uint8_t mod, uint8_t key)
+{
+ uint8_t c = OemToAscii(mod, key);
+
+ if (c)
+ OnKeyPressed(c);
+}
+
+/* what to do when symbol arrives */
+void KbdRptParser::OnKeyPressed(uint8_t key)
+{
+const char* new_line = "\n";
+uint8_t rcode;
+uint8_t keylcl;
+
+ if( adk.isReady() == false ) {
+ return;
+ }
+
+ keylcl = key;
+
+ if( keylcl == 0x13 ) {
+ rcode = adk.SndData( strlen( new_line ), (uint8_t *)new_line );
+ }
+ else {
+ rcode = adk.SndData( 1, &keylcl );
+ }
+
+ Serial.print((char) keylcl );
+ Serial.print(" : ");
+ Serial.println( keylcl, HEX );
+};
+
+KbdRptParser Prs;
+
+void setup()
+{
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("\r\nADK demo start");
+
+ if (Usb.Init() == -1) {
+ Serial.println("OSCOKIRQ failed to assert");
+ while(1); //halt
+ }//if (Usb.Init() == -1...
+
+ Keyboard.SetReportParser(0, (HIDReportParser*)&Prs);
+
+ delay( 200 );
+}
+
+void loop()
+{
+ Usb.Task();
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/demokit_20/demokit_20.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/demokit_20/demokit_20.ino
new file mode 100644
index 000000000..f65adf57b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/demokit_20/demokit_20.ino
@@ -0,0 +1,103 @@
+#include <adk.h>
+#include <usbhub.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+USBHub hub0(&Usb);
+USBHub hub1(&Usb);
+ADK adk(&Usb,"Google, Inc.",
+ "DemoKit",
+ "DemoKit Arduino Board",
+ "1.0",
+ "http://www.android.com",
+ "0000000012345678");
+uint8_t b, b1;
+
+
+#define LED1_RED 3
+#define BUTTON1 2
+
+void init_buttons()
+{
+ pinMode(BUTTON1, INPUT);
+
+ // enable the internal pullups
+ digitalWrite(BUTTON1, HIGH);
+}
+
+void init_leds()
+{
+ digitalWrite(LED1_RED, 0);
+
+ pinMode(LED1_RED, OUTPUT);
+}
+
+void setup()
+{
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("\r\nADK demo start");
+
+ if (Usb.Init() == -1) {
+ Serial.println("OSCOKIRQ failed to assert");
+ while(1); //halt
+ }//if (Usb.Init() == -1...
+
+
+ init_leds();
+ init_buttons();
+ b1 = digitalRead(BUTTON1);
+}
+
+void loop()
+{
+ uint8_t rcode;
+ uint8_t msg[3] = { 0x00 };
+ Usb.Task();
+
+ if( adk.isReady() == false ) {
+ analogWrite(LED1_RED, 255);
+ return;
+ }
+ uint16_t len = sizeof(msg);
+
+ rcode = adk.RcvData(&len, msg);
+ if( rcode ) {
+ USBTRACE2("Data rcv. :", rcode );
+ }
+ if(len > 0) {
+ USBTRACE("\r\nData Packet.");
+ // assumes only one command per packet
+ if (msg[0] == 0x2) {
+ switch( msg[1] ) {
+ case 0:
+ analogWrite(LED1_RED, 255 - msg[2]);
+ break;
+ }//switch( msg[1]...
+ }//if (msg[0] == 0x2...
+ }//if( len > 0...
+
+ msg[0] = 0x1;
+
+ b = digitalRead(BUTTON1);
+ if (b != b1) {
+ USBTRACE("\r\nButton state changed");
+ msg[1] = 0;
+ msg[2] = b ? 0 : 1;
+ rcode = adk.SndData( 3, msg );
+ if( rcode ) {
+ USBTRACE2("Button send: ", rcode );
+ }
+ b1 = b;
+ }//if (b != b1...
+
+
+ delay( 10 );
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/term_test/term_test.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/term_test/term_test.ino
new file mode 100644
index 000000000..db681c3b5
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/term_test/term_test.ino
@@ -0,0 +1,65 @@
+#include <adk.h>
+#include <usbhub.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+//USBHub Hub(&Usb);
+
+ADK adk(&Usb,"Circuits@Home, ltd.",
+ "USB Host Shield",
+ "Arduino Terminal for Android",
+ "1.0",
+ "http://www.circuitsathome.com",
+ "0000000000000001");
+
+void setup()
+{
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("\r\nADK demo start");
+
+ if (Usb.Init() == -1) {
+ Serial.println("OSCOKIRQ failed to assert");
+ while(1); //halt
+ }//if (Usb.Init() == -1...
+}
+
+void loop()
+{
+ uint8_t rcode;
+ uint8_t msg[64] = { 0x00 };
+ const char* recv = "Received: ";
+
+ Usb.Task();
+
+ if( adk.isReady() == false ) {
+ return;
+ }
+ uint16_t len = 64;
+
+ rcode = adk.RcvData(&len, msg);
+ if( rcode & ( rcode != hrNAK )) {
+ USBTRACE2("Data rcv. :", rcode );
+ }
+ if(len > 0) {
+ USBTRACE("\r\nData Packet.");
+
+ for( uint8_t i = 0; i < len; i++ ) {
+ Serial.print((char)msg[i]);
+ }
+ /* sending back what was received */
+ rcode = adk.SndData( strlen( recv ), (uint8_t *)recv );
+ rcode = adk.SndData( strlen(( char * )msg ), msg );
+
+ }//if( len > 0 )...
+
+ delay( 1000 );
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/term_time/term_time.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/term_time/term_time.ino
new file mode 100644
index 000000000..a3f1dbc8c
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/adk/term_time/term_time.ino
@@ -0,0 +1,50 @@
+#include <adk.h>
+#include <usbhub.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+
+ADK adk(&Usb,"Circuits@Home, ltd.",
+ "USB Host Shield",
+ "Arduino Terminal for Android",
+ "1.0",
+ "http://www.circuitsathome.com",
+ "0000000000000001");
+
+void setup()
+{
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("\r\nADK demo start");
+
+ if (Usb.Init() == -1) {
+ Serial.println("OSCOKIRQ failed to assert");
+ while(1); //halt
+ }//if (Usb.Init() == -1...
+}
+
+void loop()
+{
+ uint8_t buf[ 12 ] = { 0 }; //buffer to convert unsigned long to ASCII
+ const char* sec_ela = " seconds elapsed\r";
+ uint8_t rcode;
+
+ Usb.Task();
+ if( adk.isReady() == false ) {
+ return;
+ }
+
+ ultoa( millis()/1000, (char *)buf, 10 );
+
+ rcode = adk.SndData( strlen((char *)buf), buf );
+ rcode = adk.SndData( strlen( sec_ela), (uint8_t *)sec_ela );
+
+ delay( 1000 );
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/board_qc/board_qc.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/board_qc/board_qc.ino
new file mode 100644
index 000000000..573c3ce08
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/board_qc/board_qc.ino
@@ -0,0 +1,259 @@
+/* USB Host Shield 2.0 board quality control routine */
+/* To see the output set your terminal speed to 115200 */
+/* for GPIO test to pass you need to connect GPIN0 to GPOUT7, GPIN1 to GPOUT6, etc. */
+/* otherwise press any key after getting GPIO error to complete the test */
+/**/
+#include <usbhub.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <../../../../hardware/pic32/libraries/SPI/SPI.h> // Hack to use the SPI library
+#include <SPI.h> // Hack to use the SPI library
+#endif
+
+/* variables */
+uint8_t rcode;
+uint8_t usbstate;
+uint8_t laststate;
+//uint8_t buf[sizeof(USB_DEVICE_DESCRIPTOR)];
+USB_DEVICE_DESCRIPTOR buf;
+
+/* objects */
+USB Usb;
+//USBHub hub(&Usb);
+
+void setup() {
+ laststate = 0;
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while(!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ E_Notify(PSTR("\r\nCircuits At Home 2011"), 0x80);
+ E_Notify(PSTR("\r\nUSB Host Shield Quality Control Routine"), 0x80);
+ /* SPI quick test - check revision register */
+ E_Notify(PSTR("\r\nReading REVISION register... Die revision "), 0x80);
+ Usb.Init(); // Initializes SPI, we don't care about the return value here
+ {
+ uint8_t tmpbyte = Usb.regRd(rREVISION);
+ switch(tmpbyte) {
+ case( 0x01): //rev.01
+ E_Notify(PSTR("01"), 0x80);
+ break;
+ case( 0x12): //rev.02
+ E_Notify(PSTR("02"), 0x80);
+ break;
+ case( 0x13): //rev.03
+ E_Notify(PSTR("03"), 0x80);
+ break;
+ default:
+ E_Notify(PSTR("invalid. Value returned: "), 0x80);
+ print_hex(tmpbyte, 8);
+ halt55();
+ break;
+ }//switch( tmpbyte...
+ }//check revision register
+ /* SPI long test */
+ {
+ E_Notify(PSTR("\r\nSPI long test. Transfers 1MB of data. Each dot is 64K"), 0x80);
+ uint8_t sample_wr = 0;
+ uint8_t sample_rd = 0;
+ uint8_t gpinpol_copy = Usb.regRd(rGPINPOL);
+ for(uint8_t i = 0; i < 16; i++) {
+ for(uint16_t j = 0; j < 65535; j++) {
+ Usb.regWr(rGPINPOL, sample_wr);
+ sample_rd = Usb.regRd(rGPINPOL);
+ if(sample_rd != sample_wr) {
+ E_Notify(PSTR("\r\nTest failed. "), 0x80);
+ E_Notify(PSTR("Value written: "), 0x80);
+ print_hex(sample_wr, 8);
+ E_Notify(PSTR(" read: "), 0x80);
+ print_hex(sample_rd, 8);
+ halt55();
+ }//if( sample_rd != sample_wr..
+ sample_wr++;
+ }//for( uint16_t j...
+ E_Notify(PSTR("."), 0x80);
+ }//for( uint8_t i...
+ Usb.regWr(rGPINPOL, gpinpol_copy);
+ E_Notify(PSTR(" SPI long test passed"), 0x80);
+ }//SPI long test
+ /* GPIO test */
+ /* in order to simplify board layout, GPIN pins on text fixture are connected to GPOUT */
+ /* in reverse order, i.e, GPIN0 is connected to GPOUT7, GPIN1 to GPOUT6, etc. */
+ {
+ uint8_t tmpbyte;
+ E_Notify(PSTR("\r\nGPIO test. Connect GPIN0 to GPOUT7, GPIN1 to GPOUT6, and so on"), 0x80);
+ for(uint8_t sample_gpio = 0; sample_gpio < 255; sample_gpio++) {
+ Usb.gpioWr(sample_gpio);
+ tmpbyte = Usb.gpioRd();
+ /* bit reversing code copied vetbatim from http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious */
+ tmpbyte = ((tmpbyte * 0x0802LU & 0x22110LU) | (tmpbyte * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;
+ if(sample_gpio != tmpbyte) {
+ E_Notify(PSTR("\r\nTest failed. Value written: "), 0x80);
+ print_hex(sample_gpio, 8);
+ E_Notify(PSTR(" Value read: "), 0x80);
+ print_hex(tmpbyte, 8);
+ E_Notify(PSTR(" "), 0x80);
+ press_any_key();
+ break;
+ }//if( sample_gpio != tmpbyte...
+ }//for( uint8_t sample_gpio...
+ E_Notify(PSTR("\r\nGPIO test passed."), 0x80);
+ }//GPIO test
+ /* PLL test. Stops/starts MAX3421E oscillator several times */
+ {
+ E_Notify(PSTR("\r\nPLL test. 100 chip resets will be performed"), 0x80);
+ /* check current state of the oscillator */
+ if(!(Usb.regRd(rUSBIRQ) & bmOSCOKIRQ)) { //wrong state - should be on
+ E_Notify(PSTR("\r\nCurrent oscillator state unexpected."), 0x80);
+ press_any_key();
+ }
+ /* Restart oscillator */
+ E_Notify(PSTR("\r\nResetting oscillator\r\n"), 0x80);
+ for(uint16_t i = 0; i < 100; i++) {
+ E_Notify(PSTR("\rReset number "), 0x80);
+ Serial.print(i, DEC);
+ Usb.regWr(rUSBCTL, bmCHIPRES); //reset
+ if(Usb.regRd(rUSBIRQ) & bmOSCOKIRQ) { //wrong state - should be off
+ E_Notify(PSTR("\r\nCurrent oscillator state unexpected."), 0x80);
+ halt55();
+ }
+ Usb.regWr(rUSBCTL, 0x00); //release from reset
+ uint16_t j = 0;
+ for(j = 1; j < 65535; j++) { //tracking off to on time
+ if(Usb.regRd(rUSBIRQ) & bmOSCOKIRQ) {
+ E_Notify(PSTR(" Time to stabilize - "), 0x80);
+ Serial.print(j, DEC);
+ E_Notify(PSTR(" cycles\r\n"), 0x80);
+ break;
+ }
+ }//for( uint16_t j = 0; j < 65535; j++
+ if(j == 0) {
+ E_Notify(PSTR("PLL failed to stabilize"), 0x80);
+ press_any_key();
+ }
+ }//for( uint8_t i = 0; i < 255; i++
+
+ }//PLL test
+ /* initializing USB stack */
+ if(Usb.Init() == -1) {
+ E_Notify(PSTR("\r\nOSCOKIRQ failed to assert"), 0x80);
+ halt55();
+ }
+ E_Notify(PSTR("\r\nChecking USB device communication.\r\n"), 0x80);
+}
+
+void loop() {
+ delay(200);
+ Usb.Task();
+ usbstate = Usb.getUsbTaskState();
+ if(usbstate != laststate) {
+ laststate = usbstate;
+ /**/
+ switch(usbstate) {
+ case( USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE):
+ E_Notify(PSTR("\r\nWaiting for device..."), 0x80);
+ break;
+ case( USB_ATTACHED_SUBSTATE_RESET_DEVICE):
+ E_Notify(PSTR("\r\nDevice connected. Resetting..."), 0x80);
+ break;
+ case( USB_ATTACHED_SUBSTATE_WAIT_SOF):
+ E_Notify(PSTR("\r\nReset complete. Waiting for the first SOF..."), 0x80);
+ break;
+ case( USB_ATTACHED_SUBSTATE_GET_DEVICE_DESCRIPTOR_SIZE):
+ E_Notify(PSTR("\r\nSOF generation started. Enumerating device..."), 0x80);
+ break;
+ case( USB_STATE_ADDRESSING):
+ E_Notify(PSTR("\r\nSetting device address..."), 0x80);
+ break;
+ case( USB_STATE_RUNNING):
+ E_Notify(PSTR("\r\nGetting device descriptor"), 0x80);
+ rcode = Usb.getDevDescr(1, 0, sizeof (USB_DEVICE_DESCRIPTOR), (uint8_t*) & buf);
+
+ if(rcode) {
+ E_Notify(PSTR("\r\nError reading device descriptor. Error code "), 0x80);
+ print_hex(rcode, 8);
+ } else {
+ /**/
+ E_Notify(PSTR("\r\nDescriptor Length:\t"), 0x80);
+ print_hex(buf.bLength, 8);
+ E_Notify(PSTR("\r\nDescriptor type:\t"), 0x80);
+ print_hex(buf.bDescriptorType, 8);
+ E_Notify(PSTR("\r\nUSB version:\t\t"), 0x80);
+ print_hex(buf.bcdUSB, 16);
+ E_Notify(PSTR("\r\nDevice class:\t\t"), 0x80);
+ print_hex(buf.bDeviceClass, 8);
+ E_Notify(PSTR("\r\nDevice Subclass:\t"), 0x80);
+ print_hex(buf.bDeviceSubClass, 8);
+ E_Notify(PSTR("\r\nDevice Protocol:\t"), 0x80);
+ print_hex(buf.bDeviceProtocol, 8);
+ E_Notify(PSTR("\r\nMax.packet size:\t"), 0x80);
+ print_hex(buf.bMaxPacketSize0, 8);
+ E_Notify(PSTR("\r\nVendor ID:\t\t"), 0x80);
+ print_hex(buf.idVendor, 16);
+ E_Notify(PSTR("\r\nProduct ID:\t\t"), 0x80);
+ print_hex(buf.idProduct, 16);
+ E_Notify(PSTR("\r\nRevision ID:\t\t"), 0x80);
+ print_hex(buf.bcdDevice, 16);
+ E_Notify(PSTR("\r\nMfg.string index:\t"), 0x80);
+ print_hex(buf.iManufacturer, 8);
+ E_Notify(PSTR("\r\nProd.string index:\t"), 0x80);
+ print_hex(buf.iProduct, 8);
+ E_Notify(PSTR("\r\nSerial number index:\t"), 0x80);
+ print_hex(buf.iSerialNumber, 8);
+ E_Notify(PSTR("\r\nNumber of conf.:\t"), 0x80);
+ print_hex(buf.bNumConfigurations, 8);
+ /**/
+ E_Notify(PSTR("\r\n\nAll tests passed. Press RESET to restart test"), 0x80);
+ while(1);
+ }
+ break;
+ case( USB_STATE_ERROR):
+ E_Notify(PSTR("\r\nUSB state machine reached error state"), 0x80);
+ break;
+
+ default:
+ break;
+ }//switch( usbstate...
+ }
+}//loop()...
+
+/* constantly transmits 0x55 via SPI to aid probing */
+void halt55() {
+
+ E_Notify(PSTR("\r\nUnrecoverable error - test halted!!"), 0x80);
+ E_Notify(PSTR("\r\n0x55 pattern is transmitted via SPI"), 0x80);
+ E_Notify(PSTR("\r\nPress RESET to restart test"), 0x80);
+
+ while(1) {
+ Usb.regWr(0x55, 0x55);
+ }
+}
+
+/* prints hex numbers with leading zeroes */
+void print_hex(int v, int num_places) {
+ int mask = 0, n, num_nibbles, digit;
+
+ for(n = 1; n <= num_places; n++) {
+ mask = (mask << 1) | 0x0001;
+ }
+ v = v & mask; // truncate v to specified number of places
+
+ num_nibbles = num_places / 4;
+ if((num_places % 4) != 0) {
+ ++num_nibbles;
+ }
+ do {
+ digit = ((v >> (num_nibbles - 1) * 4)) & 0x0f;
+ Serial.print(digit, HEX);
+ } while(--num_nibbles);
+}
+
+/* prints "Press any key" and returns when key is pressed */
+void press_any_key() {
+ E_Notify(PSTR("\r\nPress any key to continue..."), 0x80);
+ while(Serial.available() <= 0); //wait for input
+ Serial.read(); //empty input buffer
+ return;
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/cdc_XR21B1411/XR_terminal/XR_terminal.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/cdc_XR21B1411/XR_terminal/XR_terminal.ino
new file mode 100644
index 000000000..0173a08b5
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/cdc_XR21B1411/XR_terminal/XR_terminal.ino
@@ -0,0 +1,83 @@
+#include <cdc_XR21B1411.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class ACMAsyncOper : public CDCAsyncOper
+{
+public:
+ uint8_t OnInit(ACM *pacm);
+};
+
+uint8_t ACMAsyncOper::OnInit(ACM *pacm)
+{
+ uint8_t rcode;
+ // Set DTR = 1 RTS=1
+ rcode = pacm->SetControlLineState(3);
+
+ if (rcode)
+ {
+ ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
+ return rcode;
+ }
+
+ LINE_CODING lc;
+ lc.dwDTERate = 115200;
+ lc.bCharFormat = 0;
+ lc.bParityType = 0;
+ lc.bDataBits = 8;
+
+ rcode = pacm->SetLineCoding(&lc);
+
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
+
+ return rcode;
+}
+
+USB Usb;
+ACMAsyncOper AsyncOper;
+XR21B1411 Acm(&Usb, &AsyncOper);
+
+void setup() {
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("\r\n\r\nStart");
+
+ if (Usb.Init() == -1) Serial.println("OSCOKIRQ failed to assert");
+}
+
+void loop() {
+ Usb.Task();
+ if( Acm.isReady()) {
+ uint8_t rcode;
+ uint8_t buf[1];
+ uint16_t rcvd = 1;
+
+ /* read keyboard */
+ if(Serial.available()) {
+ uint8_t data = Serial.read();
+ /* send */
+ rcode = Acm.SndData(1, &data);
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
+ }
+
+ /* read XR serial */
+ rcode = Acm.RcvData(&rcvd, buf);
+ if (rcode && rcode != hrNAK)
+ ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
+
+ if( rcvd ) { //more than zero bytes received
+ for(uint16_t i=0; i < rcvd; i++ ) {
+ Serial.print((char)buf[i]);
+ }
+ }
+ }
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/ftdi/USBFTDILoopback/USBFTDILoopback.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/ftdi/USBFTDILoopback/USBFTDILoopback.ino
new file mode 100644
index 000000000..5be7adc2f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/ftdi/USBFTDILoopback/USBFTDILoopback.ino
@@ -0,0 +1,98 @@
+#include <cdcftdi.h>
+#include <usbhub.h>
+
+#include "pgmstrings.h"
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class FTDIAsync : public FTDIAsyncOper
+{
+public:
+ uint8_t OnInit(FTDI *pftdi);
+};
+
+uint8_t FTDIAsync::OnInit(FTDI *pftdi)
+{
+ uint8_t rcode = 0;
+
+ rcode = pftdi->SetBaudRate(115200);
+
+ if (rcode)
+ {
+ ErrorMessage<uint8_t>(PSTR("SetBaudRate"), rcode);
+ return rcode;
+ }
+ rcode = pftdi->SetFlowControl(FTDI_SIO_DISABLE_FLOW_CTRL);
+
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SetFlowControl"), rcode);
+
+ return rcode;
+}
+
+USB Usb;
+//USBHub Hub(&Usb);
+FTDIAsync FtdiAsync;
+FTDI Ftdi(&Usb, &FtdiAsync);
+
+uint32_t next_time;
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay( 200 );
+
+ next_time = millis() + 5000;
+}
+
+void loop()
+{
+ Usb.Task();
+
+ if( Usb.getUsbTaskState() == USB_STATE_RUNNING )
+ {
+ uint8_t rcode;
+ char strbuf[] = "DEADBEEF";
+ //char strbuf[] = "The quick brown fox jumps over the lazy dog";
+ //char strbuf[] = "This string contains 61 character to demonstrate FTDI buffers"; //add one symbol to it to see some garbage
+ Serial.print(".");
+
+ rcode = Ftdi.SndData(strlen(strbuf), (uint8_t*)strbuf);
+
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
+
+ delay(50);
+
+ uint8_t buf[64];
+
+ for (uint8_t i=0; i<64; i++)
+ buf[i] = 0;
+
+ uint16_t rcvd = 64;
+ rcode = Ftdi.RcvData(&rcvd, buf);
+
+ if (rcode && rcode != hrNAK)
+ ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
+
+ // The device reserves the first two bytes of data
+ // to contain the current values of the modem and line status registers.
+ if (rcvd > 2)
+ Serial.print((char*)(buf+2));
+
+ delay(10);
+ }
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/ftdi/USBFTDILoopback/pgmstrings.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/ftdi/USBFTDILoopback/pgmstrings.h
new file mode 100644
index 000000000..bdb0077ec
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/ftdi/USBFTDILoopback/pgmstrings.h
@@ -0,0 +1,52 @@
+#if !defined(__PGMSTRINGS_H__)
+#define __PGMSTRINGS_H__
+
+#define LOBYTE(x) ((char*)(&(x)))[0]
+#define HIBYTE(x) ((char*)(&(x)))[1]
+#define BUFSIZE 256 //buffer size
+
+
+/* Print strings in Program Memory */
+const char Gen_Error_str[] PROGMEM = "\r\nRequest error. Error code:\t";
+const char Dev_Header_str[] PROGMEM ="\r\nDevice descriptor: ";
+const char Dev_Length_str[] PROGMEM ="\r\nDescriptor Length:\t";
+const char Dev_Type_str[] PROGMEM ="\r\nDescriptor type:\t";
+const char Dev_Version_str[] PROGMEM ="\r\nUSB version:\t\t";
+const char Dev_Class_str[] PROGMEM ="\r\nDevice class:\t\t";
+const char Dev_Subclass_str[] PROGMEM ="\r\nDevice Subclass:\t";
+const char Dev_Protocol_str[] PROGMEM ="\r\nDevice Protocol:\t";
+const char Dev_Pktsize_str[] PROGMEM ="\r\nMax.packet size:\t";
+const char Dev_Vendor_str[] PROGMEM ="\r\nVendor ID:\t\t";
+const char Dev_Product_str[] PROGMEM ="\r\nProduct ID:\t\t";
+const char Dev_Revision_str[] PROGMEM ="\r\nRevision ID:\t\t";
+const char Dev_Mfg_str[] PROGMEM ="\r\nMfg.string index:\t";
+const char Dev_Prod_str[] PROGMEM ="\r\nProd.string index:\t";
+const char Dev_Serial_str[] PROGMEM ="\r\nSerial number index:\t";
+const char Dev_Nconf_str[] PROGMEM ="\r\nNumber of conf.:\t";
+const char Conf_Trunc_str[] PROGMEM ="Total length truncated to 256 bytes";
+const char Conf_Header_str[] PROGMEM ="\r\nConfiguration descriptor:";
+const char Conf_Totlen_str[] PROGMEM ="\r\nTotal length:\t\t";
+const char Conf_Nint_str[] PROGMEM ="\r\nNum.intf:\t\t";
+const char Conf_Value_str[] PROGMEM ="\r\nConf.value:\t\t";
+const char Conf_String_str[] PROGMEM ="\r\nConf.string:\t\t";
+const char Conf_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char Conf_Pwr_str[] PROGMEM ="\r\nMax.pwr:\t\t";
+const char Int_Header_str[] PROGMEM ="\r\n\r\nInterface descriptor:";
+const char Int_Number_str[] PROGMEM ="\r\nIntf.number:\t\t";
+const char Int_Alt_str[] PROGMEM ="\r\nAlt.:\t\t\t";
+const char Int_Endpoints_str[] PROGMEM ="\r\nEndpoints:\t\t";
+const char Int_Class_str[] PROGMEM ="\r\nIntf. Class:\t\t";
+const char Int_Subclass_str[] PROGMEM ="\r\nIntf. Subclass:\t\t";
+const char Int_Protocol_str[] PROGMEM ="\r\nIntf. Protocol:\t\t";
+const char Int_String_str[] PROGMEM ="\r\nIntf.string:\t\t";
+const char End_Header_str[] PROGMEM ="\r\n\r\nEndpoint descriptor:";
+const char End_Address_str[] PROGMEM ="\r\nEndpoint address:\t";
+const char End_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char End_Pktsize_str[] PROGMEM ="\r\nMax.pkt size:\t\t";
+const char End_Interval_str[] PROGMEM ="\r\nPolling interval:\t";
+const char Unk_Header_str[] PROGMEM = "\r\nUnknown descriptor:";
+const char Unk_Length_str[] PROGMEM ="\r\nLength:\t\t";
+const char Unk_Type_str[] PROGMEM ="\r\nType:\t\t";
+const char Unk_Contents_str[] PROGMEM ="\r\nContents:\t";
+
+#endif // __PGMSTRINGS_H__ \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/hub_demo/hub_demo.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/hub_demo/hub_demo.ino
new file mode 100644
index 000000000..d8b2d4bb7
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/hub_demo/hub_demo.ino
@@ -0,0 +1,345 @@
+#include <usbhub.h>
+#include "pgmstrings.h"
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+USBHub Hub1(&Usb);
+USBHub Hub2(&Usb);
+USBHub Hub3(&Usb);
+USBHub Hub4(&Usb);
+
+uint32_t next_time;
+
+void PrintAllAddresses(UsbDevice *pdev)
+{
+ UsbDeviceAddress adr;
+ adr.devAddress = pdev->address.devAddress;
+ Serial.print("\r\nAddr:");
+ Serial.print(adr.devAddress, HEX);
+ Serial.print("(");
+ Serial.print(adr.bmHub, HEX);
+ Serial.print(".");
+ Serial.print(adr.bmParent, HEX);
+ Serial.print(".");
+ Serial.print(adr.bmAddress, HEX);
+ Serial.println(")");
+}
+
+void PrintAddress(uint8_t addr)
+{
+ UsbDeviceAddress adr;
+ adr.devAddress = addr;
+ Serial.print("\r\nADDR:\t");
+ Serial.println(adr.devAddress, HEX);
+ Serial.print("DEV:\t");
+ Serial.println(adr.bmAddress, HEX);
+ Serial.print("PRNT:\t");
+ Serial.println(adr.bmParent, HEX);
+ Serial.print("HUB:\t");
+ Serial.println(adr.bmHub, HEX);
+}
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSC did not start.");
+
+ delay( 200 );
+
+ next_time = millis() + 10000;
+}
+
+byte getdevdescr( byte addr, byte &num_conf );
+
+void PrintDescriptors(uint8_t addr)
+{
+ uint8_t rcode = 0;
+ byte num_conf = 0;
+
+ rcode = getdevdescr( (byte)addr, num_conf );
+ if ( rcode )
+ {
+ printProgStr(Gen_Error_str);
+ print_hex( rcode, 8 );
+ }
+ Serial.print("\r\n");
+
+ for (int i = 0; i < num_conf; i++)
+ {
+ rcode = getconfdescr( addr, i ); // get configuration descriptor
+ if ( rcode )
+ {
+ printProgStr(Gen_Error_str);
+ print_hex(rcode, 8);
+ }
+ Serial.println("\r\n");
+ }
+}
+
+void PrintAllDescriptors(UsbDevice *pdev)
+{
+ Serial.println("\r\n");
+ print_hex(pdev->address.devAddress, 8);
+ Serial.println("\r\n--");
+ PrintDescriptors( pdev->address.devAddress );
+}
+
+void loop()
+{
+ Usb.Task();
+
+ if ( Usb.getUsbTaskState() == USB_STATE_RUNNING )
+ {
+ if ((millis() - next_time) >= 0L)
+ {
+ Usb.ForEachUsbDevice(&PrintAllDescriptors);
+ Usb.ForEachUsbDevice(&PrintAllAddresses);
+
+ while ( 1 ); //stop
+ }
+ }
+}
+
+byte getdevdescr( byte addr, byte &num_conf )
+{
+ USB_DEVICE_DESCRIPTOR buf;
+ byte rcode;
+ rcode = Usb.getDevDescr( addr, 0, 0x12, ( uint8_t *)&buf );
+ if ( rcode ) {
+ return ( rcode );
+ }
+ printProgStr(Dev_Header_str);
+ printProgStr(Dev_Length_str);
+ print_hex( buf.bLength, 8 );
+ printProgStr(Dev_Type_str);
+ print_hex( buf.bDescriptorType, 8 );
+ printProgStr(Dev_Version_str);
+ print_hex( buf.bcdUSB, 16 );
+ printProgStr(Dev_Class_str);
+ print_hex( buf.bDeviceClass, 8 );
+ printProgStr(Dev_Subclass_str);
+ print_hex( buf.bDeviceSubClass, 8 );
+ printProgStr(Dev_Protocol_str);
+ print_hex( buf.bDeviceProtocol, 8 );
+ printProgStr(Dev_Pktsize_str);
+ print_hex( buf.bMaxPacketSize0, 8 );
+ printProgStr(Dev_Vendor_str);
+ print_hex( buf.idVendor, 16 );
+ printProgStr(Dev_Product_str);
+ print_hex( buf.idProduct, 16 );
+ printProgStr(Dev_Revision_str);
+ print_hex( buf.bcdDevice, 16 );
+ printProgStr(Dev_Mfg_str);
+ print_hex( buf.iManufacturer, 8 );
+ printProgStr(Dev_Prod_str);
+ print_hex( buf.iProduct, 8 );
+ printProgStr(Dev_Serial_str);
+ print_hex( buf.iSerialNumber, 8 );
+ printProgStr(Dev_Nconf_str);
+ print_hex( buf.bNumConfigurations, 8 );
+ num_conf = buf.bNumConfigurations;
+ return ( 0 );
+}
+
+void printhubdescr(uint8_t *descrptr, uint8_t addr)
+{
+ HubDescriptor *pHub = (HubDescriptor*) descrptr;
+ uint8_t len = *((uint8_t*)descrptr);
+
+ printProgStr(PSTR("\r\n\r\nHub Descriptor:\r\n"));
+ printProgStr(PSTR("bDescLength:\t\t"));
+ Serial.println(pHub->bDescLength, HEX);
+
+ printProgStr(PSTR("bDescriptorType:\t"));
+ Serial.println(pHub->bDescriptorType, HEX);
+
+ printProgStr(PSTR("bNbrPorts:\t\t"));
+ Serial.println(pHub->bNbrPorts, HEX);
+
+ printProgStr(PSTR("LogPwrSwitchMode:\t"));
+ Serial.println(pHub->LogPwrSwitchMode, BIN);
+
+ printProgStr(PSTR("CompoundDevice:\t\t"));
+ Serial.println(pHub->CompoundDevice, BIN);
+
+ printProgStr(PSTR("OverCurrentProtectMode:\t"));
+ Serial.println(pHub->OverCurrentProtectMode, BIN);
+
+ printProgStr(PSTR("TTThinkTime:\t\t"));
+ Serial.println(pHub->TTThinkTime, BIN);
+
+ printProgStr(PSTR("PortIndicatorsSupported:"));
+ Serial.println(pHub->PortIndicatorsSupported, BIN);
+
+ printProgStr(PSTR("Reserved:\t\t"));
+ Serial.println(pHub->Reserved, HEX);
+
+ printProgStr(PSTR("bPwrOn2PwrGood:\t\t"));
+ Serial.println(pHub->bPwrOn2PwrGood, HEX);
+
+ printProgStr(PSTR("bHubContrCurrent:\t"));
+ Serial.println(pHub->bHubContrCurrent, HEX);
+
+ for (uint8_t i = 7; i < len; i++)
+ print_hex(descrptr[i], 8);
+
+ //for (uint8_t i=1; i<=pHub->bNbrPorts; i++)
+ // PrintHubPortStatus(&Usb, addr, i, 1);
+}
+
+byte getconfdescr( byte addr, byte conf )
+{
+ uint8_t buf[ BUFSIZE ];
+ uint8_t* buf_ptr = buf;
+ byte rcode;
+ byte descr_length;
+ byte descr_type;
+ unsigned int total_length;
+ rcode = Usb.getConfDescr( addr, 0, 4, conf, buf ); //get total length
+ LOBYTE( total_length ) = buf[ 2 ];
+ HIBYTE( total_length ) = buf[ 3 ];
+ if ( total_length > 256 ) { //check if total length is larger than buffer
+ printProgStr(Conf_Trunc_str);
+ total_length = 256;
+ }
+ rcode = Usb.getConfDescr( addr, 0, total_length, conf, buf ); //get the whole descriptor
+ while ( buf_ptr < buf + total_length ) { //parsing descriptors
+ descr_length = *( buf_ptr );
+ descr_type = *( buf_ptr + 1 );
+ switch ( descr_type ) {
+ case ( USB_DESCRIPTOR_CONFIGURATION ):
+ printconfdescr( buf_ptr );
+ break;
+ case ( USB_DESCRIPTOR_INTERFACE ):
+ printintfdescr( buf_ptr );
+ break;
+ case ( USB_DESCRIPTOR_ENDPOINT ):
+ printepdescr( buf_ptr );
+ break;
+ case 0x29:
+ printhubdescr( buf_ptr, addr );
+ break;
+ default:
+ printunkdescr( buf_ptr );
+ break;
+ }//switch( descr_type
+ buf_ptr = ( buf_ptr + descr_length ); //advance buffer pointer
+ }//while( buf_ptr <=...
+ return ( rcode );
+}
+/* prints hex numbers with leading zeroes */
+// copyright, Peter H Anderson, Baltimore, MD, Nov, '07
+// source: http://www.phanderson.com/arduino/arduino_display.html
+void print_hex(int v, int num_places)
+{
+ int mask = 0, n, num_nibbles, digit;
+
+ for (n = 1; n <= num_places; n++) {
+ mask = (mask << 1) | 0x0001;
+ }
+ v = v & mask; // truncate v to specified number of places
+
+ num_nibbles = num_places / 4;
+ if ((num_places % 4) != 0) {
+ ++num_nibbles;
+ }
+ do {
+ digit = ((v >> (num_nibbles - 1) * 4)) & 0x0f;
+ Serial.print(digit, HEX);
+ }
+ while (--num_nibbles);
+}
+/* function to print configuration descriptor */
+void printconfdescr( uint8_t* descr_ptr )
+{
+ USB_CONFIGURATION_DESCRIPTOR* conf_ptr = ( USB_CONFIGURATION_DESCRIPTOR* )descr_ptr;
+ printProgStr(Conf_Header_str);
+ printProgStr(Conf_Totlen_str);
+ print_hex( conf_ptr->wTotalLength, 16 );
+ printProgStr(Conf_Nint_str);
+ print_hex( conf_ptr->bNumInterfaces, 8 );
+ printProgStr(Conf_Value_str);
+ print_hex( conf_ptr->bConfigurationValue, 8 );
+ printProgStr(Conf_String_str);
+ print_hex( conf_ptr->iConfiguration, 8 );
+ printProgStr(Conf_Attr_str);
+ print_hex( conf_ptr->bmAttributes, 8 );
+ printProgStr(Conf_Pwr_str);
+ print_hex( conf_ptr->bMaxPower, 8 );
+ return;
+}
+/* function to print interface descriptor */
+void printintfdescr( uint8_t* descr_ptr )
+{
+ USB_INTERFACE_DESCRIPTOR* intf_ptr = ( USB_INTERFACE_DESCRIPTOR* )descr_ptr;
+ printProgStr(Int_Header_str);
+ printProgStr(Int_Number_str);
+ print_hex( intf_ptr->bInterfaceNumber, 8 );
+ printProgStr(Int_Alt_str);
+ print_hex( intf_ptr->bAlternateSetting, 8 );
+ printProgStr(Int_Endpoints_str);
+ print_hex( intf_ptr->bNumEndpoints, 8 );
+ printProgStr(Int_Class_str);
+ print_hex( intf_ptr->bInterfaceClass, 8 );
+ printProgStr(Int_Subclass_str);
+ print_hex( intf_ptr->bInterfaceSubClass, 8 );
+ printProgStr(Int_Protocol_str);
+ print_hex( intf_ptr->bInterfaceProtocol, 8 );
+ printProgStr(Int_String_str);
+ print_hex( intf_ptr->iInterface, 8 );
+ return;
+}
+/* function to print endpoint descriptor */
+void printepdescr( uint8_t* descr_ptr )
+{
+ USB_ENDPOINT_DESCRIPTOR* ep_ptr = ( USB_ENDPOINT_DESCRIPTOR* )descr_ptr;
+ printProgStr(End_Header_str);
+ printProgStr(End_Address_str);
+ print_hex( ep_ptr->bEndpointAddress, 8 );
+ printProgStr(End_Attr_str);
+ print_hex( ep_ptr->bmAttributes, 8 );
+ printProgStr(End_Pktsize_str);
+ print_hex( ep_ptr->wMaxPacketSize, 16 );
+ printProgStr(End_Interval_str);
+ print_hex( ep_ptr->bInterval, 8 );
+
+ return;
+}
+/*function to print unknown descriptor */
+void printunkdescr( uint8_t* descr_ptr )
+{
+ byte length = *descr_ptr;
+ byte i;
+ printProgStr(Unk_Header_str);
+ printProgStr(Unk_Length_str);
+ print_hex( *descr_ptr, 8 );
+ printProgStr(Unk_Type_str);
+ print_hex( *(descr_ptr + 1 ), 8 );
+ printProgStr(Unk_Contents_str);
+ descr_ptr += 2;
+ for ( i = 0; i < length; i++ ) {
+ print_hex( *descr_ptr, 8 );
+ descr_ptr++;
+ }
+}
+
+
+/* Print a string from Program Memory directly to save RAM */
+void printProgStr(const char* str)
+{
+ char c;
+ if (!str) return;
+ while ((c = pgm_read_byte(str++)))
+ Serial.print(c);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/hub_demo/pgmstrings.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/hub_demo/pgmstrings.h
new file mode 100644
index 000000000..bdb0077ec
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/hub_demo/pgmstrings.h
@@ -0,0 +1,52 @@
+#if !defined(__PGMSTRINGS_H__)
+#define __PGMSTRINGS_H__
+
+#define LOBYTE(x) ((char*)(&(x)))[0]
+#define HIBYTE(x) ((char*)(&(x)))[1]
+#define BUFSIZE 256 //buffer size
+
+
+/* Print strings in Program Memory */
+const char Gen_Error_str[] PROGMEM = "\r\nRequest error. Error code:\t";
+const char Dev_Header_str[] PROGMEM ="\r\nDevice descriptor: ";
+const char Dev_Length_str[] PROGMEM ="\r\nDescriptor Length:\t";
+const char Dev_Type_str[] PROGMEM ="\r\nDescriptor type:\t";
+const char Dev_Version_str[] PROGMEM ="\r\nUSB version:\t\t";
+const char Dev_Class_str[] PROGMEM ="\r\nDevice class:\t\t";
+const char Dev_Subclass_str[] PROGMEM ="\r\nDevice Subclass:\t";
+const char Dev_Protocol_str[] PROGMEM ="\r\nDevice Protocol:\t";
+const char Dev_Pktsize_str[] PROGMEM ="\r\nMax.packet size:\t";
+const char Dev_Vendor_str[] PROGMEM ="\r\nVendor ID:\t\t";
+const char Dev_Product_str[] PROGMEM ="\r\nProduct ID:\t\t";
+const char Dev_Revision_str[] PROGMEM ="\r\nRevision ID:\t\t";
+const char Dev_Mfg_str[] PROGMEM ="\r\nMfg.string index:\t";
+const char Dev_Prod_str[] PROGMEM ="\r\nProd.string index:\t";
+const char Dev_Serial_str[] PROGMEM ="\r\nSerial number index:\t";
+const char Dev_Nconf_str[] PROGMEM ="\r\nNumber of conf.:\t";
+const char Conf_Trunc_str[] PROGMEM ="Total length truncated to 256 bytes";
+const char Conf_Header_str[] PROGMEM ="\r\nConfiguration descriptor:";
+const char Conf_Totlen_str[] PROGMEM ="\r\nTotal length:\t\t";
+const char Conf_Nint_str[] PROGMEM ="\r\nNum.intf:\t\t";
+const char Conf_Value_str[] PROGMEM ="\r\nConf.value:\t\t";
+const char Conf_String_str[] PROGMEM ="\r\nConf.string:\t\t";
+const char Conf_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char Conf_Pwr_str[] PROGMEM ="\r\nMax.pwr:\t\t";
+const char Int_Header_str[] PROGMEM ="\r\n\r\nInterface descriptor:";
+const char Int_Number_str[] PROGMEM ="\r\nIntf.number:\t\t";
+const char Int_Alt_str[] PROGMEM ="\r\nAlt.:\t\t\t";
+const char Int_Endpoints_str[] PROGMEM ="\r\nEndpoints:\t\t";
+const char Int_Class_str[] PROGMEM ="\r\nIntf. Class:\t\t";
+const char Int_Subclass_str[] PROGMEM ="\r\nIntf. Subclass:\t\t";
+const char Int_Protocol_str[] PROGMEM ="\r\nIntf. Protocol:\t\t";
+const char Int_String_str[] PROGMEM ="\r\nIntf.string:\t\t";
+const char End_Header_str[] PROGMEM ="\r\n\r\nEndpoint descriptor:";
+const char End_Address_str[] PROGMEM ="\r\nEndpoint address:\t";
+const char End_Attr_str[] PROGMEM ="\r\nAttr.:\t\t\t";
+const char End_Pktsize_str[] PROGMEM ="\r\nMax.pkt size:\t\t";
+const char End_Interval_str[] PROGMEM ="\r\nPolling interval:\t";
+const char Unk_Header_str[] PROGMEM = "\r\nUnknown descriptor:";
+const char Unk_Length_str[] PROGMEM ="\r\nLength:\t\t";
+const char Unk_Type_str[] PROGMEM ="\r\nType:\t\t";
+const char Unk_Contents_str[] PROGMEM ="\r\nContents:\t";
+
+#endif // __PGMSTRINGS_H__ \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/max_LCD/max_LCD.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/max_LCD/max_LCD.ino
new file mode 100644
index 000000000..6603ab90d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/max_LCD/max_LCD.ino
@@ -0,0 +1,29 @@
+// Just a copy of the HelloWorld example bundled with the LiquidCrystal library in the Arduino IDE
+
+// HD44780 compatible LCD display via MAX3421E GPOUT support header
+// pinout: D[4-7] -> GPOUT[4-7], RS-> GPOUT[2], E ->GPOUT[3]
+
+#include <max_LCD.h>
+
+// Satisfy IDE, which only needs to see the include statment in the ino.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+USB Usb;
+Max_LCD lcd(&Usb);
+
+void setup() {
+ // Set up the LCD's number of columns and rows:
+ lcd.begin(16, 2);
+ // Print a message to the LCD.
+ lcd.print("Hello, World!");
+}
+
+void loop() {
+ // Set the cursor to column 0, line 1 (note: line 1 is the second row, since counting begins with 0):
+ lcd.setCursor(0, 1);
+ // Print the number of seconds since reset:
+ lcd.print(millis() / 1000);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_gprs_terminal/pl2303_gprs_terminal.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_gprs_terminal/pl2303_gprs_terminal.ino
new file mode 100644
index 000000000..7c4c9f6cb
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_gprs_terminal/pl2303_gprs_terminal.ino
@@ -0,0 +1,101 @@
+/* Arduino terminal for PL2303 USB to serial converter and DealeXtreme GPRS modem. */
+/* USB support */
+#include <usbhub.h>
+/* CDC support */
+#include <cdcacm.h>
+#include <cdcprolific.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class PLAsyncOper : public CDCAsyncOper
+{
+public:
+ uint8_t OnInit(ACM *pacm);
+};
+
+uint8_t PLAsyncOper::OnInit(ACM *pacm)
+{
+ uint8_t rcode;
+
+ // Set DTR = 1
+ rcode = pacm->SetControlLineState(1);
+
+ if (rcode)
+ {
+ ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
+ return rcode;
+ }
+
+ LINE_CODING lc;
+ //lc.dwDTERate = 9600;
+ lc.dwDTERate = 115200;
+ lc.bCharFormat = 0;
+ lc.bParityType = 0;
+ lc.bDataBits = 8;
+
+ rcode = pacm->SetLineCoding(&lc);
+
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
+
+ return rcode;
+}
+USB Usb;
+//USBHub Hub(&Usb);
+PLAsyncOper AsyncOper;
+PL2303 Pl(&Usb, &AsyncOper);
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSCOKIRQ failed to assert");
+
+ delay( 200 );
+}
+
+void loop()
+{
+ Usb.Task();
+
+ if( Usb.getUsbTaskState() == USB_STATE_RUNNING )
+ {
+ uint8_t rcode;
+
+ /* reading the keyboard */
+ if(Serial.available()) {
+ uint8_t data= Serial.read();
+
+ /* sending to the phone */
+ rcode = Pl.SndData(1, &data);
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
+ }//if(Serial.available()...
+
+ /* reading the converter */
+ /* buffer size must be greater or equal to max.packet size */
+ /* it it set to 64 (largest possible max.packet size) here, can be tuned down
+ for particular endpoint */
+ uint8_t buf[64];
+ uint16_t rcvd = 64;
+ rcode = Pl.RcvData(&rcvd, buf);
+ if (rcode && rcode != hrNAK)
+ ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
+
+ if( rcvd ) { //more than zero bytes received
+ for(uint16_t i=0; i < rcvd; i++ ) {
+ Serial.print((char)buf[i]); //printing on the screen
+ }
+ }//if( rcvd ...
+ }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING..
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_gps/pl2303_gps.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_gps/pl2303_gps.ino
new file mode 100644
index 000000000..e8c8a0223
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_gps/pl2303_gps.ino
@@ -0,0 +1,88 @@
+/* USB Host to PL2303-based USB GPS unit interface */
+/* Navibee GM720 receiver - Sirf Star III */
+/* USB support */
+#include <usbhub.h>
+/* CDC support */
+#include <cdcacm.h>
+#include <cdcprolific.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class PLAsyncOper : public CDCAsyncOper {
+public:
+ uint8_t OnInit(ACM *pacm);
+};
+
+uint8_t PLAsyncOper::OnInit(ACM *pacm) {
+ uint8_t rcode;
+
+ // Set DTR = 1
+ rcode = pacm->SetControlLineState(1);
+
+ if(rcode) {
+ ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
+ return rcode;
+ }
+
+ LINE_CODING lc;
+ lc.dwDTERate = 4800; //default serial speed of GPS unit
+ lc.bCharFormat = 0;
+ lc.bParityType = 0;
+ lc.bDataBits = 8;
+
+ rcode = pacm->SetLineCoding(&lc);
+
+ if(rcode)
+ ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
+
+ return rcode;
+}
+
+USB Usb;
+USBHub Hub(&Usb);
+PLAsyncOper AsyncOper;
+PL2303 Pl(&Usb, &AsyncOper);
+uint32_t read_delay;
+#define READ_DELAY 100
+
+void setup() {
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if(Usb.Init() == -1)
+ Serial.println("OSCOKIRQ failed to assert");
+
+ delay(200);
+}
+
+void loop() {
+ uint8_t rcode;
+ uint8_t buf[64]; //serial buffer equals Max.packet size of bulk-IN endpoint
+ uint16_t rcvd = 64;
+
+ Usb.Task();
+
+ if(Pl.isReady()) {
+ /* reading the GPS */
+ if((long)(millis() - read_delay) >= 0L) {
+ read_delay += READ_DELAY;
+ rcode = Pl.RcvData(&rcvd, buf);
+ if(rcode && rcode != hrNAK)
+ ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
+ if(rcvd) { //more than zero bytes received
+ for(uint16_t i = 0; i < rcvd; i++) {
+ Serial.print((char)buf[i]); //printing on the screen
+ }//for( uint16_t i=0; i < rcvd; i++...
+ }//if( rcvd
+ }//if( read_delay > millis()...
+ }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING..
+}
+
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_tinygps/pl2303_tinygps.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_tinygps/pl2303_tinygps.ino
new file mode 100644
index 000000000..d527eabe0
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_tinygps/pl2303_tinygps.ino
@@ -0,0 +1,217 @@
+/* USB Host to PL2303-based USB GPS unit interface */
+/* Navibee GM720 receiver - Sirf Star III */
+/* Mikal Hart's TinyGPS library */
+/* test_with_gps_device library example modified for PL2302 access */
+
+/* USB support */
+#include <usbhub.h>
+
+/* CDC support */
+#include <cdcacm.h>
+#include <cdcprolific.h>
+
+#include <TinyGPS.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+/* This sample code demonstrates the normal use of a TinyGPS object.
+ Modified to be used with USB Host Shield Library r2.0
+ and USB Host Shield 2.0
+*/
+
+class PLAsyncOper : public CDCAsyncOper
+{
+public:
+ uint8_t OnInit(ACM *pacm);
+};
+
+uint8_t PLAsyncOper::OnInit(ACM *pacm)
+{
+ uint8_t rcode;
+
+ // Set DTR = 1
+ rcode = pacm->SetControlLineState(1);
+
+ if (rcode) {
+ ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
+ return rcode;
+ }
+
+ LINE_CODING lc;
+ lc.dwDTERate = 4800; //default serial speed of GPS unit
+ lc.bCharFormat = 0;
+ lc.bParityType = 0;
+ lc.bDataBits = 8;
+
+ rcode = pacm->SetLineCoding(&lc);
+
+ if (rcode) {
+ ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
+ }
+
+ return rcode;
+}
+
+USB Usb;
+//USBHub Hub(&Usb);
+PLAsyncOper AsyncOper;
+PL2303 Pl(&Usb, &AsyncOper);
+TinyGPS gps;
+
+void gpsdump(TinyGPS &gps);
+bool feedgps();
+void printFloat(double f, int digits = 2);
+
+void setup()
+{
+
+ Serial.begin(115200);
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+
+ Serial.print("Testing TinyGPS library v. "); Serial.println(TinyGPS::library_version());
+ Serial.println("by Mikal Hart");
+ Serial.println();
+ Serial.print("Sizeof(gpsobject) = "); Serial.println(sizeof(TinyGPS));
+ Serial.println();
+ /* USB Initialization */
+ if (Usb.Init() == -1) {
+ Serial.println("OSCOKIRQ failed to assert");
+ }
+
+ delay( 200 );
+}
+
+void loop()
+{
+ Usb.Task();
+
+ if( Pl.isReady()) {
+
+ bool newdata = false;
+ unsigned long start = millis();
+
+ // Every 5 seconds we print an update
+ while (millis() - start < 5000) {
+ if( feedgps()) {
+ newdata = true;
+ }
+ }//while (millis()...
+
+ if (newdata) {
+ Serial.println("Acquired Data");
+ Serial.println("-------------");
+ gpsdump(gps);
+ Serial.println("-------------");
+ Serial.println();
+ }//if( newdata...
+ }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING...
+}
+
+void printFloat(double number, int digits)
+{
+ // Handle negative numbers
+ if (number < 0.0)
+ {
+ Serial.print('-');
+ number = -number;
+ }
+
+ // Round correctly so that print(1.999, 2) prints as "2.00"
+ double rounding = 0.5;
+ for (uint8_t i=0; i<digits; ++i)
+ rounding /= 10.0;
+
+ number += rounding;
+
+ // Extract the integer part of the number and print it
+ unsigned long int_part = (unsigned long)number;
+ double remainder = number - (double)int_part;
+ Serial.print(int_part);
+
+ // Print the decimal point, but only if there are digits beyond
+ if (digits > 0)
+ Serial.print(".");
+
+ // Extract digits from the remainder one at a time
+ while (digits-- > 0)
+ {
+ remainder *= 10.0;
+ int toPrint = int(remainder);
+ Serial.print(toPrint);
+ remainder -= toPrint;
+ }
+}
+
+void gpsdump(TinyGPS &gps)
+{
+ long lat, lon;
+ float flat, flon;
+ unsigned long age, date, time, chars;
+ int year;
+ byte month, day, hour, minute, second, hundredths;
+ unsigned short sentences, failed;
+
+ gps.get_position(&lat, &lon, &age);
+ Serial.print("Lat/Long(10^-5 deg): "); Serial.print(lat); Serial.print(", "); Serial.print(lon);
+ Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");
+
+ feedgps(); // If we don't feed the gps during this long routine, we may drop characters and get checksum errors
+
+ gps.f_get_position(&flat, &flon, &age);
+ Serial.print("Lat/Long(float): "); printFloat(flat, 5); Serial.print(", "); printFloat(flon, 5);
+ Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");
+
+ feedgps();
+
+ gps.get_datetime(&date, &time, &age);
+ Serial.print("Date(ddmmyy): "); Serial.print(date); Serial.print(" Time(hhmmsscc): "); Serial.print(time);
+ Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");
+
+ feedgps();
+
+ gps.crack_datetime(&year, &month, &day, &hour, &minute, &second, &hundredths, &age);
+ Serial.print("Date: "); Serial.print(static_cast<int>(month)); Serial.print("/"); Serial.print(static_cast<int>(day)); Serial.print("/"); Serial.print(year);
+ Serial.print(" Time: "); Serial.print(static_cast<int>(hour)); Serial.print(":"); Serial.print(static_cast<int>(minute)); Serial.print(":"); Serial.print(static_cast<int>(second)); Serial.print("."); Serial.print(static_cast<int>(hundredths));
+ Serial.print(" Fix age: "); Serial.print(age); Serial.println("ms.");
+
+ feedgps();
+
+ Serial.print("Alt(cm): "); Serial.print(gps.altitude()); Serial.print(" Course(10^-2 deg): "); Serial.print(gps.course()); Serial.print(" Speed(10^-2 knots): "); Serial.println(gps.speed());
+ Serial.print("Alt(float): "); printFloat(gps.f_altitude()); Serial.print(" Course(float): "); printFloat(gps.f_course()); Serial.println();
+ Serial.print("Speed(knots): "); printFloat(gps.f_speed_knots()); Serial.print(" (mph): "); printFloat(gps.f_speed_mph());
+ Serial.print(" (mps): "); printFloat(gps.f_speed_mps()); Serial.print(" (kmph): "); printFloat(gps.f_speed_kmph()); Serial.println();
+
+ feedgps();
+
+ gps.stats(&chars, &sentences, &failed);
+ Serial.print("Stats: characters: "); Serial.print(chars); Serial.print(" sentences: "); Serial.print(sentences); Serial.print(" failed checksum: "); Serial.println(failed);
+}
+
+bool feedgps()
+{
+ uint8_t rcode;
+ uint8_t buf[64]; //serial buffer equals Max.packet size of bulk-IN endpoint
+ uint16_t rcvd = 64;
+ {
+ /* reading the GPS */
+ rcode = Pl.RcvData(&rcvd, buf);
+ if (rcode && rcode != hrNAK)
+ ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
+ rcode = false;
+ if( rcvd ) { //more than zero bytes received
+ for( uint16_t i=0; i < rcvd; i++ ) {
+ if( gps.encode((char)buf[i])) { //feed a character to gps object
+ rcode = true;
+ }//if( gps.encode(buf[i]...
+ }//for( uint16_t i=0; i < rcvd; i++...
+ }//if( rcvd...
+ }
+ return( rcode );
+}
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_xbee_terminal/pl2303_xbee_terminal.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_xbee_terminal/pl2303_xbee_terminal.ino
new file mode 100644
index 000000000..67b7dab60
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/pl2303/pl2303_xbee_terminal/pl2303_xbee_terminal.ino
@@ -0,0 +1,117 @@
+/* Arduino terminal for PL2303 USB to serial converter and XBee radio. */
+/* Inserts linefeed after carriage return in data sent to and received from Xbee */
+/* USB support */
+#include <usbhub.h>
+/* CDC support */
+#include <cdcacm.h>
+#include <cdcprolific.h>
+
+// Satisfy the IDE, which needs to see the include statment in the ino too.
+#ifdef dobogusinclude
+#include <spi4teensy3.h>
+#include <SPI.h>
+#endif
+
+class PLAsyncOper : public CDCAsyncOper
+{
+public:
+ uint8_t OnInit(ACM *pacm);
+};
+
+uint8_t PLAsyncOper::OnInit(ACM *pacm)
+{
+ uint8_t rcode;
+
+ // Set DTR = 1
+ rcode = pacm->SetControlLineState(1);
+
+ if (rcode)
+ {
+ ErrorMessage<uint8_t>(PSTR("SetControlLineState"), rcode);
+ return rcode;
+ }
+
+ LINE_CODING lc;
+ lc.dwDTERate = 115200;
+ lc.bCharFormat = 0;
+ lc.bParityType = 0;
+ lc.bDataBits = 8;
+
+ rcode = pacm->SetLineCoding(&lc);
+
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SetLineCoding"), rcode);
+
+ return rcode;
+}
+USB Usb;
+//USBHub Hub(&Usb);
+PLAsyncOper AsyncOper;
+PL2303 Pl(&Usb, &AsyncOper);
+
+void setup()
+{
+ Serial.begin( 115200 );
+#if !defined(__MIPSEL__)
+ while (!Serial); // Wait for serial port to connect - used on Leonardo, Teensy and other boards with built-in USB CDC serial connection
+#endif
+ Serial.println("Start");
+
+ if (Usb.Init() == -1)
+ Serial.println("OSCOKIRQ failed to assert");
+
+ delay( 200 );
+}
+
+void loop()
+{
+ Usb.Task();
+
+ if( Usb.getUsbTaskState() == USB_STATE_RUNNING )
+ {
+ uint8_t rcode;
+
+ /* reading the keyboard */
+ if(Serial.available()) {
+ uint8_t data= Serial.read();
+
+ if ( data == '\r' ) {
+ Serial.print("\r\n"); //insert linefeed
+ }
+ else {
+ Serial.print( data ); //echo back to the screen
+ }
+
+ /* sending to the phone */
+ rcode = Pl.SndData(1, &data);
+ if (rcode)
+ ErrorMessage<uint8_t>(PSTR("SndData"), rcode);
+ }//if(Serial.available()...
+
+ delay(50);
+
+ /* reading the converter */
+ /* buffer size must be greater or equal to max.packet size */
+ /* it it set to 64 (largest possible max.packet size) here, can be tuned down
+ for particular endpoint */
+ uint8_t buf[64];
+ uint16_t rcvd = 64;
+ rcode = Pl.RcvData(&rcvd, buf);
+ if (rcode && rcode != hrNAK)
+ ErrorMessage<uint8_t>(PSTR("Ret"), rcode);
+
+ if( rcvd ) { //more than zero bytes received
+ for(uint16_t i=0; i < rcvd; i++ ) {
+ if( buf[i] =='\r' ) {
+ Serial.print("\r\n"); //insert linefeed
+ }
+ else {
+ Serial.print((char)buf[i]); //printing on the screen
+ }
+ }
+ }
+ delay(10);
+ }//if( Usb.getUsbTaskState() == USB_STATE_RUNNING..
+}
+
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/Makefile b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/Makefile
new file mode 100644
index 000000000..8a12ddc04
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/Makefile
@@ -0,0 +1,64 @@
+#
+# These are set for a mega 1280 + quadram plus my serial patch.
+# If you lack quadram, or want to disable LFN, just change _FS_TINY=1 _USE_LFN=0
+#
+# If your board is a mega 2560 comment out the following two lines
+BOARD = mega
+
+BOARD_SUB = mega.menu.cpu.atmega1280
+PROGRAMMER = arduino
+
+# ...and then uncomment out the following two lines
+#BOARD_SUB = mega.menu.cpu.atmega2560
+#PROGRAMMER = wiring
+
+#BOARD = teensypp2
+#BOARD = teensy3
+#BOARD = teensy31
+
+# set your Arduino tty port here
+PORT = /dev/ttyUSB0
+
+EXTRA_FLAGS = -D _USE_LFN=3
+
+# change to 0 if you have quadram to take advantage of caching FAT
+EXTRA_FLAGS += -D _FS_TINY=1
+
+
+EXTRA_FLAGS += -D _MAX_SS=512
+
+
+# Don't worry if you don't have external RAM, xmem2 detects this situation.
+# You *WILL* be wanting to get some kind of external ram on your mega in order to
+# do anything that is intense.
+EXTRA_FLAGS += -D EXT_RAM_STACK=1
+EXTRA_FLAGS += -D EXT_RAM_HEAP=1
+
+
+# These are no longer needed for the demo to work.
+# In the event you need more ram, uncomment these 3 lines.
+#EXTRA_FLAGS += -D DISABLE_SERIAL1
+#EXTRA_FLAGS += -D DISABLE_SERIAL2
+#EXTRA_FLAGS += -D DISABLE_SERIAL3
+
+#
+# Advanced debug on Serial3
+#
+
+# uncomment the next two to enable debug on Serial3
+EXTRA_FLAGS += -D USB_HOST_SERIAL=Serial3
+#EXTRA_FLAGS += -D DEBUG_USB_HOST
+
+# The following are the libraries used.
+LIB_DIRS += ../../
+LIB_DIRS += ../testusbhostFAT/xmem2
+LIB_DIRS += ../testusbhostFAT/generic_storage
+LIB_DIRS += ../testusbhostFAT/RTClib
+LIB_DIRS += $(ARD_HOME)/libraries/Wire
+LIB_DIRS += $(ARD_HOME)/libraries/Wire/utility
+LIB_DIRS += $(ARD_HOME)/hardware/arduino/$(BUILD_ARCH)/libraries/Wire
+LIB_DIRS += $(ARD_HOME)/hardware/arduino/$(BUILD_ARCH)/libraries/Wire/utility
+LIB_DIRS += $(ARD_HOME)/hardware/arduino/$(BUILD_ARCH)/libraries/SPI
+
+# And finally, the part that brings everything together for you.
+include Arduino_Makefile_master/_Makefile.master
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/readme.md b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/readme.md
new file mode 100644
index 000000000..d8b4296b1
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/readme.md
@@ -0,0 +1,29 @@
+This small sketch tests the USB host shield mass storage library.
+
+__Note:__ This will not run a Arduino Uno due to the limited ram available in the ATmega328p.
+
+The Arduino Mega (ATmega1280) and the Arduino Mega 2560 (ATmega2560) are confirmed to work with this test code.
+
+To compile this example you will need the following libraries as well:
+
+* [xmem2](https://github.com/xxxajk/xmem2)
+* [generic_storage FATfs](https://github.com/xxxajk/generic_storage)
+* [RTClib](https://github.com/xxxajk/RTClib)
+
+The following shield is recommended for larger projects: <http://ruggedcircuits.com/html/quadram.html>.
+
+You may use the bundled [Makefile](Makefile) to compile the code instead of the Arduino IDE if you have problems or want a smaller binary. The master makefile is bundled as a submodule, but can also be downloaded manually at the following link: <https://github.com/xxxajk/Arduino_Makefile_master>.
+
+To download the USB Host library and all the needed libraries for this test.
+
+Run the following command in a terminal application:
+
+```
+git clone --recursive https://github.com/felis/USB_Host_Shield_2.0
+```
+
+If you want to update all the submodules run:
+
+```
+git submodule foreach --recursive git pull origin master
+```
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/testusbhostFAT.ino b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/testusbhostFAT.ino
new file mode 100644
index 000000000..e8b9cd359
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/examples/testusbhostFAT/testusbhostFAT.ino
@@ -0,0 +1,736 @@
+/*
+ * Mega + USB storage + optional DS1307 + optional expansion RAM + funky status LED,
+ * Includes interactive debug level setting, and supports hot-plug.
+ *
+ * IMPORTANT! PLEASE USE Arduino 1.0.5 or better!
+ * Older versions HAVE MAJOR BUGS AND WILL NOT WORK AT ALL!
+ * Use of gcc-avr and lib-c that is newer than the Arduino version is even better.
+ * If you experience random crashes, use make.
+ * The options that the IDE use can generate bad code and cause the AVR to crash.
+ *
+ * This sketch requires the following libraries:
+ * https://github.com/felis/USB_Host_Shield_2.0 Install as 'USB_Host_Shield_2_0'
+ * https://github.com/xxxajk/xmem2 Install as 'xmem', provides memory services.
+ * https://github.com/xxxajk/generic_storage provides access to FAT file system.
+ * https://github.com/xxxajk/RTClib provides access to DS1307, or fake clock.
+ *
+ * Optional, to use the Makefile (Recommended! See above!):
+ * https://github.com/xxxajk/Arduino_Makefile_master
+ *
+ */
+
+/////////////////////////////////////////////////////////////
+// Please Note: //
+// This section is for info with the Arduino IDE ONLY. //
+// Unfortunately due to short sightedness of the Arduino //
+// code team, that you must set the following in the //
+// respective libraries. //
+// Changing them here will have _NO_ effect! //
+/////////////////////////////////////////////////////////////
+
+// Uncomment to enable debugging
+//#define DEBUG_USB_HOST
+// This is where stderr/USB debugging goes to
+//#define USB_HOST_SERIAL Serial3
+
+// If you have external memory, setting this to 0 enables FAT table caches.
+// The 0 setting is recommended only if you have external memory.
+//#define _FS_TINY 1
+
+//#define _USE_LFN 3
+//#define _MAX_SS 512
+
+
+/////////////////////////////////////////////////////////////
+// End of Arduino IDE specific information //
+/////////////////////////////////////////////////////////////
+
+// You can set this to 0 if you are not using a USB hub.
+// It will save a little bit of flash and RAM.
+// Set to 1 if you want to use a hub.
+#define WANT_HUB_TEST 1
+
+// this is for XMEM2
+#define EXT_RAM_STACK 1
+#define EXT_RAM_HEAP 1
+#define LOAD_XMEM
+
+#if defined(CORE_TEENSY) && !defined(_AVR_)
+#include <xmem.h>
+#include <spi4teensy3.h>
+#endif
+
+#if defined(__AVR__)
+#include <xmem.h>
+#include <SPI.h>
+#elif defined(ARDUINO_ARCH_SAM)
+#include <SPI.h>
+#endif
+
+#if WANT_HUB_TEST
+#include <usbhub.h>
+#endif
+#include <Wire.h>
+#define LOAD_RTCLIB
+#include <RTClib.h>
+#include <masstorage.h>
+#include <Storage.h>
+#include <PCpartition/PCPartition.h>
+#include <avr/interrupt.h>
+#include <FAT/FAT.h>
+#include <stdio.h>
+#if defined(__AVR__)
+static FILE tty_stdio;
+static FILE tty_stderr;
+volatile uint32_t LEDnext_time; // fade timeout
+volatile uint32_t HEAPnext_time; // when to print out next heap report
+volatile int brightness = 0; // how bright the LED is
+volatile int fadeAmount = 80; // how many points to fade the LED by
+#endif
+
+USB Usb;
+
+volatile uint8_t current_state = 1;
+volatile uint8_t last_state = 0;
+volatile bool fatready = false;
+volatile bool partsready = false;
+volatile bool notified = false;
+volatile bool runtest = false;
+volatile bool usbon = false;
+volatile uint32_t usbon_time;
+volatile bool change = false;
+volatile bool reportlvl = false;
+int cpart = 0;
+PCPartition *PT;
+
+#if WANT_HUB_TEST
+#define MAX_HUBS 1
+USBHub *Hubs[MAX_HUBS];
+#endif
+
+static PFAT *Fats[_VOLUMES];
+static part_t parts[_VOLUMES];
+static storage_t sto[_VOLUMES];
+
+/*make sure this is a power of two. */
+#define mbxs 128
+static uint8_t My_Buff_x[mbxs]; /* File read buffer */
+
+#if defined(__AVR__)
+
+#define prescale1 ((1 << WGM12) | (1 << CS10))
+#define prescale8 ((1 << WGM12) | (1 << CS11))
+#define prescale64 ((1 << WGM12) | (1 << CS10) | (1 << CS11))
+#define prescale256 ((1 << WGM12) | (1 << CS12))
+#define prescale1024 ((1 << WGM12) | (1 << CS12) | (1 << CS10))
+
+extern "C" {
+ extern unsigned int freeHeap();
+}
+static int tty_stderr_putc(char c, FILE *t) {
+ USB_HOST_SERIAL.write(c);
+ return 0;
+}
+
+static int __attribute__((unused)) tty_stderr_flush(FILE *t) {
+ USB_HOST_SERIAL.flush();
+ return 0;
+}
+
+static int tty_std_putc(char c, FILE *t) {
+ Serial.write(c);
+ return 0;
+}
+
+static int tty_std_getc(FILE *t) {
+ while(!Serial.available());
+ return Serial.read();
+}
+
+static int __attribute__((unused)) tty_std_flush(FILE *t) {
+ Serial.flush();
+ return 0;
+}
+
+#else
+// Supposedly the DUE has stdio already pointing to serial...
+#if !defined(ARDUINO_ARCH_SAM)
+// But newlib needs this...
+extern "C" {
+ int _write(int fd, const char *ptr, int len) {
+ int j;
+ for(j = 0; j < len; j++) {
+ if(fd == 1)
+ Serial.write(*ptr++);
+ else if(fd == 2)
+ USB_HOST_SERIAL.write(*ptr++);
+ }
+ return len;
+ }
+
+ int _read(int fd, char *ptr, int len) {
+ if(len > 0 && fd == 0) {
+ while(!Serial.available());
+ *ptr = Serial.read();
+ return 1;
+ }
+ return 0;
+ }
+
+#include <sys/stat.h>
+
+ int _fstat(int fd, struct stat *st) {
+ memset(st, 0, sizeof (*st));
+ st->st_mode = S_IFCHR;
+ st->st_blksize = 1024;
+ return 0;
+ }
+
+ int _isatty(int fd) {
+ return (fd < 3) ? 1 : 0;
+ }
+}
+#endif // !defined(ARDUINO_ARCH_SAM)
+#endif
+
+void setup() {
+ bool serr = false;
+ for(int i = 0; i < _VOLUMES; i++) {
+ Fats[i] = NULL;
+ sto[i].private_data = new pvt_t;
+ ((pvt_t *)sto[i].private_data)->B = 255; // impossible
+ }
+ // Set this to higher values to enable more debug information
+ // minimum 0x00, maximum 0xff
+ UsbDEBUGlvl = 0x81;
+
+#if !defined(CORE_TEENSY) && defined(__AVR__)
+ // make LED pin as an output:
+ pinMode(LED_BUILTIN, OUTPUT);
+ pinMode(2, OUTPUT);
+ // Ensure TX is off
+ _SFR_BYTE(UCSR0B) &= ~_BV(TXEN0);
+ // Initialize 'debug' serial port
+ USB_HOST_SERIAL.begin(115200);
+ // Do not start primary Serial port if already started.
+ if(bit_is_clear(UCSR0B, TXEN0)) {
+ Serial.begin(115200);
+ serr = true;
+ }
+
+
+ // Blink LED
+ delay(500);
+ analogWrite(LED_BUILTIN, 255);
+ delay(500);
+ analogWrite(LED_BUILTIN, 0);
+ delay(500);
+#else
+ while(!Serial);
+ Serial.begin(115200); // On the Teensy 3.x we get a delay at least!
+#endif
+#if defined(__AVR__)
+ // Set up stdio/stderr
+ tty_stdio.put = tty_std_putc;
+ tty_stdio.get = tty_std_getc;
+ tty_stdio.flags = _FDEV_SETUP_RW;
+ tty_stdio.udata = 0;
+
+ tty_stderr.put = tty_stderr_putc;
+ tty_stderr.get = NULL;
+ tty_stderr.flags = _FDEV_SETUP_WRITE;
+ tty_stderr.udata = 0;
+
+ stdout = &tty_stdio;
+ stdin = &tty_stdio;
+ stderr = &tty_stderr;
+#endif
+ printf_P(PSTR("\r\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nStart\r\n"));
+ printf_P(PSTR("Current UsbDEBUGlvl %02x\r\n"), UsbDEBUGlvl);
+ printf_P(PSTR("'+' and '-' increase/decrease by 0x01\r\n"));
+ printf_P(PSTR("'.' and ',' increase/decrease by 0x10\r\n"));
+ printf_P(PSTR("'t' will run a 10MB write/read test and print out the time it took.\r\n"));
+ printf_P(PSTR("'e' will toggle vbus off for a few moments.\r\n\r\n"));
+ printf_P(PSTR("Long filename support: "
+#if _USE_LFN
+ "Enabled"
+#else
+ "Disabled"
+#endif
+ "\r\n"));
+ if(serr) {
+ fprintf_P(stderr, PSTR("\r\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nStart\r\n"));
+ fprintf_P(stderr, PSTR("Current UsbDEBUGlvl %02x\r\n"), UsbDEBUGlvl);
+ fprintf_P(stderr, PSTR("Long filename support: "
+#if _USE_LFN
+ "Enabled"
+#else
+ "Disabled"
+#endif
+ "\r\n"));
+ }
+
+#if !defined(CORE_TEENSY) && defined(__AVR__)
+ analogWrite(LED_BUILTIN, 255);
+ delay(500);
+ analogWrite(LED_BUILTIN, 0);
+ delay(500);
+ analogWrite(LED_BUILTIN, 255);
+ delay(500);
+ analogWrite(LED_BUILTIN, 0);
+ delay(500);
+ analogWrite(LED_BUILTIN, 255);
+ delay(500);
+ analogWrite(LED_BUILTIN, 0);
+ delay(500);
+
+ LEDnext_time = millis() + 1;
+#if EXT_RAM
+ printf_P(PSTR("Total EXT RAM banks %i\r\n"), xmem::getTotalBanks());
+#endif
+ printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap());
+ printf_P(PSTR("SP %x\r\n"), (uint8_t *)(SP));
+#endif
+
+ // Even though I'm not going to actually be deleting,
+ // I want to be able to have slightly more control.
+ // Besides, it is easier to initialize stuff...
+#if WANT_HUB_TEST
+ for(int i = 0; i < MAX_HUBS; i++) {
+ Hubs[i] = new USBHub(&Usb);
+#if defined(__AVR__)
+ printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap());
+#endif
+ }
+#endif
+ // Initialize generic storage. This must be done before USB starts.
+ Init_Generic_Storage();
+
+ while(Usb.Init(1000) == -1) {
+ printf_P(PSTR("No USB HOST Shield?\r\n"));
+ Notify(PSTR("OSC did not start."), 0x40);
+ }
+
+#if !defined(CORE_TEENSY) && defined(__AVR__)
+ cli();
+ TCCR3A = 0;
+ TCCR3B = 0;
+ // (0.01/(1/((16 *(10^6)) / 8))) - 1 = 19999
+ OCR3A = 19999;
+ TCCR3B |= prescale8;
+ TIMSK3 |= (1 << OCIE1A);
+ sei();
+
+ HEAPnext_time = millis() + 10000;
+#endif
+#if defined(__AVR__)
+ HEAPnext_time = millis() + 10000;
+#endif
+}
+
+void serialEvent() {
+ // Adjust UsbDEBUGlvl level on-the-fly.
+ // + to increase, - to decrease, * to display current level.
+ // . to increase by 16, , to decrease by 16
+ // e to flick VBUS
+ // * to report debug level
+ if(Serial.available()) {
+ int inByte = Serial.read();
+ switch(inByte) {
+ case '+':
+ if(UsbDEBUGlvl < 0xff) UsbDEBUGlvl++;
+ reportlvl = true;
+ break;
+ case '-':
+ if(UsbDEBUGlvl > 0x00) UsbDEBUGlvl--;
+ reportlvl = true;
+ break;
+ case '.':
+ if(UsbDEBUGlvl < 0xf0) UsbDEBUGlvl += 16;
+ reportlvl = true;
+ break;
+ case ',':
+ if(UsbDEBUGlvl > 0x0f) UsbDEBUGlvl -= 16;
+ reportlvl = true;
+ break;
+ case '*':
+ reportlvl = true;
+ break;
+ case 't':
+ runtest = true;
+ break;
+ case 'e':
+ change = true;
+ usbon = false;
+ break;
+ }
+ }
+}
+
+#if !defined(CORE_TEENSY) && defined(__AVR__)
+// ALL teensy versions LACK PWM ON LED
+
+ISR(TIMER3_COMPA_vect) {
+ if((long)(millis() - LEDnext_time) >= 0L) {
+ LEDnext_time = millis() + 30;
+
+ // set the brightness of LED
+ analogWrite(LED_BUILTIN, brightness);
+
+ // change the brightness for next time through the loop:
+ brightness = brightness + fadeAmount;
+
+ // reverse the direction of the fading at the ends of the fade:
+ if(brightness <= 0) {
+ brightness = 0;
+ fadeAmount = -fadeAmount;
+ }
+ if(brightness >= 255) {
+ brightness = 255;
+ fadeAmount = -fadeAmount;
+ }
+ }
+}
+#endif
+
+bool isfat(uint8_t t) {
+ return (t == 0x01 || t == 0x04 || t == 0x06 || t == 0x0b || t == 0x0c || t == 0x0e || t == 0x1);
+}
+
+void die(FRESULT rc) {
+ printf_P(PSTR("Failed with rc=%u.\r\n"), rc);
+ //for (;;);
+}
+
+void loop() {
+ FIL My_File_Object_x; /* File object */
+
+#if defined(__AVR__)
+ // Print a heap status report about every 10 seconds.
+ if((long)(millis() - HEAPnext_time) >= 0L) {
+ if(UsbDEBUGlvl > 0x50) {
+ printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap());
+ }
+ HEAPnext_time = millis() + 10000;
+ }
+ TCCR3B = 0;
+#endif
+#if defined(CORE_TEENSY)
+ // Teensy suffers here, oh well...
+ serialEvent();
+#endif
+ // Horrid! This sort of thing really belongs in an ISR, not here!
+ // We also will be needing to test each hub port, we don't do this yet!
+ if(!change && !usbon && (long)(millis() - usbon_time) >= 0L) {
+ change = true;
+ usbon = true;
+ }
+
+ if(change) {
+ change = false;
+ if(usbon) {
+ Usb.vbusPower(vbus_on);
+ printf_P(PSTR("VBUS on\r\n"));
+ } else {
+ Usb.vbusPower(vbus_off);
+ usbon_time = millis() + 2000;
+ }
+ }
+ Usb.Task();
+ current_state = Usb.getUsbTaskState();
+ if(current_state != last_state) {
+ if(UsbDEBUGlvl > 0x50)
+ printf_P(PSTR("USB state = %x\r\n"), current_state);
+#if !defined(CORE_TEENSY) && defined(__AVR__)
+ if(current_state == USB_STATE_RUNNING) {
+ fadeAmount = 30;
+ }
+#endif
+ if(current_state == USB_DETACHED_SUBSTATE_WAIT_FOR_DEVICE) {
+#if !defined(CORE_TEENSY) && defined(__AVR__)
+ fadeAmount = 80;
+#endif
+ partsready = false;
+ for(int i = 0; i < cpart; i++) {
+ if(Fats[i] != NULL)
+ delete Fats[i];
+ Fats[i] = NULL;
+ }
+ fatready = false;
+ notified = false;
+ cpart = 0;
+ }
+ last_state = current_state;
+ }
+
+ // only do any of this if usb is on
+ if(usbon) {
+ if(partsready && !fatready) {
+ if(cpart > 0) fatready = true;
+ }
+ // This is horrible, and needs to be moved elsewhere!
+ for(int B = 0; B < MAX_USB_MS_DRIVERS; B++) {
+ if((!partsready) && (UHS_USB_BulkOnly[B]->GetAddress())) {
+
+ // Build a list.
+ int ML = UHS_USB_BulkOnly[B]->GetbMaxLUN();
+ //printf("MAXLUN = %i\r\n", ML);
+ ML++;
+ for(int i = 0; i < ML; i++) {
+ if(UHS_USB_BulkOnly[B]->LUNIsGood(i)) {
+ partsready = true;
+ ((pvt_t *)(sto[i].private_data))->lun = i;
+ ((pvt_t *)(sto[i].private_data))->B = B;
+ sto[i].Reads = *UHS_USB_BulkOnly_Read;
+ sto[i].Writes = *UHS_USB_BulkOnly_Write;
+ sto[i].Status = *UHS_USB_BulkOnly_Status;
+ sto[i].Initialize = *UHS_USB_BulkOnly_Initialize;
+ sto[i].Commit = *UHS_USB_BulkOnly_Commit;
+ sto[i].TotalSectors = UHS_USB_BulkOnly[B]->GetCapacity(i);
+ sto[i].SectorSize = UHS_USB_BulkOnly[B]->GetSectorSize(i);
+ printf_P(PSTR("LUN:\t\t%u\r\n"), i);
+ printf_P(PSTR("Total Sectors:\t%08lx\t%lu\r\n"), sto[i].TotalSectors, sto[i].TotalSectors);
+ printf_P(PSTR("Sector Size:\t%04x\t\t%u\r\n"), sto[i].SectorSize, sto[i].SectorSize);
+ // get the partition data...
+ PT = new PCPartition;
+
+ if(!PT->Init(&sto[i])) {
+ part_t *apart;
+ for(int j = 0; j < 4; j++) {
+ apart = PT->GetPart(j);
+ if(apart != NULL && apart->type != 0x00) {
+ memcpy(&(parts[cpart]), apart, sizeof (part_t));
+ printf_P(PSTR("Partition %u type %#02x\r\n"), j, parts[cpart].type);
+ // for now
+ if(isfat(parts[cpart].type)) {
+ Fats[cpart] = new PFAT(&sto[i], cpart, parts[cpart].firstSector);
+ //int r = Fats[cpart]->Good();
+ if(Fats[cpart]->MountStatus()) {
+ delete Fats[cpart];
+ Fats[cpart] = NULL;
+ } else cpart++;
+ }
+ }
+ }
+ } else {
+ // try superblock
+ Fats[cpart] = new PFAT(&sto[i], cpart, 0);
+ //int r = Fats[cpart]->Good();
+ if(Fats[cpart]->MountStatus()) {
+ //printf_P(PSTR("Superblock error %x\r\n"), r);
+ delete Fats[cpart];
+ Fats[cpart] = NULL;
+ } else cpart++;
+
+ }
+ delete PT;
+ } else {
+ sto[i].Writes = NULL;
+ sto[i].Reads = NULL;
+ sto[i].Initialize = NULL;
+ sto[i].TotalSectors = 0UL;
+ sto[i].SectorSize = 0;
+ }
+ }
+
+ }
+ }
+
+ if(fatready) {
+ if(Fats[0] != NULL) {
+ struct Pvt * p;
+ p = ((struct Pvt *)(Fats[0]->storage->private_data));
+ if(!UHS_USB_BulkOnly[p->B]->LUNIsGood(p->lun)) {
+ // media change
+#if !defined(CORE_TEENSY) && defined(__AVR__)
+ fadeAmount = 80;
+#endif
+ partsready = false;
+ for(int i = 0; i < cpart; i++) {
+ if(Fats[i] != NULL)
+ delete Fats[i];
+ Fats[cpart] = NULL;
+ }
+ fatready = false;
+ notified = false;
+ cpart = 0;
+ }
+
+ }
+ }
+ if(fatready) {
+ FRESULT rc; /* Result code */
+ UINT bw, br, i;
+ if(!notified) {
+#if !defined(CORE_TEENSY) && defined(__AVR__)
+ fadeAmount = 5;
+#endif
+ notified = true;
+ FATFS *fs = NULL;
+ for(int zz = 0; zz < _VOLUMES; zz++) {
+ if(Fats[zz]->volmap == 0) fs = Fats[zz]->ffs;
+ }
+ printf_P(PSTR("\r\nOpen an existing file (message.txt).\r\n"));
+ rc = f_open(&My_File_Object_x, "0:/MESSAGE.TXT", FA_READ);
+ if(rc) printf_P(PSTR("Error %i, message.txt not found.\r\n"), rc);
+ else {
+ printf_P(PSTR("\r\nType the file content.\r\n"));
+ for(;;) {
+ rc = f_read(&My_File_Object_x, My_Buff_x, mbxs, &br); /* Read a chunk of file */
+ if(rc || !br) break; /* Error or end of file */
+ for(i = 0; i < br; i++) {
+ /* Type the data */
+ if(My_Buff_x[i] == '\n')
+ Serial.write('\r');
+ if(My_Buff_x[i] != '\r')
+ Serial.write(My_Buff_x[i]);
+ Serial.flush();
+ }
+ }
+ if(rc) {
+ f_close(&My_File_Object_x);
+ goto out;
+ }
+
+ printf_P(PSTR("\r\nClose the file.\r\n"));
+ rc = f_close(&My_File_Object_x);
+ if(rc) goto out;
+ }
+ printf_P(PSTR("\r\nCreate a new file (hello.txt).\r\n"));
+ rc = f_open(&My_File_Object_x, "0:/Hello.TxT", FA_WRITE | FA_CREATE_ALWAYS);
+ if(rc) {
+ die(rc);
+ goto outdir;
+ }
+ printf_P(PSTR("\r\nWrite a text data. (Hello world!)\r\n"));
+ rc = f_write(&My_File_Object_x, "Hello world!\r\n", 14, &bw);
+ if(rc) {
+ goto out;
+ }
+ printf_P(PSTR("%u bytes written.\r\n"), bw);
+
+ printf_P(PSTR("\r\nClose the file.\r\n"));
+ rc = f_close(&My_File_Object_x);
+ if(rc) {
+ die(rc);
+ goto out;
+ }
+outdir:{
+#if _USE_LFN
+ char lfn[_MAX_LFN + 1];
+ FILINFO My_File_Info_Object_x; /* File information object */
+ My_File_Info_Object_x.lfname = lfn;
+#endif
+ DIR My_Dir_Object_x; /* Directory object */
+ printf_P(PSTR("\r\nOpen root directory.\r\n"));
+ rc = f_opendir(&My_Dir_Object_x, "0:/");
+ if(rc) {
+ die(rc);
+ goto out;
+ }
+
+ printf_P(PSTR("\r\nDirectory listing...\r\n"));
+#if defined(__AVR__)
+ printf_P(PSTR("Available heap: %u Bytes\r\n"), freeHeap());
+#endif
+ for(;;) {
+#if _USE_LFN
+ My_File_Info_Object_x.lfsize = _MAX_LFN;
+#endif
+
+ rc = f_readdir(&My_Dir_Object_x, &My_File_Info_Object_x); /* Read a directory item */
+ if(rc || !My_File_Info_Object_x.fname[0]) break; /* Error or end of dir */
+
+ if(My_File_Info_Object_x.fattrib & AM_DIR) {
+ Serial.write('d');
+ } else {
+ Serial.write('-');
+ }
+ Serial.write('r');
+
+ if(My_File_Info_Object_x.fattrib & AM_RDO) {
+ Serial.write('-');
+ } else {
+ Serial.write('w');
+ }
+ if(My_File_Info_Object_x.fattrib & AM_HID) {
+ Serial.write('h');
+ } else {
+ Serial.write('-');
+ }
+
+ if(My_File_Info_Object_x.fattrib & AM_SYS) {
+ Serial.write('s');
+ } else {
+ Serial.write('-');
+ }
+
+ if(My_File_Info_Object_x.fattrib & AM_ARC) {
+ Serial.write('a');
+ } else {
+ Serial.write('-');
+ }
+
+#if _USE_LFN
+ if(*My_File_Info_Object_x.lfname)
+ printf_P(PSTR(" %8lu %s (%s)\r\n"), My_File_Info_Object_x.fsize, My_File_Info_Object_x.fname, My_File_Info_Object_x.lfname);
+ else
+#endif
+ printf_P(PSTR(" %8lu %s\r\n"), My_File_Info_Object_x.fsize, &(My_File_Info_Object_x.fname[0]));
+ }
+ }
+out:
+ if(rc) die(rc);
+
+ DISK_IOCTL(fs->drv, CTRL_COMMIT, 0);
+ printf_P(PSTR("\r\nTest completed.\r\n"));
+
+ }
+
+ if(runtest) {
+ ULONG ii, wt, rt, start, end;
+ FATFS *fs = NULL;
+ for(int zz = 0; zz < _VOLUMES; zz++) {
+ if(Fats[zz]->volmap == 0) fs = Fats[zz]->ffs;
+ }
+ runtest = false;
+ f_unlink("0:/10MB.bin");
+ printf_P(PSTR("\r\nCreate a new 10MB test file (10MB.bin).\r\n"));
+ rc = f_open(&My_File_Object_x, "0:/10MB.bin", FA_WRITE | FA_CREATE_ALWAYS);
+ if(rc) goto failed;
+ for(bw = 0; bw < mbxs; bw++) My_Buff_x[bw] = bw & 0xff;
+ fflush(stdout);
+ start = millis();
+ while(start == millis());
+ for(ii = 10485760LU / mbxs; ii > 0LU; ii--) {
+ rc = f_write(&My_File_Object_x, My_Buff_x, mbxs, &bw);
+ if(rc || !bw) goto failed;
+ }
+ rc = f_close(&My_File_Object_x);
+ if(rc) goto failed;
+ end = millis();
+ wt = (end - start) - 1;
+ printf_P(PSTR("Time to write 10485760 bytes: %lu ms (%lu sec) \r\n"), wt, (500 + wt) / 1000UL);
+ rc = f_open(&My_File_Object_x, "0:/10MB.bin", FA_READ);
+ fflush(stdout);
+ start = millis();
+ while(start == millis());
+ if(rc) goto failed;
+ for(;;) {
+ rc = f_read(&My_File_Object_x, My_Buff_x, mbxs, &bw); /* Read a chunk of file */
+ if(rc || !bw) break; /* Error or end of file */
+ }
+ end = millis();
+ if(rc) goto failed;
+ rc = f_close(&My_File_Object_x);
+ if(rc) goto failed;
+ rt = (end - start) - 1;
+ printf_P(PSTR("Time to read 10485760 bytes: %lu ms (%lu sec)\r\nDelete test file\r\n"), rt, (500 + rt) / 1000UL);
+failed:
+ if(rc) die(rc);
+ DISK_IOCTL(fs->drv, CTRL_COMMIT, 0);
+ printf_P(PSTR("10MB timing test finished.\r\n"));
+ }
+ }
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/gpl2.txt b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/gpl2.txt
new file mode 100644
index 000000000..5b6e7c66c
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/gpl2.txt
@@ -0,0 +1,340 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hexdump.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hexdump.h
new file mode 100644
index 000000000..ffa7248b7
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hexdump.h
@@ -0,0 +1,61 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(_usb_h_) || defined(__HEXDUMP_H__)
+#error "Never include hexdump.h directly; include Usb.h instead"
+#else
+#define __HEXDUMP_H__
+
+extern int UsbDEBUGlvl;
+
+template <class BASE_CLASS, class LEN_TYPE, class OFFSET_TYPE>
+class HexDumper : public BASE_CLASS {
+ uint8_t byteCount;
+ OFFSET_TYPE byteTotal;
+
+public:
+
+ HexDumper() : byteCount(0), byteTotal(0) {
+ };
+
+ void Initialize() {
+ byteCount = 0;
+ byteTotal = 0;
+ };
+
+ void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset);
+};
+
+template <class BASE_CLASS, class LEN_TYPE, class OFFSET_TYPE>
+void HexDumper<BASE_CLASS, LEN_TYPE, OFFSET_TYPE>::Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) {
+ if(UsbDEBUGlvl >= 0x80) { // Fully bypass this block of code if we do not debug.
+ for(LEN_TYPE j = 0; j < len; j++, byteCount++, byteTotal++) {
+ if(!byteCount) {
+ PrintHex<OFFSET_TYPE > (byteTotal, 0x80);
+ E_Notify(PSTR(": "), 0x80);
+ }
+ PrintHex<uint8_t > (pbuf[j], 0x80);
+ E_Notify(PSTR(" "), 0x80);
+
+ if(byteCount == 15) {
+ E_Notify(PSTR("\r\n"), 0x80);
+ byteCount = 0xFF;
+ }
+ }
+ }
+}
+
+#endif // __HEXDUMP_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hid.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hid.cpp
new file mode 100644
index 000000000..e4c7721a3
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hid.cpp
@@ -0,0 +1,112 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#include "hid.h"
+
+//get HID report descriptor
+
+/* WRONG! Endpoint is _ALWAYS_ ZERO for HID! We want the _INTERFACE_ value here!
+uint8_t HID::GetReportDescr(uint8_t ep, USBReadParser *parser) {
+ const uint8_t constBufLen = 64;
+ uint8_t buf[constBufLen];
+
+ uint8_t rcode = pUsb->ctrlReq(bAddress, ep, bmREQ_HID_REPORT, USB_REQUEST_GET_DESCRIPTOR, 0x00,
+ HID_DESCRIPTOR_REPORT, 0x0000, 128, constBufLen, buf, (USBReadParser*)parser);
+
+ //return ((rcode != hrSTALL) ? rcode : 0);
+ return rcode;
+}
+ */
+uint8_t HID::GetReportDescr(uint16_t wIndex, USBReadParser *parser) {
+ const uint8_t constBufLen = 64;
+ uint8_t buf[constBufLen];
+
+ uint8_t rcode = pUsb->ctrlReq(bAddress, 0x00, bmREQ_HID_REPORT, USB_REQUEST_GET_DESCRIPTOR, 0x00,
+ HID_DESCRIPTOR_REPORT, wIndex, 128, constBufLen, buf, (USBReadParser*)parser);
+
+ //return ((rcode != hrSTALL) ? rcode : 0);
+ return rcode;
+}
+
+//uint8_t HID::getHidDescr( uint8_t ep, uint16_t nbytes, uint8_t* dataptr )
+//{
+// return( pUsb->ctrlReq( bAddress, ep, bmREQ_GET_DESCR, USB_REQUEST_GET_DESCRIPTOR, 0x00, HID_DESCRIPTOR_HID, 0x0000, nbytes, dataptr ));
+//}
+
+uint8_t HID::SetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr) {
+ return ( pUsb->ctrlReq(bAddress, ep, bmREQ_HID_OUT, HID_REQUEST_SET_REPORT, report_id, report_type, iface, nbytes, nbytes, dataptr, NULL));
+}
+
+uint8_t HID::GetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr) {
+ return ( pUsb->ctrlReq(bAddress, ep, bmREQ_HID_IN, HID_REQUEST_GET_REPORT, report_id, report_type, iface, nbytes, nbytes, dataptr, NULL));
+}
+
+uint8_t HID::GetIdle(uint8_t iface, uint8_t reportID, uint8_t* dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HID_IN, HID_REQUEST_GET_IDLE, reportID, 0, iface, 0x0001, 0x0001, dataptr, NULL));
+}
+
+uint8_t HID::SetIdle(uint8_t iface, uint8_t reportID, uint8_t duration) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HID_OUT, HID_REQUEST_SET_IDLE, reportID, duration, iface, 0x0000, 0x0000, NULL, NULL));
+}
+
+uint8_t HID::SetProtocol(uint8_t iface, uint8_t protocol) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HID_OUT, HID_REQUEST_SET_PROTOCOL, protocol, 0x00, iface, 0x0000, 0x0000, NULL, NULL));
+}
+
+uint8_t HID::GetProtocol(uint8_t iface, uint8_t* dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_HID_IN, HID_REQUEST_GET_PROTOCOL, 0x00, 0x00, iface, 0x0001, 0x0001, dataptr, NULL));
+}
+
+void HID::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr) {
+ Notify(PSTR("Endpoint descriptor:"), 0x80);
+ Notify(PSTR("\r\nLength:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
+ Notify(PSTR("\r\nType:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
+ Notify(PSTR("\r\nAddress:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
+ Notify(PSTR("\r\nAttributes:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
+ Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
+ D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
+ Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
+}
+
+void HID::PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc) {
+ Notify(PSTR("\r\n\r\nHID Descriptor:\r\n"), 0x80);
+ Notify(PSTR("bDescLength:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (pDesc->bLength, 0x80);
+
+ Notify(PSTR("\r\nbDescriptorType:\t"), 0x80);
+ D_PrintHex<uint8_t > (pDesc->bDescriptorType, 0x80);
+
+ Notify(PSTR("\r\nbcdHID:\t\t\t"), 0x80);
+ D_PrintHex<uint16_t > (pDesc->bcdHID, 0x80);
+
+ Notify(PSTR("\r\nbCountryCode:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (pDesc->bCountryCode, 0x80);
+
+ Notify(PSTR("\r\nbNumDescriptors:\t"), 0x80);
+ D_PrintHex<uint8_t > (pDesc->bNumDescriptors, 0x80);
+
+ Notify(PSTR("\r\nbDescrType:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (pDesc->bDescrType, 0x80);
+
+ Notify(PSTR("\r\nwDescriptorLength:\t"), 0x80);
+ D_PrintHex<uint16_t > (pDesc->wDescriptorLength, 0x80);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hid.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hid.h
new file mode 100644
index 000000000..72942ebc9
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hid.h
@@ -0,0 +1,188 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__HID_H__)
+#define __HID_H__
+
+#include "Usb.h"
+#include "hidusagestr.h"
+
+#define MAX_REPORT_PARSERS 2
+#define HID_MAX_HID_CLASS_DESCRIPTORS 5
+
+#define DATA_SIZE_MASK 0x03
+#define TYPE_MASK 0x0C
+#define TAG_MASK 0xF0
+
+#define DATA_SIZE_0 0x00
+#define DATA_SIZE_1 0x01
+#define DATA_SIZE_2 0x02
+#define DATA_SIZE_4 0x03
+
+#define TYPE_MAIN 0x00
+#define TYPE_GLOBAL 0x04
+#define TYPE_LOCAL 0x08
+
+#define TAG_MAIN_INPUT 0x80
+#define TAG_MAIN_OUTPUT 0x90
+#define TAG_MAIN_COLLECTION 0xA0
+#define TAG_MAIN_FEATURE 0xB0
+#define TAG_MAIN_ENDCOLLECTION 0xC0
+
+#define TAG_GLOBAL_USAGEPAGE 0x00
+#define TAG_GLOBAL_LOGICALMIN 0x10
+#define TAG_GLOBAL_LOGICALMAX 0x20
+#define TAG_GLOBAL_PHYSMIN 0x30
+#define TAG_GLOBAL_PHYSMAX 0x40
+#define TAG_GLOBAL_UNITEXP 0x50
+#define TAG_GLOBAL_UNIT 0x60
+#define TAG_GLOBAL_REPORTSIZE 0x70
+#define TAG_GLOBAL_REPORTID 0x80
+#define TAG_GLOBAL_REPORTCOUNT 0x90
+#define TAG_GLOBAL_PUSH 0xA0
+#define TAG_GLOBAL_POP 0xB0
+
+#define TAG_LOCAL_USAGE 0x00
+#define TAG_LOCAL_USAGEMIN 0x10
+#define TAG_LOCAL_USAGEMAX 0x20
+
+/* HID requests */
+#define bmREQ_HID_OUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
+#define bmREQ_HID_IN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
+#define bmREQ_HID_REPORT USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_STANDARD|USB_SETUP_RECIPIENT_INTERFACE
+
+/* HID constants. Not part of chapter 9 */
+/* Class-Specific Requests */
+#define HID_REQUEST_GET_REPORT 0x01
+#define HID_REQUEST_GET_IDLE 0x02
+#define HID_REQUEST_GET_PROTOCOL 0x03
+#define HID_REQUEST_SET_REPORT 0x09
+#define HID_REQUEST_SET_IDLE 0x0A
+#define HID_REQUEST_SET_PROTOCOL 0x0B
+
+/* Class Descriptor Types */
+#define HID_DESCRIPTOR_HID 0x21
+#define HID_DESCRIPTOR_REPORT 0x22
+#define HID_DESRIPTOR_PHY 0x23
+
+/* Protocol Selection */
+#define HID_BOOT_PROTOCOL 0x00
+#define HID_RPT_PROTOCOL 0x01
+
+/* HID Interface Class Code */
+#define HID_INTF 0x03
+
+/* HID Interface Class SubClass Codes */
+#define HID_BOOT_INTF_SUBCLASS 0x01
+
+/* HID Interface Class Protocol Codes */
+#define HID_PROTOCOL_NONE 0x00
+#define HID_PROTOCOL_KEYBOARD 0x01
+#define HID_PROTOCOL_MOUSE 0x02
+
+#define HID_ITEM_TYPE_MAIN 0
+#define HID_ITEM_TYPE_GLOBAL 1
+#define HID_ITEM_TYPE_LOCAL 2
+#define HID_ITEM_TYPE_RESERVED 3
+
+#define HID_LONG_ITEM_PREFIX 0xfe // Long item prefix value
+
+#define bmHID_MAIN_ITEM_TAG 0xfc // Main item tag mask
+
+#define bmHID_MAIN_ITEM_INPUT 0x80 // Main item Input tag value
+#define bmHID_MAIN_ITEM_OUTPUT 0x90 // Main item Output tag value
+#define bmHID_MAIN_ITEM_FEATURE 0xb0 // Main item Feature tag value
+#define bmHID_MAIN_ITEM_COLLECTION 0xa0 // Main item Collection tag value
+#define bmHID_MAIN_ITEM_END_COLLECTION 0xce // Main item End Collection tag value
+
+#define HID_MAIN_ITEM_COLLECTION_PHYSICAL 0
+#define HID_MAIN_ITEM_COLLECTION_APPLICATION 1
+#define HID_MAIN_ITEM_COLLECTION_LOGICAL 2
+#define HID_MAIN_ITEM_COLLECTION_REPORT 3
+#define HID_MAIN_ITEM_COLLECTION_NAMED_ARRAY 4
+#define HID_MAIN_ITEM_COLLECTION_USAGE_SWITCH 5
+#define HID_MAIN_ITEM_COLLECTION_USAGE_MODIFIER 6
+
+struct HidItemPrefix {
+ uint8_t bSize : 2;
+ uint8_t bType : 2;
+ uint8_t bTag : 4;
+};
+
+struct MainItemIOFeature {
+ uint8_t bmIsConstantOrData : 1;
+ uint8_t bmIsArrayOrVariable : 1;
+ uint8_t bmIsRelativeOrAbsolute : 1;
+ uint8_t bmIsWrapOrNoWrap : 1;
+ uint8_t bmIsNonLonearOrLinear : 1;
+ uint8_t bmIsNoPreferedOrPrefered : 1;
+ uint8_t bmIsNullOrNoNull : 1;
+ uint8_t bmIsVolatileOrNonVolatile : 1;
+};
+
+class HID;
+
+class HIDReportParser {
+public:
+ virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) = 0;
+};
+
+class HID : public USBDeviceConfig, public UsbConfigXtracter {
+protected:
+ USB *pUsb; // USB class instance pointer
+ uint8_t bAddress; // address
+
+protected:
+ static const uint8_t epInterruptInIndex = 1; // InterruptIN endpoint index
+ static const uint8_t epInterruptOutIndex = 2; // InterruptOUT endpoint index
+
+ static const uint8_t maxHidInterfaces = 3;
+ static const uint8_t maxEpPerInterface = 2;
+ static const uint8_t totalEndpoints = (maxHidInterfaces * maxEpPerInterface + 1);
+
+ void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
+ void PrintHidDescriptor(const USB_HID_DESCRIPTOR *pDesc);
+
+ virtual HIDReportParser* GetReportParser(uint8_t id) {
+ return NULL;
+ };
+
+public:
+
+ HID(USB *pusb) : pUsb(pusb) {
+ };
+
+ const USB* GetUsb() {
+ return pUsb;
+ };
+
+ virtual bool SetReportParser(uint8_t id, HIDReportParser *prs) {
+ return false;
+ };
+
+ uint8_t SetProtocol(uint8_t iface, uint8_t protocol);
+ uint8_t GetProtocol(uint8_t iface, uint8_t* dataptr);
+ uint8_t GetIdle(uint8_t iface, uint8_t reportID, uint8_t* dataptr);
+ uint8_t SetIdle(uint8_t iface, uint8_t reportID, uint8_t duration);
+
+ uint8_t GetReportDescr(uint16_t wIndex, USBReadParser *parser = NULL);
+
+ uint8_t GetHidDescr(uint8_t ep, uint16_t nbytes, uint8_t* dataptr);
+ uint8_t GetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr);
+ uint8_t SetReport(uint8_t ep, uint8_t iface, uint8_t report_type, uint8_t report_id, uint16_t nbytes, uint8_t* dataptr);
+};
+
+#endif // __HID_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidboot.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidboot.cpp
new file mode 100644
index 000000000..280b2f978
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidboot.cpp
@@ -0,0 +1,201 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#include "hidboot.h"
+
+void MouseReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
+ MOUSEINFO *pmi = (MOUSEINFO*)buf;
+ // Future:
+ // bool event;
+
+#if 0
+ if (prevState.mouseInfo.bmLeftButton == 0 && pmi->bmLeftButton == 1)
+ OnLeftButtonDown(pmi);
+
+ if (prevState.mouseInfo.bmLeftButton == 1 && pmi->bmLeftButton == 0)
+ OnLeftButtonUp(pmi);
+
+ if (prevState.mouseInfo.bmRightButton == 0 && pmi->bmRightButton == 1)
+ OnRightButtonDown(pmi);
+
+ if (prevState.mouseInfo.bmRightButton == 1 && pmi->bmRightButton == 0)
+ OnRightButtonUp(pmi);
+
+ if (prevState.mouseInfo.bmMiddleButton == 0 && pmi->bmMiddleButton == 1)
+ OnMiddleButtonDown(pmi);
+
+ if (prevState.mouseInfo.bmMiddleButton == 1 && pmi->bmMiddleButton == 0)
+ OnMiddleButtonUp(pmi);
+
+ if (prevState.mouseInfo.dX != pmi->dX || prevState.mouseInfo.dY != pmi->dY)
+ OnMouseMove(pmi);
+
+ if (len > sizeof (MOUSEINFO))
+ for (uint8_t i = 0; i<sizeof (MOUSEINFO); i++)
+ prevState.bInfo[i] = buf[i];
+#else
+ //
+ // Optimization idea:
+ //
+ // 1: Don't pass the structure on every event. Buttons would not need it.
+ // 2: Only pass x/y values in the movement routine.
+ //
+ // These two changes (with the ones I have made) will save extra flash.
+ // The only "bad" thing is that it could break old code.
+ //
+ // Future thoughts:
+ //
+ // The extra space gained can be used for a generic mouse event that can be called
+ // when there are _ANY_ changes. This one you _MAY_ want to pass everything, however the
+ // sketch could already have noted these facts to support drag/drop scroll wheel stuff, etc.
+ //
+
+ // Why do we need to pass the structure for buttons?
+ // The function call not enough of a hint for what is happening?
+ if(prevState.mouseInfo.bmLeftButton != pmi->bmLeftButton ) {
+ if(pmi->bmLeftButton) {
+ OnLeftButtonDown(pmi);
+ } else {
+ OnLeftButtonUp(pmi);
+ }
+ // Future:
+ // event = true;
+ }
+
+ if(prevState.mouseInfo.bmRightButton != pmi->bmRightButton) {
+ if(pmi->bmRightButton) {
+ OnRightButtonDown(pmi);
+ } else {
+ OnRightButtonUp(pmi);
+ }
+ // Future:
+ // event = true;
+ }
+
+ if(prevState.mouseInfo.bmMiddleButton != pmi->bmMiddleButton) {
+ if(pmi->bmMiddleButton) {
+ OnMiddleButtonDown(pmi);
+ } else {
+ OnMiddleButtonUp(pmi);
+ }
+ // Future:
+ // event = true;
+ }
+
+ //
+ // Scroll wheel(s), are not part of the spec, but we could support it.
+ // Logitech wireless keyboard and mouse combo reports scroll wheel in byte 4
+ // We wouldn't even need to save this information.
+ //if(len > 3) {
+ //}
+ //
+
+ // Mice only report motion when they actually move!
+ // Why not just pass the x/y values to simplify things??
+ if(pmi->dX || pmi->dY) {
+ OnMouseMove(pmi);
+ // Future:
+ // event = true;
+ }
+
+ //
+ // Future:
+ // Provide a callback that operates on the gathered events from above.
+ //
+ // if(event) OnMouse();
+ //
+
+ // Only the first byte matters (buttons). We do NOT need to save position info.
+ prevState.bInfo[0] = buf[0];
+#endif
+
+};
+
+void KeyboardReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
+ // On error - return
+ if (buf[2] == 1)
+ return;
+
+ //KBDINFO *pki = (KBDINFO*)buf;
+
+ // provide event for changed control key state
+ if (prevState.bInfo[0x00] != buf[0x00]) {
+ OnControlKeysChanged(prevState.bInfo[0x00], buf[0x00]);
+ }
+
+ for (uint8_t i = 2; i < 8; i++) {
+ bool down = false;
+ bool up = false;
+
+ for (uint8_t j = 2; j < 8; j++) {
+ if (buf[i] == prevState.bInfo[j] && buf[i] != 1)
+ down = true;
+ if (buf[j] == prevState.bInfo[i] && prevState.bInfo[i] != 1)
+ up = true;
+ }
+ if (!down) {
+ HandleLockingKeys(hid, buf[i]);
+ OnKeyDown(*buf, buf[i]);
+ }
+ if (!up)
+ OnKeyUp(prevState.bInfo[0], prevState.bInfo[i]);
+ }
+ for (uint8_t i = 0; i < 8; i++)
+ prevState.bInfo[i] = buf[i];
+};
+
+const uint8_t KeyboardReportParser::numKeys[10] PROGMEM = {'!', '@', '#', '$', '%', '^', '&', '*', '(', ')'};
+const uint8_t KeyboardReportParser::symKeysUp[12] PROGMEM = {'_', '+', '{', '}', '|', '~', ':', '"', '~', '<', '>', '?'};
+const uint8_t KeyboardReportParser::symKeysLo[12] PROGMEM = {'-', '=', '[', ']', '\\', ' ', ';', '\'', '`', ',', '.', '/'};
+const uint8_t KeyboardReportParser::padKeys[5] PROGMEM = {'/', '*', '-', '+', 0x13};
+
+uint8_t KeyboardReportParser::OemToAscii(uint8_t mod, uint8_t key) {
+ uint8_t shift = (mod & 0x22);
+
+ // [a-z]
+ if (VALUE_WITHIN(key, 0x04, 0x1d)) {
+ // Upper case letters
+ if ((kbdLockingKeys.kbdLeds.bmCapsLock == 0 && shift) ||
+ (kbdLockingKeys.kbdLeds.bmCapsLock == 1 && shift == 0))
+ return (key - 4 + 'A');
+
+ // Lower case letters
+ else
+ return (key - 4 + 'a');
+ }// Numbers
+ else if (VALUE_WITHIN(key, 0x1e, 0x27)) {
+ if (shift)
+ return ((uint8_t)pgm_read_byte(&getNumKeys()[key - 0x1e]));
+ else
+ return ((key == UHS_HID_BOOT_KEY_ZERO) ? '0' : key - 0x1e + '1');
+ }// Keypad Numbers
+ else if(VALUE_WITHIN(key, 0x59, 0x61)) {
+ if(kbdLockingKeys.kbdLeds.bmNumLock == 1)
+ return (key - 0x59 + '1');
+ } else if(VALUE_WITHIN(key, 0x2d, 0x38))
+ return ((shift) ? (uint8_t)pgm_read_byte(&getSymKeysUp()[key - 0x2d]) : (uint8_t)pgm_read_byte(&getSymKeysLo()[key - 0x2d]));
+ else if(VALUE_WITHIN(key, 0x54, 0x58))
+ return (uint8_t)pgm_read_byte(&getPadKeys()[key - 0x54]);
+ else {
+ switch(key) {
+ case UHS_HID_BOOT_KEY_SPACE: return (0x20);
+ case UHS_HID_BOOT_KEY_ENTER: return (0x13);
+ case UHS_HID_BOOT_KEY_ZERO2: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '0': 0);
+ case UHS_HID_BOOT_KEY_PERIOD: return ((kbdLockingKeys.kbdLeds.bmNumLock == 1) ? '.': 0);
+ }
+ }
+ return ( 0);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidboot.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidboot.h
new file mode 100644
index 000000000..fb63ec5e5
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidboot.h
@@ -0,0 +1,618 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__HIDBOOT_H__)
+#define __HIDBOOT_H__
+
+#include "hid.h"
+
+#define UHS_HID_BOOT_KEY_ZERO 0x27
+#define UHS_HID_BOOT_KEY_ENTER 0x28
+#define UHS_HID_BOOT_KEY_SPACE 0x2c
+#define UHS_HID_BOOT_KEY_CAPS_LOCK 0x39
+#define UHS_HID_BOOT_KEY_SCROLL_LOCK 0x47
+#define UHS_HID_BOOT_KEY_NUM_LOCK 0x53
+#define UHS_HID_BOOT_KEY_ZERO2 0x62
+#define UHS_HID_BOOT_KEY_PERIOD 0x63
+
+// Don't worry, GCC will optimize the result to a final value.
+#define bitsEndpoints(p) ((((p) & HID_PROTOCOL_KEYBOARD)? 2 : 0) | (((p) & HID_PROTOCOL_MOUSE)? 1 : 0))
+#define totalEndpoints(p) ((bitsEndpoints(p) == 3) ? 3 : 2)
+#define epMUL(p) ((((p) & HID_PROTOCOL_KEYBOARD)? 1 : 0) + (((p) & HID_PROTOCOL_MOUSE)? 1 : 0))
+
+// Already defined in hid.h
+// #define HID_MAX_HID_CLASS_DESCRIPTORS 5
+
+struct MOUSEINFO {
+
+ struct {
+ uint8_t bmLeftButton : 1;
+ uint8_t bmRightButton : 1;
+ uint8_t bmMiddleButton : 1;
+ uint8_t bmDummy : 5;
+ };
+ int8_t dX;
+ int8_t dY;
+};
+
+class MouseReportParser : public HIDReportParser {
+
+ union {
+ MOUSEINFO mouseInfo;
+ uint8_t bInfo[sizeof (MOUSEINFO)];
+ } prevState;
+
+public:
+ void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
+
+protected:
+
+ virtual void OnMouseMove(MOUSEINFO *mi) {
+ };
+
+ virtual void OnLeftButtonUp(MOUSEINFO *mi) {
+ };
+
+ virtual void OnLeftButtonDown(MOUSEINFO *mi) {
+ };
+
+ virtual void OnRightButtonUp(MOUSEINFO *mi) {
+ };
+
+ virtual void OnRightButtonDown(MOUSEINFO *mi) {
+ };
+
+ virtual void OnMiddleButtonUp(MOUSEINFO *mi) {
+ };
+
+ virtual void OnMiddleButtonDown(MOUSEINFO *mi) {
+ };
+};
+
+struct MODIFIERKEYS {
+ uint8_t bmLeftCtrl : 1;
+ uint8_t bmLeftShift : 1;
+ uint8_t bmLeftAlt : 1;
+ uint8_t bmLeftGUI : 1;
+ uint8_t bmRightCtrl : 1;
+ uint8_t bmRightShift : 1;
+ uint8_t bmRightAlt : 1;
+ uint8_t bmRightGUI : 1;
+};
+
+struct KBDINFO {
+
+ struct {
+ uint8_t bmLeftCtrl : 1;
+ uint8_t bmLeftShift : 1;
+ uint8_t bmLeftAlt : 1;
+ uint8_t bmLeftGUI : 1;
+ uint8_t bmRightCtrl : 1;
+ uint8_t bmRightShift : 1;
+ uint8_t bmRightAlt : 1;
+ uint8_t bmRightGUI : 1;
+ };
+ uint8_t bReserved;
+ uint8_t Keys[6];
+};
+
+struct KBDLEDS {
+ uint8_t bmNumLock : 1;
+ uint8_t bmCapsLock : 1;
+ uint8_t bmScrollLock : 1;
+ uint8_t bmCompose : 1;
+ uint8_t bmKana : 1;
+ uint8_t bmReserved : 3;
+};
+
+class KeyboardReportParser : public HIDReportParser {
+ static const uint8_t numKeys[10];
+ static const uint8_t symKeysUp[12];
+ static const uint8_t symKeysLo[12];
+ static const uint8_t padKeys[5];
+
+protected:
+
+ union {
+ KBDINFO kbdInfo;
+ uint8_t bInfo[sizeof (KBDINFO)];
+ } prevState;
+
+ union {
+ KBDLEDS kbdLeds;
+ uint8_t bLeds;
+ } kbdLockingKeys;
+
+ uint8_t OemToAscii(uint8_t mod, uint8_t key);
+
+public:
+
+ KeyboardReportParser() {
+ kbdLockingKeys.bLeds = 0;
+ };
+
+ void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
+
+protected:
+
+ virtual uint8_t HandleLockingKeys(HID* hid, uint8_t key) {
+ uint8_t old_keys = kbdLockingKeys.bLeds;
+
+ switch(key) {
+ case UHS_HID_BOOT_KEY_NUM_LOCK:
+ kbdLockingKeys.kbdLeds.bmNumLock = ~kbdLockingKeys.kbdLeds.bmNumLock;
+ break;
+ case UHS_HID_BOOT_KEY_CAPS_LOCK:
+ kbdLockingKeys.kbdLeds.bmCapsLock = ~kbdLockingKeys.kbdLeds.bmCapsLock;
+ break;
+ case UHS_HID_BOOT_KEY_SCROLL_LOCK:
+ kbdLockingKeys.kbdLeds.bmScrollLock = ~kbdLockingKeys.kbdLeds.bmScrollLock;
+ break;
+ }
+
+ if(old_keys != kbdLockingKeys.bLeds && hid)
+ return (hid->SetReport(0, 0/*hid->GetIface()*/, 2, 0, 1, &kbdLockingKeys.bLeds));
+
+ return 0;
+ };
+
+ virtual void OnControlKeysChanged(uint8_t before, uint8_t after) {
+ };
+
+ virtual void OnKeyDown(uint8_t mod, uint8_t key) {
+ };
+
+ virtual void OnKeyUp(uint8_t mod, uint8_t key) {
+ };
+
+ virtual const uint8_t *getNumKeys() {
+ return numKeys;
+ };
+
+ virtual const uint8_t *getSymKeysUp() {
+ return symKeysUp;
+ };
+
+ virtual const uint8_t *getSymKeysLo() {
+ return symKeysLo;
+ };
+
+ virtual const uint8_t *getPadKeys() {
+ return padKeys;
+ };
+};
+
+template <const uint8_t BOOT_PROTOCOL>
+class HIDBoot : public HID //public USBDeviceConfig, public UsbConfigXtracter
+{
+ EpInfo epInfo[totalEndpoints(BOOT_PROTOCOL)];
+ HIDReportParser *pRptParser[epMUL(BOOT_PROTOCOL)];
+
+ uint8_t bConfNum; // configuration number
+ uint8_t bIfaceNum; // Interface Number
+ uint8_t bNumIface; // number of interfaces in the configuration
+ uint8_t bNumEP; // total number of EP in the configuration
+ uint32_t qNextPollTime; // next poll time
+ bool bPollEnable; // poll enable flag
+ uint8_t bInterval; // largest interval
+
+ void Initialize();
+
+ virtual HIDReportParser* GetReportParser(uint8_t id) {
+ return pRptParser[id];
+ };
+
+public:
+ HIDBoot(USB *p);
+
+ virtual bool SetReportParser(uint8_t id, HIDReportParser *prs) {
+ pRptParser[id] = prs;
+ return true;
+ };
+
+ // USBDeviceConfig implementation
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t Release();
+ uint8_t Poll();
+
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ virtual bool isReady() {
+ return bPollEnable;
+ };
+
+ // UsbConfigXtracter implementation
+ // Method should be defined here if virtual.
+ virtual void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
+
+ virtual bool DEVCLASSOK(uint8_t klass) {
+ return (klass == USB_CLASS_HID);
+ }
+
+ virtual bool DEVSUBCLASSOK(uint8_t subklass) {
+ return (subklass == BOOT_PROTOCOL);
+ }
+};
+
+template <const uint8_t BOOT_PROTOCOL>
+HIDBoot<BOOT_PROTOCOL>::HIDBoot(USB *p) :
+HID(p),
+qNextPollTime(0),
+bPollEnable(false) {
+ Initialize();
+
+ for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) {
+ pRptParser[i] = NULL;
+ }
+ if(pUsb)
+ pUsb->RegisterDeviceClass(this);
+}
+
+template <const uint8_t BOOT_PROTOCOL>
+void HIDBoot<BOOT_PROTOCOL>::Initialize() {
+ for(int i = 0; i < totalEndpoints(BOOT_PROTOCOL); i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }
+ bNumEP = 1;
+ bNumIface = 0;
+ bConfNum = 0;
+}
+
+template <const uint8_t BOOT_PROTOCOL>
+uint8_t HIDBoot<BOOT_PROTOCOL>::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+
+ uint8_t buf[constBufSize];
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint8_t len = 0;
+ //uint16_t cd_len = 0;
+
+ uint8_t num_of_conf; // number of configurations
+ //uint8_t num_of_intf; // number of interfaces
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+ USBTRACE("BM Init\r\n");
+ //USBTRACE2("totalEndpoints:", (uint8_t) (totalEndpoints(BOOT_PROTOCOL)));
+ //USBTRACE2("epMUL:", epMUL(BOOT_PROTOCOL));
+
+ if(bAddress)
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+
+ bInterval = 0;
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p->epinfo) {
+ USBTRACE("epinfo\r\n");
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf);
+
+ if(!rcode)
+ len = (buf[0] > constBufSize) ? constBufSize : buf[0];
+
+ if(rcode) {
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ goto FailGetDevDescr;
+ }
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from the device descriptor
+ epInfo[0].maxPktSize = (uint8_t)((USB_DEVICE_DESCRIPTOR*)buf)->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ USBTRACE2("setAddr:", rcode);
+ return rcode;
+ }
+ //delay(2); //per USB 2.0 sect.9.2.6.3
+
+ USBTRACE2("Addr:", bAddress);
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ if(len)
+ rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf);
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ num_of_conf = ((USB_DEVICE_DESCRIPTOR*)buf)->bNumConfigurations;
+
+ USBTRACE2("NC:", num_of_conf);
+
+ // GCC will optimize unused stuff away.
+ if((BOOT_PROTOCOL & (HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE)) == (HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE)) {
+ USBTRACE("HID_PROTOCOL_KEYBOARD AND MOUSE\r\n");
+ ConfigDescParser<
+ USB_CLASS_HID,
+ HID_BOOT_INTF_SUBCLASS,
+ HID_PROTOCOL_KEYBOARD | HID_PROTOCOL_MOUSE,
+ CP_MASK_COMPARE_ALL > confDescrParser(this);
+ confDescrParser.SetOR(); // Use the OR variant.
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
+ if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL)))
+ break;
+ }
+ } else {
+ // GCC will optimize unused stuff away.
+ if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) {
+ USBTRACE("HID_PROTOCOL_KEYBOARD\r\n");
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ ConfigDescParser<
+ USB_CLASS_HID,
+ HID_BOOT_INTF_SUBCLASS,
+ HID_PROTOCOL_KEYBOARD,
+ CP_MASK_COMPARE_ALL> confDescrParserA(this);
+
+ pUsb->getConfDescr(bAddress, 0, i, &confDescrParserA);
+ if(bNumEP == (uint8_t)(totalEndpoints(BOOT_PROTOCOL)))
+ break;
+ }
+ }
+
+ // GCC will optimize unused stuff away.
+ if(BOOT_PROTOCOL & HID_PROTOCOL_MOUSE) {
+ USBTRACE("HID_PROTOCOL_MOUSE\r\n");
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ ConfigDescParser<
+ USB_CLASS_HID,
+ HID_BOOT_INTF_SUBCLASS,
+ HID_PROTOCOL_MOUSE,
+ CP_MASK_COMPARE_ALL> confDescrParserB(this);
+
+ pUsb->getConfDescr(bAddress, 0, i, &confDescrParserB);
+ if(bNumEP == ((uint8_t)(totalEndpoints(BOOT_PROTOCOL))))
+ break;
+
+ }
+ }
+ }
+ USBTRACE2("bNumEP:", bNumEP);
+
+ if(bNumEP != (uint8_t)(totalEndpoints(BOOT_PROTOCOL))) {
+ rcode = USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+ goto Fail;
+ }
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
+ //USBTRACE2("setEpInfoEntry returned ", rcode);
+ USBTRACE2("Cnf:", bConfNum);
+
+ delay(1000);
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, bConfNum);
+
+ if(rcode)
+ goto FailSetConfDescr;
+
+ delay(1000);
+
+ USBTRACE2("bIfaceNum:", bIfaceNum);
+ USBTRACE2("bNumIface:", bNumIface);
+
+ // Yes, mouse wants SetProtocol and SetIdle too!
+ for(uint8_t i = 0; i < epMUL(BOOT_PROTOCOL); i++) {
+ USBTRACE2("\r\nInterface:", i);
+ rcode = SetProtocol(i, HID_BOOT_PROTOCOL);
+ if(rcode) goto FailSetProtocol;
+ USBTRACE2("PROTOCOL SET HID_BOOT rcode:", rcode);
+ rcode = SetIdle(i, 0, 0);
+ USBTRACE2("SET_IDLE rcode:", rcode);
+ // if(rcode) goto FailSetIdle; This can fail.
+ // Get the RPIPE and just throw it away.
+ SinkParser<USBReadParser, uint16_t, uint16_t> sink;
+ rcode = GetReportDescr(i, &sink);
+ USBTRACE2("RPIPE rcode:", rcode);
+ }
+
+ // Get RPIPE and throw it away.
+
+ if(BOOT_PROTOCOL & HID_PROTOCOL_KEYBOARD) {
+ // Wake keyboard interface by twinkling up to 5 LEDs that are in the spec.
+ // kana, compose, scroll, caps, num
+ rcode = 0x20; // Reuse rcode.
+ while(rcode) {
+ rcode >>= 1;
+ // Ignore any error returned, we don't care if LED is not supported
+ SetReport(0, 0, 2, 0, 1, &rcode); // Eventually becomes zero (All off)
+ delay(25);
+ }
+ }
+ USBTRACE("BM configured\r\n");
+
+ bPollEnable = true;
+ return 0;
+
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+ //FailSetDevTblEntry:
+ //#ifdef DEBUG_USB_HOST
+ // NotifyFailSetDevTblEntry();
+ // goto Fail;
+ //#endif
+
+ //FailGetConfDescr:
+ //#ifdef DEBUG_USB_HOST
+ // NotifyFailGetConfDescr();
+ // goto Fail;
+ //#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+ goto Fail;
+#endif
+
+FailSetProtocol:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("SetProto:");
+ goto Fail;
+#endif
+
+ //FailSetIdle:
+ //#ifdef DEBUG_USB_HOST
+ // USBTRACE("SetIdle:");
+ //#endif
+
+Fail:
+#ifdef DEBUG_USB_HOST
+ NotifyFail(rcode);
+#endif
+ Release();
+
+ return rcode;
+}
+
+template <const uint8_t BOOT_PROTOCOL>
+void HIDBoot<BOOT_PROTOCOL>::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) {
+
+ // If the first configuration satisfies, the others are not considered.
+ //if(bNumEP > 1 && conf != bConfNum)
+ if(bNumEP == totalEndpoints(BOOT_PROTOCOL))
+ return;
+
+ bConfNum = conf;
+ bIfaceNum = iface;
+
+ if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80) {
+ if(pep->bInterval > bInterval) bInterval = pep->bInterval;
+
+ // Fill in the endpoint info structure
+ epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F);
+ epInfo[bNumEP].maxPktSize = (uint8_t)pep->wMaxPacketSize;
+ epInfo[bNumEP].epAttribs = 0;
+ epInfo[bNumEP].bmNakPower = USB_NAK_NOWAIT;
+ bNumEP++;
+
+ }
+}
+
+template <const uint8_t BOOT_PROTOCOL>
+uint8_t HIDBoot<BOOT_PROTOCOL>::Release() {
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+
+ bConfNum = 0;
+ bIfaceNum = 0;
+ bNumEP = 1;
+ bAddress = 0;
+ qNextPollTime = 0;
+ bPollEnable = false;
+
+ return 0;
+}
+
+template <const uint8_t BOOT_PROTOCOL>
+uint8_t HIDBoot<BOOT_PROTOCOL>::Poll() {
+ uint8_t rcode = 0;
+
+ if(bPollEnable && ((long)(millis() - qNextPollTime) >= 0L)) {
+
+ // To-do: optimize manually, using the for loop only if needed.
+ for(int i = 0; i < epMUL(BOOT_PROTOCOL); i++) {
+ const uint16_t const_buff_len = 16;
+ uint8_t buf[const_buff_len];
+
+ USBTRACE3("(hidboot.h) i=", i, 0x81);
+ USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].epAddr=", epInfo[epInterruptInIndex + i].epAddr, 0x81);
+ USBTRACE3("(hidboot.h) epInfo[epInterruptInIndex + i].maxPktSize=", epInfo[epInterruptInIndex + i].maxPktSize, 0x81);
+ uint16_t read = (uint16_t)epInfo[epInterruptInIndex + i].maxPktSize;
+
+ rcode = pUsb->inTransfer(bAddress, epInfo[epInterruptInIndex + i].epAddr, &read, buf);
+ // SOME buggy dongles report extra keys (like sleep) using a 2 byte packet on the wrong endpoint.
+ // Since keyboard and mice must report at least 3 bytes, we ignore the extra data.
+ if(!rcode && read > 2) {
+ if(pRptParser[i])
+ pRptParser[i]->Parse((HID*)this, 0, (uint8_t)read, buf);
+#ifdef DEBUG_USB_HOST
+ // We really don't care about errors and anomalies unless we are debugging.
+ } else {
+ if(rcode != hrNAK) {
+ USBTRACE3("(hidboot.h) Poll:", rcode, 0x81);
+ }
+ if(!rcode && read) {
+ USBTRACE3("(hidboot.h) Strange read count: ", read, 0x80);
+ USBTRACE3("(hidboot.h) Interface:", i, 0x80);
+ }
+ }
+
+ if(!rcode && read && (UsbDEBUGlvl > 0x7f)) {
+ for(uint8_t i = 0; i < read; i++) {
+ PrintHex<uint8_t > (buf[i], 0x80);
+ USBTRACE1(" ", 0x80);
+ }
+ if(read)
+ USBTRACE1("\r\n", 0x80);
+#endif
+ }
+
+ }
+ qNextPollTime = millis() + bInterval;
+ }
+ return rcode;
+}
+
+#endif // __HIDBOOTMOUSE_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidescriptorparser.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidescriptorparser.cpp
new file mode 100644
index 000000000..e4491b4e9
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidescriptorparser.cpp
@@ -0,0 +1,1588 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#include "hidescriptorparser.h"
+
+const char * const ReportDescParserBase::usagePageTitles0[] PROGMEM = {
+ pstrUsagePageGenericDesktopControls,
+ pstrUsagePageSimulationControls,
+ pstrUsagePageVRControls,
+ pstrUsagePageSportControls,
+ pstrUsagePageGameControls,
+ pstrUsagePageGenericDeviceControls,
+ pstrUsagePageKeyboardKeypad,
+ pstrUsagePageLEDs,
+ pstrUsagePageButton,
+ pstrUsagePageOrdinal,
+ pstrUsagePageTelephone,
+ pstrUsagePageConsumer,
+ pstrUsagePageDigitizer,
+ pstrUsagePagePID,
+ pstrUsagePageUnicode
+};
+
+const char * const ReportDescParserBase::usagePageTitles1[] PROGMEM = {
+ pstrUsagePageBarCodeScanner,
+ pstrUsagePageScale,
+ pstrUsagePageMSRDevices,
+ pstrUsagePagePointOfSale,
+ pstrUsagePageCameraControl,
+ pstrUsagePageArcade
+};
+const char * const ReportDescParserBase::genDesktopTitles0[] PROGMEM = {
+ pstrUsagePointer,
+ pstrUsageMouse,
+ pstrUsageJoystick,
+ pstrUsageGamePad,
+ pstrUsageKeyboard,
+ pstrUsageKeypad,
+ pstrUsageMultiAxisController,
+ pstrUsageTabletPCSystemControls
+
+};
+const char * const ReportDescParserBase::genDesktopTitles1[] PROGMEM = {
+ pstrUsageX,
+ pstrUsageY,
+ pstrUsageZ,
+ pstrUsageRx,
+ pstrUsageRy,
+ pstrUsageRz,
+ pstrUsageSlider,
+ pstrUsageDial,
+ pstrUsageWheel,
+ pstrUsageHatSwitch,
+ pstrUsageCountedBuffer,
+ pstrUsageByteCount,
+ pstrUsageMotionWakeup,
+ pstrUsageStart,
+ pstrUsageSelect,
+ pstrUsagePageReserved,
+ pstrUsageVx,
+ pstrUsageVy,
+ pstrUsageVz,
+ pstrUsageVbrx,
+ pstrUsageVbry,
+ pstrUsageVbrz,
+ pstrUsageVno,
+ pstrUsageFeatureNotification,
+ pstrUsageResolutionMultiplier
+};
+const char * const ReportDescParserBase::genDesktopTitles2[] PROGMEM = {
+ pstrUsageSystemControl,
+ pstrUsageSystemPowerDown,
+ pstrUsageSystemSleep,
+ pstrUsageSystemWakeup,
+ pstrUsageSystemContextMenu,
+ pstrUsageSystemMainMenu,
+ pstrUsageSystemAppMenu,
+ pstrUsageSystemMenuHelp,
+ pstrUsageSystemMenuExit,
+ pstrUsageSystemMenuSelect,
+ pstrUsageSystemMenuRight,
+ pstrUsageSystemMenuLeft,
+ pstrUsageSystemMenuUp,
+ pstrUsageSystemMenuDown,
+ pstrUsageSystemColdRestart,
+ pstrUsageSystemWarmRestart,
+ pstrUsageDPadUp,
+ pstrUsageDPadDown,
+ pstrUsageDPadRight,
+ pstrUsageDPadLeft
+};
+const char * const ReportDescParserBase::genDesktopTitles3[] PROGMEM = {
+ pstrUsageSystemDock,
+ pstrUsageSystemUndock,
+ pstrUsageSystemSetup,
+ pstrUsageSystemBreak,
+ pstrUsageSystemDebuggerBreak,
+ pstrUsageApplicationBreak,
+ pstrUsageApplicationDebuggerBreak,
+ pstrUsageSystemSpeakerMute,
+ pstrUsageSystemHibernate
+};
+const char * const ReportDescParserBase::genDesktopTitles4[] PROGMEM = {
+ pstrUsageSystemDisplayInvert,
+ pstrUsageSystemDisplayInternal,
+ pstrUsageSystemDisplayExternal,
+ pstrUsageSystemDisplayBoth,
+ pstrUsageSystemDisplayDual,
+ pstrUsageSystemDisplayToggleIntExt,
+ pstrUsageSystemDisplaySwapPriSec,
+ pstrUsageSystemDisplayLCDAutoscale
+};
+const char * const ReportDescParserBase::simuTitles0[] PROGMEM = {
+ pstrUsageFlightSimulationDevice,
+ pstrUsageAutomobileSimulationDevice,
+ pstrUsageTankSimulationDevice,
+ pstrUsageSpaceshipSimulationDevice,
+ pstrUsageSubmarineSimulationDevice,
+ pstrUsageSailingSimulationDevice,
+ pstrUsageMotocicleSimulationDevice,
+ pstrUsageSportsSimulationDevice,
+ pstrUsageAirplaneSimulationDevice,
+ pstrUsageHelicopterSimulationDevice,
+ pstrUsageMagicCarpetSimulationDevice,
+ pstrUsageBicycleSimulationDevice
+};
+const char * const ReportDescParserBase::simuTitles1[] PROGMEM = {
+ pstrUsageFlightControlStick,
+ pstrUsageFlightStick,
+ pstrUsageCyclicControl,
+ pstrUsageCyclicTrim,
+ pstrUsageFlightYoke,
+ pstrUsageTrackControl
+};
+const char * const ReportDescParserBase::simuTitles2[] PROGMEM = {
+ pstrUsageAileron,
+ pstrUsageAileronTrim,
+ pstrUsageAntiTorqueControl,
+ pstrUsageAutopilotEnable,
+ pstrUsageChaffRelease,
+ pstrUsageCollectiveControl,
+ pstrUsageDiveBrake,
+ pstrUsageElectronicCountermeasures,
+ pstrUsageElevator,
+ pstrUsageElevatorTrim,
+ pstrUsageRudder,
+ pstrUsageThrottle,
+ pstrUsageFlightCommunications,
+ pstrUsageFlareRelease,
+ pstrUsageLandingGear,
+ pstrUsageToeBrake,
+ pstrUsageTrigger,
+ pstrUsageWeaponsArm,
+ pstrUsageWeaponsSelect,
+ pstrUsageWingFlaps,
+ pstrUsageAccelerator,
+ pstrUsageBrake,
+ pstrUsageClutch,
+ pstrUsageShifter,
+ pstrUsageSteering,
+ pstrUsageTurretDirection,
+ pstrUsageBarrelElevation,
+ pstrUsageDivePlane,
+ pstrUsageBallast,
+ pstrUsageBicycleCrank,
+ pstrUsageHandleBars,
+ pstrUsageFrontBrake,
+ pstrUsageRearBrake
+};
+const char * const ReportDescParserBase::vrTitles0[] PROGMEM = {
+ pstrUsageBelt,
+ pstrUsageBodySuit,
+ pstrUsageFlexor,
+ pstrUsageGlove,
+ pstrUsageHeadTracker,
+ pstrUsageHeadMountedDisplay,
+ pstrUsageHandTracker,
+ pstrUsageOculometer,
+ pstrUsageVest,
+ pstrUsageAnimatronicDevice
+};
+const char * const ReportDescParserBase::vrTitles1[] PROGMEM = {
+ pstrUsageStereoEnable,
+ pstrUsageDisplayEnable
+};
+const char * const ReportDescParserBase::sportsCtrlTitles0[] PROGMEM = {
+ pstrUsageBaseballBat,
+ pstrUsageGolfClub,
+ pstrUsageRowingMachine,
+ pstrUsageTreadmill
+};
+const char * const ReportDescParserBase::sportsCtrlTitles1[] PROGMEM = {
+ pstrUsageOar,
+ pstrUsageSlope,
+ pstrUsageRate,
+ pstrUsageStickSpeed,
+ pstrUsageStickFaceAngle,
+ pstrUsageStickHeelToe,
+ pstrUsageStickFollowThough,
+ pstrUsageStickTempo,
+ pstrUsageStickType,
+ pstrUsageStickHeight
+};
+const char * const ReportDescParserBase::sportsCtrlTitles2[] PROGMEM = {
+ pstrUsagePutter,
+ pstrUsage1Iron,
+ pstrUsage2Iron,
+ pstrUsage3Iron,
+ pstrUsage4Iron,
+ pstrUsage5Iron,
+ pstrUsage6Iron,
+ pstrUsage7Iron,
+ pstrUsage8Iron,
+ pstrUsage9Iron,
+ pstrUsage10Iron,
+ pstrUsage11Iron,
+ pstrUsageSandWedge,
+ pstrUsageLoftWedge,
+ pstrUsagePowerWedge,
+ pstrUsage1Wood,
+ pstrUsage3Wood,
+ pstrUsage5Wood,
+ pstrUsage7Wood,
+ pstrUsage9Wood
+};
+const char * const ReportDescParserBase::gameTitles0[] PROGMEM = {
+ pstrUsage3DGameController,
+ pstrUsagePinballDevice,
+ pstrUsageGunDevice
+};
+const char * const ReportDescParserBase::gameTitles1[] PROGMEM = {
+ pstrUsagePointOfView,
+ pstrUsageTurnRightLeft,
+ pstrUsagePitchForwardBackward,
+ pstrUsageRollRightLeft,
+ pstrUsageMoveRightLeft,
+ pstrUsageMoveForwardBackward,
+ pstrUsageMoveUpDown,
+ pstrUsageLeanRightLeft,
+ pstrUsageLeanForwardBackward,
+ pstrUsageHeightOfPOV,
+ pstrUsageFlipper,
+ pstrUsageSecondaryFlipper,
+ pstrUsageBump,
+ pstrUsageNewGame,
+ pstrUsageShootBall,
+ pstrUsagePlayer,
+ pstrUsageGunBolt,
+ pstrUsageGunClip,
+ pstrUsageGunSelector,
+ pstrUsageGunSingleShot,
+ pstrUsageGunBurst,
+ pstrUsageGunAutomatic,
+ pstrUsageGunSafety,
+ pstrUsageGamepadFireJump,
+ pstrUsageGamepadTrigger
+};
+const char * const ReportDescParserBase::genDevCtrlTitles[] PROGMEM = {
+ pstrUsageBatteryStrength,
+ pstrUsageWirelessChannel,
+ pstrUsageWirelessID,
+ pstrUsageDiscoverWirelessControl,
+ pstrUsageSecurityCodeCharEntered,
+ pstrUsageSecurityCodeCharErased,
+ pstrUsageSecurityCodeCleared
+};
+const char * const ReportDescParserBase::ledTitles[] PROGMEM = {
+ pstrUsageNumLock,
+ pstrUsageCapsLock,
+ pstrUsageScrollLock,
+ pstrUsageCompose,
+ pstrUsageKana,
+ pstrUsagePower,
+ pstrUsageShift,
+ pstrUsageDoNotDisturb,
+ pstrUsageMute,
+ pstrUsageToneEnable,
+ pstrUsageHighCutFilter,
+ pstrUsageLowCutFilter,
+ pstrUsageEqualizerEnable,
+ pstrUsageSoundFieldOn,
+ pstrUsageSurroundOn,
+ pstrUsageRepeat,
+ pstrUsageStereo,
+ pstrUsageSamplingRateDetect,
+ pstrUsageSpinning,
+ pstrUsageCAV,
+ pstrUsageCLV,
+ pstrUsageRecordingFormatDetect,
+ pstrUsageOffHook,
+ pstrUsageRing,
+ pstrUsageMessageWaiting,
+ pstrUsageDataMode,
+ pstrUsageBatteryOperation,
+ pstrUsageBatteryOK,
+ pstrUsageBatteryLow,
+ pstrUsageSpeaker,
+ pstrUsageHeadSet,
+ pstrUsageHold,
+ pstrUsageMicrophone,
+ pstrUsageCoverage,
+ pstrUsageNightMode,
+ pstrUsageSendCalls,
+ pstrUsageCallPickup,
+ pstrUsageConference,
+ pstrUsageStandBy,
+ pstrUsageCameraOn,
+ pstrUsageCameraOff,
+ pstrUsageOnLine,
+ pstrUsageOffLine,
+ pstrUsageBusy,
+ pstrUsageReady,
+ pstrUsagePaperOut,
+ pstrUsagePaperJam,
+ pstrUsageRemote,
+ pstrUsageForward,
+ pstrUsageReverse,
+ pstrUsageStop,
+ pstrUsageRewind,
+ pstrUsageFastForward,
+ pstrUsagePlay,
+ pstrUsagePause,
+ pstrUsageRecord,
+ pstrUsageError,
+ pstrUsageSelectedIndicator,
+ pstrUsageInUseIndicator,
+ pstrUsageMultiModeIndicator,
+ pstrUsageIndicatorOn,
+ pstrUsageIndicatorFlash,
+ pstrUsageIndicatorSlowBlink,
+ pstrUsageIndicatorFastBlink,
+ pstrUsageIndicatorOff,
+ pstrUsageFlashOnTime,
+ pstrUsageSlowBlinkOnTime,
+ pstrUsageSlowBlinkOffTime,
+ pstrUsageFastBlinkOnTime,
+ pstrUsageFastBlinkOffTime,
+ pstrUsageIndicatorColor,
+ pstrUsageIndicatorRed,
+ pstrUsageIndicatorGreen,
+ pstrUsageIndicatorAmber,
+ pstrUsageGenericIndicator,
+ pstrUsageSystemSuspend,
+ pstrUsageExternalPowerConnected
+};
+const char * const ReportDescParserBase::telTitles0 [] PROGMEM = {
+ pstrUsagePhone,
+ pstrUsageAnsweringMachine,
+ pstrUsageMessageControls,
+ pstrUsageHandset,
+ pstrUsageHeadset,
+ pstrUsageTelephonyKeyPad,
+ pstrUsageProgrammableButton
+};
+const char * const ReportDescParserBase::telTitles1 [] PROGMEM = {
+ pstrUsageHookSwitch,
+ pstrUsageFlash,
+ pstrUsageFeature,
+ pstrUsageHold,
+ pstrUsageRedial,
+ pstrUsageTransfer,
+ pstrUsageDrop,
+ pstrUsagePark,
+ pstrUsageForwardCalls,
+ pstrUsageAlternateFunction,
+ pstrUsageLine,
+ pstrUsageSpeakerPhone,
+ pstrUsageConference,
+ pstrUsageRingEnable,
+ pstrUsageRingSelect,
+ pstrUsagePhoneMute,
+ pstrUsageCallerID,
+ pstrUsageSend
+};
+const char * const ReportDescParserBase::telTitles2 [] PROGMEM = {
+ pstrUsageSpeedDial,
+ pstrUsageStoreNumber,
+ pstrUsageRecallNumber,
+ pstrUsagePhoneDirectory
+};
+const char * const ReportDescParserBase::telTitles3 [] PROGMEM = {
+ pstrUsageVoiceMail,
+ pstrUsageScreenCalls,
+ pstrUsageDoNotDisturb,
+ pstrUsageMessage,
+ pstrUsageAnswerOnOff
+};
+const char * const ReportDescParserBase::telTitles4 [] PROGMEM = {
+ pstrUsageInsideDialTone,
+ pstrUsageOutsideDialTone,
+ pstrUsageInsideRingTone,
+ pstrUsageOutsideRingTone,
+ pstrUsagePriorityRingTone,
+ pstrUsageInsideRingback,
+ pstrUsagePriorityRingback,
+ pstrUsageLineBusyTone,
+ pstrUsageReorderTone,
+ pstrUsageCallWaitingTone,
+ pstrUsageConfirmationTone1,
+ pstrUsageConfirmationTone2,
+ pstrUsageTonesOff,
+ pstrUsageOutsideRingback,
+ pstrUsageRinger
+};
+const char * const ReportDescParserBase::telTitles5 [] PROGMEM = {
+ pstrUsagePhoneKey0,
+ pstrUsagePhoneKey1,
+ pstrUsagePhoneKey2,
+ pstrUsagePhoneKey3,
+ pstrUsagePhoneKey4,
+ pstrUsagePhoneKey5,
+ pstrUsagePhoneKey6,
+ pstrUsagePhoneKey7,
+ pstrUsagePhoneKey8,
+ pstrUsagePhoneKey9,
+ pstrUsagePhoneKeyStar,
+ pstrUsagePhoneKeyPound,
+ pstrUsagePhoneKeyA,
+ pstrUsagePhoneKeyB,
+ pstrUsagePhoneKeyC,
+ pstrUsagePhoneKeyD
+};
+const char * const ReportDescParserBase::consTitles0[] PROGMEM = {
+ pstrUsageConsumerControl,
+ pstrUsageNumericKeyPad,
+ pstrUsageProgrammableButton,
+ pstrUsageMicrophone,
+ pstrUsageHeadphone,
+ pstrUsageGraphicEqualizer
+};
+const char * const ReportDescParserBase::consTitles1[] PROGMEM = {
+ pstrUsagePlus10,
+ pstrUsagePlus100,
+ pstrUsageAMPM
+};
+const char * const ReportDescParserBase::consTitles2[] PROGMEM = {
+ pstrUsagePower,
+ pstrUsageReset,
+ pstrUsageSleep,
+ pstrUsageSleepAfter,
+ pstrUsageSleepMode,
+ pstrUsageIllumination,
+ pstrUsageFunctionButtons
+
+};
+const char * const ReportDescParserBase::consTitles3[] PROGMEM = {
+ pstrUsageMenu,
+ pstrUsageMenuPick,
+ pstrUsageMenuUp,
+ pstrUsageMenuDown,
+ pstrUsageMenuLeft,
+ pstrUsageMenuRight,
+ pstrUsageMenuEscape,
+ pstrUsageMenuValueIncrease,
+ pstrUsageMenuValueDecrease
+};
+const char * const ReportDescParserBase::consTitles4[] PROGMEM = {
+ pstrUsageDataOnScreen,
+ pstrUsageClosedCaption,
+ pstrUsageClosedCaptionSelect,
+ pstrUsageVCRTV,
+ pstrUsageBroadcastMode,
+ pstrUsageSnapshot,
+ pstrUsageStill
+};
+const char * const ReportDescParserBase::consTitles5[] PROGMEM = {
+ pstrUsageSelection,
+ pstrUsageAssignSelection,
+ pstrUsageModeStep,
+ pstrUsageRecallLast,
+ pstrUsageEnterChannel,
+ pstrUsageOrderMovie,
+ pstrUsageChannel,
+ pstrUsageMediaSelection,
+ pstrUsageMediaSelectComputer,
+ pstrUsageMediaSelectTV,
+ pstrUsageMediaSelectWWW,
+ pstrUsageMediaSelectDVD,
+ pstrUsageMediaSelectTelephone,
+ pstrUsageMediaSelectProgramGuide,
+ pstrUsageMediaSelectVideoPhone,
+ pstrUsageMediaSelectGames,
+ pstrUsageMediaSelectMessages,
+ pstrUsageMediaSelectCD,
+ pstrUsageMediaSelectVCR,
+ pstrUsageMediaSelectTuner,
+ pstrUsageQuit,
+ pstrUsageHelp,
+ pstrUsageMediaSelectTape,
+ pstrUsageMediaSelectCable,
+ pstrUsageMediaSelectSatellite,
+ pstrUsageMediaSelectSecurity,
+ pstrUsageMediaSelectHome,
+ pstrUsageMediaSelectCall,
+ pstrUsageChannelIncrement,
+ pstrUsageChannelDecrement,
+ pstrUsageMediaSelectSAP,
+ pstrUsagePageReserved,
+ pstrUsageVCRPlus,
+ pstrUsageOnce,
+ pstrUsageDaily,
+ pstrUsageWeekly,
+ pstrUsageMonthly
+};
+const char * const ReportDescParserBase::consTitles6[] PROGMEM = {
+ pstrUsagePlay,
+ pstrUsagePause,
+ pstrUsageRecord,
+ pstrUsageFastForward,
+ pstrUsageRewind,
+ pstrUsageScanNextTrack,
+ pstrUsageScanPreviousTrack,
+ pstrUsageStop,
+ pstrUsageEject,
+ pstrUsageRandomPlay,
+ pstrUsageSelectDisk,
+ pstrUsageEnterDisk,
+ pstrUsageRepeat,
+ pstrUsageTracking,
+ pstrUsageTrackNormal,
+ pstrUsageSlowTracking,
+ pstrUsageFrameForward,
+ pstrUsageFrameBackwards,
+ pstrUsageMark,
+ pstrUsageClearMark,
+ pstrUsageRepeatFromMark,
+ pstrUsageReturnToMark,
+ pstrUsageSearchMarkForward,
+ pstrUsageSearchMarkBackwards,
+ pstrUsageCounterReset,
+ pstrUsageShowCounter,
+ pstrUsageTrackingIncrement,
+ pstrUsageTrackingDecrement,
+ pstrUsageStopEject,
+ pstrUsagePlayPause,
+ pstrUsagePlaySkip
+};
+const char * const ReportDescParserBase::consTitles7[] PROGMEM = {
+ pstrUsageVolume,
+ pstrUsageBalance,
+ pstrUsageMute,
+ pstrUsageBass,
+ pstrUsageTreble,
+ pstrUsageBassBoost,
+ pstrUsageSurroundMode,
+ pstrUsageLoudness,
+ pstrUsageMPX,
+ pstrUsageVolumeIncrement,
+ pstrUsageVolumeDecrement
+};
+const char * const ReportDescParserBase::consTitles8[] PROGMEM = {
+ pstrUsageSpeedSelect,
+ pstrUsagePlaybackSpeed,
+ pstrUsageStandardPlay,
+ pstrUsageLongPlay,
+ pstrUsageExtendedPlay,
+ pstrUsageSlow
+};
+const char * const ReportDescParserBase::consTitles9[] PROGMEM = {
+ pstrUsageFanEnable,
+ pstrUsageFanSpeed,
+ pstrUsageLightEnable,
+ pstrUsageLightIlluminationLevel,
+ pstrUsageClimateControlEnable,
+ pstrUsageRoomTemperature,
+ pstrUsageSecurityEnable,
+ pstrUsageFireAlarm,
+ pstrUsagePoliceAlarm,
+ pstrUsageProximity,
+ pstrUsageMotion,
+ pstrUsageDuresAlarm,
+ pstrUsageHoldupAlarm,
+ pstrUsageMedicalAlarm
+};
+const char * const ReportDescParserBase::consTitlesA[] PROGMEM = {
+ pstrUsageBalanceRight,
+ pstrUsageBalanceLeft,
+ pstrUsageBassIncrement,
+ pstrUsageBassDecrement,
+ pstrUsageTrebleIncrement,
+ pstrUsageTrebleDecrement
+};
+const char * const ReportDescParserBase::consTitlesB[] PROGMEM = {
+ pstrUsageSpeakerSystem,
+ pstrUsageChannelLeft,
+ pstrUsageChannelRight,
+ pstrUsageChannelCenter,
+ pstrUsageChannelFront,
+ pstrUsageChannelCenterFront,
+ pstrUsageChannelSide,
+ pstrUsageChannelSurround,
+ pstrUsageChannelLowFreqEnhancement,
+ pstrUsageChannelTop,
+ pstrUsageChannelUnknown
+};
+const char * const ReportDescParserBase::consTitlesC[] PROGMEM = {
+ pstrUsageSubChannel,
+ pstrUsageSubChannelIncrement,
+ pstrUsageSubChannelDecrement,
+ pstrUsageAlternateAudioIncrement,
+ pstrUsageAlternateAudioDecrement
+};
+const char * const ReportDescParserBase::consTitlesD[] PROGMEM = {
+ pstrUsageApplicationLaunchButtons,
+ pstrUsageALLaunchButtonConfigTool,
+ pstrUsageALProgrammableButton,
+ pstrUsageALConsumerControlConfig,
+ pstrUsageALWordProcessor,
+ pstrUsageALTextEditor,
+ pstrUsageALSpreadsheet,
+ pstrUsageALGraphicsEditor,
+ pstrUsageALPresentationApp,
+ pstrUsageALDatabaseApp,
+ pstrUsageALEmailReader,
+ pstrUsageALNewsreader,
+ pstrUsageALVoicemail,
+ pstrUsageALContactsAddressBook,
+ pstrUsageALCalendarSchedule,
+ pstrUsageALTaskProjectManager,
+ pstrUsageALLogJournalTimecard,
+ pstrUsageALCheckbookFinance,
+ pstrUsageALCalculator,
+ pstrUsageALAVCapturePlayback,
+ pstrUsageALLocalMachineBrowser,
+ pstrUsageALLANWANBrow,
+ pstrUsageALInternetBrowser,
+ pstrUsageALRemoteNetISPConnect,
+ pstrUsageALNetworkConference,
+ pstrUsageALNetworkChat,
+ pstrUsageALTelephonyDialer,
+ pstrUsageALLogon,
+ pstrUsageALLogoff,
+ pstrUsageALLogonLogoff,
+ pstrUsageALTermLockScrSav,
+ pstrUsageALControlPannel,
+ pstrUsageALCommandLineProcessorRun,
+ pstrUsageALProcessTaskManager,
+ pstrUsageALSelectTaskApplication,
+ pstrUsageALNextTaskApplication,
+ pstrUsageALPreviousTaskApplication,
+ pstrUsageALPreemptiveHaltTaskApp,
+ pstrUsageALIntegratedHelpCenter,
+ pstrUsageALDocuments,
+ pstrUsageALThesaurus,
+ pstrUsageALDictionary,
+ pstrUsageALDesktop,
+ pstrUsageALSpellCheck,
+ pstrUsageALGrammarCheck,
+ pstrUsageALWirelessStatus,
+ pstrUsageALKeyboardLayout,
+ pstrUsageALVirusProtection,
+ pstrUsageALEncryption,
+ pstrUsageALScreenSaver,
+ pstrUsageALAlarms,
+ pstrUsageALClock,
+ pstrUsageALFileBrowser,
+ pstrUsageALPowerStatus,
+ pstrUsageALImageBrowser,
+ pstrUsageALAudioBrowser,
+ pstrUsageALMovieBrowser,
+ pstrUsageALDigitalRightsManager,
+ pstrUsageALDigitalWallet,
+ pstrUsagePageReserved,
+ pstrUsageALInstantMessaging,
+ pstrUsageALOEMFeaturesBrowser,
+ pstrUsageALOEMHelp,
+ pstrUsageALOnlineCommunity,
+ pstrUsageALEntertainmentContentBrow,
+ pstrUsageALOnlineShoppingBrowser,
+ pstrUsageALSmartCardInfoHelp,
+ pstrUsageALMarketMonitorFinBrowser,
+ pstrUsageALCustomCorpNewsBrowser,
+ pstrUsageALOnlineActivityBrowser,
+ pstrUsageALResearchSearchBrowser,
+ pstrUsageALAudioPlayer
+};
+const char * const ReportDescParserBase::consTitlesE[] PROGMEM = {
+ pstrUsageGenericGUIAppControls,
+ pstrUsageACNew,
+ pstrUsageACOpen,
+ pstrUsageACClose,
+ pstrUsageACExit,
+ pstrUsageACMaximize,
+ pstrUsageACMinimize,
+ pstrUsageACSave,
+ pstrUsageACPrint,
+ pstrUsageACProperties,
+ pstrUsageACUndo,
+ pstrUsageACCopy,
+ pstrUsageACCut,
+ pstrUsageACPaste,
+ pstrUsageACSelectAll,
+ pstrUsageACFind,
+ pstrUsageACFindAndReplace,
+ pstrUsageACSearch,
+ pstrUsageACGoto,
+ pstrUsageACHome,
+ pstrUsageACBack,
+ pstrUsageACForward,
+ pstrUsageACStop,
+ pstrUsageACRefresh,
+ pstrUsageACPreviousLink,
+ pstrUsageACNextLink,
+ pstrUsageACBookmarks,
+ pstrUsageACHistory,
+ pstrUsageACSubscriptions,
+ pstrUsageACZoomIn,
+ pstrUsageACZoomOut,
+ pstrUsageACZoom,
+ pstrUsageACFullScreenView,
+ pstrUsageACNormalView,
+ pstrUsageACViewToggle,
+ pstrUsageACScrollUp,
+ pstrUsageACScrollDown,
+ pstrUsageACScroll,
+ pstrUsageACPanLeft,
+ pstrUsageACPanRight,
+ pstrUsageACPan,
+ pstrUsageACNewWindow,
+ pstrUsageACTileHoriz,
+ pstrUsageACTileVert,
+ pstrUsageACFormat,
+ pstrUsageACEdit,
+ pstrUsageACBold,
+ pstrUsageACItalics,
+ pstrUsageACUnderline,
+ pstrUsageACStrikethrough,
+ pstrUsageACSubscript,
+ pstrUsageACSuperscript,
+ pstrUsageACAllCaps,
+ pstrUsageACRotate,
+ pstrUsageACResize,
+ pstrUsageACFlipHorizontal,
+ pstrUsageACFlipVertical,
+ pstrUsageACMirrorHorizontal,
+ pstrUsageACMirrorVertical,
+ pstrUsageACFontSelect,
+ pstrUsageACFontColor,
+ pstrUsageACFontSize,
+ pstrUsageACJustifyLeft,
+ pstrUsageACJustifyCenterH,
+ pstrUsageACJustifyRight,
+ pstrUsageACJustifyBlockH,
+ pstrUsageACJustifyTop,
+ pstrUsageACJustifyCenterV,
+ pstrUsageACJustifyBottom,
+ pstrUsageACJustifyBlockV,
+ pstrUsageACIndentDecrease,
+ pstrUsageACIndentIncrease,
+ pstrUsageACNumberedList,
+ pstrUsageACRestartNumbering,
+ pstrUsageACBulletedList,
+ pstrUsageACPromote,
+ pstrUsageACDemote,
+ pstrUsageACYes,
+ pstrUsageACNo,
+ pstrUsageACCancel,
+ pstrUsageACCatalog,
+ pstrUsageACBuyChkout,
+ pstrUsageACAddToCart,
+ pstrUsageACExpand,
+ pstrUsageACExpandAll,
+ pstrUsageACCollapse,
+ pstrUsageACCollapseAll,
+ pstrUsageACPrintPreview,
+ pstrUsageACPasteSpecial,
+ pstrUsageACInsertMode,
+ pstrUsageACDelete,
+ pstrUsageACLock,
+ pstrUsageACUnlock,
+ pstrUsageACProtect,
+ pstrUsageACUnprotect,
+ pstrUsageACAttachComment,
+ pstrUsageACDeleteComment,
+ pstrUsageACViewComment,
+ pstrUsageACSelectWord,
+ pstrUsageACSelectSentence,
+ pstrUsageACSelectParagraph,
+ pstrUsageACSelectColumn,
+ pstrUsageACSelectRow,
+ pstrUsageACSelectTable,
+ pstrUsageACSelectObject,
+ pstrUsageACRedoRepeat,
+ pstrUsageACSort,
+ pstrUsageACSortAscending,
+ pstrUsageACSortDescending,
+ pstrUsageACFilter,
+ pstrUsageACSetClock,
+ pstrUsageACViewClock,
+ pstrUsageACSelectTimeZone,
+ pstrUsageACEditTimeZone,
+ pstrUsageACSetAlarm,
+ pstrUsageACClearAlarm,
+ pstrUsageACSnoozeAlarm,
+ pstrUsageACResetAlarm,
+ pstrUsageACSyncronize,
+ pstrUsageACSendReceive,
+ pstrUsageACSendTo,
+ pstrUsageACReply,
+ pstrUsageACReplyAll,
+ pstrUsageACForwardMessage,
+ pstrUsageACSend,
+ pstrUsageACAttachFile,
+ pstrUsageACUpload,
+ pstrUsageACDownload,
+ pstrUsageACSetBorders,
+ pstrUsageACInsertRow,
+ pstrUsageACInsertColumn,
+ pstrUsageACInsertFile,
+ pstrUsageACInsertPicture,
+ pstrUsageACInsertObject,
+ pstrUsageACInsertSymbol,
+ pstrUsageACSaveAndClose,
+ pstrUsageACRename,
+ pstrUsageACMerge,
+ pstrUsageACSplit,
+ pstrUsageACDistributeHorizontaly,
+ pstrUsageACDistributeVerticaly
+};
+const char * const ReportDescParserBase::digitTitles0[] PROGMEM = {
+ pstrUsageDigitizer,
+ pstrUsagePen,
+ pstrUsageLightPen,
+ pstrUsageTouchScreen,
+ pstrUsageTouchPad,
+ pstrUsageWhiteBoard,
+ pstrUsageCoordinateMeasuringMachine,
+ pstrUsage3DDigitizer,
+ pstrUsageStereoPlotter,
+ pstrUsageArticulatedArm,
+ pstrUsageArmature,
+ pstrUsageMultiplePointDigitizer,
+ pstrUsageFreeSpaceWand
+};
+const char * const ReportDescParserBase::digitTitles1[] PROGMEM = {
+ pstrUsageStylus,
+ pstrUsagePuck,
+ pstrUsageFinger
+
+};
+const char * const ReportDescParserBase::digitTitles2[] PROGMEM = {
+ pstrUsageTipPressure,
+ pstrUsageBarrelPressure,
+ pstrUsageInRange,
+ pstrUsageTouch,
+ pstrUsageUntouch,
+ pstrUsageTap,
+ pstrUsageQuality,
+ pstrUsageDataValid,
+ pstrUsageTransducerIndex,
+ pstrUsageTabletFunctionKeys,
+ pstrUsageProgramChangeKeys,
+ pstrUsageBatteryStrength,
+ pstrUsageInvert,
+ pstrUsageXTilt,
+ pstrUsageYTilt,
+ pstrUsageAzimuth,
+ pstrUsageAltitude,
+ pstrUsageTwist,
+ pstrUsageTipSwitch,
+ pstrUsageSecondaryTipSwitch,
+ pstrUsageBarrelSwitch,
+ pstrUsageEraser,
+ pstrUsageTabletPick
+};
+const char * const ReportDescParserBase::aplphanumTitles0[] PROGMEM = {
+ pstrUsageAlphanumericDisplay,
+ pstrUsageBitmappedDisplay
+};
+const char * const ReportDescParserBase::aplphanumTitles1[] PROGMEM = {
+ pstrUsageDisplayAttributesReport,
+ pstrUsageASCIICharacterSet,
+ pstrUsageDataReadBack,
+ pstrUsageFontReadBack,
+ pstrUsageDisplayControlReport,
+ pstrUsageClearDisplay,
+ pstrUsageDisplayEnable,
+ pstrUsageScreenSaverDelay,
+ pstrUsageScreenSaverEnable,
+ pstrUsageVerticalScroll,
+ pstrUsageHorizontalScroll,
+ pstrUsageCharacterReport,
+ pstrUsageDisplayData,
+ pstrUsageDisplayStatus,
+ pstrUsageStatusNotReady,
+ pstrUsageStatusReady,
+ pstrUsageErrorNotALoadableCharacter,
+ pstrUsageErrorFotDataCanNotBeRead,
+ pstrUsageCursorPositionReport,
+ pstrUsageRow,
+ pstrUsageColumn,
+ pstrUsageRows,
+ pstrUsageColumns,
+ pstrUsageCursorPixelPosition,
+ pstrUsageCursorMode,
+ pstrUsageCursorEnable,
+ pstrUsageCursorBlink,
+ pstrUsageFontReport,
+ pstrUsageFontData,
+ pstrUsageCharacterWidth,
+ pstrUsageCharacterHeight,
+ pstrUsageCharacterSpacingHorizontal,
+ pstrUsageCharacterSpacingVertical,
+ pstrUsageUnicodeCharset,
+ pstrUsageFont7Segment,
+ pstrUsage7SegmentDirectMap,
+ pstrUsageFont14Segment,
+ pstrUsage14SegmentDirectMap,
+ pstrUsageDisplayBrightness,
+ pstrUsageDisplayContrast,
+ pstrUsageCharacterAttribute,
+ pstrUsageAttributeReadback,
+ pstrUsageAttributeData,
+ pstrUsageCharAttributeEnhance,
+ pstrUsageCharAttributeUnderline,
+ pstrUsageCharAttributeBlink
+};
+const char * const ReportDescParserBase::aplphanumTitles2[] PROGMEM = {
+ pstrUsageBitmapSizeX,
+ pstrUsageBitmapSizeY,
+ pstrUsagePageReserved,
+ pstrUsageBitDepthFormat,
+ pstrUsageDisplayOrientation,
+ pstrUsagePaletteReport,
+ pstrUsagePaletteDataSize,
+ pstrUsagePaletteDataOffset,
+ pstrUsagePaletteData,
+ pstrUsageBlitReport,
+ pstrUsageBlitRectangleX1,
+ pstrUsageBlitRectangleY1,
+ pstrUsageBlitRectangleX2,
+ pstrUsageBlitRectangleY2,
+ pstrUsageBlitData,
+ pstrUsageSoftButton,
+ pstrUsageSoftButtonID,
+ pstrUsageSoftButtonSide,
+ pstrUsageSoftButtonOffset1,
+ pstrUsageSoftButtonOffset2,
+ pstrUsageSoftButtonReport
+};
+const char * const ReportDescParserBase::medInstrTitles0[] PROGMEM = {
+ pstrUsageVCRAcquisition,
+ pstrUsageFreezeThaw,
+ pstrUsageClipStore,
+ pstrUsageUpdate,
+ pstrUsageNext,
+ pstrUsageSave,
+ pstrUsagePrint,
+ pstrUsageMicrophoneEnable
+};
+const char * const ReportDescParserBase::medInstrTitles1[] PROGMEM = {
+ pstrUsageCine,
+ pstrUsageTransmitPower,
+ pstrUsageVolume,
+ pstrUsageFocus,
+ pstrUsageDepth
+};
+const char * const ReportDescParserBase::medInstrTitles2[] PROGMEM = {
+ pstrUsageSoftStepPrimary,
+ pstrUsageSoftStepSecondary
+};
+const char * const ReportDescParserBase::medInstrTitles3[] PROGMEM = {
+ pstrUsageZoomSelect,
+ pstrUsageZoomAdjust,
+ pstrUsageSpectralDopplerModeSelect,
+ pstrUsageSpectralDopplerModeAdjust,
+ pstrUsageColorDopplerModeSelect,
+ pstrUsageColorDopplerModeAdjust,
+ pstrUsageMotionModeSelect,
+ pstrUsageMotionModeAdjust,
+ pstrUsage2DModeSelect,
+ pstrUsage2DModeAdjust
+};
+const char * const ReportDescParserBase::medInstrTitles4[] PROGMEM = {
+ pstrUsageSoftControlSelect,
+ pstrUsageSoftControlAdjust
+};
+
+void ReportDescParserBase::Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset) {
+ uint16_t cntdn = (uint16_t)len;
+ uint8_t *p = (uint8_t*)pbuf;
+
+
+ totalSize = 0;
+
+ while(cntdn) {
+ //USB_HOST_SERIAL.println("");
+ //PrintHex<uint16_t>(offset + len - cntdn);
+ //USB_HOST_SERIAL.print(":");
+
+ ParseItem(&p, &cntdn);
+
+ //if (ParseItem(&p, &cntdn))
+ // return;
+ }
+ //USBTRACE2("Total:", totalSize);
+}
+
+void ReportDescParserBase::PrintValue(uint8_t *p, uint8_t len) {
+ E_Notify(PSTR("("), 0x80);
+ for(; len; p++, len--)
+ PrintHex<uint8_t > (*p, 0x80);
+ E_Notify(PSTR(")"), 0x80);
+}
+
+void ReportDescParserBase::PrintByteValue(uint8_t data) {
+ E_Notify(PSTR("("), 0x80);
+ PrintHex<uint8_t > (data, 0x80);
+ E_Notify(PSTR(")"), 0x80);
+}
+
+void ReportDescParserBase::PrintItemTitle(uint8_t prefix) {
+ switch(prefix & (TYPE_MASK | TAG_MASK)) {
+ case (TYPE_GLOBAL | TAG_GLOBAL_PUSH):
+ E_Notify(PSTR("\r\nPush"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_POP):
+ E_Notify(PSTR("\r\nPop"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE):
+ E_Notify(PSTR("\r\nUsage Page"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMIN):
+ E_Notify(PSTR("\r\nLogical Min"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMAX):
+ E_Notify(PSTR("\r\nLogical Max"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMIN):
+ E_Notify(PSTR("\r\nPhysical Min"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMAX):
+ E_Notify(PSTR("\r\nPhysical Max"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_UNITEXP):
+ E_Notify(PSTR("\r\nUnit Exp"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_UNIT):
+ E_Notify(PSTR("\r\nUnit"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE):
+ E_Notify(PSTR("\r\nReport Size"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT):
+ E_Notify(PSTR("\r\nReport Count"), 0x80);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID):
+ E_Notify(PSTR("\r\nReport Id"), 0x80);
+ break;
+ case (TYPE_LOCAL | TAG_LOCAL_USAGE):
+ E_Notify(PSTR("\r\nUsage"), 0x80);
+ break;
+ case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN):
+ E_Notify(PSTR("\r\nUsage Min"), 0x80);
+ break;
+ case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX):
+ E_Notify(PSTR("\r\nUsage Max"), 0x80);
+ break;
+ case (TYPE_MAIN | TAG_MAIN_COLLECTION):
+ E_Notify(PSTR("\r\nCollection"), 0x80);
+ break;
+ case (TYPE_MAIN | TAG_MAIN_ENDCOLLECTION):
+ E_Notify(PSTR("\r\nEnd Collection"), 0x80);
+ break;
+ case (TYPE_MAIN | TAG_MAIN_INPUT):
+ E_Notify(PSTR("\r\nInput"), 0x80);
+ break;
+ case (TYPE_MAIN | TAG_MAIN_OUTPUT):
+ E_Notify(PSTR("\r\nOutput"), 0x80);
+ break;
+ case (TYPE_MAIN | TAG_MAIN_FEATURE):
+ E_Notify(PSTR("\r\nFeature"), 0x80);
+ break;
+ } // switch (**pp & (TYPE_MASK | TAG_MASK))
+}
+
+uint8_t ReportDescParserBase::ParseItem(uint8_t **pp, uint16_t *pcntdn) {
+ //uint8_t ret = enErrorSuccess;
+ //reinterpret_cast<>(varBuffer);
+ switch(itemParseState) {
+ case 0:
+ if(**pp == HID_LONG_ITEM_PREFIX)
+ USBTRACE("\r\nLONG\r\n");
+ else {
+ uint8_t size = ((**pp) & DATA_SIZE_MASK);
+
+ itemPrefix = (**pp);
+ itemSize = 1 + ((size == DATA_SIZE_4) ? 4 : size);
+
+ PrintItemTitle(itemPrefix);
+ }
+ (*pp)++;
+ (*pcntdn)--;
+ itemSize--;
+ itemParseState = 1;
+
+ if(!itemSize)
+ break;
+
+ if(!pcntdn)
+ return enErrorIncomplete;
+ case 1:
+ //USBTRACE2("\r\niSz:",itemSize);
+
+ theBuffer.valueSize = itemSize;
+ valParser.Initialize(&theBuffer);
+ itemParseState = 2;
+ case 2:
+ if(!valParser.Parse(pp, pcntdn))
+ return enErrorIncomplete;
+ itemParseState = 3;
+ case 3:
+ {
+ uint8_t data = *((uint8_t*)varBuffer);
+
+ switch(itemPrefix & (TYPE_MASK | TAG_MASK)) {
+ case (TYPE_LOCAL | TAG_LOCAL_USAGE):
+ if(pfUsage) {
+ if(theBuffer.valueSize > 1) {
+ uint16_t* ui16 = reinterpret_cast<uint16_t *>(varBuffer);
+ pfUsage(*ui16);
+ } else
+ pfUsage(data);
+ }
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE):
+ rptSize = data;
+ PrintByteValue(data);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT):
+ rptCount = data;
+ PrintByteValue(data);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMIN):
+ case (TYPE_GLOBAL | TAG_GLOBAL_LOGICALMAX):
+ case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMIN):
+ case (TYPE_GLOBAL | TAG_GLOBAL_PHYSMAX):
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID):
+ case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN):
+ case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX):
+ case (TYPE_GLOBAL | TAG_GLOBAL_UNITEXP):
+ case (TYPE_GLOBAL | TAG_GLOBAL_UNIT):
+ PrintValue(varBuffer, theBuffer.valueSize);
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_PUSH):
+ case (TYPE_GLOBAL | TAG_GLOBAL_POP):
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE):
+ SetUsagePage(data);
+ PrintUsagePage(data);
+ PrintByteValue(data);
+ break;
+ case (TYPE_MAIN | TAG_MAIN_COLLECTION):
+ case (TYPE_MAIN | TAG_MAIN_ENDCOLLECTION):
+ switch(data) {
+ case 0x00:
+ E_Notify(PSTR(" Physical"), 0x80);
+ break;
+ case 0x01:
+ E_Notify(PSTR(" Application"), 0x80);
+ break;
+ case 0x02:
+ E_Notify(PSTR(" Logical"), 0x80);
+ break;
+ case 0x03:
+ E_Notify(PSTR(" Report"), 0x80);
+ break;
+ case 0x04:
+ E_Notify(PSTR(" Named Array"), 0x80);
+ break;
+ case 0x05:
+ E_Notify(PSTR(" Usage Switch"), 0x80);
+ break;
+ case 0x06:
+ E_Notify(PSTR(" Usage Modifier"), 0x80);
+ break;
+ default:
+ E_Notify(PSTR(" Vendor Defined("), 0x80);
+ PrintHex<uint8_t > (data, 0x80);
+ E_Notify(PSTR(")"), 0x80);
+ }
+ break;
+ case (TYPE_MAIN | TAG_MAIN_INPUT):
+ case (TYPE_MAIN | TAG_MAIN_OUTPUT):
+ case (TYPE_MAIN | TAG_MAIN_FEATURE):
+ totalSize += (uint16_t)rptSize * (uint16_t)rptCount;
+ rptSize = 0;
+ rptCount = 0;
+ E_Notify(PSTR("("), 0x80);
+ PrintBin<uint8_t > (data, 0x80);
+ E_Notify(PSTR(")"), 0x80);
+ break;
+ } // switch (**pp & (TYPE_MASK | TAG_MASK))
+ }
+ } // switch (itemParseState)
+ itemParseState = 0;
+ return enErrorSuccess;
+}
+
+ReportDescParserBase::UsagePageFunc ReportDescParserBase::usagePageFunctions[] /*PROGMEM*/ = {
+ &ReportDescParserBase::PrintGenericDesktopPageUsage,
+ &ReportDescParserBase::PrintSimulationControlsPageUsage,
+ &ReportDescParserBase::PrintVRControlsPageUsage,
+ &ReportDescParserBase::PrintSportsControlsPageUsage,
+ &ReportDescParserBase::PrintGameControlsPageUsage,
+ &ReportDescParserBase::PrintGenericDeviceControlsPageUsage,
+ NULL, // Keyboard/Keypad
+ &ReportDescParserBase::PrintLEDPageUsage,
+ &ReportDescParserBase::PrintButtonPageUsage,
+ &ReportDescParserBase::PrintOrdinalPageUsage,
+ &ReportDescParserBase::PrintTelephonyPageUsage,
+ &ReportDescParserBase::PrintConsumerPageUsage,
+ &ReportDescParserBase::PrintDigitizerPageUsage,
+ NULL, // Reserved
+ NULL, // PID
+ NULL // Unicode
+};
+
+void ReportDescParserBase::SetUsagePage(uint16_t page) {
+ pfUsage = NULL;
+
+ if(VALUE_BETWEEN(page, 0x00, 0x11)) {
+ pfUsage = (usagePageFunctions[page - 1]);
+
+ } else {
+ switch(page) {
+ case 0x14:
+ pfUsage = &ReportDescParserBase::PrintAlphanumDisplayPageUsage;
+ break;
+ case 0x40:
+ pfUsage = &ReportDescParserBase::PrintMedicalInstrumentPageUsage;
+ break;
+ }
+ }
+}
+
+void ReportDescParserBase::PrintUsagePage(uint16_t page) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(page, 0x00, 0x11, w, E_Notify, usagePageTitles0, 0x80)
+ else output_if_between(page, 0x8b, 0x92, w, E_Notify, usagePageTitles1, 0x80)
+ else if(VALUE_BETWEEN(page, 0x7f, 0x84))
+ E_Notify(pstrUsagePageMonitor, 0x80);
+ else if(VALUE_BETWEEN(page, 0x83, 0x8c))
+ E_Notify(pstrUsagePagePower, 0x80);
+ else if(page > 0xfeff /* && page <= 0xffff */)
+ E_Notify(pstrUsagePageVendorDefined, 0x80);
+ else
+ switch(page) {
+ case 0x14:
+ E_Notify(pstrUsagePageAlphaNumericDisplay, 0x80);
+ break;
+ case 0x40:
+ E_Notify(pstrUsagePageMedicalInstruments, 0x80);
+ break;
+ default:
+ E_Notify(pstrUsagePageUndefined, 0x80);
+ }
+}
+
+void ReportDescParserBase::PrintButtonPageUsage(uint16_t usage) {
+ E_Notify(pstrSpace, 0x80);
+ E_Notify(PSTR("Btn"), 0x80);
+ PrintHex<uint16_t > (usage, 0x80);
+ E_Notify(PSTR("\r\n"), 0x80);
+ //USB_HOST_SERIAL.print(usage, HEX);
+}
+
+void ReportDescParserBase::PrintOrdinalPageUsage(uint16_t usage) {
+ E_Notify(pstrSpace, 0x80);
+ E_Notify(PSTR("Inst"), 0x80);
+ // Sorry, HEX for now...
+ PrintHex<uint16_t > (usage, 0x80);
+ E_Notify(PSTR("\r\n"), 0x80);
+ //USB_HOST_SERIAL.print(usage, DEC);
+}
+
+void ReportDescParserBase::PrintGenericDesktopPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x0a, w, E_Notify, genDesktopTitles0, 0x80)
+ else output_if_between(usage, 0x2f, 0x49, w, E_Notify, genDesktopTitles1, 0x80)
+ else output_if_between(usage, 0x7f, 0x94, w, E_Notify, genDesktopTitles2, 0x80)
+ else output_if_between(usage, 0x9f, 0xa9, w, E_Notify, genDesktopTitles3, 0x80)
+ else output_if_between(usage, 0xaf, 0xb8, w, E_Notify, genDesktopTitles4, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintSimulationControlsPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x0d, w, E_Notify, simuTitles0, 0x80)
+ else output_if_between(usage, 0x1f, 0x26, w, E_Notify, simuTitles1, 0x80)
+ else output_if_between(usage, 0xaf, 0xd1, w, E_Notify, simuTitles2, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintVRControlsPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x0b, w, E_Notify, vrTitles0, 0x80)
+ else output_if_between(usage, 0x1f, 0x22, w, E_Notify, vrTitles1, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintSportsControlsPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x05, w, E_Notify, sportsCtrlTitles0, 0x80)
+ else output_if_between(usage, 0x2f, 0x3a, w, E_Notify, sportsCtrlTitles1, 0x80)
+ else output_if_between(usage, 0x4f, 0x64, w, E_Notify, sportsCtrlTitles2, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintGameControlsPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x04, w, E_Notify, gameTitles0, 0x80)
+ else output_if_between(usage, 0x1f, 0x3a, w, E_Notify, gameTitles1, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintGenericDeviceControlsPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x1f, 0x27, w, E_Notify, genDevCtrlTitles, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintLEDPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x4e, w, E_Notify, ledTitles, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintTelephonyPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x08, w, E_Notify, telTitles0, 0x80)
+ else output_if_between(usage, 0x1f, 0x32, w, E_Notify, telTitles1, 0x80)
+ else output_if_between(usage, 0x4f, 0x54, w, E_Notify, telTitles2, 0x80)
+ else output_if_between(usage, 0x6f, 0x75, w, E_Notify, telTitles3, 0x80)
+ else output_if_between(usage, 0x8f, 0x9f, w, E_Notify, telTitles4, 0x80)
+ else output_if_between(usage, 0xaf, 0xc0, w, E_Notify, telTitles5, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintConsumerPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x07, w, E_Notify, consTitles0, 0x80)
+ else output_if_between(usage, 0x1f, 0x23, w, E_Notify, consTitles1, 0x80)
+ else output_if_between(usage, 0x2f, 0x37, w, E_Notify, consTitles2, 0x80)
+ else output_if_between(usage, 0x3f, 0x49, w, E_Notify, consTitles3, 0x80)
+ else output_if_between(usage, 0x5f, 0x67, w, E_Notify, consTitles4, 0x80)
+ else output_if_between(usage, 0x7f, 0xa5, w, E_Notify, consTitles5, 0x80)
+ else output_if_between(usage, 0xaf, 0xcf, w, E_Notify, consTitles6, 0x80)
+ else output_if_between(usage, 0xdf, 0xeb, w, E_Notify, consTitles7, 0x80)
+ else output_if_between(usage, 0xef, 0xf6, w, E_Notify, consTitles8, 0x80)
+ else output_if_between(usage, 0xff, 0x10e, w, E_Notify, consTitles9, 0x80)
+ else output_if_between(usage, 0x14f, 0x156, w, E_Notify, consTitlesA, 0x80)
+ else output_if_between(usage, 0x15f, 0x16b, w, E_Notify, consTitlesB, 0x80)
+ else output_if_between(usage, 0x16f, 0x175, w, E_Notify, consTitlesC, 0x80)
+ else output_if_between(usage, 0x17f, 0x1c8, w, E_Notify, consTitlesD, 0x80)
+ else output_if_between(usage, 0x1ff, 0x29d, w, E_Notify, consTitlesE, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintDigitizerPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x0e, w, E_Notify, digitTitles0, 0x80)
+ else output_if_between(usage, 0x1f, 0x23, w, E_Notify, digitTitles1, 0x80)
+ else output_if_between(usage, 0x2f, 0x47, w, E_Notify, digitTitles2, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintAlphanumDisplayPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ output_if_between(usage, 0x00, 0x03, w, E_Notify, aplphanumTitles0, 0x80)
+ else output_if_between(usage, 0x1f, 0x4e, w, E_Notify, aplphanumTitles1, 0x80)
+ else output_if_between(usage, 0x7f, 0x96, w, E_Notify, digitTitles2, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+void ReportDescParserBase::PrintMedicalInstrumentPageUsage(uint16_t usage) {
+ const char * const * w;
+ E_Notify(pstrSpace, 0x80);
+
+ if(usage == 1) E_Notify(pstrUsageMedicalUltrasound, 0x80);
+ else if(usage == 0x70)
+ E_Notify(pstrUsageDepthGainCompensation, 0x80);
+ else output_if_between(usage, 0x1f, 0x28, w, E_Notify, medInstrTitles0, 0x80)
+ else output_if_between(usage, 0x3f, 0x45, w, E_Notify, medInstrTitles1, 0x80)
+ else output_if_between(usage, 0x5f, 0x62, w, E_Notify, medInstrTitles2, 0x80)
+ else output_if_between(usage, 0x7f, 0x8a, w, E_Notify, medInstrTitles3, 0x80)
+ else output_if_between(usage, 0x9f, 0xa2, w, E_Notify, medInstrTitles4, 0x80)
+ else E_Notify(pstrUsagePageUndefined, 0x80);
+}
+
+uint8_t ReportDescParser2::ParseItem(uint8_t **pp, uint16_t *pcntdn) {
+ //uint8_t ret = enErrorSuccess;
+
+ switch(itemParseState) {
+ case 0:
+ if(**pp == HID_LONG_ITEM_PREFIX)
+ USBTRACE("\r\nLONG\r\n");
+ else {
+ uint8_t size = ((**pp) & DATA_SIZE_MASK);
+ itemPrefix = (**pp);
+ itemSize = 1 + ((size == DATA_SIZE_4) ? 4 : size);
+ }
+ (*pp)++;
+ (*pcntdn)--;
+ itemSize--;
+ itemParseState = 1;
+
+ if(!itemSize)
+ break;
+
+ if(!pcntdn)
+ return enErrorIncomplete;
+ case 1:
+ theBuffer.valueSize = itemSize;
+ valParser.Initialize(&theBuffer);
+ itemParseState = 2;
+ case 2:
+ if(!valParser.Parse(pp, pcntdn))
+ return enErrorIncomplete;
+ itemParseState = 3;
+ case 3:
+ {
+ uint8_t data = *((uint8_t*)varBuffer);
+
+ switch(itemPrefix & (TYPE_MASK | TAG_MASK)) {
+ case (TYPE_LOCAL | TAG_LOCAL_USAGE):
+ if(pfUsage) {
+ if(theBuffer.valueSize > 1) {
+ uint16_t* ui16 = reinterpret_cast<uint16_t *>(varBuffer);
+ pfUsage(*ui16);
+ } else
+ pfUsage(data);
+ }
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTSIZE):
+ rptSize = data;
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTCOUNT):
+ rptCount = data;
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_REPORTID):
+ rptId = data;
+ break;
+ case (TYPE_LOCAL | TAG_LOCAL_USAGEMIN):
+ useMin = data;
+ break;
+ case (TYPE_LOCAL | TAG_LOCAL_USAGEMAX):
+ useMax = data;
+ break;
+ case (TYPE_GLOBAL | TAG_GLOBAL_USAGEPAGE):
+ SetUsagePage(data);
+ break;
+ case (TYPE_MAIN | TAG_MAIN_OUTPUT):
+ case (TYPE_MAIN | TAG_MAIN_FEATURE):
+ rptSize = 0;
+ rptCount = 0;
+ useMin = 0;
+ useMax = 0;
+ break;
+ case (TYPE_MAIN | TAG_MAIN_INPUT):
+ OnInputItem(data);
+
+ totalSize += (uint16_t)rptSize * (uint16_t)rptCount;
+
+ rptSize = 0;
+ rptCount = 0;
+ useMin = 0;
+ useMax = 0;
+ break;
+ } // switch (**pp & (TYPE_MASK | TAG_MASK))
+ }
+ } // switch (itemParseState)
+ itemParseState = 0;
+ return enErrorSuccess;
+}
+
+void ReportDescParser2::OnInputItem(uint8_t itm) {
+ uint8_t byte_offset = (totalSize >> 3); // calculate offset to the next unhandled byte i = (int)(totalCount / 8);
+ uint32_t tmp = (byte_offset << 3);
+ uint8_t bit_offset = totalSize - tmp; // number of bits in the current byte already handled
+ uint8_t *p = pBuf + byte_offset; // current byte pointer
+
+ if(bit_offset)
+ *p >>= bit_offset;
+
+ uint8_t usage = useMin;
+
+ bool print_usemin_usemax = ((useMin < useMax) && ((itm & 3) == 2) && pfUsage) ? true : false;
+
+ uint8_t bits_of_byte = 8;
+
+ // for each field in field array defined by rptCount
+ for(uint8_t field = 0; field < rptCount; field++, usage++) {
+
+ union {
+ uint8_t bResult[4];
+ uint16_t wResult[2];
+ uint32_t dwResult;
+ } result;
+
+ result.dwResult = 0;
+ uint8_t mask = 0;
+
+ if(print_usemin_usemax)
+ pfUsage(usage);
+
+ // bits_left - number of bits in the field(array of fields, depending on Report Count) left to process
+ // bits_of_byte - number of bits in current byte left to process
+ // bits_to_copy - number of bits to copy to result buffer
+
+ // for each bit in a field
+ for(uint8_t bits_left = rptSize, bits_to_copy = 0; bits_left;
+ bits_left -= bits_to_copy) {
+ bits_to_copy = (bits_left > bits_of_byte) ? bits_of_byte : bits_left;
+
+ result.dwResult <<= bits_to_copy; // Result buffer is shifted by the number of bits to be copied into it
+
+ uint8_t val = *p;
+
+ val >>= (8 - bits_of_byte); // Shift by the number of bits already processed
+
+ mask = 0;
+
+ for(uint8_t j = bits_to_copy; j; j--) {
+ mask <<= 1;
+ mask |= 1;
+ }
+
+ result.bResult[0] = (result.bResult[0] | (val & mask));
+
+ bits_of_byte -= bits_to_copy;
+
+ if(bits_of_byte < 1) {
+ bits_of_byte = 8;
+ p++;
+ }
+ }
+ PrintByteValue(result.dwResult);
+ }
+ E_Notify(PSTR("\r\n"), 0x80);
+}
+
+void UniversalReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
+ ReportDescParser2 prs(len, buf);
+
+ uint8_t ret = hid->GetReportDescr(0, &prs);
+
+ if(ret)
+ ErrorMessage<uint8_t > (PSTR("GetReportDescr-2"), ret);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidescriptorparser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidescriptorparser.h
new file mode 100644
index 000000000..f3b496ffa
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidescriptorparser.h
@@ -0,0 +1,176 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__HIDDESCRIPTORPARSER_H__)
+#define __HIDDESCRIPTORPARSER_H__
+
+#include "hid.h"
+
+class ReportDescParserBase : public USBReadParser {
+public:
+ typedef void (*UsagePageFunc)(uint16_t usage);
+
+ static void PrintGenericDesktopPageUsage(uint16_t usage);
+ static void PrintSimulationControlsPageUsage(uint16_t usage);
+ static void PrintVRControlsPageUsage(uint16_t usage);
+ static void PrintSportsControlsPageUsage(uint16_t usage);
+ static void PrintGameControlsPageUsage(uint16_t usage);
+ static void PrintGenericDeviceControlsPageUsage(uint16_t usage);
+ static void PrintLEDPageUsage(uint16_t usage);
+ static void PrintButtonPageUsage(uint16_t usage);
+ static void PrintOrdinalPageUsage(uint16_t usage);
+ static void PrintTelephonyPageUsage(uint16_t usage);
+ static void PrintConsumerPageUsage(uint16_t usage);
+ static void PrintDigitizerPageUsage(uint16_t usage);
+ static void PrintAlphanumDisplayPageUsage(uint16_t usage);
+ static void PrintMedicalInstrumentPageUsage(uint16_t usage);
+
+ static void PrintValue(uint8_t *p, uint8_t len);
+ static void PrintByteValue(uint8_t data);
+
+ static void PrintItemTitle(uint8_t prefix);
+
+ static const char * const usagePageTitles0[];
+ static const char * const usagePageTitles1[];
+ static const char * const genDesktopTitles0[];
+ static const char * const genDesktopTitles1[];
+ static const char * const genDesktopTitles2[];
+ static const char * const genDesktopTitles3[];
+ static const char * const genDesktopTitles4[];
+ static const char * const simuTitles0[];
+ static const char * const simuTitles1[];
+ static const char * const simuTitles2[];
+ static const char * const vrTitles0[];
+ static const char * const vrTitles1[];
+ static const char * const sportsCtrlTitles0[];
+ static const char * const sportsCtrlTitles1[];
+ static const char * const sportsCtrlTitles2[];
+ static const char * const gameTitles0[];
+ static const char * const gameTitles1[];
+ static const char * const genDevCtrlTitles[];
+ static const char * const ledTitles[];
+ static const char * const telTitles0[];
+ static const char * const telTitles1[];
+ static const char * const telTitles2[];
+ static const char * const telTitles3[];
+ static const char * const telTitles4[];
+ static const char * const telTitles5[];
+ static const char * const consTitles0[];
+ static const char * const consTitles1[];
+ static const char * const consTitles2[];
+ static const char * const consTitles3[];
+ static const char * const consTitles4[];
+ static const char * const consTitles5[];
+ static const char * const consTitles6[];
+ static const char * const consTitles7[];
+ static const char * const consTitles8[];
+ static const char * const consTitles9[];
+ static const char * const consTitlesA[];
+ static const char * const consTitlesB[];
+ static const char * const consTitlesC[];
+ static const char * const consTitlesD[];
+ static const char * const consTitlesE[];
+ static const char * const digitTitles0[];
+ static const char * const digitTitles1[];
+ static const char * const digitTitles2[];
+ static const char * const aplphanumTitles0[];
+ static const char * const aplphanumTitles1[];
+ static const char * const aplphanumTitles2[];
+ static const char * const medInstrTitles0[];
+ static const char * const medInstrTitles1[];
+ static const char * const medInstrTitles2[];
+ static const char * const medInstrTitles3[];
+ static const char * const medInstrTitles4[];
+
+protected:
+ static UsagePageFunc usagePageFunctions[];
+
+ MultiValueBuffer theBuffer;
+ MultiByteValueParser valParser;
+ ByteSkipper theSkipper;
+ uint8_t varBuffer[sizeof (USB_CONFIGURATION_DESCRIPTOR)];
+
+ uint8_t itemParseState; // Item parser state variable
+ uint8_t itemSize; // Item size
+ uint8_t itemPrefix; // Item prefix (first byte)
+ uint8_t rptSize; // Report Size
+ uint8_t rptCount; // Report Count
+
+ uint16_t totalSize; // Report size in bits
+
+ // Method should be defined here if virtual.
+ virtual uint8_t ParseItem(uint8_t **pp, uint16_t *pcntdn);
+
+ UsagePageFunc pfUsage;
+
+ static void PrintUsagePage(uint16_t page);
+ void SetUsagePage(uint16_t page);
+
+public:
+
+ ReportDescParserBase() :
+ itemParseState(0),
+ itemSize(0),
+ itemPrefix(0),
+ rptSize(0),
+ rptCount(0),
+ pfUsage(NULL) {
+ theBuffer.pValue = varBuffer;
+ valParser.Initialize(&theBuffer);
+ theSkipper.Initialize(&theBuffer);
+ };
+
+ void Parse(const uint16_t len, const uint8_t *pbuf, const uint16_t &offset);
+
+ enum {
+ enErrorSuccess = 0
+ , enErrorIncomplete // value or record is partialy read in buffer
+ , enErrorBufferTooSmall
+ };
+};
+
+class ReportDescParser : public ReportDescParserBase {
+};
+
+class ReportDescParser2 : public ReportDescParserBase {
+ uint8_t rptId; // Report ID
+ uint8_t useMin; // Usage Minimum
+ uint8_t useMax; // Usage Maximum
+ uint8_t fieldCount; // Number of field being currently processed
+
+ void OnInputItem(uint8_t itm); // Method which is called every time Input item is found
+
+ uint8_t *pBuf; // Report buffer pointer
+ uint8_t bLen; // Report length
+
+protected:
+ // Method should be defined here if virtual.
+ virtual uint8_t ParseItem(uint8_t **pp, uint16_t *pcntdn);
+
+public:
+
+ ReportDescParser2(uint16_t len, uint8_t *pbuf) :
+ ReportDescParserBase(), rptId(0), useMin(0), useMax(0), fieldCount(0), pBuf(pbuf), bLen(len) {
+ };
+};
+
+class UniversalReportParser : public HIDReportParser {
+public:
+ // Method should be defined here if virtual.
+ virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
+};
+
+#endif // __HIDDESCRIPTORPARSER_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hiduniversal.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hiduniversal.cpp
new file mode 100644
index 000000000..395aa69e3
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hiduniversal.cpp
@@ -0,0 +1,425 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#include "hiduniversal.h"
+
+HIDUniversal::HIDUniversal(USB *p) :
+HID(p),
+qNextPollTime(0),
+pollInterval(0),
+bPollEnable(false),
+bHasReportId(false) {
+ Initialize();
+
+ if(pUsb)
+ pUsb->RegisterDeviceClass(this);
+}
+
+uint16_t HIDUniversal::GetHidClassDescrLen(uint8_t type, uint8_t num) {
+ for(uint8_t i = 0, n = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) {
+ if(descrInfo[i].bDescrType == type) {
+ if(n == num)
+ return descrInfo[i].wDescriptorLength;
+ n++;
+ }
+ }
+ return 0;
+}
+
+void HIDUniversal::Initialize() {
+ for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) {
+ rptParsers[i].rptId = 0;
+ rptParsers[i].rptParser = NULL;
+ }
+ for(uint8_t i = 0; i < HID_MAX_HID_CLASS_DESCRIPTORS; i++) {
+ descrInfo[i].bDescrType = 0;
+ descrInfo[i].wDescriptorLength = 0;
+ }
+ for(uint8_t i = 0; i < maxHidInterfaces; i++) {
+ hidInterfaces[i].bmInterface = 0;
+ hidInterfaces[i].bmProtocol = 0;
+
+ for(uint8_t j = 0; j < maxEpPerInterface; j++)
+ hidInterfaces[i].epIndex[j] = 0;
+ }
+ for(uint8_t i = 0; i < totalEndpoints; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+ epInfo[i].bmNakPower = (i) ? USB_NAK_NOWAIT : USB_NAK_MAX_POWER;
+ }
+ bNumEP = 1;
+ bNumIface = 0;
+ bConfNum = 0;
+ pollInterval = 0;
+
+ ZeroMemory(constBuffLen, prevBuf);
+}
+
+bool HIDUniversal::SetReportParser(uint8_t id, HIDReportParser *prs) {
+ for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) {
+ if(rptParsers[i].rptId == 0 && rptParsers[i].rptParser == NULL) {
+ rptParsers[i].rptId = id;
+ rptParsers[i].rptParser = prs;
+ return true;
+ }
+ }
+ return false;
+}
+
+HIDReportParser* HIDUniversal::GetReportParser(uint8_t id) {
+ if(!bHasReportId)
+ return ((rptParsers[0].rptParser) ? rptParsers[0].rptParser : NULL);
+
+ for(uint8_t i = 0; i < MAX_REPORT_PARSERS; i++) {
+ if(rptParsers[i].rptId == id)
+ return rptParsers[i].rptParser;
+ }
+ return NULL;
+}
+
+uint8_t HIDUniversal::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+
+ uint8_t buf[constBufSize];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint8_t len = 0;
+
+ uint8_t num_of_conf; // number of configurations
+ //uint8_t num_of_intf; // number of interfaces
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+ USBTRACE("HU Init\r\n");
+
+ if(bAddress)
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p->epinfo) {
+ USBTRACE("epinfo\r\n");
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf);
+
+ if(!rcode)
+ len = (buf[0] > constBufSize) ? constBufSize : buf[0];
+
+ if(rcode) {
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ goto FailGetDevDescr;
+ }
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from the device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ USBTRACE2("setAddr:", rcode);
+ return rcode;
+ }
+
+ //delay(2); //per USB 2.0 sect.9.2.6.3
+
+ USBTRACE2("Addr:", bAddress);
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ if(len)
+ rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf);
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ VID = udd->idVendor; // Can be used by classes that inherits this class to check the VID and PID of the connected device
+ PID = udd->idProduct;
+
+ num_of_conf = udd->bNumConfigurations;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ USBTRACE2("NC:", num_of_conf);
+
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ //HexDumper<USBReadParser, uint16_t, uint16_t> HexDump;
+ ConfigDescParser<USB_CLASS_HID, 0, 0,
+ CP_MASK_COMPARE_CLASS> confDescrParser(this);
+
+ //rcode = pUsb->getConfDescr(bAddress, 0, i, &HexDump);
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &confDescrParser);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ if(bNumEP > 1)
+ break;
+ } // for
+
+ if(bNumEP < 2)
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
+
+ USBTRACE2("Cnf:", bConfNum);
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, bConfNum);
+
+ if(rcode)
+ goto FailSetConfDescr;
+
+ for(uint8_t i = 0; i < bNumIface; i++) {
+ if(hidInterfaces[i].epIndex[epInterruptInIndex] == 0)
+ continue;
+
+ rcode = SetIdle(hidInterfaces[i].bmInterface, 0, 0);
+
+ if(rcode && rcode != hrSTALL)
+ goto FailSetIdle;
+ }
+
+ USBTRACE("HU configured\r\n");
+
+ OnInitSuccessful();
+
+ bPollEnable = true;
+ return 0;
+
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr();
+ goto Fail;
+#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailGetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetConfDescr();
+ goto Fail;
+#endif
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+ goto Fail;
+#endif
+
+
+FailSetIdle:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("SetIdle:");
+#endif
+
+#ifdef DEBUG_USB_HOST
+Fail:
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+HIDUniversal::HIDInterface* HIDUniversal::FindInterface(uint8_t iface, uint8_t alt, uint8_t proto) {
+ for(uint8_t i = 0; i < bNumIface && i < maxHidInterfaces; i++)
+ if(hidInterfaces[i].bmInterface == iface && hidInterfaces[i].bmAltSet == alt
+ && hidInterfaces[i].bmProtocol == proto)
+ return hidInterfaces + i;
+ return NULL;
+}
+
+void HIDUniversal::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *pep) {
+ // If the first configuration satisfies, the others are not concidered.
+ if(bNumEP > 1 && conf != bConfNum)
+ return;
+
+ //ErrorMessage<uint8_t>(PSTR("\r\nConf.Val"), conf);
+ //ErrorMessage<uint8_t>(PSTR("Iface Num"), iface);
+ //ErrorMessage<uint8_t>(PSTR("Alt.Set"), alt);
+
+ bConfNum = conf;
+
+ uint8_t index = 0;
+ HIDInterface *piface = FindInterface(iface, alt, proto);
+
+ // Fill in interface structure in case of new interface
+ if(!piface) {
+ piface = hidInterfaces + bNumIface;
+ piface->bmInterface = iface;
+ piface->bmAltSet = alt;
+ piface->bmProtocol = proto;
+ bNumIface++;
+ }
+
+ if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80)
+ index = epInterruptInIndex;
+ else
+ index = epInterruptOutIndex;
+
+ if(index) {
+ // Fill in the endpoint info structure
+ epInfo[bNumEP].epAddr = (pep->bEndpointAddress & 0x0F);
+ epInfo[bNumEP].maxPktSize = (uint8_t)pep->wMaxPacketSize;
+ epInfo[bNumEP].epAttribs = 0;
+ epInfo[bNumEP].bmNakPower = USB_NAK_NOWAIT;
+
+ // Fill in the endpoint index list
+ piface->epIndex[index] = bNumEP; //(pep->bEndpointAddress & 0x0F);
+
+ if(pollInterval < pep->bInterval) // Set the polling interval as the largest polling interval obtained from endpoints
+ pollInterval = pep->bInterval;
+
+ bNumEP++;
+ }
+ //PrintEndpointDescriptor(pep);
+}
+
+uint8_t HIDUniversal::Release() {
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+
+ bNumEP = 1;
+ bAddress = 0;
+ qNextPollTime = 0;
+ bPollEnable = false;
+ return 0;
+}
+
+bool HIDUniversal::BuffersIdentical(uint8_t len, uint8_t *buf1, uint8_t *buf2) {
+ for(uint8_t i = 0; i < len; i++)
+ if(buf1[i] != buf2[i])
+ return false;
+ return true;
+}
+
+void HIDUniversal::ZeroMemory(uint8_t len, uint8_t *buf) {
+ for(uint8_t i = 0; i < len; i++)
+ buf[i] = 0;
+}
+
+void HIDUniversal::SaveBuffer(uint8_t len, uint8_t *src, uint8_t *dest) {
+ for(uint8_t i = 0; i < len; i++)
+ dest[i] = src[i];
+}
+
+uint8_t HIDUniversal::Poll() {
+ uint8_t rcode = 0;
+
+ if(!bPollEnable)
+ return 0;
+
+ if((long)(millis() - qNextPollTime) >= 0L) {
+ qNextPollTime = millis() + pollInterval;
+
+ uint8_t buf[constBuffLen];
+
+ for(uint8_t i = 0; i < bNumIface; i++) {
+ uint8_t index = hidInterfaces[i].epIndex[epInterruptInIndex];
+ uint16_t read = (uint16_t)epInfo[index].maxPktSize;
+
+ ZeroMemory(constBuffLen, buf);
+
+ uint8_t rcode = pUsb->inTransfer(bAddress, epInfo[index].epAddr, &read, buf);
+
+ if(rcode) {
+ if(rcode != hrNAK)
+ USBTRACE3("(hiduniversal.h) Poll:", rcode, 0x81);
+ return rcode;
+ }
+
+ if(read > constBuffLen)
+ read = constBuffLen;
+
+ bool identical = BuffersIdentical(read, buf, prevBuf);
+
+ SaveBuffer(read, buf, prevBuf);
+
+ if(identical)
+ return 0;
+#if 0
+ Notify(PSTR("\r\nBuf: "), 0x80);
+
+ for(uint8_t i = 0; i < read; i++) {
+ D_PrintHex<uint8_t > (buf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+ ParseHIDData(this, bHasReportId, (uint8_t)read, buf);
+
+ HIDReportParser *prs = GetReportParser(((bHasReportId) ? *buf : 0));
+
+ if(prs)
+ prs->Parse(this, bHasReportId, (uint8_t)read, buf);
+ }
+ }
+ return rcode;
+}
+
+// Send a report to interrupt out endpoint. This is NOT SetReport() request!
+uint8_t HIDUniversal::SndRpt(uint16_t nbytes, uint8_t *dataptr) {
+ return pUsb->outTransfer(bAddress, epInfo[epInterruptOutIndex].epAddr, nbytes, dataptr);
+} \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hiduniversal.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hiduniversal.h
new file mode 100644
index 000000000..d7af38406
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hiduniversal.h
@@ -0,0 +1,108 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#if !defined(__HIDUNIVERSAL_H__)
+#define __HIDUNIVERSAL_H__
+
+#include "hid.h"
+//#include "hidescriptorparser.h"
+
+class HIDUniversal : public HID {
+
+ struct ReportParser {
+ uint8_t rptId;
+ HIDReportParser *rptParser;
+ } rptParsers[MAX_REPORT_PARSERS];
+
+ // HID class specific descriptor type and length info obtained from HID descriptor
+ HID_CLASS_DESCRIPTOR_LEN_AND_TYPE descrInfo[HID_MAX_HID_CLASS_DESCRIPTORS];
+
+ // Returns HID class specific descriptor length by its type and order number
+ uint16_t GetHidClassDescrLen(uint8_t type, uint8_t num);
+
+ struct HIDInterface {
+ struct {
+ uint8_t bmInterface : 3;
+ uint8_t bmAltSet : 3;
+ uint8_t bmProtocol : 2;
+ };
+ uint8_t epIndex[maxEpPerInterface];
+ };
+
+ uint8_t bConfNum; // configuration number
+ uint8_t bNumIface; // number of interfaces in the configuration
+ uint8_t bNumEP; // total number of EP in the configuration
+ uint32_t qNextPollTime; // next poll time
+ uint8_t pollInterval;
+ bool bPollEnable; // poll enable flag
+
+ static const uint16_t constBuffLen = 64; // event buffer length
+ uint8_t prevBuf[constBuffLen]; // previous event buffer
+
+ void Initialize();
+ HIDInterface* FindInterface(uint8_t iface, uint8_t alt, uint8_t proto);
+
+ void ZeroMemory(uint8_t len, uint8_t *buf);
+ bool BuffersIdentical(uint8_t len, uint8_t *buf1, uint8_t *buf2);
+ void SaveBuffer(uint8_t len, uint8_t *src, uint8_t *dest);
+
+protected:
+ EpInfo epInfo[totalEndpoints];
+ HIDInterface hidInterfaces[maxHidInterfaces];
+
+ bool bHasReportId;
+
+ uint16_t PID, VID; // PID and VID of connected device
+
+ // HID implementation
+ HIDReportParser* GetReportParser(uint8_t id);
+
+ virtual uint8_t OnInitSuccessful() {
+ return 0;
+ };
+
+ virtual void ParseHIDData(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf) {
+ return;
+ };
+
+public:
+ HIDUniversal(USB *p);
+
+ // HID implementation
+ bool SetReportParser(uint8_t id, HIDReportParser *prs);
+
+ // USBDeviceConfig implementation
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t Release();
+ uint8_t Poll();
+
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ virtual bool isReady() {
+ return bPollEnable;
+ };
+
+ // UsbConfigXtracter implementation
+ void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
+
+ // Send report - do not mix with SetReport()!
+ uint8_t SndRpt(uint16_t nbytes, uint8_t *dataptr);
+};
+
+#endif // __HIDUNIVERSAL_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidusagestr.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidusagestr.h
new file mode 100644
index 000000000..5ef48f925
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidusagestr.h
@@ -0,0 +1,977 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined( __HIDUSAGESTR_H__)
+#define __HIDUSAGESTR_H__
+
+#include "Usb.h"
+
+const char pstrSpace [] PROGMEM = " ";
+const char pstrCRLF [] PROGMEM = "\r\n";
+const char pstrSingleTab [] PROGMEM = "\t";
+const char pstrDoubleTab [] PROGMEM = "\t\t";
+const char pstrTripleTab [] PROGMEM = "\t\t\t";
+
+// Usage Page String Titles
+const char pstrUsagePageUndefined [] PROGMEM = "Undef";
+const char pstrUsagePageGenericDesktopControls [] PROGMEM = "Gen Desktop Ctrls";
+const char pstrUsagePageSimulationControls [] PROGMEM = "Simu Ctrls";
+const char pstrUsagePageVRControls [] PROGMEM = "VR Ctrls";
+const char pstrUsagePageSportControls [] PROGMEM = "Sport Ctrls";
+const char pstrUsagePageGameControls [] PROGMEM = "Game Ctrls";
+const char pstrUsagePageGenericDeviceControls [] PROGMEM = "Gen Dev Ctrls";
+const char pstrUsagePageKeyboardKeypad [] PROGMEM = "Kbrd/Keypad";
+const char pstrUsagePageLEDs [] PROGMEM = "LEDs";
+const char pstrUsagePageButton [] PROGMEM = "Button";
+const char pstrUsagePageOrdinal [] PROGMEM = "Ordinal";
+const char pstrUsagePageTelephone [] PROGMEM = "Tel";
+const char pstrUsagePageConsumer [] PROGMEM = "Consumer";
+const char pstrUsagePageDigitizer [] PROGMEM = "Digitizer";
+const char pstrUsagePagePID [] PROGMEM = "PID";
+const char pstrUsagePageUnicode [] PROGMEM = "Unicode";
+const char pstrUsagePageAlphaNumericDisplay [] PROGMEM = "Alpha Num Disp";
+const char pstrUsagePageMedicalInstruments [] PROGMEM = "Medical Instr";
+const char pstrUsagePageMonitor [] PROGMEM = "Monitor";
+const char pstrUsagePagePower [] PROGMEM = "Power";
+const char pstrUsagePageBarCodeScanner [] PROGMEM = "Bar Code Scan";
+const char pstrUsagePageScale [] PROGMEM = "Scale";
+const char pstrUsagePageMSRDevices [] PROGMEM = "Magn Stripe Read Dev";
+const char pstrUsagePagePointOfSale [] PROGMEM = "POS";
+const char pstrUsagePageCameraControl [] PROGMEM = "Cam Ctrl";
+const char pstrUsagePageArcade [] PROGMEM = "Arcade";
+const char pstrUsagePageReserved [] PROGMEM = "Reserved";
+const char pstrUsagePageVendorDefined [] PROGMEM = "Vendor Def";
+
+// Generic Desktop Controls Page
+const char pstrUsagePointer [] PROGMEM = "Pointer";
+const char pstrUsageMouse [] PROGMEM = "Mouse";
+const char pstrUsageJoystick [] PROGMEM = "Joystick";
+const char pstrUsageGamePad [] PROGMEM = "Game Pad";
+const char pstrUsageKeyboard [] PROGMEM = "Kbrd";
+const char pstrUsageKeypad [] PROGMEM = "Keypad";
+const char pstrUsageMultiAxisController [] PROGMEM = "Multi-axis Ctrl";
+const char pstrUsageTabletPCSystemControls [] PROGMEM = "Tablet PC Sys Ctrls";
+const char pstrUsageX [] PROGMEM = "X";
+const char pstrUsageY [] PROGMEM = "Y";
+const char pstrUsageZ [] PROGMEM = "Z";
+const char pstrUsageRx [] PROGMEM = "Rx";
+const char pstrUsageRy [] PROGMEM = "Ry";
+const char pstrUsageRz [] PROGMEM = "Rz";
+const char pstrUsageSlider [] PROGMEM = "Slider";
+const char pstrUsageDial [] PROGMEM = "Dial";
+const char pstrUsageWheel [] PROGMEM = "Wheel";
+const char pstrUsageHatSwitch [] PROGMEM = "Hat Switch";
+const char pstrUsageCountedBuffer [] PROGMEM = "Counted Buf";
+const char pstrUsageByteCount [] PROGMEM = "Byte Count";
+const char pstrUsageMotionWakeup [] PROGMEM = "Motion Wakeup";
+const char pstrUsageStart [] PROGMEM = "Start";
+const char pstrUsageSelect [] PROGMEM = "Sel";
+const char pstrUsageVx [] PROGMEM = "Vx";
+const char pstrUsageVy [] PROGMEM = "Vy";
+const char pstrUsageVz [] PROGMEM = "Vz";
+const char pstrUsageVbrx [] PROGMEM = "Vbrx";
+const char pstrUsageVbry [] PROGMEM = "Vbry";
+const char pstrUsageVbrz [] PROGMEM = "Vbrz";
+const char pstrUsageVno [] PROGMEM = "Vno";
+const char pstrUsageFeatureNotification [] PROGMEM = "Feature Notif";
+const char pstrUsageResolutionMultiplier [] PROGMEM = "Res Mult";
+const char pstrUsageSystemControl [] PROGMEM = "Sys Ctrl";
+const char pstrUsageSystemPowerDown [] PROGMEM = "Sys Pwr Down";
+const char pstrUsageSystemSleep [] PROGMEM = "Sys Sleep";
+const char pstrUsageSystemWakeup [] PROGMEM = "Sys Wakeup";
+const char pstrUsageSystemContextMenu [] PROGMEM = "Sys Context Menu";
+const char pstrUsageSystemMainMenu [] PROGMEM = "Sys Main Menu";
+const char pstrUsageSystemAppMenu [] PROGMEM = "Sys App Menu";
+const char pstrUsageSystemMenuHelp [] PROGMEM = "Sys Menu Help";
+const char pstrUsageSystemMenuExit [] PROGMEM = "Sys Menu Exit";
+const char pstrUsageSystemMenuSelect [] PROGMEM = "Sys Menu Select";
+const char pstrUsageSystemMenuRight [] PROGMEM = "Sys Menu Right";
+const char pstrUsageSystemMenuLeft [] PROGMEM = "Sys Menu Left";
+const char pstrUsageSystemMenuUp [] PROGMEM = "Sys Menu Up";
+const char pstrUsageSystemMenuDown [] PROGMEM = "Sys Menu Down";
+const char pstrUsageSystemColdRestart [] PROGMEM = "Sys Cold Restart";
+const char pstrUsageSystemWarmRestart [] PROGMEM = "Sys Warm Restart";
+const char pstrUsageDPadUp [] PROGMEM = "D-pad Up";
+const char pstrUsageDPadDown [] PROGMEM = "D-pad Down";
+const char pstrUsageDPadRight [] PROGMEM = "D-pad Right";
+const char pstrUsageDPadLeft [] PROGMEM = "D-pad Left";
+const char pstrUsageSystemDock [] PROGMEM = "Sys Dock";
+const char pstrUsageSystemUndock [] PROGMEM = "Sys Undock";
+const char pstrUsageSystemSetup [] PROGMEM = "Sys Setup";
+const char pstrUsageSystemBreak [] PROGMEM = "Sys Break";
+const char pstrUsageSystemDebuggerBreak [] PROGMEM = "Sys Dbg Brk";
+const char pstrUsageApplicationBreak [] PROGMEM = "App Break";
+const char pstrUsageApplicationDebuggerBreak [] PROGMEM = "App Dbg Brk";
+const char pstrUsageSystemSpeakerMute [] PROGMEM = "Sys Spk Mute";
+const char pstrUsageSystemHibernate [] PROGMEM = "Sys Hiber";
+const char pstrUsageSystemDisplayInvert [] PROGMEM = "Sys Disp Inv";
+const char pstrUsageSystemDisplayInternal [] PROGMEM = "Sys Disp Int";
+const char pstrUsageSystemDisplayExternal [] PROGMEM = "Sys Disp Ext";
+const char pstrUsageSystemDisplayBoth [] PROGMEM = "Sys Disp Both";
+const char pstrUsageSystemDisplayDual [] PROGMEM = "Sys Disp Dual";
+const char pstrUsageSystemDisplayToggleIntExt [] PROGMEM = "Sys Disp Tgl Int/Ext";
+const char pstrUsageSystemDisplaySwapPriSec [] PROGMEM = "Sys Disp Swap Pri/Sec";
+const char pstrUsageSystemDisplayLCDAutoscale [] PROGMEM = "Sys Disp LCD Autoscale";
+
+// Simulation Controls Page
+const char pstrUsageFlightSimulationDevice [] PROGMEM = "Flight Simu Dev";
+const char pstrUsageAutomobileSimulationDevice [] PROGMEM = "Auto Simu Dev";
+const char pstrUsageTankSimulationDevice [] PROGMEM = "Tank Simu Dev";
+const char pstrUsageSpaceshipSimulationDevice [] PROGMEM = "Space Simu Dev";
+const char pstrUsageSubmarineSimulationDevice [] PROGMEM = "Subm Simu Dev";
+const char pstrUsageSailingSimulationDevice [] PROGMEM = "Sail Simu Dev";
+const char pstrUsageMotocicleSimulationDevice [] PROGMEM = "Moto Simu Dev";
+const char pstrUsageSportsSimulationDevice [] PROGMEM = "Sport Simu Dev";
+const char pstrUsageAirplaneSimulationDevice [] PROGMEM = "Airp Simu Dev";
+const char pstrUsageHelicopterSimulationDevice [] PROGMEM = "Heli Simu Dev";
+const char pstrUsageMagicCarpetSimulationDevice [] PROGMEM = "Magic Carpet Simu Dev";
+const char pstrUsageBicycleSimulationDevice [] PROGMEM = "Bike Simu Dev";
+const char pstrUsageFlightControlStick [] PROGMEM = "Flight Ctrl Stick";
+const char pstrUsageFlightStick [] PROGMEM = "Flight Stick";
+const char pstrUsageCyclicControl [] PROGMEM = "Cyclic Ctrl";
+const char pstrUsageCyclicTrim [] PROGMEM = "Cyclic Trim";
+const char pstrUsageFlightYoke [] PROGMEM = "Flight Yoke";
+const char pstrUsageTrackControl [] PROGMEM = "Track Ctrl";
+const char pstrUsageAileron [] PROGMEM = "Aileron";
+const char pstrUsageAileronTrim [] PROGMEM = "Aileron Trim";
+const char pstrUsageAntiTorqueControl [] PROGMEM = "Anti-Torque Ctrl";
+const char pstrUsageAutopilotEnable [] PROGMEM = "Autopilot Enable";
+const char pstrUsageChaffRelease [] PROGMEM = "Chaff Release";
+const char pstrUsageCollectiveControl [] PROGMEM = "Collective Ctrl";
+const char pstrUsageDiveBrake [] PROGMEM = "Dive Brake";
+const char pstrUsageElectronicCountermeasures [] PROGMEM = "El Countermeasures";
+const char pstrUsageElevator [] PROGMEM = "Elevator";
+const char pstrUsageElevatorTrim [] PROGMEM = "Elevator Trim";
+const char pstrUsageRudder [] PROGMEM = "Rudder";
+const char pstrUsageThrottle [] PROGMEM = "Throttle";
+const char pstrUsageFlightCommunications [] PROGMEM = "Flight Comm";
+const char pstrUsageFlareRelease [] PROGMEM = "Flare Release";
+const char pstrUsageLandingGear [] PROGMEM = "Landing Gear";
+const char pstrUsageToeBrake [] PROGMEM = "Toe Brake";
+const char pstrUsageTrigger [] PROGMEM = "Trigger";
+const char pstrUsageWeaponsArm [] PROGMEM = "Weapons Arm";
+const char pstrUsageWeaponsSelect [] PROGMEM = "Weapons Sel";
+const char pstrUsageWingFlaps [] PROGMEM = "Wing Flaps";
+const char pstrUsageAccelerator [] PROGMEM = "Accel";
+const char pstrUsageBrake [] PROGMEM = "Brake";
+const char pstrUsageClutch [] PROGMEM = "Clutch";
+const char pstrUsageShifter [] PROGMEM = "Shifter";
+const char pstrUsageSteering [] PROGMEM = "Steering";
+const char pstrUsageTurretDirection [] PROGMEM = "Turret Dir";
+const char pstrUsageBarrelElevation [] PROGMEM = "Barrel Ele";
+const char pstrUsageDivePlane [] PROGMEM = "Dive Plane";
+const char pstrUsageBallast [] PROGMEM = "Ballast";
+const char pstrUsageBicycleCrank [] PROGMEM = "Bicycle Crank";
+const char pstrUsageHandleBars [] PROGMEM = "Handle Bars";
+const char pstrUsageFrontBrake [] PROGMEM = "Front Brake";
+const char pstrUsageRearBrake [] PROGMEM = "Rear Brake";
+
+// VR Controls Page
+const char pstrUsageBelt [] PROGMEM = "Belt";
+const char pstrUsageBodySuit [] PROGMEM = "Body Suit";
+const char pstrUsageFlexor [] PROGMEM = "Flexor";
+const char pstrUsageGlove [] PROGMEM = "Glove";
+const char pstrUsageHeadTracker [] PROGMEM = "Head Track";
+const char pstrUsageHeadMountedDisplay [] PROGMEM = "Head Disp";
+const char pstrUsageHandTracker [] PROGMEM = "Hand Track";
+const char pstrUsageOculometer [] PROGMEM = "Oculometer";
+const char pstrUsageVest [] PROGMEM = "Vest";
+const char pstrUsageAnimatronicDevice [] PROGMEM = "Animat Dev";
+const char pstrUsageStereoEnable [] PROGMEM = "Stereo Enbl";
+const char pstrUsageDisplayEnable [] PROGMEM = "Display Enbl";
+
+// Sport Controls Page
+const char pstrUsageBaseballBat [] PROGMEM = "Baseball Bat";
+const char pstrUsageGolfClub [] PROGMEM = "Golf Club";
+const char pstrUsageRowingMachine [] PROGMEM = "Rowing Mach";
+const char pstrUsageTreadmill [] PROGMEM = "Treadmill";
+const char pstrUsageOar [] PROGMEM = "Oar";
+const char pstrUsageSlope [] PROGMEM = "Slope";
+const char pstrUsageRate [] PROGMEM = "Rate";
+const char pstrUsageStickSpeed [] PROGMEM = "Stick Speed";
+const char pstrUsageStickFaceAngle [] PROGMEM = "Stick Face Ang";
+const char pstrUsageStickHeelToe [] PROGMEM = "Stick Heel/Toe";
+const char pstrUsageStickFollowThough [] PROGMEM = "Stick Flw Thru";
+const char pstrUsageStickTempo [] PROGMEM = "Stick Tempo";
+const char pstrUsageStickType [] PROGMEM = "Stick Type";
+const char pstrUsageStickHeight [] PROGMEM = "Stick Hght";
+const char pstrUsagePutter [] PROGMEM = "Putter";
+const char pstrUsage1Iron [] PROGMEM = "1 Iron";
+const char pstrUsage2Iron [] PROGMEM = "2 Iron";
+const char pstrUsage3Iron [] PROGMEM = "3 Iron";
+const char pstrUsage4Iron [] PROGMEM = "4 Iron";
+const char pstrUsage5Iron [] PROGMEM = "5 Iron";
+const char pstrUsage6Iron [] PROGMEM = "6 Iron";
+const char pstrUsage7Iron [] PROGMEM = "7 Iron";
+const char pstrUsage8Iron [] PROGMEM = "8 Iron";
+const char pstrUsage9Iron [] PROGMEM = "9 Iron";
+const char pstrUsage10Iron [] PROGMEM = "10 Iron";
+const char pstrUsage11Iron [] PROGMEM = "11 Iron";
+const char pstrUsageSandWedge [] PROGMEM = "Sand Wedge";
+const char pstrUsageLoftWedge [] PROGMEM = "Loft Wedge";
+const char pstrUsagePowerWedge [] PROGMEM = "Pwr Wedge";
+const char pstrUsage1Wood [] PROGMEM = "1 Wood";
+const char pstrUsage3Wood [] PROGMEM = "3 Wood";
+const char pstrUsage5Wood [] PROGMEM = "5 Wood";
+const char pstrUsage7Wood [] PROGMEM = "7 Wood";
+const char pstrUsage9Wood [] PROGMEM = "9 Wood";
+
+// Game Controls Page
+const char pstrUsage3DGameController [] PROGMEM = "3D Game Ctrl";
+const char pstrUsagePinballDevice [] PROGMEM = "Pinball Dev";
+const char pstrUsageGunDevice [] PROGMEM = "Gun Dev";
+const char pstrUsagePointOfView [] PROGMEM = "POV";
+const char pstrUsageTurnRightLeft [] PROGMEM = "Turn Right Left";
+const char pstrUsagePitchForwardBackward [] PROGMEM = "Pitch Fwd/Back";
+const char pstrUsageRollRightLeft [] PROGMEM = "Roll Right/Left";
+const char pstrUsageMoveRightLeft [] PROGMEM = "Move Right/Left";
+const char pstrUsageMoveForwardBackward [] PROGMEM = "Move Fwd/Back";
+const char pstrUsageMoveUpDown [] PROGMEM = "Move Up/Down";
+const char pstrUsageLeanRightLeft [] PROGMEM = "Lean Right/Left";
+const char pstrUsageLeanForwardBackward [] PROGMEM = "Lean Fwd/Back";
+const char pstrUsageHeightOfPOV [] PROGMEM = "Height of POV";
+const char pstrUsageFlipper [] PROGMEM = "Flipper";
+const char pstrUsageSecondaryFlipper [] PROGMEM = "Second Flipper";
+const char pstrUsageBump [] PROGMEM = "Bump";
+const char pstrUsageNewGame [] PROGMEM = "New Game";
+const char pstrUsageShootBall [] PROGMEM = "Shoot Ball";
+const char pstrUsagePlayer [] PROGMEM = "Player";
+const char pstrUsageGunBolt [] PROGMEM = "Gun Bolt";
+const char pstrUsageGunClip [] PROGMEM = "Gun Clip";
+const char pstrUsageGunSelector [] PROGMEM = "Gun Sel";
+const char pstrUsageGunSingleShot [] PROGMEM = "Gun Sngl Shot";
+const char pstrUsageGunBurst [] PROGMEM = "Gun Burst";
+const char pstrUsageGunAutomatic [] PROGMEM = "Gun Auto";
+const char pstrUsageGunSafety [] PROGMEM = "Gun Safety";
+const char pstrUsageGamepadFireJump [] PROGMEM = "Gamepad Fire/Jump";
+const char pstrUsageGamepadTrigger [] PROGMEM = "Gamepad Trig";
+
+// Generic Device Controls Page
+const char pstrUsageBatteryStrength [] PROGMEM = "Bat Strength";
+const char pstrUsageWirelessChannel [] PROGMEM = "Wireless Ch";
+const char pstrUsageWirelessID [] PROGMEM = "Wireless ID";
+const char pstrUsageDiscoverWirelessControl [] PROGMEM = "Discover Wireless Ctrl";
+const char pstrUsageSecurityCodeCharEntered [] PROGMEM = "Sec Code Char Entrd";
+const char pstrUsageSecurityCodeCharErased [] PROGMEM = "Sec Code Char Erased";
+const char pstrUsageSecurityCodeCleared [] PROGMEM = "Sec Code Cleared";
+
+// LED Page
+const char pstrUsageNumLock [] PROGMEM = "Num Lock";
+const char pstrUsageCapsLock [] PROGMEM = "Caps Lock";
+const char pstrUsageScrollLock [] PROGMEM = "Scroll Lock";
+const char pstrUsageCompose [] PROGMEM = "Compose";
+const char pstrUsageKana [] PROGMEM = "Kana";
+const char pstrUsagePower [] PROGMEM = "Pwr";
+const char pstrUsageShift [] PROGMEM = "Shift";
+const char pstrUsageDoNotDisturb [] PROGMEM = "DND";
+const char pstrUsageMute [] PROGMEM = "Mute";
+const char pstrUsageToneEnable [] PROGMEM = "Tone Enbl";
+const char pstrUsageHighCutFilter [] PROGMEM = "High Cut Fltr";
+const char pstrUsageLowCutFilter [] PROGMEM = "Low Cut Fltr";
+const char pstrUsageEqualizerEnable [] PROGMEM = "Eq Enbl";
+const char pstrUsageSoundFieldOn [] PROGMEM = "Sound Field On";
+const char pstrUsageSurroundOn [] PROGMEM = "Surround On";
+const char pstrUsageRepeat [] PROGMEM = "Repeat";
+const char pstrUsageStereo [] PROGMEM = "Stereo";
+const char pstrUsageSamplingRateDetect [] PROGMEM = "Smpl Rate Detect";
+const char pstrUsageSpinning [] PROGMEM = "Spinning";
+const char pstrUsageCAV [] PROGMEM = "CAV";
+const char pstrUsageCLV [] PROGMEM = "CLV";
+const char pstrUsageRecordingFormatDetect [] PROGMEM = "Rec Format Detect";
+const char pstrUsageOffHook [] PROGMEM = "Off Hook";
+const char pstrUsageRing [] PROGMEM = "Ring";
+const char pstrUsageMessageWaiting [] PROGMEM = "Msg Wait";
+const char pstrUsageDataMode [] PROGMEM = "Data Mode";
+const char pstrUsageBatteryOperation [] PROGMEM = "Bat Op";
+const char pstrUsageBatteryOK [] PROGMEM = "Bat OK";
+const char pstrUsageBatteryLow [] PROGMEM = "Bat Low";
+const char pstrUsageSpeaker [] PROGMEM = "Speaker";
+const char pstrUsageHeadSet [] PROGMEM = "Head Set";
+const char pstrUsageHold [] PROGMEM = "Hold";
+const char pstrUsageMicrophone [] PROGMEM = "Mic";
+const char pstrUsageCoverage [] PROGMEM = "Coverage";
+const char pstrUsageNightMode [] PROGMEM = "Night Mode";
+const char pstrUsageSendCalls [] PROGMEM = "Send Calls";
+const char pstrUsageCallPickup [] PROGMEM = "Call Pickup";
+const char pstrUsageConference [] PROGMEM = "Conf";
+const char pstrUsageStandBy [] PROGMEM = "Stand-by";
+const char pstrUsageCameraOn [] PROGMEM = "Cam On";
+const char pstrUsageCameraOff [] PROGMEM = "Cam Off";
+const char pstrUsageOnLine [] PROGMEM = "On-Line";
+const char pstrUsageOffLine [] PROGMEM = "Off-Line";
+const char pstrUsageBusy [] PROGMEM = "Busy";
+const char pstrUsageReady [] PROGMEM = "Ready";
+const char pstrUsagePaperOut [] PROGMEM = "Paper Out";
+const char pstrUsagePaperJam [] PROGMEM = "Paper Jam";
+const char pstrUsageRemote [] PROGMEM = "Remote";
+const char pstrUsageForward [] PROGMEM = "Fwd";
+const char pstrUsageReverse [] PROGMEM = "Rev";
+const char pstrUsageStop [] PROGMEM = "Stop";
+const char pstrUsageRewind [] PROGMEM = "Rewind";
+const char pstrUsageFastForward [] PROGMEM = "Fast Fwd";
+const char pstrUsagePlay [] PROGMEM = "Play";
+const char pstrUsagePause [] PROGMEM = "Pause";
+const char pstrUsageRecord [] PROGMEM = "Rec";
+const char pstrUsageError [] PROGMEM = "Error";
+const char pstrUsageSelectedIndicator [] PROGMEM = "Usage Sel Ind";
+const char pstrUsageInUseIndicator [] PROGMEM = "Usage In Use Ind";
+const char pstrUsageMultiModeIndicator [] PROGMEM = "Usage Multi Mode Ind";
+const char pstrUsageIndicatorOn [] PROGMEM = "Ind On";
+const char pstrUsageIndicatorFlash [] PROGMEM = "Ind Flash";
+const char pstrUsageIndicatorSlowBlink [] PROGMEM = "Ind Slow Blk";
+const char pstrUsageIndicatorFastBlink [] PROGMEM = "Ind Fast Blk";
+const char pstrUsageIndicatorOff [] PROGMEM = "Ind Off";
+const char pstrUsageFlashOnTime [] PROGMEM = "Flash On Time";
+const char pstrUsageSlowBlinkOnTime [] PROGMEM = "Slow Blk On Time";
+const char pstrUsageSlowBlinkOffTime [] PROGMEM = "Slow Blk Off Time";
+const char pstrUsageFastBlinkOnTime [] PROGMEM = "Fast Blk On Time";
+const char pstrUsageFastBlinkOffTime [] PROGMEM = "Fast Blk Off Time";
+const char pstrUsageIndicatorColor [] PROGMEM = "Usage Ind Color";
+const char pstrUsageIndicatorRed [] PROGMEM = "Ind Red";
+const char pstrUsageIndicatorGreen [] PROGMEM = "Ind Green";
+const char pstrUsageIndicatorAmber [] PROGMEM = "Ind Amber";
+const char pstrUsageGenericIndicator [] PROGMEM = "Gen Ind";
+const char pstrUsageSystemSuspend [] PROGMEM = "Sys Suspend";
+const char pstrUsageExternalPowerConnected [] PROGMEM = "Ext Pwr Conn";
+
+// Telephony Usage Page
+const char pstrUsagePhone [] PROGMEM = "Phone";
+const char pstrUsageAnsweringMachine [] PROGMEM = "Answ Mach";
+const char pstrUsageMessageControls [] PROGMEM = "Msg Ctrls";
+const char pstrUsageHandset [] PROGMEM = "Handset";
+const char pstrUsageHeadset [] PROGMEM = "Headset";
+const char pstrUsageTelephonyKeyPad [] PROGMEM = "Tel Key Pad";
+const char pstrUsageProgrammableButton [] PROGMEM = "Prog Button";
+const char pstrUsageHookSwitch [] PROGMEM = "Hook Sw";
+const char pstrUsageFlash [] PROGMEM = "Flash";
+const char pstrUsageFeature [] PROGMEM = "Feature";
+//const char pstrUsageHold [] PROGMEM = "Hold";
+const char pstrUsageRedial [] PROGMEM = "Redial";
+const char pstrUsageTransfer [] PROGMEM = "Transfer";
+const char pstrUsageDrop [] PROGMEM = "Drop";
+const char pstrUsagePark [] PROGMEM = "Park";
+const char pstrUsageForwardCalls [] PROGMEM = "Fwd Calls";
+const char pstrUsageAlternateFunction [] PROGMEM = "Alt Func";
+const char pstrUsageLine [] PROGMEM = "Line";
+const char pstrUsageSpeakerPhone [] PROGMEM = "Spk Phone";
+//const char pstrUsageConference [] PROGMEM = "Conference";
+const char pstrUsageRingEnable [] PROGMEM = "Ring Enbl";
+const char pstrUsageRingSelect [] PROGMEM = "Ring Sel";
+const char pstrUsagePhoneMute [] PROGMEM = "Phone Mute";
+const char pstrUsageCallerID [] PROGMEM = "Caller ID";
+const char pstrUsageSend [] PROGMEM = "Send";
+const char pstrUsageSpeedDial [] PROGMEM = "Speed Dial";
+const char pstrUsageStoreNumber [] PROGMEM = "Store Num";
+const char pstrUsageRecallNumber [] PROGMEM = "Recall Num";
+const char pstrUsagePhoneDirectory [] PROGMEM = "Phone Dir";
+const char pstrUsageVoiceMail [] PROGMEM = "Voice Mail";
+const char pstrUsageScreenCalls [] PROGMEM = "Screen Calls";
+//const char pstrUsageDoNotDisturb [] PROGMEM = "Do Not Disturb";
+const char pstrUsageMessage [] PROGMEM = "Msg";
+const char pstrUsageAnswerOnOff [] PROGMEM = "Answer On/Off";
+const char pstrUsageInsideDialTone [] PROGMEM = "Inside Dial Tone";
+const char pstrUsageOutsideDialTone [] PROGMEM = "Outside Dial Tone";
+const char pstrUsageInsideRingTone [] PROGMEM = "Inside Ring Tone";
+const char pstrUsageOutsideRingTone [] PROGMEM = "Outside Ring Tone";
+const char pstrUsagePriorityRingTone [] PROGMEM = "Prior Ring Tone";
+const char pstrUsageInsideRingback [] PROGMEM = "Inside Ringback";
+const char pstrUsagePriorityRingback [] PROGMEM = "Priority Ringback";
+const char pstrUsageLineBusyTone [] PROGMEM = "Ln Busy Tone";
+const char pstrUsageReorderTone [] PROGMEM = "Reorder Tone";
+const char pstrUsageCallWaitingTone [] PROGMEM = "Call Wait Tone";
+const char pstrUsageConfirmationTone1 [] PROGMEM = "Cnfrm Tone1";
+const char pstrUsageConfirmationTone2 [] PROGMEM = "Cnfrm Tone2";
+const char pstrUsageTonesOff [] PROGMEM = "Tones Off";
+const char pstrUsageOutsideRingback [] PROGMEM = "Outside Ringback";
+const char pstrUsageRinger [] PROGMEM = "Ringer";
+const char pstrUsagePhoneKey0 [] PROGMEM = "0";
+const char pstrUsagePhoneKey1 [] PROGMEM = "1";
+const char pstrUsagePhoneKey2 [] PROGMEM = "2";
+const char pstrUsagePhoneKey3 [] PROGMEM = "3";
+const char pstrUsagePhoneKey4 [] PROGMEM = "4";
+const char pstrUsagePhoneKey5 [] PROGMEM = "5";
+const char pstrUsagePhoneKey6 [] PROGMEM = "6";
+const char pstrUsagePhoneKey7 [] PROGMEM = "7";
+const char pstrUsagePhoneKey8 [] PROGMEM = "8";
+const char pstrUsagePhoneKey9 [] PROGMEM = "9";
+const char pstrUsagePhoneKeyStar [] PROGMEM = "*";
+const char pstrUsagePhoneKeyPound [] PROGMEM = "#";
+const char pstrUsagePhoneKeyA [] PROGMEM = "A";
+const char pstrUsagePhoneKeyB [] PROGMEM = "B";
+const char pstrUsagePhoneKeyC [] PROGMEM = "C";
+const char pstrUsagePhoneKeyD [] PROGMEM = "D";
+
+// Consumer Usage Page
+const char pstrUsageConsumerControl [] PROGMEM = "Consumer Ctrl";
+const char pstrUsageNumericKeyPad [] PROGMEM = "Num Key Pad";
+//const char pstrUsageProgrammableButton [] PROGMEM = "Prog Btn";
+//const char pstrUsageMicrophone [] PROGMEM = "Mic";
+const char pstrUsageHeadphone [] PROGMEM = "Headphone";
+const char pstrUsageGraphicEqualizer [] PROGMEM = "Graph Eq";
+const char pstrUsagePlus10 [] PROGMEM = "+10";
+const char pstrUsagePlus100 [] PROGMEM = "+100";
+const char pstrUsageAMPM [] PROGMEM = "AM/PM";
+//const char pstrUsagePower [] PROGMEM = "Pwr";
+const char pstrUsageReset [] PROGMEM = "Reset";
+const char pstrUsageSleep [] PROGMEM = "Sleep";
+const char pstrUsageSleepAfter [] PROGMEM = "Sleep After";
+const char pstrUsageSleepMode [] PROGMEM = "Sleep Mode";
+const char pstrUsageIllumination [] PROGMEM = "Illumin";
+const char pstrUsageFunctionButtons [] PROGMEM = "Func Btns";
+const char pstrUsageMenu [] PROGMEM = "Menu";
+const char pstrUsageMenuPick [] PROGMEM = "Menu Pick";
+const char pstrUsageMenuUp [] PROGMEM = "Menu Up";
+const char pstrUsageMenuDown [] PROGMEM = "Menu Down";
+const char pstrUsageMenuLeft [] PROGMEM = "Menu Left";
+const char pstrUsageMenuRight [] PROGMEM = "Menu Right";
+const char pstrUsageMenuEscape [] PROGMEM = "Menu Esc";
+const char pstrUsageMenuValueIncrease [] PROGMEM = "Menu Val Inc";
+const char pstrUsageMenuValueDecrease [] PROGMEM = "Menu Val Dec";
+const char pstrUsageDataOnScreen [] PROGMEM = "Data On Scr";
+const char pstrUsageClosedCaption [] PROGMEM = "Closed Cptn";
+const char pstrUsageClosedCaptionSelect [] PROGMEM = "Closed Cptn Sel";
+const char pstrUsageVCRTV [] PROGMEM = "VCR/TV";
+const char pstrUsageBroadcastMode [] PROGMEM = "Brdcast Mode";
+const char pstrUsageSnapshot [] PROGMEM = "Snapshot";
+const char pstrUsageStill [] PROGMEM = "Still";
+const char pstrUsageSelection [] PROGMEM = "Sel";
+const char pstrUsageAssignSelection [] PROGMEM = "Assign Sel";
+const char pstrUsageModeStep [] PROGMEM = "Mode Step";
+const char pstrUsageRecallLast [] PROGMEM = "Recall Last";
+const char pstrUsageEnterChannel [] PROGMEM = "Entr Channel";
+const char pstrUsageOrderMovie [] PROGMEM = "Ord Movie";
+const char pstrUsageChannel [] PROGMEM = "Channel";
+const char pstrUsageMediaSelection [] PROGMEM = "Med Sel";
+const char pstrUsageMediaSelectComputer [] PROGMEM = "Med Sel Comp";
+const char pstrUsageMediaSelectTV [] PROGMEM = "Med Sel TV";
+const char pstrUsageMediaSelectWWW [] PROGMEM = "Med Sel WWW";
+const char pstrUsageMediaSelectDVD [] PROGMEM = "Med Sel DVD";
+const char pstrUsageMediaSelectTelephone [] PROGMEM = "Med Sel Tel";
+const char pstrUsageMediaSelectProgramGuide [] PROGMEM = "Med Sel PG";
+const char pstrUsageMediaSelectVideoPhone [] PROGMEM = "Med Sel Vid";
+const char pstrUsageMediaSelectGames [] PROGMEM = "Med Sel Games";
+const char pstrUsageMediaSelectMessages [] PROGMEM = "Med Sel Msg";
+const char pstrUsageMediaSelectCD [] PROGMEM = "Med Sel CD";
+const char pstrUsageMediaSelectVCR [] PROGMEM = "Med Sel VCR";
+const char pstrUsageMediaSelectTuner [] PROGMEM = "Med Sel Tuner";
+const char pstrUsageQuit [] PROGMEM = "Quit";
+const char pstrUsageHelp [] PROGMEM = "Help";
+const char pstrUsageMediaSelectTape [] PROGMEM = "Med Sel Tape";
+const char pstrUsageMediaSelectCable [] PROGMEM = "Med Sel Cbl";
+const char pstrUsageMediaSelectSatellite [] PROGMEM = "Med Sel Sat";
+const char pstrUsageMediaSelectSecurity [] PROGMEM = "Med Sel Secur";
+const char pstrUsageMediaSelectHome [] PROGMEM = "Med Sel Home";
+const char pstrUsageMediaSelectCall [] PROGMEM = "Med Sel Call";
+const char pstrUsageChannelIncrement [] PROGMEM = "Ch Inc";
+const char pstrUsageChannelDecrement [] PROGMEM = "Ch Dec";
+const char pstrUsageMediaSelectSAP [] PROGMEM = "Med Sel SAP";
+const char pstrUsageVCRPlus [] PROGMEM = "VCR+";
+const char pstrUsageOnce [] PROGMEM = "Once";
+const char pstrUsageDaily [] PROGMEM = "Daily";
+const char pstrUsageWeekly [] PROGMEM = "Weekly";
+const char pstrUsageMonthly [] PROGMEM = "Monthly";
+//const char pstrUsagePlay [] PROGMEM = "Play";
+//const char pstrUsagePause [] PROGMEM = "Pause";
+//const char pstrUsageRecord [] PROGMEM = "Rec";
+//const char pstrUsageFastForward [] PROGMEM = "FF";
+//const char pstrUsageRewind [] PROGMEM = "Rewind";
+const char pstrUsageScanNextTrack [] PROGMEM = "Next Track";
+const char pstrUsageScanPreviousTrack [] PROGMEM = "Prev Track";
+//const char pstrUsageStop [] PROGMEM = "Stop";
+const char pstrUsageEject [] PROGMEM = "Eject";
+const char pstrUsageRandomPlay [] PROGMEM = "Random";
+const char pstrUsageSelectDisk [] PROGMEM = "Sel Disk";
+const char pstrUsageEnterDisk [] PROGMEM = "Ent Disk";
+//const char pstrUsageRepeat [] PROGMEM = "Repeat";
+const char pstrUsageTracking [] PROGMEM = "Tracking";
+const char pstrUsageTrackNormal [] PROGMEM = "Trk Norm";
+const char pstrUsageSlowTracking [] PROGMEM = "Slow Trk";
+const char pstrUsageFrameForward [] PROGMEM = "Frm Fwd";
+const char pstrUsageFrameBackwards [] PROGMEM = "Frm Back";
+const char pstrUsageMark [] PROGMEM = "Mark";
+const char pstrUsageClearMark [] PROGMEM = "Clr Mark";
+const char pstrUsageRepeatFromMark [] PROGMEM = "Rpt Mark";
+const char pstrUsageReturnToMark [] PROGMEM = "Ret to Mark";
+const char pstrUsageSearchMarkForward [] PROGMEM = "Search Mark Fwd";
+const char pstrUsageSearchMarkBackwards [] PROGMEM = "Search Mark Back";
+const char pstrUsageCounterReset [] PROGMEM = "Counter Reset";
+const char pstrUsageShowCounter [] PROGMEM = "Show Counter";
+const char pstrUsageTrackingIncrement [] PROGMEM = "Track Inc";
+const char pstrUsageTrackingDecrement [] PROGMEM = "Track Dec";
+const char pstrUsageStopEject [] PROGMEM = "Stop/Eject";
+const char pstrUsagePlayPause [] PROGMEM = "Play/Pause";
+const char pstrUsagePlaySkip [] PROGMEM = "Play/Skip";
+const char pstrUsageVolume [] PROGMEM = "Vol";
+const char pstrUsageBalance [] PROGMEM = "Balance";
+//const char pstrUsageMute [] PROGMEM = "Mute";
+const char pstrUsageBass [] PROGMEM = "Bass";
+const char pstrUsageTreble [] PROGMEM = "Treble";
+const char pstrUsageBassBoost [] PROGMEM = "Bass Boost";
+const char pstrUsageSurroundMode [] PROGMEM = "Surround";
+const char pstrUsageLoudness [] PROGMEM = "Loud";
+const char pstrUsageMPX [] PROGMEM = "MPX";
+const char pstrUsageVolumeIncrement [] PROGMEM = "Vol Inc";
+const char pstrUsageVolumeDecrement [] PROGMEM = "Vol Dec";
+const char pstrUsageSpeedSelect [] PROGMEM = "Speed";
+const char pstrUsagePlaybackSpeed [] PROGMEM = "Play Speed";
+const char pstrUsageStandardPlay [] PROGMEM = "Std Play";
+const char pstrUsageLongPlay [] PROGMEM = "Long Play";
+const char pstrUsageExtendedPlay [] PROGMEM = "Ext Play";
+const char pstrUsageSlow [] PROGMEM = "Slow";
+const char pstrUsageFanEnable [] PROGMEM = "Fan Enbl";
+const char pstrUsageFanSpeed [] PROGMEM = "Fan Speed";
+const char pstrUsageLightEnable [] PROGMEM = "Light Enbl";
+const char pstrUsageLightIlluminationLevel [] PROGMEM = "Light Illum Lev";
+const char pstrUsageClimateControlEnable [] PROGMEM = "Climate Enbl";
+const char pstrUsageRoomTemperature [] PROGMEM = "Room Temp";
+const char pstrUsageSecurityEnable [] PROGMEM = "Secur Enbl";
+const char pstrUsageFireAlarm [] PROGMEM = "Fire Alm";
+const char pstrUsagePoliceAlarm [] PROGMEM = "Police Alm";
+const char pstrUsageProximity [] PROGMEM = "Prox";
+const char pstrUsageMotion [] PROGMEM = "Motion";
+const char pstrUsageDuresAlarm [] PROGMEM = "Dures Alm";
+const char pstrUsageHoldupAlarm [] PROGMEM = "Holdup Alm";
+const char pstrUsageMedicalAlarm [] PROGMEM = "Med Alm";
+const char pstrUsageBalanceRight [] PROGMEM = "Balance Right";
+const char pstrUsageBalanceLeft [] PROGMEM = "Balance Left";
+const char pstrUsageBassIncrement [] PROGMEM = "Bass Inc";
+const char pstrUsageBassDecrement [] PROGMEM = "Bass Dec";
+const char pstrUsageTrebleIncrement [] PROGMEM = "Treble Inc";
+const char pstrUsageTrebleDecrement [] PROGMEM = "Treble Dec";
+const char pstrUsageSpeakerSystem [] PROGMEM = "Spk Sys";
+const char pstrUsageChannelLeft [] PROGMEM = "Ch Left";
+const char pstrUsageChannelRight [] PROGMEM = "Ch Right";
+const char pstrUsageChannelCenter [] PROGMEM = "Ch Center";
+const char pstrUsageChannelFront [] PROGMEM = "Ch Front";
+const char pstrUsageChannelCenterFront [] PROGMEM = "Ch Cntr Front";
+const char pstrUsageChannelSide [] PROGMEM = "Ch Side";
+const char pstrUsageChannelSurround [] PROGMEM = "Ch Surround";
+const char pstrUsageChannelLowFreqEnhancement [] PROGMEM = "Ch Low Freq Enh";
+const char pstrUsageChannelTop [] PROGMEM = "Ch Top";
+const char pstrUsageChannelUnknown [] PROGMEM = "Ch Unk";
+const char pstrUsageSubChannel [] PROGMEM = "Sub-ch";
+const char pstrUsageSubChannelIncrement [] PROGMEM = "Sub-ch Inc";
+const char pstrUsageSubChannelDecrement [] PROGMEM = "Sub-ch Dec";
+const char pstrUsageAlternateAudioIncrement [] PROGMEM = "Alt Aud Inc";
+const char pstrUsageAlternateAudioDecrement [] PROGMEM = "Alt Aud Dec";
+const char pstrUsageApplicationLaunchButtons [] PROGMEM = "App Launch Btns";
+const char pstrUsageALLaunchButtonConfigTool [] PROGMEM = "AL Launch Conf Tl";
+const char pstrUsageALProgrammableButton [] PROGMEM = "AL Pgm Btn";
+const char pstrUsageALConsumerControlConfig [] PROGMEM = "AL Cons Ctrl Cfg";
+const char pstrUsageALWordProcessor [] PROGMEM = "AL Word Proc";
+const char pstrUsageALTextEditor [] PROGMEM = "AL Txt Edtr";
+const char pstrUsageALSpreadsheet [] PROGMEM = "AL Sprdsheet";
+const char pstrUsageALGraphicsEditor [] PROGMEM = "AL Graph Edtr";
+const char pstrUsageALPresentationApp [] PROGMEM = "AL Present App";
+const char pstrUsageALDatabaseApp [] PROGMEM = "AL DB App";
+const char pstrUsageALEmailReader [] PROGMEM = "AL E-mail Rdr";
+const char pstrUsageALNewsreader [] PROGMEM = "AL Newsrdr";
+const char pstrUsageALVoicemail [] PROGMEM = "AL Voicemail";
+const char pstrUsageALContactsAddressBook [] PROGMEM = "AL Addr Book";
+const char pstrUsageALCalendarSchedule [] PROGMEM = "AL Clndr/Schdlr";
+const char pstrUsageALTaskProjectManager [] PROGMEM = "AL Task/Prj Mgr";
+const char pstrUsageALLogJournalTimecard [] PROGMEM = "AL Log/Jrnl/Tmcrd";
+const char pstrUsageALCheckbookFinance [] PROGMEM = "AL Chckbook/Fin";
+const char pstrUsageALCalculator [] PROGMEM = "AL Calc";
+const char pstrUsageALAVCapturePlayback [] PROGMEM = "AL A/V Capt/Play";
+const char pstrUsageALLocalMachineBrowser [] PROGMEM = "AL Loc Mach Brow";
+const char pstrUsageALLANWANBrow [] PROGMEM = "AL LAN/WAN Brow";
+const char pstrUsageALInternetBrowser [] PROGMEM = "AL I-net Brow";
+const char pstrUsageALRemoteNetISPConnect [] PROGMEM = "AL Rem Net Con";
+const char pstrUsageALNetworkConference [] PROGMEM = "AL Net Conf";
+const char pstrUsageALNetworkChat [] PROGMEM = "AL Net Chat";
+const char pstrUsageALTelephonyDialer [] PROGMEM = "AL Tel/Dial";
+const char pstrUsageALLogon [] PROGMEM = "AL Logon";
+const char pstrUsageALLogoff [] PROGMEM = "AL Logoff";
+const char pstrUsageALLogonLogoff [] PROGMEM = "AL Logon/Logoff";
+const char pstrUsageALTermLockScrSav [] PROGMEM = "AL Term Lock/Scr Sav";
+const char pstrUsageALControlPannel [] PROGMEM = "AL Ctrl Pan";
+const char pstrUsageALCommandLineProcessorRun [] PROGMEM = "AL Cmd/Run";
+const char pstrUsageALProcessTaskManager [] PROGMEM = "AL Task Mgr";
+const char pstrUsageALSelectTaskApplication [] PROGMEM = "AL Sel App";
+const char pstrUsageALNextTaskApplication [] PROGMEM = "AL Next App";
+const char pstrUsageALPreviousTaskApplication [] PROGMEM = "AL Prev App";
+const char pstrUsageALPreemptiveHaltTaskApp [] PROGMEM = "AL Prmpt Halt App";
+const char pstrUsageALIntegratedHelpCenter [] PROGMEM = "AL Hlp Cntr";
+const char pstrUsageALDocuments [] PROGMEM = "AL Docs";
+const char pstrUsageALThesaurus [] PROGMEM = "AL Thsrs";
+const char pstrUsageALDictionary [] PROGMEM = "AL Dict";
+const char pstrUsageALDesktop [] PROGMEM = "AL Desktop";
+const char pstrUsageALSpellCheck [] PROGMEM = "AL Spell Chk";
+const char pstrUsageALGrammarCheck [] PROGMEM = "AL Gram Chk";
+const char pstrUsageALWirelessStatus [] PROGMEM = "AL Wireless Sts";
+const char pstrUsageALKeyboardLayout [] PROGMEM = "AL Kbd Layout";
+const char pstrUsageALVirusProtection [] PROGMEM = "AL Vir Protect";
+const char pstrUsageALEncryption [] PROGMEM = "AL Encrypt";
+const char pstrUsageALScreenSaver [] PROGMEM = "AL Scr Sav";
+const char pstrUsageALAlarms [] PROGMEM = "AL Alarms";
+const char pstrUsageALClock [] PROGMEM = "AL Clock";
+const char pstrUsageALFileBrowser [] PROGMEM = "AL File Brow";
+const char pstrUsageALPowerStatus [] PROGMEM = "AL Pwr Sts";
+const char pstrUsageALImageBrowser [] PROGMEM = "AL Img Brow";
+const char pstrUsageALAudioBrowser [] PROGMEM = "AL Aud Brow";
+const char pstrUsageALMovieBrowser [] PROGMEM = "AL Mov Brow";
+const char pstrUsageALDigitalRightsManager [] PROGMEM = "AL Dig Rights Mgr";
+const char pstrUsageALDigitalWallet [] PROGMEM = "AL Dig Wallet";
+const char pstrUsageALInstantMessaging [] PROGMEM = "AL Inst Msg";
+const char pstrUsageALOEMFeaturesBrowser [] PROGMEM = "AL OEM Tips Brow";
+const char pstrUsageALOEMHelp [] PROGMEM = "AL OEM Hlp";
+const char pstrUsageALOnlineCommunity [] PROGMEM = "AL Online Com";
+const char pstrUsageALEntertainmentContentBrow [] PROGMEM = "AL Ent Cont Brow";
+const char pstrUsageALOnlineShoppingBrowser [] PROGMEM = "AL Online Shop Brow";
+const char pstrUsageALSmartCardInfoHelp [] PROGMEM = "AL SmartCard Inf";
+const char pstrUsageALMarketMonitorFinBrowser [] PROGMEM = "AL Market Brow";
+const char pstrUsageALCustomCorpNewsBrowser [] PROGMEM = "AL Cust Corp News Brow";
+const char pstrUsageALOnlineActivityBrowser [] PROGMEM = "AL Online Act Brow";
+const char pstrUsageALResearchSearchBrowser [] PROGMEM = "AL Search Brow";
+const char pstrUsageALAudioPlayer [] PROGMEM = "AL Aud Player";
+const char pstrUsageGenericGUIAppControls [] PROGMEM = "Gen GUI App Ctrl";
+const char pstrUsageACNew [] PROGMEM = "AC New";
+const char pstrUsageACOpen [] PROGMEM = "AC Open";
+const char pstrUsageACClose [] PROGMEM = "AC Close";
+const char pstrUsageACExit [] PROGMEM = "AC Exit";
+const char pstrUsageACMaximize [] PROGMEM = "AC Max";
+const char pstrUsageACMinimize [] PROGMEM = "AC Min";
+const char pstrUsageACSave [] PROGMEM = "AC Save";
+const char pstrUsageACPrint [] PROGMEM = "AC Print";
+const char pstrUsageACProperties [] PROGMEM = "AC Prop";
+const char pstrUsageACUndo [] PROGMEM = "AC Undo";
+const char pstrUsageACCopy [] PROGMEM = "AC Copy";
+const char pstrUsageACCut [] PROGMEM = "AC Cut";
+const char pstrUsageACPaste [] PROGMEM = "AC Paste";
+const char pstrUsageACSelectAll [] PROGMEM = "AC Sel All";
+const char pstrUsageACFind [] PROGMEM = "AC Find";
+const char pstrUsageACFindAndReplace [] PROGMEM = "AC Find/Replace";
+const char pstrUsageACSearch [] PROGMEM = "AC Search";
+const char pstrUsageACGoto [] PROGMEM = "AC Goto";
+const char pstrUsageACHome [] PROGMEM = "AC Home";
+const char pstrUsageACBack [] PROGMEM = "AC Back";
+const char pstrUsageACForward [] PROGMEM = "AC Fwd";
+const char pstrUsageACStop [] PROGMEM = "AC Stop";
+const char pstrUsageACRefresh [] PROGMEM = "AC Refresh";
+const char pstrUsageACPreviousLink [] PROGMEM = "AC Prev Link";
+const char pstrUsageACNextLink [] PROGMEM = "AC Next Link";
+const char pstrUsageACBookmarks [] PROGMEM = "AC Bkmarks";
+const char pstrUsageACHistory [] PROGMEM = "AC Hist";
+const char pstrUsageACSubscriptions [] PROGMEM = "AC Subscr";
+const char pstrUsageACZoomIn [] PROGMEM = "AC Zoom In";
+const char pstrUsageACZoomOut [] PROGMEM = "AC Zoom Out";
+const char pstrUsageACZoom [] PROGMEM = "AC Zoom";
+const char pstrUsageACFullScreenView [] PROGMEM = "AC Full Scr";
+const char pstrUsageACNormalView [] PROGMEM = "AC Norm View";
+const char pstrUsageACViewToggle [] PROGMEM = "AC View Tgl";
+const char pstrUsageACScrollUp [] PROGMEM = "AC Scroll Up";
+const char pstrUsageACScrollDown [] PROGMEM = "AC Scroll Down";
+const char pstrUsageACScroll [] PROGMEM = "AC Scroll";
+const char pstrUsageACPanLeft [] PROGMEM = "AC Pan Left";
+const char pstrUsageACPanRight [] PROGMEM = "AC Pan Right";
+const char pstrUsageACPan [] PROGMEM = "AC Pan";
+const char pstrUsageACNewWindow [] PROGMEM = "AC New Wnd";
+const char pstrUsageACTileHoriz [] PROGMEM = "AC Tile Horiz";
+const char pstrUsageACTileVert [] PROGMEM = "AC Tile Vert";
+const char pstrUsageACFormat [] PROGMEM = "AC Frmt";
+const char pstrUsageACEdit [] PROGMEM = "AC Edit";
+const char pstrUsageACBold [] PROGMEM = "AC Bold";
+const char pstrUsageACItalics [] PROGMEM = "AC Ital";
+const char pstrUsageACUnderline [] PROGMEM = "AC Under";
+const char pstrUsageACStrikethrough [] PROGMEM = "AC Strike";
+const char pstrUsageACSubscript [] PROGMEM = "AC Sub";
+const char pstrUsageACSuperscript [] PROGMEM = "AC Super";
+const char pstrUsageACAllCaps [] PROGMEM = "AC All Caps";
+const char pstrUsageACRotate [] PROGMEM = "AC Rotate";
+const char pstrUsageACResize [] PROGMEM = "AC Resize";
+const char pstrUsageACFlipHorizontal [] PROGMEM = "AC Flp H";
+const char pstrUsageACFlipVertical [] PROGMEM = "AC Flp V";
+const char pstrUsageACMirrorHorizontal [] PROGMEM = "AC Mir H";
+const char pstrUsageACMirrorVertical [] PROGMEM = "AC Mir V";
+const char pstrUsageACFontSelect [] PROGMEM = "AC Fnt Sel";
+const char pstrUsageACFontColor [] PROGMEM = "AC Fnt Clr";
+const char pstrUsageACFontSize [] PROGMEM = "AC Fnt Size";
+const char pstrUsageACJustifyLeft [] PROGMEM = "AC Just Left";
+const char pstrUsageACJustifyCenterH [] PROGMEM = "AC Just Cent H";
+const char pstrUsageACJustifyRight [] PROGMEM = "AC Just Right";
+const char pstrUsageACJustifyBlockH [] PROGMEM = "AC Just Block H";
+const char pstrUsageACJustifyTop [] PROGMEM = "AC Just Top";
+const char pstrUsageACJustifyCenterV [] PROGMEM = "AC Just Cent V";
+const char pstrUsageACJustifyBottom [] PROGMEM = "AC Just Bot";
+const char pstrUsageACJustifyBlockV [] PROGMEM = "AC Just Block V";
+const char pstrUsageACIndentDecrease [] PROGMEM = "AC Indent Dec";
+const char pstrUsageACIndentIncrease [] PROGMEM = "AC Indent Inc";
+const char pstrUsageACNumberedList [] PROGMEM = "AC Num List";
+const char pstrUsageACRestartNumbering [] PROGMEM = "AC Res Num";
+const char pstrUsageACBulletedList [] PROGMEM = "AC Blt List";
+const char pstrUsageACPromote [] PROGMEM = "AC Promote";
+const char pstrUsageACDemote [] PROGMEM = "AC Demote";
+const char pstrUsageACYes [] PROGMEM = "AC Yes";
+const char pstrUsageACNo [] PROGMEM = "AC No";
+const char pstrUsageACCancel [] PROGMEM = "AC Cancel";
+const char pstrUsageACCatalog [] PROGMEM = "AC Ctlg";
+const char pstrUsageACBuyChkout [] PROGMEM = "AC Buy";
+const char pstrUsageACAddToCart [] PROGMEM = "AC Add2Cart";
+const char pstrUsageACExpand [] PROGMEM = "AC Xpnd";
+const char pstrUsageACExpandAll [] PROGMEM = "AC Xpand All";
+const char pstrUsageACCollapse [] PROGMEM = "AC Collapse";
+const char pstrUsageACCollapseAll [] PROGMEM = "AC Collapse All";
+const char pstrUsageACPrintPreview [] PROGMEM = "AC Prn Prevw";
+const char pstrUsageACPasteSpecial [] PROGMEM = "AC Paste Spec";
+const char pstrUsageACInsertMode [] PROGMEM = "AC Ins Mode";
+const char pstrUsageACDelete [] PROGMEM = "AC Del";
+const char pstrUsageACLock [] PROGMEM = "AC Lock";
+const char pstrUsageACUnlock [] PROGMEM = "AC Unlock";
+const char pstrUsageACProtect [] PROGMEM = "AC Prot";
+const char pstrUsageACUnprotect [] PROGMEM = "AC Unprot";
+const char pstrUsageACAttachComment [] PROGMEM = "AC Attach Cmnt";
+const char pstrUsageACDeleteComment [] PROGMEM = "AC Del Cmnt";
+const char pstrUsageACViewComment [] PROGMEM = "AC View Cmnt";
+const char pstrUsageACSelectWord [] PROGMEM = "AC Sel Word";
+const char pstrUsageACSelectSentence [] PROGMEM = "AC Sel Sntc";
+const char pstrUsageACSelectParagraph [] PROGMEM = "AC Sel Para";
+const char pstrUsageACSelectColumn [] PROGMEM = "AC Sel Col";
+const char pstrUsageACSelectRow [] PROGMEM = "AC Sel Row";
+const char pstrUsageACSelectTable [] PROGMEM = "AC Sel Tbl";
+const char pstrUsageACSelectObject [] PROGMEM = "AC Sel Obj";
+const char pstrUsageACRedoRepeat [] PROGMEM = "AC Redo";
+const char pstrUsageACSort [] PROGMEM = "AC Sort";
+const char pstrUsageACSortAscending [] PROGMEM = "AC Sort Asc";
+const char pstrUsageACSortDescending [] PROGMEM = "AC Sort Desc";
+const char pstrUsageACFilter [] PROGMEM = "AC Filt";
+const char pstrUsageACSetClock [] PROGMEM = "AC Set Clk";
+const char pstrUsageACViewClock [] PROGMEM = "AC View Clk";
+const char pstrUsageACSelectTimeZone [] PROGMEM = "AC Sel Time Z";
+const char pstrUsageACEditTimeZone [] PROGMEM = "AC Edt Time Z";
+const char pstrUsageACSetAlarm [] PROGMEM = "AC Set Alm";
+const char pstrUsageACClearAlarm [] PROGMEM = "AC Clr Alm";
+const char pstrUsageACSnoozeAlarm [] PROGMEM = "AC Snz Alm";
+const char pstrUsageACResetAlarm [] PROGMEM = "AC Rst Alm";
+const char pstrUsageACSyncronize [] PROGMEM = "AC Sync";
+const char pstrUsageACSendReceive [] PROGMEM = "AC Snd/Rcv";
+const char pstrUsageACSendTo [] PROGMEM = "AC Snd To";
+const char pstrUsageACReply [] PROGMEM = "AC Reply";
+const char pstrUsageACReplyAll [] PROGMEM = "AC Reply All";
+const char pstrUsageACForwardMessage [] PROGMEM = "AC Fwd Msg";
+const char pstrUsageACSend [] PROGMEM = "AC Snd";
+const char pstrUsageACAttachFile [] PROGMEM = "AC Att File";
+const char pstrUsageACUpload [] PROGMEM = "AC Upld";
+const char pstrUsageACDownload [] PROGMEM = "AC Dnld";
+const char pstrUsageACSetBorders [] PROGMEM = "AC Set Brd";
+const char pstrUsageACInsertRow [] PROGMEM = "AC Ins Row";
+const char pstrUsageACInsertColumn [] PROGMEM = "AC Ins Col";
+const char pstrUsageACInsertFile [] PROGMEM = "AC Ins File";
+const char pstrUsageACInsertPicture [] PROGMEM = "AC Ins Pic";
+const char pstrUsageACInsertObject [] PROGMEM = "AC Ins Obj";
+const char pstrUsageACInsertSymbol [] PROGMEM = "AC Ins Sym";
+const char pstrUsageACSaveAndClose [] PROGMEM = "AC Sav&Cls";
+const char pstrUsageACRename [] PROGMEM = "AC Rename";
+const char pstrUsageACMerge [] PROGMEM = "AC Merge";
+const char pstrUsageACSplit [] PROGMEM = "AC Split";
+const char pstrUsageACDistributeHorizontaly [] PROGMEM = "AC Dist Hor";
+const char pstrUsageACDistributeVerticaly [] PROGMEM = "AC Dist Ver";
+
+// Digitaizers
+const char pstrUsageDigitizer [] PROGMEM = "Digitizer";
+const char pstrUsagePen [] PROGMEM = "Pen";
+const char pstrUsageLightPen [] PROGMEM = "Light Pen";
+const char pstrUsageTouchScreen [] PROGMEM = "Touch Scr";
+const char pstrUsageTouchPad [] PROGMEM = "Touch Pad";
+const char pstrUsageWhiteBoard [] PROGMEM = "White Brd";
+const char pstrUsageCoordinateMeasuringMachine [] PROGMEM = "Coord Meas Mach";
+const char pstrUsage3DDigitizer [] PROGMEM = "3D Dgtz";
+const char pstrUsageStereoPlotter [] PROGMEM = "Stereo Plot";
+const char pstrUsageArticulatedArm [] PROGMEM = "Art Arm";
+const char pstrUsageArmature [] PROGMEM = "Armature";
+const char pstrUsageMultiplePointDigitizer [] PROGMEM = "Multi Point Dgtz";
+const char pstrUsageFreeSpaceWand [] PROGMEM = "Free Space Wand";
+const char pstrUsageStylus [] PROGMEM = "Stylus";
+const char pstrUsagePuck [] PROGMEM = "Puck";
+const char pstrUsageFinger [] PROGMEM = "Finger";
+const char pstrUsageTipPressure [] PROGMEM = "Tip Press";
+const char pstrUsageBarrelPressure [] PROGMEM = "Brl Press";
+const char pstrUsageInRange [] PROGMEM = "In Range";
+const char pstrUsageTouch [] PROGMEM = "Touch";
+const char pstrUsageUntouch [] PROGMEM = "Untouch";
+const char pstrUsageTap [] PROGMEM = "Tap";
+const char pstrUsageQuality [] PROGMEM = "Qlty";
+const char pstrUsageDataValid [] PROGMEM = "Data Valid";
+const char pstrUsageTransducerIndex [] PROGMEM = "Transducer Ind";
+const char pstrUsageTabletFunctionKeys [] PROGMEM = "Tabl Func Keys";
+const char pstrUsageProgramChangeKeys [] PROGMEM = "Pgm Chng Keys";
+//const char pstrUsageBatteryStrength [] PROGMEM = "Bat Strength";
+const char pstrUsageInvert [] PROGMEM = "Invert";
+const char pstrUsageXTilt [] PROGMEM = "X Tilt";
+const char pstrUsageYTilt [] PROGMEM = "Y Tilt";
+const char pstrUsageAzimuth [] PROGMEM = "Azimuth";
+const char pstrUsageAltitude [] PROGMEM = "Altitude";
+const char pstrUsageTwist [] PROGMEM = "Twist";
+const char pstrUsageTipSwitch [] PROGMEM = "Tip Sw";
+const char pstrUsageSecondaryTipSwitch [] PROGMEM = "Scnd Tip Sw";
+const char pstrUsageBarrelSwitch [] PROGMEM = "Brl Sw";
+const char pstrUsageEraser [] PROGMEM = "Eraser";
+const char pstrUsageTabletPick [] PROGMEM = "Tbl Pick";
+
+// Alphanumeric Display Page
+const char pstrUsageAlphanumericDisplay [] PROGMEM = "Alphanum Disp";
+const char pstrUsageBitmappedDisplay [] PROGMEM = "Bmp Disp";
+const char pstrUsageDisplayAttributesReport [] PROGMEM = "Disp Attr Rpt";
+const char pstrUsageASCIICharacterSet [] PROGMEM = "ASCII chset";
+const char pstrUsageDataReadBack [] PROGMEM = "Data Rd Back";
+const char pstrUsageFontReadBack [] PROGMEM = "Fnt Rd Back";
+const char pstrUsageDisplayControlReport [] PROGMEM = "Disp Ctrl Rpt";
+const char pstrUsageClearDisplay [] PROGMEM = "Clr Disp";
+//const char pstrUsageDisplayEnable [] PROGMEM = "Disp Enbl";
+const char pstrUsageScreenSaverDelay [] PROGMEM = "Scr Sav Delay";
+const char pstrUsageScreenSaverEnable [] PROGMEM = "Scr Sav Enbl";
+const char pstrUsageVerticalScroll [] PROGMEM = "V Scroll";
+const char pstrUsageHorizontalScroll [] PROGMEM = "H Scroll";
+const char pstrUsageCharacterReport [] PROGMEM = "Char Rpt";
+const char pstrUsageDisplayData [] PROGMEM = "Disp Data";
+const char pstrUsageDisplayStatus [] PROGMEM = "Disp Stat";
+const char pstrUsageStatusNotReady [] PROGMEM = "Stat !Ready";
+const char pstrUsageStatusReady [] PROGMEM = "Stat Ready";
+const char pstrUsageErrorNotALoadableCharacter [] PROGMEM = "Err Not Ld Char";
+const char pstrUsageErrorFotDataCanNotBeRead [] PROGMEM = "Fnt Data Rd Err";
+const char pstrUsageCursorPositionReport [] PROGMEM = "Cur Pos Rpt";
+const char pstrUsageRow [] PROGMEM = "Row";
+const char pstrUsageColumn [] PROGMEM = "Col";
+const char pstrUsageRows [] PROGMEM = "Rows";
+const char pstrUsageColumns [] PROGMEM = "Cols";
+const char pstrUsageCursorPixelPosition [] PROGMEM = "Cur Pix Pos";
+const char pstrUsageCursorMode [] PROGMEM = "Cur Mode";
+const char pstrUsageCursorEnable [] PROGMEM = "Cur Enbl";
+const char pstrUsageCursorBlink [] PROGMEM = "Cur Blnk";
+const char pstrUsageFontReport [] PROGMEM = "Fnt Rpt";
+const char pstrUsageFontData [] PROGMEM = "Fnt Data";
+const char pstrUsageCharacterWidth [] PROGMEM = "Char Wdth";
+const char pstrUsageCharacterHeight [] PROGMEM = "Char Hght";
+const char pstrUsageCharacterSpacingHorizontal [] PROGMEM = "Char Space H";
+const char pstrUsageCharacterSpacingVertical [] PROGMEM = "Char Space V";
+const char pstrUsageUnicodeCharset [] PROGMEM = "Unicode Char";
+const char pstrUsageFont7Segment [] PROGMEM = "Fnt 7-seg";
+const char pstrUsage7SegmentDirectMap [] PROGMEM = "7-seg map";
+const char pstrUsageFont14Segment [] PROGMEM = "Fnt 14-seg";
+const char pstrUsage14SegmentDirectMap [] PROGMEM = "14-seg map";
+const char pstrUsageDisplayBrightness [] PROGMEM = "Disp Bright";
+const char pstrUsageDisplayContrast [] PROGMEM = "Disp Cntrst";
+const char pstrUsageCharacterAttribute [] PROGMEM = "Char Attr";
+const char pstrUsageAttributeReadback [] PROGMEM = "Attr Readbk";
+const char pstrUsageAttributeData [] PROGMEM = "Attr Data";
+const char pstrUsageCharAttributeEnhance [] PROGMEM = "Char Attr Enh";
+const char pstrUsageCharAttributeUnderline [] PROGMEM = "Char Attr Undl";
+const char pstrUsageCharAttributeBlink [] PROGMEM = "Char Attr Blnk";
+const char pstrUsageBitmapSizeX [] PROGMEM = "Bmp Size X";
+const char pstrUsageBitmapSizeY [] PROGMEM = "Bmp Size Y";
+const char pstrUsageBitDepthFormat [] PROGMEM = "Bit Dpth Fmt";
+const char pstrUsageDisplayOrientation [] PROGMEM = "Disp Ornt";
+const char pstrUsagePaletteReport [] PROGMEM = "Pal Rpt";
+const char pstrUsagePaletteDataSize [] PROGMEM = "Pal Data Size";
+const char pstrUsagePaletteDataOffset [] PROGMEM = "Pal Data Off";
+const char pstrUsagePaletteData [] PROGMEM = "Pal Data";
+const char pstrUsageBlitReport [] PROGMEM = "Blit Rpt";
+const char pstrUsageBlitRectangleX1 [] PROGMEM = "Blit Rect X1";
+const char pstrUsageBlitRectangleY1 [] PROGMEM = "Blit Rect Y1";
+const char pstrUsageBlitRectangleX2 [] PROGMEM = "Blit Rect X2";
+const char pstrUsageBlitRectangleY2 [] PROGMEM = "Blit Rect Y2";
+const char pstrUsageBlitData [] PROGMEM = "Blit Data";
+const char pstrUsageSoftButton [] PROGMEM = "Soft Btn";
+const char pstrUsageSoftButtonID [] PROGMEM = "Soft Btn ID";
+const char pstrUsageSoftButtonSide [] PROGMEM = "Soft Btn Side";
+const char pstrUsageSoftButtonOffset1 [] PROGMEM = "Soft Btn Off1";
+const char pstrUsageSoftButtonOffset2 [] PROGMEM = "Soft Btn Off2";
+const char pstrUsageSoftButtonReport [] PROGMEM = "Soft Btn Rpt";
+
+// Medical Instrument Page
+const char pstrUsageMedicalUltrasound [] PROGMEM = "Med Ultrasnd";
+const char pstrUsageVCRAcquisition [] PROGMEM = "VCR/Acq";
+const char pstrUsageFreezeThaw [] PROGMEM = "Freeze";
+const char pstrUsageClipStore [] PROGMEM = "Clip Store";
+const char pstrUsageUpdate [] PROGMEM = "Update";
+const char pstrUsageNext [] PROGMEM = "Next";
+const char pstrUsageSave [] PROGMEM = "Save";
+const char pstrUsagePrint [] PROGMEM = "Print";
+const char pstrUsageMicrophoneEnable [] PROGMEM = "Mic Enbl";
+const char pstrUsageCine [] PROGMEM = "Cine";
+const char pstrUsageTransmitPower [] PROGMEM = "Trans Pwr";
+//const char pstrUsageVolume [] PROGMEM = "Vol";
+const char pstrUsageFocus [] PROGMEM = "Focus";
+const char pstrUsageDepth [] PROGMEM = "Depth";
+const char pstrUsageSoftStepPrimary [] PROGMEM = "Soft Stp-Pri";
+const char pstrUsageSoftStepSecondary [] PROGMEM = "Soft Stp-Sec";
+const char pstrUsageDepthGainCompensation [] PROGMEM = "Dpth Gain Comp";
+const char pstrUsageZoomSelect [] PROGMEM = "Zoom Sel";
+const char pstrUsageZoomAdjust [] PROGMEM = "Zoom Adj";
+const char pstrUsageSpectralDopplerModeSelect [] PROGMEM = "Spec Dop Mode Sel";
+const char pstrUsageSpectralDopplerModeAdjust [] PROGMEM = "Spec Dop Mode Adj";
+const char pstrUsageColorDopplerModeSelect [] PROGMEM = "Color Dop Mode Sel";
+const char pstrUsageColorDopplerModeAdjust [] PROGMEM = "Color Dop Mode Adj";
+const char pstrUsageMotionModeSelect [] PROGMEM = "Motion Mode Sel";
+const char pstrUsageMotionModeAdjust [] PROGMEM = "Motion Mode Adj";
+const char pstrUsage2DModeSelect [] PROGMEM = "2D Mode Sel";
+const char pstrUsage2DModeAdjust [] PROGMEM = "2D Mode Adj";
+const char pstrUsageSoftControlSelect [] PROGMEM = "Soft Ctrl Sel";
+const char pstrUsageSoftControlAdjust [] PROGMEM = "Soft Ctrl Adj";
+
+//extern const char *usagePageTitles0[15];
+//const char *usagePageTitles1[];
+//const char *genDesktopTitles0[];
+//const char *genDesktopTitles1[];
+//const char *genDesktopTitles2[];
+//const char *genDesktopTitles3[];
+//const char *genDesktopTitles4[];
+//const char *simuTitles0[];
+//const char *simuTitles1[];
+//const char *simuTitles2[];
+//const char *vrTitles0[];
+//const char *vrTitles1[];
+//const char *sportsCtrlTitles0[];
+//const char *sportsCtrlTitles1[];
+//const char *sportsCtrlTitles2[];
+//const char *gameTitles0[];
+//const char *gameTitles1[];
+//const char *genDevCtrlTitles[];
+//const char *ledTitles[];
+//const char *telTitles0[];
+//const char *telTitles1[];
+//const char *telTitles2[];
+//const char *telTitles3[];
+//const char *telTitles4[];
+//const char *telTitles5[];
+//const char *consTitles0[];
+//const char *consTitles1[];
+//const char *consTitles2[];
+//const char *consTitles3[];
+//const char *consTitles4[];
+//const char *consTitles5[];
+//const char *consTitles6[];
+//const char *consTitles7[];
+//const char *consTitles8[];
+//const char *consTitles9[];
+//const char *consTitlesA[];
+//const char *consTitlesB[];
+//const char *consTitlesC[];
+//const char *consTitlesD[];
+//const char *consTitlesE[];
+//const char *digitTitles0[];
+//const char *digitTitles1[];
+//const char *digitTitles2[];
+//const char *aplphanumTitles0[];
+//const char *aplphanumTitles1[];
+//const char *aplphanumTitles2[];
+//const char *medInstrTitles0[];
+//const char *medInstrTitles1[];
+//const char *medInstrTitles2[];
+//const char *medInstrTitles3[];
+//const char *medInstrTitles4[];
+
+#endif //__HIDUSAGESTR_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidusagetitlearrays.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidusagetitlearrays.cpp
new file mode 100644
index 000000000..ee233002c
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/hidusagetitlearrays.cpp
@@ -0,0 +1,1048 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__HIDUSAGETITLEARRAYS_H__)
+#define __HIDUSAGETITLEARRAYS_H__
+
+#include "hidusagestr.h"
+
+// This is here why?
+
+//const char *usagePageTitles0[] PROGMEM =
+//{
+// pstrUsagePageGenericDesktopControls ,
+// pstrUsagePageSimulationControls ,
+// pstrUsagePageVRControls ,
+// pstrUsagePageSportControls ,
+// pstrUsagePageGameControls ,
+// pstrUsagePageGenericDeviceControls ,
+// pstrUsagePageKeyboardKeypad ,
+// pstrUsagePageLEDs ,
+// pstrUsagePageButton ,
+// pstrUsagePageOrdinal ,
+// pstrUsagePageTelephone ,
+// pstrUsagePageConsumer ,
+// pstrUsagePageDigitizer ,
+// pstrUsagePagePID ,
+// pstrUsagePageUnicode
+//};
+//
+//const char *usagePageTitles1[] PROGMEM =
+//{
+// pstrUsagePageBarCodeScanner ,
+// pstrUsagePageScale ,
+// pstrUsagePageMSRDevices ,
+// pstrUsagePagePointOfSale ,
+// pstrUsagePageCameraControl ,
+// pstrUsagePageArcade
+//};
+//const char *genDesktopTitles0[] PROGMEM =
+//{
+// pstrUsagePointer ,
+// pstrUsageMouse ,
+// pstrUsageJoystick ,
+// pstrUsageGamePad ,
+// pstrUsageKeyboard ,
+// pstrUsageKeypad ,
+// pstrUsageMultiAxisController ,
+// pstrUsageTabletPCSystemControls
+//
+//};
+//const char *genDesktopTitles1[] PROGMEM =
+//{
+// pstrUsageX ,
+// pstrUsageY ,
+// pstrUsageZ ,
+// pstrUsageRx ,
+// pstrUsageRy ,
+// pstrUsageRz ,
+// pstrUsageSlider ,
+// pstrUsageDial ,
+// pstrUsageWheel ,
+// pstrUsageHatSwitch ,
+// pstrUsageCountedBuffer ,
+// pstrUsageByteCount ,
+// pstrUsageMotionWakeup ,
+// pstrUsageStart ,
+// pstrUsageSelect ,
+// pstrUsagePageReserved ,
+// pstrUsageVx ,
+// pstrUsageVy ,
+// pstrUsageVz ,
+// pstrUsageVbrx ,
+// pstrUsageVbry ,
+// pstrUsageVbrz ,
+// pstrUsageVno ,
+// pstrUsageFeatureNotification ,
+// pstrUsageResolutionMultiplier
+//};
+//const char *genDesktopTitles2[] PROGMEM =
+//{
+// pstrUsageSystemControl ,
+// pstrUsageSystemPowerDown ,
+// pstrUsageSystemSleep ,
+// pstrUsageSystemWakeup ,
+// pstrUsageSystemContextMenu ,
+// pstrUsageSystemMainMenu ,
+// pstrUsageSystemAppMenu ,
+// pstrUsageSystemMenuHelp ,
+// pstrUsageSystemMenuExit ,
+// pstrUsageSystemMenuSelect ,
+// pstrUsageSystemMenuRight ,
+// pstrUsageSystemMenuLeft ,
+// pstrUsageSystemMenuUp ,
+// pstrUsageSystemMenuDown ,
+// pstrUsageSystemColdRestart ,
+// pstrUsageSystemWarmRestart ,
+// pstrUsageDPadUp ,
+// pstrUsageDPadDown ,
+// pstrUsageDPadRight ,
+// pstrUsageDPadLeft
+//};
+//const char *genDesktopTitles3[] PROGMEM =
+//{
+// pstrUsageSystemDock ,
+// pstrUsageSystemUndock ,
+// pstrUsageSystemSetup ,
+// pstrUsageSystemBreak ,
+// pstrUsageSystemDebuggerBreak ,
+// pstrUsageApplicationBreak ,
+// pstrUsageApplicationDebuggerBreak,
+// pstrUsageSystemSpeakerMute ,
+// pstrUsageSystemHibernate
+//};
+//const char *genDesktopTitles4[] PROGMEM =
+//{
+// pstrUsageSystemDisplayInvert ,
+// pstrUsageSystemDisplayInternal ,
+// pstrUsageSystemDisplayExternal ,
+// pstrUsageSystemDisplayBoth ,
+// pstrUsageSystemDisplayDual ,
+// pstrUsageSystemDisplayToggleIntExt ,
+// pstrUsageSystemDisplaySwapPriSec ,
+// pstrUsageSystemDisplayLCDAutoscale
+//};
+//const char *simuTitles0[] PROGMEM =
+//{
+// pstrUsageFlightSimulationDevice ,
+// pstrUsageAutomobileSimulationDevice ,
+// pstrUsageTankSimulationDevice ,
+// pstrUsageSpaceshipSimulationDevice ,
+// pstrUsageSubmarineSimulationDevice ,
+// pstrUsageSailingSimulationDevice ,
+// pstrUsageMotocicleSimulationDevice ,
+// pstrUsageSportsSimulationDevice ,
+// pstrUsageAirplaneSimulationDevice ,
+// pstrUsageHelicopterSimulationDevice ,
+// pstrUsageMagicCarpetSimulationDevice,
+// pstrUsageBicycleSimulationDevice
+//};
+//const char *simuTitles1[] PROGMEM =
+//{
+// pstrUsageFlightControlStick ,
+// pstrUsageFlightStick ,
+// pstrUsageCyclicControl ,
+// pstrUsageCyclicTrim ,
+// pstrUsageFlightYoke ,
+// pstrUsageTrackControl
+//};
+//const char *simuTitles2[] PROGMEM =
+//{
+// pstrUsageAileron ,
+// pstrUsageAileronTrim ,
+// pstrUsageAntiTorqueControl ,
+// pstrUsageAutopilotEnable ,
+// pstrUsageChaffRelease ,
+// pstrUsageCollectiveControl ,
+// pstrUsageDiveBrake ,
+// pstrUsageElectronicCountermeasures ,
+// pstrUsageElevator ,
+// pstrUsageElevatorTrim ,
+// pstrUsageRudder ,
+// pstrUsageThrottle ,
+// pstrUsageFlightCommunications ,
+// pstrUsageFlareRelease ,
+// pstrUsageLandingGear ,
+// pstrUsageToeBrake ,
+// pstrUsageTrigger ,
+// pstrUsageWeaponsArm ,
+// pstrUsageWeaponsSelect ,
+// pstrUsageWingFlaps ,
+// pstrUsageAccelerator ,
+// pstrUsageBrake ,
+// pstrUsageClutch ,
+// pstrUsageShifter ,
+// pstrUsageSteering ,
+// pstrUsageTurretDirection ,
+// pstrUsageBarrelElevation ,
+// pstrUsageDivePlane ,
+// pstrUsageBallast ,
+// pstrUsageBicycleCrank ,
+// pstrUsageHandleBars ,
+// pstrUsageFrontBrake ,
+// pstrUsageRearBrake
+//};
+//const char *vrTitles0[] PROGMEM =
+//{
+// pstrUsageBelt ,
+// pstrUsageBodySuit ,
+// pstrUsageFlexor ,
+// pstrUsageGlove ,
+// pstrUsageHeadTracker ,
+// pstrUsageHeadMountedDisplay ,
+// pstrUsageHandTracker ,
+// pstrUsageOculometer ,
+// pstrUsageVest ,
+// pstrUsageAnimatronicDevice
+//};
+//const char *vrTitles1[] PROGMEM =
+//{
+// pstrUsageStereoEnable ,
+// pstrUsageDisplayEnable
+//};
+//const char *sportsCtrlTitles0[] PROGMEM =
+//{
+// pstrUsageBaseballBat ,
+// pstrUsageGolfClub ,
+// pstrUsageRowingMachine ,
+// pstrUsageTreadmill
+//};
+//const char *sportsCtrlTitles1[] PROGMEM =
+//{
+// pstrUsageOar ,
+// pstrUsageSlope ,
+// pstrUsageRate ,
+// pstrUsageStickSpeed ,
+// pstrUsageStickFaceAngle ,
+// pstrUsageStickHeelToe ,
+// pstrUsageStickFollowThough ,
+// pstrUsageStickTempo ,
+// pstrUsageStickType ,
+// pstrUsageStickHeight
+//};
+//const char *sportsCtrlTitles2[] PROGMEM =
+//{
+// pstrUsagePutter ,
+// pstrUsage1Iron ,
+// pstrUsage2Iron ,
+// pstrUsage3Iron ,
+// pstrUsage4Iron ,
+// pstrUsage5Iron ,
+// pstrUsage6Iron ,
+// pstrUsage7Iron ,
+// pstrUsage8Iron ,
+// pstrUsage9Iron ,
+// pstrUsage10Iron ,
+// pstrUsage11Iron ,
+// pstrUsageSandWedge ,
+// pstrUsageLoftWedge ,
+// pstrUsagePowerWedge ,
+// pstrUsage1Wood ,
+// pstrUsage3Wood ,
+// pstrUsage5Wood ,
+// pstrUsage7Wood ,
+// pstrUsage9Wood
+//};
+//const char *gameTitles0[] PROGMEM =
+//{
+// pstrUsage3DGameController ,
+// pstrUsagePinballDevice ,
+// pstrUsageGunDevice
+//};
+//const char *gameTitles1[] PROGMEM =
+//{
+// pstrUsagePointOfView ,
+// pstrUsageTurnRightLeft ,
+// pstrUsagePitchForwardBackward ,
+// pstrUsageRollRightLeft ,
+// pstrUsageMoveRightLeft ,
+// pstrUsageMoveForwardBackward ,
+// pstrUsageMoveUpDown ,
+// pstrUsageLeanRightLeft ,
+// pstrUsageLeanForwardBackward ,
+// pstrUsageHeightOfPOV ,
+// pstrUsageFlipper ,
+// pstrUsageSecondaryFlipper ,
+// pstrUsageBump ,
+// pstrUsageNewGame ,
+// pstrUsageShootBall ,
+// pstrUsagePlayer ,
+// pstrUsageGunBolt ,
+// pstrUsageGunClip ,
+// pstrUsageGunSelector ,
+// pstrUsageGunSingleShot ,
+// pstrUsageGunBurst ,
+// pstrUsageGunAutomatic ,
+// pstrUsageGunSafety ,
+// pstrUsageGamepadFireJump ,
+// pstrUsageGamepadTrigger
+//};
+//const char *genDevCtrlTitles[] PROGMEM =
+//{
+// pstrUsageBatteryStrength,
+// pstrUsageWirelessChannel,
+// pstrUsageWirelessID,
+// pstrUsageDiscoverWirelessControl,
+// pstrUsageSecurityCodeCharEntered,
+// pstrUsageSecurityCodeCharErased,
+// pstrUsageSecurityCodeCleared
+//};
+//const char *ledTitles[] PROGMEM =
+//{
+// pstrUsageNumLock ,
+// pstrUsageCapsLock ,
+// pstrUsageScrollLock ,
+// pstrUsageCompose ,
+// pstrUsageKana ,
+// pstrUsagePower ,
+// pstrUsageShift ,
+// pstrUsageDoNotDisturb ,
+// pstrUsageMute ,
+// pstrUsageToneEnable ,
+// pstrUsageHighCutFilter ,
+// pstrUsageLowCutFilter ,
+// pstrUsageEqualizerEnable ,
+// pstrUsageSoundFieldOn ,
+// pstrUsageSurroundOn ,
+// pstrUsageRepeat ,
+// pstrUsageStereo ,
+// pstrUsageSamplingRateDetect ,
+// pstrUsageSpinning ,
+// pstrUsageCAV ,
+// pstrUsageCLV ,
+// pstrUsageRecordingFormatDetect ,
+// pstrUsageOffHook ,
+// pstrUsageRing ,
+// pstrUsageMessageWaiting ,
+// pstrUsageDataMode ,
+// pstrUsageBatteryOperation ,
+// pstrUsageBatteryOK ,
+// pstrUsageBatteryLow ,
+// pstrUsageSpeaker ,
+// pstrUsageHeadSet ,
+// pstrUsageHold ,
+// pstrUsageMicrophone ,
+// pstrUsageCoverage ,
+// pstrUsageNightMode ,
+// pstrUsageSendCalls ,
+// pstrUsageCallPickup ,
+// pstrUsageConference ,
+// pstrUsageStandBy ,
+// pstrUsageCameraOn ,
+// pstrUsageCameraOff ,
+// pstrUsageOnLine ,
+// pstrUsageOffLine ,
+// pstrUsageBusy ,
+// pstrUsageReady ,
+// pstrUsagePaperOut ,
+// pstrUsagePaperJam ,
+// pstrUsageRemote ,
+// pstrUsageForward ,
+// pstrUsageReverse ,
+// pstrUsageStop ,
+// pstrUsageRewind ,
+// pstrUsageFastForward ,
+// pstrUsagePlay ,
+// pstrUsagePause ,
+// pstrUsageRecord ,
+// pstrUsageError ,
+// pstrUsageSelectedIndicator ,
+// pstrUsageInUseIndicator ,
+// pstrUsageMultiModeIndicator ,
+// pstrUsageIndicatorOn ,
+// pstrUsageIndicatorFlash ,
+// pstrUsageIndicatorSlowBlink ,
+// pstrUsageIndicatorFastBlink ,
+// pstrUsageIndicatorOff ,
+// pstrUsageFlashOnTime ,
+// pstrUsageSlowBlinkOnTime ,
+// pstrUsageSlowBlinkOffTime ,
+// pstrUsageFastBlinkOnTime ,
+// pstrUsageFastBlinkOffTime ,
+// pstrUsageIndicatorColor ,
+// pstrUsageIndicatorRed ,
+// pstrUsageIndicatorGreen ,
+// pstrUsageIndicatorAmber ,
+// pstrUsageGenericIndicator ,
+// pstrUsageSystemSuspend ,
+// pstrUsageExternalPowerConnected
+//};
+//const char *telTitles0 [] PROGMEM =
+//{
+// pstrUsagePhone ,
+// pstrUsageAnsweringMachine ,
+// pstrUsageMessageControls ,
+// pstrUsageHandset ,
+// pstrUsageHeadset ,
+// pstrUsageTelephonyKeyPad ,
+// pstrUsageProgrammableButton
+//};
+//const char *telTitles1 [] PROGMEM =
+//{
+// pstrUsageHookSwitch ,
+// pstrUsageFlash ,
+// pstrUsageFeature ,
+// pstrUsageHold ,
+// pstrUsageRedial ,
+// pstrUsageTransfer ,
+// pstrUsageDrop ,
+// pstrUsagePark ,
+// pstrUsageForwardCalls ,
+// pstrUsageAlternateFunction ,
+// pstrUsageLine ,
+// pstrUsageSpeakerPhone ,
+// pstrUsageConference ,
+// pstrUsageRingEnable ,
+// pstrUsageRingSelect ,
+// pstrUsagePhoneMute ,
+// pstrUsageCallerID ,
+// pstrUsageSend
+//};
+//const char *telTitles2 [] PROGMEM =
+//{
+// pstrUsageSpeedDial ,
+// pstrUsageStoreNumber ,
+// pstrUsageRecallNumber ,
+// pstrUsagePhoneDirectory
+//};
+//const char *telTitles3 [] PROGMEM =
+//{
+// pstrUsageVoiceMail ,
+// pstrUsageScreenCalls ,
+// pstrUsageDoNotDisturb ,
+// pstrUsageMessage ,
+// pstrUsageAnswerOnOff
+//};
+//const char *telTitles4 [] PROGMEM =
+//{
+// pstrUsageInsideDialTone ,
+// pstrUsageOutsideDialTone ,
+// pstrUsageInsideRingTone ,
+// pstrUsageOutsideRingTone ,
+// pstrUsagePriorityRingTone ,
+// pstrUsageInsideRingback ,
+// pstrUsagePriorityRingback ,
+// pstrUsageLineBusyTone ,
+// pstrUsageReorderTone ,
+// pstrUsageCallWaitingTone ,
+// pstrUsageConfirmationTone1 ,
+// pstrUsageConfirmationTone2 ,
+// pstrUsageTonesOff ,
+// pstrUsageOutsideRingback ,
+// pstrUsageRinger
+//};
+//const char *telTitles5 [] PROGMEM =
+//{
+// pstrUsagePhoneKey0 ,
+// pstrUsagePhoneKey1 ,
+// pstrUsagePhoneKey2 ,
+// pstrUsagePhoneKey3 ,
+// pstrUsagePhoneKey4 ,
+// pstrUsagePhoneKey5 ,
+// pstrUsagePhoneKey6 ,
+// pstrUsagePhoneKey7 ,
+// pstrUsagePhoneKey8 ,
+// pstrUsagePhoneKey9 ,
+// pstrUsagePhoneKeyStar ,
+// pstrUsagePhoneKeyPound ,
+// pstrUsagePhoneKeyA ,
+// pstrUsagePhoneKeyB ,
+// pstrUsagePhoneKeyC ,
+// pstrUsagePhoneKeyD
+//};
+//const char *consTitles0[] PROGMEM =
+//{
+// pstrUsageConsumerControl,
+// pstrUsageNumericKeyPad,
+// pstrUsageProgrammableButton,
+// pstrUsageMicrophone,
+// pstrUsageHeadphone,
+// pstrUsageGraphicEqualizer
+//};
+//const char *consTitles1[] PROGMEM =
+//{
+// pstrUsagePlus10 ,
+// pstrUsagePlus100,
+// pstrUsageAMPM
+//};
+//const char *consTitles2[] PROGMEM =
+//{
+// pstrUsagePower ,
+// pstrUsageReset ,
+// pstrUsageSleep ,
+// pstrUsageSleepAfter ,
+// pstrUsageSleepMode ,
+// pstrUsageIllumination ,
+// pstrUsageFunctionButtons
+//
+//};
+//const char *consTitles3[] PROGMEM =
+//{
+// pstrUsageMenu ,
+// pstrUsageMenuPick ,
+// pstrUsageMenuUp ,
+// pstrUsageMenuDown ,
+// pstrUsageMenuLeft ,
+// pstrUsageMenuRight ,
+// pstrUsageMenuEscape ,
+// pstrUsageMenuValueIncrease,
+// pstrUsageMenuValueDecrease
+//};
+//const char *consTitles4[] PROGMEM =
+//{
+// pstrUsageDataOnScreen ,
+// pstrUsageClosedCaption ,
+// pstrUsageClosedCaptionSelect,
+// pstrUsageVCRTV ,
+// pstrUsageBroadcastMode ,
+// pstrUsageSnapshot ,
+// pstrUsageStill
+//};
+//const char *consTitles5[] PROGMEM =
+//{
+// pstrUsageSelection ,
+// pstrUsageAssignSelection ,
+// pstrUsageModeStep ,
+// pstrUsageRecallLast ,
+// pstrUsageEnterChannel ,
+// pstrUsageOrderMovie ,
+// pstrUsageChannel ,
+// pstrUsageMediaSelection ,
+// pstrUsageMediaSelectComputer ,
+// pstrUsageMediaSelectTV ,
+// pstrUsageMediaSelectWWW ,
+// pstrUsageMediaSelectDVD ,
+// pstrUsageMediaSelectTelephone ,
+// pstrUsageMediaSelectProgramGuide ,
+// pstrUsageMediaSelectVideoPhone ,
+// pstrUsageMediaSelectGames ,
+// pstrUsageMediaSelectMessages ,
+// pstrUsageMediaSelectCD ,
+// pstrUsageMediaSelectVCR ,
+// pstrUsageMediaSelectTuner ,
+// pstrUsageQuit ,
+// pstrUsageHelp ,
+// pstrUsageMediaSelectTape ,
+// pstrUsageMediaSelectCable ,
+// pstrUsageMediaSelectSatellite ,
+// pstrUsageMediaSelectSecurity ,
+// pstrUsageMediaSelectHome ,
+// pstrUsageMediaSelectCall ,
+// pstrUsageChannelIncrement ,
+// pstrUsageChannelDecrement ,
+// pstrUsageMediaSelectSAP ,
+// pstrUsagePageReserved ,
+// pstrUsageVCRPlus ,
+// pstrUsageOnce ,
+// pstrUsageDaily ,
+// pstrUsageWeekly ,
+// pstrUsageMonthly
+//};
+//const char *consTitles6[] PROGMEM =
+//{
+// pstrUsagePlay ,
+// pstrUsagePause ,
+// pstrUsageRecord ,
+// pstrUsageFastForward ,
+// pstrUsageRewind ,
+// pstrUsageScanNextTrack ,
+// pstrUsageScanPreviousTrack ,
+// pstrUsageStop ,
+// pstrUsageEject ,
+// pstrUsageRandomPlay ,
+// pstrUsageSelectDisk ,
+// pstrUsageEnterDisk ,
+// pstrUsageRepeat ,
+// pstrUsageTracking ,
+// pstrUsageTrackNormal ,
+// pstrUsageSlowTracking ,
+// pstrUsageFrameForward ,
+// pstrUsageFrameBackwards ,
+// pstrUsageMark ,
+// pstrUsageClearMark ,
+// pstrUsageRepeatFromMark ,
+// pstrUsageReturnToMark ,
+// pstrUsageSearchMarkForward ,
+// pstrUsageSearchMarkBackwards ,
+// pstrUsageCounterReset ,
+// pstrUsageShowCounter ,
+// pstrUsageTrackingIncrement ,
+// pstrUsageTrackingDecrement ,
+// pstrUsageStopEject ,
+// pstrUsagePlayPause ,
+// pstrUsagePlaySkip
+//};
+//const char *consTitles7[] PROGMEM =
+//{
+// pstrUsageVolume ,
+// pstrUsageBalance ,
+// pstrUsageMute ,
+// pstrUsageBass ,
+// pstrUsageTreble ,
+// pstrUsageBassBoost ,
+// pstrUsageSurroundMode ,
+// pstrUsageLoudness ,
+// pstrUsageMPX ,
+// pstrUsageVolumeIncrement ,
+// pstrUsageVolumeDecrement
+//};
+//const char *consTitles8[] PROGMEM =
+//{
+// pstrUsageSpeedSelect ,
+// pstrUsagePlaybackSpeed ,
+// pstrUsageStandardPlay ,
+// pstrUsageLongPlay ,
+// pstrUsageExtendedPlay ,
+// pstrUsageSlow
+//};
+//const char *consTitles9[] PROGMEM =
+//{
+// pstrUsageFanEnable ,
+// pstrUsageFanSpeed ,
+// pstrUsageLightEnable ,
+// pstrUsageLightIlluminationLevel ,
+// pstrUsageClimateControlEnable ,
+// pstrUsageRoomTemperature ,
+// pstrUsageSecurityEnable ,
+// pstrUsageFireAlarm ,
+// pstrUsagePoliceAlarm ,
+// pstrUsageProximity ,
+// pstrUsageMotion ,
+// pstrUsageDuresAlarm ,
+// pstrUsageHoldupAlarm ,
+// pstrUsageMedicalAlarm
+//};
+//const char *consTitlesA[] PROGMEM =
+//{
+// pstrUsageBalanceRight ,
+// pstrUsageBalanceLeft ,
+// pstrUsageBassIncrement ,
+// pstrUsageBassDecrement ,
+// pstrUsageTrebleIncrement ,
+// pstrUsageTrebleDecrement
+//};
+//const char *consTitlesB[] PROGMEM =
+//{
+// pstrUsageSpeakerSystem ,
+// pstrUsageChannelLeft ,
+// pstrUsageChannelRight ,
+// pstrUsageChannelCenter ,
+// pstrUsageChannelFront ,
+// pstrUsageChannelCenterFront ,
+// pstrUsageChannelSide ,
+// pstrUsageChannelSurround ,
+// pstrUsageChannelLowFreqEnhancement ,
+// pstrUsageChannelTop ,
+// pstrUsageChannelUnknown
+//};
+//const char *consTitlesC[] PROGMEM =
+//{
+// pstrUsageSubChannel ,
+// pstrUsageSubChannelIncrement ,
+// pstrUsageSubChannelDecrement ,
+// pstrUsageAlternateAudioIncrement ,
+// pstrUsageAlternateAudioDecrement
+//};
+//const char *consTitlesD[] PROGMEM =
+//{
+// pstrUsageApplicationLaunchButtons ,
+// pstrUsageALLaunchButtonConfigTool ,
+// pstrUsageALProgrammableButton ,
+// pstrUsageALConsumerControlConfig ,
+// pstrUsageALWordProcessor ,
+// pstrUsageALTextEditor ,
+// pstrUsageALSpreadsheet ,
+// pstrUsageALGraphicsEditor ,
+// pstrUsageALPresentationApp ,
+// pstrUsageALDatabaseApp ,
+// pstrUsageALEmailReader ,
+// pstrUsageALNewsreader ,
+// pstrUsageALVoicemail ,
+// pstrUsageALContactsAddressBook ,
+// pstrUsageALCalendarSchedule ,
+// pstrUsageALTaskProjectManager ,
+// pstrUsageALLogJournalTimecard ,
+// pstrUsageALCheckbookFinance ,
+// pstrUsageALCalculator ,
+// pstrUsageALAVCapturePlayback ,
+// pstrUsageALLocalMachineBrowser ,
+// pstrUsageALLANWANBrow ,
+// pstrUsageALInternetBrowser ,
+// pstrUsageALRemoteNetISPConnect ,
+// pstrUsageALNetworkConference ,
+// pstrUsageALNetworkChat ,
+// pstrUsageALTelephonyDialer ,
+// pstrUsageALLogon ,
+// pstrUsageALLogoff ,
+// pstrUsageALLogonLogoff ,
+// pstrUsageALTermLockScrSav ,
+// pstrUsageALControlPannel ,
+// pstrUsageALCommandLineProcessorRun ,
+// pstrUsageALProcessTaskManager ,
+// pstrUsageALSelectTaskApplication ,
+// pstrUsageALNextTaskApplication ,
+// pstrUsageALPreviousTaskApplication ,
+// pstrUsageALPreemptiveHaltTaskApp ,
+// pstrUsageALIntegratedHelpCenter ,
+// pstrUsageALDocuments ,
+// pstrUsageALThesaurus ,
+// pstrUsageALDictionary ,
+// pstrUsageALDesktop ,
+// pstrUsageALSpellCheck ,
+// pstrUsageALGrammarCheck ,
+// pstrUsageALWirelessStatus ,
+// pstrUsageALKeyboardLayout ,
+// pstrUsageALVirusProtection ,
+// pstrUsageALEncryption ,
+// pstrUsageALScreenSaver ,
+// pstrUsageALAlarms ,
+// pstrUsageALClock ,
+// pstrUsageALFileBrowser ,
+// pstrUsageALPowerStatus ,
+// pstrUsageALImageBrowser ,
+// pstrUsageALAudioBrowser ,
+// pstrUsageALMovieBrowser ,
+// pstrUsageALDigitalRightsManager ,
+// pstrUsageALDigitalWallet ,
+// pstrUsagePageReserved ,
+// pstrUsageALInstantMessaging ,
+// pstrUsageALOEMFeaturesBrowser ,
+// pstrUsageALOEMHelp ,
+// pstrUsageALOnlineCommunity ,
+// pstrUsageALEntertainmentContentBrow ,
+// pstrUsageALOnlineShoppingBrowser ,
+// pstrUsageALSmartCardInfoHelp ,
+// pstrUsageALMarketMonitorFinBrowser ,
+// pstrUsageALCustomCorpNewsBrowser ,
+// pstrUsageALOnlineActivityBrowser ,
+// pstrUsageALResearchSearchBrowser ,
+// pstrUsageALAudioPlayer
+//};
+//const char *consTitlesE[] PROGMEM =
+//{
+// pstrUsageGenericGUIAppControls ,
+// pstrUsageACNew ,
+// pstrUsageACOpen ,
+// pstrUsageACClose ,
+// pstrUsageACExit ,
+// pstrUsageACMaximize ,
+// pstrUsageACMinimize ,
+// pstrUsageACSave ,
+// pstrUsageACPrint ,
+// pstrUsageACProperties ,
+// pstrUsageACUndo ,
+// pstrUsageACCopy ,
+// pstrUsageACCut ,
+// pstrUsageACPaste ,
+// pstrUsageACSelectAll ,
+// pstrUsageACFind ,
+// pstrUsageACFindAndReplace ,
+// pstrUsageACSearch ,
+// pstrUsageACGoto ,
+// pstrUsageACHome ,
+// pstrUsageACBack ,
+// pstrUsageACForward ,
+// pstrUsageACStop ,
+// pstrUsageACRefresh ,
+// pstrUsageACPreviousLink ,
+// pstrUsageACNextLink ,
+// pstrUsageACBookmarks ,
+// pstrUsageACHistory ,
+// pstrUsageACSubscriptions ,
+// pstrUsageACZoomIn ,
+// pstrUsageACZoomOut ,
+// pstrUsageACZoom ,
+// pstrUsageACFullScreenView ,
+// pstrUsageACNormalView ,
+// pstrUsageACViewToggle ,
+// pstrUsageACScrollUp ,
+// pstrUsageACScrollDown ,
+// pstrUsageACScroll ,
+// pstrUsageACPanLeft ,
+// pstrUsageACPanRight ,
+// pstrUsageACPan ,
+// pstrUsageACNewWindow ,
+// pstrUsageACTileHoriz ,
+// pstrUsageACTileVert ,
+// pstrUsageACFormat ,
+// pstrUsageACEdit ,
+// pstrUsageACBold ,
+// pstrUsageACItalics ,
+// pstrUsageACUnderline ,
+// pstrUsageACStrikethrough ,
+// pstrUsageACSubscript ,
+// pstrUsageACSuperscript ,
+// pstrUsageACAllCaps ,
+// pstrUsageACRotate ,
+// pstrUsageACResize ,
+// pstrUsageACFlipHorizontal ,
+// pstrUsageACFlipVertical ,
+// pstrUsageACMirrorHorizontal ,
+// pstrUsageACMirrorVertical ,
+// pstrUsageACFontSelect ,
+// pstrUsageACFontColor ,
+// pstrUsageACFontSize ,
+// pstrUsageACJustifyLeft ,
+// pstrUsageACJustifyCenterH ,
+// pstrUsageACJustifyRight ,
+// pstrUsageACJustifyBlockH ,
+// pstrUsageACJustifyTop ,
+// pstrUsageACJustifyCenterV ,
+// pstrUsageACJustifyBottom ,
+// pstrUsageACJustifyBlockV ,
+// pstrUsageACIndentDecrease ,
+// pstrUsageACIndentIncrease ,
+// pstrUsageACNumberedList ,
+// pstrUsageACRestartNumbering ,
+// pstrUsageACBulletedList ,
+// pstrUsageACPromote ,
+// pstrUsageACDemote ,
+// pstrUsageACYes ,
+// pstrUsageACNo ,
+// pstrUsageACCancel ,
+// pstrUsageACCatalog ,
+// pstrUsageACBuyChkout ,
+// pstrUsageACAddToCart ,
+// pstrUsageACExpand ,
+// pstrUsageACExpandAll ,
+// pstrUsageACCollapse ,
+// pstrUsageACCollapseAll ,
+// pstrUsageACPrintPreview ,
+// pstrUsageACPasteSpecial ,
+// pstrUsageACInsertMode ,
+// pstrUsageACDelete ,
+// pstrUsageACLock ,
+// pstrUsageACUnlock ,
+// pstrUsageACProtect ,
+// pstrUsageACUnprotect ,
+// pstrUsageACAttachComment ,
+// pstrUsageACDeleteComment ,
+// pstrUsageACViewComment ,
+// pstrUsageACSelectWord ,
+// pstrUsageACSelectSentence ,
+// pstrUsageACSelectParagraph ,
+// pstrUsageACSelectColumn ,
+// pstrUsageACSelectRow ,
+// pstrUsageACSelectTable ,
+// pstrUsageACSelectObject ,
+// pstrUsageACRedoRepeat ,
+// pstrUsageACSort ,
+// pstrUsageACSortAscending ,
+// pstrUsageACSortDescending ,
+// pstrUsageACFilter ,
+// pstrUsageACSetClock ,
+// pstrUsageACViewClock ,
+// pstrUsageACSelectTimeZone ,
+// pstrUsageACEditTimeZone ,
+// pstrUsageACSetAlarm ,
+// pstrUsageACClearAlarm ,
+// pstrUsageACSnoozeAlarm ,
+// pstrUsageACResetAlarm ,
+// pstrUsageACSyncronize ,
+// pstrUsageACSendReceive ,
+// pstrUsageACSendTo ,
+// pstrUsageACReply ,
+// pstrUsageACReplyAll ,
+// pstrUsageACForwardMessage ,
+// pstrUsageACSend ,
+// pstrUsageACAttachFile ,
+// pstrUsageACUpload ,
+// pstrUsageACDownload ,
+// pstrUsageACSetBorders ,
+// pstrUsageACInsertRow ,
+// pstrUsageACInsertColumn ,
+// pstrUsageACInsertFile ,
+// pstrUsageACInsertPicture ,
+// pstrUsageACInsertObject ,
+// pstrUsageACInsertSymbol ,
+// pstrUsageACSaveAndClose ,
+// pstrUsageACRename ,
+// pstrUsageACMerge ,
+// pstrUsageACSplit ,
+// pstrUsageACDistributeHorizontaly ,
+// pstrUsageACDistributeVerticaly
+//};
+//const char *digitTitles0[] PROGMEM =
+//{
+// pstrUsageDigitizer ,
+// pstrUsagePen ,
+// pstrUsageLightPen ,
+// pstrUsageTouchScreen ,
+// pstrUsageTouchPad ,
+// pstrUsageWhiteBoard ,
+// pstrUsageCoordinateMeasuringMachine ,
+// pstrUsage3DDigitizer ,
+// pstrUsageStereoPlotter ,
+// pstrUsageArticulatedArm ,
+// pstrUsageArmature ,
+// pstrUsageMultiplePointDigitizer ,
+// pstrUsageFreeSpaceWand
+//};
+//const char *digitTitles1[] PROGMEM =
+//{
+// pstrUsageStylus ,
+// pstrUsagePuck ,
+// pstrUsageFinger
+//
+//};
+//const char *digitTitles2[] PROGMEM =
+//{
+// pstrUsageTipPressure ,
+// pstrUsageBarrelPressure ,
+// pstrUsageInRange ,
+// pstrUsageTouch ,
+// pstrUsageUntouch ,
+// pstrUsageTap ,
+// pstrUsageQuality ,
+// pstrUsageDataValid ,
+// pstrUsageTransducerIndex ,
+// pstrUsageTabletFunctionKeys ,
+// pstrUsageProgramChangeKeys ,
+// pstrUsageBatteryStrength ,
+// pstrUsageInvert ,
+// pstrUsageXTilt ,
+// pstrUsageYTilt ,
+// pstrUsageAzimuth ,
+// pstrUsageAltitude ,
+// pstrUsageTwist ,
+// pstrUsageTipSwitch ,
+// pstrUsageSecondaryTipSwitch ,
+// pstrUsageBarrelSwitch ,
+// pstrUsageEraser ,
+// pstrUsageTabletPick
+//};
+//const char *aplphanumTitles0[] PROGMEM =
+//{
+// pstrUsageAlphanumericDisplay,
+// pstrUsageBitmappedDisplay
+//};
+//const char *aplphanumTitles1[] PROGMEM =
+//{
+// pstrUsageDisplayAttributesReport ,
+// pstrUsageASCIICharacterSet ,
+// pstrUsageDataReadBack ,
+// pstrUsageFontReadBack ,
+// pstrUsageDisplayControlReport ,
+// pstrUsageClearDisplay ,
+// pstrUsageDisplayEnable ,
+// pstrUsageScreenSaverDelay ,
+// pstrUsageScreenSaverEnable ,
+// pstrUsageVerticalScroll ,
+// pstrUsageHorizontalScroll ,
+// pstrUsageCharacterReport ,
+// pstrUsageDisplayData ,
+// pstrUsageDisplayStatus ,
+// pstrUsageStatusNotReady ,
+// pstrUsageStatusReady ,
+// pstrUsageErrorNotALoadableCharacter ,
+// pstrUsageErrorFotDataCanNotBeRead ,
+// pstrUsageCursorPositionReport ,
+// pstrUsageRow ,
+// pstrUsageColumn ,
+// pstrUsageRows ,
+// pstrUsageColumns ,
+// pstrUsageCursorPixelPosition ,
+// pstrUsageCursorMode ,
+// pstrUsageCursorEnable ,
+// pstrUsageCursorBlink ,
+// pstrUsageFontReport ,
+// pstrUsageFontData ,
+// pstrUsageCharacterWidth ,
+// pstrUsageCharacterHeight ,
+// pstrUsageCharacterSpacingHorizontal ,
+// pstrUsageCharacterSpacingVertical ,
+// pstrUsageUnicodeCharset ,
+// pstrUsageFont7Segment ,
+// pstrUsage7SegmentDirectMap ,
+// pstrUsageFont14Segment ,
+// pstrUsage14SegmentDirectMap ,
+// pstrUsageDisplayBrightness ,
+// pstrUsageDisplayContrast ,
+// pstrUsageCharacterAttribute ,
+// pstrUsageAttributeReadback ,
+// pstrUsageAttributeData ,
+// pstrUsageCharAttributeEnhance ,
+// pstrUsageCharAttributeUnderline ,
+// pstrUsageCharAttributeBlink
+//};
+//const char *aplphanumTitles2[] PROGMEM =
+//{
+// pstrUsageBitmapSizeX ,
+// pstrUsageBitmapSizeY ,
+// pstrUsagePageReserved ,
+// pstrUsageBitDepthFormat ,
+// pstrUsageDisplayOrientation ,
+// pstrUsagePaletteReport ,
+// pstrUsagePaletteDataSize ,
+// pstrUsagePaletteDataOffset ,
+// pstrUsagePaletteData ,
+// pstrUsageBlitReport ,
+// pstrUsageBlitRectangleX1 ,
+// pstrUsageBlitRectangleY1 ,
+// pstrUsageBlitRectangleX2 ,
+// pstrUsageBlitRectangleY2 ,
+// pstrUsageBlitData ,
+// pstrUsageSoftButton ,
+// pstrUsageSoftButtonID ,
+// pstrUsageSoftButtonSide ,
+// pstrUsageSoftButtonOffset1 ,
+// pstrUsageSoftButtonOffset2 ,
+// pstrUsageSoftButtonReport
+//};
+//const char *medInstrTitles0[] PROGMEM =
+//{
+// pstrUsageVCRAcquisition ,
+// pstrUsageFreezeThaw ,
+// pstrUsageClipStore ,
+// pstrUsageUpdate ,
+// pstrUsageNext ,
+// pstrUsageSave ,
+// pstrUsagePrint ,
+// pstrUsageMicrophoneEnable
+//};
+//const char *medInstrTitles1[] PROGMEM =
+//{
+// pstrUsageCine ,
+// pstrUsageTransmitPower ,
+// pstrUsageVolume ,
+// pstrUsageFocus ,
+// pstrUsageDepth
+//};
+//const char *medInstrTitles2[] PROGMEM =
+//{
+// pstrUsageSoftStepPrimary ,
+// pstrUsageSoftStepSecondary
+//};
+//const char *medInstrTitles3[] PROGMEM =
+//{
+// pstrUsageZoomSelect ,
+// pstrUsageZoomAdjust ,
+// pstrUsageSpectralDopplerModeSelect ,
+// pstrUsageSpectralDopplerModeAdjust ,
+// pstrUsageColorDopplerModeSelect ,
+// pstrUsageColorDopplerModeAdjust ,
+// pstrUsageMotionModeSelect ,
+// pstrUsageMotionModeAdjust ,
+// pstrUsage2DModeSelect ,
+// pstrUsage2DModeAdjust
+//};
+//const char *medInstrTitles4[] PROGMEM =
+//{
+// pstrUsageSoftControlSelect ,
+// pstrUsageSoftControlAdjust
+//};
+
+#endif // __HIDUSAGETITLEARRAYS_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/keywords.txt b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/keywords.txt
new file mode 100644
index 000000000..f4e19cd13
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/keywords.txt
@@ -0,0 +1,371 @@
+####################################################
+# Syntax Coloring Map For USB Library
+####################################################
+
+####################################################
+# Datatypes (KEYWORD1)
+####################################################
+
+USB KEYWORD1
+USBHub KEYWORD1
+
+####################################################
+# Syntax Coloring Map For BTD (Bluetooth) Library
+####################################################
+
+####################################################
+# Datatypes (KEYWORD1)
+####################################################
+
+BTD KEYWORD1
+
+####################################################
+# Methods and Functions (KEYWORD2)
+####################################################
+Task KEYWORD2
+
+####################################################
+# Syntax Coloring Map For PS3/PS4 Bluetooth/USB Library
+####################################################
+
+####################################################
+# Datatypes (KEYWORD1)
+####################################################
+
+PS3BT KEYWORD1
+PS3USB KEYWORD1
+PS4BT KEYWORD1
+PS4USB KEYWORD1
+
+####################################################
+# Methods and Functions (KEYWORD2)
+####################################################
+setBdaddr KEYWORD2
+getBdaddr KEYWORD2
+setMoveBdaddr KEYWORD2
+getMoveBdaddr KEYWORD2
+getMoveCalibration KEYWORD2
+
+getButtonPress KEYWORD2
+getButtonClick KEYWORD2
+getAnalogButton KEYWORD2
+getAnalogHat KEYWORD2
+getSensor KEYWORD2
+getAngle KEYWORD2
+get9DOFValues KEYWORD2
+getStatus KEYWORD2
+printStatusString KEYWORD2
+getTemperature KEYWORD2
+disconnect KEYWORD2
+
+setAllOff KEYWORD2
+setRumbleOff KEYWORD2
+setRumbleOn KEYWORD2
+setLedOff KEYWORD2
+setLedOn KEYWORD2
+setLedToggle KEYWORD2
+setLedFlash KEYWORD2
+moveSetBulb KEYWORD2
+moveSetRumble KEYWORD2
+
+attachOnInit KEYWORD2
+
+PS3Connected KEYWORD2
+PS3MoveConnected KEYWORD2
+PS3NavigationConnected KEYWORD2
+
+isReady KEYWORD2
+watingForConnection KEYWORD2
+
+isTouching KEYWORD2
+getX KEYWORD2
+getY KEYWORD2
+getTouchCounter KEYWORD2
+
+getUsbStatus KEYWORD2
+getAudioStatus KEYWORD2
+getMicStatus KEYWORD2
+
+####################################################
+# Constants and enums (LITERAL1)
+####################################################
+OFF LITERAL1
+LED1 LITERAL1
+LED2 LITERAL1
+LED3 LITERAL1
+LED4 LITERAL1
+LED5 LITERAL1
+LED6 LITERAL1
+LED7 LITERAL1
+LED8 LITERAL1
+LED9 LITERAL1
+LED10 LITERAL1
+
+Red LITERAL1
+Green LITERAL1
+Blue LITERAL1
+Yellow LITERAL1
+Lightblue LITERAL1
+Purble LITERAL1
+White LITERAL1
+Off LITERAL1
+
+SELECT LITERAL1
+L3 LITERAL1
+R3 LITERAL1
+START LITERAL1
+UP LITERAL1
+RIGHT LITERAL1
+DOWN LITERAL1
+LEFT LITERAL1
+L2 LITERAL1
+R2 LITERAL1
+L1 LITERAL1
+R1 LITERAL1
+TRIANGLE LITERAL1
+CIRCLE LITERAL1
+CROSS LITERAL1
+SQUARE LITERAL1
+PS LITERAL1
+MOVE LITERAL1
+T LITERAL1
+
+SHARE LITERAL1
+OPTIONS LITERAL1
+TOUCHPAD LITERAL1
+
+LeftHatX LITERAL1
+LeftHatY LITERAL1
+RightHatX LITERAL1
+RightHatY LITERAL1
+
+aX LITERAL1
+aY LITERAL1
+aZ LITERAL1
+gX LITERAL1
+gY LITERAL1
+gZ LITERAL1
+aXmove LITERAL1
+aYmove LITERAL1
+aZmove LITERAL1
+gXmove LITERAL1
+gYmove LITERAL1
+gZmove LITERAL1
+tempMove LITERAL1
+mXmove LITERAL1
+mZmove LITERAL1
+mYmove LITERAL1
+
+Pitch LITERAL1
+Roll LITERAL1
+
+Plugged LITERAL1
+Unplugged LITERAL1
+Charging LITERAL1
+NotCharging LITERAL1
+Shutdown LITERAL1
+Dying LITERAL1
+Low LITERAL1
+High LITERAL1
+Full LITERAL1
+MoveCharging LITERAL1
+MoveNotCharging LITERAL1
+MoveShutdown LITERAL1
+MoveDying LITERAL1
+MoveLow LITERAL1
+MoveHigh LITERAL1
+MoveFull LITERAL1
+CableRumble LITERAL1
+Cable LITERAL1
+BluetoothRumble LITERAL1
+Bluetooth LITERAL1
+
+RumbleHigh LITERAL1
+RumbleLow LITERAL1
+
+####################################################
+# Syntax Coloring Map For Xbox 360 Libraries
+####################################################
+
+####################################################
+# Datatypes (KEYWORD1)
+####################################################
+
+XBOXUSB KEYWORD1
+XBOXONE KEYWORD1
+XBOXOLD KEYWORD1
+XBOXRECV KEYWORD1
+
+####################################################
+# Methods and Functions (KEYWORD2)
+####################################################
+
+setLedRaw KEYWORD2
+setLedBlink KEYWORD2
+setLedMode KEYWORD2
+getBatteryLevel KEYWORD2
+buttonChanged KEYWORD2
+
+XboxReceiverConnected KEYWORD2
+Xbox360Connected KEYWORD2
+XboxOneConnected KEYWORD2
+
+####################################################
+# Constants and enums (LITERAL1)
+####################################################
+
+ALL LITERAL1
+
+ROTATING LITERAL1
+FASTBLINK LITERAL1
+SLOWBLINK LITERAL1
+ALTERNATING LITERAL1
+
+BACK LITERAL1
+
+XBOX LITERAL1
+SYNC LITERAL1
+
+BLACK LITERAL1
+WHITE LITERAL1
+
+A LITERAL1
+B LITERAL1
+X LITERAL1
+Y LITERAL1
+
+####################################################
+# Syntax Coloring Map For RFCOMM/SPP Library
+####################################################
+
+####################################################
+# Datatypes (KEYWORD1)
+####################################################
+
+SPP KEYWORD1
+
+####################################################
+# Methods and Functions (KEYWORD2)
+####################################################
+
+connected KEYWORD2
+discard KEYWORD2
+
+####################################################
+# Syntax Coloring Map For Wiimote Library
+####################################################
+
+####################################################
+# Datatypes (KEYWORD1)
+####################################################
+
+WII KEYWORD1
+
+####################################################
+# Methods and Functions (KEYWORD2)
+####################################################
+
+wiimoteConnected KEYWORD2
+nunchuckConnected KEYWORD2
+motionPlusConnected KEYWORD2
+wiiUProControllerConnected KEYWORD2
+wiiBalanceBoardConnected KEYWORD2
+setRumbleToggle KEYWORD2
+getPitch KEYWORD2
+getRoll KEYWORD2
+getYaw KEYWORD2
+getWiimotePitch KEYWORD2
+getWiimoteRoll KEYWORD2
+getNunchuckPitch KEYWORD2
+getNunchuckRoll KEYWORD2
+PAIR KEYWORD2
+statusRequest KEYWORD2
+getBatteryLevel KEYWORD2
+getWiiState KEYWORD2
+getWeight KEYWORD2
+getTotalWeight KEYWORD2
+getWeightRaw KEYWORD2
+
+####################################################
+# Constants and enums (LITERAL1)
+####################################################
+
+PLUS LITERAL1
+MINUS LITERAL1
+ONE LITERAL1
+TWO LITERAL1
+HOME LITERAL1
+Z LITERAL1
+C LITERAL1
+L LITERAL1
+R LITERAL1
+ZL LITERAL1
+ZR LITERAL1
+HatX LITERAL1
+HatY LITERAL1
+TopRight LITERAL1
+BotRight LITERAL1
+TopLeft LITERAL1
+BotLeft LITERAL1
+
+####################################################
+# Methods and Functions for the IR Camera
+####################################################
+
+IRinitialize KEYWORD2
+isIRCameraEnabled KEYWORD2
+getIRx1 KEYWORD2
+getIRy1 KEYWORD2
+getIRs1 KEYWORD2
+getIRx2 KEYWORD2
+getIRy2 KEYWORD2
+getIRs2 KEYWORD2
+getIRx3 KEYWORD2
+getIRy3 KEYWORD2
+getIRs3 KEYWORD2
+getIRx4 KEYWORD2
+getIRy4 KEYWORD2
+getIRs4 KEYWORD2
+
+####################################################
+# Syntax Coloring Map For BTHID Library
+####################################################
+
+####################################################
+# Datatypes (KEYWORD1)
+####################################################
+
+BTHID KEYWORD1
+
+####################################################
+# Methods and Functions (KEYWORD2)
+####################################################
+SetReportParser KEYWORD2
+setProtocolMode KEYWORD2
+
+####################################################
+# Syntax Coloring Map For PS Buzz Library
+####################################################
+
+####################################################
+# Datatypes (KEYWORD1)
+####################################################
+
+PSBuzz KEYWORD1
+
+####################################################
+# Methods and Functions (KEYWORD2)
+####################################################
+
+setLedOnAll KEYWORD2
+setLedOffAll KEYWORD2
+
+####################################################
+# Constants and enums (LITERAL1)
+####################################################
+
+RED LITERAL1
+YELLOW LITERAL1
+GREEN LITERAL1
+ORANGE LITERAL1
+BLUE LITERAL1
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/library.json b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/library.json
new file mode 100644
index 000000000..1d649b1e1
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/library.json
@@ -0,0 +1,47 @@
+{
+ "name": "USB-Host-Shield-20",
+ "keywords": "usb, host, ftdi, adk, acm, pl2303, hid, bluetooth, spp, ps3, ps4, buzz, xbox, wii, mass storage",
+ "description": "Revision 2.0 of MAX3421E-based USB Host Shield Library",
+ "authors":
+ [
+ {
+ "name": "Oleg Mazurov",
+ "email": "mazurov@circuitsathome.com",
+ "url": "http://www.circuitsathome.com",
+ "maintainer": true
+ },
+ {
+ "name": "Alexei Glushchenko",
+ "email": "alex-gl@mail.ru"
+ },
+ {
+ "name": "Kristian Lauszus",
+ "email": "kristianl@tkjelectronics.com",
+ "url": "http://tkjelectronics.com",
+ "maintainer": true
+ },
+ {
+ "name": "Andrew Kroll",
+ "email": "xxxajk@gmail.com",
+ "maintainer": true
+ }
+ ],
+ "repository":
+ {
+ "type": "git",
+ "url": "https://github.com/felis/USB_Host_Shield_2.0.git"
+ },
+ "examples":
+ [
+ "examples/*/*.ino",
+ "examples/*/*/*.ino"
+ ],
+ "frameworks": "arduino",
+ "platforms":
+ [
+ "atmelavr",
+ "teensy",
+ "atmelsam",
+ "nordicnrf51"
+ ]
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/library.properties b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/library.properties
new file mode 100644
index 000000000..7881b05e9
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/library.properties
@@ -0,0 +1,9 @@
+name=USB Host Shield Library 2.0
+version=1.1.0
+author=Oleg Mazurov (Circuits@Home) <mazurov@circuitsathome.com>, Kristian Lauszus (TKJ Electronics) <kristianl@tkjelectronics.com>, Andrew Kroll <xxxajk@gmail.com>, Alexei Glushchenko (Circuits@Home) <alex-gl@mail.ru>
+maintainer=Oleg Mazurov (Circuits@Home) <mazurov@circuitsathome.com>, Kristian Lauszus (TKJ Electronics) <kristianl@tkjelectronics.com>, Andrew Kroll <xxxajk@gmail.com>
+sentence=Revision 2.0 of MAX3421E-based USB Host Shield Library.
+paragraph=Supports HID devices, FTDI, ADK, ACM, PL2303, Bluetooth HID devices, SPP communication and mass storage devices. Furthermore it supports PS3, PS4, PS Buzz, Wii and Xbox controllers.
+category=Other
+url=https://github.com/felis/USB_Host_Shield_2.0
+architectures=* \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/macros.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/macros.h
new file mode 100644
index 000000000..e14a711fa
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/macros.h
@@ -0,0 +1,82 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#if !defined(_usb_h_) || defined(MACROS_H)
+#error "Never include macros.h directly; include Usb.h instead"
+#else
+#define MACROS_H
+
+////////////////////////////////////////////////////////////////////////////////
+// HANDY MACROS
+////////////////////////////////////////////////////////////////////////////////
+
+#define VALUE_BETWEEN(v,l,h) (((v)>(l)) && ((v)<(h)))
+#define VALUE_WITHIN(v,l,h) (((v)>=(l)) && ((v)<=(h)))
+#define output_pgm_message(wa,fp,mp,el) wa = &mp, fp((char *)pgm_read_pointer(wa), el)
+#define output_if_between(v,l,h,wa,fp,mp,el) if(VALUE_BETWEEN(v,l,h)) output_pgm_message(wa,fp,mp[v-(l+1)],el);
+
+#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))
+#ifndef __BYTE_GRABBING_DEFINED__
+#define __BYTE_GRABBING_DEFINED__ 1
+#ifdef BROKEN_OPTIMIZER_LITTLE_ENDIAN
+// Note: Use this if your compiler generates horrible assembler!
+#define BGRAB0(__usi__) (((uint8_t *)&(__usi__))[0])
+#define BGRAB1(__usi__) (((uint8_t *)&(__usi__))[1])
+#define BGRAB2(__usi__) (((uint8_t *)&(__usi__))[2])
+#define BGRAB3(__usi__) (((uint8_t *)&(__usi__))[3])
+#define BGRAB4(__usi__) (((uint8_t *)&(__usi__))[4])
+#define BGRAB5(__usi__) (((uint8_t *)&(__usi__))[5])
+#define BGRAB6(__usi__) (((uint8_t *)&(__usi__))[6])
+#define BGRAB7(__usi__) (((uint8_t *)&(__usi__))[7])
+#else
+// Note: The cast alone to uint8_t is actually enough.
+// GCC throws out the "& 0xff", and the size is no different.
+// Some compilers need it.
+#define BGRAB0(__usi__) ((uint8_t)((__usi__) & 0xff ))
+#define BGRAB1(__usi__) ((uint8_t)(((__usi__) >> 8) & 0xff))
+#define BGRAB2(__usi__) ((uint8_t)(((__usi__) >> 16) & 0xff))
+#define BGRAB3(__usi__) ((uint8_t)(((__usi__) >> 24) & 0xff))
+#define BGRAB4(__usi__) ((uint8_t)(((__usi__) >> 32) & 0xff))
+#define BGRAB5(__usi__) ((uint8_t)(((__usi__) >> 40) & 0xff))
+#define BGRAB6(__usi__) ((uint8_t)(((__usi__) >> 48) & 0xff))
+#define BGRAB7(__usi__) ((uint8_t)(((__usi__) >> 56) & 0xff))
+#endif
+#define BOVER1(__usi__) ((uint16_t)(__usi__) << 8)
+#define BOVER2(__usi__) ((uint32_t)(__usi__) << 16)
+#define BOVER3(__usi__) ((uint32_t)(__usi__) << 24)
+#define BOVER4(__usi__) ((uint64_t)(__usi__) << 32)
+#define BOVER5(__usi__) ((uint64_t)(__usi__) << 40)
+#define BOVER6(__usi__) ((uint64_t)(__usi__) << 48)
+#define BOVER7(__usi__) ((uint64_t)(__usi__) << 56)
+
+// These are the smallest and fastest ways I have found so far in pure C/C++.
+#define BMAKE16(__usc1__,__usc0__) ((uint16_t)((uint16_t)(__usc0__) | (uint16_t)BOVER1(__usc1__)))
+#define BMAKE32(__usc3__,__usc2__,__usc1__,__usc0__) ((uint32_t)((uint32_t)(__usc0__) | (uint32_t)BOVER1(__usc1__) | (uint32_t)BOVER2(__usc2__) | (uint32_t)BOVER3(__usc3__)))
+#define BMAKE64(__usc7__,__usc6__,__usc5__,__usc4__,__usc3__,__usc2__,__usc1__,__usc0__) ((uint64_t)((uint64_t)__usc0__ | (uint64_t)BOVER1(__usc1__) | (uint64_t)BOVER2(__usc2__) | (uint64_t)BOVER3(__usc3__) | (uint64_t)BOVER4(__usc4__) | (uint64_t)BOVER5(__usc5__) | (uint64_t)BOVER6(__usc6__) | (uint64_t)BOVER1(__usc7__)))
+#endif
+
+/*
+ * Debug macros: Strings are stored in progmem (flash) instead of RAM.
+ */
+#define USBTRACE(s) (Notify(PSTR(s), 0x80))
+#define USBTRACE1(s,l) (Notify(PSTR(s), l))
+#define USBTRACE2(s,r) (Notify(PSTR(s), 0x80), D_PrintHex((r), 0x80), Notify(PSTR("\r\n"), 0x80))
+#define USBTRACE3(s,r,l) (Notify(PSTR(s), l), D_PrintHex((r), l), Notify(PSTR("\r\n"), l))
+
+
+#endif /* MACROS_H */
+
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/masstorage.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/masstorage.cpp
new file mode 100644
index 000000000..9299f71a4
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/masstorage.cpp
@@ -0,0 +1,1266 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#include "masstorage.h"
+
+const uint8_t BulkOnly::epDataInIndex = 1;
+const uint8_t BulkOnly::epDataOutIndex = 2;
+const uint8_t BulkOnly::epInterruptInIndex = 3;
+
+////////////////////////////////////////////////////////////////////////////////
+
+// Interface code
+
+////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * Get the capacity of the media
+ *
+ * @param lun Logical Unit Number
+ * @return media capacity
+ */
+uint32_t BulkOnly::GetCapacity(uint8_t lun) {
+ if(LUNOk[lun])
+ return CurrentCapacity[lun];
+ return 0LU;
+}
+
+/**
+ * Get the sector (block) size used on the media
+ *
+ * @param lun Logical Unit Number
+ * @return media sector size
+ */
+uint16_t BulkOnly::GetSectorSize(uint8_t lun) {
+ if(LUNOk[lun])
+ return CurrentSectorSize[lun];
+ return 0U;
+}
+
+/**
+ * Test if LUN is ready for use
+ *
+ * @param lun Logical Unit Number
+ * @return true if LUN is ready for use
+ */
+bool BulkOnly::LUNIsGood(uint8_t lun) {
+ return LUNOk[lun];
+}
+
+/**
+ * Test if LUN is write protected
+ *
+ * @param lun Logical Unit Number
+ * @return cached status of write protect switch
+ */
+bool BulkOnly::WriteProtected(uint8_t lun) {
+ return WriteOk[lun];
+}
+
+/**
+ * Wrap and execute a SCSI CDB with length of 6
+ *
+ * @param cdb CDB to execute
+ * @param buf_size Size of expected transaction
+ * @param buf Buffer
+ * @param dir MASS_CMD_DIR_IN | MASS_CMD_DIR_OUT
+ * @return
+ */
+uint8_t BulkOnly::SCSITransaction6(CDB6_t *cdb, uint16_t buf_size, void *buf, uint8_t dir) {
+ // promote buf_size to 32bits.
+ CommandBlockWrapper cbw = CommandBlockWrapper(++dCBWTag, (uint32_t)buf_size, cdb, dir);
+ //SetCurLUN(cdb->LUN);
+ return (HandleSCSIError(Transaction(&cbw, buf_size, buf)));
+}
+
+/**
+ * Wrap and execute a SCSI CDB with length of 10
+ *
+ * @param cdb CDB to execute
+ * @param buf_size Size of expected transaction
+ * @param buf Buffer
+ * @param dir MASS_CMD_DIR_IN | MASS_CMD_DIR_OUT
+ * @return
+ */
+uint8_t BulkOnly::SCSITransaction10(CDB10_t *cdb, uint16_t buf_size, void *buf, uint8_t dir) {
+ // promote buf_size to 32bits.
+ CommandBlockWrapper cbw = CommandBlockWrapper(++dCBWTag, (uint32_t)buf_size, cdb, dir);
+ //SetCurLUN(cdb->LUN);
+ return (HandleSCSIError(Transaction(&cbw, buf_size, buf)));
+}
+
+/**
+ * Lock or Unlock the tray or door on device.
+ * Caution: Some devices with buggy firmware will lock up.
+ *
+ * @param lun Logical Unit Number
+ * @param lock 1 to lock, 0 to unlock
+ * @return
+ */
+uint8_t BulkOnly::LockMedia(uint8_t lun, uint8_t lock) {
+ Notify(PSTR("\r\nLockMedia\r\n"), 0x80);
+ Notify(PSTR("---------\r\n"), 0x80);
+
+ CDB6_t cdb = CDB6_t(SCSI_CMD_PREVENT_REMOVAL, lun, (uint8_t)0, lock);
+ return SCSITransaction6(&cdb, (uint16_t)0, NULL, (uint8_t)MASS_CMD_DIR_IN);
+}
+
+/**
+ * Media control, for spindle motor and media tray or door.
+ * This includes CDROM, TAPE and anything with a media loader.
+ *
+ * @param lun Logical Unit Number
+ * @param ctl 0x00 Stop Motor, 0x01 Start Motor, 0x02 Eject Media, 0x03 Load Media
+ * @return 0 on success
+ */
+uint8_t BulkOnly::MediaCTL(uint8_t lun, uint8_t ctl) {
+ Notify(PSTR("\r\nMediaCTL\r\n"), 0x80);
+ Notify(PSTR("-----------------\r\n"), 0x80);
+
+ uint8_t rcode = MASS_ERR_UNIT_NOT_READY;
+ if(bAddress) {
+ CDB6_t cdb = CDB6_t(SCSI_CMD_START_STOP_UNIT, lun, ctl & 0x03, 0);
+ rcode = SCSITransaction6(&cdb, (uint16_t)0, NULL, (uint8_t)MASS_CMD_DIR_OUT);
+ } else {
+ SetCurLUN(lun);
+ }
+ return rcode;
+}
+
+/**
+ * Read data from media
+ *
+ * @param lun Logical Unit Number
+ * @param addr LBA address on media to read
+ * @param bsize size of a block (we should probably use the cached size)
+ * @param blocks how many blocks to read
+ * @param buf memory that is able to hold the requested data
+ * @return 0 on success
+ */
+uint8_t BulkOnly::Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, uint8_t *buf) {
+ if(!LUNOk[lun]) return MASS_ERR_NO_MEDIA;
+ Notify(PSTR("\r\nRead LUN:\t"), 0x80);
+ D_PrintHex<uint8_t > (lun, 0x90);
+ Notify(PSTR("\r\nLBA:\t\t"), 0x90);
+ D_PrintHex<uint32_t > (addr, 0x90);
+ Notify(PSTR("\r\nblocks:\t\t"), 0x90);
+ D_PrintHex<uint8_t > (blocks, 0x90);
+ Notify(PSTR("\r\nblock size:\t"), 0x90);
+ D_PrintHex<uint16_t > (bsize, 0x90);
+ Notify(PSTR("\r\n---------\r\n"), 0x80);
+ CDB10_t cdb = CDB10_t(SCSI_CMD_READ_10, lun, blocks, addr);
+
+again:
+ uint8_t er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), buf, (uint8_t)MASS_CMD_DIR_IN);
+
+ if(er == MASS_ERR_STALL) {
+ MediaCTL(lun, 1);
+ delay(150);
+ if(!TestUnitReady(lun)) goto again;
+ }
+ return er;
+}
+
+/**
+ * Write data to media
+ *
+ * @param lun Logical Unit Number
+ * @param addr LBA address on media to write
+ * @param bsize size of a block (we should probably use the cached size)
+ * @param blocks how many blocks to write
+ * @param buf memory that contains the data to write
+ * @return 0 on success
+ */
+uint8_t BulkOnly::Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, const uint8_t * buf) {
+ if(!LUNOk[lun]) return MASS_ERR_NO_MEDIA;
+ if(!WriteOk[lun]) return MASS_ERR_WRITE_PROTECTED;
+ Notify(PSTR("\r\nWrite LUN:\t"), 0x80);
+ D_PrintHex<uint8_t > (lun, 0x90);
+ Notify(PSTR("\r\nLBA:\t\t"), 0x90);
+ D_PrintHex<uint32_t > (addr, 0x90);
+ Notify(PSTR("\r\nblocks:\t\t"), 0x90);
+ D_PrintHex<uint8_t > (blocks, 0x90);
+ Notify(PSTR("\r\nblock size:\t"), 0x90);
+ D_PrintHex<uint16_t > (bsize, 0x90);
+ Notify(PSTR("\r\n---------\r\n"), 0x80);
+ CDB10_t cdb = CDB10_t(SCSI_CMD_WRITE_10, lun, blocks, addr);
+
+again:
+ uint8_t er = SCSITransaction10(&cdb, ((uint16_t)bsize * blocks), (void*)buf, (uint8_t)MASS_CMD_DIR_OUT);
+
+ if(er == MASS_ERR_WRITE_STALL) {
+ MediaCTL(lun, 1);
+ delay(150);
+ if(!TestUnitReady(lun)) goto again;
+ }
+ return er;
+}
+
+// End of user functions, the remaining code below is driver internals.
+// Only developer serviceable parts below!
+
+////////////////////////////////////////////////////////////////////////////////
+
+// Main driver code
+
+////////////////////////////////////////////////////////////////////////////////
+
+BulkOnly::BulkOnly(USB *p) :
+pUsb(p),
+bAddress(0),
+bIface(0),
+bNumEP(1),
+qNextPollTime(0),
+bPollEnable(false),
+//dCBWTag(0),
+bLastUsbError(0) {
+ ClearAllEP();
+ dCBWTag = 0;
+ if(pUsb)
+ pUsb->RegisterDeviceClass(this);
+}
+
+/**
+ * USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET == success
+ * We need to standardize either the rcode, or change the API to return values
+ * so a signal that additional actions are required can be produced.
+ * Some of these codes do exist already.
+ *
+ * TECHNICAL: We could do most of this code elsewhere, with the exception of checking the class instance.
+ * Doing so would save some program memory when using multiple drivers.
+ *
+ * @param parent USB address of parent
+ * @param port address of port on parent
+ * @param lowspeed true if device is low speed
+ * @return
+ */
+uint8_t BulkOnly::ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed) {
+
+ const uint8_t constBufSize = sizeof (USB_DEVICE_DESCRIPTOR);
+
+ uint8_t buf[constBufSize];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ USBTRACE("MS ConfigureDevice\r\n");
+ ClearAllEP();
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+
+ if(bAddress)
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+
+ // <TECHNICAL>
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+ if(!p) {
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+ }
+
+ if(!p->epinfo) {
+ USBTRACE("epinfo\r\n");
+ return USB_ERROR_EPINFO_IS_NULL;
+ }
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, constBufSize, (uint8_t*)buf);
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(rcode) {
+ goto FailGetDevDescr;
+ }
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from the device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+ // Steal and abuse from epInfo structure to save on memory.
+ epInfo[1].epAddr = udd->bNumConfigurations;
+ // </TECHNICAL>
+ return USB_ERROR_CONFIG_REQUIRES_ADDITIONAL_RESET;
+
+FailGetDevDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetDevDescr(rcode);
+#endif
+ rcode = USB_ERROR_FailGetDevDescr;
+
+ Release();
+ return rcode;
+};
+
+/**
+ *
+ * @param parent (not used)
+ * @param port (not used)
+ * @param lowspeed true if device is low speed
+ * @return 0 for success
+ */
+uint8_t BulkOnly::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t rcode;
+ uint8_t num_of_conf = epInfo[1].epAddr; // number of configurations
+ epInfo[1].epAddr = 0;
+ USBTRACE("MS Init\r\n");
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+ UsbDevice *p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ // Assign new address to the device
+ delay(2000);
+ rcode = pUsb->setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ p->lowspeed = false;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ USBTRACE2("setAddr:", rcode);
+ return rcode;
+ }
+
+ USBTRACE2("Addr:", bAddress);
+
+ p->lowspeed = false;
+
+ p = addrPool.GetUsbDevicePtr(bAddress);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ p->lowspeed = lowspeed;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, 1, epInfo);
+
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ USBTRACE2("NC:", num_of_conf);
+
+ for(uint8_t i = 0; i < num_of_conf; i++) {
+ ConfigDescParser< USB_CLASS_MASS_STORAGE,
+ MASS_SUBCLASS_SCSI,
+ MASS_PROTO_BBB,
+ CP_MASK_COMPARE_CLASS |
+ CP_MASK_COMPARE_SUBCLASS |
+ CP_MASK_COMPARE_PROTOCOL > BulkOnlyParser(this);
+
+ rcode = pUsb->getConfDescr(bAddress, 0, i, &BulkOnlyParser);
+
+ if(rcode)
+ goto FailGetConfDescr;
+
+ if(bNumEP > 1)
+ break;
+ }
+
+ if(bNumEP < 3)
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ // Assign epInfo to epinfo pointer
+ pUsb->setEpInfoEntry(bAddress, bNumEP, epInfo);
+
+ USBTRACE2("Conf:", bConfNum);
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, bConfNum);
+
+ if(rcode)
+ goto FailSetConfDescr;
+
+ //Linux does a 1sec delay after this.
+ delay(1000);
+
+ rcode = GetMaxLUN(&bMaxLUN);
+ if(rcode)
+ goto FailGetMaxLUN;
+
+ if(bMaxLUN >= MASS_MAX_SUPPORTED_LUN) bMaxLUN = MASS_MAX_SUPPORTED_LUN - 1;
+ ErrorMessage<uint8_t > (PSTR("MaxLUN"), bMaxLUN);
+
+ delay(1000); // Delay a bit for slow firmware.
+
+ for(uint8_t lun = 0; lun <= bMaxLUN; lun++) {
+ InquiryResponse response;
+ rcode = Inquiry(lun, sizeof (InquiryResponse), (uint8_t*) & response);
+ if(rcode) {
+ ErrorMessage<uint8_t > (PSTR("Inquiry"), rcode);
+ } else {
+#if 0
+ printf("LUN %i `", lun);
+ uint8_t *buf = response.VendorID;
+ for(int i = 0; i < 28; i++) printf("%c", buf[i]);
+ printf("'\r\nQualifier %1.1X ", response.PeripheralQualifier);
+ printf("Device type %2.2X ", response.DeviceType);
+ printf("RMB %1.1X ", response.Removable);
+ printf("SSCS %1.1X ", response.SCCS);
+ uint8_t sv = response.Version;
+ printf("SCSI version %2.2X\r\nDevice conforms to ", sv);
+ switch(sv) {
+ case 0:
+ printf("No specific");
+ break;
+ case 1:
+ printf("ANSI X3.131-1986 (ANSI 1)");
+ break;
+ case 2:
+ printf("ANSI X3.131-1994 (ANSI 2)");
+ break;
+ case 3:
+ printf("ANSI INCITS 301-1997 (SPC)");
+ break;
+ case 4:
+ printf("ANSI INCITS 351-2001 (SPC-2)");
+ break;
+ case 5:
+ printf("ANSI INCITS 408-2005 (SPC-4)");
+ break;
+ case 6:
+ printf("T10/1731-D (SPC-4)");
+ break;
+ default:
+ printf("unknown");
+ }
+ printf(" standards.\r\n");
+#endif
+ uint8_t tries = 0xf0;
+ while((rcode = TestUnitReady(lun))) {
+ if(rcode == 0x08) break; // break on no media, this is OK to do.
+ // try to lock media and spin up
+ if(tries < 14) {
+ LockMedia(lun, 1);
+ MediaCTL(lun, 1); // I actually have a USB stick that needs this!
+ } else delay(2 * (tries + 1));
+ tries++;
+ if(!tries) break;
+ }
+ if(!rcode) {
+ delay(1000);
+ LUNOk[lun] = CheckLUN(lun);
+ if(!LUNOk[lun]) LUNOk[lun] = CheckLUN(lun);
+ }
+ }
+ }
+
+
+ CheckMedia();
+
+ rcode = OnInit();
+
+ if(rcode)
+ goto FailOnInit;
+
+#ifdef DEBUG_USB_HOST
+ USBTRACE("MS configured\r\n\r\n");
+#endif
+
+ bPollEnable = true;
+
+ //USBTRACE("Poll enabled\r\n");
+ return 0;
+
+FailSetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetConfDescr();
+ goto Fail;
+#endif
+
+FailOnInit:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("OnInit:");
+ goto Fail;
+#endif
+
+FailGetMaxLUN:
+#ifdef DEBUG_USB_HOST
+ USBTRACE("GetMaxLUN:");
+ goto Fail;
+#endif
+
+ //#ifdef DEBUG_USB_HOST
+ //FailInvalidSectorSize:
+ // USBTRACE("Sector Size is NOT VALID: ");
+ // goto Fail;
+ //#endif
+
+FailSetDevTblEntry:
+#ifdef DEBUG_USB_HOST
+ NotifyFailSetDevTblEntry();
+ goto Fail;
+#endif
+
+FailGetConfDescr:
+#ifdef DEBUG_USB_HOST
+ NotifyFailGetConfDescr();
+#endif
+
+#ifdef DEBUG_USB_HOST
+Fail:
+ NotifyFail(rcode);
+#endif
+ Release();
+ return rcode;
+}
+
+/**
+ * For driver use only.
+ *
+ * @param conf
+ * @param iface
+ * @param alt
+ * @param proto
+ * @param pep
+ */
+void BulkOnly::EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR * pep) {
+ ErrorMessage<uint8_t > (PSTR("Conf.Val"), conf);
+ ErrorMessage<uint8_t > (PSTR("Iface Num"), iface);
+ ErrorMessage<uint8_t > (PSTR("Alt.Set"), alt);
+
+ bConfNum = conf;
+
+ uint8_t index;
+
+#if 1
+ if((pep->bmAttributes & 0x02) == 2) {
+ index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
+ // Fill in the endpoint info structure
+ epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
+ epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
+ epInfo[index].epAttribs = 0;
+
+ bNumEP++;
+
+ PrintEndpointDescriptor(pep);
+
+ }
+#else
+ if((pep->bmAttributes & 0x03) == 3 && (pep->bEndpointAddress & 0x80) == 0x80)
+ index = epInterruptInIndex;
+ else
+ if((pep->bmAttributes & 0x02) == 2)
+ index = ((pep->bEndpointAddress & 0x80) == 0x80) ? epDataInIndex : epDataOutIndex;
+ else
+ return;
+
+ // Fill in the endpoint info structure
+ epInfo[index].epAddr = (pep->bEndpointAddress & 0x0F);
+ epInfo[index].maxPktSize = (uint8_t)pep->wMaxPacketSize;
+ epInfo[index].epAttribs = 0;
+
+ bNumEP++;
+
+ PrintEndpointDescriptor(pep);
+#endif
+}
+
+/**
+ * For driver use only.
+ *
+ * @return
+ */
+uint8_t BulkOnly::Release() {
+ ClearAllEP();
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+ return 0;
+}
+
+/**
+ * For driver use only.
+ *
+ * @param lun Logical Unit Number
+ * @return true if LUN is ready for use.
+ */
+bool BulkOnly::CheckLUN(uint8_t lun) {
+ uint8_t rcode;
+ Capacity capacity;
+ for(uint8_t i = 0; i < 8; i++) capacity.data[i] = 0;
+
+ rcode = ReadCapacity10(lun, (uint8_t*)capacity.data);
+ if(rcode) {
+ //printf(">>>>>>>>>>>>>>>>ReadCapacity returned %i\r\n", rcode);
+ return false;
+ }
+ ErrorMessage<uint8_t > (PSTR(">>>>>>>>>>>>>>>>CAPACITY OK ON LUN"), lun);
+ for(uint8_t i = 0; i < 8 /*sizeof (Capacity)*/; i++)
+ D_PrintHex<uint8_t > (capacity.data[i], 0x80);
+ Notify(PSTR("\r\n\r\n"), 0x80);
+ // Only 512/1024/2048/4096 are valid values!
+ uint32_t c = BMAKE32(capacity.data[4], capacity.data[5], capacity.data[6], capacity.data[7]);
+ if(c != 0x0200LU && c != 0x0400LU && c != 0x0800LU && c != 0x1000LU) {
+ return false;
+ }
+ // Store capacity information.
+ CurrentSectorSize[lun] = (uint16_t)(c); // & 0xFFFF);
+
+ CurrentCapacity[lun] = BMAKE32(capacity.data[0], capacity.data[1], capacity.data[2], capacity.data[3]) + 1;
+ if(CurrentCapacity[lun] == /*0xffffffffLU */ 0x01LU || CurrentCapacity[lun] == 0x00LU) {
+ // Buggy firmware will report 0xffffffff or 0 for no media
+ if(CurrentCapacity[lun])
+ ErrorMessage<uint8_t > (PSTR(">>>>>>>>>>>>>>>>BUGGY FIRMWARE. CAPACITY FAIL ON LUN"), lun);
+ return false;
+ }
+ delay(20);
+ Page3F(lun);
+ if(!TestUnitReady(lun)) return true;
+ return false;
+}
+
+/**
+ * For driver use only.
+ *
+ * Scan for media change on all LUNs
+ */
+void BulkOnly::CheckMedia() {
+ for(uint8_t lun = 0; lun <= bMaxLUN; lun++) {
+ if(TestUnitReady(lun)) {
+ LUNOk[lun] = false;
+ continue;
+ }
+ if(!LUNOk[lun])
+ LUNOk[lun] = CheckLUN(lun);
+ }
+#if 0
+ printf("}}}}}}}}}}}}}}}}STATUS ");
+ for(uint8_t lun = 0; lun <= bMaxLUN; lun++) {
+ if(LUNOk[lun])
+ printf("#");
+ else printf(".");
+ }
+ printf("\r\n");
+#endif
+ qNextPollTime = millis() + 2000;
+}
+
+/**
+ * For driver use only.
+ *
+ * @return
+ */
+uint8_t BulkOnly::Poll() {
+ //uint8_t rcode = 0;
+
+ if(!bPollEnable)
+ return 0;
+
+ if((long)(millis() - qNextPollTime) >= 0L) {
+ CheckMedia();
+ }
+ //rcode = 0;
+
+ return 0;
+}
+
+////////////////////////////////////////////////////////////////////////////////
+
+
+// SCSI code
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * For driver use only.
+ *
+ * @param plun
+ * @return
+ */
+uint8_t BulkOnly::GetMaxLUN(uint8_t *plun) {
+ uint8_t ret = pUsb->ctrlReq(bAddress, 0, bmREQ_MASSIN, MASS_REQ_GET_MAX_LUN, 0, 0, bIface, 1, 1, plun, NULL);
+
+ if(ret == hrSTALL)
+ *plun = 0;
+
+ return 0;
+}
+
+/**
+ * For driver use only. Used during Driver Init
+ *
+ * @param lun Logical Unit Number
+ * @param bsize
+ * @param buf
+ * @return
+ */
+uint8_t BulkOnly::Inquiry(uint8_t lun, uint16_t bsize, uint8_t *buf) {
+ Notify(PSTR("\r\nInquiry\r\n"), 0x80);
+ Notify(PSTR("---------\r\n"), 0x80);
+
+ CDB6_t cdb = CDB6_t(SCSI_CMD_INQUIRY, lun, 0LU, (uint8_t)bsize, 0);
+ uint8_t rc = SCSITransaction6(&cdb, bsize, buf, (uint8_t)MASS_CMD_DIR_IN);
+
+ return rc;
+}
+
+/**
+ * For driver use only.
+ *
+ * @param lun Logical Unit Number
+ * @return
+ */
+uint8_t BulkOnly::TestUnitReady(uint8_t lun) {
+ //SetCurLUN(lun);
+ if(!bAddress)
+ return MASS_ERR_UNIT_NOT_READY;
+
+ Notify(PSTR("\r\nTestUnitReady\r\n"), 0x80);
+ Notify(PSTR("-----------------\r\n"), 0x80);
+
+ CDB6_t cdb = CDB6_t(SCSI_CMD_TEST_UNIT_READY, lun, (uint8_t)0, 0);
+ return SCSITransaction6(&cdb, 0, NULL, (uint8_t)MASS_CMD_DIR_IN);
+
+}
+
+/**
+ * For driver use only.
+ *
+ * @param lun Logical Unit Number
+ * @param pc
+ * @param page
+ * @param subpage
+ * @param len
+ * @param pbuf
+ * @return
+ */
+uint8_t BulkOnly::ModeSense6(uint8_t lun, uint8_t pc, uint8_t page, uint8_t subpage, uint8_t len, uint8_t * pbuf) {
+ Notify(PSTR("\r\rModeSense\r\n"), 0x80);
+ Notify(PSTR("------------\r\n"), 0x80);
+
+ CDB6_t cdb = CDB6_t(SCSI_CMD_TEST_UNIT_READY, lun, (uint32_t)((((pc << 6) | page) << 8) | subpage), len, 0);
+ return SCSITransaction6(&cdb, len, pbuf, (uint8_t)MASS_CMD_DIR_IN);
+}
+
+/**
+ * For driver use only.
+ *
+ * @param lun Logical Unit Number
+ * @param bsize
+ * @param buf
+ * @return
+ */
+uint8_t BulkOnly::ReadCapacity10(uint8_t lun, uint8_t *buf) {
+ Notify(PSTR("\r\nReadCapacity\r\n"), 0x80);
+ Notify(PSTR("---------------\r\n"), 0x80);
+
+ CDB10_t cdb = CDB10_t(SCSI_CMD_READ_CAPACITY_10, lun);
+ return SCSITransaction10(&cdb, 8, buf, (uint8_t)MASS_CMD_DIR_IN);
+}
+
+/**
+ * For driver use only.
+ *
+ * Page 3F contains write protect status.
+ *
+ * @param lun Logical Unit Number to test.
+ * @return Write protect switch status.
+ */
+uint8_t BulkOnly::Page3F(uint8_t lun) {
+ uint8_t buf[192];
+ for(int i = 0; i < 192; i++) {
+ buf[i] = 0x00;
+ }
+ WriteOk[lun] = true;
+ uint8_t rc = ModeSense6(lun, 0, 0x3f, 0, 192, buf);
+ if(!rc) {
+ WriteOk[lun] = ((buf[2] & 0x80) == 0);
+ Notify(PSTR("Mode Sense: "), 0x80);
+ for(int i = 0; i < 4; i++) {
+ D_PrintHex<uint8_t > (buf[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+ }
+ return rc;
+}
+
+/**
+ * For driver use only.
+ *
+ * @param lun Logical Unit Number
+ * @param size
+ * @param buf
+ * @return
+ */
+uint8_t BulkOnly::RequestSense(uint8_t lun, uint16_t size, uint8_t *buf) {
+ Notify(PSTR("\r\nRequestSense\r\n"), 0x80);
+ Notify(PSTR("----------------\r\n"), 0x80);
+
+ CDB6_t cdb = CDB6_t(SCSI_CMD_REQUEST_SENSE, lun, 0LU, (uint8_t)size, 0);
+ CommandBlockWrapper cbw = CommandBlockWrapper(++dCBWTag, (uint32_t)size, &cdb, (uint8_t)MASS_CMD_DIR_IN);
+ //SetCurLUN(lun);
+ return Transaction(&cbw, size, buf);
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+
+// USB code
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+/**
+ * For driver use only.
+ *
+ * @param index
+ * @return
+ */
+uint8_t BulkOnly::ClearEpHalt(uint8_t index) {
+ if(index == 0)
+ return 0;
+
+ uint8_t ret = 0;
+
+ while((ret = (pUsb->ctrlReq(bAddress, 0, USB_SETUP_HOST_TO_DEVICE | USB_SETUP_TYPE_STANDARD | USB_SETUP_RECIPIENT_ENDPOINT, USB_REQUEST_CLEAR_FEATURE, USB_FEATURE_ENDPOINT_HALT, 0, ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr), 0, 0, NULL, NULL)) == 0x01))
+ delay(6);
+
+ if(ret) {
+ ErrorMessage<uint8_t > (PSTR("ClearEpHalt"), ret);
+ ErrorMessage<uint8_t > (PSTR("EP"), ((index == epDataInIndex) ? (0x80 | epInfo[index].epAddr) : epInfo[index].epAddr));
+ return ret;
+ }
+ epInfo[index].bmSndToggle = 0;
+ epInfo[index].bmRcvToggle = 0;
+ // epAttribs = 0;
+ return 0;
+}
+
+/**
+ * For driver use only.
+ *
+ */
+void BulkOnly::Reset() {
+ while(pUsb->ctrlReq(bAddress, 0, bmREQ_MASSOUT, MASS_REQ_BOMSR, 0, 0, bIface, 0, 0, NULL, NULL) == 0x01) delay(6);
+}
+
+/**
+ * For driver use only.
+ *
+ * @return 0 if successful
+ */
+uint8_t BulkOnly::ResetRecovery() {
+ Notify(PSTR("\r\nResetRecovery\r\n"), 0x80);
+ Notify(PSTR("-----------------\r\n"), 0x80);
+
+ delay(6);
+ Reset();
+ delay(6);
+ ClearEpHalt(epDataInIndex);
+ delay(6);
+ bLastUsbError = ClearEpHalt(epDataOutIndex);
+ delay(6);
+ return bLastUsbError;
+}
+
+/**
+ * For driver use only.
+ *
+ * Clear all EP data and clear all LUN status
+ */
+void BulkOnly::ClearAllEP() {
+ for(uint8_t i = 0; i < MASS_MAX_ENDPOINTS; i++) {
+ epInfo[i].epAddr = 0;
+ epInfo[i].maxPktSize = (i) ? 0 : 8;
+ epInfo[i].epAttribs = 0;
+
+ epInfo[i].bmNakPower = USB_NAK_DEFAULT;
+ }
+
+ for(uint8_t i = 0; i < MASS_MAX_SUPPORTED_LUN; i++) {
+ LUNOk[i] = false;
+ WriteOk[i] = false;
+ CurrentCapacity[i] = 0lu;
+ CurrentSectorSize[i] = 0;
+ }
+
+ bIface = 0;
+ bNumEP = 1;
+ bAddress = 0;
+ qNextPollTime = 0;
+ bPollEnable = false;
+ bLastUsbError = 0;
+ bMaxLUN = 0;
+ bTheLUN = 0;
+}
+
+/**
+ * For driver use only.
+ *
+ * @param pcsw
+ * @param pcbw
+ * @return
+ */
+bool BulkOnly::IsValidCSW(CommandStatusWrapper *pcsw, CommandBlockWrapperBase *pcbw) {
+ if(pcsw->dCSWSignature != MASS_CSW_SIGNATURE) {
+ Notify(PSTR("CSW:Sig error\r\n"), 0x80);
+ return false;
+ }
+ if(pcsw->dCSWTag != pcbw->dCBWTag) {
+ Notify(PSTR("CSW:Wrong tag\r\n"), 0x80);
+ return false;
+ }
+ return true;
+}
+
+/**
+ * For driver use only.
+ *
+ * @param error
+ * @param index
+ * @return
+ */
+uint8_t BulkOnly::HandleUsbError(uint8_t error, uint8_t index) {
+ uint8_t count = 3;
+
+ bLastUsbError = error;
+ //if (error)
+ //ClearEpHalt(index);
+ while(error && count) {
+ if(error != hrSUCCESS) {
+ ErrorMessage<uint8_t > (PSTR("USB Error"), error);
+ ErrorMessage<uint8_t > (PSTR("Index"), index);
+ }
+ switch(error) {
+ // case hrWRONGPID:
+ case hrSUCCESS:
+ return MASS_ERR_SUCCESS;
+ case hrBUSY:
+ // SIE is busy, just hang out and try again.
+ return MASS_ERR_UNIT_BUSY;
+ case hrTIMEOUT:
+ case hrJERR: return MASS_ERR_DEVICE_DISCONNECTED;
+ case hrSTALL:
+ if(index == 0)
+ return MASS_ERR_STALL;
+ ClearEpHalt(index);
+ if(index != epDataInIndex)
+ return MASS_ERR_WRITE_STALL;
+ return MASS_ERR_STALL;
+
+ case hrNAK:
+ if(index == 0)
+ return MASS_ERR_UNIT_BUSY;
+ return MASS_ERR_UNIT_BUSY;
+
+ case hrTOGERR:
+ // Handle a very super rare corner case, where toggles become de-synched.
+ // I have only ran into one device that has this firmware bug, and this is
+ // the only clean way to get back into sync with the buggy device firmware.
+ // --AJK
+ if(bAddress && bConfNum) {
+ error = pUsb->setConf(bAddress, 0, bConfNum);
+
+ if(error)
+ break;
+ }
+ return MASS_ERR_SUCCESS;
+ default:
+ ErrorMessage<uint8_t > (PSTR("\r\nUSB"), error);
+ return MASS_ERR_GENERAL_USB_ERROR;
+ }
+ count--;
+ } // while
+
+ return ((error && !count) ? MASS_ERR_GENERAL_USB_ERROR : MASS_ERR_SUCCESS);
+}
+
+#if MS_WANT_PARSER
+
+uint8_t BulkOnly::Transaction(CommandBlockWrapper *pcbw, uint16_t buf_size, void *buf) {
+ return Transaction(CommandBlockWrapper *pcbw, uint16_t buf_size, void *buf, 0);
+}
+#endif
+
+/**
+ * For driver use only.
+ *
+ * @param pcbw
+ * @param buf_size
+ * @param buf
+ * @param flags
+ * @return
+ */
+uint8_t BulkOnly::Transaction(CommandBlockWrapper *pcbw, uint16_t buf_size, void *buf
+#if MS_WANT_PARSER
+ , uint8_t flags
+#endif
+ ) {
+
+#if MS_WANT_PARSER
+ uint16_t bytes = (pcbw->dCBWDataTransferLength > buf_size) ? buf_size : pcbw->dCBWDataTransferLength;
+ printf("Transfersize %i\r\n", bytes);
+ delay(1000);
+
+ bool callback = (flags & MASS_TRANS_FLG_CALLBACK) == MASS_TRANS_FLG_CALLBACK;
+#else
+ uint16_t bytes = buf_size;
+#endif
+ bool write = (pcbw->bmCBWFlags & MASS_CMD_DIR_IN) != MASS_CMD_DIR_IN;
+ uint8_t ret = 0;
+ uint8_t usberr;
+ CommandStatusWrapper csw; // up here, we allocate ahead to save cpu cycles.
+ SetCurLUN(pcbw->bmCBWLUN);
+ ErrorMessage<uint32_t > (PSTR("CBW.dCBWTag"), pcbw->dCBWTag);
+
+ while((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (CommandBlockWrapper), (uint8_t*)pcbw)) == hrBUSY) delay(1);
+
+ ret = HandleUsbError(usberr, epDataOutIndex);
+ //ret = HandleUsbError(pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, sizeof (CommandBlockWrapper), (uint8_t*)pcbw), epDataOutIndex);
+ if(ret) {
+ ErrorMessage<uint8_t > (PSTR("============================ CBW"), ret);
+ } else {
+ if(bytes) {
+ if(!write) {
+#if MS_WANT_PARSER
+ if(callback) {
+ uint8_t rbuf[bytes];
+ while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, rbuf)) == hrBUSY) delay(1);
+ if(usberr == hrSUCCESS) ((USBReadParser*)buf)->Parse(bytes, rbuf, 0);
+ } else {
+#endif
+ while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*)buf)) == hrBUSY) delay(1);
+#if MS_WANT_PARSER
+
+ }
+#endif
+ ret = HandleUsbError(usberr, epDataInIndex);
+ } else {
+ while((usberr = pUsb->outTransfer(bAddress, epInfo[epDataOutIndex].epAddr, bytes, (uint8_t*)buf)) == hrBUSY) delay(1);
+ ret = HandleUsbError(usberr, epDataOutIndex);
+ }
+ if(ret) {
+ ErrorMessage<uint8_t > (PSTR("============================ DAT"), ret);
+ }
+ }
+ }
+
+ {
+ bytes = sizeof (CommandStatusWrapper);
+ int tries = 2;
+ while(tries--) {
+ while((usberr = pUsb->inTransfer(bAddress, epInfo[epDataInIndex].epAddr, &bytes, (uint8_t*) & csw)) == hrBUSY) delay(1);
+ if(!usberr) break;
+ ClearEpHalt(epDataInIndex);
+ if(tries) ResetRecovery();
+ }
+ if(!ret) {
+ Notify(PSTR("CBW:\t\tOK\r\n"), 0x80);
+ Notify(PSTR("Data Stage:\tOK\r\n"), 0x80);
+ } else {
+ // Throw away csw, IT IS NOT OF ANY USE.
+ ResetRecovery();
+ return ret;
+ }
+ ret = HandleUsbError(usberr, epDataInIndex);
+ if(ret) {
+ ErrorMessage<uint8_t > (PSTR("============================ CSW"), ret);
+ }
+ if(usberr == hrSUCCESS) {
+ if(IsValidCSW(&csw, pcbw)) {
+ //ErrorMessage<uint32_t > (PSTR("CSW.dCBWTag"), csw.dCSWTag);
+ //ErrorMessage<uint8_t > (PSTR("bCSWStatus"), csw.bCSWStatus);
+ //ErrorMessage<uint32_t > (PSTR("dCSWDataResidue"), csw.dCSWDataResidue);
+ Notify(PSTR("CSW:\t\tOK\r\n\r\n"), 0x80);
+ return csw.bCSWStatus;
+ } else {
+ // NOTE! Sometimes this is caused by the reported residue being wrong.
+ // Get a different device. It isn't compliant, and should have never passed Q&A.
+ // I own one... 05e3:0701 Genesys Logic, Inc. USB 2.0 IDE Adapter.
+ // Other devices that exhibit this behavior exist in the wild too.
+ // Be sure to check quirks in the Linux source code before reporting a bug. --xxxajk
+ Notify(PSTR("Invalid CSW\r\n"), 0x80);
+ ResetRecovery();
+ //return MASS_ERR_SUCCESS;
+ return MASS_ERR_INVALID_CSW;
+ }
+ }
+ }
+ return ret;
+}
+
+/**
+ * For driver use only.
+ *
+ * @param lun Logical Unit Number
+ * @return
+ */
+uint8_t BulkOnly::SetCurLUN(uint8_t lun) {
+ if(lun > bMaxLUN)
+ return MASS_ERR_INVALID_LUN;
+ bTheLUN = lun;
+ return MASS_ERR_SUCCESS;
+};
+
+/**
+ * For driver use only.
+ *
+ * @param status
+ * @return
+ */
+uint8_t BulkOnly::HandleSCSIError(uint8_t status) {
+ uint8_t ret = 0;
+
+ switch(status) {
+ case 0: return MASS_ERR_SUCCESS;
+
+ case 2:
+ ErrorMessage<uint8_t > (PSTR("Phase Error"), status);
+ ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN);
+ ResetRecovery();
+ return MASS_ERR_GENERAL_SCSI_ERROR;
+
+ case 1:
+ ErrorMessage<uint8_t > (PSTR("SCSI Error"), status);
+ ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN);
+ RequestSenseResponce rsp;
+
+ ret = RequestSense(bTheLUN, sizeof (RequestSenseResponce), (uint8_t*) & rsp);
+
+ if(ret) {
+ return MASS_ERR_GENERAL_SCSI_ERROR;
+ }
+ ErrorMessage<uint8_t > (PSTR("Response Code"), rsp.bResponseCode);
+ if(rsp.bResponseCode & 0x80) {
+ Notify(PSTR("Information field: "), 0x80);
+ for(int i = 0; i < 4; i++) {
+ D_PrintHex<uint8_t > (rsp.CmdSpecificInformation[i], 0x80);
+ Notify(PSTR(" "), 0x80);
+ }
+ Notify(PSTR("\r\n"), 0x80);
+ }
+ ErrorMessage<uint8_t > (PSTR("Sense Key"), rsp.bmSenseKey);
+ ErrorMessage<uint8_t > (PSTR("Add Sense Code"), rsp.bAdditionalSenseCode);
+ ErrorMessage<uint8_t > (PSTR("Add Sense Qual"), rsp.bAdditionalSenseQualifier);
+ // warning, this is not testing ASQ, only SK and ASC.
+ switch(rsp.bmSenseKey) {
+ case SCSI_S_UNIT_ATTENTION:
+ switch(rsp.bAdditionalSenseCode) {
+ case SCSI_ASC_MEDIA_CHANGED:
+ return MASS_ERR_MEDIA_CHANGED;
+ default:
+ return MASS_ERR_UNIT_NOT_READY;
+ }
+ case SCSI_S_NOT_READY:
+ switch(rsp.bAdditionalSenseCode) {
+ case SCSI_ASC_MEDIUM_NOT_PRESENT:
+ return MASS_ERR_NO_MEDIA;
+ default:
+ return MASS_ERR_UNIT_NOT_READY;
+ }
+ case SCSI_S_ILLEGAL_REQUEST:
+ switch(rsp.bAdditionalSenseCode) {
+ case SCSI_ASC_LBA_OUT_OF_RANGE:
+ return MASS_ERR_BAD_LBA;
+ default:
+ return MASS_ERR_CMD_NOT_SUPPORTED;
+ }
+ default:
+ return MASS_ERR_GENERAL_SCSI_ERROR;
+ }
+
+ // case 4: return MASS_ERR_UNIT_BUSY; // Busy means retry later.
+ // case 0x05/0x14: we stalled out
+ // case 0x15/0x16: we naked out.
+ default:
+ ErrorMessage<uint8_t > (PSTR("Gen SCSI Err"), status);
+ ErrorMessage<uint8_t > (PSTR("LUN"), bTheLUN);
+ return status;
+ } // switch
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+
+// Debugging code
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+/**
+ *
+ * @param ep_ptr
+ */
+void BulkOnly::PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR * ep_ptr) {
+ Notify(PSTR("Endpoint descriptor:"), 0x80);
+ Notify(PSTR("\r\nLength:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bLength, 0x80);
+ Notify(PSTR("\r\nType:\t\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bDescriptorType, 0x80);
+ Notify(PSTR("\r\nAddress:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bEndpointAddress, 0x80);
+ Notify(PSTR("\r\nAttributes:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bmAttributes, 0x80);
+ Notify(PSTR("\r\nMaxPktSize:\t"), 0x80);
+ D_PrintHex<uint16_t > (ep_ptr->wMaxPacketSize, 0x80);
+ Notify(PSTR("\r\nPoll Intrv:\t"), 0x80);
+ D_PrintHex<uint8_t > (ep_ptr->bInterval, 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+}
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+
+// misc/to kill/to-do
+
+
+////////////////////////////////////////////////////////////////////////////////
+
+/* We won't be needing this... */
+uint8_t BulkOnly::Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, USBReadParser * prs) {
+#if MS_WANT_PARSER
+ if(!LUNOk[lun]) return MASS_ERR_NO_MEDIA;
+ Notify(PSTR("\r\nRead (With parser)\r\n"), 0x80);
+ Notify(PSTR("---------\r\n"), 0x80);
+
+ CommandBlockWrapper cbw = CommandBlockWrapper();
+
+ cbw.dCBWSignature = MASS_CBW_SIGNATURE;
+ cbw.dCBWTag = ++dCBWTag;
+ cbw.dCBWDataTransferLength = ((uint32_t)bsize * blocks);
+ cbw.bmCBWFlags = MASS_CMD_DIR_IN,
+ cbw.bmCBWLUN = lun;
+ cbw.bmCBWCBLength = 10;
+
+ cbw.CBWCB[0] = SCSI_CMD_READ_10;
+ cbw.CBWCB[8] = blocks;
+ cbw.CBWCB[2] = ((addr >> 24) & 0xff);
+ cbw.CBWCB[3] = ((addr >> 16) & 0xff);
+ cbw.CBWCB[4] = ((addr >> 8) & 0xff);
+ cbw.CBWCB[5] = (addr & 0xff);
+
+ return HandleSCSIError(Transaction(&cbw, bsize, prs, 1));
+#else
+ return MASS_ERR_NOT_IMPLEMENTED;
+#endif
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/masstorage.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/masstorage.h
new file mode 100644
index 000000000..d39fd66f3
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/masstorage.h
@@ -0,0 +1,571 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#if !defined(__MASSTORAGE_H__)
+#define __MASSTORAGE_H__
+
+// Cruft removal, makes driver smaller, faster.
+#ifndef MS_WANT_PARSER
+#define MS_WANT_PARSER 0
+#endif
+
+#include "Usb.h"
+
+#define bmREQ_MASSOUT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
+#define bmREQ_MASSIN USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_INTERFACE
+
+// Mass Storage Subclass Constants
+#define MASS_SUBCLASS_SCSI_NOT_REPORTED 0x00 // De facto use
+#define MASS_SUBCLASS_RBC 0x01
+#define MASS_SUBCLASS_ATAPI 0x02 // MMC-5 (ATAPI)
+#define MASS_SUBCLASS_OBSOLETE1 0x03 // Was QIC-157
+#define MASS_SUBCLASS_UFI 0x04 // Specifies how to interface Floppy Disk Drives to USB
+#define MASS_SUBCLASS_OBSOLETE2 0x05 // Was SFF-8070i
+#define MASS_SUBCLASS_SCSI 0x06 // SCSI Transparent Command Set
+#define MASS_SUBCLASS_LSDFS 0x07 // Specifies how host has to negotiate access before trying SCSI
+#define MASS_SUBCLASS_IEEE1667 0x08
+
+// Mass Storage Class Protocols
+#define MASS_PROTO_CBI 0x00 // CBI (with command completion interrupt)
+#define MASS_PROTO_CBI_NO_INT 0x01 // CBI (without command completion interrupt)
+#define MASS_PROTO_OBSOLETE 0x02
+#define MASS_PROTO_BBB 0x50 // Bulk Only Transport
+#define MASS_PROTO_UAS 0x62
+
+// Request Codes
+#define MASS_REQ_ADSC 0x00
+#define MASS_REQ_GET 0xFC
+#define MASS_REQ_PUT 0xFD
+#define MASS_REQ_GET_MAX_LUN 0xFE
+#define MASS_REQ_BOMSR 0xFF // Bulk-Only Mass Storage Reset
+
+#define MASS_CBW_SIGNATURE 0x43425355
+#define MASS_CSW_SIGNATURE 0x53425355
+
+#define MASS_CMD_DIR_OUT 0 // (0 << 7)
+#define MASS_CMD_DIR_IN 0x80 //(1 << 7)
+
+/*
+ * Reference documents from T10 (http://www.t10.org)
+ * SCSI Primary Commands - 3 (SPC-3)
+ * SCSI Block Commands - 2 (SBC-2)
+ * Multi-Media Commands - 5 (MMC-5)
+ */
+
+/* Group 1 commands (CDB's here are should all be 6-bytes) */
+#define SCSI_CMD_TEST_UNIT_READY 0x00
+#define SCSI_CMD_REQUEST_SENSE 0x03
+#define SCSI_CMD_FORMAT_UNIT 0x04
+#define SCSI_CMD_READ_6 0x08
+#define SCSI_CMD_WRITE_6 0x0A
+#define SCSI_CMD_INQUIRY 0x12
+#define SCSI_CMD_MODE_SELECT_6 0x15
+#define SCSI_CMD_MODE_SENSE_6 0x1A
+#define SCSI_CMD_START_STOP_UNIT 0x1B
+#define SCSI_CMD_PREVENT_REMOVAL 0x1E
+/* Group 2 Commands (CDB's here are 10-bytes) */
+#define SCSI_CMD_READ_FORMAT_CAPACITIES 0x23
+#define SCSI_CMD_READ_CAPACITY_10 0x25
+#define SCSI_CMD_READ_10 0x28
+#define SCSI_CMD_WRITE_10 0x2A
+#define SCSI_CMD_SEEK_10 0x2B
+#define SCSI_CMD_ERASE_10 0x2C
+#define SCSI_CMD_WRITE_AND_VERIFY_10 0x2E
+#define SCSI_CMD_VERIFY_10 0x2F
+#define SCSI_CMD_SYNCHRONIZE_CACHE 0x35
+#define SCSI_CMD_WRITE_BUFFER 0x3B
+#define SCSI_CMD_READ_BUFFER 0x3C
+#define SCSI_CMD_READ_SUBCHANNEL 0x42
+#define SCSI_CMD_READ_TOC 0x43
+#define SCSI_CMD_READ_HEADER 0x44
+#define SCSI_CMD_PLAY_AUDIO_10 0x45
+#define SCSI_CMD_GET_CONFIGURATION 0x46
+#define SCSI_CMD_PLAY_AUDIO_MSF 0x47
+#define SCSI_CMD_PLAY_AUDIO_TI 0x48
+#define SCSI_CMD_PLAY_TRACK_REL_10 0x49
+#define SCSI_CMD_GET_EVENT_STATUS 0x4A
+#define SCSI_CMD_PAUSE_RESUME 0x4B
+#define SCSI_CMD_READ_DISC_INFORMATION 0x51
+#define SCSI_CMD_READ_TRACK_INFORMATION 0x52
+#define SCSI_CMD_RESERVE_TRACK 0x53
+#define SCSI_CMD_SEND_OPC_INFORMATION 0x54
+#define SCSI_CMD_MODE_SELECT_10 0x55
+#define SCSI_CMD_REPAIR_TRACK 0x58
+#define SCSI_CMD_MODE_SENSE_10 0x5A
+#define SCSI_CMD_CLOSE_TRACK_SESSION 0x5B
+#define SCSI_CMD_READ_BUFFER_CAPACITY 0x5C
+#define SCSI_CMD_SEND_CUE_SHEET 0x5D
+/* Group 5 Commands (CDB's here are 12-bytes) */
+#define SCSI_CMD_REPORT_LUNS 0xA0
+#define SCSI_CMD_BLANK 0xA1
+#define SCSI_CMD_SECURITY_PROTOCOL_IN 0xA2
+#define SCSI_CMD_SEND_KEY 0xA3
+#define SCSI_CMD_REPORT_KEY 0xA4
+#define SCSI_CMD_PLAY_AUDIO_12 0xA5
+#define SCSI_CMD_LOAD_UNLOAD 0xA6
+#define SCSI_CMD_SET_READ_AHEAD 0xA7
+#define SCSI_CMD_READ_12 0xA8
+#define SCSI_CMD_PLAY_TRACK_REL_12 0xA9
+#define SCSI_CMD_WRITE_12 0xAA
+#define SCSI_CMD_READ_MEDIA_SERIAL_12 0xAB
+#define SCSI_CMD_GET_PERFORMANCE 0xAC
+#define SCSI_CMD_READ_DVD_STRUCTURE 0xAD
+#define SCSI_CMD_SECURITY_PROTOCOL_OUT 0xB5
+#define SCSI_CMD_SET_STREAMING 0xB6
+#define SCSI_CMD_READ_MSF 0xB9
+#define SCSI_CMD_SET_SPEED 0xBB
+#define SCSI_CMD_MECHANISM_STATUS 0xBD
+#define SCSI_CMD_READ_CD 0xBE
+#define SCSI_CMD_SEND_DISC_STRUCTURE 0xBF
+/* Vendor-unique Commands, included for completeness */
+#define SCSI_CMD_CD_PLAYBACK_STATUS 0xC4 /* SONY unique */
+#define SCSI_CMD_PLAYBACK_CONTROL 0xC9 /* SONY unique */
+#define SCSI_CMD_READ_CDDA 0xD8 /* Vendor unique */
+#define SCSI_CMD_READ_CDXA 0xDB /* Vendor unique */
+#define SCSI_CMD_READ_ALL_SUBCODES 0xDF /* Vendor unique */
+
+/* SCSI error codes */
+#define SCSI_S_NOT_READY 0x02
+#define SCSI_S_MEDIUM_ERROR 0x03
+#define SCSI_S_ILLEGAL_REQUEST 0x05
+#define SCSI_S_UNIT_ATTENTION 0x06
+#define SCSI_ASC_LBA_OUT_OF_RANGE 0x21
+#define SCSI_ASC_MEDIA_CHANGED 0x28
+#define SCSI_ASC_MEDIUM_NOT_PRESENT 0x3A
+
+/* USB error codes */
+#define MASS_ERR_SUCCESS 0x00
+#define MASS_ERR_PHASE_ERROR 0x02
+#define MASS_ERR_UNIT_NOT_READY 0x03
+#define MASS_ERR_UNIT_BUSY 0x04
+#define MASS_ERR_STALL 0x05
+#define MASS_ERR_CMD_NOT_SUPPORTED 0x06
+#define MASS_ERR_INVALID_CSW 0x07
+#define MASS_ERR_NO_MEDIA 0x08
+#define MASS_ERR_BAD_LBA 0x09
+#define MASS_ERR_MEDIA_CHANGED 0x0A
+#define MASS_ERR_DEVICE_DISCONNECTED 0x11
+#define MASS_ERR_UNABLE_TO_RECOVER 0x12 // Reset recovery error
+#define MASS_ERR_INVALID_LUN 0x13
+#define MASS_ERR_WRITE_STALL 0x14
+#define MASS_ERR_READ_NAKS 0x15
+#define MASS_ERR_WRITE_NAKS 0x16
+#define MASS_ERR_WRITE_PROTECTED 0x17
+#define MASS_ERR_NOT_IMPLEMENTED 0xFD
+#define MASS_ERR_GENERAL_SCSI_ERROR 0xFE
+#define MASS_ERR_GENERAL_USB_ERROR 0xFF
+#define MASS_ERR_USER 0xA0 // For subclasses to define their own error codes
+
+#define MASS_TRANS_FLG_CALLBACK 0x01 // Callback is involved
+#define MASS_TRANS_FLG_NO_STALL_CHECK 0x02 // STALL condition is not checked
+#define MASS_TRANS_FLG_NO_PHASE_CHECK 0x04 // PHASE_ERROR is not checked
+
+#define MASS_MAX_ENDPOINTS 3
+
+struct Capacity {
+ uint8_t data[8];
+ //uint32_t dwBlockAddress;
+ //uint32_t dwBlockLength;
+} __attribute__((packed));
+
+struct BASICCDB {
+ uint8_t Opcode;
+
+ unsigned unused : 5;
+ unsigned LUN : 3;
+
+ uint8_t info[12];
+} __attribute__((packed));
+
+typedef BASICCDB BASICCDB_t;
+
+struct CDB6 {
+ uint8_t Opcode;
+
+ unsigned LBAMSB : 5;
+ unsigned LUN : 3;
+
+ uint8_t LBAHB;
+ uint8_t LBALB;
+ uint8_t AllocationLength;
+ uint8_t Control;
+
+public:
+
+ CDB6(uint8_t _Opcode, uint8_t _LUN, uint32_t LBA, uint8_t _AllocationLength, uint8_t _Control) :
+ Opcode(_Opcode), LBAMSB(BGRAB2(LBA) & 0x1f), LUN(_LUN), LBAHB(BGRAB1(LBA)), LBALB(BGRAB0(LBA)),
+ AllocationLength(_AllocationLength), Control(_Control) {
+ }
+
+ CDB6(uint8_t _Opcode, uint8_t _LUN, uint8_t _AllocationLength, uint8_t _Control) :
+ Opcode(_Opcode), LBAMSB(0), LUN(_LUN), LBAHB(0), LBALB(0),
+ AllocationLength(_AllocationLength), Control(_Control) {
+ }
+} __attribute__((packed));
+
+typedef CDB6 CDB6_t;
+
+struct CDB10 {
+ uint8_t Opcode;
+
+ unsigned Service_Action : 5;
+ unsigned LUN : 3;
+
+ uint8_t LBA_L_M_MB;
+ uint8_t LBA_L_M_LB;
+ uint8_t LBA_L_L_MB;
+ uint8_t LBA_L_L_LB;
+
+ uint8_t Misc2;
+
+ uint8_t ALC_MB;
+ uint8_t ALC_LB;
+
+ uint8_t Control;
+public:
+
+ CDB10(uint8_t _Opcode, uint8_t _LUN) :
+ Opcode(_Opcode), Service_Action(0), LUN(_LUN),
+ LBA_L_M_MB(0), LBA_L_M_LB(0), LBA_L_L_MB(0), LBA_L_L_LB(0),
+ Misc2(0), ALC_MB(0), ALC_LB(0), Control(0) {
+ }
+
+ CDB10(uint8_t _Opcode, uint8_t _LUN, uint16_t xflen, uint32_t _LBA) :
+ Opcode(_Opcode), Service_Action(0), LUN(_LUN),
+ LBA_L_M_MB(BGRAB3(_LBA)), LBA_L_M_LB(BGRAB2(_LBA)), LBA_L_L_MB(BGRAB1(_LBA)), LBA_L_L_LB(BGRAB0(_LBA)),
+ Misc2(0), ALC_MB(BGRAB1(xflen)), ALC_LB(BGRAB0(xflen)), Control(0) {
+ }
+} __attribute__((packed));
+
+typedef CDB10 CDB10_t;
+
+struct CDB12 {
+ uint8_t Opcode;
+
+ unsigned Service_Action : 5;
+ unsigned Misc : 3;
+
+ uint8_t LBA_L_M_LB;
+ uint8_t LBA_L_L_MB;
+ uint8_t LBA_L_L_LB;
+
+ uint8_t ALC_M_LB;
+ uint8_t ALC_L_MB;
+ uint8_t ALC_L_LB;
+ uint8_t Control;
+} __attribute__((packed));
+
+typedef CDB12 CDB12_t;
+
+struct CDB_LBA32_16 {
+ uint8_t Opcode;
+
+ unsigned Service_Action : 5;
+ unsigned Misc : 3;
+
+ uint8_t LBA_L_M_MB;
+ uint8_t LBA_L_M_LB;
+ uint8_t LBA_L_L_MB;
+ uint8_t LBA_L_L_LB;
+
+ uint8_t A_M_M_MB;
+ uint8_t A_M_M_LB;
+ uint8_t A_M_L_MB;
+ uint8_t A_M_L_LB;
+
+ uint8_t ALC_M_MB;
+ uint8_t ALC_M_LB;
+ uint8_t ALC_L_MB;
+ uint8_t ALC_L_LB;
+
+ uint8_t Misc2;
+ uint8_t Control;
+} __attribute__((packed));
+
+struct CDB_LBA64_16 {
+ uint8_t Opcode;
+ uint8_t Misc;
+
+ uint8_t LBA_M_M_MB;
+ uint8_t LBA_M_M_LB;
+ uint8_t LBA_M_L_MB;
+ uint8_t LBA_M_L_LB;
+
+ uint8_t LBA_L_M_MB;
+ uint8_t LBA_L_M_LB;
+ uint8_t LBA_L_L_MB;
+ uint8_t LBA_L_L_LB;
+
+ uint8_t ALC_M_MB;
+ uint8_t ALC_M_LB;
+ uint8_t ALC_L_MB;
+ uint8_t ALC_L_LB;
+
+ uint8_t Misc2;
+ uint8_t Control;
+} __attribute__((packed));
+
+struct InquiryResponse {
+ uint8_t DeviceType : 5;
+ uint8_t PeripheralQualifier : 3;
+
+ unsigned Reserved : 7;
+ unsigned Removable : 1;
+
+ uint8_t Version;
+
+ unsigned ResponseDataFormat : 4;
+ unsigned HISUP : 1;
+ unsigned NormACA : 1;
+ unsigned TrmTsk : 1;
+ unsigned AERC : 1;
+
+ uint8_t AdditionalLength;
+ //uint8_t Reserved3[2];
+
+ unsigned PROTECT : 1;
+ unsigned Res : 2;
+ unsigned ThreePC : 1;
+ unsigned TPGS : 2;
+ unsigned ACC : 1;
+ unsigned SCCS : 1;
+
+ unsigned ADDR16 : 1;
+ unsigned R1 : 1;
+ unsigned R2 : 1;
+ unsigned MCHNGR : 1;
+ unsigned MULTIP : 1;
+ unsigned VS : 1;
+ unsigned ENCSERV : 1;
+ unsigned BQUE : 1;
+
+ unsigned SoftReset : 1;
+ unsigned CmdQue : 1;
+ unsigned Reserved4 : 1;
+ unsigned Linked : 1;
+ unsigned Sync : 1;
+ unsigned WideBus16Bit : 1;
+ unsigned WideBus32Bit : 1;
+ unsigned RelAddr : 1;
+
+ uint8_t VendorID[8];
+ uint8_t ProductID[16];
+ uint8_t RevisionID[4];
+} __attribute__((packed));
+
+struct CommandBlockWrapperBase {
+ uint32_t dCBWSignature;
+ uint32_t dCBWTag;
+ uint32_t dCBWDataTransferLength;
+ uint8_t bmCBWFlags;
+public:
+
+ CommandBlockWrapperBase() {
+ }
+
+ CommandBlockWrapperBase(uint32_t tag, uint32_t xflen, uint8_t flgs) :
+ dCBWSignature(MASS_CBW_SIGNATURE), dCBWTag(tag), dCBWDataTransferLength(xflen), bmCBWFlags(flgs) {
+ }
+} __attribute__((packed));
+
+struct CommandBlockWrapper : public CommandBlockWrapperBase {
+
+ struct {
+ uint8_t bmCBWLUN : 4;
+ uint8_t bmReserved1 : 4;
+ };
+
+ struct {
+ uint8_t bmCBWCBLength : 4;
+ uint8_t bmReserved2 : 4;
+ };
+
+ uint8_t CBWCB[16];
+
+public:
+ // All zeroed.
+
+ CommandBlockWrapper() :
+ CommandBlockWrapperBase(0, 0, 0), bmReserved1(0), bmReserved2(0) {
+ for(int i = 0; i < 16; i++) CBWCB[i] = 0;
+ }
+
+ // Generic Wrap, CDB zeroed.
+
+ CommandBlockWrapper(uint32_t tag, uint32_t xflen, uint8_t flgs, uint8_t lu, uint8_t cmdlen, uint8_t cmd) :
+ CommandBlockWrapperBase(tag, xflen, flgs),
+ bmCBWLUN(lu), bmReserved1(0), bmCBWCBLength(cmdlen), bmReserved2(0) {
+ for(int i = 0; i < 16; i++) CBWCB[i] = 0;
+ // Type punning can cause optimization problems and bugs.
+ // Using reinterpret_cast to a dreinterpretifferent object is the proper way to do this.
+ //(((BASICCDB_t *) CBWCB)->LUN) = cmd;
+ BASICCDB_t *x = reinterpret_cast<BASICCDB_t *>(CBWCB);
+ x->LUN = cmd;
+ }
+
+ // Wrap for CDB of 6
+
+ CommandBlockWrapper(uint32_t tag, uint32_t xflen, CDB6_t *cdb, uint8_t dir) :
+ CommandBlockWrapperBase(tag, xflen, dir),
+ bmCBWLUN(cdb->LUN), bmReserved1(0), bmCBWCBLength(6), bmReserved2(0) {
+ memcpy(&CBWCB, cdb, 6);
+ }
+ // Wrap for CDB of 10
+
+ CommandBlockWrapper(uint32_t tag, uint32_t xflen, CDB10_t *cdb, uint8_t dir) :
+ CommandBlockWrapperBase(tag, xflen, dir),
+ bmCBWLUN(cdb->LUN), bmReserved1(0), bmCBWCBLength(10), bmReserved2(0) {
+ memcpy(&CBWCB, cdb, 10);
+ }
+} __attribute__((packed));
+
+struct CommandStatusWrapper {
+ uint32_t dCSWSignature;
+ uint32_t dCSWTag;
+ uint32_t dCSWDataResidue;
+ uint8_t bCSWStatus;
+} __attribute__((packed));
+
+struct RequestSenseResponce {
+ uint8_t bResponseCode;
+ uint8_t bSegmentNumber;
+
+ uint8_t bmSenseKey : 4;
+ uint8_t bmReserved : 1;
+ uint8_t bmILI : 1;
+ uint8_t bmEOM : 1;
+ uint8_t bmFileMark : 1;
+
+ uint8_t Information[4];
+ uint8_t bAdditionalLength;
+ uint8_t CmdSpecificInformation[4];
+ uint8_t bAdditionalSenseCode;
+ uint8_t bAdditionalSenseQualifier;
+ uint8_t bFieldReplaceableUnitCode;
+ uint8_t SenseKeySpecific[3];
+} __attribute__((packed));
+
+class BulkOnly : public USBDeviceConfig, public UsbConfigXtracter {
+protected:
+ static const uint8_t epDataInIndex; // DataIn endpoint index
+ static const uint8_t epDataOutIndex; // DataOUT endpoint index
+ static const uint8_t epInterruptInIndex; // InterruptIN endpoint index
+
+ USB *pUsb;
+ uint8_t bAddress;
+ uint8_t bConfNum; // configuration number
+ uint8_t bIface; // interface value
+ uint8_t bNumEP; // total number of EP in the configuration
+ uint32_t qNextPollTime; // next poll time
+ bool bPollEnable; // poll enable flag
+
+ EpInfo epInfo[MASS_MAX_ENDPOINTS];
+
+ uint32_t dCBWTag; // Tag
+ //uint32_t dCBWDataTransferLength; // Data Transfer Length
+ uint8_t bLastUsbError; // Last USB error
+ uint8_t bMaxLUN; // Max LUN
+ uint8_t bTheLUN; // Active LUN
+ uint32_t CurrentCapacity[MASS_MAX_SUPPORTED_LUN]; // Total sectors
+ uint16_t CurrentSectorSize[MASS_MAX_SUPPORTED_LUN]; // Sector size, clipped to 16 bits
+ bool LUNOk[MASS_MAX_SUPPORTED_LUN]; // use this to check for media changes.
+ bool WriteOk[MASS_MAX_SUPPORTED_LUN];
+ void PrintEndpointDescriptor(const USB_ENDPOINT_DESCRIPTOR* ep_ptr);
+
+
+ // Additional Initialization Method for Subclasses
+
+ virtual uint8_t OnInit() {
+ return 0;
+ };
+public:
+ BulkOnly(USB *p);
+
+ uint8_t GetLastUsbError() {
+ return bLastUsbError;
+ };
+
+ uint8_t GetbMaxLUN() {
+ return bMaxLUN; // Max LUN
+ }
+
+ uint8_t GetbTheLUN() {
+ return bTheLUN; // Active LUN
+ }
+
+ bool WriteProtected(uint8_t lun);
+ uint8_t MediaCTL(uint8_t lun, uint8_t ctl);
+ uint8_t Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, uint8_t *buf);
+ uint8_t Read(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, USBReadParser *prs);
+ uint8_t Write(uint8_t lun, uint32_t addr, uint16_t bsize, uint8_t blocks, const uint8_t *buf);
+ uint8_t LockMedia(uint8_t lun, uint8_t lock);
+
+ bool LUNIsGood(uint8_t lun);
+ uint32_t GetCapacity(uint8_t lun);
+ uint16_t GetSectorSize(uint8_t lun);
+
+ // USBDeviceConfig implementation
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t ConfigureDevice(uint8_t parent, uint8_t port, bool lowspeed);
+
+ uint8_t Release();
+ uint8_t Poll();
+
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ // UsbConfigXtracter implementation
+ void EndpointXtract(uint8_t conf, uint8_t iface, uint8_t alt, uint8_t proto, const USB_ENDPOINT_DESCRIPTOR *ep);
+
+ virtual bool DEVCLASSOK(uint8_t klass) {
+ return (klass == USB_CLASS_MASS_STORAGE);
+ }
+
+ uint8_t SCSITransaction6(CDB6_t *cdb, uint16_t buf_size, void *buf, uint8_t dir);
+ uint8_t SCSITransaction10(CDB10_t *cdb, uint16_t buf_size, void *buf, uint8_t dir);
+
+private:
+ uint8_t Inquiry(uint8_t lun, uint16_t size, uint8_t *buf);
+ uint8_t TestUnitReady(uint8_t lun);
+ uint8_t RequestSense(uint8_t lun, uint16_t size, uint8_t *buf);
+ uint8_t ModeSense6(uint8_t lun, uint8_t pc, uint8_t page, uint8_t subpage, uint8_t len, uint8_t *buf);
+ uint8_t GetMaxLUN(uint8_t *max_lun);
+ uint8_t SetCurLUN(uint8_t lun);
+ void Reset();
+ uint8_t ResetRecovery();
+ uint8_t ReadCapacity10(uint8_t lun, uint8_t *buf);
+ void ClearAllEP();
+ void CheckMedia();
+ bool CheckLUN(uint8_t lun);
+ uint8_t Page3F(uint8_t lun);
+ bool IsValidCBW(uint8_t size, uint8_t *pcbw);
+ bool IsMeaningfulCBW(uint8_t size, uint8_t *pcbw);
+
+ bool IsValidCSW(CommandStatusWrapper *pcsw, CommandBlockWrapperBase *pcbw);
+
+ uint8_t ClearEpHalt(uint8_t index);
+#if MS_WANT_PARSER
+ uint8_t Transaction(CommandBlockWrapper *cbw, uint16_t bsize, void *buf, uint8_t flags);
+#endif
+ uint8_t Transaction(CommandBlockWrapper *cbw, uint16_t bsize, void *buf);
+ uint8_t HandleUsbError(uint8_t error, uint8_t index);
+ uint8_t HandleSCSIError(uint8_t status);
+
+};
+
+#endif // __MASSTORAGE_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max3421e.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max3421e.h
new file mode 100644
index 000000000..4e45a35e8
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max3421e.h
@@ -0,0 +1,228 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(_usb_h_) || defined(_max3421e_h_)
+#error "Never include max3421e.h directly; include Usb.h instead"
+#else
+
+#define _max3421e_h_
+
+/* MAX3421E register/bit names and bitmasks */
+
+/* Arduino pin definitions */
+/* pin numbers to port numbers */
+
+#define SE0 0
+#define SE1 1
+#define FSHOST 2
+#define LSHOST 3
+
+/* MAX3421E command byte format: rrrrr0wa where 'r' is register number */
+//
+// MAX3421E Registers in HOST mode.
+//
+#define rRCVFIFO 0x08 //1<<3
+#define rSNDFIFO 0x10 //2<<3
+#define rSUDFIFO 0x20 //4<<3
+#define rRCVBC 0x30 //6<<3
+#define rSNDBC 0x38 //7<<3
+
+#define rUSBIRQ 0x68 //13<<3
+/* USBIRQ Bits */
+#define bmVBUSIRQ 0x40 //b6
+#define bmNOVBUSIRQ 0x20 //b5
+#define bmOSCOKIRQ 0x01 //b0
+
+#define rUSBIEN 0x70 //14<<3
+/* USBIEN Bits */
+#define bmVBUSIE 0x40 //b6
+#define bmNOVBUSIE 0x20 //b5
+#define bmOSCOKIE 0x01 //b0
+
+#define rUSBCTL 0x78 //15<<3
+/* USBCTL Bits */
+#define bmCHIPRES 0x20 //b5
+#define bmPWRDOWN 0x10 //b4
+
+#define rCPUCTL 0x80 //16<<3
+/* CPUCTL Bits */
+#define bmPUSLEWID1 0x80 //b7
+#define bmPULSEWID0 0x40 //b6
+#define bmIE 0x01 //b0
+
+#define rPINCTL 0x88 //17<<3
+/* PINCTL Bits */
+#define bmFDUPSPI 0x10 //b4
+#define bmINTLEVEL 0x08 //b3
+#define bmPOSINT 0x04 //b2
+#define bmGPXB 0x02 //b1
+#define bmGPXA 0x01 //b0
+// GPX pin selections
+#define GPX_OPERATE 0x00
+#define GPX_VBDET 0x01
+#define GPX_BUSACT 0x02
+#define GPX_SOF 0x03
+
+#define rREVISION 0x90 //18<<3
+
+#define rIOPINS1 0xa0 //20<<3
+
+/* IOPINS1 Bits */
+#define bmGPOUT0 0x01
+#define bmGPOUT1 0x02
+#define bmGPOUT2 0x04
+#define bmGPOUT3 0x08
+#define bmGPIN0 0x10
+#define bmGPIN1 0x20
+#define bmGPIN2 0x40
+#define bmGPIN3 0x80
+
+#define rIOPINS2 0xa8 //21<<3
+/* IOPINS2 Bits */
+#define bmGPOUT4 0x01
+#define bmGPOUT5 0x02
+#define bmGPOUT6 0x04
+#define bmGPOUT7 0x08
+#define bmGPIN4 0x10
+#define bmGPIN5 0x20
+#define bmGPIN6 0x40
+#define bmGPIN7 0x80
+
+#define rGPINIRQ 0xb0 //22<<3
+/* GPINIRQ Bits */
+#define bmGPINIRQ0 0x01
+#define bmGPINIRQ1 0x02
+#define bmGPINIRQ2 0x04
+#define bmGPINIRQ3 0x08
+#define bmGPINIRQ4 0x10
+#define bmGPINIRQ5 0x20
+#define bmGPINIRQ6 0x40
+#define bmGPINIRQ7 0x80
+
+#define rGPINIEN 0xb8 //23<<3
+/* GPINIEN Bits */
+#define bmGPINIEN0 0x01
+#define bmGPINIEN1 0x02
+#define bmGPINIEN2 0x04
+#define bmGPINIEN3 0x08
+#define bmGPINIEN4 0x10
+#define bmGPINIEN5 0x20
+#define bmGPINIEN6 0x40
+#define bmGPINIEN7 0x80
+
+#define rGPINPOL 0xc0 //24<<3
+/* GPINPOL Bits */
+#define bmGPINPOL0 0x01
+#define bmGPINPOL1 0x02
+#define bmGPINPOL2 0x04
+#define bmGPINPOL3 0x08
+#define bmGPINPOL4 0x10
+#define bmGPINPOL5 0x20
+#define bmGPINPOL6 0x40
+#define bmGPINPOL7 0x80
+
+#define rHIRQ 0xc8 //25<<3
+/* HIRQ Bits */
+#define bmBUSEVENTIRQ 0x01 // indicates BUS Reset Done or BUS Resume
+#define bmRWUIRQ 0x02
+#define bmRCVDAVIRQ 0x04
+#define bmSNDBAVIRQ 0x08
+#define bmSUSDNIRQ 0x10
+#define bmCONDETIRQ 0x20
+#define bmFRAMEIRQ 0x40
+#define bmHXFRDNIRQ 0x80
+
+#define rHIEN 0xd0 //26<<3
+
+/* HIEN Bits */
+#define bmBUSEVENTIE 0x01
+#define bmRWUIE 0x02
+#define bmRCVDAVIE 0x04
+#define bmSNDBAVIE 0x08
+#define bmSUSDNIE 0x10
+#define bmCONDETIE 0x20
+#define bmFRAMEIE 0x40
+#define bmHXFRDNIE 0x80
+
+#define rMODE 0xd8 //27<<3
+
+/* MODE Bits */
+#define bmHOST 0x01
+#define bmLOWSPEED 0x02
+#define bmHUBPRE 0x04
+#define bmSOFKAENAB 0x08
+#define bmSEPIRQ 0x10
+#define bmDELAYISO 0x20
+#define bmDMPULLDN 0x40
+#define bmDPPULLDN 0x80
+
+#define rPERADDR 0xe0 //28<<3
+
+#define rHCTL 0xe8 //29<<3
+/* HCTL Bits */
+#define bmBUSRST 0x01
+#define bmFRMRST 0x02
+#define bmSAMPLEBUS 0x04
+#define bmSIGRSM 0x08
+#define bmRCVTOG0 0x10
+#define bmRCVTOG1 0x20
+#define bmSNDTOG0 0x40
+#define bmSNDTOG1 0x80
+
+#define rHXFR 0xf0 //30<<3
+/* Host transfer token values for writing the HXFR register (R30) */
+/* OR this bit field with the endpoint number in bits 3:0 */
+#define tokSETUP 0x10 // HS=0, ISO=0, OUTNIN=0, SETUP=1
+#define tokIN 0x00 // HS=0, ISO=0, OUTNIN=0, SETUP=0
+#define tokOUT 0x20 // HS=0, ISO=0, OUTNIN=1, SETUP=0
+#define tokINHS 0x80 // HS=1, ISO=0, OUTNIN=0, SETUP=0
+#define tokOUTHS 0xA0 // HS=1, ISO=0, OUTNIN=1, SETUP=0
+#define tokISOIN 0x40 // HS=0, ISO=1, OUTNIN=0, SETUP=0
+#define tokISOOUT 0x60 // HS=0, ISO=1, OUTNIN=1, SETUP=0
+
+#define rHRSL 0xf8 //31<<3
+
+/* HRSL Bits */
+#define bmRCVTOGRD 0x10
+#define bmSNDTOGRD 0x20
+#define bmKSTATUS 0x40
+#define bmJSTATUS 0x80
+#define bmSE0 0x00 //SE0 - disconnect state
+#define bmSE1 0xc0 //SE1 - illegal state
+
+/* Host error result codes, the 4 LSB's in the HRSL register */
+#define hrSUCCESS 0x00
+#define hrBUSY 0x01
+#define hrBADREQ 0x02
+#define hrUNDEF 0x03
+#define hrNAK 0x04
+#define hrSTALL 0x05
+#define hrTOGERR 0x06
+#define hrWRONGPID 0x07
+#define hrBADBC 0x08
+#define hrPIDERR 0x09
+#define hrPKTERR 0x0A
+#define hrCRCERR 0x0B
+#define hrKERR 0x0C
+#define hrJERR 0x0D
+#define hrTIMEOUT 0x0E
+#define hrBABBLE 0x0F
+
+#define MODE_FS_HOST (bmDPPULLDN|bmDMPULLDN|bmHOST|bmSOFKAENAB)
+#define MODE_LS_HOST (bmDPPULLDN|bmDMPULLDN|bmHOST|bmLOWSPEED|bmSOFKAENAB)
+
+
+#endif //_max3421e_h_
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max_LCD.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max_LCD.cpp
new file mode 100644
index 000000000..f0c64666f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max_LCD.cpp
@@ -0,0 +1,255 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#include "max_LCD.h"
+#include <string.h>
+
+// pin definition and set/clear
+
+#define RS 0x04 // RS pin
+#define E 0x08 // E pin
+
+#define SET_RS lcdPins |= RS
+#define CLR_RS lcdPins &= ~RS
+#define SET_E lcdPins |= E
+#define CLR_E lcdPins &= ~E
+
+#define SENDlcdPins() pUsb->gpioWr( lcdPins )
+
+#define LCD_sendcmd(a) { CLR_RS; \
+ sendbyte(a); \
+ }
+
+#define LCD_sendchar(a) { SET_RS; \
+ sendbyte(a); \
+ }
+
+static byte lcdPins; //copy of LCD pins
+
+Max_LCD::Max_LCD(USB *pusb) : pUsb(pusb) {
+ lcdPins = 0;
+}
+
+void Max_LCD::init() {
+ _displayfunction = LCD_4BITMODE | LCD_1LINE | LCD_5x8DOTS;
+
+ // MAX3421E::gpioWr(0x55);
+
+ begin(16, 1);
+}
+
+void Max_LCD::begin(uint8_t cols, uint8_t lines, uint8_t dotsize) {
+ if(lines > 1) {
+ _displayfunction |= LCD_2LINE;
+ }
+ _numlines = lines;
+ _currline = 0;
+
+ // for some 1 line displays you can select a 10 pixel high font
+ if((dotsize != 0) && (lines == 1)) {
+ _displayfunction |= LCD_5x10DOTS;
+ }
+
+ // SEE PAGE 45/46 FOR INITIALIZATION SPECIFICATION!
+ // according to datasheet, we need at least 40ms after power rises above 2.7V
+ // before sending commands. Arduino can turn on way befer 4.5V so we'll wait 50
+ delayMicroseconds(50000);
+ lcdPins = 0x30;
+ SET_E;
+ SENDlcdPins();
+ CLR_E;
+ SENDlcdPins();
+ delayMicroseconds(10000); // wait min 4.1ms
+ //second try
+ SET_E;
+ SENDlcdPins();
+ CLR_E;
+ SENDlcdPins();
+ delayMicroseconds(10000); // wait min 4.1ms
+ // third go!
+ SET_E;
+ SENDlcdPins();
+ CLR_E;
+ SENDlcdPins();
+ delayMicroseconds(10000);
+ // finally, set to 4-bit interface
+ lcdPins = 0x20;
+ //SET_RS;
+ SET_E;
+ SENDlcdPins();
+ //CLR_RS;
+ CLR_E;
+ SENDlcdPins();
+ delayMicroseconds(10000);
+ // finally, set # lines, font size, etc.
+ command(LCD_FUNCTIONSET | _displayfunction);
+
+ // turn the display on with no cursor or blinking default
+ _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF;
+ display();
+
+ // clear it off
+ clear();
+
+ // Initialize to default text direction (for romance languages)
+ _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT;
+ // set the entry mode
+ command(LCD_ENTRYMODESET | _displaymode);
+}
+
+/********** high level commands, for the user! */
+void Max_LCD::clear() {
+ command(LCD_CLEARDISPLAY); // clear display, set cursor position to zero
+ delayMicroseconds(2000); // this command takes a long time!
+}
+
+void Max_LCD::home() {
+ command(LCD_RETURNHOME); // set cursor position to zero
+ delayMicroseconds(2000); // this command takes a long time!
+}
+
+void Max_LCD::setCursor(uint8_t col, uint8_t row) {
+ int row_offsets[] = {0x00, 0x40, 0x14, 0x54};
+ if(row > _numlines) {
+ row = _numlines - 1; // we count rows starting w/0
+ }
+
+ command(LCD_SETDDRAMADDR | (col + row_offsets[row]));
+}
+
+// Turn the display on/off (quickly)
+
+void Max_LCD::noDisplay() {
+ _displaycontrol &= ~LCD_DISPLAYON;
+ command(LCD_DISPLAYCONTROL | _displaycontrol);
+}
+
+void Max_LCD::display() {
+ _displaycontrol |= LCD_DISPLAYON;
+ command(LCD_DISPLAYCONTROL | _displaycontrol);
+}
+
+// Turns the underline cursor on/off
+
+void Max_LCD::noCursor() {
+ _displaycontrol &= ~LCD_CURSORON;
+ command(LCD_DISPLAYCONTROL | _displaycontrol);
+}
+
+void Max_LCD::cursor() {
+ _displaycontrol |= LCD_CURSORON;
+ command(LCD_DISPLAYCONTROL | _displaycontrol);
+}
+
+
+// Turn on and off the blinking cursor
+
+void Max_LCD::noBlink() {
+ _displaycontrol &= ~LCD_BLINKON;
+ command(LCD_DISPLAYCONTROL | _displaycontrol);
+}
+
+void Max_LCD::blink() {
+ _displaycontrol |= LCD_BLINKON;
+ command(LCD_DISPLAYCONTROL | _displaycontrol);
+}
+
+// These commands scroll the display without changing the RAM
+
+void Max_LCD::scrollDisplayLeft(void) {
+ command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVELEFT);
+}
+
+void Max_LCD::scrollDisplayRight(void) {
+ command(LCD_CURSORSHIFT | LCD_DISPLAYMOVE | LCD_MOVERIGHT);
+}
+
+// This is for text that flows Left to Right
+
+void Max_LCD::leftToRight(void) {
+ _displaymode |= LCD_ENTRYLEFT;
+ command(LCD_ENTRYMODESET | _displaymode);
+}
+
+// This is for text that flows Right to Left
+
+void Max_LCD::rightToLeft(void) {
+ _displaymode &= ~LCD_ENTRYLEFT;
+ command(LCD_ENTRYMODESET | _displaymode);
+}
+
+// This will 'right justify' text from the cursor
+
+void Max_LCD::autoscroll(void) {
+ _displaymode |= LCD_ENTRYSHIFTINCREMENT;
+ command(LCD_ENTRYMODESET | _displaymode);
+}
+
+// This will 'left justify' text from the cursor
+
+void Max_LCD::noAutoscroll(void) {
+ _displaymode &= ~LCD_ENTRYSHIFTINCREMENT;
+ command(LCD_ENTRYMODESET | _displaymode);
+}
+
+// Allows us to fill the first 8 CGRAM locations
+// with custom characters
+
+void Max_LCD::createChar(uint8_t location, uint8_t charmap[]) {
+ location &= 0x7; // we only have 8 locations 0-7
+ command(LCD_SETCGRAMADDR | (location << 3));
+ for(int i = 0; i < 8; i++) {
+ write(charmap[i]);
+ }
+}
+
+/*********** mid level commands, for sending data/cmds */
+
+inline void Max_LCD::command(uint8_t value) {
+ LCD_sendcmd(value);
+ delayMicroseconds(100);
+}
+
+#if defined(ARDUINO) && ARDUINO >=100
+
+inline size_t Max_LCD::write(uint8_t value) {
+ LCD_sendchar(value);
+ return 1; // Assume success
+}
+#else
+
+inline void Max_LCD::write(uint8_t value) {
+ LCD_sendchar(value);
+}
+#endif
+
+void Max_LCD::sendbyte(uint8_t val) {
+ lcdPins &= 0x0f; //prepare place for the upper nibble
+ lcdPins |= (val & 0xf0); //copy upper nibble to LCD variable
+ SET_E; //send
+ SENDlcdPins();
+ delayMicroseconds(2);
+ CLR_E;
+ delayMicroseconds(2);
+ SENDlcdPins();
+ lcdPins &= 0x0f; //prepare place for the lower nibble
+ lcdPins |= (val << 4) & 0xf0; //copy lower nibble to LCD variable
+ SET_E; //send
+ SENDlcdPins();
+ CLR_E;
+ SENDlcdPins();
+ delayMicroseconds(100);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max_LCD.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max_LCD.h
new file mode 100644
index 000000000..950c9c5aa
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/max_LCD.h
@@ -0,0 +1,106 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+//HD44780 compatible LCD display via MAX3421E GPOUT support header
+//pinout: D[4-7] -> GPOUT[4-7], RS-> GPOUT[2], E ->GPOUT[3]
+//
+
+#ifndef _Max_LCD_h_
+#define _Max_LCD_h_
+
+#include "Usb.h"
+#include "Print.h"
+
+// commands
+#define LCD_CLEARDISPLAY 0x01
+#define LCD_RETURNHOME 0x02
+#define LCD_ENTRYMODESET 0x04
+#define LCD_DISPLAYCONTROL 0x08
+#define LCD_CURSORSHIFT 0x10
+#define LCD_FUNCTIONSET 0x20
+#define LCD_SETCGRAMADDR 0x40
+#define LCD_SETDDRAMADDR 0x80
+
+// flags for display entry mode
+#define LCD_ENTRYRIGHT 0x00
+#define LCD_ENTRYLEFT 0x02
+#define LCD_ENTRYSHIFTINCREMENT 0x01
+#define LCD_ENTRYSHIFTDECREMENT 0x00
+
+// flags for display on/off control
+#define LCD_DISPLAYON 0x04
+#define LCD_DISPLAYOFF 0x00
+#define LCD_CURSORON 0x02
+#define LCD_CURSOROFF 0x00
+#define LCD_BLINKON 0x01
+#define LCD_BLINKOFF 0x00
+
+// flags for display/cursor shift
+#define LCD_DISPLAYMOVE 0x08
+#define LCD_CURSORMOVE 0x00
+#define LCD_MOVERIGHT 0x04
+#define LCD_MOVELEFT 0x00
+
+// flags for function set
+#define LCD_8BITMODE 0x10
+#define LCD_4BITMODE 0x00
+#define LCD_2LINE 0x08
+#define LCD_1LINE 0x00
+#define LCD_5x10DOTS 0x04
+#define LCD_5x8DOTS 0x00
+
+class Max_LCD : public Print {
+ USB *pUsb;
+
+public:
+ Max_LCD(USB *pusb);
+ void init();
+ void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS);
+ void clear();
+ void home();
+ void noDisplay();
+ void display();
+ void noBlink();
+ void blink();
+ void noCursor();
+ void cursor();
+ void scrollDisplayLeft();
+ void scrollDisplayRight();
+ void leftToRight();
+ void rightToLeft();
+ void autoscroll();
+ void noAutoscroll();
+ void createChar(uint8_t, uint8_t[]);
+ void setCursor(uint8_t, uint8_t);
+ void command(uint8_t);
+
+#if defined(ARDUINO) && ARDUINO >=100
+ size_t write(uint8_t);
+ using Print::write;
+#else
+ void write(uint8_t);
+#endif
+
+private:
+ void sendbyte(uint8_t val);
+ uint8_t _displayfunction; //tokill
+ uint8_t _displaycontrol;
+ uint8_t _displaymode;
+ uint8_t _initialized;
+ uint8_t _numlines, _currline;
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/message.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/message.cpp
new file mode 100644
index 000000000..bdcdd1833
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/message.cpp
@@ -0,0 +1,116 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#include "Usb.h"
+// 0x80 is the default (i.e. trace) to turn off set this global to something lower.
+// this allows for 126 other debugging levels.
+// TO-DO: Allow assignment to a different serial port by software
+int UsbDEBUGlvl = 0x80;
+
+void E_Notifyc(char c, int lvl) {
+ if(UsbDEBUGlvl < lvl) return;
+#if defined(ARDUINO) && ARDUINO >=100
+ USB_HOST_SERIAL.print(c);
+#else
+ USB_HOST_SERIAL.print(c, BYTE);
+#endif
+ //USB_HOST_SERIAL.flush();
+}
+
+void E_Notify(char const * msg, int lvl) {
+ if(UsbDEBUGlvl < lvl) return;
+ if(!msg) return;
+ char c;
+
+ while((c = pgm_read_byte(msg++))) E_Notifyc(c, lvl);
+}
+
+void E_NotifyStr(char const * msg, int lvl) {
+ if(UsbDEBUGlvl < lvl) return;
+ if(!msg) return;
+ char c;
+
+ while((c = *msg++)) E_Notifyc(c, lvl);
+}
+
+void E_Notify(uint8_t b, int lvl) {
+ if(UsbDEBUGlvl < lvl) return;
+#if defined(ARDUINO) && ARDUINO >=100
+ USB_HOST_SERIAL.print(b);
+#else
+ USB_HOST_SERIAL.print(b, DEC);
+#endif
+ //USB_HOST_SERIAL.flush();
+}
+
+void E_Notify(double d, int lvl) {
+ if(UsbDEBUGlvl < lvl) return;
+ USB_HOST_SERIAL.print(d);
+ //USB_HOST_SERIAL.flush();
+}
+
+#ifdef DEBUG_USB_HOST
+
+void NotifyFailGetDevDescr(void) {
+ Notify(PSTR("\r\ngetDevDescr "), 0x80);
+}
+
+void NotifyFailSetDevTblEntry(void) {
+ Notify(PSTR("\r\nsetDevTblEn "), 0x80);
+}
+
+void NotifyFailGetConfDescr(void) {
+ Notify(PSTR("\r\ngetConf "), 0x80);
+}
+
+void NotifyFailSetConfDescr(void) {
+ Notify(PSTR("\r\nsetConf "), 0x80);
+}
+
+void NotifyFailGetDevDescr(uint8_t reason) {
+ NotifyFailGetDevDescr();
+ NotifyFail(reason);
+}
+
+void NotifyFailSetDevTblEntry(uint8_t reason) {
+ NotifyFailSetDevTblEntry();
+ NotifyFail(reason);
+
+}
+
+void NotifyFailGetConfDescr(uint8_t reason) {
+ NotifyFailGetConfDescr();
+ NotifyFail(reason);
+}
+
+void NotifyFailSetConfDescr(uint8_t reason) {
+ NotifyFailSetConfDescr();
+ NotifyFail(reason);
+}
+
+void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID) {
+ Notify(PSTR("\r\nUnknown Device Connected - VID: "), 0x80);
+ D_PrintHex<uint16_t > (VID, 0x80);
+ Notify(PSTR(" PID: "), 0x80);
+ D_PrintHex<uint16_t > (PID, 0x80);
+}
+
+void NotifyFail(uint8_t rcode) {
+ D_PrintHex<uint8_t > (rcode, 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+}
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/message.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/message.h
new file mode 100644
index 000000000..c26628e7f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/message.h
@@ -0,0 +1,78 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(_usb_h_) || defined(__MESSAGE_H__)
+#error "Never include message.h directly; include Usb.h instead"
+#else
+#define __MESSAGE_H__
+
+extern int UsbDEBUGlvl;
+
+void E_Notify(char const * msg, int lvl);
+void E_Notify(uint8_t b, int lvl);
+void E_NotifyStr(char const * msg, int lvl);
+void E_Notifyc(char c, int lvl);
+
+#ifdef DEBUG_USB_HOST
+#define Notify E_Notify
+#define NotifyStr E_NotifyStr
+#define Notifyc E_Notifyc
+void NotifyFailGetDevDescr(uint8_t reason);
+void NotifyFailSetDevTblEntry(uint8_t reason);
+void NotifyFailGetConfDescr(uint8_t reason);
+void NotifyFailSetConfDescr(uint8_t reason);
+void NotifyFailGetDevDescr(void);
+void NotifyFailSetDevTblEntry(void);
+void NotifyFailGetConfDescr(void);
+void NotifyFailSetConfDescr(void);
+void NotifyFailUnknownDevice(uint16_t VID, uint16_t PID);
+void NotifyFail(uint8_t rcode);
+#else
+#define Notify(...) ((void)0)
+#define NotifyStr(...) ((void)0)
+#define Notifyc(...) ((void)0)
+#define NotifyFailGetDevDescr(...) ((void)0)
+#define NotifyFailSetDevTblEntry(...) ((void)0)
+#define NotifyFailGetConfDescr(...) ((void)0)
+#define NotifyFailGetDevDescr(...) ((void)0)
+#define NotifyFailSetDevTblEntry(...) ((void)0)
+#define NotifyFailGetConfDescr(...) ((void)0)
+#define NotifyFailSetConfDescr(...) ((void)0)
+#define NotifyFailUnknownDevice(...) ((void)0)
+#define NotifyFail(...) ((void)0)
+#endif
+
+template <class ERROR_TYPE>
+void ErrorMessage(uint8_t level, char const * msg, ERROR_TYPE rcode = 0) {
+#ifdef DEBUG_USB_HOST
+ Notify(msg, level);
+ Notify(PSTR(": "), level);
+ D_PrintHex<ERROR_TYPE > (rcode, level);
+ Notify(PSTR("\r\n"), level);
+#endif
+}
+
+template <class ERROR_TYPE>
+void ErrorMessage(char const * msg, ERROR_TYPE rcode = 0) {
+#ifdef DEBUG_USB_HOST
+ Notify(msg, 0x80);
+ Notify(PSTR(": "), 0x80);
+ D_PrintHex<ERROR_TYPE > (rcode, 0x80);
+ Notify(PSTR("\r\n"), 0x80);
+#endif
+}
+
+#endif // __MESSAGE_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/parsetools.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/parsetools.cpp
new file mode 100644
index 000000000..74a861059
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/parsetools.cpp
@@ -0,0 +1,67 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#include "Usb.h"
+
+bool MultiByteValueParser::Parse(uint8_t **pp, uint16_t *pcntdn) {
+ if(!pBuf) {
+ Notify(PSTR("Buffer pointer is NULL!\r\n"), 0x80);
+ return false;
+ }
+ for(; countDown && (*pcntdn); countDown--, (*pcntdn)--, (*pp)++)
+ pBuf[valueSize - countDown] = (**pp);
+
+ if(countDown)
+ return false;
+
+ countDown = valueSize;
+ return true;
+}
+
+bool PTPListParser::Parse(uint8_t **pp, uint16_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me) {
+ switch(nStage) {
+ case 0:
+ pBuf->valueSize = lenSize;
+ theParser.Initialize(pBuf);
+ nStage = 1;
+
+ case 1:
+ if(!theParser.Parse(pp, pcntdn))
+ return false;
+
+ arLen = 0;
+ arLen = (pBuf->valueSize >= 4) ? *((uint32_t*)pBuf->pValue) : (uint32_t)(*((uint16_t*)pBuf->pValue));
+ arLenCntdn = arLen;
+ nStage = 2;
+
+ case 2:
+ pBuf->valueSize = valSize;
+ theParser.Initialize(pBuf);
+ nStage = 3;
+
+ case 3:
+ for(; arLenCntdn; arLenCntdn--) {
+ if(!theParser.Parse(pp, pcntdn))
+ return false;
+
+ if(pf)
+ pf(pBuf, (arLen - arLenCntdn), me);
+ }
+
+ nStage = 0;
+ }
+ return true;
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/parsetools.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/parsetools.h
new file mode 100644
index 000000000..66e9531c3
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/parsetools.h
@@ -0,0 +1,140 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#if !defined(_usb_h_) || defined(__PARSETOOLS_H__)
+#error "Never include parsetools.h directly; include Usb.h instead"
+#else
+#define __PARSETOOLS_H__
+
+struct MultiValueBuffer {
+ uint8_t valueSize;
+ void *pValue;
+} __attribute__((packed));
+
+class MultiByteValueParser {
+ uint8_t * pBuf;
+ uint8_t countDown;
+ uint8_t valueSize;
+
+public:
+
+ MultiByteValueParser() : pBuf(NULL), countDown(0), valueSize(0) {
+ };
+
+ const uint8_t* GetBuffer() {
+ return pBuf;
+ };
+
+ void Initialize(MultiValueBuffer * const pbuf) {
+ pBuf = (uint8_t*)pbuf->pValue;
+ countDown = valueSize = pbuf->valueSize;
+ };
+
+ bool Parse(uint8_t **pp, uint16_t *pcntdn);
+};
+
+class ByteSkipper {
+ uint8_t *pBuf;
+ uint8_t nStage;
+ uint16_t countDown;
+
+public:
+
+ ByteSkipper() : pBuf(NULL), nStage(0), countDown(0) {
+ };
+
+ void Initialize(MultiValueBuffer *pbuf) {
+ pBuf = (uint8_t*)pbuf->pValue;
+ countDown = 0;
+ };
+
+ bool Skip(uint8_t **pp, uint16_t *pcntdn, uint16_t bytes_to_skip) {
+ switch(nStage) {
+ case 0:
+ countDown = bytes_to_skip;
+ nStage++;
+ case 1:
+ for(; countDown && (*pcntdn); countDown--, (*pp)++, (*pcntdn)--);
+
+ if(!countDown)
+ nStage = 0;
+ };
+ return (!countDown);
+ };
+};
+
+// Pointer to a callback function triggered for each element of PTP array when used with PTPArrayParser
+typedef void (*PTP_ARRAY_EL_FUNC)(const MultiValueBuffer * const p, uint32_t count, const void *me);
+
+class PTPListParser {
+public:
+
+ enum ParseMode {
+ modeArray, modeRange/*, modeEnum*/
+ };
+
+private:
+ uint8_t nStage;
+ uint8_t enStage;
+
+ uint32_t arLen;
+ uint32_t arLenCntdn;
+
+ uint8_t lenSize; // size of the array length field in bytes
+ uint8_t valSize; // size of the array element in bytes
+
+ MultiValueBuffer *pBuf;
+
+ // The only parser for both size and array element parsing
+ MultiByteValueParser theParser;
+
+ uint8_t /*ParseMode*/ prsMode;
+
+public:
+
+ PTPListParser() :
+ nStage(0),
+ enStage(0),
+ arLen(0),
+ arLenCntdn(0),
+ lenSize(0),
+ valSize(0),
+ pBuf(NULL),
+ prsMode(modeArray) {
+ };
+
+ void Initialize(const uint8_t len_size, const uint8_t val_size, MultiValueBuffer * const p, const uint8_t mode = modeArray) {
+ pBuf = p;
+ lenSize = len_size;
+ valSize = val_size;
+ prsMode = mode;
+
+ if(prsMode == modeRange) {
+ arLenCntdn = arLen = 3;
+ nStage = 2;
+ } else {
+ arLenCntdn = arLen = 0;
+ nStage = 0;
+ }
+ enStage = 0;
+ theParser.Initialize(p);
+ };
+
+ bool Parse(uint8_t **pp, uint16_t *pcntdn, PTP_ARRAY_EL_FUNC pf, const void *me = NULL);
+};
+
+#endif // __PARSETOOLS_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/printhex.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/printhex.h
new file mode 100644
index 000000000..369d7e1f7
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/printhex.h
@@ -0,0 +1,84 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#if !defined(_usb_h_) || defined(__PRINTHEX_H__)
+#error "Never include printhex.h directly; include Usb.h instead"
+#else
+#define __PRINTHEX_H__
+
+void E_Notifyc(char c, int lvl);
+
+template <class T>
+void PrintHex(T val, int lvl) {
+ int num_nibbles = sizeof (T) * 2;
+
+ do {
+ char v = 48 + (((val >> (num_nibbles - 1) * 4)) & 0x0f);
+ if(v > 57) v += 7;
+ E_Notifyc(v, lvl);
+ } while(--num_nibbles);
+}
+
+template <class T>
+void PrintBin(T val, int lvl) {
+ for(T mask = (((T)1) << ((sizeof (T) << 3) - 1)); mask; mask >>= 1)
+ if(val & mask)
+ E_Notifyc('1', lvl);
+ else
+ E_Notifyc('0', lvl);
+}
+
+template <class T>
+void SerialPrintHex(T val) {
+ int num_nibbles = sizeof (T) * 2;
+
+ do {
+ char v = 48 + (((val >> (num_nibbles - 1) * 4)) & 0x0f);
+ if(v > 57) v += 7;
+ USB_HOST_SERIAL.print(v);
+ } while(--num_nibbles);
+}
+
+template <class T>
+void PrintHex2(Print *prn, T val) {
+ T mask = (((T)1) << (((sizeof (T) << 1) - 1) << 2));
+
+ while(mask > 1) {
+ if(val < mask)
+ prn->print("0");
+
+ mask >>= 4;
+ }
+ prn->print((T)val, HEX);
+}
+
+template <class T> void D_PrintHex(T val, int lvl) {
+#ifdef DEBUG_USB_HOST
+ PrintHex<T > (val, lvl);
+#endif
+}
+
+template <class T>
+void D_PrintBin(T val, int lvl) {
+#ifdef DEBUG_USB_HOST
+ PrintBin<T > (val, lvl);
+#endif
+}
+
+
+
+#endif // __PRINTHEX_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/readme.md b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/readme.md
new file mode 100644
index 000000000..49cd83e0a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/readme.md
@@ -0,0 +1,351 @@
+# USB Host Library Rev.2.0
+
+The code is released under the GNU General Public License.
+__________
+
+# Summary
+This is Revision 2.0 of MAX3421E-based USB Host Shield Library for AVR's.
+
+Project main web site is: <http://www.circuitsathome.com>.
+
+Some information can also be found at: <http://blog.tkjelectronics.dk/>.
+
+The shield can be purchased at the main site: <http://www.circuitsathome.com/products-page/arduino-shields> or from [TKJ Electronics](http://tkjelectronics.com/): <http://shop.tkjelectronics.dk/product_info.php?products_id=43>.
+
+![USB Host Shield](http://shop.tkjelectronics.dk/images/USB_Host_Shield1.jpg)
+
+For more information about the hardware see the [Hardware Manual](http://www.circuitsathome.com/usb-host-shield-hardware-manual).
+
+# Developed By
+
+* __Oleg Mazurov, Circuits@Home__ - <mazurov@circuitsathome.com>
+* __Alexei Glushchenko, Circuits@Home__ - <alex-gl@mail.ru>
+ * Developers of the USB Core, HID, FTDI, ADK, ACM, and PL2303 libraries
+* __Kristian Lauszus, TKJ Electronics__ - <kristianl@tkjelectronics.com>
+ * Developer of the [BTD](#bluetooth-libraries), [BTHID](#bthid-library), [SPP](#spp-library), [PS4](#ps4-library), [PS3](#ps3-library), [Wii](#wii-library), [Xbox](#xbox-library), and [PSBuzz](#ps-buzz-library) libraries
+* __Andrew Kroll__ - <xxxajk@gmail.com>
+ * Major contributor to mass storage code
+* __guruthree__
+ * [Xbox ONE](#xbox-one-library) controller support
+
+# Donate
+
+Help yourself by helping us support you! Many thousands of hours have been spent developing the USB Host Shield library. Since you find it useful, please consider donating via the button below. Donations will allow us to support you by ensuring hardware that you have can be acquired in order to add support for your microcontroller board.
+
+<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_donations&amp;business=donate@circuitsathome.com&amp;lc=US&amp;item_name=Donate%20to%20the%20USB%20Host%20Library%20project&amp;no_note=0&amp;currency_code=USD&amp;bn=PP%2dDonationsBF%3abtn_donate_LG%2egif%3aNonHostedGuest"><img src="https://www.paypalobjects.com/en_US/i/btn/btn_donate_LG.gif" alt="PayPal - The safer, easier way to pay online!" /></a>
+
+# Table of Contents
+
+* [How to include the library](#how-to-include-the-library)
+ * [Arduino Library Manager](#arduino-library-manager)
+ * [Manual installation](#manual-installation)
+* [How to use the library](#how-to-use-the-library)
+ * [Documentation](#documentation)
+ * [Enable debugging](#enable-debugging)
+ * [Boards](#boards)
+ * [Bluetooth libraries](#bluetooth-libraries)
+ * [BTHID library](#bthid-library)
+ * [SPP library](#spp-library)
+ * [PS4 Library](#ps4-library)
+ * [PS3 Library](#ps3-library)
+ * [Xbox Libraries](#xbox-libraries)
+ * [Xbox library](#xbox-library)
+ * [Xbox 360 Library](#xbox-360-library)
+ * [Xbox ONE Library](#xbox-one-library)
+ * [Wii library](#wii-library)
+ * [PS Buzz Library](#ps-buzz-library)
+* [Interface modifications](#interface-modifications)
+* [FAQ](#faq)
+
+# How to include the library
+
+### Arduino Library Manager
+
+First install Arduino IDE version 1.6.2 or newer, then simply use the Arduino Library Manager to install the library.
+
+Please see the following page for instructions: <http://www.arduino.cc/en/Guide/Libraries#toc3>.
+
+### Manual installation
+
+First download the library by clicking on the following link: <https://github.com/felis/USB_Host_Shield_2.0/archive/master.zip>.
+
+Then uncompress the zip folder and rename the directory to "USB\_Host\_Shield\_20", as any special characters are not supported by the Arduino IDE.
+
+Now open up the Arduino IDE and open "File>Preferences". There you will see the location of your sketchbook. Open that directory and create a directory called "libraries" inside that directory.
+Now move the "USB\_Host\_Shield\_20" directory to the "libraries" directory.
+
+The final structure should look like this:
+
+* Arduino/
+ * libraries/
+ * USB\_Host\_Shield\_20/
+
+Now quit the Arduino IDE and reopen it.
+
+Now you should be able to go open all the examples codes by navigating to "File>Examples>USB\_Host\_Shield\_20" and then select the example you will like to open.
+
+For more information visit the following sites: <http://arduino.cc/en/Guide/Libraries> and <https://learn.adafruit.com/adafruit-all-about-arduino-libraries-install-use>.
+
+# How to use the library
+
+### Documentation
+
+Documentation for the library can be found at the following link: <http://felis.github.com/USB_Host_Shield_2.0/>.
+
+### Enable debugging
+
+By default serial debugging is disabled. To turn it on simply change ```ENABLE_UHS_DEBUGGING``` to 1 in [settings.h](settings.h) like so:
+
+```C++
+#define ENABLE_UHS_DEBUGGING 1
+```
+
+### Boards
+
+Currently the following boards are supported by the library:
+
+* All official Arduino AVR boards (Uno, Duemilanove, Mega, Mega 2560, Mega ADK, Leonardo etc.)
+* Arduino Due, Intel Galileo, Intel Galileo 2, and Intel Edison
+ * Note that the Intel Galileo uses pin 2 and 3 as INT and SS pin respectively by default, so some modifications to the shield are needed. See the "Interface modifications" section in the [hardware manual](https://www.circuitsathome.com/usb-host-shield-hardware-manual) for more information.
+* Teensy (Teensy++ 1.0, Teensy 2.0, Teensy++ 2.0, and Teensy 3.x)
+ * Note if you are using the Teensy 3.x you should download this SPI library as well: <https://github.com/xxxajk/spi4teensy3>. You should then add ```#include <spi4teensy3.h>``` to your .ino file.
+* Balanduino
+* Sanguino
+* Black Widdow
+* RedBearLab nRF51822
+* Digilent chipKIT
+ * Please see: <http://www.circuitsathome.com/mcu/usb/running-usb-host-code-on-digilent-chipkit-board>.
+
+The following boards need to be activated manually in [settings.h](settings.h):
+
+* Arduino Mega ADK
+ * If you are using Arduino 1.5.5 or newer there is no need to activate the Arduino Mega ADK manually
+* Black Widdow
+
+Simply set the corresponding value to 1 instead of 0.
+
+### [Bluetooth libraries](BTD.cpp)
+
+The [BTD library](BTD.cpp) is a general purpose library for an ordinary Bluetooth dongle.
+This library make it easy to add support for different Bluetooth services like a PS3 or a Wii controller or SPP which is a virtual serial port via Bluetooth.
+Some different examples can be found in the [example directory](examples/Bluetooth).
+
+The BTD library also makes it possible to use multiple services at once, the following example sketch is an example of this:
+[PS3SPP.ino](examples/Bluetooth/PS3SPP/PS3SPP.ino).
+
+### [BTHID library](BTHID.cpp)
+
+The [Bluetooth HID library](BTHID.cpp) allows you to connect HID devices via Bluetooth to the USB Host Shield.
+
+Currently HID mice and keyboards are supported.
+
+It uses the standard Boot protocol by default, but it is also able to use the Report protocol as well. You would simply have to call ```setProtocolMode()``` and then parse ```HID_RPT_PROTOCOL``` as an argument. You will then have to modify the parser for your device. See the example: [BTHID.ino](examples/Bluetooth/BTHID/BTHID.ino) for more information.
+
+The [PS4 library](#ps4-library) also uses this class to handle all Bluetooth communication.
+
+For information see the following blog post: <http://blog.tkjelectronics.dk/2013/12/bluetooth-hid-devices-now-supported-by-the-usb-host-library/>.
+
+### [SPP library](SPP.cpp)
+
+SPP stands for "Serial Port Profile" and is a Bluetooth protocol that implements a virtual comport which allows you to send data back and forth from your computer/phone to your Arduino via Bluetooth.
+It has been tested successfully on Windows, Mac OS X, Linux, and Android.
+
+Take a look at the [SPP.ino](examples/Bluetooth/SPP/SPP.ino) example for more information.
+
+More information can be found at these blog posts:
+
+* <http://www.circuitsathome.com/mcu/bluetooth-rfcommspp-service-support-for-usb-host-2-0-library-released>
+* <http://blog.tkjelectronics.dk/2012/07/rfcommspp-library-for-arduino/>
+
+To implement the SPP protocol I used a Bluetooth sniffing tool called [PacketLogger](http://www.tkjelectronics.com/uploads/PacketLogger.zip) developed by Apple.
+It enables me to see the Bluetooth communication between my Mac and any device.
+
+### PS4 Library
+
+The PS4BT library is split up into the [PS4BT](PS4BT.h) and the [PS4USB](PS4USB.h) library. These allow you to use the Sony PS4 controller via Bluetooth and USB.
+
+The [PS4BT.ino](examples/Bluetooth/PS4BT/PS4BT.ino) and [PS4USB.ino](examples/PS4USB/PS4USB.ino) examples shows how to easily read the buttons, joysticks, touchpad and IMU on the controller via Bluetooth and USB respectively. It is also possible to control the rumble and light on the controller and get the battery level.
+
+Before you can use the PS4 controller via Bluetooth you will need to pair with it.
+
+Simply create the PS4BT instance like so: ```PS4BT PS4(&Btd, PAIR);``` and then hold down the Share button and then hold down the PS without releasing the Share button. The PS4 controller will then start to blink rapidly indicating that it is in paring mode.
+
+It should then automatically pair the dongle with your controller. This only have to be done once.
+
+For information see the following blog post: <http://blog.tkjelectronics.dk/2014/01/ps4-controller-now-supported-by-the-usb-host-library/>.
+
+Also check out this excellent Wiki by Frank Zhao about the PS4 controller: <http://eleccelerator.com/wiki/index.php?title=DualShock_4> and this Linux driver: <https://github.com/chrippa/ds4drv>.
+
+### PS3 Library
+
+These libraries consist of the [PS3BT](PS3BT.cpp) and [PS3USB](PS3USB.cpp). These libraries allows you to use a Dualshock 3, Navigation or a Motion controller with the USB Host Shield both via Bluetooth and USB.
+
+In order to use your Playstation controller via Bluetooth you have to set the Bluetooth address of the dongle internally to your PS3 Controller. This can be achieved by first plugging in the Bluetooth dongle and wait a few seconds. Now plug in the controller via USB and wait until the LEDs start to flash. The library has now written the Bluetooth address of the dongle to the PS3 controller.
+
+Finally simply plug in the Bluetooth dongle again and press PS on the PS3 controller. After a few seconds it should be connected to the dongle and ready to use.
+
+__Note:__ You will have to plug in the Bluetooth dongle before connecting the controller, as the library needs to read the address of the dongle. Alternatively you could set it in code like so: [PS3BT.ino#L20](examples/Bluetooth/PS3BT/PS3BT.ino#L20).
+
+For more information about the PS3 protocol see the official wiki: <https://github.com/felis/USB_Host_Shield_2.0/wiki/PS3-Information>.
+
+Also take a look at the blog posts:
+
+* <http://blog.tkjelectronics.dk/2012/01/ps3-controller-bt-library-for-arduino/>
+* <http://www.circuitsathome.com/mcu/sony-ps3-controller-support-added-to-usb-host-library>
+* <http://www.circuitsathome.com/mcu/arduino/interfacing-ps3-controllers-via-usb>
+
+A special thanks go to the following people:
+
+1. _Richard Ibbotson_ who made this excellent guide: <http://www.circuitsathome.com/mcu/ps3-and-wiimote-game-controllers-on-the-arduino-host-shield-part>
+2. _Tomoyuki Tanaka_ for releasing his code for the Arduino USB Host shield connected to the wiimote: <http://www.circuitsathome.com/mcu/rc-car-controlled-by-wii-remote-on-arduino>
+
+Also a big thanks all the people behind these sites about the Motion controller:
+
+* <http://thp.io/2010/psmove/>
+* <http://www.copenhagengamecollective.org/unimove/>
+* <https://github.com/thp/psmoveapi>
+* <http://code.google.com/p/moveonpc/>
+
+### Xbox Libraries
+
+The library supports both the original Xbox controller via USB and the Xbox 360 controller both via USB and wirelessly.
+
+#### Xbox library
+
+The [XBOXOLD](XBOXOLD.cpp) class implements support for the original Xbox controller via USB.
+
+All the information are from the following sites:
+
+* <https://github.com/torvalds/linux/blob/master/Documentation/input/xpad.txt>
+* <https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c>
+* <http://euc.jp/periphs/xbox-controller.ja.html>
+* <https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL#L15>
+
+#### Xbox 360 Library
+
+The library support one Xbox 360 via USB or up to four Xbox 360 controllers wirelessly by using a [Xbox 360 wireless receiver](http://blog.tkjelectronics.dk/wp-content/uploads/xbox360-wireless-receiver.jpg).
+
+To use it via USB use the [XBOXUSB](XBOXUSB.cpp) library or to use it wirelessly use the [XBOXRECV](XBOXRECV.cpp) library.
+
+__Note that a Wireless controller can NOT be used via USB!__
+
+Examples code can be found in the [examples directory](examples/Xbox).
+
+Also see the following blog posts:
+
+* <http://www.circuitsathome.com/mcu/xbox360-controller-support-added-to-usb-host-shield-2-0-library>
+* <http://blog.tkjelectronics.dk/2012/07/xbox-360-controller-support-added-to-the-usb-host-library/>
+* <http://blog.tkjelectronics.dk/2012/12/xbox-360-receiver-added-to-the-usb-host-library/>
+
+All the information regarding the Xbox 360 controller protocol are form these sites:
+
+* <http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/UsbInfo>
+* <http://tattiebogle.net/index.php/ProjectRoot/Xbox360Controller/WirelessUsbInfo>
+* <https://github.com/Grumbel/xboxdrv/blob/master/PROTOCOL>
+
+#### Xbox ONE Library
+
+An Xbox ONE controller is supported via USB in the [XBOXONE](XBOXONE.cpp) class. It is heavily based on the 360 library above. In addition to cross referencing the above, information on the protocol was found at:
+
+* <https://github.com/quantus/xbox-one-controller-protocol>
+* <https://github.com/torvalds/linux/blob/master/drivers/input/joystick/xpad.c>
+* <https://github.com/kylelemons/xbox/blob/master/xbox.go>
+
+### [Wii library](Wii.cpp)
+
+The [Wii](Wii.cpp) library support the Wiimote, but also the Nunchuch and Motion Plus extensions via Bluetooth. The Wii U Pro Controller and Wii Balance Board are also supported via Bluetooth.
+
+First you have to pair with the controller, this is done automatically by the library if you create the instance like so:
+
+```C++
+WII Wii(&Btd, PAIR);
+```
+
+And then press 1 & 2 at once on the Wiimote or the SYNC buttons if you are using a Wii U Pro Controller or a Wii Balance Board.
+
+After that you can simply create the instance like so:
+
+```C++
+WII Wii(&Btd);
+```
+
+Then just press any button on the Wiimote and it will then connect to the dongle.
+
+Take a look at the example for more information: [Wii.ino](examples/Bluetooth/Wii/Wii.ino).
+
+Also take a look at the blog post:
+
+* <http://blog.tkjelectronics.dk/2012/08/wiimote-added-to-usb-host-library/>
+
+The Wii IR camera can also be used, but you will have to activate the code for it manually as it is quite large. Simply set ```ENABLE_WII_IR_CAMERA``` to 1 in [settings.h](settings.h).
+
+The [WiiIRCamera.ino](examples/Bluetooth/WiiIRCamera/WiiIRCamera.ino) example shows how it can be used.
+
+All the information about the Wii controllers are from these sites:
+
+* <http://wiibrew.org/wiki/Wiimote>
+* <http://wiibrew.org/wiki/Wiimote/Extension_Controllers>
+* <http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Nunchuck>
+* <http://wiibrew.org/wiki/Wiimote/Extension_Controllers/Wii_Motion_Plus>
+* <http://wiibrew.org/wiki/Wii_Balance_Board>
+* The old library created by _Tomoyuki Tanaka_: <https://github.com/moyuchin/WiiRemote_on_Arduino> also helped a lot.
+
+### [PS Buzz Library](PSBuzz.cpp)
+
+This library implements support for the Playstation Buzz controllers via USB.
+
+It is essentially just a wrapper around the [HIDUniversal](hiduniversal.cpp) which takes care of the initializing and reading of the controllers. The [PSBuzz](PSBuzz.cpp) class simply inherits this and parses the data, so it is easy for users to read the buttons and turn the big red button on the controllers on and off.
+
+The example [PSBuzz.ino](examples/PSBuzz/PSBuzz.ino) shows how one can do this with just a few lines of code.
+
+More information about the controller can be found at the following sites:
+
+* http://www.developerfusion.com/article/84338/making-usb-c-friendly/
+* https://github.com/torvalds/linux/blob/master/drivers/hid/hid-sony.c
+
+# Interface modifications
+
+The shield is using SPI for communicating with the MAX3421E USB host controller. It uses the SCK, MISO and MOSI pins via the ICSP on your board.
+
+Note this means that it uses pin 13, 12, 11 on an Arduino Uno, so these pins can not be used for anything else than SPI communication!
+
+Furthermore it uses one pin as SS and one INT pin. These are by default located on pin 10 and 9 respectively. They can easily be reconfigured in case you need to use them for something else by cutting the jumper on the shield and then solder a wire from the pad to the new pin.
+
+After that you need modify the following entry in [UsbCore.h](UsbCore.h):
+
+```C++
+typedef MAX3421e<P10, P9> MAX3421E;
+```
+
+For instance if you have rerouted SS to pin 7 it should read:
+
+```C++
+typedef MAX3421e<P7, P9> MAX3421E;
+```
+
+See the "Interface modifications" section in the [hardware manual](https://www.circuitsathome.com/usb-host-shield-hardware-manual) for more information.
+
+# FAQ
+
+> When I plug my device into the USB connector nothing happens?
+
+* Try to connect a external power supply to the Arduino - this solves the problem in most cases.
+* You can also use a powered hub between the device and the USB Host Shield. You should then include the USB hub library: ```#include <usbhub.h>``` and create the instance like so: ```USBHub Hub1(&Usb);```.
+
+> When I connecting my PS3 controller I get a output like this:
+
+```
+Dualshock 3 Controller Enabled
+
+LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
+LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
+LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
+LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
+LeftHatX: 0 LeftHatY: 0 RightHatX: 0 RightHatY: 0
+```
+
+* This means that your dongle does not support 2.0+EDR, so you will need another dongle. Please see the following [list](https://github.com/felis/USB_Host_Shield_2.0/wiki/Bluetooth-dongles) for tested working dongles.
+
+> When compiling I am getting the following error: "fatal error: SPI.h: No such file or directory".
+
+* Please make sure to include the SPI library like so: ```#include <SPI.h>``` in your .ino file.
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/settings.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/settings.h
new file mode 100644
index 000000000..5c060354b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/settings.h
@@ -0,0 +1,139 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#ifndef USB_HOST_SHIELD_SETTINGS_H
+#define USB_HOST_SHIELD_SETTINGS_H
+#include "macros.h"
+
+////////////////////////////////////////////////////////////////////////////////
+// DEBUGGING
+////////////////////////////////////////////////////////////////////////////////
+
+/* Set this to 1 to activate serial debugging */
+#define ENABLE_UHS_DEBUGGING 0
+
+/* This can be used to select which serial port to use for debugging if
+ * multiple serial ports are available.
+ * For example Serial3.
+ */
+#ifndef USB_HOST_SERIAL
+#define USB_HOST_SERIAL Serial
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+// Manual board activation
+////////////////////////////////////////////////////////////////////////////////
+
+/* Set this to 1 if you are using an Arduino Mega ADK board with MAX3421e built-in */
+#define USE_UHS_MEGA_ADK 0 // If you are using Arduino 1.5.5 or newer there is no need to do this manually
+
+/* Set this to 1 if you are using a Black Widdow */
+#define USE_UHS_BLACK_WIDDOW 0
+
+/* Set this to a one to use the xmem2 lock. This is needed for multitasking and threading */
+#define USE_XMEM_SPI_LOCK 0
+
+////////////////////////////////////////////////////////////////////////////////
+// Wii IR camera
+////////////////////////////////////////////////////////////////////////////////
+
+/* Set this to 1 to activate code for the Wii IR camera */
+#define ENABLE_WII_IR_CAMERA 0
+
+////////////////////////////////////////////////////////////////////////////////
+// MASS STORAGE
+////////////////////////////////////////////////////////////////////////////////
+// <<<<<<<<<<<<<<<< IMPORTANT >>>>>>>>>>>>>>>
+// Set this to 1 to support single LUN devices, and save RAM. -- I.E. thumb drives.
+// Each LUN needs ~13 bytes to be able to track the state of each unit.
+#ifndef MASS_MAX_SUPPORTED_LUN
+#define MASS_MAX_SUPPORTED_LUN 8
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+// Set to 1 to use the faster spi4teensy3 driver.
+////////////////////////////////////////////////////////////////////////////////
+#ifndef USE_SPI4TEENSY3
+#define USE_SPI4TEENSY3 1
+#endif
+
+////////////////////////////////////////////////////////////////////////////////
+// AUTOMATIC Settings
+////////////////////////////////////////////////////////////////////////////////
+
+// No user serviceable parts below this line.
+// DO NOT change anything below here unless you are a developer!
+
+#include "version_helper.h"
+
+#if defined(__GNUC__) && defined(__AVR__)
+#ifndef GCC_VERSION
+#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
+#endif
+#if GCC_VERSION < 40602 // Test for GCC < 4.6.2
+#ifdef PROGMEM
+#undef PROGMEM
+#define PROGMEM __attribute__((section(".progmem.data"))) // Workaround for http://gcc.gnu.org/bugzilla/show_bug.cgi?id=34734#c4
+#ifdef PSTR
+#undef PSTR
+#define PSTR(s) (__extension__({static const char __c[] PROGMEM = (s); &__c[0];})) // Copied from pgmspace.h in avr-libc source
+#endif
+#endif
+#endif
+#endif
+
+#if !defined(DEBUG_USB_HOST) && ENABLE_UHS_DEBUGGING
+#define DEBUG_USB_HOST
+#endif
+
+#if !defined(WIICAMERA) && ENABLE_WII_IR_CAMERA
+#define WIICAMERA
+#endif
+
+// To use some other locking (e.g. freertos),
+// define XMEM_ACQUIRE_SPI and XMEM_RELEASE_SPI to point to your lock and unlock.
+// NOTE: NO argument is passed. You have to do this within your routine for
+// whatever you are using to lock and unlock.
+#if !defined(XMEM_ACQUIRE_SPI)
+#if USE_XMEM_SPI_LOCK || defined(USE_MULTIPLE_APP_API)
+#include <xmem.h>
+#else
+#define XMEM_ACQUIRE_SPI() (void(0))
+#define XMEM_RELEASE_SPI() (void(0))
+#endif
+#endif
+
+#if !defined(EXT_RAM) && defined(EXT_RAM_STACK) || defined(EXT_RAM_HEAP)
+#include <xmem.h>
+#else
+#define EXT_RAM 0
+#endif
+
+#if defined(CORE_TEENSY) && (defined(__MK20DX128__) || defined(__MK20DX256__))
+#define USING_SPI4TEENSY3 USE_SPI4TEENSY3
+#else
+#define USING_SPI4TEENSY3 0
+#endif
+
+#if ((defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__)) || defined(RBL_NRF51822) || defined(__ARDUINO_X86__) || ARDUINO >= 10600) && !USING_SPI4TEENSY3
+#include <SPI.h> // Use the Arduino SPI library for the Arduino Due, RedBearLab nRF51822, Intel Galileo 1 & 2, Intel Edison or if the SPI library with transaction is available
+#endif
+#if defined(__PIC32MX__) || defined(__PIC32MZ__)
+#include <../../../../hardware/pic32/libraries/SPI/SPI.h> // Hack to use the SPI library
+#endif
+
+#endif /* SETTINGS_H */
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/sink_parser.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/sink_parser.h
new file mode 100644
index 000000000..a23637d2b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/sink_parser.h
@@ -0,0 +1,41 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(_usb_h_) || defined(__SINK_PARSER_H__)
+#error "Never include hexdump.h directly; include Usb.h instead"
+#else
+#define __SINK_PARSER_H__
+
+extern int UsbDEBUGlvl;
+
+// This parser does absolutely nothing with the data, just swallows it.
+
+template <class BASE_CLASS, class LEN_TYPE, class OFFSET_TYPE>
+class SinkParser : public BASE_CLASS {
+public:
+
+ SinkParser() {
+ };
+
+ void Initialize() {
+ };
+
+ void Parse(const LEN_TYPE len, const uint8_t *pbuf, const OFFSET_TYPE &offset) {
+ };
+};
+
+
+#endif // __HEXDUMP_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usb_ch9.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usb_ch9.h
new file mode 100644
index 000000000..18f2d3e2e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usb_ch9.h
@@ -0,0 +1,166 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+#if !defined(_usb_h_) || defined(_ch9_h_)
+#error "Never include usb_ch9.h directly; include Usb.h instead"
+#else
+
+/* USB chapter 9 structures */
+#define _ch9_h_
+
+/* Misc.USB constants */
+#define DEV_DESCR_LEN 18 //device descriptor length
+#define CONF_DESCR_LEN 9 //configuration descriptor length
+#define INTR_DESCR_LEN 9 //interface descriptor length
+#define EP_DESCR_LEN 7 //endpoint descriptor length
+
+/* Standard Device Requests */
+
+#define USB_REQUEST_GET_STATUS 0 // Standard Device Request - GET STATUS
+#define USB_REQUEST_CLEAR_FEATURE 1 // Standard Device Request - CLEAR FEATURE
+#define USB_REQUEST_SET_FEATURE 3 // Standard Device Request - SET FEATURE
+#define USB_REQUEST_SET_ADDRESS 5 // Standard Device Request - SET ADDRESS
+#define USB_REQUEST_GET_DESCRIPTOR 6 // Standard Device Request - GET DESCRIPTOR
+#define USB_REQUEST_SET_DESCRIPTOR 7 // Standard Device Request - SET DESCRIPTOR
+#define USB_REQUEST_GET_CONFIGURATION 8 // Standard Device Request - GET CONFIGURATION
+#define USB_REQUEST_SET_CONFIGURATION 9 // Standard Device Request - SET CONFIGURATION
+#define USB_REQUEST_GET_INTERFACE 10 // Standard Device Request - GET INTERFACE
+#define USB_REQUEST_SET_INTERFACE 11 // Standard Device Request - SET INTERFACE
+#define USB_REQUEST_SYNCH_FRAME 12 // Standard Device Request - SYNCH FRAME
+
+#define USB_FEATURE_ENDPOINT_HALT 0 // CLEAR/SET FEATURE - Endpoint Halt
+#define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // CLEAR/SET FEATURE - Device remote wake-up
+#define USB_FEATURE_TEST_MODE 2 // CLEAR/SET FEATURE - Test mode
+
+/* Setup Data Constants */
+
+#define USB_SETUP_HOST_TO_DEVICE 0x00 // Device Request bmRequestType transfer direction - host to device transfer
+#define USB_SETUP_DEVICE_TO_HOST 0x80 // Device Request bmRequestType transfer direction - device to host transfer
+#define USB_SETUP_TYPE_STANDARD 0x00 // Device Request bmRequestType type - standard
+#define USB_SETUP_TYPE_CLASS 0x20 // Device Request bmRequestType type - class
+#define USB_SETUP_TYPE_VENDOR 0x40 // Device Request bmRequestType type - vendor
+#define USB_SETUP_RECIPIENT_DEVICE 0x00 // Device Request bmRequestType recipient - device
+#define USB_SETUP_RECIPIENT_INTERFACE 0x01 // Device Request bmRequestType recipient - interface
+#define USB_SETUP_RECIPIENT_ENDPOINT 0x02 // Device Request bmRequestType recipient - endpoint
+#define USB_SETUP_RECIPIENT_OTHER 0x03 // Device Request bmRequestType recipient - other
+
+/* USB descriptors */
+
+#define USB_DESCRIPTOR_DEVICE 0x01 // bDescriptorType for a Device Descriptor.
+#define USB_DESCRIPTOR_CONFIGURATION 0x02 // bDescriptorType for a Configuration Descriptor.
+#define USB_DESCRIPTOR_STRING 0x03 // bDescriptorType for a String Descriptor.
+#define USB_DESCRIPTOR_INTERFACE 0x04 // bDescriptorType for an Interface Descriptor.
+#define USB_DESCRIPTOR_ENDPOINT 0x05 // bDescriptorType for an Endpoint Descriptor.
+#define USB_DESCRIPTOR_DEVICE_QUALIFIER 0x06 // bDescriptorType for a Device Qualifier.
+#define USB_DESCRIPTOR_OTHER_SPEED 0x07 // bDescriptorType for a Other Speed Configuration.
+#define USB_DESCRIPTOR_INTERFACE_POWER 0x08 // bDescriptorType for Interface Power.
+#define USB_DESCRIPTOR_OTG 0x09 // bDescriptorType for an OTG Descriptor.
+
+#define HID_DESCRIPTOR_HID 0x21
+
+
+
+/* OTG SET FEATURE Constants */
+#define OTG_FEATURE_B_HNP_ENABLE 3 // SET FEATURE OTG - Enable B device to perform HNP
+#define OTG_FEATURE_A_HNP_SUPPORT 4 // SET FEATURE OTG - A device supports HNP
+#define OTG_FEATURE_A_ALT_HNP_SUPPORT 5 // SET FEATURE OTG - Another port on the A device supports HNP
+
+/* USB Endpoint Transfer Types */
+#define USB_TRANSFER_TYPE_CONTROL 0x00 // Endpoint is a control endpoint.
+#define USB_TRANSFER_TYPE_ISOCHRONOUS 0x01 // Endpoint is an isochronous endpoint.
+#define USB_TRANSFER_TYPE_BULK 0x02 // Endpoint is a bulk endpoint.
+#define USB_TRANSFER_TYPE_INTERRUPT 0x03 // Endpoint is an interrupt endpoint.
+#define bmUSB_TRANSFER_TYPE 0x03 // bit mask to separate transfer type from ISO attributes
+
+
+/* Standard Feature Selectors for CLEAR_FEATURE Requests */
+#define USB_FEATURE_ENDPOINT_STALL 0 // Endpoint recipient
+#define USB_FEATURE_DEVICE_REMOTE_WAKEUP 1 // Device recipient
+#define USB_FEATURE_TEST_MODE 2 // Device recipient
+
+/* descriptor data structures */
+
+/* Device descriptor structure */
+typedef struct {
+ uint8_t bLength; // Length of this descriptor.
+ uint8_t bDescriptorType; // DEVICE descriptor type (USB_DESCRIPTOR_DEVICE).
+ uint16_t bcdUSB; // USB Spec Release Number (BCD).
+ uint8_t bDeviceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific.
+ uint8_t bDeviceSubClass; // Subclass code (assigned by the USB-IF).
+ uint8_t bDeviceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific.
+ uint8_t bMaxPacketSize0; // Maximum packet size for endpoint 0.
+ uint16_t idVendor; // Vendor ID (assigned by the USB-IF).
+ uint16_t idProduct; // Product ID (assigned by the manufacturer).
+ uint16_t bcdDevice; // Device release number (BCD).
+ uint8_t iManufacturer; // Index of String Descriptor describing the manufacturer.
+ uint8_t iProduct; // Index of String Descriptor describing the product.
+ uint8_t iSerialNumber; // Index of String Descriptor with the device's serial number.
+ uint8_t bNumConfigurations; // Number of possible configurations.
+} __attribute__((packed)) USB_DEVICE_DESCRIPTOR;
+
+/* Configuration descriptor structure */
+typedef struct {
+ uint8_t bLength; // Length of this descriptor.
+ uint8_t bDescriptorType; // CONFIGURATION descriptor type (USB_DESCRIPTOR_CONFIGURATION).
+ uint16_t wTotalLength; // Total length of all descriptors for this configuration.
+ uint8_t bNumInterfaces; // Number of interfaces in this configuration.
+ uint8_t bConfigurationValue; // Value of this configuration (1 based).
+ uint8_t iConfiguration; // Index of String Descriptor describing the configuration.
+ uint8_t bmAttributes; // Configuration characteristics.
+ uint8_t bMaxPower; // Maximum power consumed by this configuration.
+} __attribute__((packed)) USB_CONFIGURATION_DESCRIPTOR;
+
+/* Interface descriptor structure */
+typedef struct {
+ uint8_t bLength; // Length of this descriptor.
+ uint8_t bDescriptorType; // INTERFACE descriptor type (USB_DESCRIPTOR_INTERFACE).
+ uint8_t bInterfaceNumber; // Number of this interface (0 based).
+ uint8_t bAlternateSetting; // Value of this alternate interface setting.
+ uint8_t bNumEndpoints; // Number of endpoints in this interface.
+ uint8_t bInterfaceClass; // Class code (assigned by the USB-IF). 0xFF-Vendor specific.
+ uint8_t bInterfaceSubClass; // Subclass code (assigned by the USB-IF).
+ uint8_t bInterfaceProtocol; // Protocol code (assigned by the USB-IF). 0xFF-Vendor specific.
+ uint8_t iInterface; // Index of String Descriptor describing the interface.
+} __attribute__((packed)) USB_INTERFACE_DESCRIPTOR;
+
+/* Endpoint descriptor structure */
+typedef struct {
+ uint8_t bLength; // Length of this descriptor.
+ uint8_t bDescriptorType; // ENDPOINT descriptor type (USB_DESCRIPTOR_ENDPOINT).
+ uint8_t bEndpointAddress; // Endpoint address. Bit 7 indicates direction (0=OUT, 1=IN).
+ uint8_t bmAttributes; // Endpoint transfer type.
+ uint16_t wMaxPacketSize; // Maximum packet size.
+ uint8_t bInterval; // Polling interval in frames.
+} __attribute__((packed)) USB_ENDPOINT_DESCRIPTOR;
+
+/* HID descriptor */
+typedef struct {
+ uint8_t bLength;
+ uint8_t bDescriptorType;
+ uint16_t bcdHID; // HID class specification release
+ uint8_t bCountryCode;
+ uint8_t bNumDescriptors; // Number of additional class specific descriptors
+ uint8_t bDescrType; // Type of class descriptor
+ uint16_t wDescriptorLength; // Total size of the Report descriptor
+} __attribute__((packed)) USB_HID_DESCRIPTOR;
+
+typedef struct {
+ uint8_t bDescrType; // Type of class descriptor
+ uint16_t wDescriptorLength; // Total size of the Report descriptor
+} __attribute__((packed)) HID_CLASS_DESCRIPTOR_LEN_AND_TYPE;
+
+#endif // _ch9_h_
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhost.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhost.h
new file mode 100644
index 000000000..eba480e60
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhost.h
@@ -0,0 +1,529 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+/* MAX3421E-based USB Host Library header file */
+
+
+#if !defined(_usb_h_) || defined(_USBHOST_H_)
+#error "Never include usbhost.h directly; include Usb.h instead"
+#else
+#define _USBHOST_H_
+
+#if USING_SPI4TEENSY3
+#include <spi4teensy3.h>
+#include <sys/types.h>
+#endif
+
+/* SPI initialization */
+template< typename SPI_CLK, typename SPI_MOSI, typename SPI_MISO, typename SPI_SS > class SPi {
+public:
+#if USING_SPI4TEENSY3
+ static void init() {
+ // spi4teensy3 inits everything for us, except /SS
+ // CLK, MOSI and MISO are hard coded for now.
+ // spi4teensy3::init(0,0,0); // full speed, cpol 0, cpha 0
+ spi4teensy3::init(); // full speed, cpol 0, cpha 0
+ SPI_SS::SetDirWrite();
+ SPI_SS::Set();
+ }
+#elif SPI_HAS_TRANSACTION
+ static void init() {
+ SPI.begin(); // The SPI library with transaction will take care of setting up the pins - settings is set in beginTransaction()
+ }
+#elif !defined(SPDR)
+ static void init() {
+ SPI_SS::SetDirWrite();
+ SPI_SS::Set();
+ SPI.begin();
+#if defined(__MIPSEL__)
+ SPI.setClockDivider(1);
+#elif defined(__ARDUINO_X86__)
+ #ifdef SPI_CLOCK_1M // Hack used to check if setClockSpeed is available
+ SPI.setClockSpeed(12000000); // The MAX3421E can handle up to 26MHz, but in practice this was the maximum that I could reliably use
+ #else
+ SPI.setClockDivider(SPI_CLOCK_DIV2); // This will set the SPI frequency to 8MHz - it could be higher, but it is not supported in the old API
+ #endif
+#else
+ SPI.setClockDivider(4); // Set speed to 84MHz/4=21MHz - the MAX3421E can handle up to 26MHz
+#endif
+ }
+#elif defined(RBL_NRF51822)
+ static void init() {
+ SPI_SS::SetDirWrite();
+ SPI_SS::Set();
+ SPI.begin();
+ // SPI.setFrequency(SPI_FREQUENCY_8M);
+ }
+#else
+ static void init() {
+ //uint8_t tmp;
+ SPI_CLK::SetDirWrite();
+ SPI_MOSI::SetDirWrite();
+ SPI_MISO::SetDirRead();
+ SPI_SS::SetDirWrite();
+ /* mode 00 (CPOL=0, CPHA=0) master, fclk/2. Mode 11 (CPOL=11, CPHA=11) is also supported by MAX3421E */
+ SPCR = 0x50;
+ SPSR = 0x01; // 0x01
+ /**/
+ //tmp = SPSR;
+ //tmp = SPDR;
+ }
+#endif
+};
+
+/* SPI pin definitions. see avrpins.h */
+#if defined(__AVR_ATmega1280__) || (__AVR_ATmega2560__) || defined(__AVR_ATmega32U4__) || defined(__AVR_AT90USB646__) || defined(__AVR_AT90USB1286__)
+typedef SPi< Pb1, Pb2, Pb3, Pb0 > spi;
+#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
+typedef SPi< Pb5, Pb3, Pb4, Pb2 > spi;
+#elif defined(__AVR_ATmega644__) || defined(__AVR_ATmega644P__) || defined(__AVR_ATmega1284__) || defined(__AVR_ATmega1284P__)
+typedef SPi< Pb7, Pb5, Pb6, Pb4 > spi;
+#elif (defined(CORE_TEENSY) && (defined(__MK20DX128__) || defined(__MK20DX256__))) || defined(__ARDUINO_X86__) || defined(__MIPSEL__)
+typedef SPi< P13, P11, P12, P10 > spi;
+#elif defined(ARDUINO_SAM_DUE) && defined(__SAM3X8E__)
+typedef SPi< P76, P75, P74, P10 > spi;
+#elif defined(RBL_NRF51822)
+typedef SPi< P16, P18, P17, P10 > spi;
+#else
+#error "No SPI entry in usbhost.h"
+#endif
+
+typedef enum {
+ vbus_on = 0,
+ vbus_off = GPX_VBDET
+} VBUS_t;
+
+template< typename SPI_SS, typename INTR > class MAX3421e /* : public spi */ {
+ static uint8_t vbusState;
+
+public:
+ MAX3421e();
+ void regWr(uint8_t reg, uint8_t data);
+ uint8_t* bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* data_p);
+ void gpioWr(uint8_t data);
+ uint8_t regRd(uint8_t reg);
+ uint8_t* bytesRd(uint8_t reg, uint8_t nbytes, uint8_t* data_p);
+ uint8_t gpioRd();
+ uint16_t reset();
+ int8_t Init();
+ int8_t Init(int mseconds);
+
+ void vbusPower(VBUS_t state) {
+ regWr(rPINCTL, (bmFDUPSPI | bmINTLEVEL | state));
+ }
+
+ uint8_t getVbusState(void) {
+ return vbusState;
+ };
+ void busprobe();
+ uint8_t GpxHandler();
+ uint8_t IntHandler();
+ uint8_t Task();
+};
+
+template< typename SPI_SS, typename INTR >
+ uint8_t MAX3421e< SPI_SS, INTR >::vbusState = 0;
+
+/* constructor */
+template< typename SPI_SS, typename INTR >
+MAX3421e< SPI_SS, INTR >::MAX3421e() {
+ // Leaving ADK hardware setup in here, for now. This really belongs with the other parts.
+#ifdef BOARD_MEGA_ADK
+ // For Mega ADK, which has a Max3421e on-board, set MAX_RESET to output mode, and then set it to HIGH
+ P55::SetDirWrite();
+ P55::Set();
+#endif
+};
+
+/* write single byte into MAX3421 register */
+template< typename SPI_SS, typename INTR >
+void MAX3421e< SPI_SS, INTR >::regWr(uint8_t reg, uint8_t data) {
+ XMEM_ACQUIRE_SPI();
+#if SPI_HAS_TRANSACTION
+ SPI.beginTransaction(SPISettings(26000000, MSBFIRST, SPI_MODE0)); // The MAX3421E can handle up to 26MHz, use MSB First and SPI mode 0
+#endif
+ SPI_SS::Clear();
+
+#if USING_SPI4TEENSY3
+ uint8_t c[2];
+ c[0] = reg | 0x02;
+ c[1] = data;
+ spi4teensy3::send(c, 2);
+#elif SPI_HAS_TRANSACTION
+ uint8_t c[2];
+ c[0] = reg | 0x02;
+ c[1] = data;
+ SPI.transfer(c, 2);
+#elif !defined(SPDR)
+ SPI.transfer(reg | 0x02);
+ SPI.transfer(data);
+#else
+ SPDR = (reg | 0x02);
+ while(!(SPSR & (1 << SPIF)));
+ SPDR = data;
+ while(!(SPSR & (1 << SPIF)));
+#endif
+
+ SPI_SS::Set();
+#if SPI_HAS_TRANSACTION
+ SPI.endTransaction();
+#endif
+ XMEM_RELEASE_SPI();
+ return;
+};
+/* multiple-byte write */
+
+/* returns a pointer to memory position after last written */
+template< typename SPI_SS, typename INTR >
+uint8_t* MAX3421e< SPI_SS, INTR >::bytesWr(uint8_t reg, uint8_t nbytes, uint8_t* data_p) {
+ XMEM_ACQUIRE_SPI();
+#if SPI_HAS_TRANSACTION
+ SPI.beginTransaction(SPISettings(26000000, MSBFIRST, SPI_MODE0)); // The MAX3421E can handle up to 26MHz, use MSB First and SPI mode 0
+#endif
+ SPI_SS::Clear();
+
+#if USING_SPI4TEENSY3
+ spi4teensy3::send(reg | 0x02);
+ spi4teensy3::send(data_p, nbytes);
+ data_p += nbytes;
+#elif SPI_HAS_TRANSACTION
+ SPI.transfer(reg | 0x02);
+ SPI.transfer(data_p, nbytes);
+ data_p += nbytes;
+#elif defined(__ARDUINO_X86__)
+ SPI.transfer(reg | 0x02);
+ SPI.transferBuffer(data_p, NULL, nbytes);
+ data_p += nbytes;
+#elif !defined(SPDR)
+ SPI.transfer(reg | 0x02);
+ while(nbytes) {
+ SPI.transfer(*data_p);
+ nbytes--;
+ data_p++; // advance data pointer
+ }
+#else
+ SPDR = (reg | 0x02); //set WR bit and send register number
+ while(nbytes) {
+ while(!(SPSR & (1 << SPIF))); //check if previous byte was sent
+ SPDR = (*data_p); // send next data byte
+ nbytes--;
+ data_p++; // advance data pointer
+ }
+ while(!(SPSR & (1 << SPIF)));
+#endif
+
+ SPI_SS::Set();
+#if SPI_HAS_TRANSACTION
+ SPI.endTransaction();
+#endif
+ XMEM_RELEASE_SPI();
+ return ( data_p);
+}
+/* GPIO write */
+/*GPIO byte is split between 2 registers, so two writes are needed to write one byte */
+
+/* GPOUT bits are in the low nibble. 0-3 in IOPINS1, 4-7 in IOPINS2 */
+template< typename SPI_SS, typename INTR >
+void MAX3421e< SPI_SS, INTR >::gpioWr(uint8_t data) {
+ regWr(rIOPINS1, data);
+ data >>= 4;
+ regWr(rIOPINS2, data);
+ return;
+}
+
+/* single host register read */
+template< typename SPI_SS, typename INTR >
+uint8_t MAX3421e< SPI_SS, INTR >::regRd(uint8_t reg) {
+ XMEM_ACQUIRE_SPI();
+#if SPI_HAS_TRANSACTION
+ SPI.beginTransaction(SPISettings(26000000, MSBFIRST, SPI_MODE0)); // The MAX3421E can handle up to 26MHz, use MSB First and SPI mode 0
+#endif
+ SPI_SS::Clear();
+
+#if USING_SPI4TEENSY3
+ spi4teensy3::send(reg);
+ uint8_t rv = spi4teensy3::receive();
+ SPI_SS::Set();
+#elif !defined(SPDR) || SPI_HAS_TRANSACTION
+ SPI.transfer(reg);
+ uint8_t rv = SPI.transfer(0); // Send empty byte
+ SPI_SS::Set();
+#else
+ SPDR = reg;
+ while(!(SPSR & (1 << SPIF)));
+ SPDR = 0; // Send empty byte
+ while(!(SPSR & (1 << SPIF)));
+ SPI_SS::Set();
+ uint8_t rv = SPDR;
+#endif
+
+#if SPI_HAS_TRANSACTION
+ SPI.endTransaction();
+#endif
+ XMEM_RELEASE_SPI();
+ return (rv);
+}
+/* multiple-byte register read */
+
+/* returns a pointer to a memory position after last read */
+template< typename SPI_SS, typename INTR >
+uint8_t* MAX3421e< SPI_SS, INTR >::bytesRd(uint8_t reg, uint8_t nbytes, uint8_t* data_p) {
+ XMEM_ACQUIRE_SPI();
+#if SPI_HAS_TRANSACTION
+ SPI.beginTransaction(SPISettings(26000000, MSBFIRST, SPI_MODE0)); // The MAX3421E can handle up to 26MHz, use MSB First and SPI mode 0
+#endif
+ SPI_SS::Clear();
+
+#if USING_SPI4TEENSY3
+ spi4teensy3::send(reg);
+ spi4teensy3::receive(data_p, nbytes);
+ data_p += nbytes;
+#elif SPI_HAS_TRANSACTION
+ SPI.transfer(reg);
+ memset(data_p, 0, nbytes); // Make sure we send out empty bytes
+ SPI.transfer(data_p, nbytes);
+ data_p += nbytes;
+#elif defined(__ARDUINO_X86__)
+ SPI.transfer(reg);
+ SPI.transferBuffer(NULL, data_p, nbytes);
+ data_p += nbytes;
+#elif !defined(SPDR)
+ SPI.transfer(reg);
+ while(nbytes) {
+ *data_p++ = SPI.transfer(0);
+ nbytes--;
+ }
+#else
+ SPDR = reg;
+ while(!(SPSR & (1 << SPIF))); //wait
+ while(nbytes) {
+ SPDR = 0; // Send empty byte
+ nbytes--;
+ while(!(SPSR & (1 << SPIF)));
+#if 0
+ {
+ *data_p = SPDR;
+ printf("%2.2x ", *data_p);
+ }
+ data_p++;
+ }
+ printf("\r\n");
+#else
+ *data_p++ = SPDR;
+ }
+#endif
+#endif
+
+ SPI_SS::Set();
+#if SPI_HAS_TRANSACTION
+ SPI.endTransaction();
+#endif
+ XMEM_RELEASE_SPI();
+ return ( data_p);
+}
+/* GPIO read. See gpioWr for explanation */
+
+/* GPIN pins are in high nibbles of IOPINS1, IOPINS2 */
+template< typename SPI_SS, typename INTR >
+uint8_t MAX3421e< SPI_SS, INTR >::gpioRd() {
+ uint8_t gpin = 0;
+ gpin = regRd(rIOPINS2); //pins 4-7
+ gpin &= 0xf0; //clean lower nibble
+ gpin |= (regRd(rIOPINS1) >> 4); //shift low bits and OR with upper from previous operation.
+ return ( gpin);
+}
+
+/* reset MAX3421E. Returns number of cycles it took for PLL to stabilize after reset
+ or zero if PLL haven't stabilized in 65535 cycles */
+template< typename SPI_SS, typename INTR >
+uint16_t MAX3421e< SPI_SS, INTR >::reset() {
+ uint16_t i = 0;
+ regWr(rUSBCTL, bmCHIPRES);
+ regWr(rUSBCTL, 0x00);
+ while(++i) {
+ if((regRd(rUSBIRQ) & bmOSCOKIRQ)) {
+ break;
+ }
+ }
+ return ( i);
+}
+
+/* initialize MAX3421E. Set Host mode, pullups, and stuff. Returns 0 if success, -1 if not */
+template< typename SPI_SS, typename INTR >
+int8_t MAX3421e< SPI_SS, INTR >::Init() {
+ XMEM_ACQUIRE_SPI();
+ // Moved here.
+ // you really should not init hardware in the constructor when it involves locks.
+ // Also avoids the vbus flicker issue confusing some devices.
+ /* pin and peripheral setup */
+ SPI_SS::SetDirWrite();
+ SPI_SS::Set();
+ spi::init();
+ INTR::SetDirRead();
+ XMEM_RELEASE_SPI();
+ /* MAX3421E - full-duplex SPI, level interrupt */
+ // GPX pin on. Moved here, otherwise we flicker the vbus.
+ regWr(rPINCTL, (bmFDUPSPI | bmINTLEVEL));
+
+ if(reset() == 0) { //OSCOKIRQ hasn't asserted in time
+ return ( -1);
+ }
+
+ regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST); // set pull-downs, Host
+
+ regWr(rHIEN, bmCONDETIE | bmFRAMEIE); //connection detection
+
+ /* check if device is connected */
+ regWr(rHCTL, bmSAMPLEBUS); // sample USB bus
+ while(!(regRd(rHCTL) & bmSAMPLEBUS)); //wait for sample operation to finish
+
+ busprobe(); //check if anything is connected
+
+ regWr(rHIRQ, bmCONDETIRQ); //clear connection detect interrupt
+ regWr(rCPUCTL, 0x01); //enable interrupt pin
+
+ return ( 0);
+}
+
+/* initialize MAX3421E. Set Host mode, pullups, and stuff. Returns 0 if success, -1 if not */
+template< typename SPI_SS, typename INTR >
+int8_t MAX3421e< SPI_SS, INTR >::Init(int mseconds) {
+ XMEM_ACQUIRE_SPI();
+ // Moved here.
+ // you really should not init hardware in the constructor when it involves locks.
+ // Also avoids the vbus flicker issue confusing some devices.
+ /* pin and peripheral setup */
+ SPI_SS::SetDirWrite();
+ SPI_SS::Set();
+ spi::init();
+ INTR::SetDirRead();
+ XMEM_RELEASE_SPI();
+ /* MAX3421E - full-duplex SPI, level interrupt, vbus off */
+ regWr(rPINCTL, (bmFDUPSPI | bmINTLEVEL | GPX_VBDET));
+
+ if(reset() == 0) { //OSCOKIRQ hasn't asserted in time
+ return ( -1);
+ }
+
+ // Delay a minimum of 1 second to ensure any capacitors are drained.
+ // 1 second is required to make sure we do not smoke a Microdrive!
+ if(mseconds < 1000) mseconds = 1000;
+ delay(mseconds);
+
+ regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST); // set pull-downs, Host
+
+ regWr(rHIEN, bmCONDETIE | bmFRAMEIE); //connection detection
+
+ /* check if device is connected */
+ regWr(rHCTL, bmSAMPLEBUS); // sample USB bus
+ while(!(regRd(rHCTL) & bmSAMPLEBUS)); //wait for sample operation to finish
+
+ busprobe(); //check if anything is connected
+
+ regWr(rHIRQ, bmCONDETIRQ); //clear connection detect interrupt
+ regWr(rCPUCTL, 0x01); //enable interrupt pin
+
+ // GPX pin on. This is done here so that busprobe will fail if we have a switch connected.
+ regWr(rPINCTL, (bmFDUPSPI | bmINTLEVEL));
+
+ return ( 0);
+}
+
+/* probe bus to determine device presence and speed and switch host to this speed */
+template< typename SPI_SS, typename INTR >
+void MAX3421e< SPI_SS, INTR >::busprobe() {
+ uint8_t bus_sample;
+ bus_sample = regRd(rHRSL); //Get J,K status
+ bus_sample &= (bmJSTATUS | bmKSTATUS); //zero the rest of the byte
+ switch(bus_sample) { //start full-speed or low-speed host
+ case( bmJSTATUS):
+ if((regRd(rMODE) & bmLOWSPEED) == 0) {
+ regWr(rMODE, MODE_FS_HOST); //start full-speed host
+ vbusState = FSHOST;
+ } else {
+ regWr(rMODE, MODE_LS_HOST); //start low-speed host
+ vbusState = LSHOST;
+ }
+ break;
+ case( bmKSTATUS):
+ if((regRd(rMODE) & bmLOWSPEED) == 0) {
+ regWr(rMODE, MODE_LS_HOST); //start low-speed host
+ vbusState = LSHOST;
+ } else {
+ regWr(rMODE, MODE_FS_HOST); //start full-speed host
+ vbusState = FSHOST;
+ }
+ break;
+ case( bmSE1): //illegal state
+ vbusState = SE1;
+ break;
+ case( bmSE0): //disconnected state
+ regWr(rMODE, bmDPPULLDN | bmDMPULLDN | bmHOST | bmSEPIRQ);
+ vbusState = SE0;
+ break;
+ }//end switch( bus_sample )
+}
+
+/* MAX3421 state change task and interrupt handler */
+template< typename SPI_SS, typename INTR >
+uint8_t MAX3421e< SPI_SS, INTR >::Task(void) {
+ uint8_t rcode = 0;
+ uint8_t pinvalue;
+ //USB_HOST_SERIAL.print("Vbus state: ");
+ //USB_HOST_SERIAL.println( vbusState, HEX );
+ pinvalue = INTR::IsSet(); //Read();
+ //pinvalue = digitalRead( MAX_INT );
+ if(pinvalue == 0) {
+ rcode = IntHandler();
+ }
+ // pinvalue = digitalRead( MAX_GPX );
+ // if( pinvalue == LOW ) {
+ // GpxHandler();
+ // }
+ // usbSM(); //USB state machine
+ return ( rcode);
+}
+
+template< typename SPI_SS, typename INTR >
+uint8_t MAX3421e< SPI_SS, INTR >::IntHandler() {
+ uint8_t HIRQ;
+ uint8_t HIRQ_sendback = 0x00;
+ HIRQ = regRd(rHIRQ); //determine interrupt source
+ //if( HIRQ & bmFRAMEIRQ ) { //->1ms SOF interrupt handler
+ // HIRQ_sendback |= bmFRAMEIRQ;
+ //}//end FRAMEIRQ handling
+ if(HIRQ & bmCONDETIRQ) {
+ busprobe();
+ HIRQ_sendback |= bmCONDETIRQ;
+ }
+ /* End HIRQ interrupts handling, clear serviced IRQs */
+ regWr(rHIRQ, HIRQ_sendback);
+ return ( HIRQ_sendback);
+}
+//template< typename SPI_SS, typename INTR >
+//uint8_t MAX3421e< SPI_SS, INTR >::GpxHandler()
+//{
+// uint8_t GPINIRQ = regRd( rGPINIRQ ); //read GPIN IRQ register
+//// if( GPINIRQ & bmGPINIRQ7 ) { //vbus overload
+//// vbusPwr( OFF ); //attempt powercycle
+//// delay( 1000 );
+//// vbusPwr( ON );
+//// regWr( rGPINIRQ, bmGPINIRQ7 );
+//// }
+// return( GPINIRQ );
+//}
+
+#endif // _USBHOST_H_
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhub.cpp b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhub.cpp
new file mode 100644
index 000000000..7fed48e78
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhub.cpp
@@ -0,0 +1,425 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#include "usbhub.h"
+
+bool USBHub::bResetInitiated = false;
+
+USBHub::USBHub(USB *p) :
+pUsb(p),
+bAddress(0),
+bNbrPorts(0),
+//bInitState(0),
+qNextPollTime(0),
+bPollEnable(false) {
+ epInfo[0].epAddr = 0;
+ epInfo[0].maxPktSize = 8;
+ epInfo[0].epAttribs = 0;
+ epInfo[0].bmNakPower = USB_NAK_MAX_POWER;
+
+ epInfo[1].epAddr = 1;
+ epInfo[1].maxPktSize = 8; //kludge
+ epInfo[1].epAttribs = 0;
+ epInfo[1].bmNakPower = USB_NAK_NOWAIT;
+
+ if(pUsb)
+ pUsb->RegisterDeviceClass(this);
+}
+
+uint8_t USBHub::Init(uint8_t parent, uint8_t port, bool lowspeed) {
+ uint8_t buf[32];
+ USB_DEVICE_DESCRIPTOR * udd = reinterpret_cast<USB_DEVICE_DESCRIPTOR*>(buf);
+ HubDescriptor* hd = reinterpret_cast<HubDescriptor*>(buf);
+ USB_CONFIGURATION_DESCRIPTOR * ucd = reinterpret_cast<USB_CONFIGURATION_DESCRIPTOR*>(buf);
+ uint8_t rcode;
+ UsbDevice *p = NULL;
+ EpInfo *oldep_ptr = NULL;
+ uint8_t len = 0;
+ uint16_t cd_len = 0;
+
+ //USBTRACE("\r\nHub Init Start ");
+ //D_PrintHex<uint8_t > (bInitState, 0x80);
+
+ AddressPool &addrPool = pUsb->GetAddressPool();
+
+ //switch (bInitState) {
+ // case 0:
+ if(bAddress)
+ return USB_ERROR_CLASS_INSTANCE_ALREADY_IN_USE;
+
+ // Get pointer to pseudo device with address 0 assigned
+ p = addrPool.GetUsbDevicePtr(0);
+
+ if(!p)
+ return USB_ERROR_ADDRESS_NOT_FOUND_IN_POOL;
+
+ if(!p->epinfo)
+ return USB_ERROR_EPINFO_IS_NULL;
+
+ // Save old pointer to EP_RECORD of address 0
+ oldep_ptr = p->epinfo;
+
+ // Temporary assign new pointer to epInfo to p->epinfo in order to avoid toggle inconsistence
+ p->epinfo = epInfo;
+
+ p->lowspeed = lowspeed;
+
+ // Get device descriptor
+ rcode = pUsb->getDevDescr(0, 0, 8, (uint8_t*)buf);
+
+ p->lowspeed = false;
+
+ if(!rcode)
+ len = (buf[0] > 32) ? 32 : buf[0];
+
+ if(rcode) {
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+ return rcode;
+ }
+
+ // Extract device class from device descriptor
+ // If device class is not a hub return
+ if(udd->bDeviceClass != 0x09)
+ return USB_DEV_CONFIG_ERROR_DEVICE_NOT_SUPPORTED;
+
+ // Allocate new address according to device class
+ bAddress = addrPool.AllocAddress(parent, (udd->bDeviceClass == 0x09) ? true : false, port);
+
+ if(!bAddress)
+ return USB_ERROR_OUT_OF_ADDRESS_SPACE_IN_POOL;
+
+ // Extract Max Packet Size from the device descriptor
+ epInfo[0].maxPktSize = udd->bMaxPacketSize0;
+
+ // Assign new address to the device
+ rcode = pUsb->setAddr(0, 0, bAddress);
+
+ if(rcode) {
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+ addrPool.FreeAddress(bAddress);
+ bAddress = 0;
+ return rcode;
+ }
+
+ //USBTRACE2("\r\nHub address: ", bAddress );
+
+ // Restore p->epinfo
+ p->epinfo = oldep_ptr;
+
+ if(len)
+ rcode = pUsb->getDevDescr(bAddress, 0, len, (uint8_t*)buf);
+
+ if(rcode)
+ goto FailGetDevDescr;
+
+ // Assign epInfo to epinfo pointer
+ rcode = pUsb->setEpInfoEntry(bAddress, 2, epInfo);
+
+ if(rcode)
+ goto FailSetDevTblEntry;
+
+ // bInitState = 1;
+
+ // case 1:
+ // Get hub descriptor
+ rcode = GetHubDescriptor(0, 8, buf);
+
+ if(rcode)
+ goto FailGetHubDescr;
+
+ // Save number of ports for future use
+ bNbrPorts = hd->bNbrPorts;
+
+ // bInitState = 2;
+
+ // case 2:
+ // Read configuration Descriptor in Order To Obtain Proper Configuration Value
+ rcode = pUsb->getConfDescr(bAddress, 0, 8, 0, buf);
+
+ if(!rcode) {
+ cd_len = ucd->wTotalLength;
+ rcode = pUsb->getConfDescr(bAddress, 0, cd_len, 0, buf);
+ }
+ if(rcode)
+ goto FailGetConfDescr;
+
+ // The following code is of no practical use in real life applications.
+ // It only intended for the usb protocol sniffer to properly parse hub-class requests.
+ {
+ uint8_t buf2[24];
+
+ rcode = pUsb->getConfDescr(bAddress, 0, buf[0], 0, buf2);
+
+ if(rcode)
+ goto FailGetConfDescr;
+ }
+
+ // Set Configuration Value
+ rcode = pUsb->setConf(bAddress, 0, buf[5]);
+
+ if(rcode)
+ goto FailSetConfDescr;
+
+ // bInitState = 3;
+
+ // case 3:
+ // Power on all ports
+ for(uint8_t j = 1; j <= bNbrPorts; j++)
+ SetPortFeature(HUB_FEATURE_PORT_POWER, j, 0); //HubPortPowerOn(j);
+
+ pUsb->SetHubPreMask();
+ bPollEnable = true;
+ // bInitState = 0;
+ //}
+ //bInitState = 0;
+ //USBTRACE("...OK\r\n");
+ return 0;
+
+ // Oleg, No debugging?? -- xxxajk
+FailGetDevDescr:
+ goto Fail;
+
+FailSetDevTblEntry:
+ goto Fail;
+
+FailGetHubDescr:
+ goto Fail;
+
+FailGetConfDescr:
+ goto Fail;
+
+FailSetConfDescr:
+ goto Fail;
+
+Fail:
+ USBTRACE("...FAIL\r\n");
+ return rcode;
+}
+
+uint8_t USBHub::Release() {
+ pUsb->GetAddressPool().FreeAddress(bAddress);
+
+ if(bAddress == 0x41)
+ pUsb->SetHubPreMask();
+
+ bAddress = 0;
+ bNbrPorts = 0;
+ qNextPollTime = 0;
+ bPollEnable = false;
+ return 0;
+}
+
+uint8_t USBHub::Poll() {
+ uint8_t rcode = 0;
+
+ if(!bPollEnable)
+ return 0;
+
+ if(((long)(millis() - qNextPollTime) >= 0L)) {
+ rcode = CheckHubStatus();
+ qNextPollTime = millis() + 100;
+ }
+ return rcode;
+}
+
+uint8_t USBHub::CheckHubStatus() {
+ uint8_t rcode;
+ uint8_t buf[8];
+ uint16_t read = 1;
+
+ rcode = pUsb->inTransfer(bAddress, 1, &read, buf);
+
+ if(rcode)
+ return rcode;
+
+ //if (buf[0] & 0x01) // Hub Status Change
+ //{
+ // pUsb->PrintHubStatus(addr);
+ // rcode = GetHubStatus(1, 0, 1, 4, buf);
+ // if (rcode)
+ // {
+ // USB_HOST_SERIAL.print("GetHubStatus Error");
+ // USB_HOST_SERIAL.println(rcode, HEX);
+ // return rcode;
+ // }
+ //}
+ for(uint8_t port = 1, mask = 0x02; port < 8; mask <<= 1, port++) {
+ if(buf[0] & mask) {
+ HubEvent evt;
+ evt.bmEvent = 0;
+
+ rcode = GetPortStatus(port, 4, evt.evtBuff);
+
+ if(rcode)
+ continue;
+
+ rcode = PortStatusChange(port, evt);
+
+ if(rcode == HUB_ERROR_PORT_HAS_BEEN_RESET)
+ return 0;
+
+ if(rcode)
+ return rcode;
+ }
+ } // for
+
+ for(uint8_t port = 1; port <= bNbrPorts; port++) {
+ HubEvent evt;
+ evt.bmEvent = 0;
+
+ rcode = GetPortStatus(port, 4, evt.evtBuff);
+
+ if(rcode)
+ continue;
+
+ if((evt.bmStatus & bmHUB_PORT_STATE_CHECK_DISABLED) != bmHUB_PORT_STATE_DISABLED)
+ continue;
+
+ // Emulate connection event for the port
+ evt.bmChange |= bmHUB_PORT_STATUS_C_PORT_CONNECTION;
+
+ rcode = PortStatusChange(port, evt);
+
+ if(rcode == HUB_ERROR_PORT_HAS_BEEN_RESET)
+ return 0;
+
+ if(rcode)
+ return rcode;
+ } // for
+ return 0;
+}
+
+void USBHub::ResetHubPort(uint8_t port) {
+ HubEvent evt;
+ evt.bmEvent = 0;
+ uint8_t rcode;
+
+ ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0);
+ ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0);
+ SetPortFeature(HUB_FEATURE_PORT_RESET, port, 0);
+
+
+ for(int i = 0; i < 3; i++) {
+ rcode = GetPortStatus(port, 4, evt.evtBuff);
+ if(rcode) break; // Some kind of error, bail.
+ if(evt.bmEvent == bmHUB_PORT_EVENT_RESET_COMPLETE || evt.bmEvent == bmHUB_PORT_EVENT_LS_RESET_COMPLETE) {
+ break;
+ }
+ delay(100); // simulate polling.
+ }
+ ClearPortFeature(HUB_FEATURE_C_PORT_RESET, port, 0);
+ ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0);
+ delay(20);
+}
+
+uint8_t USBHub::PortStatusChange(uint8_t port, HubEvent &evt) {
+ switch(evt.bmEvent) {
+ // Device connected event
+ case bmHUB_PORT_EVENT_CONNECT:
+ case bmHUB_PORT_EVENT_LS_CONNECT:
+ if(bResetInitiated)
+ return 0;
+
+ ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0);
+ ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0);
+ SetPortFeature(HUB_FEATURE_PORT_RESET, port, 0);
+ bResetInitiated = true;
+ return HUB_ERROR_PORT_HAS_BEEN_RESET;
+
+ // Device disconnected event
+ case bmHUB_PORT_EVENT_DISCONNECT:
+ ClearPortFeature(HUB_FEATURE_C_PORT_ENABLE, port, 0);
+ ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0);
+ bResetInitiated = false;
+
+ UsbDeviceAddress a;
+ a.devAddress = 0;
+ a.bmHub = 0;
+ a.bmParent = bAddress;
+ a.bmAddress = port;
+ pUsb->ReleaseDevice(a.devAddress);
+ return 0;
+
+ // Reset complete event
+ case bmHUB_PORT_EVENT_RESET_COMPLETE:
+ case bmHUB_PORT_EVENT_LS_RESET_COMPLETE:
+ ClearPortFeature(HUB_FEATURE_C_PORT_RESET, port, 0);
+ ClearPortFeature(HUB_FEATURE_C_PORT_CONNECTION, port, 0);
+
+ delay(20);
+
+ a.devAddress = bAddress;
+
+ pUsb->Configuring(a.bmAddress, port, (evt.bmStatus & bmHUB_PORT_STATUS_PORT_LOW_SPEED));
+ bResetInitiated = false;
+ break;
+
+ } // switch (evt.bmEvent)
+ return 0;
+}
+
+void PrintHubPortStatus(USBHub *hubptr, uint8_t addr, uint8_t port, bool print_changes) {
+ uint8_t rcode = 0;
+ HubEvent evt;
+
+ rcode = hubptr->GetPortStatus(port, 4, evt.evtBuff);
+
+ if(rcode) {
+ USB_HOST_SERIAL.println("ERROR!");
+ return;
+ }
+ USB_HOST_SERIAL.print("\r\nPort ");
+ USB_HOST_SERIAL.println(port, DEC);
+
+ USB_HOST_SERIAL.println("Status");
+ USB_HOST_SERIAL.print("CONNECTION:\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_CONNECTION) > 0, DEC);
+ USB_HOST_SERIAL.print("ENABLE:\t\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_ENABLE) > 0, DEC);
+ USB_HOST_SERIAL.print("SUSPEND:\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_SUSPEND) > 0, DEC);
+ USB_HOST_SERIAL.print("OVER_CURRENT:\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_OVER_CURRENT) > 0, DEC);
+ USB_HOST_SERIAL.print("RESET:\t\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_RESET) > 0, DEC);
+ USB_HOST_SERIAL.print("POWER:\t\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_POWER) > 0, DEC);
+ USB_HOST_SERIAL.print("LOW_SPEED:\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_LOW_SPEED) > 0, DEC);
+ USB_HOST_SERIAL.print("HIGH_SPEED:\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_HIGH_SPEED) > 0, DEC);
+ USB_HOST_SERIAL.print("TEST:\t\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_TEST) > 0, DEC);
+ USB_HOST_SERIAL.print("INDICATOR:\t");
+ USB_HOST_SERIAL.println((evt.bmStatus & bmHUB_PORT_STATUS_PORT_INDICATOR) > 0, DEC);
+
+ if(!print_changes)
+ return;
+
+ USB_HOST_SERIAL.println("\r\nChange");
+ USB_HOST_SERIAL.print("CONNECTION:\t");
+ USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_CONNECTION) > 0, DEC);
+ USB_HOST_SERIAL.print("ENABLE:\t\t");
+ USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_ENABLE) > 0, DEC);
+ USB_HOST_SERIAL.print("SUSPEND:\t");
+ USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_SUSPEND) > 0, DEC);
+ USB_HOST_SERIAL.print("OVER_CURRENT:\t");
+ USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_OVER_CURRENT) > 0, DEC);
+ USB_HOST_SERIAL.print("RESET:\t\t");
+ USB_HOST_SERIAL.println((evt.bmChange & bmHUB_PORT_STATUS_C_PORT_RESET) > 0, DEC);
+}
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhub.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhub.h
new file mode 100644
index 000000000..1ac949445
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/usbhub.h
@@ -0,0 +1,252 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+#if !defined(__USBHUB_H__)
+#define __USBHUB_H__
+
+#include "Usb.h"
+
+#define USB_DESCRIPTOR_HUB 0x09 // Hub descriptor type
+
+// Hub Requests
+#define bmREQ_CLEAR_HUB_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE
+#define bmREQ_CLEAR_PORT_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER
+#define bmREQ_CLEAR_TT_BUFFER USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER
+#define bmREQ_GET_HUB_DESCRIPTOR USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE
+#define bmREQ_GET_HUB_STATUS USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE
+#define bmREQ_GET_PORT_STATUS USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER
+#define bmREQ_RESET_TT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER
+#define bmREQ_SET_HUB_DESCRIPTOR USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE
+#define bmREQ_SET_HUB_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_DEVICE
+#define bmREQ_SET_PORT_FEATURE USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER
+#define bmREQ_GET_TT_STATE USB_SETUP_DEVICE_TO_HOST|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER
+#define bmREQ_STOP_TT USB_SETUP_HOST_TO_DEVICE|USB_SETUP_TYPE_CLASS|USB_SETUP_RECIPIENT_OTHER
+
+// Hub Class Requests
+#define HUB_REQUEST_CLEAR_TT_BUFFER 8
+#define HUB_REQUEST_RESET_TT 9
+#define HUB_REQUEST_GET_TT_STATE 10
+#define HUB_REQUEST_STOP_TT 11
+
+// Hub Features
+#define HUB_FEATURE_C_HUB_LOCAL_POWER 0
+#define HUB_FEATURE_C_HUB_OVER_CURRENT 1
+#define HUB_FEATURE_PORT_CONNECTION 0
+#define HUB_FEATURE_PORT_ENABLE 1
+#define HUB_FEATURE_PORT_SUSPEND 2
+#define HUB_FEATURE_PORT_OVER_CURRENT 3
+#define HUB_FEATURE_PORT_RESET 4
+#define HUB_FEATURE_PORT_POWER 8
+#define HUB_FEATURE_PORT_LOW_SPEED 9
+#define HUB_FEATURE_C_PORT_CONNECTION 16
+#define HUB_FEATURE_C_PORT_ENABLE 17
+#define HUB_FEATURE_C_PORT_SUSPEND 18
+#define HUB_FEATURE_C_PORT_OVER_CURRENT 19
+#define HUB_FEATURE_C_PORT_RESET 20
+#define HUB_FEATURE_PORT_TEST 21
+#define HUB_FEATURE_PORT_INDICATOR 22
+
+// Hub Port Test Modes
+#define HUB_PORT_TEST_MODE_J 1
+#define HUB_PORT_TEST_MODE_K 2
+#define HUB_PORT_TEST_MODE_SE0_NAK 3
+#define HUB_PORT_TEST_MODE_PACKET 4
+#define HUB_PORT_TEST_MODE_FORCE_ENABLE 5
+
+// Hub Port Indicator Color
+#define HUB_PORT_INDICATOR_AUTO 0
+#define HUB_PORT_INDICATOR_AMBER 1
+#define HUB_PORT_INDICATOR_GREEN 2
+#define HUB_PORT_INDICATOR_OFF 3
+
+// Hub Port Status Bitmasks
+#define bmHUB_PORT_STATUS_PORT_CONNECTION 0x0001
+#define bmHUB_PORT_STATUS_PORT_ENABLE 0x0002
+#define bmHUB_PORT_STATUS_PORT_SUSPEND 0x0004
+#define bmHUB_PORT_STATUS_PORT_OVER_CURRENT 0x0008
+#define bmHUB_PORT_STATUS_PORT_RESET 0x0010
+#define bmHUB_PORT_STATUS_PORT_POWER 0x0100
+#define bmHUB_PORT_STATUS_PORT_LOW_SPEED 0x0200
+#define bmHUB_PORT_STATUS_PORT_HIGH_SPEED 0x0400
+#define bmHUB_PORT_STATUS_PORT_TEST 0x0800
+#define bmHUB_PORT_STATUS_PORT_INDICATOR 0x1000
+
+// Hub Port Status Change Bitmasks (used one byte instead of two)
+#define bmHUB_PORT_STATUS_C_PORT_CONNECTION 0x0001
+#define bmHUB_PORT_STATUS_C_PORT_ENABLE 0x0002
+#define bmHUB_PORT_STATUS_C_PORT_SUSPEND 0x0004
+#define bmHUB_PORT_STATUS_C_PORT_OVER_CURRENT 0x0008
+#define bmHUB_PORT_STATUS_C_PORT_RESET 0x0010
+
+// Hub Status Bitmasks (used one byte instead of two)
+#define bmHUB_STATUS_LOCAL_POWER_SOURCE 0x01
+#define bmHUB_STATUS_OVER_CURRENT 0x12
+
+// Hub Status Change Bitmasks (used one byte instead of two)
+#define bmHUB_STATUS_C_LOCAL_POWER_SOURCE 0x01
+#define bmHUB_STATUS_C_OVER_CURRENT 0x12
+
+
+// Hub Port Configuring Substates
+#define USB_STATE_HUB_PORT_CONFIGURING 0xb0
+#define USB_STATE_HUB_PORT_POWERED_OFF 0xb1
+#define USB_STATE_HUB_PORT_WAIT_FOR_POWER_GOOD 0xb2
+#define USB_STATE_HUB_PORT_DISCONNECTED 0xb3
+#define USB_STATE_HUB_PORT_DISABLED 0xb4
+#define USB_STATE_HUB_PORT_RESETTING 0xb5
+#define USB_STATE_HUB_PORT_ENABLED 0xb6
+
+// Additional Error Codes
+#define HUB_ERROR_PORT_HAS_BEEN_RESET 0xb1
+
+// The bit mask to check for all necessary state bits
+#define bmHUB_PORT_STATUS_ALL_MAIN ((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION | bmHUB_PORT_STATUS_C_PORT_ENABLE | bmHUB_PORT_STATUS_C_PORT_SUSPEND | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_SUSPEND)
+
+// Bit mask to check for DISABLED state in HubEvent::bmStatus field
+#define bmHUB_PORT_STATE_CHECK_DISABLED (0x0000 | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_SUSPEND)
+
+// Hub Port States
+#define bmHUB_PORT_STATE_DISABLED (0x0000 | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION)
+
+// Hub Port Events
+#define bmHUB_PORT_EVENT_CONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION)
+#define bmHUB_PORT_EVENT_DISCONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER)
+#define bmHUB_PORT_EVENT_RESET_COMPLETE (((0UL | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION)
+
+#define bmHUB_PORT_EVENT_LS_CONNECT (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED)
+#define bmHUB_PORT_EVENT_LS_RESET_COMPLETE (((0UL | bmHUB_PORT_STATUS_C_PORT_RESET) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED)
+#define bmHUB_PORT_EVENT_LS_PORT_ENABLED (((0UL | bmHUB_PORT_STATUS_C_PORT_CONNECTION | bmHUB_PORT_STATUS_C_PORT_ENABLE) << 16) | bmHUB_PORT_STATUS_PORT_POWER | bmHUB_PORT_STATUS_PORT_ENABLE | bmHUB_PORT_STATUS_PORT_CONNECTION | bmHUB_PORT_STATUS_PORT_LOW_SPEED)
+
+struct HubDescriptor {
+ uint8_t bDescLength; // descriptor length
+ uint8_t bDescriptorType; // descriptor type
+ uint8_t bNbrPorts; // number of ports a hub equiped with
+
+ struct {
+ uint16_t LogPwrSwitchMode : 2;
+ uint16_t CompoundDevice : 1;
+ uint16_t OverCurrentProtectMode : 2;
+ uint16_t TTThinkTime : 2;
+ uint16_t PortIndicatorsSupported : 1;
+ uint16_t Reserved : 8;
+ } __attribute__((packed));
+
+ uint8_t bPwrOn2PwrGood;
+ uint8_t bHubContrCurrent;
+} __attribute__((packed));
+
+struct HubEvent {
+
+ union {
+
+ struct {
+ uint16_t bmStatus; // port status bits
+ uint16_t bmChange; // port status change bits
+ } __attribute__((packed));
+ uint32_t bmEvent;
+ uint8_t evtBuff[4];
+ };
+} __attribute__((packed));
+
+class USBHub : USBDeviceConfig {
+ static bool bResetInitiated; // True when reset is triggered
+
+ USB *pUsb; // USB class instance pointer
+
+ EpInfo epInfo[2]; // interrupt endpoint info structure
+
+ uint8_t bAddress; // address
+ uint8_t bNbrPorts; // number of ports
+ // uint8_t bInitState; // initialization state variable
+ uint32_t qNextPollTime; // next poll time
+ bool bPollEnable; // poll enable flag
+
+ uint8_t CheckHubStatus();
+ uint8_t PortStatusChange(uint8_t port, HubEvent &evt);
+
+public:
+ USBHub(USB *p);
+
+ uint8_t ClearHubFeature(uint8_t fid);
+ uint8_t ClearPortFeature(uint8_t fid, uint8_t port, uint8_t sel = 0);
+ uint8_t GetHubDescriptor(uint8_t index, uint16_t nbytes, uint8_t *dataptr);
+ uint8_t GetHubStatus(uint16_t nbytes, uint8_t* dataptr);
+ uint8_t GetPortStatus(uint8_t port, uint16_t nbytes, uint8_t* dataptr);
+ uint8_t SetHubDescriptor(uint8_t port, uint16_t nbytes, uint8_t* dataptr);
+ uint8_t SetHubFeature(uint8_t fid);
+ uint8_t SetPortFeature(uint8_t fid, uint8_t port, uint8_t sel = 0);
+
+ void PrintHubStatus();
+
+ uint8_t Init(uint8_t parent, uint8_t port, bool lowspeed);
+ uint8_t Release();
+ uint8_t Poll();
+ void ResetHubPort(uint8_t port);
+
+ virtual uint8_t GetAddress() {
+ return bAddress;
+ };
+
+ virtual bool DEVCLASSOK(uint8_t klass) {
+ return (klass == 0x09);
+ }
+
+};
+
+// Clear Hub Feature
+
+inline uint8_t USBHub::ClearHubFeature(uint8_t fid) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_HUB_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, 0, 0, 0, NULL, NULL));
+}
+// Clear Port Feature
+
+inline uint8_t USBHub::ClearPortFeature(uint8_t fid, uint8_t port, uint8_t sel) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_CLEAR_PORT_FEATURE, USB_REQUEST_CLEAR_FEATURE, fid, 0, ((0x0000 | port) | (sel << 8)), 0, 0, NULL, NULL));
+}
+// Get Hub Descriptor
+
+inline uint8_t USBHub::GetHubDescriptor(uint8_t index, uint16_t nbytes, uint8_t *dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_DESCRIPTOR, USB_REQUEST_GET_DESCRIPTOR, index, 0x29, 0, nbytes, nbytes, dataptr, NULL));
+}
+// Get Hub Status
+
+inline uint8_t USBHub::GetHubStatus(uint16_t nbytes, uint8_t* dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_HUB_STATUS, USB_REQUEST_GET_STATUS, 0, 0, 0x0000, nbytes, nbytes, dataptr, NULL));
+}
+// Get Port Status
+
+inline uint8_t USBHub::GetPortStatus(uint8_t port, uint16_t nbytes, uint8_t* dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_GET_PORT_STATUS, USB_REQUEST_GET_STATUS, 0, 0, port, nbytes, nbytes, dataptr, NULL));
+}
+// Set Hub Descriptor
+
+inline uint8_t USBHub::SetHubDescriptor(uint8_t port, uint16_t nbytes, uint8_t* dataptr) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_DESCRIPTOR, USB_REQUEST_SET_DESCRIPTOR, 0, 0, port, nbytes, nbytes, dataptr, NULL));
+}
+// Set Hub Feature
+
+inline uint8_t USBHub::SetHubFeature(uint8_t fid) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_HUB_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, 0, 0, 0, NULL, NULL));
+}
+// Set Port Feature
+
+inline uint8_t USBHub::SetPortFeature(uint8_t fid, uint8_t port, uint8_t sel) {
+ return ( pUsb->ctrlReq(bAddress, 0, bmREQ_SET_PORT_FEATURE, USB_REQUEST_SET_FEATURE, fid, 0, (((0x0000 | sel) << 8) | port), 0, 0, NULL, NULL));
+}
+
+void PrintHubPortStatus(USB *usbptr, uint8_t addr, uint8_t port, bool print_changes = false);
+
+#endif // __USBHUB_H__
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/version_helper.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/version_helper.h
new file mode 100644
index 000000000..0cb3b4adc
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/version_helper.h
@@ -0,0 +1,194 @@
+/* Copyright (C) 2011 Circuits At Home, LTD. All rights reserved.
+
+This software may be distributed and modified under the terms of the GNU
+General Public License version 2 (GPL2) as published by the Free Software
+Foundation and appearing in the file GPL2.TXT included in the packaging of
+this file. Please note that GPL2 Section 2[b] requires that all works based
+on this software must also be made publicly available under the terms of
+the GPL2 ("Copyleft").
+
+Contact information
+-------------------
+
+Circuits At Home, LTD
+Web : http://www.circuitsathome.com
+e-mail : support@circuitsathome.com
+ */
+
+/*
+ * Universal Arduino(tm) "IDE" fixups.
+ * Includes fixes for versions as low as 0023, used by Digilent.
+ */
+
+#if defined(ARDUINO) && ARDUINO >=100
+#include <Arduino.h>
+#else
+#include <WProgram.h>
+#include <pins_arduino.h>
+#ifdef __AVR__
+#include <avr/pgmspace.h>
+#include <avr/io.h>
+#else
+#endif
+#endif
+
+#ifndef __PGMSPACE_H_
+#define __PGMSPACE_H_ 1
+
+#include <inttypes.h>
+
+#ifndef PROGMEM
+#define PROGMEM
+#endif
+#ifndef PGM_P
+#define PGM_P const char *
+#endif
+#ifndef PSTR
+#define PSTR(str) (str)
+#endif
+#ifndef F
+#define F(str) (str)
+#endif
+#ifndef _SFR_BYTE
+#define _SFR_BYTE(n) (n)
+#endif
+
+#ifndef memchr_P
+#define memchr_P(str, c, len) memchr((str), (c), (len))
+#endif
+#ifndef memcmp_P
+#define memcmp_P(a, b, n) memcmp((a), (b), (n))
+#endif
+#ifndef memcpy_P
+#define memcpy_P(dest, src, num) memcpy((dest), (src), (num))
+#endif
+#ifndef memmem_P
+#define memmem_P(a, alen, b, blen) memmem((a), (alen), (b), (blen))
+#endif
+#ifndef memrchr_P
+#define memrchr_P(str, val, len) memrchr((str), (val), (len))
+#endif
+#ifndef strcat_P
+#define strcat_P(dest, src) strcat((dest), (src))
+#endif
+#ifndef strchr_P
+#define strchr_P(str, c) strchr((str), (c))
+#endif
+#ifndef strchrnul_P
+#define strchrnul_P(str, c) strchrnul((str), (c))
+#endif
+#ifndef strcmp_P
+#define strcmp_P(a, b) strcmp((a), (b))
+#endif
+#ifndef strcpy_P
+#define strcpy_P(dest, src) strcpy((dest), (src))
+#endif
+#ifndef strcasecmp_P
+#define strcasecmp_P(a, b) strcasecmp((a), (b))
+#endif
+#ifndef strcasestr_P
+#define strcasestr_P(a, b) strcasestr((a), (b))
+#endif
+#ifndef strlcat_P
+#define strlcat_P(dest, src, len) strlcat((dest), (src), (len))
+#endif
+#ifndef strlcpy_P
+#define strlcpy_P(dest, src, len) strlcpy((dest), (src), (len))
+#endif
+#ifndef strlen_P
+#define strlen_P(s) strlen((const char *)(s))
+#endif
+#ifndef strnlen_P
+#define strnlen_P(str, len) strnlen((str), (len))
+#endif
+#ifndef strncmp_P
+#define strncmp_P(a, b, n) strncmp((a), (b), (n))
+#endif
+#ifndef strncasecmp_P
+#define strncasecmp_P(a, b, n) strncasecmp((a), (b), (n))
+#endif
+#ifndef strncat_P
+#define strncat_P(a, b, n) strncat((a), (b), (n))
+#endif
+#ifndef strncpy_P
+#define strncpy_P(a, b, n) strncmp((a), (b), (n))
+#endif
+#ifndef strpbrk_P
+#define strpbrk_P(str, chrs) strpbrk((str), (chrs))
+#endif
+#ifndef strrchr_P
+#define strrchr_P(str, c) strrchr((str), (c))
+#endif
+#ifndef strsep_P
+#define strsep_P(strp, delim) strsep((strp), (delim))
+#endif
+#ifndef strspn_P
+#define strspn_P(str, chrs) strspn((str), (chrs))
+#endif
+#ifndef strstr_P
+#define strstr_P(a, b) strstr((a), (b))
+#endif
+#ifndef sprintf_P
+#define sprintf_P(s, ...) sprintf((s), __VA_ARGS__)
+#endif
+#ifndef vfprintf_P
+#define vfprintf_P(s, ...) vfprintf((s), __VA_ARGS__)
+#endif
+#ifndef printf_P
+#define printf_P(...) printf(__VA_ARGS__)
+#endif
+#ifndef snprintf_P
+#define snprintf_P(s, n, ...) ((s), (n), __VA_ARGS__)
+#endif
+#ifndef vsprintf_P
+#define vsprintf_P(s, ...) ((s),__VA_ARGS__)
+#endif
+#ifndef vsnprintf_P
+#define vsnprintf_P(s, n, ...) ((s), (n),__VA_ARGS__)
+#endif
+#ifndef fprintf_P
+#define fprintf_P(s, ...) ((s), __VA_ARGS__)
+#endif
+
+#ifndef pgm_read_byte
+#define pgm_read_byte(addr) (*(const unsigned char *)(addr))
+#endif
+#ifndef pgm_read_word
+#define pgm_read_word(addr) (*(const unsigned short *)(addr))
+#endif
+#ifndef pgm_read_dword
+#define pgm_read_dword(addr) (*(const unsigned long *)(addr))
+#endif
+#ifndef pgm_read_float
+#define pgm_read_float(addr) (*(const float *)(addr))
+#endif
+
+#ifndef pgm_read_byte_near
+#define pgm_read_byte_near(addr) pgm_read_byte(addr)
+#endif
+#ifndef pgm_read_word_near
+#define pgm_read_word_near(addr) pgm_read_word(addr)
+#endif
+#ifndef pgm_read_dword_near
+#define pgm_read_dword_near(addr) pgm_read_dword(addr)
+#endif
+#ifndef pgm_read_float_near
+#define pgm_read_float_near(addr) pgm_read_float(addr)
+#endif
+#ifndef pgm_read_byte_far
+#define pgm_read_byte_far(addr) pgm_read_byte(addr)
+#endif
+#ifndef pgm_read_word_far
+#define pgm_read_word_far(addr) pgm_read_word(addr)
+#endif
+#ifndef pgm_read_dword_far
+#define pgm_read_dword_far(addr) pgm_read_dword(addr)
+#endif
+#ifndef pgm_read_float_far
+#define pgm_read_float_far(addr) pgm_read_float(addr)
+#endif
+
+#ifndef pgm_read_pointer
+#define pgm_read_pointer
+#endif
+#endif
diff --git a/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/xboxEnums.h b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/xboxEnums.h
new file mode 100644
index 000000000..84b137bb6
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/USB_Host_Shield_2.0/xboxEnums.h
@@ -0,0 +1,65 @@
+/* Copyright (C) 2012 Kristian Lauszus, TKJ Electronics. All rights reserved.
+
+ This software may be distributed and modified under the terms of the GNU
+ General Public License version 2 (GPL2) as published by the Free Software
+ Foundation and appearing in the file GPL2.TXT included in the packaging of
+ this file. Please note that GPL2 Section 2[b] requires that all works based
+ on this software must also be made publicly available under the terms of
+ the GPL2 ("Copyleft").
+
+ Contact information
+ -------------------
+
+ Kristian Lauszus, TKJ Electronics
+ Web : http://www.tkjelectronics.com
+ e-mail : kristianl@tkjelectronics.com
+ */
+
+#ifndef _xboxenums_h
+#define _xboxenums_h
+
+#include "controllerEnums.h"
+
+/** Enum used to set special LED modes supported by the Xbox controller. */
+enum LEDModeEnum {
+ ROTATING = 0x0A,
+ FASTBLINK = 0x0B,
+ SLOWBLINK = 0x0C,
+ ALTERNATING = 0x0D,
+};
+
+/** Used to set the LEDs on the controllers */
+const uint8_t XBOX_LEDS[] PROGMEM = {
+ 0x00, // OFF
+ 0x02, // LED1
+ 0x03, // LED2
+ 0x04, // LED3
+ 0x05, // LED4
+ 0x01, // ALL - Used to blink all LEDs
+};
+/** Buttons on the controllers */
+const uint16_t XBOX_BUTTONS[] PROGMEM = {
+ 0x0100, // UP
+ 0x0800, // RIGHT
+ 0x0200, // DOWN
+ 0x0400, // LEFT
+
+ 0x2000, // BACK
+ 0x1000, // START
+ 0x4000, // L3
+ 0x8000, // R3
+
+ 0, 0, // Skip L2 and R2 as these are analog buttons
+ 0x0001, // L1
+ 0x0002, // R1
+
+ 0x0020, // B
+ 0x0010, // A
+ 0x0040, // X
+ 0x0080, // Y
+
+ 0x0004, // XBOX
+ 0x0008, // SYNC
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Arduino.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Arduino.h
new file mode 100644
index 000000000..830c9952f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Arduino.h
@@ -0,0 +1,215 @@
+#ifndef Arduino_h
+#define Arduino_h
+
+#include <stdlib.h>
+#include <string.h>
+#include <math.h>
+
+#include <avr/pgmspace.h>
+#include <avr/io.h>
+#include <avr/interrupt.h>
+
+#include "binary.h"
+
+#ifdef __cplusplus
+extern "C"{
+#endif
+
+#define HIGH 0x1
+#define LOW 0x0
+
+#define INPUT 0x0
+#define OUTPUT 0x1
+#define INPUT_PULLUP 0x2
+
+#define true 0x1
+#define false 0x0
+
+#define PI 3.1415926535897932384626433832795
+#define HALF_PI 1.5707963267948966192313216916398
+#define TWO_PI 6.283185307179586476925286766559
+#define DEG_TO_RAD 0.017453292519943295769236907684886
+#define RAD_TO_DEG 57.295779513082320876798154814105
+
+#define SERIAL 0x0
+#define DISPLAY 0x1
+
+#define LSBFIRST 0
+#define MSBFIRST 1
+
+#define CHANGE 1
+#define FALLING 2
+#define RISING 3
+
+#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__)
+#define DEFAULT 0
+#define EXTERNAL 1
+#define INTERNAL 2
+#else
+#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) || defined(__AVR_ATmega1284P__)
+#define INTERNAL1V1 2
+#define INTERNAL2V56 3
+#else
+#define INTERNAL 3
+#endif
+#define DEFAULT 1
+#define EXTERNAL 0
+#endif
+
+// undefine stdlib's abs if encountered
+#ifdef abs
+#undef abs
+#endif
+
+#define min(a,b) ((a)<(b)?(a):(b))
+#define max(a,b) ((a)>(b)?(a):(b))
+#define abs(x) ((x)>0?(x):-(x))
+#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
+#define round(x) ((x)>=0?(long)((x)+0.5):(long)((x)-0.5))
+#define radians(deg) ((deg)*DEG_TO_RAD)
+#define degrees(rad) ((rad)*RAD_TO_DEG)
+#define sq(x) ((x)*(x))
+
+#define interrupts() sei()
+#define noInterrupts() cli()
+
+#define clockCyclesPerMicrosecond() ( F_CPU / 1000000L )
+#define clockCyclesToMicroseconds(a) ( (a) / clockCyclesPerMicrosecond() )
+#define microsecondsToClockCycles(a) ( (a) * clockCyclesPerMicrosecond() )
+
+#define lowByte(w) ((uint8_t) ((w) & 0xff))
+#define highByte(w) ((uint8_t) ((w) >> 8))
+
+#define bitRead(value, bit) (((value) >> (bit)) & 0x01)
+#define bitSet(value, bit) ((value) |= (1UL << (bit)))
+#define bitClear(value, bit) ((value) &= ~(1UL << (bit)))
+#define bitWrite(value, bit, bitvalue) (bitvalue ? bitSet(value, bit) : bitClear(value, bit))
+
+
+typedef unsigned int word;
+
+#define bit(b) (1UL << (b))
+
+typedef uint8_t boolean;
+typedef uint8_t byte;
+
+void init(void);
+
+void pinMode(uint8_t, uint8_t);
+void digitalWrite(uint8_t, uint8_t);
+int digitalRead(uint8_t);
+int analogRead(uint8_t);
+void analogReference(uint8_t mode);
+void analogWrite(uint8_t, int);
+
+unsigned long millis(void);
+unsigned long micros(void);
+void delay(unsigned long);
+void delayMicroseconds(unsigned int us);
+unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout);
+
+void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val);
+uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder);
+
+void attachInterrupt(uint8_t, void (*)(void), int mode);
+void detachInterrupt(uint8_t);
+
+void setup(void);
+void loop(void);
+
+// Get the bit location within the hardware port of the given virtual pin.
+// This comes from the pins_*.c file for the active board configuration.
+
+#define analogInPinToBit(P) (P)
+
+// On the ATmega1280, the addresses of some of the port registers are
+// greater than 255, so we can't store them in uint8_t's.
+extern const uint16_t PROGMEM port_to_mode_PGM[];
+extern const uint16_t PROGMEM port_to_input_PGM[];
+extern const uint16_t PROGMEM port_to_output_PGM[];
+
+extern const uint8_t PROGMEM digital_pin_to_port_PGM[];
+// extern const uint8_t PROGMEM digital_pin_to_bit_PGM[];
+extern const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[];
+extern const uint8_t PROGMEM digital_pin_to_timer_PGM[];
+
+// Get the bit location within the hardware port of the given virtual pin.
+// This comes from the pins_*.c file for the active board configuration.
+//
+// These perform slightly better as macros compared to inline functions
+//
+#define digitalPinToPort(P) ( pgm_read_byte( digital_pin_to_port_PGM + (P) ) )
+#define digitalPinToBitMask(P) ( pgm_read_byte( digital_pin_to_bit_mask_PGM + (P) ) )
+#define digitalPinToTimer(P) ( pgm_read_byte( digital_pin_to_timer_PGM + (P) ) )
+#define analogInPinToBit(P) (P)
+#define portOutputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_output_PGM + (P))) )
+#define portInputRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_input_PGM + (P))) )
+#define portModeRegister(P) ( (volatile uint8_t *)( pgm_read_word( port_to_mode_PGM + (P))) )
+
+#define NOT_A_PIN 0
+#define NOT_A_PORT 0
+
+#ifdef ARDUINO_MAIN
+#define PA 1
+#define PB 2
+#define PC 3
+#define PD 4
+#define PE 5
+#define PF 6
+#define PG 7
+#define PH 8
+#define PJ 10
+#define PK 11
+#define PL 12
+#endif
+
+#define NOT_ON_TIMER 0
+#define TIMER0A 1
+#define TIMER0B 2
+#define TIMER1A 3
+#define TIMER1B 4
+#define TIMER2 5
+#define TIMER2A 6
+#define TIMER2B 7
+
+#define TIMER3A 8
+#define TIMER3B 9
+#define TIMER3C 10
+#define TIMER4A 11
+#define TIMER4B 12
+#define TIMER4C 13
+#define TIMER4D 14
+#define TIMER5A 15
+#define TIMER5B 16
+#define TIMER5C 17
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#ifdef __cplusplus
+#include "WCharacter.h"
+#include "WString.h"
+#include "HardwareSerial.h"
+
+uint16_t makeWord(uint16_t w);
+uint16_t makeWord(byte h, byte l);
+
+#define word(...) makeWord(__VA_ARGS__)
+
+unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout = 1000000L);
+
+void tone(uint8_t _pin, unsigned int frequency, unsigned long duration = 0);
+void noTone(uint8_t _pin);
+
+// WMath prototypes
+long random(long);
+long random(long, long);
+void randomSeed(unsigned int);
+long map(long, long, long, long, long);
+
+#endif
+
+#include "pins_arduino.h"
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/CDC.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/CDC.cpp
new file mode 100644
index 000000000..1ee3a488a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/CDC.cpp
@@ -0,0 +1,233 @@
+
+
+/* Copyright (c) 2011, Peter Barrett
+**
+** Permission to use, copy, modify, and/or distribute this software for
+** any purpose with or without fee is hereby granted, provided that the
+** above copyright notice and this permission notice appear in all copies.
+**
+** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
+** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
+** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
+** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+** SOFTWARE.
+*/
+
+#include "Platform.h"
+#include "USBAPI.h"
+#include <avr/wdt.h>
+
+#if defined(USBCON)
+#ifdef CDC_ENABLED
+
+#if (RAMEND < 1000)
+#define SERIAL_BUFFER_SIZE 16
+#else
+#define SERIAL_BUFFER_SIZE 64
+#endif
+
+struct ring_buffer
+{
+ unsigned char buffer[SERIAL_BUFFER_SIZE];
+ volatile int head;
+ volatile int tail;
+};
+
+ring_buffer cdc_rx_buffer = { { 0 }, 0, 0};
+
+typedef struct
+{
+ u32 dwDTERate;
+ u8 bCharFormat;
+ u8 bParityType;
+ u8 bDataBits;
+ u8 lineState;
+} LineInfo;
+
+static volatile LineInfo _usbLineInfo = { 57600, 0x00, 0x00, 0x00, 0x00 };
+
+#define WEAK __attribute__ ((weak))
+
+extern const CDCDescriptor _cdcInterface PROGMEM;
+const CDCDescriptor _cdcInterface =
+{
+ D_IAD(0,2,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,1),
+
+ // CDC communication interface
+ D_INTERFACE(CDC_ACM_INTERFACE,1,CDC_COMMUNICATION_INTERFACE_CLASS,CDC_ABSTRACT_CONTROL_MODEL,0),
+ D_CDCCS(CDC_HEADER,0x10,0x01), // Header (1.10 bcd)
+ D_CDCCS(CDC_CALL_MANAGEMENT,1,1), // Device handles call management (not)
+ D_CDCCS4(CDC_ABSTRACT_CONTROL_MANAGEMENT,6), // SET_LINE_CODING, GET_LINE_CODING, SET_CONTROL_LINE_STATE supported
+ D_CDCCS(CDC_UNION,CDC_ACM_INTERFACE,CDC_DATA_INTERFACE), // Communication interface is master, data interface is slave 0
+ D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_ACM),USB_ENDPOINT_TYPE_INTERRUPT,0x10,0x40),
+
+ // CDC data interface
+ D_INTERFACE(CDC_DATA_INTERFACE,2,CDC_DATA_INTERFACE_CLASS,0,0),
+ D_ENDPOINT(USB_ENDPOINT_OUT(CDC_ENDPOINT_OUT),USB_ENDPOINT_TYPE_BULK,0x40,0),
+ D_ENDPOINT(USB_ENDPOINT_IN (CDC_ENDPOINT_IN ),USB_ENDPOINT_TYPE_BULK,0x40,0)
+};
+
+int WEAK CDC_GetInterface(u8* interfaceNum)
+{
+ interfaceNum[0] += 2; // uses 2
+ return USB_SendControl(TRANSFER_PGM,&_cdcInterface,sizeof(_cdcInterface));
+}
+
+bool WEAK CDC_Setup(Setup& setup)
+{
+ u8 r = setup.bRequest;
+ u8 requestType = setup.bmRequestType;
+
+ if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType)
+ {
+ if (CDC_GET_LINE_CODING == r)
+ {
+ USB_SendControl(0,(void*)&_usbLineInfo,7);
+ return true;
+ }
+ }
+
+ if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType)
+ {
+ if (CDC_SET_LINE_CODING == r)
+ {
+ USB_RecvControl((void*)&_usbLineInfo,7);
+ return true;
+ }
+
+ if (CDC_SET_CONTROL_LINE_STATE == r)
+ {
+ _usbLineInfo.lineState = setup.wValueL;
+
+ // auto-reset into the bootloader is triggered when the port, already
+ // open at 1200 bps, is closed. this is the signal to start the watchdog
+ // with a relatively long period so it can finish housekeeping tasks
+ // like servicing endpoints before the sketch ends
+ if (1200 == _usbLineInfo.dwDTERate) {
+ // We check DTR state to determine if host port is open (bit 0 of lineState).
+ if ((_usbLineInfo.lineState & 0x01) == 0) {
+ *(uint16_t *)0x0800 = 0x7777;
+ wdt_enable(WDTO_120MS);
+ } else {
+ // Most OSs do some intermediate steps when configuring ports and DTR can
+ // twiggle more than once before stabilizing.
+ // To avoid spurious resets we set the watchdog to 250ms and eventually
+ // cancel if DTR goes back high.
+
+ wdt_disable();
+ wdt_reset();
+ *(uint16_t *)0x0800 = 0x0;
+ }
+ }
+ return true;
+ }
+ }
+ return false;
+}
+
+
+int _serialPeek = -1;
+void Serial_::begin(uint16_t baud_count)
+{
+}
+
+void Serial_::end(void)
+{
+}
+
+void Serial_::accept(void)
+{
+ ring_buffer *buffer = &cdc_rx_buffer;
+ int c = USB_Recv(CDC_RX);
+ int i = (unsigned int)(buffer->head+1) % SERIAL_BUFFER_SIZE;
+
+ // if we should be storing the received character into the location
+ // just before the tail (meaning that the head would advance to the
+ // current location of the tail), we're about to overflow the buffer
+ // and so we don't write the character or advance the head.
+ if (i != buffer->tail) {
+ buffer->buffer[buffer->head] = c;
+ buffer->head = i;
+ }
+}
+
+int Serial_::available(void)
+{
+ ring_buffer *buffer = &cdc_rx_buffer;
+ return (unsigned int)(SERIAL_BUFFER_SIZE + buffer->head - buffer->tail) % SERIAL_BUFFER_SIZE;
+}
+
+int Serial_::peek(void)
+{
+ ring_buffer *buffer = &cdc_rx_buffer;
+ if (buffer->head == buffer->tail) {
+ return -1;
+ } else {
+ return buffer->buffer[buffer->tail];
+ }
+}
+
+int Serial_::read(void)
+{
+ ring_buffer *buffer = &cdc_rx_buffer;
+ // if the head isn't ahead of the tail, we don't have any characters
+ if (buffer->head == buffer->tail) {
+ return -1;
+ } else {
+ unsigned char c = buffer->buffer[buffer->tail];
+ buffer->tail = (unsigned int)(buffer->tail + 1) % SERIAL_BUFFER_SIZE;
+ return c;
+ }
+}
+
+void Serial_::flush(void)
+{
+ USB_Flush(CDC_TX);
+}
+
+size_t Serial_::write(uint8_t c)
+{
+ /* only try to send bytes if the high-level CDC connection itself
+ is open (not just the pipe) - the OS should set lineState when the port
+ is opened and clear lineState when the port is closed.
+ bytes sent before the user opens the connection or after
+ the connection is closed are lost - just like with a UART. */
+
+ // TODO - ZE - check behavior on different OSes and test what happens if an
+ // open connection isn't broken cleanly (cable is yanked out, host dies
+ // or locks up, or host virtual serial port hangs)
+ if (_usbLineInfo.lineState > 0) {
+ int r = USB_Send(CDC_TX,&c,1);
+ if (r > 0) {
+ return r;
+ } else {
+ setWriteError();
+ return 0;
+ }
+ }
+ setWriteError();
+ return 0;
+}
+
+// This operator is a convenient way for a sketch to check whether the
+// port has actually been configured and opened by the host (as opposed
+// to just being connected to the host). It can be used, for example, in
+// setup() before printing to ensure that an application on the host is
+// actually ready to receive and display the data.
+// We add a short delay before returning to fix a bug observed by Federico
+// where the port is configured (lineState != 0) but not quite opened.
+Serial_::operator bool() {
+ bool result = false;
+ if (_usbLineInfo.lineState > 0)
+ result = true;
+ delay(10);
+ return result;
+}
+
+Serial_ Serial;
+
+#endif
+#endif /* if defined(USBCON) */
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Client.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Client.h
new file mode 100644
index 000000000..ea134838a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Client.h
@@ -0,0 +1,26 @@
+#ifndef client_h
+#define client_h
+#include "Print.h"
+#include "Stream.h"
+#include "IPAddress.h"
+
+class Client : public Stream {
+
+public:
+ virtual int connect(IPAddress ip, uint16_t port) =0;
+ virtual int connect(const char *host, uint16_t port) =0;
+ virtual size_t write(uint8_t) =0;
+ virtual size_t write(const uint8_t *buf, size_t size) =0;
+ virtual int available() = 0;
+ virtual int read() = 0;
+ virtual int read(uint8_t *buf, size_t size) = 0;
+ virtual int peek() = 0;
+ virtual void flush() = 0;
+ virtual void stop() = 0;
+ virtual uint8_t connected() = 0;
+ virtual operator bool() = 0;
+protected:
+ uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); };
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HID.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HID.cpp
new file mode 100644
index 000000000..ac6360844
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HID.cpp
@@ -0,0 +1,520 @@
+
+
+/* Copyright (c) 2011, Peter Barrett
+**
+** Permission to use, copy, modify, and/or distribute this software for
+** any purpose with or without fee is hereby granted, provided that the
+** above copyright notice and this permission notice appear in all copies.
+**
+** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
+** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
+** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
+** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+** SOFTWARE.
+*/
+
+#include "Platform.h"
+#include "USBAPI.h"
+#include "USBDesc.h"
+
+#if defined(USBCON)
+#ifdef HID_ENABLED
+
+//#define RAWHID_ENABLED
+
+// Singletons for mouse and keyboard
+
+Mouse_ Mouse;
+Keyboard_ Keyboard;
+
+//================================================================================
+//================================================================================
+
+// HID report descriptor
+
+#define LSB(_x) ((_x) & 0xFF)
+#define MSB(_x) ((_x) >> 8)
+
+#define RAWHID_USAGE_PAGE 0xFFC0
+#define RAWHID_USAGE 0x0C00
+#define RAWHID_TX_SIZE 64
+#define RAWHID_RX_SIZE 64
+
+extern const u8 _hidReportDescriptor[] PROGMEM;
+const u8 _hidReportDescriptor[] = {
+
+ // Mouse
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 54
+ 0x09, 0x02, // USAGE (Mouse)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x09, 0x01, // USAGE (Pointer)
+ 0xa1, 0x00, // COLLECTION (Physical)
+ 0x85, 0x01, // REPORT_ID (1)
+ 0x05, 0x09, // USAGE_PAGE (Button)
+ 0x19, 0x01, // USAGE_MINIMUM (Button 1)
+ 0x29, 0x03, // USAGE_MAXIMUM (Button 3)
+ 0x15, 0x00, // LOGICAL_MINIMUM (0)
+ 0x25, 0x01, // LOGICAL_MAXIMUM (1)
+ 0x95, 0x03, // REPORT_COUNT (3)
+ 0x75, 0x01, // REPORT_SIZE (1)
+ 0x81, 0x02, // INPUT (Data,Var,Abs)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x75, 0x05, // REPORT_SIZE (5)
+ 0x81, 0x03, // INPUT (Cnst,Var,Abs)
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x30, // USAGE (X)
+ 0x09, 0x31, // USAGE (Y)
+ 0x09, 0x38, // USAGE (Wheel)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x03, // REPORT_COUNT (3)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ 0xc0, // END_COLLECTION
+ 0xc0, // END_COLLECTION
+
+ // Keyboard
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop) // 47
+ 0x09, 0x06, // USAGE (Keyboard)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x85, 0x02, // REPORT_ID (2)
+ 0x05, 0x07, // USAGE_PAGE (Keyboard)
+
+ 0x19, 0xe0, // USAGE_MINIMUM (Keyboard LeftControl)
+ 0x29, 0xe7, // USAGE_MAXIMUM (Keyboard Right GUI)
+ 0x15, 0x00, // LOGICAL_MINIMUM (0)
+ 0x25, 0x01, // LOGICAL_MAXIMUM (1)
+ 0x75, 0x01, // REPORT_SIZE (1)
+
+ 0x95, 0x08, // REPORT_COUNT (8)
+ 0x81, 0x02, // INPUT (Data,Var,Abs)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x81, 0x03, // INPUT (Cnst,Var,Abs)
+
+ 0x95, 0x06, // REPORT_COUNT (6)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x15, 0x00, // LOGICAL_MINIMUM (0)
+ 0x25, 0x65, // LOGICAL_MAXIMUM (101)
+ 0x05, 0x07, // USAGE_PAGE (Keyboard)
+
+ 0x19, 0x00, // USAGE_MINIMUM (Reserved (no event indicated))
+ 0x29, 0x65, // USAGE_MAXIMUM (Keyboard Application)
+ 0x81, 0x00, // INPUT (Data,Ary,Abs)
+ 0xc0, // END_COLLECTION
+
+#if RAWHID_ENABLED
+ // RAW HID
+ 0x06, LSB(RAWHID_USAGE_PAGE), MSB(RAWHID_USAGE_PAGE), // 30
+ 0x0A, LSB(RAWHID_USAGE), MSB(RAWHID_USAGE),
+
+ 0xA1, 0x01, // Collection 0x01
+ 0x85, 0x03, // REPORT_ID (3)
+ 0x75, 0x08, // report size = 8 bits
+ 0x15, 0x00, // logical minimum = 0
+ 0x26, 0xFF, 0x00, // logical maximum = 255
+
+ 0x95, 64, // report count TX
+ 0x09, 0x01, // usage
+ 0x81, 0x02, // Input (array)
+
+ 0x95, 64, // report count RX
+ 0x09, 0x02, // usage
+ 0x91, 0x02, // Output (array)
+ 0xC0 // end collection
+#endif
+};
+
+extern const HIDDescriptor _hidInterface PROGMEM;
+const HIDDescriptor _hidInterface =
+{
+ D_INTERFACE(HID_INTERFACE,1,3,0,0),
+ D_HIDREPORT(sizeof(_hidReportDescriptor)),
+ D_ENDPOINT(USB_ENDPOINT_IN (HID_ENDPOINT_INT),USB_ENDPOINT_TYPE_INTERRUPT,0x40,0x01)
+};
+
+//================================================================================
+//================================================================================
+// Driver
+
+u8 _hid_protocol = 1;
+u8 _hid_idle = 1;
+
+#define WEAK __attribute__ ((weak))
+
+int WEAK HID_GetInterface(u8* interfaceNum)
+{
+ interfaceNum[0] += 1; // uses 1
+ return USB_SendControl(TRANSFER_PGM,&_hidInterface,sizeof(_hidInterface));
+}
+
+int WEAK HID_GetDescriptor(int i)
+{
+ return USB_SendControl(TRANSFER_PGM,_hidReportDescriptor,sizeof(_hidReportDescriptor));
+}
+
+void WEAK HID_SendReport(u8 id, const void* data, int len)
+{
+ USB_Send(HID_TX, &id, 1);
+ USB_Send(HID_TX | TRANSFER_RELEASE,data,len);
+}
+
+bool WEAK HID_Setup(Setup& setup)
+{
+ u8 r = setup.bRequest;
+ u8 requestType = setup.bmRequestType;
+ if (REQUEST_DEVICETOHOST_CLASS_INTERFACE == requestType)
+ {
+ if (HID_GET_REPORT == r)
+ {
+ //HID_GetReport();
+ return true;
+ }
+ if (HID_GET_PROTOCOL == r)
+ {
+ //Send8(_hid_protocol); // TODO
+ return true;
+ }
+ }
+
+ if (REQUEST_HOSTTODEVICE_CLASS_INTERFACE == requestType)
+ {
+ if (HID_SET_PROTOCOL == r)
+ {
+ _hid_protocol = setup.wValueL;
+ return true;
+ }
+
+ if (HID_SET_IDLE == r)
+ {
+ _hid_idle = setup.wValueL;
+ return true;
+ }
+ }
+ return false;
+}
+
+//================================================================================
+//================================================================================
+// Mouse
+
+Mouse_::Mouse_(void) : _buttons(0)
+{
+}
+
+void Mouse_::begin(void)
+{
+}
+
+void Mouse_::end(void)
+{
+}
+
+void Mouse_::click(uint8_t b)
+{
+ _buttons = b;
+ move(0,0,0);
+ _buttons = 0;
+ move(0,0,0);
+}
+
+void Mouse_::move(signed char x, signed char y, signed char wheel)
+{
+ u8 m[4];
+ m[0] = _buttons;
+ m[1] = x;
+ m[2] = y;
+ m[3] = wheel;
+ HID_SendReport(1,m,4);
+}
+
+void Mouse_::buttons(uint8_t b)
+{
+ if (b != _buttons)
+ {
+ _buttons = b;
+ move(0,0,0);
+ }
+}
+
+void Mouse_::press(uint8_t b)
+{
+ buttons(_buttons | b);
+}
+
+void Mouse_::release(uint8_t b)
+{
+ buttons(_buttons & ~b);
+}
+
+bool Mouse_::isPressed(uint8_t b)
+{
+ if ((b & _buttons) > 0)
+ return true;
+ return false;
+}
+
+//================================================================================
+//================================================================================
+// Keyboard
+
+Keyboard_::Keyboard_(void)
+{
+}
+
+void Keyboard_::begin(void)
+{
+}
+
+void Keyboard_::end(void)
+{
+}
+
+void Keyboard_::sendReport(KeyReport* keys)
+{
+ HID_SendReport(2,keys,sizeof(KeyReport));
+}
+
+extern
+const uint8_t _asciimap[128] PROGMEM;
+
+#define SHIFT 0x80
+const uint8_t _asciimap[128] =
+{
+ 0x00, // NUL
+ 0x00, // SOH
+ 0x00, // STX
+ 0x00, // ETX
+ 0x00, // EOT
+ 0x00, // ENQ
+ 0x00, // ACK
+ 0x00, // BEL
+ 0x2a, // BS Backspace
+ 0x2b, // TAB Tab
+ 0x28, // LF Enter
+ 0x00, // VT
+ 0x00, // FF
+ 0x00, // CR
+ 0x00, // SO
+ 0x00, // SI
+ 0x00, // DEL
+ 0x00, // DC1
+ 0x00, // DC2
+ 0x00, // DC3
+ 0x00, // DC4
+ 0x00, // NAK
+ 0x00, // SYN
+ 0x00, // ETB
+ 0x00, // CAN
+ 0x00, // EM
+ 0x00, // SUB
+ 0x00, // ESC
+ 0x00, // FS
+ 0x00, // GS
+ 0x00, // RS
+ 0x00, // US
+
+ 0x2c, // ' '
+ 0x1e|SHIFT, // !
+ 0x34|SHIFT, // "
+ 0x20|SHIFT, // #
+ 0x21|SHIFT, // $
+ 0x22|SHIFT, // %
+ 0x24|SHIFT, // &
+ 0x34, // '
+ 0x26|SHIFT, // (
+ 0x27|SHIFT, // )
+ 0x25|SHIFT, // *
+ 0x2e|SHIFT, // +
+ 0x36, // ,
+ 0x2d, // -
+ 0x37, // .
+ 0x38, // /
+ 0x27, // 0
+ 0x1e, // 1
+ 0x1f, // 2
+ 0x20, // 3
+ 0x21, // 4
+ 0x22, // 5
+ 0x23, // 6
+ 0x24, // 7
+ 0x25, // 8
+ 0x26, // 9
+ 0x33|SHIFT, // :
+ 0x33, // ;
+ 0x36|SHIFT, // <
+ 0x2e, // =
+ 0x37|SHIFT, // >
+ 0x38|SHIFT, // ?
+ 0x1f|SHIFT, // @
+ 0x04|SHIFT, // A
+ 0x05|SHIFT, // B
+ 0x06|SHIFT, // C
+ 0x07|SHIFT, // D
+ 0x08|SHIFT, // E
+ 0x09|SHIFT, // F
+ 0x0a|SHIFT, // G
+ 0x0b|SHIFT, // H
+ 0x0c|SHIFT, // I
+ 0x0d|SHIFT, // J
+ 0x0e|SHIFT, // K
+ 0x0f|SHIFT, // L
+ 0x10|SHIFT, // M
+ 0x11|SHIFT, // N
+ 0x12|SHIFT, // O
+ 0x13|SHIFT, // P
+ 0x14|SHIFT, // Q
+ 0x15|SHIFT, // R
+ 0x16|SHIFT, // S
+ 0x17|SHIFT, // T
+ 0x18|SHIFT, // U
+ 0x19|SHIFT, // V
+ 0x1a|SHIFT, // W
+ 0x1b|SHIFT, // X
+ 0x1c|SHIFT, // Y
+ 0x1d|SHIFT, // Z
+ 0x2f, // [
+ 0x31, // bslash
+ 0x30, // ]
+ 0x23|SHIFT, // ^
+ 0x2d|SHIFT, // _
+ 0x35, // `
+ 0x04, // a
+ 0x05, // b
+ 0x06, // c
+ 0x07, // d
+ 0x08, // e
+ 0x09, // f
+ 0x0a, // g
+ 0x0b, // h
+ 0x0c, // i
+ 0x0d, // j
+ 0x0e, // k
+ 0x0f, // l
+ 0x10, // m
+ 0x11, // n
+ 0x12, // o
+ 0x13, // p
+ 0x14, // q
+ 0x15, // r
+ 0x16, // s
+ 0x17, // t
+ 0x18, // u
+ 0x19, // v
+ 0x1a, // w
+ 0x1b, // x
+ 0x1c, // y
+ 0x1d, // z
+ 0x2f|SHIFT, //
+ 0x31|SHIFT, // |
+ 0x30|SHIFT, // }
+ 0x35|SHIFT, // ~
+ 0 // DEL
+};
+
+uint8_t USBPutChar(uint8_t c);
+
+// press() adds the specified key (printing, non-printing, or modifier)
+// to the persistent key report and sends the report. Because of the way
+// USB HID works, the host acts like the key remains pressed until we
+// call release(), releaseAll(), or otherwise clear the report and resend.
+size_t Keyboard_::press(uint8_t k)
+{
+ uint8_t i;
+ if (k >= 136) { // it's a non-printing key (not a modifier)
+ k = k - 136;
+ } else if (k >= 128) { // it's a modifier key
+ _keyReport.modifiers |= (1<<(k-128));
+ k = 0;
+ } else { // it's a printing key
+ k = pgm_read_byte(_asciimap + k);
+ if (!k) {
+ setWriteError();
+ return 0;
+ }
+ if (k & 0x80) { // it's a capital letter or other character reached with shift
+ _keyReport.modifiers |= 0x02; // the left shift modifier
+ k &= 0x7F;
+ }
+ }
+
+ // Add k to the key report only if it's not already present
+ // and if there is an empty slot.
+ if (_keyReport.keys[0] != k && _keyReport.keys[1] != k &&
+ _keyReport.keys[2] != k && _keyReport.keys[3] != k &&
+ _keyReport.keys[4] != k && _keyReport.keys[5] != k) {
+
+ for (i=0; i<6; i++) {
+ if (_keyReport.keys[i] == 0x00) {
+ _keyReport.keys[i] = k;
+ break;
+ }
+ }
+ if (i == 6) {
+ setWriteError();
+ return 0;
+ }
+ }
+ sendReport(&_keyReport);
+ return 1;
+}
+
+// release() takes the specified key out of the persistent key report and
+// sends the report. This tells the OS the key is no longer pressed and that
+// it shouldn't be repeated any more.
+size_t Keyboard_::release(uint8_t k)
+{
+ uint8_t i;
+ if (k >= 136) { // it's a non-printing key (not a modifier)
+ k = k - 136;
+ } else if (k >= 128) { // it's a modifier key
+ _keyReport.modifiers &= ~(1<<(k-128));
+ k = 0;
+ } else { // it's a printing key
+ k = pgm_read_byte(_asciimap + k);
+ if (!k) {
+ return 0;
+ }
+ if (k & 0x80) { // it's a capital letter or other character reached with shift
+ _keyReport.modifiers &= ~(0x02); // the left shift modifier
+ k &= 0x7F;
+ }
+ }
+
+ // Test the key report to see if k is present. Clear it if it exists.
+ // Check all positions in case the key is present more than once (which it shouldn't be)
+ for (i=0; i<6; i++) {
+ if (0 != k && _keyReport.keys[i] == k) {
+ _keyReport.keys[i] = 0x00;
+ }
+ }
+
+ sendReport(&_keyReport);
+ return 1;
+}
+
+void Keyboard_::releaseAll(void)
+{
+ _keyReport.keys[0] = 0;
+ _keyReport.keys[1] = 0;
+ _keyReport.keys[2] = 0;
+ _keyReport.keys[3] = 0;
+ _keyReport.keys[4] = 0;
+ _keyReport.keys[5] = 0;
+ _keyReport.modifiers = 0;
+ sendReport(&_keyReport);
+}
+
+size_t Keyboard_::write(uint8_t c)
+{
+ uint8_t p = press(c); // Keydown
+ uint8_t r = release(c); // Keyup
+ return (p); // just return the result of press() since release() almost always returns 1
+}
+
+#endif
+
+#endif /* if defined(USBCON) */ \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HardwareSerial.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HardwareSerial.cpp
new file mode 100644
index 000000000..f40ddee06
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HardwareSerial.cpp
@@ -0,0 +1,428 @@
+/*
+ HardwareSerial.cpp - Hardware serial library for Wiring
+ Copyright (c) 2006 Nicholas Zambetti. All right reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+ Modified 23 November 2006 by David A. Mellis
+ Modified 28 September 2010 by Mark Sproul
+*/
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <inttypes.h>
+#include "Arduino.h"
+#include "wiring_private.h"
+
+// this next line disables the entire HardwareSerial.cpp,
+// this is so I can support Attiny series and any other chip without a uart
+#if defined(UBRRH) || defined(UBRR0H) || defined(UBRR1H) || defined(UBRR2H) || defined(UBRR3H)
+
+#include "HardwareSerial.h"
+
+// Define constants and variables for buffering incoming serial data. We're
+// using a ring buffer (I think), in which head is the index of the location
+// to which to write the next incoming character and tail is the index of the
+// location from which to read.
+#if (RAMEND < 1000)
+ #define SERIAL_BUFFER_SIZE 16
+#else
+ #define SERIAL_BUFFER_SIZE 64
+#endif
+
+struct ring_buffer
+{
+ unsigned char buffer[SERIAL_BUFFER_SIZE];
+ volatile unsigned int head;
+ volatile unsigned int tail;
+};
+
+#if defined(USBCON)
+ ring_buffer rx_buffer = { { 0 }, 0, 0};
+ ring_buffer tx_buffer = { { 0 }, 0, 0};
+#endif
+#if defined(UBRRH) || defined(UBRR0H)
+ ring_buffer rx_buffer = { { 0 }, 0, 0 };
+ ring_buffer tx_buffer = { { 0 }, 0, 0 };
+#endif
+#if defined(UBRR1H)
+ ring_buffer rx_buffer1 = { { 0 }, 0, 0 };
+ ring_buffer tx_buffer1 = { { 0 }, 0, 0 };
+#endif
+#if defined(UBRR2H)
+ ring_buffer rx_buffer2 = { { 0 }, 0, 0 };
+ ring_buffer tx_buffer2 = { { 0 }, 0, 0 };
+#endif
+#if defined(UBRR3H)
+ ring_buffer rx_buffer3 = { { 0 }, 0, 0 };
+ ring_buffer tx_buffer3 = { { 0 }, 0, 0 };
+#endif
+
+inline void store_char(unsigned char c, ring_buffer *buffer)
+{
+ int i = (unsigned int)(buffer->head + 1) % SERIAL_BUFFER_SIZE;
+
+ // if we should be storing the received character into the location
+ // just before the tail (meaning that the head would advance to the
+ // current location of the tail), we're about to overflow the buffer
+ // and so we don't write the character or advance the head.
+ if (i != buffer->tail) {
+ buffer->buffer[buffer->head] = c;
+ buffer->head = i;
+ }
+}
+
+#if !defined(USART0_RX_vect) && defined(USART1_RX_vect)
+// do nothing - on the 32u4 the first USART is USART1
+#else
+#if !defined(USART_RX_vect) && !defined(SIG_USART0_RECV) && \
+ !defined(SIG_UART0_RECV) && !defined(USART0_RX_vect) && \
+ !defined(SIG_UART_RECV)
+ #error "Don't know what the Data Received vector is called for the first UART"
+#else
+ void serialEvent() __attribute__((weak));
+ void serialEvent() {}
+ #define serialEvent_implemented
+#if defined(USART_RX_vect)
+ SIGNAL(USART_RX_vect)
+#elif defined(SIG_USART0_RECV)
+ SIGNAL(SIG_USART0_RECV)
+#elif defined(SIG_UART0_RECV)
+ SIGNAL(SIG_UART0_RECV)
+#elif defined(USART0_RX_vect)
+ SIGNAL(USART0_RX_vect)
+#elif defined(SIG_UART_RECV)
+ SIGNAL(SIG_UART_RECV)
+#endif
+ {
+ #if defined(UDR0)
+ unsigned char c = UDR0;
+ #elif defined(UDR)
+ unsigned char c = UDR;
+ #else
+ #error UDR not defined
+ #endif
+ store_char(c, &rx_buffer);
+ }
+#endif
+#endif
+
+#if defined(USART1_RX_vect)
+ void serialEvent1() __attribute__((weak));
+ void serialEvent1() {}
+ #define serialEvent1_implemented
+ SIGNAL(USART1_RX_vect)
+ {
+ unsigned char c = UDR1;
+ store_char(c, &rx_buffer1);
+ }
+#elif defined(SIG_USART1_RECV)
+ #error SIG_USART1_RECV
+#endif
+
+#if defined(USART2_RX_vect) && defined(UDR2)
+ void serialEvent2() __attribute__((weak));
+ void serialEvent2() {}
+ #define serialEvent2_implemented
+ SIGNAL(USART2_RX_vect)
+ {
+ unsigned char c = UDR2;
+ store_char(c, &rx_buffer2);
+ }
+#elif defined(SIG_USART2_RECV)
+ #error SIG_USART2_RECV
+#endif
+
+#if defined(USART3_RX_vect) && defined(UDR3)
+ void serialEvent3() __attribute__((weak));
+ void serialEvent3() {}
+ #define serialEvent3_implemented
+ SIGNAL(USART3_RX_vect)
+ {
+ unsigned char c = UDR3;
+ store_char(c, &rx_buffer3);
+ }
+#elif defined(SIG_USART3_RECV)
+ #error SIG_USART3_RECV
+#endif
+
+void serialEventRun(void)
+{
+#ifdef serialEvent_implemented
+ if (Serial.available()) serialEvent();
+#endif
+#ifdef serialEvent1_implemented
+ if (Serial1.available()) serialEvent1();
+#endif
+#ifdef serialEvent2_implemented
+ if (Serial2.available()) serialEvent2();
+#endif
+#ifdef serialEvent3_implemented
+ if (Serial3.available()) serialEvent3();
+#endif
+}
+
+
+#if !defined(USART0_UDRE_vect) && defined(USART1_UDRE_vect)
+// do nothing - on the 32u4 the first USART is USART1
+#else
+#if !defined(UART0_UDRE_vect) && !defined(UART_UDRE_vect) && !defined(USART0_UDRE_vect) && !defined(USART_UDRE_vect)
+ #error "Don't know what the Data Register Empty vector is called for the first UART"
+#else
+#if defined(UART0_UDRE_vect)
+ISR(UART0_UDRE_vect)
+#elif defined(UART_UDRE_vect)
+ISR(UART_UDRE_vect)
+#elif defined(USART0_UDRE_vect)
+ISR(USART0_UDRE_vect)
+#elif defined(USART_UDRE_vect)
+ISR(USART_UDRE_vect)
+#endif
+{
+ if (tx_buffer.head == tx_buffer.tail) {
+ // Buffer empty, so disable interrupts
+#if defined(UCSR0B)
+ cbi(UCSR0B, UDRIE0);
+#else
+ cbi(UCSRB, UDRIE);
+#endif
+ }
+ else {
+ // There is more data in the output buffer. Send the next byte
+ unsigned char c = tx_buffer.buffer[tx_buffer.tail];
+ tx_buffer.tail = (tx_buffer.tail + 1) % SERIAL_BUFFER_SIZE;
+
+ #if defined(UDR0)
+ UDR0 = c;
+ #elif defined(UDR)
+ UDR = c;
+ #else
+ #error UDR not defined
+ #endif
+ }
+}
+#endif
+#endif
+
+#ifdef USART1_UDRE_vect
+ISR(USART1_UDRE_vect)
+{
+ if (tx_buffer1.head == tx_buffer1.tail) {
+ // Buffer empty, so disable interrupts
+ cbi(UCSR1B, UDRIE1);
+ }
+ else {
+ // There is more data in the output buffer. Send the next byte
+ unsigned char c = tx_buffer1.buffer[tx_buffer1.tail];
+ tx_buffer1.tail = (tx_buffer1.tail + 1) % SERIAL_BUFFER_SIZE;
+
+ UDR1 = c;
+ }
+}
+#endif
+
+#ifdef USART2_UDRE_vect
+ISR(USART2_UDRE_vect)
+{
+ if (tx_buffer2.head == tx_buffer2.tail) {
+ // Buffer empty, so disable interrupts
+ cbi(UCSR2B, UDRIE2);
+ }
+ else {
+ // There is more data in the output buffer. Send the next byte
+ unsigned char c = tx_buffer2.buffer[tx_buffer2.tail];
+ tx_buffer2.tail = (tx_buffer2.tail + 1) % SERIAL_BUFFER_SIZE;
+
+ UDR2 = c;
+ }
+}
+#endif
+
+#ifdef USART3_UDRE_vect
+ISR(USART3_UDRE_vect)
+{
+ if (tx_buffer3.head == tx_buffer3.tail) {
+ // Buffer empty, so disable interrupts
+ cbi(UCSR3B, UDRIE3);
+ }
+ else {
+ // There is more data in the output buffer. Send the next byte
+ unsigned char c = tx_buffer3.buffer[tx_buffer3.tail];
+ tx_buffer3.tail = (tx_buffer3.tail + 1) % SERIAL_BUFFER_SIZE;
+
+ UDR3 = c;
+ }
+}
+#endif
+
+
+// Constructors ////////////////////////////////////////////////////////////////
+
+HardwareSerial::HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer,
+ volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
+ volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
+ volatile uint8_t *udr,
+ uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x)
+{
+ _rx_buffer = rx_buffer;
+ _tx_buffer = tx_buffer;
+ _ubrrh = ubrrh;
+ _ubrrl = ubrrl;
+ _ucsra = ucsra;
+ _ucsrb = ucsrb;
+ _udr = udr;
+ _rxen = rxen;
+ _txen = txen;
+ _rxcie = rxcie;
+ _udrie = udrie;
+ _u2x = u2x;
+}
+
+// Public Methods //////////////////////////////////////////////////////////////
+
+void HardwareSerial::begin(unsigned long baud)
+{
+ uint16_t baud_setting;
+ bool use_u2x = true;
+
+#if F_CPU == 16000000UL
+ // hardcoded exception for compatibility with the bootloader shipped
+ // with the Duemilanove and previous boards and the firmware on the 8U2
+ // on the Uno and Mega 2560.
+ if (baud == 57600) {
+ use_u2x = false;
+ }
+#endif
+
+try_again:
+
+ if (use_u2x) {
+ *_ucsra = 1 << _u2x;
+ baud_setting = (F_CPU / 4 / baud - 1) / 2;
+ } else {
+ *_ucsra = 0;
+ baud_setting = (F_CPU / 8 / baud - 1) / 2;
+ }
+
+ if ((baud_setting > 4095) && use_u2x)
+ {
+ use_u2x = false;
+ goto try_again;
+ }
+
+ // assign the baud_setting, a.k.a. ubbr (USART Baud Rate Register)
+ *_ubrrh = baud_setting >> 8;
+ *_ubrrl = baud_setting;
+
+ sbi(*_ucsrb, _rxen);
+ sbi(*_ucsrb, _txen);
+ sbi(*_ucsrb, _rxcie);
+ cbi(*_ucsrb, _udrie);
+}
+
+void HardwareSerial::end()
+{
+ // wait for transmission of outgoing data
+ while (_tx_buffer->head != _tx_buffer->tail)
+ ;
+
+ cbi(*_ucsrb, _rxen);
+ cbi(*_ucsrb, _txen);
+ cbi(*_ucsrb, _rxcie);
+ cbi(*_ucsrb, _udrie);
+
+ // clear any received data
+ _rx_buffer->head = _rx_buffer->tail;
+}
+
+int HardwareSerial::available(void)
+{
+ return (unsigned int)(SERIAL_BUFFER_SIZE + _rx_buffer->head - _rx_buffer->tail) % SERIAL_BUFFER_SIZE;
+}
+
+int HardwareSerial::peek(void)
+{
+ if (_rx_buffer->head == _rx_buffer->tail) {
+ return -1;
+ } else {
+ return _rx_buffer->buffer[_rx_buffer->tail];
+ }
+}
+
+int HardwareSerial::read(void)
+{
+ // if the head isn't ahead of the tail, we don't have any characters
+ if (_rx_buffer->head == _rx_buffer->tail) {
+ return -1;
+ } else {
+ unsigned char c = _rx_buffer->buffer[_rx_buffer->tail];
+ _rx_buffer->tail = (unsigned int)(_rx_buffer->tail + 1) % SERIAL_BUFFER_SIZE;
+ return c;
+ }
+}
+
+void HardwareSerial::flush()
+{
+ while (_tx_buffer->head != _tx_buffer->tail)
+ ;
+}
+
+size_t HardwareSerial::write(uint8_t c)
+{
+ int i = (_tx_buffer->head + 1) % SERIAL_BUFFER_SIZE;
+
+ // If the output buffer is full, there's nothing for it other than to
+ // wait for the interrupt handler to empty it a bit
+ // ???: return 0 here instead?
+ while (i == _tx_buffer->tail)
+ ;
+
+ _tx_buffer->buffer[_tx_buffer->head] = c;
+ _tx_buffer->head = i;
+
+ sbi(*_ucsrb, _udrie);
+
+ return 1;
+}
+
+HardwareSerial::operator bool() {
+ return true;
+}
+
+// Preinstantiate Objects //////////////////////////////////////////////////////
+
+#if defined(UBRRH) && defined(UBRRL)
+ HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRRH, &UBRRL, &UCSRA, &UCSRB, &UDR, RXEN, TXEN, RXCIE, UDRIE, U2X);
+#elif defined(UBRR0H) && defined(UBRR0L)
+ HardwareSerial Serial(&rx_buffer, &tx_buffer, &UBRR0H, &UBRR0L, &UCSR0A, &UCSR0B, &UDR0, RXEN0, TXEN0, RXCIE0, UDRIE0, U2X0);
+#elif defined(USBCON)
+ // do nothing - Serial object and buffers are initialized in CDC code
+#else
+ #error no serial port defined (port 0)
+#endif
+
+#if defined(UBRR1H)
+ HardwareSerial Serial1(&rx_buffer1, &tx_buffer1, &UBRR1H, &UBRR1L, &UCSR1A, &UCSR1B, &UDR1, RXEN1, TXEN1, RXCIE1, UDRIE1, U2X1);
+#endif
+#if defined(UBRR2H)
+ HardwareSerial Serial2(&rx_buffer2, &tx_buffer2, &UBRR2H, &UBRR2L, &UCSR2A, &UCSR2B, &UDR2, RXEN2, TXEN2, RXCIE2, UDRIE2, U2X2);
+#endif
+#if defined(UBRR3H)
+ HardwareSerial Serial3(&rx_buffer3, &tx_buffer3, &UBRR3H, &UBRR3L, &UCSR3A, &UCSR3B, &UDR3, RXEN3, TXEN3, RXCIE3, UDRIE3, U2X3);
+#endif
+
+#endif // whole file
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HardwareSerial.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HardwareSerial.h
new file mode 100644
index 000000000..bf4924c6d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/HardwareSerial.h
@@ -0,0 +1,81 @@
+/*
+ HardwareSerial.h - Hardware serial library for Wiring
+ Copyright (c) 2006 Nicholas Zambetti. All right reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+ Modified 28 September 2010 by Mark Sproul
+*/
+
+#ifndef HardwareSerial_h
+#define HardwareSerial_h
+
+#include <inttypes.h>
+
+#include "Stream.h"
+
+struct ring_buffer;
+
+class HardwareSerial : public Stream
+{
+ private:
+ ring_buffer *_rx_buffer;
+ ring_buffer *_tx_buffer;
+ volatile uint8_t *_ubrrh;
+ volatile uint8_t *_ubrrl;
+ volatile uint8_t *_ucsra;
+ volatile uint8_t *_ucsrb;
+ volatile uint8_t *_udr;
+ uint8_t _rxen;
+ uint8_t _txen;
+ uint8_t _rxcie;
+ uint8_t _udrie;
+ uint8_t _u2x;
+ public:
+ HardwareSerial(ring_buffer *rx_buffer, ring_buffer *tx_buffer,
+ volatile uint8_t *ubrrh, volatile uint8_t *ubrrl,
+ volatile uint8_t *ucsra, volatile uint8_t *ucsrb,
+ volatile uint8_t *udr,
+ uint8_t rxen, uint8_t txen, uint8_t rxcie, uint8_t udrie, uint8_t u2x);
+ void begin(unsigned long);
+ void end();
+ virtual int available(void);
+ virtual int peek(void);
+ virtual int read(void);
+ virtual void flush(void);
+ virtual size_t write(uint8_t);
+ using Print::write; // pull in write(str) and write(buf, size) from Print
+ operator bool();
+};
+
+#if defined(UBRRH) || defined(UBRR0H)
+ extern HardwareSerial Serial;
+#elif defined(USBCON)
+ #include "USBAPI.h"
+// extern HardwareSerial Serial_;
+#endif
+#if defined(UBRR1H)
+ extern HardwareSerial Serial1;
+#endif
+#if defined(UBRR2H)
+ extern HardwareSerial Serial2;
+#endif
+#if defined(UBRR3H)
+ extern HardwareSerial Serial3;
+#endif
+
+extern void serialEventRun(void) __attribute__((weak));
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/IPAddress.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/IPAddress.cpp
new file mode 100644
index 000000000..fe3deb77a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/IPAddress.cpp
@@ -0,0 +1,56 @@
+
+#include <Arduino.h>
+#include <IPAddress.h>
+
+IPAddress::IPAddress()
+{
+ memset(_address, 0, sizeof(_address));
+}
+
+IPAddress::IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet)
+{
+ _address[0] = first_octet;
+ _address[1] = second_octet;
+ _address[2] = third_octet;
+ _address[3] = fourth_octet;
+}
+
+IPAddress::IPAddress(uint32_t address)
+{
+ memcpy(_address, &address, sizeof(_address));
+}
+
+IPAddress::IPAddress(const uint8_t *address)
+{
+ memcpy(_address, address, sizeof(_address));
+}
+
+IPAddress& IPAddress::operator=(const uint8_t *address)
+{
+ memcpy(_address, address, sizeof(_address));
+ return *this;
+}
+
+IPAddress& IPAddress::operator=(uint32_t address)
+{
+ memcpy(_address, (const uint8_t *)&address, sizeof(_address));
+ return *this;
+}
+
+bool IPAddress::operator==(const uint8_t* addr)
+{
+ return memcmp(addr, _address, sizeof(_address)) == 0;
+}
+
+size_t IPAddress::printTo(Print& p) const
+{
+ size_t n = 0;
+ for (int i =0; i < 3; i++)
+ {
+ n += p.print(_address[i], DEC);
+ n += p.print('.');
+ }
+ n += p.print(_address[3], DEC);
+ return n;
+}
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/IPAddress.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/IPAddress.h
new file mode 100644
index 000000000..2585aec0e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/IPAddress.h
@@ -0,0 +1,76 @@
+/*
+ *
+ * MIT License:
+ * Copyright (c) 2011 Adrian McEwen
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * adrianm@mcqn.com 1/1/2011
+ */
+
+#ifndef IPAddress_h
+#define IPAddress_h
+
+#include <Printable.h>
+
+// A class to make it easier to handle and pass around IP addresses
+
+class IPAddress : public Printable {
+private:
+ uint8_t _address[4]; // IPv4 address
+ // Access the raw byte array containing the address. Because this returns a pointer
+ // to the internal structure rather than a copy of the address this function should only
+ // be used when you know that the usage of the returned uint8_t* will be transient and not
+ // stored.
+ uint8_t* raw_address() { return _address; };
+
+public:
+ // Constructors
+ IPAddress();
+ IPAddress(uint8_t first_octet, uint8_t second_octet, uint8_t third_octet, uint8_t fourth_octet);
+ IPAddress(uint32_t address);
+ IPAddress(const uint8_t *address);
+
+ // Overloaded cast operator to allow IPAddress objects to be used where a pointer
+ // to a four-byte uint8_t array is expected
+ operator uint32_t() { return *((uint32_t*)_address); };
+ bool operator==(const IPAddress& addr) { return (*((uint32_t*)_address)) == (*((uint32_t*)addr._address)); };
+ bool operator==(const uint8_t* addr);
+
+ // Overloaded index operator to allow getting and setting individual octets of the address
+ uint8_t operator[](int index) const { return _address[index]; };
+ uint8_t& operator[](int index) { return _address[index]; };
+
+ // Overloaded copy operators to allow initialisation of IPAddress objects from other types
+ IPAddress& operator=(const uint8_t *address);
+ IPAddress& operator=(uint32_t address);
+
+ virtual size_t printTo(Print& p) const;
+
+ friend class EthernetClass;
+ friend class UDP;
+ friend class Client;
+ friend class Server;
+ friend class DhcpClass;
+ friend class DNSClient;
+};
+
+const IPAddress INADDR_NONE(0,0,0,0);
+
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Platform.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Platform.h
new file mode 100644
index 000000000..8b8f74277
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Platform.h
@@ -0,0 +1,23 @@
+
+#ifndef __PLATFORM_H__
+#define __PLATFORM_H__
+
+#include <inttypes.h>
+#include <avr/pgmspace.h>
+#include <avr/eeprom.h>
+#include <avr/interrupt.h>
+#include <util/delay.h>
+
+typedef unsigned char u8;
+typedef unsigned short u16;
+typedef unsigned long u32;
+
+#include "Arduino.h"
+
+#if defined(USBCON)
+ #include "USBDesc.h"
+ #include "USBCore.h"
+ #include "USBAPI.h"
+#endif /* if defined(USBCON) */
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Print.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Print.cpp
new file mode 100644
index 000000000..e541a6ce7
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Print.cpp
@@ -0,0 +1,263 @@
+/*
+ Print.cpp - Base class that provides print() and println()
+ Copyright (c) 2008 David A. Mellis. All right reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+ Modified 23 November 2006 by David A. Mellis
+ */
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <math.h>
+#include "Arduino.h"
+
+#include "Print.h"
+
+// Public Methods //////////////////////////////////////////////////////////////
+
+/* default implementation: may be overridden */
+size_t Print::write(const uint8_t *buffer, size_t size)
+{
+ size_t n = 0;
+ while (size--) {
+ n += write(*buffer++);
+ }
+ return n;
+}
+
+size_t Print::print(const __FlashStringHelper *ifsh)
+{
+ const char PROGMEM *p = (const char PROGMEM *)ifsh;
+ size_t n = 0;
+ while (1) {
+ unsigned char c = pgm_read_byte(p++);
+ if (c == 0) break;
+ n += write(c);
+ }
+ return n;
+}
+
+size_t Print::print(const String &s)
+{
+ size_t n = 0;
+ for (uint16_t i = 0; i < s.length(); i++) {
+ n += write(s[i]);
+ }
+ return n;
+}
+
+size_t Print::print(const char str[])
+{
+ return write(str);
+}
+
+size_t Print::print(char c)
+{
+ return write(c);
+}
+
+size_t Print::print(unsigned char b, int base)
+{
+ return print((unsigned long) b, base);
+}
+
+size_t Print::print(int n, int base)
+{
+ return print((long) n, base);
+}
+
+size_t Print::print(unsigned int n, int base)
+{
+ return print((unsigned long) n, base);
+}
+
+size_t Print::print(long n, int base)
+{
+ if (base == 0) {
+ return write(n);
+ } else if (base == 10) {
+ if (n < 0) {
+ int t = print('-');
+ n = -n;
+ return printNumber(n, 10) + t;
+ }
+ return printNumber(n, 10);
+ } else {
+ return printNumber(n, base);
+ }
+}
+
+size_t Print::print(unsigned long n, int base)
+{
+ if (base == 0) return write(n);
+ else return printNumber(n, base);
+}
+
+size_t Print::print(double n, int digits)
+{
+ return printFloat(n, digits);
+}
+
+size_t Print::println(const __FlashStringHelper *ifsh)
+{
+ size_t n = print(ifsh);
+ n += println();
+ return n;
+}
+
+size_t Print::print(const Printable& x)
+{
+ return x.printTo(*this);
+}
+
+size_t Print::println(void)
+{
+ size_t n = print('\r');
+ n += print('\n');
+ return n;
+}
+
+size_t Print::println(const String &s)
+{
+ size_t n = print(s);
+ n += println();
+ return n;
+}
+
+size_t Print::println(const char c[])
+{
+ size_t n = print(c);
+ n += println();
+ return n;
+}
+
+size_t Print::println(char c)
+{
+ size_t n = print(c);
+ n += println();
+ return n;
+}
+
+size_t Print::println(unsigned char b, int base)
+{
+ size_t n = print(b, base);
+ n += println();
+ return n;
+}
+
+size_t Print::println(int num, int base)
+{
+ size_t n = print(num, base);
+ n += println();
+ return n;
+}
+
+size_t Print::println(unsigned int num, int base)
+{
+ size_t n = print(num, base);
+ n += println();
+ return n;
+}
+
+size_t Print::println(long num, int base)
+{
+ size_t n = print(num, base);
+ n += println();
+ return n;
+}
+
+size_t Print::println(unsigned long num, int base)
+{
+ size_t n = print(num, base);
+ n += println();
+ return n;
+}
+
+size_t Print::println(double num, int digits)
+{
+ size_t n = print(num, digits);
+ n += println();
+ return n;
+}
+
+size_t Print::println(const Printable& x)
+{
+ size_t n = print(x);
+ n += println();
+ return n;
+}
+
+// Private Methods /////////////////////////////////////////////////////////////
+
+size_t Print::printNumber(unsigned long n, uint8_t base) {
+ char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
+ char *str = &buf[sizeof(buf) - 1];
+
+ *str = '\0';
+
+ // prevent crash if called with base == 1
+ if (base < 2) base = 10;
+
+ do {
+ unsigned long m = n;
+ n /= base;
+ char c = m - base * n;
+ *--str = c < 10 ? c + '0' : c + 'A' - 10;
+ } while(n);
+
+ return write(str);
+}
+
+size_t Print::printFloat(double number, uint8_t digits)
+{
+ size_t n = 0;
+
+ // Handle negative numbers
+ if (number < 0.0)
+ {
+ n += print('-');
+ number = -number;
+ }
+
+ // Round correctly so that print(1.999, 2) prints as "2.00"
+ double rounding = 0.5;
+ for (uint8_t i=0; i<digits; ++i)
+ rounding /= 10.0;
+
+ number += rounding;
+
+ // Extract the integer part of the number and print it
+ unsigned long int_part = (unsigned long)number;
+ double remainder = number - (double)int_part;
+ n += print(int_part);
+
+ // Print the decimal point, but only if there are digits beyond
+ if (digits > 0) {
+ n += print(".");
+ }
+
+ // Extract digits from the remainder one at a time
+ while (digits-- > 0)
+ {
+ remainder *= 10.0;
+ int toPrint = int(remainder);
+ n += print(toPrint);
+ remainder -= toPrint;
+ }
+
+ return n;
+}
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Print.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Print.h
new file mode 100644
index 000000000..1af6b723f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Print.h
@@ -0,0 +1,78 @@
+/*
+ Print.h - Base class that provides print() and println()
+ Copyright (c) 2008 David A. Mellis. All right reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+#ifndef Print_h
+#define Print_h
+
+#include <inttypes.h>
+#include <stdio.h> // for size_t
+
+#include "WString.h"
+#include "Printable.h"
+
+#define DEC 10
+#define HEX 16
+#define OCT 8
+#define BIN 2
+
+class Print
+{
+ private:
+ int write_error;
+ size_t printNumber(unsigned long, uint8_t);
+ size_t printFloat(double, uint8_t);
+ protected:
+ void setWriteError(int err = 1) { write_error = err; }
+ public:
+ Print() : write_error(0) {}
+
+ int getWriteError() { return write_error; }
+ void clearWriteError() { setWriteError(0); }
+
+ virtual size_t write(uint8_t) = 0;
+ size_t write(const char *str) { return write((const uint8_t *)str, strlen(str)); }
+ virtual size_t write(const uint8_t *buffer, size_t size);
+
+ size_t print(const __FlashStringHelper *);
+ size_t print(const String &);
+ size_t print(const char[]);
+ size_t print(char);
+ size_t print(unsigned char, int = DEC);
+ size_t print(int, int = DEC);
+ size_t print(unsigned int, int = DEC);
+ size_t print(long, int = DEC);
+ size_t print(unsigned long, int = DEC);
+ size_t print(double, int = 2);
+ size_t print(const Printable&);
+
+ size_t println(const __FlashStringHelper *);
+ size_t println(const String &s);
+ size_t println(const char[]);
+ size_t println(char);
+ size_t println(unsigned char, int = DEC);
+ size_t println(int, int = DEC);
+ size_t println(unsigned int, int = DEC);
+ size_t println(long, int = DEC);
+ size_t println(unsigned long, int = DEC);
+ size_t println(double, int = 2);
+ size_t println(const Printable&);
+ size_t println(void);
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Printable.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Printable.h
new file mode 100644
index 000000000..d03c9af62
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Printable.h
@@ -0,0 +1,40 @@
+/*
+ Printable.h - Interface class that allows printing of complex types
+ Copyright (c) 2011 Adrian McEwen. All right reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+#ifndef Printable_h
+#define Printable_h
+
+#include <new.h>
+
+class Print;
+
+/** The Printable class provides a way for new classes to allow themselves to be printed.
+ By deriving from Printable and implementing the printTo method, it will then be possible
+ for users to print out instances of this class by passing them into the usual
+ Print::print and Print::println methods.
+*/
+
+class Printable
+{
+ public:
+ virtual size_t printTo(Print& p) const = 0;
+};
+
+#endif
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Server.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Server.h
new file mode 100644
index 000000000..9674c7626
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Server.h
@@ -0,0 +1,9 @@
+#ifndef server_h
+#define server_h
+
+class Server : public Print {
+public:
+ virtual void begin() =0;
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Stream.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Stream.cpp
new file mode 100644
index 000000000..aafb7fcf9
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Stream.cpp
@@ -0,0 +1,270 @@
+/*
+ Stream.cpp - adds parsing methods to Stream class
+ Copyright (c) 2008 David A. Mellis. All right reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+ Created July 2011
+ parsing functions based on TextFinder library by Michael Margolis
+ */
+
+#include "Arduino.h"
+#include "Stream.h"
+
+#define PARSE_TIMEOUT 1000 // default number of milli-seconds to wait
+#define NO_SKIP_CHAR 1 // a magic char not found in a valid ASCII numeric field
+
+// private method to read stream with timeout
+int Stream::timedRead()
+{
+ int c;
+ _startMillis = millis();
+ do {
+ c = read();
+ if (c >= 0) return c;
+ } while(millis() - _startMillis < _timeout);
+ return -1; // -1 indicates timeout
+}
+
+// private method to peek stream with timeout
+int Stream::timedPeek()
+{
+ int c;
+ _startMillis = millis();
+ do {
+ c = peek();
+ if (c >= 0) return c;
+ } while(millis() - _startMillis < _timeout);
+ return -1; // -1 indicates timeout
+}
+
+// returns peek of the next digit in the stream or -1 if timeout
+// discards non-numeric characters
+int Stream::peekNextDigit()
+{
+ int c;
+ while (1) {
+ c = timedPeek();
+ if (c < 0) return c; // timeout
+ if (c == '-') return c;
+ if (c >= '0' && c <= '9') return c;
+ read(); // discard non-numeric
+ }
+}
+
+// Public Methods
+//////////////////////////////////////////////////////////////
+
+void Stream::setTimeout(unsigned long timeout) // sets the maximum number of milliseconds to wait
+{
+ _timeout = timeout;
+}
+
+ // find returns true if the target string is found
+bool Stream::find(char *target)
+{
+ return findUntil(target, NULL);
+}
+
+// reads data from the stream until the target string of given length is found
+// returns true if target string is found, false if timed out
+bool Stream::find(char *target, size_t length)
+{
+ return findUntil(target, length, NULL, 0);
+}
+
+// as find but search ends if the terminator string is found
+bool Stream::findUntil(char *target, char *terminator)
+{
+ return findUntil(target, strlen(target), terminator, strlen(terminator));
+}
+
+// reads data from the stream until the target string of the given length is found
+// search terminated if the terminator string is found
+// returns true if target string is found, false if terminated or timed out
+bool Stream::findUntil(char *target, size_t targetLen, char *terminator, size_t termLen)
+{
+ size_t index = 0; // maximum target string length is 64k bytes!
+ size_t termIndex = 0;
+ int c;
+
+ if( *target == 0)
+ return true; // return true if target is a null string
+ while( (c = timedRead()) > 0){
+
+ if(c != target[index])
+ index = 0; // reset index if any char does not match
+
+ if( c == target[index]){
+ //////Serial.print("found "); Serial.write(c); Serial.print("index now"); Serial.println(index+1);
+ if(++index >= targetLen){ // return true if all chars in the target match
+ return true;
+ }
+ }
+
+ if(termLen > 0 && c == terminator[termIndex]){
+ if(++termIndex >= termLen)
+ return false; // return false if terminate string found before target string
+ }
+ else
+ termIndex = 0;
+ }
+ return false;
+}
+
+
+// returns the first valid (long) integer value from the current position.
+// initial characters that are not digits (or the minus sign) are skipped
+// function is terminated by the first character that is not a digit.
+long Stream::parseInt()
+{
+ return parseInt(NO_SKIP_CHAR); // terminate on first non-digit character (or timeout)
+}
+
+// as above but a given skipChar is ignored
+// this allows format characters (typically commas) in values to be ignored
+long Stream::parseInt(char skipChar)
+{
+ boolean isNegative = false;
+ long value = 0;
+ int c;
+
+ c = peekNextDigit();
+ // ignore non numeric leading characters
+ if(c < 0)
+ return 0; // zero returned if timeout
+
+ do{
+ if(c == skipChar)
+ ; // ignore this charactor
+ else if(c == '-')
+ isNegative = true;
+ else if(c >= '0' && c <= '9') // is c a digit?
+ value = value * 10 + c - '0';
+ read(); // consume the character we got with peek
+ c = timedPeek();
+ }
+ while( (c >= '0' && c <= '9') || c == skipChar );
+
+ if(isNegative)
+ value = -value;
+ return value;
+}
+
+
+// as parseInt but returns a floating point value
+float Stream::parseFloat()
+{
+ return parseFloat(NO_SKIP_CHAR);
+}
+
+// as above but the given skipChar is ignored
+// this allows format characters (typically commas) in values to be ignored
+float Stream::parseFloat(char skipChar){
+ boolean isNegative = false;
+ boolean isFraction = false;
+ long value = 0;
+ char c;
+ float fraction = 1.0;
+
+ c = peekNextDigit();
+ // ignore non numeric leading characters
+ if(c < 0)
+ return 0; // zero returned if timeout
+
+ do{
+ if(c == skipChar)
+ ; // ignore
+ else if(c == '-')
+ isNegative = true;
+ else if (c == '.')
+ isFraction = true;
+ else if(c >= '0' && c <= '9') { // is c a digit?
+ value = value * 10 + c - '0';
+ if(isFraction)
+ fraction *= 0.1;
+ }
+ read(); // consume the character we got with peek
+ c = timedPeek();
+ }
+ while( (c >= '0' && c <= '9') || c == '.' || c == skipChar );
+
+ if(isNegative)
+ value = -value;
+ if(isFraction)
+ return value * fraction;
+ else
+ return value;
+}
+
+// read characters from stream into buffer
+// terminates if length characters have been read, or timeout (see setTimeout)
+// returns the number of characters placed in the buffer
+// the buffer is NOT null terminated.
+//
+size_t Stream::readBytes(char *buffer, size_t length)
+{
+ size_t count = 0;
+ while (count < length) {
+ int c = timedRead();
+ if (c < 0) break;
+ *buffer++ = (char)c;
+ count++;
+ }
+ return count;
+}
+
+
+// as readBytes with terminator character
+// terminates if length characters have been read, timeout, or if the terminator character detected
+// returns the number of characters placed in the buffer (0 means no valid data found)
+
+size_t Stream::readBytesUntil(char terminator, char *buffer, size_t length)
+{
+ if (length < 1) return 0;
+ size_t index = 0;
+ while (index < length) {
+ int c = timedRead();
+ if (c < 0 || c == terminator) break;
+ *buffer++ = (char)c;
+ index++;
+ }
+ return index; // return number of characters, not including null terminator
+}
+
+String Stream::readString()
+{
+ String ret;
+ int c = timedRead();
+ while (c >= 0)
+ {
+ ret += (char)c;
+ c = timedRead();
+ }
+ return ret;
+}
+
+String Stream::readStringUntil(char terminator)
+{
+ String ret;
+ int c = timedRead();
+ while (c >= 0 && c != terminator)
+ {
+ ret += (char)c;
+ c = timedRead();
+ }
+ return ret;
+}
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Stream.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Stream.h
new file mode 100644
index 000000000..58bbf752f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Stream.h
@@ -0,0 +1,96 @@
+/*
+ Stream.h - base class for character-based streams.
+ Copyright (c) 2010 David A. Mellis. All right reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+ parsing functions based on TextFinder library by Michael Margolis
+*/
+
+#ifndef Stream_h
+#define Stream_h
+
+#include <inttypes.h>
+#include "Print.h"
+
+// compatability macros for testing
+/*
+#define getInt() parseInt()
+#define getInt(skipChar) parseInt(skipchar)
+#define getFloat() parseFloat()
+#define getFloat(skipChar) parseFloat(skipChar)
+#define getString( pre_string, post_string, buffer, length)
+readBytesBetween( pre_string, terminator, buffer, length)
+*/
+
+class Stream : public Print
+{
+ private:
+ unsigned long _timeout; // number of milliseconds to wait for the next char before aborting timed read
+ unsigned long _startMillis; // used for timeout measurement
+ int timedRead(); // private method to read stream with timeout
+ int timedPeek(); // private method to peek stream with timeout
+ int peekNextDigit(); // returns the next numeric digit in the stream or -1 if timeout
+
+ public:
+ virtual int available() = 0;
+ virtual int read() = 0;
+ virtual int peek() = 0;
+ virtual void flush() = 0;
+
+ Stream() {_timeout=1000;}
+
+// parsing methods
+
+ void setTimeout(unsigned long timeout); // sets maximum milliseconds to wait for stream data, default is 1 second
+
+ bool find(char *target); // reads data from the stream until the target string is found
+ // returns true if target string is found, false if timed out (see setTimeout)
+
+ bool find(char *target, size_t length); // reads data from the stream until the target string of given length is found
+ // returns true if target string is found, false if timed out
+
+ bool findUntil(char *target, char *terminator); // as find but search ends if the terminator string is found
+
+ bool findUntil(char *target, size_t targetLen, char *terminate, size_t termLen); // as above but search ends if the terminate string is found
+
+
+ long parseInt(); // returns the first valid (long) integer value from the current position.
+ // initial characters that are not digits (or the minus sign) are skipped
+ // integer is terminated by the first character that is not a digit.
+
+ float parseFloat(); // float version of parseInt
+
+ size_t readBytes( char *buffer, size_t length); // read chars from stream into buffer
+ // terminates if length characters have been read or timeout (see setTimeout)
+ // returns the number of characters placed in the buffer (0 means no valid data found)
+
+ size_t readBytesUntil( char terminator, char *buffer, size_t length); // as readBytes with terminator character
+ // terminates if length characters have been read, timeout, or if the terminator character detected
+ // returns the number of characters placed in the buffer (0 means no valid data found)
+
+ // Arduino String functions to be added here
+ String readString();
+ String readStringUntil(char terminator);
+
+ protected:
+ long parseInt(char skipChar); // as above but the given skipChar is ignored
+ // as above but the given skipChar is ignored
+ // this allows format characters (typically commas) in values to be ignored
+
+ float parseFloat(char skipChar); // as above but the given skipChar is ignored
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Tone.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Tone.cpp
new file mode 100644
index 000000000..20eed3f48
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Tone.cpp
@@ -0,0 +1,601 @@
+/* Tone.cpp
+
+ A Tone Generator Library
+
+ Written by Brett Hagman
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+
+Version Modified By Date Comments
+------- ----------- -------- --------
+0001 B Hagman 09/08/02 Initial coding
+0002 B Hagman 09/08/18 Multiple pins
+0003 B Hagman 09/08/18 Moved initialization from constructor to begin()
+0004 B Hagman 09/09/26 Fixed problems with ATmega8
+0005 B Hagman 09/11/23 Scanned prescalars for best fit on 8 bit timers
+ 09/11/25 Changed pin toggle method to XOR
+ 09/11/25 Fixed timer0 from being excluded
+0006 D Mellis 09/12/29 Replaced objects with functions
+0007 M Sproul 10/08/29 Changed #ifdefs from cpu to register
+*************************************************/
+
+#include <avr/interrupt.h>
+#include <avr/pgmspace.h>
+#include "Arduino.h"
+#include "pins_arduino.h"
+
+#if defined(__AVR_ATmega8__) || defined(__AVR_ATmega128__)
+#define TCCR2A TCCR2
+#define TCCR2B TCCR2
+#define COM2A1 COM21
+#define COM2A0 COM20
+#define OCR2A OCR2
+#define TIMSK2 TIMSK
+#define OCIE2A OCIE2
+#define TIMER2_COMPA_vect TIMER2_COMP_vect
+#define TIMSK1 TIMSK
+#endif
+
+// timerx_toggle_count:
+// > 0 - duration specified
+// = 0 - stopped
+// < 0 - infinitely (until stop() method called, or new play() called)
+
+#if !defined(__AVR_ATmega8__)
+volatile long timer0_toggle_count;
+volatile uint8_t *timer0_pin_port;
+volatile uint8_t timer0_pin_mask;
+#endif
+
+volatile long timer1_toggle_count;
+volatile uint8_t *timer1_pin_port;
+volatile uint8_t timer1_pin_mask;
+volatile long timer2_toggle_count;
+volatile uint8_t *timer2_pin_port;
+volatile uint8_t timer2_pin_mask;
+
+#if defined(TIMSK3)
+volatile long timer3_toggle_count;
+volatile uint8_t *timer3_pin_port;
+volatile uint8_t timer3_pin_mask;
+#endif
+
+#if defined(TIMSK4)
+volatile long timer4_toggle_count;
+volatile uint8_t *timer4_pin_port;
+volatile uint8_t timer4_pin_mask;
+#endif
+
+#if defined(TIMSK5)
+volatile long timer5_toggle_count;
+volatile uint8_t *timer5_pin_port;
+volatile uint8_t timer5_pin_mask;
+#endif
+
+
+// MLS: This does not make sense, the 3 options are the same
+#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+
+#define AVAILABLE_TONE_PINS 1
+
+const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 3, 4, 5, 1, 0 */ };
+static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255, 255, 255, 255 */ };
+
+#elif defined(__AVR_ATmega8__)
+
+#define AVAILABLE_TONE_PINS 1
+
+const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1 */ };
+static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255 */ };
+
+#else
+
+#define AVAILABLE_TONE_PINS 1
+
+// Leave timer 0 to last.
+const uint8_t PROGMEM tone_pin_to_timer_PGM[] = { 2 /*, 1, 0 */ };
+static uint8_t tone_pins[AVAILABLE_TONE_PINS] = { 255 /*, 255, 255 */ };
+
+#endif
+
+
+
+static int8_t toneBegin(uint8_t _pin)
+{
+ int8_t _timer = -1;
+
+ // if we're already using the pin, the timer should be configured.
+ for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
+ if (tone_pins[i] == _pin) {
+ return pgm_read_byte(tone_pin_to_timer_PGM + i);
+ }
+ }
+
+ // search for an unused timer.
+ for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
+ if (tone_pins[i] == 255) {
+ tone_pins[i] = _pin;
+ _timer = pgm_read_byte(tone_pin_to_timer_PGM + i);
+ break;
+ }
+ }
+
+ if (_timer != -1)
+ {
+ // Set timer specific stuff
+ // All timers in CTC mode
+ // 8 bit timers will require changing prescalar values,
+ // whereas 16 bit timers are set to either ck/1 or ck/64 prescalar
+ switch (_timer)
+ {
+ #if defined(TCCR0A) && defined(TCCR0B)
+ case 0:
+ // 8 bit timer
+ TCCR0A = 0;
+ TCCR0B = 0;
+ bitWrite(TCCR0A, WGM01, 1);
+ bitWrite(TCCR0B, CS00, 1);
+ timer0_pin_port = portOutputRegister(digitalPinToPort(_pin));
+ timer0_pin_mask = digitalPinToBitMask(_pin);
+ break;
+ #endif
+
+ #if defined(TCCR1A) && defined(TCCR1B) && defined(WGM12)
+ case 1:
+ // 16 bit timer
+ TCCR1A = 0;
+ TCCR1B = 0;
+ bitWrite(TCCR1B, WGM12, 1);
+ bitWrite(TCCR1B, CS10, 1);
+ timer1_pin_port = portOutputRegister(digitalPinToPort(_pin));
+ timer1_pin_mask = digitalPinToBitMask(_pin);
+ break;
+ #endif
+
+ #if defined(TCCR2A) && defined(TCCR2B)
+ case 2:
+ // 8 bit timer
+ TCCR2A = 0;
+ TCCR2B = 0;
+ bitWrite(TCCR2A, WGM21, 1);
+ bitWrite(TCCR2B, CS20, 1);
+ timer2_pin_port = portOutputRegister(digitalPinToPort(_pin));
+ timer2_pin_mask = digitalPinToBitMask(_pin);
+ break;
+ #endif
+
+ #if defined(TCCR3A) && defined(TCCR3B) && defined(TIMSK3)
+ case 3:
+ // 16 bit timer
+ TCCR3A = 0;
+ TCCR3B = 0;
+ bitWrite(TCCR3B, WGM32, 1);
+ bitWrite(TCCR3B, CS30, 1);
+ timer3_pin_port = portOutputRegister(digitalPinToPort(_pin));
+ timer3_pin_mask = digitalPinToBitMask(_pin);
+ break;
+ #endif
+
+ #if defined(TCCR4A) && defined(TCCR4B) && defined(TIMSK4)
+ case 4:
+ // 16 bit timer
+ TCCR4A = 0;
+ TCCR4B = 0;
+ #if defined(WGM42)
+ bitWrite(TCCR4B, WGM42, 1);
+ #elif defined(CS43)
+ #warning this may not be correct
+ // atmega32u4
+ bitWrite(TCCR4B, CS43, 1);
+ #endif
+ bitWrite(TCCR4B, CS40, 1);
+ timer4_pin_port = portOutputRegister(digitalPinToPort(_pin));
+ timer4_pin_mask = digitalPinToBitMask(_pin);
+ break;
+ #endif
+
+ #if defined(TCCR5A) && defined(TCCR5B) && defined(TIMSK5)
+ case 5:
+ // 16 bit timer
+ TCCR5A = 0;
+ TCCR5B = 0;
+ bitWrite(TCCR5B, WGM52, 1);
+ bitWrite(TCCR5B, CS50, 1);
+ timer5_pin_port = portOutputRegister(digitalPinToPort(_pin));
+ timer5_pin_mask = digitalPinToBitMask(_pin);
+ break;
+ #endif
+ }
+ }
+
+ return _timer;
+}
+
+
+
+// frequency (in hertz) and duration (in milliseconds).
+
+void tone(uint8_t _pin, unsigned int frequency, unsigned long duration)
+{
+ uint8_t prescalarbits = 0b001;
+ long toggle_count = 0;
+ uint32_t ocr = 0;
+ int8_t _timer;
+
+ _timer = toneBegin(_pin);
+
+ if (_timer >= 0)
+ {
+ // Set the pinMode as OUTPUT
+ pinMode(_pin, OUTPUT);
+
+ // if we are using an 8 bit timer, scan through prescalars to find the best fit
+ if (_timer == 0 || _timer == 2)
+ {
+ ocr = F_CPU / frequency / 2 - 1;
+ prescalarbits = 0b001; // ck/1: same for both timers
+ if (ocr > 255)
+ {
+ ocr = F_CPU / frequency / 2 / 8 - 1;
+ prescalarbits = 0b010; // ck/8: same for both timers
+
+ if (_timer == 2 && ocr > 255)
+ {
+ ocr = F_CPU / frequency / 2 / 32 - 1;
+ prescalarbits = 0b011;
+ }
+
+ if (ocr > 255)
+ {
+ ocr = F_CPU / frequency / 2 / 64 - 1;
+ prescalarbits = _timer == 0 ? 0b011 : 0b100;
+
+ if (_timer == 2 && ocr > 255)
+ {
+ ocr = F_CPU / frequency / 2 / 128 - 1;
+ prescalarbits = 0b101;
+ }
+
+ if (ocr > 255)
+ {
+ ocr = F_CPU / frequency / 2 / 256 - 1;
+ prescalarbits = _timer == 0 ? 0b100 : 0b110;
+ if (ocr > 255)
+ {
+ // can't do any better than /1024
+ ocr = F_CPU / frequency / 2 / 1024 - 1;
+ prescalarbits = _timer == 0 ? 0b101 : 0b111;
+ }
+ }
+ }
+ }
+
+#if defined(TCCR0B)
+ if (_timer == 0)
+ {
+ TCCR0B = prescalarbits;
+ }
+ else
+#endif
+#if defined(TCCR2B)
+ {
+ TCCR2B = prescalarbits;
+ }
+#else
+ {
+ // dummy place holder to make the above ifdefs work
+ }
+#endif
+ }
+ else
+ {
+ // two choices for the 16 bit timers: ck/1 or ck/64
+ ocr = F_CPU / frequency / 2 - 1;
+
+ prescalarbits = 0b001;
+ if (ocr > 0xffff)
+ {
+ ocr = F_CPU / frequency / 2 / 64 - 1;
+ prescalarbits = 0b011;
+ }
+
+ if (_timer == 1)
+ {
+#if defined(TCCR1B)
+ TCCR1B = (TCCR1B & 0b11111000) | prescalarbits;
+#endif
+ }
+#if defined(TCCR3B)
+ else if (_timer == 3)
+ TCCR3B = (TCCR3B & 0b11111000) | prescalarbits;
+#endif
+#if defined(TCCR4B)
+ else if (_timer == 4)
+ TCCR4B = (TCCR4B & 0b11111000) | prescalarbits;
+#endif
+#if defined(TCCR5B)
+ else if (_timer == 5)
+ TCCR5B = (TCCR5B & 0b11111000) | prescalarbits;
+#endif
+
+ }
+
+
+ // Calculate the toggle count
+ if (duration > 0)
+ {
+ toggle_count = 2 * frequency * duration / 1000;
+ }
+ else
+ {
+ toggle_count = -1;
+ }
+
+ // Set the OCR for the given timer,
+ // set the toggle count,
+ // then turn on the interrupts
+ switch (_timer)
+ {
+
+#if defined(OCR0A) && defined(TIMSK0) && defined(OCIE0A)
+ case 0:
+ OCR0A = ocr;
+ timer0_toggle_count = toggle_count;
+ bitWrite(TIMSK0, OCIE0A, 1);
+ break;
+#endif
+
+ case 1:
+#if defined(OCR1A) && defined(TIMSK1) && defined(OCIE1A)
+ OCR1A = ocr;
+ timer1_toggle_count = toggle_count;
+ bitWrite(TIMSK1, OCIE1A, 1);
+#elif defined(OCR1A) && defined(TIMSK) && defined(OCIE1A)
+ // this combination is for at least the ATmega32
+ OCR1A = ocr;
+ timer1_toggle_count = toggle_count;
+ bitWrite(TIMSK, OCIE1A, 1);
+#endif
+ break;
+
+#if defined(OCR2A) && defined(TIMSK2) && defined(OCIE2A)
+ case 2:
+ OCR2A = ocr;
+ timer2_toggle_count = toggle_count;
+ bitWrite(TIMSK2, OCIE2A, 1);
+ break;
+#endif
+
+#if defined(TIMSK3)
+ case 3:
+ OCR3A = ocr;
+ timer3_toggle_count = toggle_count;
+ bitWrite(TIMSK3, OCIE3A, 1);
+ break;
+#endif
+
+#if defined(TIMSK4)
+ case 4:
+ OCR4A = ocr;
+ timer4_toggle_count = toggle_count;
+ bitWrite(TIMSK4, OCIE4A, 1);
+ break;
+#endif
+
+#if defined(OCR5A) && defined(TIMSK5) && defined(OCIE5A)
+ case 5:
+ OCR5A = ocr;
+ timer5_toggle_count = toggle_count;
+ bitWrite(TIMSK5, OCIE5A, 1);
+ break;
+#endif
+
+ }
+ }
+}
+
+
+// XXX: this function only works properly for timer 2 (the only one we use
+// currently). for the others, it should end the tone, but won't restore
+// proper PWM functionality for the timer.
+void disableTimer(uint8_t _timer)
+{
+ switch (_timer)
+ {
+ case 0:
+ #if defined(TIMSK0)
+ TIMSK0 = 0;
+ #elif defined(TIMSK)
+ TIMSK = 0; // atmega32
+ #endif
+ break;
+
+#if defined(TIMSK1) && defined(OCIE1A)
+ case 1:
+ bitWrite(TIMSK1, OCIE1A, 0);
+ break;
+#endif
+
+ case 2:
+ #if defined(TIMSK2) && defined(OCIE2A)
+ bitWrite(TIMSK2, OCIE2A, 0); // disable interrupt
+ #endif
+ #if defined(TCCR2A) && defined(WGM20)
+ TCCR2A = (1 << WGM20);
+ #endif
+ #if defined(TCCR2B) && defined(CS22)
+ TCCR2B = (TCCR2B & 0b11111000) | (1 << CS22);
+ #endif
+ #if defined(OCR2A)
+ OCR2A = 0;
+ #endif
+ break;
+
+#if defined(TIMSK3)
+ case 3:
+ TIMSK3 = 0;
+ break;
+#endif
+
+#if defined(TIMSK4)
+ case 4:
+ TIMSK4 = 0;
+ break;
+#endif
+
+#if defined(TIMSK5)
+ case 5:
+ TIMSK5 = 0;
+ break;
+#endif
+ }
+}
+
+
+void noTone(uint8_t _pin)
+{
+ int8_t _timer = -1;
+
+ for (int i = 0; i < AVAILABLE_TONE_PINS; i++) {
+ if (tone_pins[i] == _pin) {
+ _timer = pgm_read_byte(tone_pin_to_timer_PGM + i);
+ tone_pins[i] = 255;
+ }
+ }
+
+ disableTimer(_timer);
+
+ digitalWrite(_pin, 0);
+}
+
+#if 0
+#if !defined(__AVR_ATmega8__)
+ISR(TIMER0_COMPA_vect)
+{
+ if (timer0_toggle_count != 0)
+ {
+ // toggle the pin
+ *timer0_pin_port ^= timer0_pin_mask;
+
+ if (timer0_toggle_count > 0)
+ timer0_toggle_count--;
+ }
+ else
+ {
+ disableTimer(0);
+ *timer0_pin_port &= ~(timer0_pin_mask); // keep pin low after stop
+ }
+}
+#endif
+
+
+ISR(TIMER1_COMPA_vect)
+{
+ if (timer1_toggle_count != 0)
+ {
+ // toggle the pin
+ *timer1_pin_port ^= timer1_pin_mask;
+
+ if (timer1_toggle_count > 0)
+ timer1_toggle_count--;
+ }
+ else
+ {
+ disableTimer(1);
+ *timer1_pin_port &= ~(timer1_pin_mask); // keep pin low after stop
+ }
+}
+#endif
+
+
+ISR(TIMER2_COMPA_vect)
+{
+
+ if (timer2_toggle_count != 0)
+ {
+ // toggle the pin
+ *timer2_pin_port ^= timer2_pin_mask;
+
+ if (timer2_toggle_count > 0)
+ timer2_toggle_count--;
+ }
+ else
+ {
+ // need to call noTone() so that the tone_pins[] entry is reset, so the
+ // timer gets initialized next time we call tone().
+ // XXX: this assumes timer 2 is always the first one used.
+ noTone(tone_pins[0]);
+// disableTimer(2);
+// *timer2_pin_port &= ~(timer2_pin_mask); // keep pin low after stop
+ }
+}
+
+
+
+//#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+#if 0
+
+ISR(TIMER3_COMPA_vect)
+{
+ if (timer3_toggle_count != 0)
+ {
+ // toggle the pin
+ *timer3_pin_port ^= timer3_pin_mask;
+
+ if (timer3_toggle_count > 0)
+ timer3_toggle_count--;
+ }
+ else
+ {
+ disableTimer(3);
+ *timer3_pin_port &= ~(timer3_pin_mask); // keep pin low after stop
+ }
+}
+
+ISR(TIMER4_COMPA_vect)
+{
+ if (timer4_toggle_count != 0)
+ {
+ // toggle the pin
+ *timer4_pin_port ^= timer4_pin_mask;
+
+ if (timer4_toggle_count > 0)
+ timer4_toggle_count--;
+ }
+ else
+ {
+ disableTimer(4);
+ *timer4_pin_port &= ~(timer4_pin_mask); // keep pin low after stop
+ }
+}
+
+ISR(TIMER5_COMPA_vect)
+{
+ if (timer5_toggle_count != 0)
+ {
+ // toggle the pin
+ *timer5_pin_port ^= timer5_pin_mask;
+
+ if (timer5_toggle_count > 0)
+ timer5_toggle_count--;
+ }
+ else
+ {
+ disableTimer(5);
+ *timer5_pin_port &= ~(timer5_pin_mask); // keep pin low after stop
+ }
+}
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBAPI.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBAPI.h
new file mode 100644
index 000000000..d5abdb690
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBAPI.h
@@ -0,0 +1,195 @@
+
+
+#ifndef __USBAPI__
+#define __USBAPI__
+
+#if defined(USBCON)
+
+//================================================================================
+//================================================================================
+// USB
+
+class USBDevice_
+{
+public:
+ USBDevice_();
+ bool configured();
+
+ void attach();
+ void detach(); // Serial port goes down too...
+ void poll();
+};
+extern USBDevice_ USBDevice;
+
+//================================================================================
+//================================================================================
+// Serial over CDC (Serial1 is the physical port)
+
+class Serial_ : public Stream
+{
+private:
+ ring_buffer *_cdc_rx_buffer;
+public:
+ void begin(uint16_t baud_count);
+ void end(void);
+
+ virtual int available(void);
+ virtual void accept(void);
+ virtual int peek(void);
+ virtual int read(void);
+ virtual void flush(void);
+ virtual size_t write(uint8_t);
+ operator bool();
+};
+extern Serial_ Serial;
+
+//================================================================================
+//================================================================================
+// Mouse
+
+#define MOUSE_LEFT 1
+#define MOUSE_RIGHT 2
+#define MOUSE_MIDDLE 4
+#define MOUSE_ALL (MOUSE_LEFT | MOUSE_RIGHT | MOUSE_MIDDLE)
+
+class Mouse_
+{
+private:
+ uint8_t _buttons;
+ void buttons(uint8_t b);
+public:
+ Mouse_(void);
+ void begin(void);
+ void end(void);
+ void click(uint8_t b = MOUSE_LEFT);
+ void move(signed char x, signed char y, signed char wheel = 0);
+ void press(uint8_t b = MOUSE_LEFT); // press LEFT by default
+ void release(uint8_t b = MOUSE_LEFT); // release LEFT by default
+ bool isPressed(uint8_t b = MOUSE_LEFT); // check LEFT by default
+};
+extern Mouse_ Mouse;
+
+//================================================================================
+//================================================================================
+// Keyboard
+
+#define KEY_LEFT_CTRL 0x80
+#define KEY_LEFT_SHIFT 0x81
+#define KEY_LEFT_ALT 0x82
+#define KEY_LEFT_GUI 0x83
+#define KEY_RIGHT_CTRL 0x84
+#define KEY_RIGHT_SHIFT 0x85
+#define KEY_RIGHT_ALT 0x86
+#define KEY_RIGHT_GUI 0x87
+
+#define KEY_UP_ARROW 0xDA
+#define KEY_DOWN_ARROW 0xD9
+#define KEY_LEFT_ARROW 0xD8
+#define KEY_RIGHT_ARROW 0xD7
+#define KEY_BACKSPACE 0xB2
+#define KEY_TAB 0xB3
+#define KEY_RETURN 0xB0
+#define KEY_ESC 0xB1
+#define KEY_INSERT 0xD1
+#define KEY_DELETE 0xD4
+#define KEY_PAGE_UP 0xD3
+#define KEY_PAGE_DOWN 0xD6
+#define KEY_HOME 0xD2
+#define KEY_END 0xD5
+#define KEY_CAPS_LOCK 0xC1
+#define KEY_F1 0xC2
+#define KEY_F2 0xC3
+#define KEY_F3 0xC4
+#define KEY_F4 0xC5
+#define KEY_F5 0xC6
+#define KEY_F6 0xC7
+#define KEY_F7 0xC8
+#define KEY_F8 0xC9
+#define KEY_F9 0xCA
+#define KEY_F10 0xCB
+#define KEY_F11 0xCC
+#define KEY_F12 0xCD
+
+// Low level key report: up to 6 keys and shift, ctrl etc at once
+typedef struct
+{
+ uint8_t modifiers;
+ uint8_t reserved;
+ uint8_t keys[6];
+} KeyReport;
+
+class Keyboard_ : public Print
+{
+private:
+ KeyReport _keyReport;
+ void sendReport(KeyReport* keys);
+public:
+ Keyboard_(void);
+ void begin(void);
+ void end(void);
+ virtual size_t write(uint8_t k);
+ virtual size_t press(uint8_t k);
+ virtual size_t release(uint8_t k);
+ virtual void releaseAll(void);
+};
+extern Keyboard_ Keyboard;
+
+//================================================================================
+//================================================================================
+// Low level API
+
+typedef struct
+{
+ uint8_t bmRequestType;
+ uint8_t bRequest;
+ uint8_t wValueL;
+ uint8_t wValueH;
+ uint16_t wIndex;
+ uint16_t wLength;
+} Setup;
+
+//================================================================================
+//================================================================================
+// HID 'Driver'
+
+int HID_GetInterface(uint8_t* interfaceNum);
+int HID_GetDescriptor(int i);
+bool HID_Setup(Setup& setup);
+void HID_SendReport(uint8_t id, const void* data, int len);
+
+//================================================================================
+//================================================================================
+// MSC 'Driver'
+
+int MSC_GetInterface(uint8_t* interfaceNum);
+int MSC_GetDescriptor(int i);
+bool MSC_Setup(Setup& setup);
+bool MSC_Data(uint8_t rx,uint8_t tx);
+
+//================================================================================
+//================================================================================
+// CSC 'Driver'
+
+int CDC_GetInterface(uint8_t* interfaceNum);
+int CDC_GetDescriptor(int i);
+bool CDC_Setup(Setup& setup);
+
+//================================================================================
+//================================================================================
+
+#define TRANSFER_PGM 0x80
+#define TRANSFER_RELEASE 0x40
+#define TRANSFER_ZERO 0x20
+
+int USB_SendControl(uint8_t flags, const void* d, int len);
+int USB_RecvControl(void* d, int len);
+
+uint8_t USB_Available(uint8_t ep);
+int USB_Send(uint8_t ep, const void* data, int len); // blocking
+int USB_Recv(uint8_t ep, void* data, int len); // non-blocking
+int USB_Recv(uint8_t ep); // non-blocking
+void USB_Flush(uint8_t ep);
+
+#endif
+
+#endif /* if defined(USBCON) */ \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBCore.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBCore.cpp
new file mode 100644
index 000000000..6766be61a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBCore.cpp
@@ -0,0 +1,672 @@
+
+
+/* Copyright (c) 2010, Peter Barrett
+**
+** Permission to use, copy, modify, and/or distribute this software for
+** any purpose with or without fee is hereby granted, provided that the
+** above copyright notice and this permission notice appear in all copies.
+**
+** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
+** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
+** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
+** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+** SOFTWARE.
+*/
+
+#include "Platform.h"
+#include "USBAPI.h"
+#include "USBDesc.h"
+
+#if defined(USBCON)
+
+#define EP_TYPE_CONTROL 0x00
+#define EP_TYPE_BULK_IN 0x81
+#define EP_TYPE_BULK_OUT 0x80
+#define EP_TYPE_INTERRUPT_IN 0xC1
+#define EP_TYPE_INTERRUPT_OUT 0xC0
+#define EP_TYPE_ISOCHRONOUS_IN 0x41
+#define EP_TYPE_ISOCHRONOUS_OUT 0x40
+
+/** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */
+#define TX_RX_LED_PULSE_MS 100
+volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */
+volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */
+
+//==================================================================
+//==================================================================
+
+extern const u16 STRING_LANGUAGE[] PROGMEM;
+extern const u16 STRING_IPRODUCT[] PROGMEM;
+extern const u16 STRING_IMANUFACTURER[] PROGMEM;
+extern const DeviceDescriptor USB_DeviceDescriptor PROGMEM;
+extern const DeviceDescriptor USB_DeviceDescriptorA PROGMEM;
+
+const u16 STRING_LANGUAGE[2] = {
+ (3<<8) | (2+2),
+ 0x0409 // English
+};
+
+const u16 STRING_IPRODUCT[17] = {
+ (3<<8) | (2+2*16),
+#if USB_PID == 0x8036
+ 'A','r','d','u','i','n','o',' ','L','e','o','n','a','r','d','o'
+#else
+ 'U','S','B',' ','I','O',' ','B','o','a','r','d',' ',' ',' ',' '
+#endif
+};
+
+const u16 STRING_IMANUFACTURER[12] = {
+ (3<<8) | (2+2*11),
+#if USB_VID == 0x2341
+ 'A','r','d','u','i','n','o',' ','L','L','C'
+#else
+ 'U','n','k','n','o','w','n',' ',' ',' ',' '
+#endif
+};
+
+#ifdef CDC_ENABLED
+#define DEVICE_CLASS 0x02
+#else
+#define DEVICE_CLASS 0x00
+#endif
+
+// DEVICE DESCRIPTOR
+const DeviceDescriptor USB_DeviceDescriptor =
+ D_DEVICE(0x00,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1);
+
+const DeviceDescriptor USB_DeviceDescriptorA =
+ D_DEVICE(DEVICE_CLASS,0x00,0x00,64,USB_VID,USB_PID,0x100,IMANUFACTURER,IPRODUCT,0,1);
+
+//==================================================================
+//==================================================================
+
+volatile u8 _usbConfiguration = 0;
+
+static inline void WaitIN(void)
+{
+ while (!(UEINTX & (1<<TXINI)));
+}
+
+static inline void ClearIN(void)
+{
+ UEINTX = ~(1<<TXINI);
+}
+
+static inline void WaitOUT(void)
+{
+ while (!(UEINTX & (1<<RXOUTI)))
+ ;
+}
+
+static inline u8 WaitForINOrOUT()
+{
+ while (!(UEINTX & ((1<<TXINI)|(1<<RXOUTI))))
+ ;
+ return (UEINTX & (1<<RXOUTI)) == 0;
+}
+
+static inline void ClearOUT(void)
+{
+ UEINTX = ~(1<<RXOUTI);
+}
+
+void Recv(volatile u8* data, u8 count)
+{
+ while (count--)
+ *data++ = UEDATX;
+
+ RXLED1; // light the RX LED
+ RxLEDPulse = TX_RX_LED_PULSE_MS;
+}
+
+static inline u8 Recv8()
+{
+ RXLED1; // light the RX LED
+ RxLEDPulse = TX_RX_LED_PULSE_MS;
+
+ return UEDATX;
+}
+
+static inline void Send8(u8 d)
+{
+ UEDATX = d;
+}
+
+static inline void SetEP(u8 ep)
+{
+ UENUM = ep;
+}
+
+static inline u8 FifoByteCount()
+{
+ return UEBCLX;
+}
+
+static inline u8 ReceivedSetupInt()
+{
+ return UEINTX & (1<<RXSTPI);
+}
+
+static inline void ClearSetupInt()
+{
+ UEINTX = ~((1<<RXSTPI) | (1<<RXOUTI) | (1<<TXINI));
+}
+
+static inline void Stall()
+{
+ UECONX = (1<<STALLRQ) | (1<<EPEN);
+}
+
+static inline u8 ReadWriteAllowed()
+{
+ return UEINTX & (1<<RWAL);
+}
+
+static inline u8 Stalled()
+{
+ return UEINTX & (1<<STALLEDI);
+}
+
+static inline u8 FifoFree()
+{
+ return UEINTX & (1<<FIFOCON);
+}
+
+static inline void ReleaseRX()
+{
+ UEINTX = 0x6B; // FIFOCON=0 NAKINI=1 RWAL=1 NAKOUTI=0 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=1
+}
+
+static inline void ReleaseTX()
+{
+ UEINTX = 0x3A; // FIFOCON=0 NAKINI=0 RWAL=1 NAKOUTI=1 RXSTPI=1 RXOUTI=0 STALLEDI=1 TXINI=0
+}
+
+static inline u8 FrameNumber()
+{
+ return UDFNUML;
+}
+
+//==================================================================
+//==================================================================
+
+u8 USBGetConfiguration(void)
+{
+ return _usbConfiguration;
+}
+
+#define USB_RECV_TIMEOUT
+class LockEP
+{
+ u8 _sreg;
+public:
+ LockEP(u8 ep) : _sreg(SREG)
+ {
+ cli();
+ SetEP(ep & 7);
+ }
+ ~LockEP()
+ {
+ SREG = _sreg;
+ }
+};
+
+// Number of bytes, assumes a rx endpoint
+u8 USB_Available(u8 ep)
+{
+ LockEP lock(ep);
+ return FifoByteCount();
+}
+
+// Non Blocking receive
+// Return number of bytes read
+int USB_Recv(u8 ep, void* d, int len)
+{
+ if (!_usbConfiguration || len < 0)
+ return -1;
+
+ LockEP lock(ep);
+ u8 n = FifoByteCount();
+ len = min(n,len);
+ n = len;
+ u8* dst = (u8*)d;
+ while (n--)
+ *dst++ = Recv8();
+ if (len && !FifoByteCount()) // release empty buffer
+ ReleaseRX();
+
+ return len;
+}
+
+// Recv 1 byte if ready
+int USB_Recv(u8 ep)
+{
+ u8 c;
+ if (USB_Recv(ep,&c,1) != 1)
+ return -1;
+ return c;
+}
+
+// Space in send EP
+u8 USB_SendSpace(u8 ep)
+{
+ LockEP lock(ep);
+ if (!ReadWriteAllowed())
+ return 0;
+ return 64 - FifoByteCount();
+}
+
+// Blocking Send of data to an endpoint
+int USB_Send(u8 ep, const void* d, int len)
+{
+ if (!_usbConfiguration)
+ return -1;
+
+ int r = len;
+ const u8* data = (const u8*)d;
+ u8 zero = ep & TRANSFER_ZERO;
+ u8 timeout = 250; // 250ms timeout on send? TODO
+ while (len)
+ {
+ u8 n = USB_SendSpace(ep);
+ if (n == 0)
+ {
+ if (!(--timeout))
+ return -1;
+ delay(1);
+ continue;
+ }
+
+ if (n > len)
+ n = len;
+ len -= n;
+ {
+ LockEP lock(ep);
+ if (ep & TRANSFER_ZERO)
+ {
+ while (n--)
+ Send8(0);
+ }
+ else if (ep & TRANSFER_PGM)
+ {
+ while (n--)
+ Send8(pgm_read_byte(data++));
+ }
+ else
+ {
+ while (n--)
+ Send8(*data++);
+ }
+ if (!ReadWriteAllowed() || ((len == 0) && (ep & TRANSFER_RELEASE))) // Release full buffer
+ ReleaseTX();
+ }
+ }
+ TXLED1; // light the TX LED
+ TxLEDPulse = TX_RX_LED_PULSE_MS;
+ return r;
+}
+
+extern const u8 _initEndpoints[] PROGMEM;
+const u8 _initEndpoints[] =
+{
+ 0,
+
+#ifdef CDC_ENABLED
+ EP_TYPE_INTERRUPT_IN, // CDC_ENDPOINT_ACM
+ EP_TYPE_BULK_OUT, // CDC_ENDPOINT_OUT
+ EP_TYPE_BULK_IN, // CDC_ENDPOINT_IN
+#endif
+
+#ifdef HID_ENABLED
+ EP_TYPE_INTERRUPT_IN // HID_ENDPOINT_INT
+#endif
+};
+
+#define EP_SINGLE_64 0x32 // EP0
+#define EP_DOUBLE_64 0x36 // Other endpoints
+
+static
+void InitEP(u8 index, u8 type, u8 size)
+{
+ UENUM = index;
+ UECONX = 1;
+ UECFG0X = type;
+ UECFG1X = size;
+}
+
+static
+void InitEndpoints()
+{
+ for (u8 i = 1; i < sizeof(_initEndpoints); i++)
+ {
+ UENUM = i;
+ UECONX = 1;
+ UECFG0X = pgm_read_byte(_initEndpoints+i);
+ UECFG1X = EP_DOUBLE_64;
+ }
+ UERST = 0x7E; // And reset them
+ UERST = 0;
+}
+
+// Handle CLASS_INTERFACE requests
+static
+bool ClassInterfaceRequest(Setup& setup)
+{
+ u8 i = setup.wIndex;
+
+#ifdef CDC_ENABLED
+ if (CDC_ACM_INTERFACE == i)
+ return CDC_Setup(setup);
+#endif
+
+#ifdef HID_ENABLED
+ if (HID_INTERFACE == i)
+ return HID_Setup(setup);
+#endif
+ return false;
+}
+
+int _cmark;
+int _cend;
+void InitControl(int end)
+{
+ SetEP(0);
+ _cmark = 0;
+ _cend = end;
+}
+
+static
+bool SendControl(u8 d)
+{
+ if (_cmark < _cend)
+ {
+ if (!WaitForINOrOUT())
+ return false;
+ Send8(d);
+ if (!((_cmark + 1) & 0x3F))
+ ClearIN(); // Fifo is full, release this packet
+ }
+ _cmark++;
+ return true;
+};
+
+// Clipped by _cmark/_cend
+int USB_SendControl(u8 flags, const void* d, int len)
+{
+ int sent = len;
+ const u8* data = (const u8*)d;
+ bool pgm = flags & TRANSFER_PGM;
+ while (len--)
+ {
+ u8 c = pgm ? pgm_read_byte(data++) : *data++;
+ if (!SendControl(c))
+ return -1;
+ }
+ return sent;
+}
+
+// Does not timeout or cross fifo boundaries
+// Will only work for transfers <= 64 bytes
+// TODO
+int USB_RecvControl(void* d, int len)
+{
+ WaitOUT();
+ Recv((u8*)d,len);
+ ClearOUT();
+ return len;
+}
+
+int SendInterfaces()
+{
+ int total = 0;
+ u8 interfaces = 0;
+
+#ifdef CDC_ENABLED
+ total = CDC_GetInterface(&interfaces);
+#endif
+
+#ifdef HID_ENABLED
+ total += HID_GetInterface(&interfaces);
+#endif
+
+ return interfaces;
+}
+
+// Construct a dynamic configuration descriptor
+// This really needs dynamic endpoint allocation etc
+// TODO
+static
+bool SendConfiguration(int maxlen)
+{
+ // Count and measure interfaces
+ InitControl(0);
+ int interfaces = SendInterfaces();
+ ConfigDescriptor config = D_CONFIG(_cmark + sizeof(ConfigDescriptor),interfaces);
+
+ // Now send them
+ InitControl(maxlen);
+ USB_SendControl(0,&config,sizeof(ConfigDescriptor));
+ SendInterfaces();
+ return true;
+}
+
+u8 _cdcComposite = 0;
+
+static
+bool SendDescriptor(Setup& setup)
+{
+ u8 t = setup.wValueH;
+ if (USB_CONFIGURATION_DESCRIPTOR_TYPE == t)
+ return SendConfiguration(setup.wLength);
+
+ InitControl(setup.wLength);
+#ifdef HID_ENABLED
+ if (HID_REPORT_DESCRIPTOR_TYPE == t)
+ return HID_GetDescriptor(t);
+#endif
+
+ u8 desc_length = 0;
+ const u8* desc_addr = 0;
+ if (USB_DEVICE_DESCRIPTOR_TYPE == t)
+ {
+ if (setup.wLength == 8)
+ _cdcComposite = 1;
+ desc_addr = _cdcComposite ? (const u8*)&USB_DeviceDescriptorA : (const u8*)&USB_DeviceDescriptor;
+ }
+ else if (USB_STRING_DESCRIPTOR_TYPE == t)
+ {
+ if (setup.wValueL == 0)
+ desc_addr = (const u8*)&STRING_LANGUAGE;
+ else if (setup.wValueL == IPRODUCT)
+ desc_addr = (const u8*)&STRING_IPRODUCT;
+ else if (setup.wValueL == IMANUFACTURER)
+ desc_addr = (const u8*)&STRING_IMANUFACTURER;
+ else
+ return false;
+ }
+
+ if (desc_addr == 0)
+ return false;
+ if (desc_length == 0)
+ desc_length = pgm_read_byte(desc_addr);
+
+ USB_SendControl(TRANSFER_PGM,desc_addr,desc_length);
+ return true;
+}
+
+// Endpoint 0 interrupt
+ISR(USB_COM_vect)
+{
+ SetEP(0);
+ if (!ReceivedSetupInt())
+ return;
+
+ Setup setup;
+ Recv((u8*)&setup,8);
+ ClearSetupInt();
+
+ u8 requestType = setup.bmRequestType;
+ if (requestType & REQUEST_DEVICETOHOST)
+ WaitIN();
+ else
+ ClearIN();
+
+ bool ok = true;
+ if (REQUEST_STANDARD == (requestType & REQUEST_TYPE))
+ {
+ // Standard Requests
+ u8 r = setup.bRequest;
+ if (GET_STATUS == r)
+ {
+ Send8(0); // TODO
+ Send8(0);
+ }
+ else if (CLEAR_FEATURE == r)
+ {
+ }
+ else if (SET_FEATURE == r)
+ {
+ }
+ else if (SET_ADDRESS == r)
+ {
+ WaitIN();
+ UDADDR = setup.wValueL | (1<<ADDEN);
+ }
+ else if (GET_DESCRIPTOR == r)
+ {
+ ok = SendDescriptor(setup);
+ }
+ else if (SET_DESCRIPTOR == r)
+ {
+ ok = false;
+ }
+ else if (GET_CONFIGURATION == r)
+ {
+ Send8(1);
+ }
+ else if (SET_CONFIGURATION == r)
+ {
+ if (REQUEST_DEVICE == (requestType & REQUEST_RECIPIENT))
+ {
+ InitEndpoints();
+ _usbConfiguration = setup.wValueL;
+ } else
+ ok = false;
+ }
+ else if (GET_INTERFACE == r)
+ {
+ }
+ else if (SET_INTERFACE == r)
+ {
+ }
+ }
+ else
+ {
+ InitControl(setup.wLength); // Max length of transfer
+ ok = ClassInterfaceRequest(setup);
+ }
+
+ if (ok)
+ ClearIN();
+ else
+ {
+ Stall();
+ }
+}
+
+void USB_Flush(u8 ep)
+{
+ SetEP(ep);
+ if (FifoByteCount())
+ ReleaseTX();
+}
+
+// General interrupt
+ISR(USB_GEN_vect)
+{
+ u8 udint = UDINT;
+ UDINT = 0;
+
+ // End of Reset
+ if (udint & (1<<EORSTI))
+ {
+ InitEP(0,EP_TYPE_CONTROL,EP_SINGLE_64); // init ep0
+ _usbConfiguration = 0; // not configured yet
+ UEIENX = 1 << RXSTPE; // Enable interrupts for ep0
+ }
+
+ // Start of Frame - happens every millisecond so we use it for TX and RX LED one-shot timing, too
+ if (udint & (1<<SOFI))
+ {
+#ifdef CDC_ENABLED
+ USB_Flush(CDC_TX); // Send a tx frame if found
+ while (USB_Available(CDC_RX)) // Handle received bytes (if any)
+ Serial.accept();
+#endif
+
+ // check whether the one-shot period has elapsed. if so, turn off the LED
+ if (TxLEDPulse && !(--TxLEDPulse))
+ TXLED0;
+ if (RxLEDPulse && !(--RxLEDPulse))
+ RXLED0;
+ }
+}
+
+// VBUS or counting frames
+// Any frame counting?
+u8 USBConnected()
+{
+ u8 f = UDFNUML;
+ delay(3);
+ return f != UDFNUML;
+}
+
+//=======================================================================
+//=======================================================================
+
+USBDevice_ USBDevice;
+
+USBDevice_::USBDevice_()
+{
+}
+
+void USBDevice_::attach()
+{
+ _usbConfiguration = 0;
+ UHWCON = 0x01; // power internal reg
+ USBCON = (1<<USBE)|(1<<FRZCLK); // clock frozen, usb enabled
+ PLLCSR = 0x12; // Need 16 MHz xtal
+ while (!(PLLCSR & (1<<PLOCK))) // wait for lock pll
+ ;
+
+ // Some tests on specific versions of macosx (10.7.3), reported some
+ // strange behaviuors when the board is reset using the serial
+ // port touch at 1200 bps. This delay fixes this behaviour.
+ delay(1);
+
+ USBCON = ((1<<USBE)|(1<<OTGPADE)); // start USB clock
+ UDIEN = (1<<EORSTE)|(1<<SOFE); // Enable interrupts for EOR (End of Reset) and SOF (start of frame)
+ UDCON = 0; // enable attach resistor
+
+ TX_RX_LED_INIT;
+}
+
+void USBDevice_::detach()
+{
+}
+
+// Check for interrupts
+// TODO: VBUS detection
+bool USBDevice_::configured()
+{
+ return _usbConfiguration;
+}
+
+void USBDevice_::poll()
+{
+}
+
+#endif /* if defined(USBCON) */
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBCore.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBCore.h
new file mode 100644
index 000000000..8d1380689
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBCore.h
@@ -0,0 +1,303 @@
+
+// Copyright (c) 2010, Peter Barrett
+/*
+** Permission to use, copy, modify, and/or distribute this software for
+** any purpose with or without fee is hereby granted, provided that the
+** above copyright notice and this permission notice appear in all copies.
+**
+** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
+** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
+** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
+** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+** SOFTWARE.
+*/
+
+#ifndef __USBCORE_H__
+#define __USBCORE_H__
+
+// Standard requests
+#define GET_STATUS 0
+#define CLEAR_FEATURE 1
+#define SET_FEATURE 3
+#define SET_ADDRESS 5
+#define GET_DESCRIPTOR 6
+#define SET_DESCRIPTOR 7
+#define GET_CONFIGURATION 8
+#define SET_CONFIGURATION 9
+#define GET_INTERFACE 10
+#define SET_INTERFACE 11
+
+
+// bmRequestType
+#define REQUEST_HOSTTODEVICE 0x00
+#define REQUEST_DEVICETOHOST 0x80
+#define REQUEST_DIRECTION 0x80
+
+#define REQUEST_STANDARD 0x00
+#define REQUEST_CLASS 0x20
+#define REQUEST_VENDOR 0x40
+#define REQUEST_TYPE 0x60
+
+#define REQUEST_DEVICE 0x00
+#define REQUEST_INTERFACE 0x01
+#define REQUEST_ENDPOINT 0x02
+#define REQUEST_OTHER 0x03
+#define REQUEST_RECIPIENT 0x03
+
+#define REQUEST_DEVICETOHOST_CLASS_INTERFACE (REQUEST_DEVICETOHOST + REQUEST_CLASS + REQUEST_INTERFACE)
+#define REQUEST_HOSTTODEVICE_CLASS_INTERFACE (REQUEST_HOSTTODEVICE + REQUEST_CLASS + REQUEST_INTERFACE)
+
+// Class requests
+
+#define CDC_SET_LINE_CODING 0x20
+#define CDC_GET_LINE_CODING 0x21
+#define CDC_SET_CONTROL_LINE_STATE 0x22
+
+#define MSC_RESET 0xFF
+#define MSC_GET_MAX_LUN 0xFE
+
+#define HID_GET_REPORT 0x01
+#define HID_GET_IDLE 0x02
+#define HID_GET_PROTOCOL 0x03
+#define HID_SET_REPORT 0x09
+#define HID_SET_IDLE 0x0A
+#define HID_SET_PROTOCOL 0x0B
+
+// Descriptors
+
+#define USB_DEVICE_DESC_SIZE 18
+#define USB_CONFIGUARTION_DESC_SIZE 9
+#define USB_INTERFACE_DESC_SIZE 9
+#define USB_ENDPOINT_DESC_SIZE 7
+
+#define USB_DEVICE_DESCRIPTOR_TYPE 1
+#define USB_CONFIGURATION_DESCRIPTOR_TYPE 2
+#define USB_STRING_DESCRIPTOR_TYPE 3
+#define USB_INTERFACE_DESCRIPTOR_TYPE 4
+#define USB_ENDPOINT_DESCRIPTOR_TYPE 5
+
+#define USB_DEVICE_CLASS_COMMUNICATIONS 0x02
+#define USB_DEVICE_CLASS_HUMAN_INTERFACE 0x03
+#define USB_DEVICE_CLASS_STORAGE 0x08
+#define USB_DEVICE_CLASS_VENDOR_SPECIFIC 0xFF
+
+#define USB_CONFIG_POWERED_MASK 0x40
+#define USB_CONFIG_BUS_POWERED 0x80
+#define USB_CONFIG_SELF_POWERED 0xC0
+#define USB_CONFIG_REMOTE_WAKEUP 0x20
+
+// bMaxPower in Configuration Descriptor
+#define USB_CONFIG_POWER_MA(mA) ((mA)/2)
+
+// bEndpointAddress in Endpoint Descriptor
+#define USB_ENDPOINT_DIRECTION_MASK 0x80
+#define USB_ENDPOINT_OUT(addr) ((addr) | 0x00)
+#define USB_ENDPOINT_IN(addr) ((addr) | 0x80)
+
+#define USB_ENDPOINT_TYPE_MASK 0x03
+#define USB_ENDPOINT_TYPE_CONTROL 0x00
+#define USB_ENDPOINT_TYPE_ISOCHRONOUS 0x01
+#define USB_ENDPOINT_TYPE_BULK 0x02
+#define USB_ENDPOINT_TYPE_INTERRUPT 0x03
+
+#define TOBYTES(x) ((x) & 0xFF),(((x) >> 8) & 0xFF)
+
+#define CDC_V1_10 0x0110
+#define CDC_COMMUNICATION_INTERFACE_CLASS 0x02
+
+#define CDC_CALL_MANAGEMENT 0x01
+#define CDC_ABSTRACT_CONTROL_MODEL 0x02
+#define CDC_HEADER 0x00
+#define CDC_ABSTRACT_CONTROL_MANAGEMENT 0x02
+#define CDC_UNION 0x06
+#define CDC_CS_INTERFACE 0x24
+#define CDC_CS_ENDPOINT 0x25
+#define CDC_DATA_INTERFACE_CLASS 0x0A
+
+#define MSC_SUBCLASS_SCSI 0x06
+#define MSC_PROTOCOL_BULK_ONLY 0x50
+
+#define HID_HID_DESCRIPTOR_TYPE 0x21
+#define HID_REPORT_DESCRIPTOR_TYPE 0x22
+#define HID_PHYSICAL_DESCRIPTOR_TYPE 0x23
+
+
+// Device
+typedef struct {
+ u8 len; // 18
+ u8 dtype; // 1 USB_DEVICE_DESCRIPTOR_TYPE
+ u16 usbVersion; // 0x200
+ u8 deviceClass;
+ u8 deviceSubClass;
+ u8 deviceProtocol;
+ u8 packetSize0; // Packet 0
+ u16 idVendor;
+ u16 idProduct;
+ u16 deviceVersion; // 0x100
+ u8 iManufacturer;
+ u8 iProduct;
+ u8 iSerialNumber;
+ u8 bNumConfigurations;
+} DeviceDescriptor;
+
+// Config
+typedef struct {
+ u8 len; // 9
+ u8 dtype; // 2
+ u16 clen; // total length
+ u8 numInterfaces;
+ u8 config;
+ u8 iconfig;
+ u8 attributes;
+ u8 maxPower;
+} ConfigDescriptor;
+
+// String
+
+// Interface
+typedef struct
+{
+ u8 len; // 9
+ u8 dtype; // 4
+ u8 number;
+ u8 alternate;
+ u8 numEndpoints;
+ u8 interfaceClass;
+ u8 interfaceSubClass;
+ u8 protocol;
+ u8 iInterface;
+} InterfaceDescriptor;
+
+// Endpoint
+typedef struct
+{
+ u8 len; // 7
+ u8 dtype; // 5
+ u8 addr;
+ u8 attr;
+ u16 packetSize;
+ u8 interval;
+} EndpointDescriptor;
+
+// Interface Association Descriptor
+// Used to bind 2 interfaces together in CDC compostite device
+typedef struct
+{
+ u8 len; // 8
+ u8 dtype; // 11
+ u8 firstInterface;
+ u8 interfaceCount;
+ u8 functionClass;
+ u8 funtionSubClass;
+ u8 functionProtocol;
+ u8 iInterface;
+} IADDescriptor;
+
+// CDC CS interface descriptor
+typedef struct
+{
+ u8 len; // 5
+ u8 dtype; // 0x24
+ u8 subtype;
+ u8 d0;
+ u8 d1;
+} CDCCSInterfaceDescriptor;
+
+typedef struct
+{
+ u8 len; // 4
+ u8 dtype; // 0x24
+ u8 subtype;
+ u8 d0;
+} CDCCSInterfaceDescriptor4;
+
+typedef struct
+{
+ u8 len;
+ u8 dtype; // 0x24
+ u8 subtype; // 1
+ u8 bmCapabilities;
+ u8 bDataInterface;
+} CMFunctionalDescriptor;
+
+typedef struct
+{
+ u8 len;
+ u8 dtype; // 0x24
+ u8 subtype; // 1
+ u8 bmCapabilities;
+} ACMFunctionalDescriptor;
+
+typedef struct
+{
+ // IAD
+ IADDescriptor iad; // Only needed on compound device
+
+ // Control
+ InterfaceDescriptor cif; //
+ CDCCSInterfaceDescriptor header;
+ CMFunctionalDescriptor callManagement; // Call Management
+ ACMFunctionalDescriptor controlManagement; // ACM
+ CDCCSInterfaceDescriptor functionalDescriptor; // CDC_UNION
+ EndpointDescriptor cifin;
+
+ // Data
+ InterfaceDescriptor dif;
+ EndpointDescriptor in;
+ EndpointDescriptor out;
+} CDCDescriptor;
+
+typedef struct
+{
+ InterfaceDescriptor msc;
+ EndpointDescriptor in;
+ EndpointDescriptor out;
+} MSCDescriptor;
+
+typedef struct
+{
+ u8 len; // 9
+ u8 dtype; // 0x21
+ u8 addr;
+ u8 versionL; // 0x101
+ u8 versionH; // 0x101
+ u8 country;
+ u8 desctype; // 0x22 report
+ u8 descLenL;
+ u8 descLenH;
+} HIDDescDescriptor;
+
+typedef struct
+{
+ InterfaceDescriptor hid;
+ HIDDescDescriptor desc;
+ EndpointDescriptor in;
+} HIDDescriptor;
+
+
+#define D_DEVICE(_class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs) \
+ { 18, 1, 0x200, _class,_subClass,_proto,_packetSize0,_vid,_pid,_version,_im,_ip,_is,_configs }
+
+#define D_CONFIG(_totalLength,_interfaces) \
+ { 9, 2, _totalLength,_interfaces, 1, 0, USB_CONFIG_BUS_POWERED, USB_CONFIG_POWER_MA(500) }
+
+#define D_INTERFACE(_n,_numEndpoints,_class,_subClass,_protocol) \
+ { 9, 4, _n, 0, _numEndpoints, _class,_subClass, _protocol, 0 }
+
+#define D_ENDPOINT(_addr,_attr,_packetSize, _interval) \
+ { 7, 5, _addr,_attr,_packetSize, _interval }
+
+#define D_IAD(_firstInterface, _count, _class, _subClass, _protocol) \
+ { 8, 11, _firstInterface, _count, _class, _subClass, _protocol, 0 }
+
+#define D_HIDREPORT(_descriptorLength) \
+ { 9, 0x21, 0x1, 0x1, 0, 1, 0x22, _descriptorLength, 0 }
+
+#define D_CDCCS(_subtype,_d0,_d1) { 5, 0x24, _subtype, _d0, _d1 }
+#define D_CDCCS4(_subtype,_d0) { 4, 0x24, _subtype, _d0 }
+
+
+#endif \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBDesc.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBDesc.h
new file mode 100644
index 000000000..900713e0f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/USBDesc.h
@@ -0,0 +1,63 @@
+
+
+/* Copyright (c) 2011, Peter Barrett
+**
+** Permission to use, copy, modify, and/or distribute this software for
+** any purpose with or without fee is hereby granted, provided that the
+** above copyright notice and this permission notice appear in all copies.
+**
+** THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
+** WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
+** WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR
+** BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES
+** OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
+** WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
+** ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
+** SOFTWARE.
+*/
+
+#define CDC_ENABLED
+#define HID_ENABLED
+
+
+#ifdef CDC_ENABLED
+#define CDC_INTERFACE_COUNT 2
+#define CDC_ENPOINT_COUNT 3
+#else
+#define CDC_INTERFACE_COUNT 0
+#define CDC_ENPOINT_COUNT 0
+#endif
+
+#ifdef HID_ENABLED
+#define HID_INTERFACE_COUNT 1
+#define HID_ENPOINT_COUNT 1
+#else
+#define HID_INTERFACE_COUNT 0
+#define HID_ENPOINT_COUNT 0
+#endif
+
+#define CDC_ACM_INTERFACE 0 // CDC ACM
+#define CDC_DATA_INTERFACE 1 // CDC Data
+#define CDC_FIRST_ENDPOINT 1
+#define CDC_ENDPOINT_ACM (CDC_FIRST_ENDPOINT) // CDC First
+#define CDC_ENDPOINT_OUT (CDC_FIRST_ENDPOINT+1)
+#define CDC_ENDPOINT_IN (CDC_FIRST_ENDPOINT+2)
+
+#define HID_INTERFACE (CDC_ACM_INTERFACE + CDC_INTERFACE_COUNT) // HID Interface
+#define HID_FIRST_ENDPOINT (CDC_FIRST_ENDPOINT + CDC_ENPOINT_COUNT)
+#define HID_ENDPOINT_INT (HID_FIRST_ENDPOINT)
+
+#define INTERFACE_COUNT (MSC_INTERFACE + MSC_INTERFACE_COUNT)
+
+#ifdef CDC_ENABLED
+#define CDC_RX CDC_ENDPOINT_OUT
+#define CDC_TX CDC_ENDPOINT_IN
+#endif
+
+#ifdef HID_ENABLED
+#define HID_TX HID_ENDPOINT_INT
+#endif
+
+#define IMANUFACTURER 1
+#define IPRODUCT 2
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Udp.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Udp.h
new file mode 100644
index 000000000..dc5644b9d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/Udp.h
@@ -0,0 +1,88 @@
+/*
+ * Udp.cpp: Library to send/receive UDP packets.
+ *
+ * NOTE: UDP is fast, but has some important limitations (thanks to Warren Gray for mentioning these)
+ * 1) UDP does not guarantee the order in which assembled UDP packets are received. This
+ * might not happen often in practice, but in larger network topologies, a UDP
+ * packet can be received out of sequence.
+ * 2) UDP does not guard against lost packets - so packets *can* disappear without the sender being
+ * aware of it. Again, this may not be a concern in practice on small local networks.
+ * For more information, see http://www.cafeaulait.org/course/week12/35.html
+ *
+ * MIT License:
+ * Copyright (c) 2008 Bjoern Hartmann
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ *
+ * bjoern@cs.stanford.edu 12/30/2008
+ */
+
+#ifndef udp_h
+#define udp_h
+
+#include <Stream.h>
+#include <IPAddress.h>
+
+class UDP : public Stream {
+
+public:
+ virtual uint8_t begin(uint16_t) =0; // initialize, start listening on specified port. Returns 1 if successful, 0 if there are no sockets available to use
+ virtual void stop() =0; // Finish with the UDP socket
+
+ // Sending UDP packets
+
+ // Start building up a packet to send to the remote host specific in ip and port
+ // Returns 1 if successful, 0 if there was a problem with the supplied IP address or port
+ virtual int beginPacket(IPAddress ip, uint16_t port) =0;
+ // Start building up a packet to send to the remote host specific in host and port
+ // Returns 1 if successful, 0 if there was a problem resolving the hostname or port
+ virtual int beginPacket(const char *host, uint16_t port) =0;
+ // Finish off this packet and send it
+ // Returns 1 if the packet was sent successfully, 0 if there was an error
+ virtual int endPacket() =0;
+ // Write a single byte into the packet
+ virtual size_t write(uint8_t) =0;
+ // Write size bytes from buffer into the packet
+ virtual size_t write(const uint8_t *buffer, size_t size) =0;
+
+ // Start processing the next available incoming packet
+ // Returns the size of the packet in bytes, or 0 if no packets are available
+ virtual int parsePacket() =0;
+ // Number of bytes remaining in the current packet
+ virtual int available() =0;
+ // Read a single byte from the current packet
+ virtual int read() =0;
+ // Read up to len bytes from the current packet and place them into buffer
+ // Returns the number of bytes read, or 0 if none are available
+ virtual int read(unsigned char* buffer, size_t len) =0;
+ // Read up to len characters from the current packet and place them into buffer
+ // Returns the number of characters read, or 0 if none are available
+ virtual int read(char* buffer, size_t len) =0;
+ // Return the next byte from the current packet without moving on to the next byte
+ virtual int peek() =0;
+ virtual void flush() =0; // Finish reading the current packet
+
+ // Return the IP address of the host who sent the current incoming packet
+ virtual IPAddress remoteIP() =0;
+ // Return the port of the host who sent the current incoming packet
+ virtual uint16_t remotePort() =0;
+protected:
+ uint8_t* rawIPAddress(IPAddress& addr) { return addr.raw_address(); };
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WCharacter.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WCharacter.h
new file mode 100644
index 000000000..79733b50a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WCharacter.h
@@ -0,0 +1,168 @@
+/*
+ WCharacter.h - Character utility functions for Wiring & Arduino
+ Copyright (c) 2010 Hernando Barragan. All right reserved.
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#ifndef Character_h
+#define Character_h
+
+#include <ctype.h>
+
+// WCharacter.h prototypes
+inline boolean isAlphaNumeric(int c) __attribute__((always_inline));
+inline boolean isAlpha(int c) __attribute__((always_inline));
+inline boolean isAscii(int c) __attribute__((always_inline));
+inline boolean isWhitespace(int c) __attribute__((always_inline));
+inline boolean isControl(int c) __attribute__((always_inline));
+inline boolean isDigit(int c) __attribute__((always_inline));
+inline boolean isGraph(int c) __attribute__((always_inline));
+inline boolean isLowerCase(int c) __attribute__((always_inline));
+inline boolean isPrintable(int c) __attribute__((always_inline));
+inline boolean isPunct(int c) __attribute__((always_inline));
+inline boolean isSpace(int c) __attribute__((always_inline));
+inline boolean isUpperCase(int c) __attribute__((always_inline));
+inline boolean isHexadecimalDigit(int c) __attribute__((always_inline));
+inline int toAscii(int c) __attribute__((always_inline));
+inline int toLowerCase(int c) __attribute__((always_inline));
+inline int toUpperCase(int c)__attribute__((always_inline));
+
+
+// Checks for an alphanumeric character.
+// It is equivalent to (isalpha(c) || isdigit(c)).
+inline boolean isAlphaNumeric(int c)
+{
+ return ( isalnum(c) == 0 ? false : true);
+}
+
+
+// Checks for an alphabetic character.
+// It is equivalent to (isupper(c) || islower(c)).
+inline boolean isAlpha(int c)
+{
+ return ( isalpha(c) == 0 ? false : true);
+}
+
+
+// Checks whether c is a 7-bit unsigned char value
+// that fits into the ASCII character set.
+inline boolean isAscii(int c)
+{
+ return ( isascii (c) == 0 ? false : true);
+}
+
+
+// Checks for a blank character, that is, a space or a tab.
+inline boolean isWhitespace(int c)
+{
+ return ( isblank (c) == 0 ? false : true);
+}
+
+
+// Checks for a control character.
+inline boolean isControl(int c)
+{
+ return ( iscntrl (c) == 0 ? false : true);
+}
+
+
+// Checks for a digit (0 through 9).
+inline boolean isDigit(int c)
+{
+ return ( isdigit (c) == 0 ? false : true);
+}
+
+
+// Checks for any printable character except space.
+inline boolean isGraph(int c)
+{
+ return ( isgraph (c) == 0 ? false : true);
+}
+
+
+// Checks for a lower-case character.
+inline boolean isLowerCase(int c)
+{
+ return (islower (c) == 0 ? false : true);
+}
+
+
+// Checks for any printable character including space.
+inline boolean isPrintable(int c)
+{
+ return ( isprint (c) == 0 ? false : true);
+}
+
+
+// Checks for any printable character which is not a space
+// or an alphanumeric character.
+inline boolean isPunct(int c)
+{
+ return ( ispunct (c) == 0 ? false : true);
+}
+
+
+// Checks for white-space characters. For the avr-libc library,
+// these are: space, formfeed ('\f'), newline ('\n'), carriage
+// return ('\r'), horizontal tab ('\t'), and vertical tab ('\v').
+inline boolean isSpace(int c)
+{
+ return ( isspace (c) == 0 ? false : true);
+}
+
+
+// Checks for an uppercase letter.
+inline boolean isUpperCase(int c)
+{
+ return ( isupper (c) == 0 ? false : true);
+}
+
+
+// Checks for a hexadecimal digits, i.e. one of 0 1 2 3 4 5 6 7
+// 8 9 a b c d e f A B C D E F.
+inline boolean isHexadecimalDigit(int c)
+{
+ return ( isxdigit (c) == 0 ? false : true);
+}
+
+
+// Converts c to a 7-bit unsigned char value that fits into the
+// ASCII character set, by clearing the high-order bits.
+inline int toAscii(int c)
+{
+ return toascii (c);
+}
+
+
+// Warning:
+// Many people will be unhappy if you use this function.
+// This function will convert accented letters into random
+// characters.
+
+// Converts the letter c to lower case, if possible.
+inline int toLowerCase(int c)
+{
+ return tolower (c);
+}
+
+
+// Converts the letter c to upper case, if possible.
+inline int toUpperCase(int c)
+{
+ return toupper (c);
+}
+
+#endif \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WInterrupts.c b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WInterrupts.c
new file mode 100644
index 000000000..8f3ec847f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WInterrupts.c
@@ -0,0 +1,298 @@
+/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Wiring project - http://wiring.uniandes.edu.co
+
+ Copyright (c) 2004-05 Hernando Barragan
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ Modified 24 November 2006 by David A. Mellis
+ Modified 1 August 2010 by Mark Sproul
+*/
+
+#include <inttypes.h>
+#include <avr/io.h>
+#include <avr/interrupt.h>
+#include <avr/pgmspace.h>
+#include <stdio.h>
+
+#include "wiring_private.h"
+
+static volatile voidFuncPtr intFunc[EXTERNAL_NUM_INTERRUPTS];
+// volatile static voidFuncPtr twiIntFunc;
+
+void attachInterrupt(uint8_t interruptNum, void (*userFunc)(void), int mode) {
+ if(interruptNum < EXTERNAL_NUM_INTERRUPTS) {
+ intFunc[interruptNum] = userFunc;
+
+ // Configure the interrupt mode (trigger on low input, any change, rising
+ // edge, or falling edge). The mode constants were chosen to correspond
+ // to the configuration bits in the hardware register, so we simply shift
+ // the mode into place.
+
+ // Enable the interrupt.
+
+ switch (interruptNum) {
+#if defined(__AVR_ATmega32U4__)
+ // I hate doing this, but the register assignment differs between the 1280/2560
+ // and the 32U4. Since avrlib defines registers PCMSK1 and PCMSK2 that aren't
+ // even present on the 32U4 this is the only way to distinguish between them.
+ case 0:
+ EICRA = (EICRA & ~((1<<ISC00) | (1<<ISC01))) | (mode << ISC00);
+ EIMSK |= (1<<INT0);
+ break;
+ case 1:
+ EICRA = (EICRA & ~((1<<ISC10) | (1<<ISC11))) | (mode << ISC10);
+ EIMSK |= (1<<INT1);
+ break;
+#elif defined(EICRA) && defined(EICRB) && defined(EIMSK)
+ case 2:
+ EICRA = (EICRA & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
+ EIMSK |= (1 << INT0);
+ break;
+ case 3:
+ EICRA = (EICRA & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
+ EIMSK |= (1 << INT1);
+ break;
+ case 4:
+ EICRA = (EICRA & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20);
+ EIMSK |= (1 << INT2);
+ break;
+ case 5:
+ EICRA = (EICRA & ~((1 << ISC30) | (1 << ISC31))) | (mode << ISC30);
+ EIMSK |= (1 << INT3);
+ break;
+ case 0:
+ EICRB = (EICRB & ~((1 << ISC40) | (1 << ISC41))) | (mode << ISC40);
+ EIMSK |= (1 << INT4);
+ break;
+ case 1:
+ EICRB = (EICRB & ~((1 << ISC50) | (1 << ISC51))) | (mode << ISC50);
+ EIMSK |= (1 << INT5);
+ break;
+ case 6:
+ EICRB = (EICRB & ~((1 << ISC60) | (1 << ISC61))) | (mode << ISC60);
+ EIMSK |= (1 << INT6);
+ break;
+ case 7:
+ EICRB = (EICRB & ~((1 << ISC70) | (1 << ISC71))) | (mode << ISC70);
+ EIMSK |= (1 << INT7);
+ break;
+#else
+ case 0:
+ #if defined(EICRA) && defined(ISC00) && defined(EIMSK)
+ EICRA = (EICRA & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
+ EIMSK |= (1 << INT0);
+ #elif defined(MCUCR) && defined(ISC00) && defined(GICR)
+ MCUCR = (MCUCR & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
+ GICR |= (1 << INT0);
+ #elif defined(MCUCR) && defined(ISC00) && defined(GIMSK)
+ MCUCR = (MCUCR & ~((1 << ISC00) | (1 << ISC01))) | (mode << ISC00);
+ GIMSK |= (1 << INT0);
+ #else
+ #error attachInterrupt not finished for this CPU (case 0)
+ #endif
+ break;
+
+ case 1:
+ #if defined(EICRA) && defined(ISC10) && defined(ISC11) && defined(EIMSK)
+ EICRA = (EICRA & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
+ EIMSK |= (1 << INT1);
+ #elif defined(MCUCR) && defined(ISC10) && defined(ISC11) && defined(GICR)
+ MCUCR = (MCUCR & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
+ GICR |= (1 << INT1);
+ #elif defined(MCUCR) && defined(ISC10) && defined(GIMSK) && defined(GIMSK)
+ MCUCR = (MCUCR & ~((1 << ISC10) | (1 << ISC11))) | (mode << ISC10);
+ GIMSK |= (1 << INT1);
+ #else
+ #warning attachInterrupt may need some more work for this cpu (case 1)
+ #endif
+ break;
+
+ case 2:
+ #if defined(EICRA) && defined(ISC20) && defined(ISC21) && defined(EIMSK)
+ EICRA = (EICRA & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20);
+ EIMSK |= (1 << INT2);
+ #elif defined(MCUCR) && defined(ISC20) && defined(ISC21) && defined(GICR)
+ MCUCR = (MCUCR & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20);
+ GICR |= (1 << INT2);
+ #elif defined(MCUCR) && defined(ISC20) && defined(GIMSK) && defined(GIMSK)
+ MCUCR = (MCUCR & ~((1 << ISC20) | (1 << ISC21))) | (mode << ISC20);
+ GIMSK |= (1 << INT2);
+ #endif
+ break;
+#endif
+ }
+ }
+}
+
+void detachInterrupt(uint8_t interruptNum) {
+ if(interruptNum < EXTERNAL_NUM_INTERRUPTS) {
+ // Disable the interrupt. (We can't assume that interruptNum is equal
+ // to the number of the EIMSK bit to clear, as this isn't true on the
+ // ATmega8. There, INT0 is 6 and INT1 is 7.)
+ switch (interruptNum) {
+#if defined(__AVR_ATmega32U4__)
+ case 0:
+ EIMSK &= ~(1<<INT0);
+ break;
+ case 1:
+ EIMSK &= ~(1<<INT1);
+ break;
+#elif defined(EICRA) && defined(EICRB) && defined(EIMSK)
+ case 2:
+ EIMSK &= ~(1 << INT0);
+ break;
+ case 3:
+ EIMSK &= ~(1 << INT1);
+ break;
+ case 4:
+ EIMSK &= ~(1 << INT2);
+ break;
+ case 5:
+ EIMSK &= ~(1 << INT3);
+ break;
+ case 0:
+ EIMSK &= ~(1 << INT4);
+ break;
+ case 1:
+ EIMSK &= ~(1 << INT5);
+ break;
+ case 6:
+ EIMSK &= ~(1 << INT6);
+ break;
+ case 7:
+ EIMSK &= ~(1 << INT7);
+ break;
+#else
+ case 0:
+ #if defined(EIMSK) && defined(INT0)
+ EIMSK &= ~(1 << INT0);
+ #elif defined(GICR) && defined(ISC00)
+ GICR &= ~(1 << INT0); // atmega32
+ #elif defined(GIMSK) && defined(INT0)
+ GIMSK &= ~(1 << INT0);
+ #else
+ #error detachInterrupt not finished for this cpu
+ #endif
+ break;
+
+ case 1:
+ #if defined(EIMSK) && defined(INT1)
+ EIMSK &= ~(1 << INT1);
+ #elif defined(GICR) && defined(INT1)
+ GICR &= ~(1 << INT1); // atmega32
+ #elif defined(GIMSK) && defined(INT1)
+ GIMSK &= ~(1 << INT1);
+ #else
+ #warning detachInterrupt may need some more work for this cpu (case 1)
+ #endif
+ break;
+#endif
+ }
+
+ intFunc[interruptNum] = 0;
+ }
+}
+
+/*
+void attachInterruptTwi(void (*userFunc)(void) ) {
+ twiIntFunc = userFunc;
+}
+*/
+
+#if defined(__AVR_ATmega32U4__)
+SIGNAL(INT0_vect) {
+ if(intFunc[EXTERNAL_INT_0])
+ intFunc[EXTERNAL_INT_0]();
+}
+
+SIGNAL(INT1_vect) {
+ if(intFunc[EXTERNAL_INT_1])
+ intFunc[EXTERNAL_INT_1]();
+}
+
+#elif defined(EICRA) && defined(EICRB)
+
+SIGNAL(INT0_vect) {
+ if(intFunc[EXTERNAL_INT_2])
+ intFunc[EXTERNAL_INT_2]();
+}
+
+SIGNAL(INT1_vect) {
+ if(intFunc[EXTERNAL_INT_3])
+ intFunc[EXTERNAL_INT_3]();
+}
+
+SIGNAL(INT2_vect) {
+ if(intFunc[EXTERNAL_INT_4])
+ intFunc[EXTERNAL_INT_4]();
+}
+
+SIGNAL(INT3_vect) {
+ if(intFunc[EXTERNAL_INT_5])
+ intFunc[EXTERNAL_INT_5]();
+}
+
+SIGNAL(INT4_vect) {
+ if(intFunc[EXTERNAL_INT_0])
+ intFunc[EXTERNAL_INT_0]();
+}
+
+SIGNAL(INT5_vect) {
+ if(intFunc[EXTERNAL_INT_1])
+ intFunc[EXTERNAL_INT_1]();
+}
+
+SIGNAL(INT6_vect) {
+ if(intFunc[EXTERNAL_INT_6])
+ intFunc[EXTERNAL_INT_6]();
+}
+
+SIGNAL(INT7_vect) {
+ if(intFunc[EXTERNAL_INT_7])
+ intFunc[EXTERNAL_INT_7]();
+}
+
+#else
+
+SIGNAL(INT0_vect) {
+ if(intFunc[EXTERNAL_INT_0])
+ intFunc[EXTERNAL_INT_0]();
+}
+
+SIGNAL(INT1_vect) {
+ if(intFunc[EXTERNAL_INT_1])
+ intFunc[EXTERNAL_INT_1]();
+}
+
+#if defined(EICRA) && defined(ISC20)
+SIGNAL(INT2_vect) {
+ if(intFunc[EXTERNAL_INT_2])
+ intFunc[EXTERNAL_INT_2]();
+}
+#endif
+
+#endif
+
+/*
+SIGNAL(SIG_2WIRE_SERIAL) {
+ if(twiIntFunc)
+ twiIntFunc();
+}
+*/
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WMath.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WMath.cpp
new file mode 100644
index 000000000..2120c4cc1
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WMath.cpp
@@ -0,0 +1,60 @@
+/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */
+
+/*
+ Part of the Wiring project - http://wiring.org.co
+ Copyright (c) 2004-06 Hernando Barragan
+ Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id$
+*/
+
+extern "C" {
+ #include "stdlib.h"
+}
+
+void randomSeed(unsigned int seed)
+{
+ if (seed != 0) {
+ srandom(seed);
+ }
+}
+
+long random(long howbig)
+{
+ if (howbig == 0) {
+ return 0;
+ }
+ return random() % howbig;
+}
+
+long random(long howsmall, long howbig)
+{
+ if (howsmall >= howbig) {
+ return howsmall;
+ }
+ long diff = howbig - howsmall;
+ return random(diff) + howsmall;
+}
+
+long map(long x, long in_min, long in_max, long out_min, long out_max)
+{
+ return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
+}
+
+unsigned int makeWord(unsigned int w) { return w; }
+unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; } \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WString.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WString.cpp
new file mode 100644
index 000000000..c6839fc0d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WString.cpp
@@ -0,0 +1,645 @@
+/*
+ WString.cpp - String library for Wiring & Arduino
+ ...mostly rewritten by Paul Stoffregen...
+ Copyright (c) 2009-10 Hernando Barragan. All rights reserved.
+ Copyright 2011, Paul Stoffregen, paul@pjrc.com
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+#include "WString.h"
+
+
+/*********************************************/
+/* Constructors */
+/*********************************************/
+
+String::String(const char *cstr)
+{
+ init();
+ if (cstr) copy(cstr, strlen(cstr));
+}
+
+String::String(const String &value)
+{
+ init();
+ *this = value;
+}
+
+#ifdef __GXX_EXPERIMENTAL_CXX0X__
+String::String(String &&rval)
+{
+ init();
+ move(rval);
+}
+String::String(StringSumHelper &&rval)
+{
+ init();
+ move(rval);
+}
+#endif
+
+String::String(char c)
+{
+ init();
+ char buf[2];
+ buf[0] = c;
+ buf[1] = 0;
+ *this = buf;
+}
+
+String::String(unsigned char value, unsigned char base)
+{
+ init();
+ char buf[9];
+ utoa(value, buf, base);
+ *this = buf;
+}
+
+String::String(int value, unsigned char base)
+{
+ init();
+ char buf[18];
+ itoa(value, buf, base);
+ *this = buf;
+}
+
+String::String(unsigned int value, unsigned char base)
+{
+ init();
+ char buf[17];
+ utoa(value, buf, base);
+ *this = buf;
+}
+
+String::String(long value, unsigned char base)
+{
+ init();
+ char buf[34];
+ ltoa(value, buf, base);
+ *this = buf;
+}
+
+String::String(unsigned long value, unsigned char base)
+{
+ init();
+ char buf[33];
+ ultoa(value, buf, base);
+ *this = buf;
+}
+
+String::~String()
+{
+ free(buffer);
+}
+
+/*********************************************/
+/* Memory Management */
+/*********************************************/
+
+inline void String::init(void)
+{
+ buffer = NULL;
+ capacity = 0;
+ len = 0;
+ flags = 0;
+}
+
+void String::invalidate(void)
+{
+ if (buffer) free(buffer);
+ buffer = NULL;
+ capacity = len = 0;
+}
+
+unsigned char String::reserve(unsigned int size)
+{
+ if (buffer && capacity >= size) return 1;
+ if (changeBuffer(size)) {
+ if (len == 0) buffer[0] = 0;
+ return 1;
+ }
+ return 0;
+}
+
+unsigned char String::changeBuffer(unsigned int maxStrLen)
+{
+ char *newbuffer = (char *)realloc(buffer, maxStrLen + 1);
+ if (newbuffer) {
+ buffer = newbuffer;
+ capacity = maxStrLen;
+ return 1;
+ }
+ return 0;
+}
+
+/*********************************************/
+/* Copy and Move */
+/*********************************************/
+
+String & String::copy(const char *cstr, unsigned int length)
+{
+ if (!reserve(length)) {
+ invalidate();
+ return *this;
+ }
+ len = length;
+ strcpy(buffer, cstr);
+ return *this;
+}
+
+#ifdef __GXX_EXPERIMENTAL_CXX0X__
+void String::move(String &rhs)
+{
+ if (buffer) {
+ if (capacity >= rhs.len) {
+ strcpy(buffer, rhs.buffer);
+ len = rhs.len;
+ rhs.len = 0;
+ return;
+ } else {
+ free(buffer);
+ }
+ }
+ buffer = rhs.buffer;
+ capacity = rhs.capacity;
+ len = rhs.len;
+ rhs.buffer = NULL;
+ rhs.capacity = 0;
+ rhs.len = 0;
+}
+#endif
+
+String & String::operator = (const String &rhs)
+{
+ if (this == &rhs) return *this;
+
+ if (rhs.buffer) copy(rhs.buffer, rhs.len);
+ else invalidate();
+
+ return *this;
+}
+
+#ifdef __GXX_EXPERIMENTAL_CXX0X__
+String & String::operator = (String &&rval)
+{
+ if (this != &rval) move(rval);
+ return *this;
+}
+
+String & String::operator = (StringSumHelper &&rval)
+{
+ if (this != &rval) move(rval);
+ return *this;
+}
+#endif
+
+String & String::operator = (const char *cstr)
+{
+ if (cstr) copy(cstr, strlen(cstr));
+ else invalidate();
+
+ return *this;
+}
+
+/*********************************************/
+/* concat */
+/*********************************************/
+
+unsigned char String::concat(const String &s)
+{
+ return concat(s.buffer, s.len);
+}
+
+unsigned char String::concat(const char *cstr, unsigned int length)
+{
+ unsigned int newlen = len + length;
+ if (!cstr) return 0;
+ if (length == 0) return 1;
+ if (!reserve(newlen)) return 0;
+ strcpy(buffer + len, cstr);
+ len = newlen;
+ return 1;
+}
+
+unsigned char String::concat(const char *cstr)
+{
+ if (!cstr) return 0;
+ return concat(cstr, strlen(cstr));
+}
+
+unsigned char String::concat(char c)
+{
+ char buf[2];
+ buf[0] = c;
+ buf[1] = 0;
+ return concat(buf, 1);
+}
+
+unsigned char String::concat(unsigned char num)
+{
+ char buf[4];
+ itoa(num, buf, 10);
+ return concat(buf, strlen(buf));
+}
+
+unsigned char String::concat(int num)
+{
+ char buf[7];
+ itoa(num, buf, 10);
+ return concat(buf, strlen(buf));
+}
+
+unsigned char String::concat(unsigned int num)
+{
+ char buf[6];
+ utoa(num, buf, 10);
+ return concat(buf, strlen(buf));
+}
+
+unsigned char String::concat(long num)
+{
+ char buf[12];
+ ltoa(num, buf, 10);
+ return concat(buf, strlen(buf));
+}
+
+unsigned char String::concat(unsigned long num)
+{
+ char buf[11];
+ ultoa(num, buf, 10);
+ return concat(buf, strlen(buf));
+}
+
+/*********************************************/
+/* Concatenate */
+/*********************************************/
+
+StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs)
+{
+ StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
+ if (!a.concat(rhs.buffer, rhs.len)) a.invalidate();
+ return a;
+}
+
+StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr)
+{
+ StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
+ if (!cstr || !a.concat(cstr, strlen(cstr))) a.invalidate();
+ return a;
+}
+
+StringSumHelper & operator + (const StringSumHelper &lhs, char c)
+{
+ StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
+ if (!a.concat(c)) a.invalidate();
+ return a;
+}
+
+StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num)
+{
+ StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
+ if (!a.concat(num)) a.invalidate();
+ return a;
+}
+
+StringSumHelper & operator + (const StringSumHelper &lhs, int num)
+{
+ StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
+ if (!a.concat(num)) a.invalidate();
+ return a;
+}
+
+StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num)
+{
+ StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
+ if (!a.concat(num)) a.invalidate();
+ return a;
+}
+
+StringSumHelper & operator + (const StringSumHelper &lhs, long num)
+{
+ StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
+ if (!a.concat(num)) a.invalidate();
+ return a;
+}
+
+StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num)
+{
+ StringSumHelper &a = const_cast<StringSumHelper&>(lhs);
+ if (!a.concat(num)) a.invalidate();
+ return a;
+}
+
+/*********************************************/
+/* Comparison */
+/*********************************************/
+
+int String::compareTo(const String &s) const
+{
+ if (!buffer || !s.buffer) {
+ if (s.buffer && s.len > 0) return 0 - *(unsigned char *)s.buffer;
+ if (buffer && len > 0) return *(unsigned char *)buffer;
+ return 0;
+ }
+ return strcmp(buffer, s.buffer);
+}
+
+unsigned char String::equals(const String &s2) const
+{
+ return (len == s2.len && compareTo(s2) == 0);
+}
+
+unsigned char String::equals(const char *cstr) const
+{
+ if (len == 0) return (cstr == NULL || *cstr == 0);
+ if (cstr == NULL) return buffer[0] == 0;
+ return strcmp(buffer, cstr) == 0;
+}
+
+unsigned char String::operator<(const String &rhs) const
+{
+ return compareTo(rhs) < 0;
+}
+
+unsigned char String::operator>(const String &rhs) const
+{
+ return compareTo(rhs) > 0;
+}
+
+unsigned char String::operator<=(const String &rhs) const
+{
+ return compareTo(rhs) <= 0;
+}
+
+unsigned char String::operator>=(const String &rhs) const
+{
+ return compareTo(rhs) >= 0;
+}
+
+unsigned char String::equalsIgnoreCase( const String &s2 ) const
+{
+ if (this == &s2) return 1;
+ if (len != s2.len) return 0;
+ if (len == 0) return 1;
+ const char *p1 = buffer;
+ const char *p2 = s2.buffer;
+ while (*p1) {
+ if (tolower(*p1++) != tolower(*p2++)) return 0;
+ }
+ return 1;
+}
+
+unsigned char String::startsWith( const String &s2 ) const
+{
+ if (len < s2.len) return 0;
+ return startsWith(s2, 0);
+}
+
+unsigned char String::startsWith( const String &s2, unsigned int offset ) const
+{
+ if (offset > len - s2.len || !buffer || !s2.buffer) return 0;
+ return strncmp( &buffer[offset], s2.buffer, s2.len ) == 0;
+}
+
+unsigned char String::endsWith( const String &s2 ) const
+{
+ if ( len < s2.len || !buffer || !s2.buffer) return 0;
+ return strcmp(&buffer[len - s2.len], s2.buffer) == 0;
+}
+
+/*********************************************/
+/* Character Access */
+/*********************************************/
+
+char String::charAt(unsigned int loc) const
+{
+ return operator[](loc);
+}
+
+void String::setCharAt(unsigned int loc, char c)
+{
+ if (loc < len) buffer[loc] = c;
+}
+
+char & String::operator[](unsigned int index)
+{
+ static char dummy_writable_char;
+ if (index >= len || !buffer) {
+ dummy_writable_char = 0;
+ return dummy_writable_char;
+ }
+ return buffer[index];
+}
+
+char String::operator[]( unsigned int index ) const
+{
+ if (index >= len || !buffer) return 0;
+ return buffer[index];
+}
+
+void String::getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index) const
+{
+ if (!bufsize || !buf) return;
+ if (index >= len) {
+ buf[0] = 0;
+ return;
+ }
+ unsigned int n = bufsize - 1;
+ if (n > len - index) n = len - index;
+ strncpy((char *)buf, buffer + index, n);
+ buf[n] = 0;
+}
+
+/*********************************************/
+/* Search */
+/*********************************************/
+
+int String::indexOf(char c) const
+{
+ return indexOf(c, 0);
+}
+
+int String::indexOf( char ch, unsigned int fromIndex ) const
+{
+ if (fromIndex >= len) return -1;
+ const char* temp = strchr(buffer + fromIndex, ch);
+ if (temp == NULL) return -1;
+ return temp - buffer;
+}
+
+int String::indexOf(const String &s2) const
+{
+ return indexOf(s2, 0);
+}
+
+int String::indexOf(const String &s2, unsigned int fromIndex) const
+{
+ if (fromIndex >= len) return -1;
+ const char *found = strstr(buffer + fromIndex, s2.buffer);
+ if (found == NULL) return -1;
+ return found - buffer;
+}
+
+int String::lastIndexOf( char theChar ) const
+{
+ return lastIndexOf(theChar, len - 1);
+}
+
+int String::lastIndexOf(char ch, unsigned int fromIndex) const
+{
+ if (fromIndex >= len) return -1;
+ char tempchar = buffer[fromIndex + 1];
+ buffer[fromIndex + 1] = '\0';
+ char* temp = strrchr( buffer, ch );
+ buffer[fromIndex + 1] = tempchar;
+ if (temp == NULL) return -1;
+ return temp - buffer;
+}
+
+int String::lastIndexOf(const String &s2) const
+{
+ return lastIndexOf(s2, len - s2.len);
+}
+
+int String::lastIndexOf(const String &s2, unsigned int fromIndex) const
+{
+ if (s2.len == 0 || len == 0 || s2.len > len) return -1;
+ if (fromIndex >= len) fromIndex = len - 1;
+ int found = -1;
+ for (char *p = buffer; p <= buffer + fromIndex; p++) {
+ p = strstr(p, s2.buffer);
+ if (!p) break;
+ if ((unsigned int)(p - buffer) <= fromIndex) found = p - buffer;
+ }
+ return found;
+}
+
+String String::substring( unsigned int left ) const
+{
+ return substring(left, len);
+}
+
+String String::substring(unsigned int left, unsigned int right) const
+{
+ if (left > right) {
+ unsigned int temp = right;
+ right = left;
+ left = temp;
+ }
+ String out;
+ if (left > len) return out;
+ if (right > len) right = len;
+ char temp = buffer[right]; // save the replaced character
+ buffer[right] = '\0';
+ out = buffer + left; // pointer arithmetic
+ buffer[right] = temp; //restore character
+ return out;
+}
+
+/*********************************************/
+/* Modification */
+/*********************************************/
+
+void String::replace(char find, char replace)
+{
+ if (!buffer) return;
+ for (char *p = buffer; *p; p++) {
+ if (*p == find) *p = replace;
+ }
+}
+
+void String::replace(const String& find, const String& replace)
+{
+ if (len == 0 || find.len == 0) return;
+ int diff = replace.len - find.len;
+ char *readFrom = buffer;
+ char *foundAt;
+ if (diff == 0) {
+ while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
+ memcpy(foundAt, replace.buffer, replace.len);
+ readFrom = foundAt + replace.len;
+ }
+ } else if (diff < 0) {
+ char *writeTo = buffer;
+ while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
+ unsigned int n = foundAt - readFrom;
+ memcpy(writeTo, readFrom, n);
+ writeTo += n;
+ memcpy(writeTo, replace.buffer, replace.len);
+ writeTo += replace.len;
+ readFrom = foundAt + find.len;
+ len += diff;
+ }
+ strcpy(writeTo, readFrom);
+ } else {
+ unsigned int size = len; // compute size needed for result
+ while ((foundAt = strstr(readFrom, find.buffer)) != NULL) {
+ readFrom = foundAt + find.len;
+ size += diff;
+ }
+ if (size == len) return;
+ if (size > capacity && !changeBuffer(size)) return; // XXX: tell user!
+ int index = len - 1;
+ while (index >= 0 && (index = lastIndexOf(find, index)) >= 0) {
+ readFrom = buffer + index + find.len;
+ memmove(readFrom + diff, readFrom, len - (readFrom - buffer));
+ len += diff;
+ buffer[len] = 0;
+ memcpy(buffer + index, replace.buffer, replace.len);
+ index--;
+ }
+ }
+}
+
+void String::toLowerCase(void)
+{
+ if (!buffer) return;
+ for (char *p = buffer; *p; p++) {
+ *p = tolower(*p);
+ }
+}
+
+void String::toUpperCase(void)
+{
+ if (!buffer) return;
+ for (char *p = buffer; *p; p++) {
+ *p = toupper(*p);
+ }
+}
+
+void String::trim(void)
+{
+ if (!buffer || len == 0) return;
+ char *begin = buffer;
+ while (isspace(*begin)) begin++;
+ char *end = buffer + len - 1;
+ while (isspace(*end) && end >= begin) end--;
+ len = end + 1 - begin;
+ if (begin > buffer) memcpy(buffer, begin, len);
+ buffer[len] = 0;
+}
+
+/*********************************************/
+/* Parsing / Conversion */
+/*********************************************/
+
+long String::toInt(void) const
+{
+ if (buffer) return atol(buffer);
+ return 0;
+}
+
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WString.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WString.h
new file mode 100644
index 000000000..947325e5f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/WString.h
@@ -0,0 +1,205 @@
+/*
+ WString.h - String library for Wiring & Arduino
+ ...mostly rewritten by Paul Stoffregen...
+ Copyright (c) 2009-10 Hernando Barragan. All right reserved.
+ Copyright 2011, Paul Stoffregen, paul@pjrc.com
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+#ifndef String_class_h
+#define String_class_h
+#ifdef __cplusplus
+
+#include <stdlib.h>
+#include <string.h>
+#include <ctype.h>
+#include <avr/pgmspace.h>
+
+// When compiling programs with this class, the following gcc parameters
+// dramatically increase performance and memory (RAM) efficiency, typically
+// with little or no increase in code size.
+// -felide-constructors
+// -std=c++0x
+
+class __FlashStringHelper;
+#define F(string_literal) (reinterpret_cast<const __FlashStringHelper *>(PSTR(string_literal)))
+
+// An inherited class for holding the result of a concatenation. These
+// result objects are assumed to be writable by subsequent concatenations.
+class StringSumHelper;
+
+// The string class
+class String
+{
+ // use a function pointer to allow for "if (s)" without the
+ // complications of an operator bool(). for more information, see:
+ // http://www.artima.com/cppsource/safebool.html
+ typedef void (String::*StringIfHelperType)() const;
+ void StringIfHelper() const {}
+
+public:
+ // constructors
+ // creates a copy of the initial value.
+ // if the initial value is null or invalid, or if memory allocation
+ // fails, the string will be marked as invalid (i.e. "if (s)" will
+ // be false).
+ String(const char *cstr = "");
+ String(const String &str);
+ #ifdef __GXX_EXPERIMENTAL_CXX0X__
+ String(String &&rval);
+ String(StringSumHelper &&rval);
+ #endif
+ explicit String(char c);
+ explicit String(unsigned char, unsigned char base=10);
+ explicit String(int, unsigned char base=10);
+ explicit String(unsigned int, unsigned char base=10);
+ explicit String(long, unsigned char base=10);
+ explicit String(unsigned long, unsigned char base=10);
+ ~String(void);
+
+ // memory management
+ // return true on success, false on failure (in which case, the string
+ // is left unchanged). reserve(0), if successful, will validate an
+ // invalid string (i.e., "if (s)" will be true afterwards)
+ unsigned char reserve(unsigned int size);
+ inline unsigned int length(void) const {return len;}
+
+ // creates a copy of the assigned value. if the value is null or
+ // invalid, or if the memory allocation fails, the string will be
+ // marked as invalid ("if (s)" will be false).
+ String & operator = (const String &rhs);
+ String & operator = (const char *cstr);
+ #ifdef __GXX_EXPERIMENTAL_CXX0X__
+ String & operator = (String &&rval);
+ String & operator = (StringSumHelper &&rval);
+ #endif
+
+ // concatenate (works w/ built-in types)
+
+ // returns true on success, false on failure (in which case, the string
+ // is left unchanged). if the argument is null or invalid, the
+ // concatenation is considered unsucessful.
+ unsigned char concat(const String &str);
+ unsigned char concat(const char *cstr);
+ unsigned char concat(char c);
+ unsigned char concat(unsigned char c);
+ unsigned char concat(int num);
+ unsigned char concat(unsigned int num);
+ unsigned char concat(long num);
+ unsigned char concat(unsigned long num);
+
+ // if there's not enough memory for the concatenated value, the string
+ // will be left unchanged (but this isn't signalled in any way)
+ String & operator += (const String &rhs) {concat(rhs); return (*this);}
+ String & operator += (const char *cstr) {concat(cstr); return (*this);}
+ String & operator += (char c) {concat(c); return (*this);}
+ String & operator += (unsigned char num) {concat(num); return (*this);}
+ String & operator += (int num) {concat(num); return (*this);}
+ String & operator += (unsigned int num) {concat(num); return (*this);}
+ String & operator += (long num) {concat(num); return (*this);}
+ String & operator += (unsigned long num) {concat(num); return (*this);}
+
+ friend StringSumHelper & operator + (const StringSumHelper &lhs, const String &rhs);
+ friend StringSumHelper & operator + (const StringSumHelper &lhs, const char *cstr);
+ friend StringSumHelper & operator + (const StringSumHelper &lhs, char c);
+ friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned char num);
+ friend StringSumHelper & operator + (const StringSumHelper &lhs, int num);
+ friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned int num);
+ friend StringSumHelper & operator + (const StringSumHelper &lhs, long num);
+ friend StringSumHelper & operator + (const StringSumHelper &lhs, unsigned long num);
+
+ // comparison (only works w/ Strings and "strings")
+ operator StringIfHelperType() const { return buffer ? &String::StringIfHelper : 0; }
+ int compareTo(const String &s) const;
+ unsigned char equals(const String &s) const;
+ unsigned char equals(const char *cstr) const;
+ unsigned char operator == (const String &rhs) const {return equals(rhs);}
+ unsigned char operator == (const char *cstr) const {return equals(cstr);}
+ unsigned char operator != (const String &rhs) const {return !equals(rhs);}
+ unsigned char operator != (const char *cstr) const {return !equals(cstr);}
+ unsigned char operator < (const String &rhs) const;
+ unsigned char operator > (const String &rhs) const;
+ unsigned char operator <= (const String &rhs) const;
+ unsigned char operator >= (const String &rhs) const;
+ unsigned char equalsIgnoreCase(const String &s) const;
+ unsigned char startsWith( const String &prefix) const;
+ unsigned char startsWith(const String &prefix, unsigned int offset) const;
+ unsigned char endsWith(const String &suffix) const;
+
+ // character acccess
+ char charAt(unsigned int index) const;
+ void setCharAt(unsigned int index, char c);
+ char operator [] (unsigned int index) const;
+ char& operator [] (unsigned int index);
+ void getBytes(unsigned char *buf, unsigned int bufsize, unsigned int index=0) const;
+ void toCharArray(char *buf, unsigned int bufsize, unsigned int index=0) const
+ {getBytes((unsigned char *)buf, bufsize, index);}
+
+ // search
+ int indexOf( char ch ) const;
+ int indexOf( char ch, unsigned int fromIndex ) const;
+ int indexOf( const String &str ) const;
+ int indexOf( const String &str, unsigned int fromIndex ) const;
+ int lastIndexOf( char ch ) const;
+ int lastIndexOf( char ch, unsigned int fromIndex ) const;
+ int lastIndexOf( const String &str ) const;
+ int lastIndexOf( const String &str, unsigned int fromIndex ) const;
+ String substring( unsigned int beginIndex ) const;
+ String substring( unsigned int beginIndex, unsigned int endIndex ) const;
+
+ // modification
+ void replace(char find, char replace);
+ void replace(const String& find, const String& replace);
+ void toLowerCase(void);
+ void toUpperCase(void);
+ void trim(void);
+
+ // parsing/conversion
+ long toInt(void) const;
+
+protected:
+ char *buffer; // the actual char array
+ unsigned int capacity; // the array length minus one (for the '\0')
+ unsigned int len; // the String length (not counting the '\0')
+ unsigned char flags; // unused, for future features
+protected:
+ void init(void);
+ void invalidate(void);
+ unsigned char changeBuffer(unsigned int maxStrLen);
+ unsigned char concat(const char *cstr, unsigned int length);
+
+ // copy and move
+ String & copy(const char *cstr, unsigned int length);
+ #ifdef __GXX_EXPERIMENTAL_CXX0X__
+ void move(String &rhs);
+ #endif
+};
+
+class StringSumHelper : public String
+{
+public:
+ StringSumHelper(const String &s) : String(s) {}
+ StringSumHelper(const char *p) : String(p) {}
+ StringSumHelper(char c) : String(c) {}
+ StringSumHelper(unsigned char num) : String(num) {}
+ StringSumHelper(int num) : String(num) {}
+ StringSumHelper(unsigned int num) : String(num) {}
+ StringSumHelper(long num) : String(num) {}
+ StringSumHelper(unsigned long num) : String(num) {}
+};
+
+#endif // __cplusplus
+#endif // String_class_h
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/binary.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/binary.h
new file mode 100644
index 000000000..af1498033
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/binary.h
@@ -0,0 +1,515 @@
+#ifndef Binary_h
+#define Binary_h
+
+#define B0 0
+#define B00 0
+#define B000 0
+#define B0000 0
+#define B00000 0
+#define B000000 0
+#define B0000000 0
+#define B00000000 0
+#define B1 1
+#define B01 1
+#define B001 1
+#define B0001 1
+#define B00001 1
+#define B000001 1
+#define B0000001 1
+#define B00000001 1
+#define B10 2
+#define B010 2
+#define B0010 2
+#define B00010 2
+#define B000010 2
+#define B0000010 2
+#define B00000010 2
+#define B11 3
+#define B011 3
+#define B0011 3
+#define B00011 3
+#define B000011 3
+#define B0000011 3
+#define B00000011 3
+#define B100 4
+#define B0100 4
+#define B00100 4
+#define B000100 4
+#define B0000100 4
+#define B00000100 4
+#define B101 5
+#define B0101 5
+#define B00101 5
+#define B000101 5
+#define B0000101 5
+#define B00000101 5
+#define B110 6
+#define B0110 6
+#define B00110 6
+#define B000110 6
+#define B0000110 6
+#define B00000110 6
+#define B111 7
+#define B0111 7
+#define B00111 7
+#define B000111 7
+#define B0000111 7
+#define B00000111 7
+#define B1000 8
+#define B01000 8
+#define B001000 8
+#define B0001000 8
+#define B00001000 8
+#define B1001 9
+#define B01001 9
+#define B001001 9
+#define B0001001 9
+#define B00001001 9
+#define B1010 10
+#define B01010 10
+#define B001010 10
+#define B0001010 10
+#define B00001010 10
+#define B1011 11
+#define B01011 11
+#define B001011 11
+#define B0001011 11
+#define B00001011 11
+#define B1100 12
+#define B01100 12
+#define B001100 12
+#define B0001100 12
+#define B00001100 12
+#define B1101 13
+#define B01101 13
+#define B001101 13
+#define B0001101 13
+#define B00001101 13
+#define B1110 14
+#define B01110 14
+#define B001110 14
+#define B0001110 14
+#define B00001110 14
+#define B1111 15
+#define B01111 15
+#define B001111 15
+#define B0001111 15
+#define B00001111 15
+#define B10000 16
+#define B010000 16
+#define B0010000 16
+#define B00010000 16
+#define B10001 17
+#define B010001 17
+#define B0010001 17
+#define B00010001 17
+#define B10010 18
+#define B010010 18
+#define B0010010 18
+#define B00010010 18
+#define B10011 19
+#define B010011 19
+#define B0010011 19
+#define B00010011 19
+#define B10100 20
+#define B010100 20
+#define B0010100 20
+#define B00010100 20
+#define B10101 21
+#define B010101 21
+#define B0010101 21
+#define B00010101 21
+#define B10110 22
+#define B010110 22
+#define B0010110 22
+#define B00010110 22
+#define B10111 23
+#define B010111 23
+#define B0010111 23
+#define B00010111 23
+#define B11000 24
+#define B011000 24
+#define B0011000 24
+#define B00011000 24
+#define B11001 25
+#define B011001 25
+#define B0011001 25
+#define B00011001 25
+#define B11010 26
+#define B011010 26
+#define B0011010 26
+#define B00011010 26
+#define B11011 27
+#define B011011 27
+#define B0011011 27
+#define B00011011 27
+#define B11100 28
+#define B011100 28
+#define B0011100 28
+#define B00011100 28
+#define B11101 29
+#define B011101 29
+#define B0011101 29
+#define B00011101 29
+#define B11110 30
+#define B011110 30
+#define B0011110 30
+#define B00011110 30
+#define B11111 31
+#define B011111 31
+#define B0011111 31
+#define B00011111 31
+#define B100000 32
+#define B0100000 32
+#define B00100000 32
+#define B100001 33
+#define B0100001 33
+#define B00100001 33
+#define B100010 34
+#define B0100010 34
+#define B00100010 34
+#define B100011 35
+#define B0100011 35
+#define B00100011 35
+#define B100100 36
+#define B0100100 36
+#define B00100100 36
+#define B100101 37
+#define B0100101 37
+#define B00100101 37
+#define B100110 38
+#define B0100110 38
+#define B00100110 38
+#define B100111 39
+#define B0100111 39
+#define B00100111 39
+#define B101000 40
+#define B0101000 40
+#define B00101000 40
+#define B101001 41
+#define B0101001 41
+#define B00101001 41
+#define B101010 42
+#define B0101010 42
+#define B00101010 42
+#define B101011 43
+#define B0101011 43
+#define B00101011 43
+#define B101100 44
+#define B0101100 44
+#define B00101100 44
+#define B101101 45
+#define B0101101 45
+#define B00101101 45
+#define B101110 46
+#define B0101110 46
+#define B00101110 46
+#define B101111 47
+#define B0101111 47
+#define B00101111 47
+#define B110000 48
+#define B0110000 48
+#define B00110000 48
+#define B110001 49
+#define B0110001 49
+#define B00110001 49
+#define B110010 50
+#define B0110010 50
+#define B00110010 50
+#define B110011 51
+#define B0110011 51
+#define B00110011 51
+#define B110100 52
+#define B0110100 52
+#define B00110100 52
+#define B110101 53
+#define B0110101 53
+#define B00110101 53
+#define B110110 54
+#define B0110110 54
+#define B00110110 54
+#define B110111 55
+#define B0110111 55
+#define B00110111 55
+#define B111000 56
+#define B0111000 56
+#define B00111000 56
+#define B111001 57
+#define B0111001 57
+#define B00111001 57
+#define B111010 58
+#define B0111010 58
+#define B00111010 58
+#define B111011 59
+#define B0111011 59
+#define B00111011 59
+#define B111100 60
+#define B0111100 60
+#define B00111100 60
+#define B111101 61
+#define B0111101 61
+#define B00111101 61
+#define B111110 62
+#define B0111110 62
+#define B00111110 62
+#define B111111 63
+#define B0111111 63
+#define B00111111 63
+#define B1000000 64
+#define B01000000 64
+#define B1000001 65
+#define B01000001 65
+#define B1000010 66
+#define B01000010 66
+#define B1000011 67
+#define B01000011 67
+#define B1000100 68
+#define B01000100 68
+#define B1000101 69
+#define B01000101 69
+#define B1000110 70
+#define B01000110 70
+#define B1000111 71
+#define B01000111 71
+#define B1001000 72
+#define B01001000 72
+#define B1001001 73
+#define B01001001 73
+#define B1001010 74
+#define B01001010 74
+#define B1001011 75
+#define B01001011 75
+#define B1001100 76
+#define B01001100 76
+#define B1001101 77
+#define B01001101 77
+#define B1001110 78
+#define B01001110 78
+#define B1001111 79
+#define B01001111 79
+#define B1010000 80
+#define B01010000 80
+#define B1010001 81
+#define B01010001 81
+#define B1010010 82
+#define B01010010 82
+#define B1010011 83
+#define B01010011 83
+#define B1010100 84
+#define B01010100 84
+#define B1010101 85
+#define B01010101 85
+#define B1010110 86
+#define B01010110 86
+#define B1010111 87
+#define B01010111 87
+#define B1011000 88
+#define B01011000 88
+#define B1011001 89
+#define B01011001 89
+#define B1011010 90
+#define B01011010 90
+#define B1011011 91
+#define B01011011 91
+#define B1011100 92
+#define B01011100 92
+#define B1011101 93
+#define B01011101 93
+#define B1011110 94
+#define B01011110 94
+#define B1011111 95
+#define B01011111 95
+#define B1100000 96
+#define B01100000 96
+#define B1100001 97
+#define B01100001 97
+#define B1100010 98
+#define B01100010 98
+#define B1100011 99
+#define B01100011 99
+#define B1100100 100
+#define B01100100 100
+#define B1100101 101
+#define B01100101 101
+#define B1100110 102
+#define B01100110 102
+#define B1100111 103
+#define B01100111 103
+#define B1101000 104
+#define B01101000 104
+#define B1101001 105
+#define B01101001 105
+#define B1101010 106
+#define B01101010 106
+#define B1101011 107
+#define B01101011 107
+#define B1101100 108
+#define B01101100 108
+#define B1101101 109
+#define B01101101 109
+#define B1101110 110
+#define B01101110 110
+#define B1101111 111
+#define B01101111 111
+#define B1110000 112
+#define B01110000 112
+#define B1110001 113
+#define B01110001 113
+#define B1110010 114
+#define B01110010 114
+#define B1110011 115
+#define B01110011 115
+#define B1110100 116
+#define B01110100 116
+#define B1110101 117
+#define B01110101 117
+#define B1110110 118
+#define B01110110 118
+#define B1110111 119
+#define B01110111 119
+#define B1111000 120
+#define B01111000 120
+#define B1111001 121
+#define B01111001 121
+#define B1111010 122
+#define B01111010 122
+#define B1111011 123
+#define B01111011 123
+#define B1111100 124
+#define B01111100 124
+#define B1111101 125
+#define B01111101 125
+#define B1111110 126
+#define B01111110 126
+#define B1111111 127
+#define B01111111 127
+#define B10000000 128
+#define B10000001 129
+#define B10000010 130
+#define B10000011 131
+#define B10000100 132
+#define B10000101 133
+#define B10000110 134
+#define B10000111 135
+#define B10001000 136
+#define B10001001 137
+#define B10001010 138
+#define B10001011 139
+#define B10001100 140
+#define B10001101 141
+#define B10001110 142
+#define B10001111 143
+#define B10010000 144
+#define B10010001 145
+#define B10010010 146
+#define B10010011 147
+#define B10010100 148
+#define B10010101 149
+#define B10010110 150
+#define B10010111 151
+#define B10011000 152
+#define B10011001 153
+#define B10011010 154
+#define B10011011 155
+#define B10011100 156
+#define B10011101 157
+#define B10011110 158
+#define B10011111 159
+#define B10100000 160
+#define B10100001 161
+#define B10100010 162
+#define B10100011 163
+#define B10100100 164
+#define B10100101 165
+#define B10100110 166
+#define B10100111 167
+#define B10101000 168
+#define B10101001 169
+#define B10101010 170
+#define B10101011 171
+#define B10101100 172
+#define B10101101 173
+#define B10101110 174
+#define B10101111 175
+#define B10110000 176
+#define B10110001 177
+#define B10110010 178
+#define B10110011 179
+#define B10110100 180
+#define B10110101 181
+#define B10110110 182
+#define B10110111 183
+#define B10111000 184
+#define B10111001 185
+#define B10111010 186
+#define B10111011 187
+#define B10111100 188
+#define B10111101 189
+#define B10111110 190
+#define B10111111 191
+#define B11000000 192
+#define B11000001 193
+#define B11000010 194
+#define B11000011 195
+#define B11000100 196
+#define B11000101 197
+#define B11000110 198
+#define B11000111 199
+#define B11001000 200
+#define B11001001 201
+#define B11001010 202
+#define B11001011 203
+#define B11001100 204
+#define B11001101 205
+#define B11001110 206
+#define B11001111 207
+#define B11010000 208
+#define B11010001 209
+#define B11010010 210
+#define B11010011 211
+#define B11010100 212
+#define B11010101 213
+#define B11010110 214
+#define B11010111 215
+#define B11011000 216
+#define B11011001 217
+#define B11011010 218
+#define B11011011 219
+#define B11011100 220
+#define B11011101 221
+#define B11011110 222
+#define B11011111 223
+#define B11100000 224
+#define B11100001 225
+#define B11100010 226
+#define B11100011 227
+#define B11100100 228
+#define B11100101 229
+#define B11100110 230
+#define B11100111 231
+#define B11101000 232
+#define B11101001 233
+#define B11101010 234
+#define B11101011 235
+#define B11101100 236
+#define B11101101 237
+#define B11101110 238
+#define B11101111 239
+#define B11110000 240
+#define B11110001 241
+#define B11110010 242
+#define B11110011 243
+#define B11110100 244
+#define B11110101 245
+#define B11110110 246
+#define B11110111 247
+#define B11111000 248
+#define B11111001 249
+#define B11111010 250
+#define B11111011 251
+#define B11111100 252
+#define B11111101 253
+#define B11111110 254
+#define B11111111 255
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/main.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/main.cpp
new file mode 100644
index 000000000..3d4e079d2
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/main.cpp
@@ -0,0 +1,20 @@
+#include <Arduino.h>
+
+int main(void)
+{
+ init();
+
+#if defined(USBCON)
+ USBDevice.attach();
+#endif
+
+ setup();
+
+ for (;;) {
+ loop();
+ if (serialEventRun) serialEventRun();
+ }
+
+ return 0;
+}
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/new.cpp b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/new.cpp
new file mode 100644
index 000000000..0f6d4220e
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/new.cpp
@@ -0,0 +1,18 @@
+#include <new.h>
+
+void * operator new(size_t size)
+{
+ return malloc(size);
+}
+
+void operator delete(void * ptr)
+{
+ free(ptr);
+}
+
+int __cxa_guard_acquire(__guard *g) {return !*(char *)(g);};
+void __cxa_guard_release (__guard *g) {*(char *)g = 1;};
+void __cxa_guard_abort (__guard *) {};
+
+void __cxa_pure_virtual(void) {};
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/new.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/new.h
new file mode 100644
index 000000000..cd940ce8b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/new.h
@@ -0,0 +1,22 @@
+/* Header to define new/delete operators as they aren't provided by avr-gcc by default
+ Taken from http://www.avrfreaks.net/index.php?name=PNphpBB2&file=viewtopic&t=59453
+ */
+
+#ifndef NEW_H
+#define NEW_H
+
+#include <stdlib.h>
+
+void * operator new(size_t size);
+void operator delete(void * ptr);
+
+__extension__ typedef int __guard __attribute__((mode (__DI__)));
+
+extern "C" int __cxa_guard_acquire(__guard *);
+extern "C" void __cxa_guard_release (__guard *);
+extern "C" void __cxa_guard_abort (__guard *);
+
+extern "C" void __cxa_pure_virtual(void);
+
+#endif
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring.c b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring.c
new file mode 100644
index 000000000..ac8bb6f9b
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring.c
@@ -0,0 +1,324 @@
+/*
+ wiring.c - Partial implementation of the Wiring API for the ATmega8.
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2005-2006 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id$
+*/
+
+#include "wiring_private.h"
+
+// the prescaler is set so that timer0 ticks every 64 clock cycles, and the
+// the overflow handler is called every 256 ticks.
+#define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
+
+// the whole number of milliseconds per timer0 overflow
+#define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
+
+// the fractional number of milliseconds per timer0 overflow. we shift right
+// by three to fit these numbers into a byte. (for the clock speeds we care
+// about - 8 and 16 MHz - this doesn't lose precision.)
+#define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
+#define FRACT_MAX (1000 >> 3)
+
+volatile unsigned long timer0_overflow_count = 0;
+volatile unsigned long timer0_millis = 0;
+static unsigned char timer0_fract = 0;
+
+#if defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__)
+SIGNAL(TIM0_OVF_vect)
+#else
+SIGNAL(TIMER0_OVF_vect)
+#endif
+{
+ // copy these to local variables so they can be stored in registers
+ // (volatile variables must be read from memory on every access)
+ unsigned long m = timer0_millis;
+ unsigned char f = timer0_fract;
+
+ m += MILLIS_INC;
+ f += FRACT_INC;
+ if (f >= FRACT_MAX) {
+ f -= FRACT_MAX;
+ m += 1;
+ }
+
+ timer0_fract = f;
+ timer0_millis = m;
+ timer0_overflow_count++;
+}
+
+unsigned long millis()
+{
+ unsigned long m;
+ uint8_t oldSREG = SREG;
+
+ // disable interrupts while we read timer0_millis or we might get an
+ // inconsistent value (e.g. in the middle of a write to timer0_millis)
+ cli();
+ m = timer0_millis;
+ SREG = oldSREG;
+
+ return m;
+}
+
+unsigned long micros() {
+ unsigned long m;
+ uint8_t oldSREG = SREG, t;
+
+ cli();
+ m = timer0_overflow_count;
+#if defined(TCNT0)
+ t = TCNT0;
+#elif defined(TCNT0L)
+ t = TCNT0L;
+#else
+ #error TIMER 0 not defined
+#endif
+
+
+#ifdef TIFR0
+ if ((TIFR0 & _BV(TOV0)) && (t < 255))
+ m++;
+#else
+ if ((TIFR & _BV(TOV0)) && (t < 255))
+ m++;
+#endif
+
+ SREG = oldSREG;
+
+ return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
+}
+
+void delay(unsigned long ms)
+{
+ uint16_t start = (uint16_t)micros();
+
+ while (ms > 0) {
+ if (((uint16_t)micros() - start) >= 1000) {
+ ms--;
+ start += 1000;
+ }
+ }
+}
+
+/* Delay for the given number of microseconds. Assumes a 8 or 16 MHz clock. */
+void delayMicroseconds(unsigned int us)
+{
+ // calling avrlib's delay_us() function with low values (e.g. 1 or
+ // 2 microseconds) gives delays longer than desired.
+ //delay_us(us);
+#if F_CPU >= 20000000L
+ // for the 20 MHz clock on rare Arduino boards
+
+ // for a one-microsecond delay, simply wait 2 cycle and return. The overhead
+ // of the function call yields a delay of exactly a one microsecond.
+ __asm__ __volatile__ (
+ "nop" "\n\t"
+ "nop"); //just waiting 2 cycle
+ if (--us == 0)
+ return;
+
+ // the following loop takes a 1/5 of a microsecond (4 cycles)
+ // per iteration, so execute it five times for each microsecond of
+ // delay requested.
+ us = (us<<2) + us; // x5 us
+
+ // account for the time taken in the preceeding commands.
+ us -= 2;
+
+#elif F_CPU >= 16000000L
+ // for the 16 MHz clock on most Arduino boards
+
+ // for a one-microsecond delay, simply return. the overhead
+ // of the function call yields a delay of approximately 1 1/8 us.
+ if (--us == 0)
+ return;
+
+ // the following loop takes a quarter of a microsecond (4 cycles)
+ // per iteration, so execute it four times for each microsecond of
+ // delay requested.
+ us <<= 2;
+
+ // account for the time taken in the preceeding commands.
+ us -= 2;
+#else
+ // for the 8 MHz internal clock on the ATmega168
+
+ // for a one- or two-microsecond delay, simply return. the overhead of
+ // the function calls takes more than two microseconds. can't just
+ // subtract two, since us is unsigned; we'd overflow.
+ if (--us == 0)
+ return;
+ if (--us == 0)
+ return;
+
+ // the following loop takes half of a microsecond (4 cycles)
+ // per iteration, so execute it twice for each microsecond of
+ // delay requested.
+ us <<= 1;
+
+ // partially compensate for the time taken by the preceeding commands.
+ // we can't subtract any more than this or we'd overflow w/ small delays.
+ us--;
+#endif
+
+ // busy wait
+ __asm__ __volatile__ (
+ "1: sbiw %0,1" "\n\t" // 2 cycles
+ "brne 1b" : "=w" (us) : "0" (us) // 2 cycles
+ );
+}
+
+void init()
+{
+ // this needs to be called before setup() or some functions won't
+ // work there
+ sei();
+
+ // on the ATmega168, timer 0 is also used for fast hardware pwm
+ // (using phase-correct PWM would mean that timer 0 overflowed half as often
+ // resulting in different millis() behavior on the ATmega8 and ATmega168)
+#if defined(TCCR0A) && defined(WGM01)
+ sbi(TCCR0A, WGM01);
+ sbi(TCCR0A, WGM00);
+#endif
+
+ // set timer 0 prescale factor to 64
+#if defined(__AVR_ATmega128__)
+ // CPU specific: different values for the ATmega128
+ sbi(TCCR0, CS02);
+#elif defined(TCCR0) && defined(CS01) && defined(CS00)
+ // this combination is for the standard atmega8
+ sbi(TCCR0, CS01);
+ sbi(TCCR0, CS00);
+#elif defined(TCCR0B) && defined(CS01) && defined(CS00)
+ // this combination is for the standard 168/328/1280/2560
+ sbi(TCCR0B, CS01);
+ sbi(TCCR0B, CS00);
+#elif defined(TCCR0A) && defined(CS01) && defined(CS00)
+ // this combination is for the __AVR_ATmega645__ series
+ sbi(TCCR0A, CS01);
+ sbi(TCCR0A, CS00);
+#else
+ #error Timer 0 prescale factor 64 not set correctly
+#endif
+
+ // enable timer 0 overflow interrupt
+#if defined(TIMSK) && defined(TOIE0)
+ sbi(TIMSK, TOIE0);
+#elif defined(TIMSK0) && defined(TOIE0)
+ sbi(TIMSK0, TOIE0);
+#else
+ #error Timer 0 overflow interrupt not set correctly
+#endif
+
+ // timers 1 and 2 are used for phase-correct hardware pwm
+ // this is better for motors as it ensures an even waveform
+ // note, however, that fast pwm mode can achieve a frequency of up
+ // 8 MHz (with a 16 MHz clock) at 50% duty cycle
+
+#if defined(TCCR1B) && defined(CS11) && defined(CS10)
+ TCCR1B = 0;
+
+ // set timer 1 prescale factor to 64
+ sbi(TCCR1B, CS11);
+#if F_CPU >= 8000000L
+ sbi(TCCR1B, CS10);
+#endif
+#elif defined(TCCR1) && defined(CS11) && defined(CS10)
+ sbi(TCCR1, CS11);
+#if F_CPU >= 8000000L
+ sbi(TCCR1, CS10);
+#endif
+#endif
+ // put timer 1 in 8-bit phase correct pwm mode
+#if defined(TCCR1A) && defined(WGM10)
+ sbi(TCCR1A, WGM10);
+#elif defined(TCCR1)
+ #warning this needs to be finished
+#endif
+
+ // set timer 2 prescale factor to 64
+#if defined(TCCR2) && defined(CS22)
+ sbi(TCCR2, CS22);
+#elif defined(TCCR2B) && defined(CS22)
+ sbi(TCCR2B, CS22);
+#else
+ #warning Timer 2 not finished (may not be present on this CPU)
+#endif
+
+ // configure timer 2 for phase correct pwm (8-bit)
+#if defined(TCCR2) && defined(WGM20)
+ sbi(TCCR2, WGM20);
+#elif defined(TCCR2A) && defined(WGM20)
+ sbi(TCCR2A, WGM20);
+#else
+ #warning Timer 2 not finished (may not be present on this CPU)
+#endif
+
+#if defined(TCCR3B) && defined(CS31) && defined(WGM30)
+ sbi(TCCR3B, CS31); // set timer 3 prescale factor to 64
+ sbi(TCCR3B, CS30);
+ sbi(TCCR3A, WGM30); // put timer 3 in 8-bit phase correct pwm mode
+#endif
+
+#if defined(TCCR4A) && defined(TCCR4B) && defined(TCCR4D) /* beginning of timer4 block for 32U4 and similar */
+ sbi(TCCR4B, CS42); // set timer4 prescale factor to 64
+ sbi(TCCR4B, CS41);
+ sbi(TCCR4B, CS40);
+ sbi(TCCR4D, WGM40); // put timer 4 in phase- and frequency-correct PWM mode
+ sbi(TCCR4A, PWM4A); // enable PWM mode for comparator OCR4A
+ sbi(TCCR4C, PWM4D); // enable PWM mode for comparator OCR4D
+#else /* beginning of timer4 block for ATMEGA1280 and ATMEGA2560 */
+#if defined(TCCR4B) && defined(CS41) && defined(WGM40)
+ sbi(TCCR4B, CS41); // set timer 4 prescale factor to 64
+ sbi(TCCR4B, CS40);
+ sbi(TCCR4A, WGM40); // put timer 4 in 8-bit phase correct pwm mode
+#endif
+#endif /* end timer4 block for ATMEGA1280/2560 and similar */
+
+#if defined(TCCR5B) && defined(CS51) && defined(WGM50)
+ sbi(TCCR5B, CS51); // set timer 5 prescale factor to 64
+ sbi(TCCR5B, CS50);
+ sbi(TCCR5A, WGM50); // put timer 5 in 8-bit phase correct pwm mode
+#endif
+
+#if defined(ADCSRA)
+ // set a2d prescale factor to 128
+ // 16 MHz / 128 = 125 KHz, inside the desired 50-200 KHz range.
+ // XXX: this will not work properly for other clock speeds, and
+ // this code should use F_CPU to determine the prescale factor.
+ sbi(ADCSRA, ADPS2);
+ sbi(ADCSRA, ADPS1);
+ sbi(ADCSRA, ADPS0);
+
+ // enable a2d conversions
+ sbi(ADCSRA, ADEN);
+#endif
+
+ // the bootloader connects pins 0 and 1 to the USART; disconnect them
+ // here so they can be used as normal digital i/o; they will be
+ // reconnected in Serial.begin()
+#if defined(UCSRB)
+ UCSRB = 0;
+#elif defined(UCSR0B)
+ UCSR0B = 0;
+#endif
+}
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_analog.c b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_analog.c
new file mode 100644
index 000000000..0e9881f6a
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_analog.c
@@ -0,0 +1,282 @@
+/*
+ wiring_analog.c - analog input and output
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2005-2006 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ Modified 28 September 2010 by Mark Sproul
+
+ $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $
+*/
+
+#include "wiring_private.h"
+#include "pins_arduino.h"
+
+uint8_t analog_reference = DEFAULT;
+
+void analogReference(uint8_t mode)
+{
+ // can't actually set the register here because the default setting
+ // will connect AVCC and the AREF pin, which would cause a short if
+ // there's something connected to AREF.
+ analog_reference = mode;
+}
+
+int analogRead(uint8_t pin)
+{
+ uint8_t low, high;
+
+#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+ if (pin >= 54) pin -= 54; // allow for channel or pin numbers
+#elif defined(__AVR_ATmega32U4__)
+ if (pin >= 18) pin -= 18; // allow for channel or pin numbers
+#elif defined(__AVR_ATmega1284__)
+ if (pin >= 24) pin -= 24; // allow for channel or pin numbers
+#else
+ if (pin >= 14) pin -= 14; // allow for channel or pin numbers
+#endif
+
+#if defined(__AVR_ATmega32U4__)
+ pin = analogPinToChannel(pin);
+ ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
+#elif defined(ADCSRB) && defined(MUX5)
+ // the MUX5 bit of ADCSRB selects whether we're reading from channels
+ // 0 to 7 (MUX5 low) or 8 to 15 (MUX5 high).
+ ADCSRB = (ADCSRB & ~(1 << MUX5)) | (((pin >> 3) & 0x01) << MUX5);
+#endif
+
+ // set the analog reference (high two bits of ADMUX) and select the
+ // channel (low 4 bits). this also sets ADLAR (left-adjust result)
+ // to 0 (the default).
+#if defined(ADMUX)
+ ADMUX = (analog_reference << 6) | (pin & 0x07);
+#endif
+
+ // without a delay, we seem to read from the wrong channel
+ //delay(1);
+
+#if defined(ADCSRA) && defined(ADCL)
+ // start the conversion
+ sbi(ADCSRA, ADSC);
+
+ // ADSC is cleared when the conversion finishes
+ while (bit_is_set(ADCSRA, ADSC));
+
+ // we have to read ADCL first; doing so locks both ADCL
+ // and ADCH until ADCH is read. reading ADCL second would
+ // cause the results of each conversion to be discarded,
+ // as ADCL and ADCH would be locked when it completed.
+ low = ADCL;
+ high = ADCH;
+#else
+ // we dont have an ADC, return 0
+ low = 0;
+ high = 0;
+#endif
+
+ // combine the two bytes
+ return (high << 8) | low;
+}
+
+// Right now, PWM output only works on the pins with
+// hardware support. These are defined in the appropriate
+// pins_*.c file. For the rest of the pins, we default
+// to digital output.
+void analogWrite(uint8_t pin, int val)
+{
+ // We need to make sure the PWM output is enabled for those pins
+ // that support it, as we turn it off when digitally reading or
+ // writing with them. Also, make sure the pin is in output mode
+ // for consistenty with Wiring, which doesn't require a pinMode
+ // call for the analog output pins.
+ pinMode(pin, OUTPUT);
+ if (val == 0)
+ {
+ digitalWrite(pin, LOW);
+ }
+ else if (val == 255)
+ {
+ digitalWrite(pin, HIGH);
+ }
+ else
+ {
+ switch(digitalPinToTimer(pin))
+ {
+ // XXX fix needed for atmega8
+ #if defined(TCCR0) && defined(COM00) && !defined(__AVR_ATmega8__)
+ case TIMER0A:
+ // connect pwm to pin on timer 0
+ sbi(TCCR0, COM00);
+ OCR0 = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR0A) && defined(COM0A1)
+ case TIMER0A:
+ // connect pwm to pin on timer 0, channel A
+ sbi(TCCR0A, COM0A1);
+ OCR0A = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR0A) && defined(COM0B1)
+ case TIMER0B:
+ // connect pwm to pin on timer 0, channel B
+ sbi(TCCR0A, COM0B1);
+ OCR0B = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR1A) && defined(COM1A1)
+ case TIMER1A:
+ // connect pwm to pin on timer 1, channel A
+ sbi(TCCR1A, COM1A1);
+ OCR1A = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR1A) && defined(COM1B1)
+ case TIMER1B:
+ // connect pwm to pin on timer 1, channel B
+ sbi(TCCR1A, COM1B1);
+ OCR1B = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR2) && defined(COM21)
+ case TIMER2:
+ // connect pwm to pin on timer 2
+ sbi(TCCR2, COM21);
+ OCR2 = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR2A) && defined(COM2A1)
+ case TIMER2A:
+ // connect pwm to pin on timer 2, channel A
+ sbi(TCCR2A, COM2A1);
+ OCR2A = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR2A) && defined(COM2B1)
+ case TIMER2B:
+ // connect pwm to pin on timer 2, channel B
+ sbi(TCCR2A, COM2B1);
+ OCR2B = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR3A) && defined(COM3A1)
+ case TIMER3A:
+ // connect pwm to pin on timer 3, channel A
+ sbi(TCCR3A, COM3A1);
+ OCR3A = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR3A) && defined(COM3B1)
+ case TIMER3B:
+ // connect pwm to pin on timer 3, channel B
+ sbi(TCCR3A, COM3B1);
+ OCR3B = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR3A) && defined(COM3C1)
+ case TIMER3C:
+ // connect pwm to pin on timer 3, channel C
+ sbi(TCCR3A, COM3C1);
+ OCR3C = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR4A)
+ case TIMER4A:
+ //connect pwm to pin on timer 4, channel A
+ sbi(TCCR4A, COM4A1);
+ #if defined(COM4A0) // only used on 32U4
+ cbi(TCCR4A, COM4A0);
+ #endif
+ OCR4A = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR4A) && defined(COM4B1)
+ case TIMER4B:
+ // connect pwm to pin on timer 4, channel B
+ sbi(TCCR4A, COM4B1);
+ OCR4B = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR4A) && defined(COM4C1)
+ case TIMER4C:
+ // connect pwm to pin on timer 4, channel C
+ sbi(TCCR4A, COM4C1);
+ OCR4C = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR4C) && defined(COM4D1)
+ case TIMER4D:
+ // connect pwm to pin on timer 4, channel D
+ sbi(TCCR4C, COM4D1);
+ #if defined(COM4D0) // only used on 32U4
+ cbi(TCCR4C, COM4D0);
+ #endif
+ OCR4D = val; // set pwm duty
+ break;
+ #endif
+
+
+ #if defined(TCCR5A) && defined(COM5A1)
+ case TIMER5A:
+ // connect pwm to pin on timer 5, channel A
+ sbi(TCCR5A, COM5A1);
+ OCR5A = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR5A) && defined(COM5B1)
+ case TIMER5B:
+ // connect pwm to pin on timer 5, channel B
+ sbi(TCCR5A, COM5B1);
+ OCR5B = val; // set pwm duty
+ break;
+ #endif
+
+ #if defined(TCCR5A) && defined(COM5C1)
+ case TIMER5C:
+ // connect pwm to pin on timer 5, channel C
+ sbi(TCCR5A, COM5C1);
+ OCR5C = val; // set pwm duty
+ break;
+ #endif
+
+ case NOT_ON_TIMER:
+ default:
+ if (val < 128) {
+ digitalWrite(pin, LOW);
+ } else {
+ digitalWrite(pin, HIGH);
+ }
+ }
+ }
+}
+
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_digital.c b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_digital.c
new file mode 100644
index 000000000..be323b1df
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_digital.c
@@ -0,0 +1,178 @@
+/*
+ wiring_digital.c - digital input and output functions
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2005-2006 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ Modified 28 September 2010 by Mark Sproul
+
+ $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $
+*/
+
+#define ARDUINO_MAIN
+#include "wiring_private.h"
+#include "pins_arduino.h"
+
+void pinMode(uint8_t pin, uint8_t mode)
+{
+ uint8_t bit = digitalPinToBitMask(pin);
+ uint8_t port = digitalPinToPort(pin);
+ volatile uint8_t *reg, *out;
+
+ if (port == NOT_A_PIN) return;
+
+ // JWS: can I let the optimizer do this?
+ reg = portModeRegister(port);
+ out = portOutputRegister(port);
+
+ if (mode == INPUT) {
+ uint8_t oldSREG = SREG;
+ cli();
+ *reg &= ~bit;
+ *out &= ~bit;
+ SREG = oldSREG;
+ } else if (mode == INPUT_PULLUP) {
+ uint8_t oldSREG = SREG;
+ cli();
+ *reg &= ~bit;
+ *out |= bit;
+ SREG = oldSREG;
+ } else {
+ uint8_t oldSREG = SREG;
+ cli();
+ *reg |= bit;
+ SREG = oldSREG;
+ }
+}
+
+// Forcing this inline keeps the callers from having to push their own stuff
+// on the stack. It is a good performance win and only takes 1 more byte per
+// user than calling. (It will take more bytes on the 168.)
+//
+// But shouldn't this be moved into pinMode? Seems silly to check and do on
+// each digitalread or write.
+//
+// Mark Sproul:
+// - Removed inline. Save 170 bytes on atmega1280
+// - changed to a switch statment; added 32 bytes but much easier to read and maintain.
+// - Added more #ifdefs, now compiles for atmega645
+//
+//static inline void turnOffPWM(uint8_t timer) __attribute__ ((always_inline));
+//static inline void turnOffPWM(uint8_t timer)
+static void turnOffPWM(uint8_t timer)
+{
+ switch (timer)
+ {
+ #if defined(TCCR1A) && defined(COM1A1)
+ case TIMER1A: cbi(TCCR1A, COM1A1); break;
+ #endif
+ #if defined(TCCR1A) && defined(COM1B1)
+ case TIMER1B: cbi(TCCR1A, COM1B1); break;
+ #endif
+
+ #if defined(TCCR2) && defined(COM21)
+ case TIMER2: cbi(TCCR2, COM21); break;
+ #endif
+
+ #if defined(TCCR0A) && defined(COM0A1)
+ case TIMER0A: cbi(TCCR0A, COM0A1); break;
+ #endif
+
+ #if defined(TIMER0B) && defined(COM0B1)
+ case TIMER0B: cbi(TCCR0A, COM0B1); break;
+ #endif
+ #if defined(TCCR2A) && defined(COM2A1)
+ case TIMER2A: cbi(TCCR2A, COM2A1); break;
+ #endif
+ #if defined(TCCR2A) && defined(COM2B1)
+ case TIMER2B: cbi(TCCR2A, COM2B1); break;
+ #endif
+
+ #if defined(TCCR3A) && defined(COM3A1)
+ case TIMER3A: cbi(TCCR3A, COM3A1); break;
+ #endif
+ #if defined(TCCR3A) && defined(COM3B1)
+ case TIMER3B: cbi(TCCR3A, COM3B1); break;
+ #endif
+ #if defined(TCCR3A) && defined(COM3C1)
+ case TIMER3C: cbi(TCCR3A, COM3C1); break;
+ #endif
+
+ #if defined(TCCR4A) && defined(COM4A1)
+ case TIMER4A: cbi(TCCR4A, COM4A1); break;
+ #endif
+ #if defined(TCCR4A) && defined(COM4B1)
+ case TIMER4B: cbi(TCCR4A, COM4B1); break;
+ #endif
+ #if defined(TCCR4A) && defined(COM4C1)
+ case TIMER4C: cbi(TCCR4A, COM4C1); break;
+ #endif
+ #if defined(TCCR4C) && defined(COM4D1)
+ case TIMER4D: cbi(TCCR4C, COM4D1); break;
+ #endif
+
+ #if defined(TCCR5A)
+ case TIMER5A: cbi(TCCR5A, COM5A1); break;
+ case TIMER5B: cbi(TCCR5A, COM5B1); break;
+ case TIMER5C: cbi(TCCR5A, COM5C1); break;
+ #endif
+ }
+}
+
+void digitalWrite(uint8_t pin, uint8_t val)
+{
+ uint8_t timer = digitalPinToTimer(pin);
+ uint8_t bit = digitalPinToBitMask(pin);
+ uint8_t port = digitalPinToPort(pin);
+ volatile uint8_t *out;
+
+ if (port == NOT_A_PIN) return;
+
+ // If the pin that support PWM output, we need to turn it off
+ // before doing a digital write.
+ if (timer != NOT_ON_TIMER) turnOffPWM(timer);
+
+ out = portOutputRegister(port);
+
+ uint8_t oldSREG = SREG;
+ cli();
+
+ if (val == LOW) {
+ *out &= ~bit;
+ } else {
+ *out |= bit;
+ }
+
+ SREG = oldSREG;
+}
+
+int digitalRead(uint8_t pin)
+{
+ uint8_t timer = digitalPinToTimer(pin);
+ uint8_t bit = digitalPinToBitMask(pin);
+ uint8_t port = digitalPinToPort(pin);
+
+ if (port == NOT_A_PIN) return LOW;
+
+ // If the pin that support PWM output, we need to turn it off
+ // before getting a digital reading.
+ if (timer != NOT_ON_TIMER) turnOffPWM(timer);
+
+ if (*portInputRegister(port) & bit) return HIGH;
+ return LOW;
+}
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_private.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_private.h
new file mode 100644
index 000000000..f0ceb0cc4
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_private.h
@@ -0,0 +1,69 @@
+/*
+ wiring_private.h - Internal header file.
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2005-2006 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id: wiring.h 239 2007-01-12 17:58:39Z mellis $
+*/
+
+#ifndef WiringPrivate_h
+#define WiringPrivate_h
+
+#include <avr/io.h>
+#include <avr/interrupt.h>
+#include <stdio.h>
+#include <stdarg.h>
+
+#include "Arduino.h"
+
+#ifdef __cplusplus
+extern "C"{
+#endif
+
+#ifndef cbi
+#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
+#endif
+#ifndef sbi
+#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
+#endif
+
+#define EXTERNAL_INT_0 0
+#define EXTERNAL_INT_1 1
+#define EXTERNAL_INT_2 2
+#define EXTERNAL_INT_3 3
+#define EXTERNAL_INT_4 4
+#define EXTERNAL_INT_5 5
+#define EXTERNAL_INT_6 6
+#define EXTERNAL_INT_7 7
+
+#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__)
+#define EXTERNAL_NUM_INTERRUPTS 8
+#elif defined(__AVR_ATmega1284P__)
+#define EXTERNAL_NUM_INTERRUPTS 3
+#else
+#define EXTERNAL_NUM_INTERRUPTS 2
+#endif
+
+typedef void (*voidFuncPtr)(void);
+
+#ifdef __cplusplus
+} // extern "C"
+#endif
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_pulse.c b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_pulse.c
new file mode 100644
index 000000000..0d968865d
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_pulse.c
@@ -0,0 +1,69 @@
+/*
+ wiring_pulse.c - pulseIn() function
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2005-2006 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $
+*/
+
+#include "wiring_private.h"
+#include "pins_arduino.h"
+
+/* Measures the length (in microseconds) of a pulse on the pin; state is HIGH
+ * or LOW, the type of pulse to measure. Works on pulses from 2-3 microseconds
+ * to 3 minutes in length, but must be called at least a few dozen microseconds
+ * before the start of the pulse. */
+unsigned long pulseIn(uint8_t pin, uint8_t state, unsigned long timeout)
+{
+ // cache the port and bit of the pin in order to speed up the
+ // pulse width measuring loop and achieve finer resolution. calling
+ // digitalRead() instead yields much coarser resolution.
+ uint8_t bit = digitalPinToBitMask(pin);
+ uint8_t port = digitalPinToPort(pin);
+ uint8_t stateMask = (state ? bit : 0);
+ unsigned long width = 0; // keep initialization out of time critical area
+
+ // convert the timeout from microseconds to a number of times through
+ // the initial loop; it takes 16 clock cycles per iteration.
+ unsigned long numloops = 0;
+ unsigned long maxloops = microsecondsToClockCycles(timeout) / 16;
+
+ // wait for any previous pulse to end
+ while ((*portInputRegister(port) & bit) == stateMask)
+ if (numloops++ == maxloops)
+ return 0;
+
+ // wait for the pulse to start
+ while ((*portInputRegister(port) & bit) != stateMask)
+ if (numloops++ == maxloops)
+ return 0;
+
+ // wait for the pulse to stop
+ while ((*portInputRegister(port) & bit) == stateMask) {
+ if (numloops++ == maxloops)
+ return 0;
+ width++;
+ }
+
+ // convert the reading to microseconds. The loop has been determined
+ // to be 20 clock cycles long and have about 16 clocks between the edge
+ // and the start of the loop. There will be some error introduced by
+ // the interrupt handlers.
+ return clockCyclesToMicroseconds(width * 21 + 16);
+}
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_shift.c b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_shift.c
new file mode 100644
index 000000000..cfe786758
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/cores/arduino/wiring_shift.c
@@ -0,0 +1,55 @@
+/*
+ wiring_shift.c - shiftOut() function
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2005-2006 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id: wiring.c 248 2007-02-03 15:36:30Z mellis $
+*/
+
+#include "wiring_private.h"
+
+uint8_t shiftIn(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder) {
+ uint8_t value = 0;
+ uint8_t i;
+
+ for (i = 0; i < 8; ++i) {
+ digitalWrite(clockPin, HIGH);
+ if (bitOrder == LSBFIRST)
+ value |= digitalRead(dataPin) << i;
+ else
+ value |= digitalRead(dataPin) << (7 - i);
+ digitalWrite(clockPin, LOW);
+ }
+ return value;
+}
+
+void shiftOut(uint8_t dataPin, uint8_t clockPin, uint8_t bitOrder, uint8_t val)
+{
+ uint8_t i;
+
+ for (i = 0; i < 8; i++) {
+ if (bitOrder == LSBFIRST)
+ digitalWrite(dataPin, !!(val & (1 << i)));
+ else
+ digitalWrite(dataPin, !!(val & (1 << (7 - i))));
+
+ digitalWrite(clockPin, HIGH);
+ digitalWrite(clockPin, LOW);
+ }
+}
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/eightanaloginputs/pins_arduino.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/eightanaloginputs/pins_arduino.h
new file mode 100644
index 000000000..52b37efc4
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/eightanaloginputs/pins_arduino.h
@@ -0,0 +1,27 @@
+/*
+ pins_arduino.h - Pin definition functions for Arduino
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2007 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $
+*/
+
+#include "../standard/pins_arduino.h"
+#undef NUM_ANALOG_INPUTS
+#define NUM_ANALOG_INPUTS 8
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/leonardo/pins_arduino.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/leonardo/pins_arduino.h
new file mode 100644
index 000000000..9f770d6ce
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/leonardo/pins_arduino.h
@@ -0,0 +1,256 @@
+/*
+ pins_arduino.h - Pin definition functions for Arduino
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2007 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $
+*/
+
+#ifndef Pins_Arduino_h
+#define Pins_Arduino_h
+
+#include <avr/pgmspace.h>
+
+#define TX_RX_LED_INIT DDRD |= (1<<5), DDRB |= (1<<0)
+#define TXLED0 PORTD |= (1<<5)
+#define TXLED1 PORTD &= ~(1<<5)
+#define RXLED0 PORTB |= (1<<0)
+#define RXLED1 PORTB &= ~(1<<0)
+
+static const uint8_t SDA = 2;
+static const uint8_t SCL = 3;
+
+// Map SPI port to 'new' pins D14..D17
+static const uint8_t SS = 17;
+static const uint8_t MOSI = 16;
+static const uint8_t MISO = 14;
+static const uint8_t SCK = 15;
+
+// Mapping of analog pins as digital I/O
+// A6-A11 share with digital pins
+static const uint8_t A0 = 18;
+static const uint8_t A1 = 19;
+static const uint8_t A2 = 20;
+static const uint8_t A3 = 21;
+static const uint8_t A4 = 22;
+static const uint8_t A5 = 23;
+static const uint8_t A6 = 24; // D4
+static const uint8_t A7 = 25; // D6
+static const uint8_t A8 = 26; // D8
+static const uint8_t A9 = 27; // D9
+static const uint8_t A10 = 28; // D10
+static const uint8_t A11 = 29; // D12
+
+#define digitalPinToPCICR(p) ((((p) >= 8 && (p) <= 11) || ((p) >= 14 && (p) <= 17) || ((p) >= A8 && (p) <= A10)) ? (&PCICR) : ((uint8_t *)0))
+#define digitalPinToPCICRbit(p) 0
+#define digitalPinToPCMSK(p) ((((p) >= 8 && (p) <= 11) || ((p) >= 14 && (p) <= 17) || ((p) >= A8 && (p) <= A10)) ? (&PCMSK0) : ((uint8_t *)0))
+#define digitalPinToPCMSKbit(p) ( ((p) >= 8 && (p) <= 11) ? (p) - 4 : ((p) == 14 ? 3 : ((p) == 15 ? 1 : ((p) == 16 ? 2 : ((p) == 17 ? 0 : (p - A8 + 4))))))
+
+// __AVR_ATmega32U4__ has an unusual mapping of pins to channels
+extern const uint8_t PROGMEM analog_pin_to_channel_PGM[];
+#define analogPinToChannel(P) ( pgm_read_byte( analog_pin_to_channel_PGM + (P) ) )
+
+#ifdef ARDUINO_MAIN
+
+// On the Arduino board, digital pins are also used
+// for the analog output (software PWM). Analog input
+// pins are a separate set.
+
+// ATMEL ATMEGA32U4 / ARDUINO LEONARDO
+//
+// D0 PD2 RXD1/INT2
+// D1 PD3 TXD1/INT3
+// D2 PD1 SDA SDA/INT1
+// D3# PD0 PWM8/SCL OC0B/SCL/INT0
+// D4 A6 PD4 ADC8
+// D5# PC6 ??? OC3A/#OC4A
+// D6# A7 PD7 FastPWM #OC4D/ADC10
+// D7 PE6 INT6/AIN0
+//
+// D8 A8 PB4 ADC11/PCINT4
+// D9# A9 PB5 PWM16 OC1A/#OC4B/ADC12/PCINT5
+// D10# A10 PB6 PWM16 OC1B/0c4B/ADC13/PCINT6
+// D11# PB7 PWM8/16 0C0A/OC1C/#RTS/PCINT7
+// D12 A11 PD6 T1/#OC4D/ADC9
+// D13# PC7 PWM10 CLK0/OC4A
+//
+// A0 D18 PF7 ADC7
+// A1 D19 PF6 ADC6
+// A2 D20 PF5 ADC5
+// A3 D21 PF4 ADC4
+// A4 D22 PF1 ADC1
+// A5 D23 PF0 ADC0
+//
+// New pins D14..D17 to map SPI port to digital pins
+//
+// MISO D14 PB3 MISO,PCINT3
+// SCK D15 PB1 SCK,PCINT1
+// MOSI D16 PB2 MOSI,PCINT2
+// SS D17 PB0 RXLED,SS/PCINT0
+//
+// TXLED PD5
+// RXLED PB0
+// HWB PE2 HWB
+
+// these arrays map port names (e.g. port B) to the
+// appropriate addresses for various functions (e.g. reading
+// and writing)
+const uint16_t PROGMEM port_to_mode_PGM[] = {
+ NOT_A_PORT,
+ NOT_A_PORT,
+ (uint16_t) &DDRB,
+ (uint16_t) &DDRC,
+ (uint16_t) &DDRD,
+ (uint16_t) &DDRE,
+ (uint16_t) &DDRF,
+};
+
+const uint16_t PROGMEM port_to_output_PGM[] = {
+ NOT_A_PORT,
+ NOT_A_PORT,
+ (uint16_t) &PORTB,
+ (uint16_t) &PORTC,
+ (uint16_t) &PORTD,
+ (uint16_t) &PORTE,
+ (uint16_t) &PORTF,
+};
+
+const uint16_t PROGMEM port_to_input_PGM[] = {
+ NOT_A_PORT,
+ NOT_A_PORT,
+ (uint16_t) &PINB,
+ (uint16_t) &PINC,
+ (uint16_t) &PIND,
+ (uint16_t) &PINE,
+ (uint16_t) &PINF,
+};
+
+const uint8_t PROGMEM digital_pin_to_port_PGM[30] = {
+ PD, // D0 - PD2
+ PD, // D1 - PD3
+ PD, // D2 - PD1
+ PD, // D3 - PD0
+ PD, // D4 - PD4
+ PC, // D5 - PC6
+ PD, // D6 - PD7
+ PE, // D7 - PE6
+
+ PB, // D8 - PB4
+ PB, // D9 - PB5
+ PB, // D10 - PB6
+ PB, // D11 - PB7
+ PD, // D12 - PD6
+ PC, // D13 - PC7
+
+ PB, // D14 - MISO - PB3
+ PB, // D15 - SCK - PB1
+ PB, // D16 - MOSI - PB2
+ PB, // D17 - SS - PB0
+
+ PF, // D18 - A0 - PF7
+ PF, // D19 - A1 - PF6
+ PF, // D20 - A2 - PF5
+ PF, // D21 - A3 - PF4
+ PF, // D22 - A4 - PF1
+ PF, // D23 - A5 - PF0
+
+ PD, // D24 / D4 - A6 - PD4
+ PD, // D25 / D6 - A7 - PD7
+ PB, // D26 / D8 - A8 - PB4
+ PB, // D27 / D9 - A9 - PB5
+ PB, // D28 / D10 - A10 - PB6
+ PD, // D29 / D12 - A11 - PD6
+};
+
+const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[30] = {
+ _BV(2), // D0 - PD2
+ _BV(3), // D1 - PD3
+ _BV(1), // D2 - PD1
+ _BV(0), // D3 - PD0
+ _BV(4), // D4 - PD4
+ _BV(6), // D5 - PC6
+ _BV(7), // D6 - PD7
+ _BV(6), // D7 - PE6
+
+ _BV(4), // D8 - PB4
+ _BV(5), // D9 - PB5
+ _BV(6), // D10 - PB6
+ _BV(7), // D11 - PB7
+ _BV(6), // D12 - PD6
+ _BV(7), // D13 - PC7
+
+ _BV(3), // D14 - MISO - PB3
+ _BV(1), // D15 - SCK - PB1
+ _BV(2), // D16 - MOSI - PB2
+ _BV(0), // D17 - SS - PB0
+
+ _BV(7), // D18 - A0 - PF7
+ _BV(6), // D19 - A1 - PF6
+ _BV(5), // D20 - A2 - PF5
+ _BV(4), // D21 - A3 - PF4
+ _BV(1), // D22 - A4 - PF1
+ _BV(0), // D23 - A5 - PF0
+
+ _BV(4), // D24 / D4 - A6 - PD4
+ _BV(7), // D25 / D6 - A7 - PD7
+ _BV(4), // D26 / D8 - A8 - PB4
+ _BV(5), // D27 / D9 - A9 - PB5
+ _BV(6), // D28 / D10 - A10 - PB6
+ _BV(6), // D29 / D12 - A11 - PD6
+};
+
+const uint8_t PROGMEM digital_pin_to_timer_PGM[16] = {
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+ TIMER0B, /* 3 */
+ NOT_ON_TIMER,
+ TIMER3A, /* 5 */
+ TIMER4D, /* 6 */
+ NOT_ON_TIMER,
+
+ NOT_ON_TIMER,
+ TIMER1A, /* 9 */
+ TIMER1B, /* 10 */
+ TIMER0A, /* 11 */
+
+ NOT_ON_TIMER,
+ TIMER4A, /* 13 */
+
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+};
+
+const uint8_t PROGMEM analog_pin_to_channel_PGM[12] = {
+ 7, // A0 PF7 ADC7
+ 6, // A1 PF6 ADC6
+ 5, // A2 PF5 ADC5
+ 4, // A3 PF4 ADC4
+ 1, // A4 PF1 ADC1
+ 0, // A5 PF0 ADC0
+ 8, // A6 D4 PD4 ADC8
+ 10, // A7 D6 PD7 ADC10
+ 11, // A8 D8 PB4 ADC11
+ 12, // A9 D9 PB5 ADC12
+ 13, // A10 D10 PB6 ADC13
+ 9 // A11 D12 PD6 ADC9
+};
+
+#endif /* ARDUINO_MAIN */
+#endif /* Pins_Arduino_h */
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/mega/pins_arduino.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/mega/pins_arduino.h
new file mode 100644
index 000000000..5a9b4cb09
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/mega/pins_arduino.h
@@ -0,0 +1,363 @@
+/*
+ pins_arduino.h - Pin definition functions for Arduino
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2007 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $
+*/
+
+#ifndef Pins_Arduino_h
+#define Pins_Arduino_h
+
+#include <avr/pgmspace.h>
+
+#define NUM_DIGITAL_PINS 70
+#define NUM_ANALOG_INPUTS 16
+#define analogInputToDigitalPin(p) ((p < 16) ? (p) + 54 : -1)
+#define digitalPinHasPWM(p) (((p) >= 2 && (p) <= 13) || ((p) >= 44 && (p)<= 46))
+
+static const uint8_t SS = 53;
+static const uint8_t MOSI = 51;
+static const uint8_t MISO = 50;
+static const uint8_t SCK = 52;
+
+static const uint8_t SDA = 20;
+static const uint8_t SCL = 21;
+static const uint8_t LED_BUILTIN = 13;
+
+static const uint8_t A0 = 54;
+static const uint8_t A1 = 55;
+static const uint8_t A2 = 56;
+static const uint8_t A3 = 57;
+static const uint8_t A4 = 58;
+static const uint8_t A5 = 59;
+static const uint8_t A6 = 60;
+static const uint8_t A7 = 61;
+static const uint8_t A8 = 62;
+static const uint8_t A9 = 63;
+static const uint8_t A10 = 64;
+static const uint8_t A11 = 65;
+static const uint8_t A12 = 66;
+static const uint8_t A13 = 67;
+static const uint8_t A14 = 68;
+static const uint8_t A15 = 69;
+
+// A majority of the pins are NOT PCINTs, SO BE WARNED (i.e. you cannot use them as receive pins)
+// Only pins available for RECEIVE (TRANSMIT can be on any pin):
+// (I've deliberately left out pin mapping to the Hardware USARTs - seems senseless to me)
+// Pins: 10, 11, 12, 13, 50, 51, 52, 53, 62, 63, 64, 65, 66, 67, 68, 69
+
+#define digitalPinToPCICR(p) ( (((p) >= 10) && ((p) <= 13)) || \
+ (((p) >= 50) && ((p) <= 53)) || \
+ (((p) >= 62) && ((p) <= 69)) ? (&PCICR) : ((uint8_t *)0) )
+
+#define digitalPinToPCICRbit(p) ( (((p) >= 10) && ((p) <= 13)) || (((p) >= 50) && ((p) <= 53)) ? 0 : \
+ ( (((p) >= 62) && ((p) <= 69)) ? 2 : \
+ 0 ) )
+
+#define digitalPinToPCMSK(p) ( (((p) >= 10) && ((p) <= 13)) || (((p) >= 50) && ((p) <= 53)) ? (&PCMSK0) : \
+ ( (((p) >= 62) && ((p) <= 69)) ? (&PCMSK2) : \
+ ((uint8_t *)0) ) )
+
+#define digitalPinToPCMSKbit(p) ( (((p) >= 10) && ((p) <= 13)) ? ((p) - 6) : \
+ ( ((p) == 50) ? 3 : \
+ ( ((p) == 51) ? 2 : \
+ ( ((p) == 52) ? 1 : \
+ ( ((p) == 53) ? 0 : \
+ ( (((p) >= 62) && ((p) <= 69)) ? ((p) - 62) : \
+ 0 ) ) ) ) ) )
+
+#ifdef ARDUINO_MAIN
+
+const uint16_t PROGMEM port_to_mode_PGM[] = {
+ NOT_A_PORT,
+ (uint16_t) &DDRA,
+ (uint16_t) &DDRB,
+ (uint16_t) &DDRC,
+ (uint16_t) &DDRD,
+ (uint16_t) &DDRE,
+ (uint16_t) &DDRF,
+ (uint16_t) &DDRG,
+ (uint16_t) &DDRH,
+ NOT_A_PORT,
+ (uint16_t) &DDRJ,
+ (uint16_t) &DDRK,
+ (uint16_t) &DDRL,
+};
+
+const uint16_t PROGMEM port_to_output_PGM[] = {
+ NOT_A_PORT,
+ (uint16_t) &PORTA,
+ (uint16_t) &PORTB,
+ (uint16_t) &PORTC,
+ (uint16_t) &PORTD,
+ (uint16_t) &PORTE,
+ (uint16_t) &PORTF,
+ (uint16_t) &PORTG,
+ (uint16_t) &PORTH,
+ NOT_A_PORT,
+ (uint16_t) &PORTJ,
+ (uint16_t) &PORTK,
+ (uint16_t) &PORTL,
+};
+
+const uint16_t PROGMEM port_to_input_PGM[] = {
+ NOT_A_PIN,
+ (uint16_t) &PINA,
+ (uint16_t) &PINB,
+ (uint16_t) &PINC,
+ (uint16_t) &PIND,
+ (uint16_t) &PINE,
+ (uint16_t) &PINF,
+ (uint16_t) &PING,
+ (uint16_t) &PINH,
+ NOT_A_PIN,
+ (uint16_t) &PINJ,
+ (uint16_t) &PINK,
+ (uint16_t) &PINL,
+};
+
+const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
+ // PORTLIST
+ // -------------------------------------------
+ PE , // PE 0 ** 0 ** USART0_RX
+ PE , // PE 1 ** 1 ** USART0_TX
+ PE , // PE 4 ** 2 ** PWM2
+ PE , // PE 5 ** 3 ** PWM3
+ PG , // PG 5 ** 4 ** PWM4
+ PE , // PE 3 ** 5 ** PWM5
+ PH , // PH 3 ** 6 ** PWM6
+ PH , // PH 4 ** 7 ** PWM7
+ PH , // PH 5 ** 8 ** PWM8
+ PH , // PH 6 ** 9 ** PWM9
+ PB , // PB 4 ** 10 ** PWM10
+ PB , // PB 5 ** 11 ** PWM11
+ PB , // PB 6 ** 12 ** PWM12
+ PB , // PB 7 ** 13 ** PWM13
+ PJ , // PJ 1 ** 14 ** USART3_TX
+ PJ , // PJ 0 ** 15 ** USART3_RX
+ PH , // PH 1 ** 16 ** USART2_TX
+ PH , // PH 0 ** 17 ** USART2_RX
+ PD , // PD 3 ** 18 ** USART1_TX
+ PD , // PD 2 ** 19 ** USART1_RX
+ PD , // PD 1 ** 20 ** I2C_SDA
+ PD , // PD 0 ** 21 ** I2C_SCL
+ PA , // PA 0 ** 22 ** D22
+ PA , // PA 1 ** 23 ** D23
+ PA , // PA 2 ** 24 ** D24
+ PA , // PA 3 ** 25 ** D25
+ PA , // PA 4 ** 26 ** D26
+ PA , // PA 5 ** 27 ** D27
+ PA , // PA 6 ** 28 ** D28
+ PA , // PA 7 ** 29 ** D29
+ PC , // PC 7 ** 30 ** D30
+ PC , // PC 6 ** 31 ** D31
+ PC , // PC 5 ** 32 ** D32
+ PC , // PC 4 ** 33 ** D33
+ PC , // PC 3 ** 34 ** D34
+ PC , // PC 2 ** 35 ** D35
+ PC , // PC 1 ** 36 ** D36
+ PC , // PC 0 ** 37 ** D37
+ PD , // PD 7 ** 38 ** D38
+ PG , // PG 2 ** 39 ** D39
+ PG , // PG 1 ** 40 ** D40
+ PG , // PG 0 ** 41 ** D41
+ PL , // PL 7 ** 42 ** D42
+ PL , // PL 6 ** 43 ** D43
+ PL , // PL 5 ** 44 ** D44
+ PL , // PL 4 ** 45 ** D45
+ PL , // PL 3 ** 46 ** D46
+ PL , // PL 2 ** 47 ** D47
+ PL , // PL 1 ** 48 ** D48
+ PL , // PL 0 ** 49 ** D49
+ PB , // PB 3 ** 50 ** SPI_MISO
+ PB , // PB 2 ** 51 ** SPI_MOSI
+ PB , // PB 1 ** 52 ** SPI_SCK
+ PB , // PB 0 ** 53 ** SPI_SS
+ PF , // PF 0 ** 54 ** A0
+ PF , // PF 1 ** 55 ** A1
+ PF , // PF 2 ** 56 ** A2
+ PF , // PF 3 ** 57 ** A3
+ PF , // PF 4 ** 58 ** A4
+ PF , // PF 5 ** 59 ** A5
+ PF , // PF 6 ** 60 ** A6
+ PF , // PF 7 ** 61 ** A7
+ PK , // PK 0 ** 62 ** A8
+ PK , // PK 1 ** 63 ** A9
+ PK , // PK 2 ** 64 ** A10
+ PK , // PK 3 ** 65 ** A11
+ PK , // PK 4 ** 66 ** A12
+ PK , // PK 5 ** 67 ** A13
+ PK , // PK 6 ** 68 ** A14
+ PK , // PK 7 ** 69 ** A15
+};
+
+const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = {
+ // PIN IN PORT
+ // -------------------------------------------
+ _BV( 0 ) , // PE 0 ** 0 ** USART0_RX
+ _BV( 1 ) , // PE 1 ** 1 ** USART0_TX
+ _BV( 4 ) , // PE 4 ** 2 ** PWM2
+ _BV( 5 ) , // PE 5 ** 3 ** PWM3
+ _BV( 5 ) , // PG 5 ** 4 ** PWM4
+ _BV( 3 ) , // PE 3 ** 5 ** PWM5
+ _BV( 3 ) , // PH 3 ** 6 ** PWM6
+ _BV( 4 ) , // PH 4 ** 7 ** PWM7
+ _BV( 5 ) , // PH 5 ** 8 ** PWM8
+ _BV( 6 ) , // PH 6 ** 9 ** PWM9
+ _BV( 4 ) , // PB 4 ** 10 ** PWM10
+ _BV( 5 ) , // PB 5 ** 11 ** PWM11
+ _BV( 6 ) , // PB 6 ** 12 ** PWM12
+ _BV( 7 ) , // PB 7 ** 13 ** PWM13
+ _BV( 1 ) , // PJ 1 ** 14 ** USART3_TX
+ _BV( 0 ) , // PJ 0 ** 15 ** USART3_RX
+ _BV( 1 ) , // PH 1 ** 16 ** USART2_TX
+ _BV( 0 ) , // PH 0 ** 17 ** USART2_RX
+ _BV( 3 ) , // PD 3 ** 18 ** USART1_TX
+ _BV( 2 ) , // PD 2 ** 19 ** USART1_RX
+ _BV( 1 ) , // PD 1 ** 20 ** I2C_SDA
+ _BV( 0 ) , // PD 0 ** 21 ** I2C_SCL
+ _BV( 0 ) , // PA 0 ** 22 ** D22
+ _BV( 1 ) , // PA 1 ** 23 ** D23
+ _BV( 2 ) , // PA 2 ** 24 ** D24
+ _BV( 3 ) , // PA 3 ** 25 ** D25
+ _BV( 4 ) , // PA 4 ** 26 ** D26
+ _BV( 5 ) , // PA 5 ** 27 ** D27
+ _BV( 6 ) , // PA 6 ** 28 ** D28
+ _BV( 7 ) , // PA 7 ** 29 ** D29
+ _BV( 7 ) , // PC 7 ** 30 ** D30
+ _BV( 6 ) , // PC 6 ** 31 ** D31
+ _BV( 5 ) , // PC 5 ** 32 ** D32
+ _BV( 4 ) , // PC 4 ** 33 ** D33
+ _BV( 3 ) , // PC 3 ** 34 ** D34
+ _BV( 2 ) , // PC 2 ** 35 ** D35
+ _BV( 1 ) , // PC 1 ** 36 ** D36
+ _BV( 0 ) , // PC 0 ** 37 ** D37
+ _BV( 7 ) , // PD 7 ** 38 ** D38
+ _BV( 2 ) , // PG 2 ** 39 ** D39
+ _BV( 1 ) , // PG 1 ** 40 ** D40
+ _BV( 0 ) , // PG 0 ** 41 ** D41
+ _BV( 7 ) , // PL 7 ** 42 ** D42
+ _BV( 6 ) , // PL 6 ** 43 ** D43
+ _BV( 5 ) , // PL 5 ** 44 ** D44
+ _BV( 4 ) , // PL 4 ** 45 ** D45
+ _BV( 3 ) , // PL 3 ** 46 ** D46
+ _BV( 2 ) , // PL 2 ** 47 ** D47
+ _BV( 1 ) , // PL 1 ** 48 ** D48
+ _BV( 0 ) , // PL 0 ** 49 ** D49
+ _BV( 3 ) , // PB 3 ** 50 ** SPI_MISO
+ _BV( 2 ) , // PB 2 ** 51 ** SPI_MOSI
+ _BV( 1 ) , // PB 1 ** 52 ** SPI_SCK
+ _BV( 0 ) , // PB 0 ** 53 ** SPI_SS
+ _BV( 0 ) , // PF 0 ** 54 ** A0
+ _BV( 1 ) , // PF 1 ** 55 ** A1
+ _BV( 2 ) , // PF 2 ** 56 ** A2
+ _BV( 3 ) , // PF 3 ** 57 ** A3
+ _BV( 4 ) , // PF 4 ** 58 ** A4
+ _BV( 5 ) , // PF 5 ** 59 ** A5
+ _BV( 6 ) , // PF 6 ** 60 ** A6
+ _BV( 7 ) , // PF 7 ** 61 ** A7
+ _BV( 0 ) , // PK 0 ** 62 ** A8
+ _BV( 1 ) , // PK 1 ** 63 ** A9
+ _BV( 2 ) , // PK 2 ** 64 ** A10
+ _BV( 3 ) , // PK 3 ** 65 ** A11
+ _BV( 4 ) , // PK 4 ** 66 ** A12
+ _BV( 5 ) , // PK 5 ** 67 ** A13
+ _BV( 6 ) , // PK 6 ** 68 ** A14
+ _BV( 7 ) , // PK 7 ** 69 ** A15
+};
+
+const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
+ // TIMERS
+ // -------------------------------------------
+ NOT_ON_TIMER , // PE 0 ** 0 ** USART0_RX
+ NOT_ON_TIMER , // PE 1 ** 1 ** USART0_TX
+ TIMER3B , // PE 4 ** 2 ** PWM2
+ TIMER3C , // PE 5 ** 3 ** PWM3
+ TIMER0B , // PG 5 ** 4 ** PWM4
+ TIMER3A , // PE 3 ** 5 ** PWM5
+ TIMER4A , // PH 3 ** 6 ** PWM6
+ TIMER4B , // PH 4 ** 7 ** PWM7
+ TIMER4C , // PH 5 ** 8 ** PWM8
+ TIMER2B , // PH 6 ** 9 ** PWM9
+ TIMER2A , // PB 4 ** 10 ** PWM10
+ TIMER1A , // PB 5 ** 11 ** PWM11
+ TIMER1B , // PB 6 ** 12 ** PWM12
+ TIMER0A , // PB 7 ** 13 ** PWM13
+ NOT_ON_TIMER , // PJ 1 ** 14 ** USART3_TX
+ NOT_ON_TIMER , // PJ 0 ** 15 ** USART3_RX
+ NOT_ON_TIMER , // PH 1 ** 16 ** USART2_TX
+ NOT_ON_TIMER , // PH 0 ** 17 ** USART2_RX
+ NOT_ON_TIMER , // PD 3 ** 18 ** USART1_TX
+ NOT_ON_TIMER , // PD 2 ** 19 ** USART1_RX
+ NOT_ON_TIMER , // PD 1 ** 20 ** I2C_SDA
+ NOT_ON_TIMER , // PD 0 ** 21 ** I2C_SCL
+ NOT_ON_TIMER , // PA 0 ** 22 ** D22
+ NOT_ON_TIMER , // PA 1 ** 23 ** D23
+ NOT_ON_TIMER , // PA 2 ** 24 ** D24
+ NOT_ON_TIMER , // PA 3 ** 25 ** D25
+ NOT_ON_TIMER , // PA 4 ** 26 ** D26
+ NOT_ON_TIMER , // PA 5 ** 27 ** D27
+ NOT_ON_TIMER , // PA 6 ** 28 ** D28
+ NOT_ON_TIMER , // PA 7 ** 29 ** D29
+ NOT_ON_TIMER , // PC 7 ** 30 ** D30
+ NOT_ON_TIMER , // PC 6 ** 31 ** D31
+ NOT_ON_TIMER , // PC 5 ** 32 ** D32
+ NOT_ON_TIMER , // PC 4 ** 33 ** D33
+ NOT_ON_TIMER , // PC 3 ** 34 ** D34
+ NOT_ON_TIMER , // PC 2 ** 35 ** D35
+ NOT_ON_TIMER , // PC 1 ** 36 ** D36
+ NOT_ON_TIMER , // PC 0 ** 37 ** D37
+ NOT_ON_TIMER , // PD 7 ** 38 ** D38
+ NOT_ON_TIMER , // PG 2 ** 39 ** D39
+ NOT_ON_TIMER , // PG 1 ** 40 ** D40
+ NOT_ON_TIMER , // PG 0 ** 41 ** D41
+ NOT_ON_TIMER , // PL 7 ** 42 ** D42
+ NOT_ON_TIMER , // PL 6 ** 43 ** D43
+ TIMER5C , // PL 5 ** 44 ** D44
+ TIMER5B , // PL 4 ** 45 ** D45
+ TIMER5A , // PL 3 ** 46 ** D46
+ NOT_ON_TIMER , // PL 2 ** 47 ** D47
+ NOT_ON_TIMER , // PL 1 ** 48 ** D48
+ NOT_ON_TIMER , // PL 0 ** 49 ** D49
+ NOT_ON_TIMER , // PB 3 ** 50 ** SPI_MISO
+ NOT_ON_TIMER , // PB 2 ** 51 ** SPI_MOSI
+ NOT_ON_TIMER , // PB 1 ** 52 ** SPI_SCK
+ NOT_ON_TIMER , // PB 0 ** 53 ** SPI_SS
+ NOT_ON_TIMER , // PF 0 ** 54 ** A0
+ NOT_ON_TIMER , // PF 1 ** 55 ** A1
+ NOT_ON_TIMER , // PF 2 ** 56 ** A2
+ NOT_ON_TIMER , // PF 3 ** 57 ** A3
+ NOT_ON_TIMER , // PF 4 ** 58 ** A4
+ NOT_ON_TIMER , // PF 5 ** 59 ** A5
+ NOT_ON_TIMER , // PF 6 ** 60 ** A6
+ NOT_ON_TIMER , // PF 7 ** 61 ** A7
+ NOT_ON_TIMER , // PK 0 ** 62 ** A8
+ NOT_ON_TIMER , // PK 1 ** 63 ** A9
+ NOT_ON_TIMER , // PK 2 ** 64 ** A10
+ NOT_ON_TIMER , // PK 3 ** 65 ** A11
+ NOT_ON_TIMER , // PK 4 ** 66 ** A12
+ NOT_ON_TIMER , // PK 5 ** 67 ** A13
+ NOT_ON_TIMER , // PK 6 ** 68 ** A14
+ NOT_ON_TIMER , // PK 7 ** 69 ** A15
+};
+
+#endif
+
+#endif \ No newline at end of file
diff --git a/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/standard/pins_arduino.h b/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/standard/pins_arduino.h
new file mode 100644
index 000000000..30b426630
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/arduino-1.0.1/variants/standard/pins_arduino.h
@@ -0,0 +1,218 @@
+/*
+ pins_arduino.h - Pin definition functions for Arduino
+ Part of Arduino - http://www.arduino.cc/
+
+ Copyright (c) 2007 David A. Mellis
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General
+ Public License along with this library; if not, write to the
+ Free Software Foundation, Inc., 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307 USA
+
+ $Id: wiring.h 249 2007-02-03 16:52:51Z mellis $
+*/
+
+#ifndef Pins_Arduino_h
+#define Pins_Arduino_h
+
+#include <avr/pgmspace.h>
+
+#define NUM_DIGITAL_PINS 20
+#define NUM_ANALOG_INPUTS 6
+#define analogInputToDigitalPin(p) ((p < 6) ? (p) + 14 : -1)
+
+#if defined(__AVR_ATmega8__)
+#define digitalPinHasPWM(p) ((p) == 9 || (p) == 10 || (p) == 11)
+#else
+#define digitalPinHasPWM(p) ((p) == 3 || (p) == 5 || (p) == 6 || (p) == 9 || (p) == 10 || (p) == 11)
+#endif
+
+static const uint8_t SS = 10;
+static const uint8_t MOSI = 11;
+static const uint8_t MISO = 12;
+static const uint8_t SCK = 13;
+
+static const uint8_t SDA = 18;
+static const uint8_t SCL = 19;
+static const uint8_t LED_BUILTIN = 13;
+
+static const uint8_t A0 = 14;
+static const uint8_t A1 = 15;
+static const uint8_t A2 = 16;
+static const uint8_t A3 = 17;
+static const uint8_t A4 = 18;
+static const uint8_t A5 = 19;
+static const uint8_t A6 = 20;
+static const uint8_t A7 = 21;
+
+#define digitalPinToPCICR(p) (((p) >= 0 && (p) <= 21) ? (&PCICR) : ((uint8_t *)0))
+#define digitalPinToPCICRbit(p) (((p) <= 7) ? 2 : (((p) <= 13) ? 0 : 1))
+#define digitalPinToPCMSK(p) (((p) <= 7) ? (&PCMSK2) : (((p) <= 13) ? (&PCMSK0) : (((p) <= 21) ? (&PCMSK1) : ((uint8_t *)0))))
+#define digitalPinToPCMSKbit(p) (((p) <= 7) ? (p) : (((p) <= 13) ? ((p) - 8) : ((p) - 14)))
+
+#ifdef ARDUINO_MAIN
+
+// On the Arduino board, digital pins are also used
+// for the analog output (software PWM). Analog input
+// pins are a separate set.
+
+// ATMEL ATMEGA8 & 168 / ARDUINO
+//
+// +-\/-+
+// PC6 1| |28 PC5 (AI 5)
+// (D 0) PD0 2| |27 PC4 (AI 4)
+// (D 1) PD1 3| |26 PC3 (AI 3)
+// (D 2) PD2 4| |25 PC2 (AI 2)
+// PWM+ (D 3) PD3 5| |24 PC1 (AI 1)
+// (D 4) PD4 6| |23 PC0 (AI 0)
+// VCC 7| |22 GND
+// GND 8| |21 AREF
+// PB6 9| |20 AVCC
+// PB7 10| |19 PB5 (D 13)
+// PWM+ (D 5) PD5 11| |18 PB4 (D 12)
+// PWM+ (D 6) PD6 12| |17 PB3 (D 11) PWM
+// (D 7) PD7 13| |16 PB2 (D 10) PWM
+// (D 8) PB0 14| |15 PB1 (D 9) PWM
+// +----+
+//
+// (PWM+ indicates the additional PWM pins on the ATmega168.)
+
+// ATMEL ATMEGA1280 / ARDUINO
+//
+// 0-7 PE0-PE7 works
+// 8-13 PB0-PB5 works
+// 14-21 PA0-PA7 works
+// 22-29 PH0-PH7 works
+// 30-35 PG5-PG0 works
+// 36-43 PC7-PC0 works
+// 44-51 PJ7-PJ0 works
+// 52-59 PL7-PL0 works
+// 60-67 PD7-PD0 works
+// A0-A7 PF0-PF7
+// A8-A15 PK0-PK7
+
+
+// these arrays map port names (e.g. port B) to the
+// appropriate addresses for various functions (e.g. reading
+// and writing)
+const uint16_t PROGMEM port_to_mode_PGM[] = {
+ NOT_A_PORT,
+ NOT_A_PORT,
+ (uint16_t) &DDRB,
+ (uint16_t) &DDRC,
+ (uint16_t) &DDRD,
+};
+
+const uint16_t PROGMEM port_to_output_PGM[] = {
+ NOT_A_PORT,
+ NOT_A_PORT,
+ (uint16_t) &PORTB,
+ (uint16_t) &PORTC,
+ (uint16_t) &PORTD,
+};
+
+const uint16_t PROGMEM port_to_input_PGM[] = {
+ NOT_A_PORT,
+ NOT_A_PORT,
+ (uint16_t) &PINB,
+ (uint16_t) &PINC,
+ (uint16_t) &PIND,
+};
+
+const uint8_t PROGMEM digital_pin_to_port_PGM[] = {
+ PD, /* 0 */
+ PD,
+ PD,
+ PD,
+ PD,
+ PD,
+ PD,
+ PD,
+ PB, /* 8 */
+ PB,
+ PB,
+ PB,
+ PB,
+ PB,
+ PC, /* 14 */
+ PC,
+ PC,
+ PC,
+ PC,
+ PC,
+};
+
+const uint8_t PROGMEM digital_pin_to_bit_mask_PGM[] = {
+ _BV(0), /* 0, port D */
+ _BV(1),
+ _BV(2),
+ _BV(3),
+ _BV(4),
+ _BV(5),
+ _BV(6),
+ _BV(7),
+ _BV(0), /* 8, port B */
+ _BV(1),
+ _BV(2),
+ _BV(3),
+ _BV(4),
+ _BV(5),
+ _BV(0), /* 14, port C */
+ _BV(1),
+ _BV(2),
+ _BV(3),
+ _BV(4),
+ _BV(5),
+};
+
+const uint8_t PROGMEM digital_pin_to_timer_PGM[] = {
+ NOT_ON_TIMER, /* 0 - port D */
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+ // on the ATmega168, digital pin 3 has hardware pwm
+#if defined(__AVR_ATmega8__)
+ NOT_ON_TIMER,
+#else
+ TIMER2B,
+#endif
+ NOT_ON_TIMER,
+ // on the ATmega168, digital pins 5 and 6 have hardware pwm
+#if defined(__AVR_ATmega8__)
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+#else
+ TIMER0B,
+ TIMER0A,
+#endif
+ NOT_ON_TIMER,
+ NOT_ON_TIMER, /* 8 - port B */
+ TIMER1A,
+ TIMER1B,
+#if defined(__AVR_ATmega8__)
+ TIMER2,
+#else
+ TIMER2A,
+#endif
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+ NOT_ON_TIMER, /* 14 - port C */
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+ NOT_ON_TIMER,
+};
+
+#endif
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/override_Serial.cpp b/tmk_core/protocol/usb_hid/override_Serial.cpp
new file mode 100644
index 000000000..e1755a5dc
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/override_Serial.cpp
@@ -0,0 +1,51 @@
+/*
+ * Null implementation of Serial to dump debug print into blackhole
+ */
+#include "Arduino.h"
+#include "sendchar.h"
+
+#include "USBAPI.h"
+
+
+void Serial_::begin(uint16_t baud_count)
+{
+}
+
+void Serial_::end(void)
+{
+}
+
+void Serial_::accept(void)
+{
+}
+
+int Serial_::available(void)
+{
+ return 0;
+}
+
+int Serial_::peek(void)
+{
+ return -1;
+}
+
+int Serial_::read(void)
+{
+ return -1;
+}
+
+void Serial_::flush(void)
+{
+}
+
+size_t Serial_::write(uint8_t c)
+{
+ sendchar(c);
+ return 1;
+}
+
+Serial_::operator bool() {
+ return true;
+}
+
+Serial_ Serial;
diff --git a/tmk_core/protocol/usb_hid/override_wiring.c b/tmk_core/protocol/usb_hid/override_wiring.c
new file mode 100644
index 000000000..1e9a94ce2
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/override_wiring.c
@@ -0,0 +1,29 @@
+/*
+ * To keep Timer0 for common/timer.c override arduino/wiring.c.
+ */
+#define __DELAY_BACKWARD_COMPATIBLE__
+#include <util/delay.h>
+#include "common/timer.h"
+#include "Arduino.h"
+
+
+unsigned long millis()
+{
+ return timer_read32();
+}
+unsigned long micros()
+{
+ return timer_read32() * 1000UL;
+}
+void delay(unsigned long ms)
+{
+ _delay_ms(ms);
+}
+void delayMicroseconds(unsigned int us)
+{
+ _delay_us(us);
+}
+void init()
+{
+ timer_init();
+}
diff --git a/tmk_core/protocol/usb_hid/parser.cpp b/tmk_core/protocol/usb_hid/parser.cpp
new file mode 100644
index 000000000..1a152ff3f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/parser.cpp
@@ -0,0 +1,33 @@
+#include "parser.h"
+#include "usb_hid.h"
+
+#include "debug.h"
+
+
+report_keyboard_t usb_hid_keyboard_report;
+uint16_t usb_hid_time_stamp;
+
+
+void KBDReportParser::Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf)
+{
+ bool is_error = false;
+ report_keyboard_t *report = (report_keyboard_t *)buf;
+
+ dprintf("KBDReport: %02X %02X", report->mods, report->reserved);
+ for (uint8_t i = 0; i < KEYBOARD_REPORT_KEYS; i++) {
+ if (IS_ERROR(report->keys[i])) {
+ is_error = true;
+ }
+ dprintf(" %02X", report->keys[i]);
+ }
+ dprint("\r\n");
+
+ // ignore error and not send report to computer
+ if (is_error) {
+ dprint("Error usage! \r\n");
+ return;
+ }
+
+ ::memcpy(&usb_hid_keyboard_report, buf, sizeof(report_keyboard_t));
+ usb_hid_time_stamp = millis();
+}
diff --git a/tmk_core/protocol/usb_hid/parser.h b/tmk_core/protocol/usb_hid/parser.h
new file mode 100644
index 000000000..703eb1ed4
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/parser.h
@@ -0,0 +1,12 @@
+#ifndef PARSER_H
+#define PARSER_H
+
+#include "hid.h"
+
+class KBDReportParser : public HIDReportParser
+{
+public:
+ virtual void Parse(HID *hid, bool is_rpt_id, uint8_t len, uint8_t *buf);
+};
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/test/Makefile b/tmk_core/protocol/usb_hid/test/Makefile
new file mode 100644
index 000000000..c093bbd4c
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/test/Makefile
@@ -0,0 +1,88 @@
+
+
+# Target file name (without extension).
+TARGET = usb_hid_test
+
+TMK_DIR = ../../..
+
+# Directory keyboard dependent files exist
+TARGET_DIR = .
+
+# MCU name
+MCU = atmega32u4
+
+
+# Processor frequency.
+# This will define a symbol, F_CPU, in all source code files equal to the
+# processor frequency in Hz. You can then use this symbol in your source code to
+# calculate timings. Do NOT tack on a 'UL' at the end, this will be done
+# automatically to create a 32-bit value in your source code.
+#
+# This will be an integer division of F_USB below, as it is sourced by
+# F_USB after it has run through any CPU prescalers. Note that this value
+# does not *change* the processor frequency - it should merely be updated to
+# reflect the processor speed set externally so that the code can use accurate
+# software delays.
+F_CPU = 16000000
+
+
+
+#
+# LUFA specific
+#
+# Target architecture (see library "Board Types" documentation).
+ARCH = AVR8
+# Input clock frequency.
+# This will define a symbol, F_USB, in all source code files equal to the
+# input clock frequency (before any prescaling is performed) in Hz. This value may
+# differ from F_CPU if prescaling is used on the latter, and is required as the
+# raw input clock is fed directly to the PLL sections of the AVR for high speed
+# clock generation for the USB and other AVR subsections. Do NOT tack on a 'UL'
+# at the end, this will be done automatically to create a 32-bit value in your
+# source code.
+#
+# If no clock division is performed on the input clock inside the AVR (via the
+# CPU clock adjust registers or the clock division fuses), this will be equal to F_CPU.
+F_USB = $(F_CPU)
+# Interrupt driven control endpoint task
+OPT_DEFS += -DINTERRUPT_CONTROL_ENDPOINT
+
+
+
+# Build Options
+# comment out to disable the options.
+#
+# Console for debug
+OPT_DEFS += -DCONSOLE_ENABLE
+
+# Boot Section Size in bytes
+# Teensy halfKay 512
+# Atmel DFU loader 4096
+# LUFA bootloader 4096
+#OPT_DEFS += -DBOOT_SIZE=4096
+
+
+
+SRC = test.cpp
+SRC += common/debug.c
+SRC += common/print.c
+
+CONFIG_H = config.h
+
+
+
+# Search Path
+VPATH += $(TARGET_DIR)
+VPATH += $(TMK_DIR)
+VPATH += $(TMK_DIR)/common
+
+
+
+# program Leonardo
+PROGRAM_CMD = avrdude -p$(MCU) -cavr109 -P$(DEV) -b57600 -Uflash:w:$(TARGET).hex
+
+
+
+include $(TMK_DIR)/protocol/usb_hid.mk
+include $(TMK_DIR)/protocol/lufa.mk
+include $(TMK_DIR)/rules.mk
diff --git a/tmk_core/protocol/usb_hid/test/config.h b/tmk_core/protocol/usb_hid/test/config.h
new file mode 100644
index 000000000..c2230fb57
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/test/config.h
@@ -0,0 +1,40 @@
+/*
+Copyright 2012 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef CONFIG_H
+#define CONFIG_H
+
+
+#define VENDOR_ID 0xFEED
+#define PRODUCT_ID 0xCAFE
+#define DEVICE_VER 0x0814
+#define MANUFACTURER t.m.k.
+#define PRODUCT USB to USB keyboard converter
+
+
+#define DESCRIPTION Product from t.m.k. keyboard firmware project
+
+
+/* matrix size */
+#define MATRIX_ROWS 32
+#define MATRIX_COLS 8
+
+
+/* key combination for command */
+#define IS_COMMAND() (keyboard_report->mods == (MOD_BIT(KB_LSHIFT) | MOD_BIT(KB_RSHIFT)))
+
+#endif
diff --git a/tmk_core/protocol/usb_hid/test/test.cpp b/tmk_core/protocol/usb_hid/test/test.cpp
new file mode 100644
index 000000000..4958f0c61
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/test/test.cpp
@@ -0,0 +1,92 @@
+#include <avr/io.h>
+#include <avr/wdt.h>
+#include <avr/power.h>
+#include <util/delay.h>
+#include <Arduino.h>
+
+// USB HID host
+#include "Usb.h"
+#include "hid.h"
+#include "hidboot.h"
+#include "parser.h"
+
+// LUFA
+#include "lufa.h"
+
+#include "debug.h"
+
+#include "leonardo_led.h"
+
+
+static USB usb_host;
+static HIDBoot<HID_PROTOCOL_KEYBOARD> kbd(&usb_host);
+static KBDReportParser kbd_parser;
+
+static void LUFA_setup(void)
+{
+ /* Disable watchdog if enabled by bootloader/fuses */
+ MCUSR &= ~(1 << WDRF);
+ wdt_disable();
+
+ /* Disable clock division */
+ clock_prescale_set(clock_div_1);
+
+ // Leonardo needs. Without this USB device is not recognized.
+ USB_Disable();
+
+ USB_Init();
+
+ // for Console_Task
+ USB_Device_EnableSOFEvents();
+}
+
+static void HID_setup()
+{
+ // Arduino Timer startup: wiring.c
+ init();
+
+ if (usb_host.Init() == -1) {
+ debug("HID init: failed\n");
+ LED_TX_OFF;
+ }
+
+ _delay_ms(200);
+
+ kbd.SetReportParser(0, (HIDReportParser*)&kbd_parser);
+}
+
+int main(void)
+{
+ // LED for debug
+ LED_TX_INIT;
+ LED_TX_ON;
+
+ print_enable = true;
+ debug_enable = true;
+ debug_matrix = true;
+ debug_keyboard = true;
+ debug_mouse = true;
+
+ LUFA_setup();
+ sei();
+
+ // wait for startup of sendchar routine
+ while (USB_DeviceState != DEVICE_STATE_Configured) ;
+ if (debug_enable) {
+ _delay_ms(1000);
+ }
+
+ HID_setup();
+
+ debug("init: done\n");
+ for (;;) {
+ usb_host.Task();
+
+#if !defined(INTERRUPT_CONTROL_ENDPOINT)
+ // LUFA Task for control request
+ USB_USBTask();
+#endif
+ }
+
+ return 0;
+}
diff --git a/tmk_core/protocol/usb_hid/usb_hid.h b/tmk_core/protocol/usb_hid/usb_hid.h
new file mode 100644
index 000000000..083b68d1f
--- /dev/null
+++ b/tmk_core/protocol/usb_hid/usb_hid.h
@@ -0,0 +1,10 @@
+#ifndef USB_HID_H
+#define USB_HID_H
+
+#include "report.h"
+
+
+extern report_keyboard_t usb_hid_keyboard_report;
+extern uint16_t usb_hid_time_stamp;
+
+#endif
diff --git a/tmk_core/protocol/vusb.mk b/tmk_core/protocol/vusb.mk
new file mode 100644
index 000000000..897b833e1
--- /dev/null
+++ b/tmk_core/protocol/vusb.mk
@@ -0,0 +1,22 @@
+VUSB_DIR = protocol/vusb
+
+OPT_DEFS += -DPROTOCOL_VUSB
+
+SRC += $(VUSB_DIR)/main.c \
+ $(VUSB_DIR)/vusb.c \
+ $(VUSB_DIR)/usbdrv/usbdrv.c \
+ $(VUSB_DIR)/usbdrv/usbdrvasm.S \
+ $(VUSB_DIR)/usbdrv/oddebug.c
+
+
+ifdef NO_UART
+SRC += $(COMMON_DIR)/sendchar_null.c
+else
+SRC += $(COMMON_DIR)/sendchar_uart.c \
+ $(COMMON_DIR)/uart.c
+endif
+
+
+# Search Path
+VPATH += $(TMK_PATH)/$(VUSB_DIR)
+VPATH += $(TMK_PATH)/$(VUSB_DIR)/usbdrv
diff --git a/tmk_core/protocol/vusb/main.c b/tmk_core/protocol/vusb/main.c
new file mode 100644
index 000000000..f6a0c7e9a
--- /dev/null
+++ b/tmk_core/protocol/vusb/main.c
@@ -0,0 +1,104 @@
+/* Name: main.c
+ * Project: hid-mouse, a very simple HID example
+ * Author: Christian Starkjohann
+ * Creation Date: 2008-04-07
+ * Tabsize: 4
+ * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: main.c 790 2010-05-30 21:00:26Z cs $
+ */
+#include <stdint.h>
+#include <avr/interrupt.h>
+#include <avr/wdt.h>
+#include <avr/sleep.h>
+#include <util/delay.h>
+#include "usbdrv.h"
+#include "oddebug.h"
+#include "vusb.h"
+#include "keyboard.h"
+#include "host.h"
+#include "timer.h"
+#include "uart.h"
+#include "debug.h"
+
+
+#define UART_BAUD_RATE 115200
+
+
+/* This is from main.c of USBaspLoader */
+static void initForUsbConnectivity(void)
+{
+ uint8_t i = 0;
+
+ usbInit();
+ /* enforce USB re-enumerate: */
+ usbDeviceDisconnect(); /* do this while interrupts are disabled */
+ while(--i){ /* fake USB disconnect for > 250 ms */
+ wdt_reset();
+ _delay_ms(1);
+ }
+ usbDeviceConnect();
+ sei();
+}
+
+int main(void)
+{
+ bool suspended = false;
+#if USB_COUNT_SOF
+ uint16_t last_timer = timer_read();
+#endif
+
+#ifdef CLKPR
+ // avoid unintentional changes of clock frequency in devices that have a
+ // clock prescaler
+ CLKPR = 0x80, CLKPR = 0;
+#endif
+#ifndef NO_UART
+ uart_init(UART_BAUD_RATE);
+#endif
+
+ keyboard_init();
+ host_set_driver(vusb_driver());
+
+ debug("initForUsbConnectivity()\n");
+ initForUsbConnectivity();
+
+ debug("main loop\n");
+ while (1) {
+#if USB_COUNT_SOF
+ if (usbSofCount != 0) {
+ suspended = false;
+ usbSofCount = 0;
+ last_timer = timer_read();
+ } else {
+ // Suspend when no SOF in 3ms-10ms(7.1.7.4 Suspending of USB1.1)
+ if (timer_elapsed(last_timer) > 5) {
+ suspended = true;
+/*
+ uart_putchar('S');
+ _delay_ms(1);
+ cli();
+ set_sleep_mode(SLEEP_MODE_PWR_DOWN);
+ sleep_enable();
+ sleep_bod_disable();
+ sei();
+ sleep_cpu();
+ sleep_disable();
+ _delay_ms(10);
+ uart_putchar('W');
+*/
+ }
+ }
+#endif
+ if (!suspended) {
+ usbPoll();
+
+ // TODO: configuration process is incosistent. it sometime fails.
+ // To prevent failing to configure NOT scan keyboard during configuration
+ if (usbConfiguration && usbInterruptIsReady()) {
+ keyboard_task();
+ }
+ vusb_transfer_keyboard();
+ }
+ }
+}
diff --git a/tmk_core/protocol/vusb/sendchar_usart.c b/tmk_core/protocol/vusb/sendchar_usart.c
new file mode 100644
index 000000000..8d24f87d1
--- /dev/null
+++ b/tmk_core/protocol/vusb/sendchar_usart.c
@@ -0,0 +1,23 @@
+/*
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ */
+#include <stdint.h>
+#include "oddebug.h"
+#include "sendchar.h"
+
+
+#if DEBUG_LEVEL > 0
+/* from oddebug.c */
+int8_t sendchar(uint8_t c)
+{
+ while(!(ODDBG_USR & (1 << ODDBG_UDRE))); /* wait for data register empty */
+ ODDBG_UDR = c;
+ return 1;
+}
+#else
+int8_t sendchar(uint8_t c)
+{
+ return 1;
+}
+#endif
diff --git a/tmk_core/protocol/vusb/usbdrv/Changelog.txt b/tmk_core/protocol/vusb/usbdrv/Changelog.txt
new file mode 100644
index 000000000..1e74180a9
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/Changelog.txt
@@ -0,0 +1,308 @@
+This file documents changes in the firmware-only USB driver for atmel's AVR
+microcontrollers. New entries are always appended to the end of the file.
+Scroll down to the bottom to see the most recent changes.
+
+2005-04-01:
+ - Implemented endpoint 1 as interrupt-in endpoint.
+ - Moved all configuration options to usbconfig.h which is not part of the
+ driver.
+ - Changed interface for usbVendorSetup().
+ - Fixed compatibility with ATMega8 device.
+ - Various minor optimizations.
+
+2005-04-11:
+ - Changed interface to application: Use usbFunctionSetup(), usbFunctionRead()
+ and usbFunctionWrite() now. Added configuration options to choose which
+ of these functions to compile in.
+ - Assembler module delivers receive data non-inverted now.
+ - Made register and bit names compatible with more AVR devices.
+
+2005-05-03:
+ - Allow address of usbRxBuf on any memory page as long as the buffer does
+ not cross 256 byte page boundaries.
+ - Better device compatibility: works with Mega88 now.
+ - Code optimization in debugging module.
+ - Documentation updates.
+
+2006-01-02:
+ - Added (free) default Vendor- and Product-IDs bought from voti.nl.
+ - Added USBID-License.txt file which defines the rules for using the free
+ shared VID/PID pair.
+ - Added readme.txt to the usbdrv directory which clarifies administrative
+ issues.
+
+2006-01-25:
+ - Added "configured state" to become more standards compliant.
+ - Added "HALT" state for interrupt endpoint.
+ - Driver passes the "USB Command Verifier" test from usb.org now.
+ - Made "serial number" a configuration option.
+ - Minor optimizations, we now recommend compiler option "-Os" for best
+ results.
+ - Added a version number to usbdrv.h
+
+2006-02-03:
+ - New configuration variable USB_BUFFER_SECTION for the memory section where
+ the USB rx buffer will go. This defaults to ".bss" if not defined. Since
+ this buffer MUST NOT cross 256 byte pages (not even touch a page at the
+ end), the user may want to pass a linker option similar to
+ "-Wl,--section-start=.mybuffer=0x800060".
+ - Provide structure for usbRequest_t.
+ - New defines for USB constants.
+ - Prepared for HID implementations.
+ - Increased data size limit for interrupt transfers to 8 bytes.
+ - New macro usbInterruptIsReady() to query interrupt buffer state.
+
+2006-02-18:
+ - Ensure that the data token which is sent as an ack to an OUT transfer is
+ always zero sized. This fixes a bug where the host reports an error after
+ sending an out transfer to the device, although all data arrived at the
+ device.
+ - Updated docs in usbdrv.h to reflect changed API in usbFunctionWrite().
+
+* Release 2006-02-20
+
+ - Give a compiler warning when compiling with debugging turned on.
+ - Added Oleg Semyonov's changes for IAR-cc compatibility.
+ - Added new (optional) functions usbDeviceConnect() and usbDeviceDisconnect()
+ (also thanks to Oleg!).
+ - Rearranged tests in usbPoll() to save a couple of instructions in the most
+ likely case that no actions are pending.
+ - We need a delay between the SET ADDRESS request until the new address
+ becomes active. This delay was handled in usbPoll() until now. Since the
+ spec says that the delay must not exceed 2ms, previous versions required
+ aggressive polling during the enumeration phase. We have now moved the
+ handling of the delay into the interrupt routine.
+ - We must not reply with NAK to a SETUP transaction. We can only achieve this
+ by making sure that the rx buffer is empty when SETUP tokens are expected.
+ We therefore don't pass zero sized data packets from the status phase of
+ a transfer to usbPoll(). This change MAY cause troubles if you rely on
+ receiving a less than 8 bytes long packet in usbFunctionWrite() to
+ identify the end of a transfer. usbFunctionWrite() will NEVER be called
+ with a zero length.
+
+* Release 2006-03-14
+
+ - Improved IAR C support: tiny memory model, more devices
+ - Added template usbconfig.h file under the name usbconfig-prototype.h
+
+* Release 2006-03-26
+
+ - Added provision for one more interrupt-in endpoint (endpoint 3).
+ - Added provision for one interrupt-out endpoint (endpoint 1).
+ - Added flowcontrol macros for USB.
+ - Added provision for custom configuration descriptor.
+ - Allow ANY two port bits for D+ and D-.
+ - Merged (optional) receive endpoint number into global usbRxToken variable.
+ - Use USB_CFG_IOPORTNAME instead of USB_CFG_IOPORT. We now construct the
+ variable name from the single port letter instead of computing the address
+ of related ports from the output-port address.
+
+* Release 2006-06-26
+
+ - Updated documentation in usbdrv.h and usbconfig-prototype.h to reflect the
+ new features.
+ - Removed "#warning" directives because IAR does not understand them. Use
+ unused static variables instead to generate a warning.
+ - Do not include <avr/io.h> when compiling with IAR.
+ - Introduced USB_CFG_DESCR_PROPS_* in usbconfig.h to configure how each
+ USB descriptor should be handled. It is now possible to provide descriptor
+ data in Flash, RAM or dynamically at runtime.
+ - STALL is now a status in usbTxLen* instead of a message. We can now conform
+ to the spec and leave the stall status pending until it is cleared.
+ - Made usbTxPacketCnt1 and usbTxPacketCnt3 public. This allows the
+ application code to reset data toggling on interrupt pipes.
+
+* Release 2006-07-18
+
+ - Added an #if !defined __ASSEMBLER__ to the warning in usbdrv.h. This fixes
+ an assembler error.
+ - usbDeviceDisconnect() takes pull-up resistor to high impedance now.
+
+* Release 2007-02-01
+
+ - Merged in some code size improvements from usbtiny (thanks to Dick
+ Streefland for these optimizations!)
+ - Special alignment requirement for usbRxBuf not required any more. Thanks
+ again to Dick Streefland for this hint!
+ - Reverted to "#warning" instead of unused static variables -- new versions
+ of IAR CC should handle this directive.
+ - Changed Open Source license to GNU GPL v2 in order to make linking against
+ other free libraries easier. We no longer require publication of the
+ circuit diagrams, but we STRONGLY encourage it. If you improve the driver
+ itself, PLEASE grant us a royalty free license to your changes for our
+ commercial license.
+
+* Release 2007-03-29
+
+ - New configuration option "USB_PUBLIC" in usbconfig.h.
+ - Set USB version number to 1.10 instead of 1.01.
+ - Code used USB_CFG_DESCR_PROPS_STRING_DEVICE and
+ USB_CFG_DESCR_PROPS_STRING_PRODUCT inconsistently. Changed all occurrences
+ to USB_CFG_DESCR_PROPS_STRING_PRODUCT.
+ - New assembler module for 16.5 MHz RC oscillator clock with PLL in receiver
+ code.
+ - New assembler module for 16 MHz crystal.
+ - usbdrvasm.S contains common code only, clock-specific parts have been moved
+ to usbdrvasm12.S, usbdrvasm16.S and usbdrvasm165.S respectively.
+
+* Release 2007-06-25
+
+ - 16 MHz module: Do SE0 check in stuffed bits as well.
+
+* Release 2007-07-07
+
+ - Define hi8(x) for IAR compiler to limit result to 8 bits. This is necessary
+ for negative values.
+ - Added 15 MHz module contributed by V. Bosch.
+ - Interrupt vector name can now be configured. This is useful if somebody
+ wants to use a different hardware interrupt than INT0.
+
+* Release 2007-08-07
+
+ - Moved handleIn3 routine in usbdrvasm16.S so that relative jump range is
+ not exceeded.
+ - More config options: USB_RX_USER_HOOK(), USB_INITIAL_DATATOKEN,
+ USB_COUNT_SOF
+ - USB_INTR_PENDING can now be a memory address, not just I/O
+
+* Release 2007-09-19
+
+ - Split out common parts of assembler modules into separate include file
+ - Made endpoint numbers configurable so that given interface definitions
+ can be matched. See USB_CFG_EP3_NUMBER in usbconfig-prototype.h.
+ - Store endpoint number for interrupt/bulk-out so that usbFunctionWriteOut()
+ can handle any number of endpoints.
+ - Define usbDeviceConnect() and usbDeviceDisconnect() even if no
+ USB_CFG_PULLUP_IOPORTNAME is defined. Directly set D+ and D- to 0 in this
+ case.
+
+* Release 2007-12-01
+
+ - Optimize usbDeviceConnect() and usbDeviceDisconnect() for less code size
+ when USB_CFG_PULLUP_IOPORTNAME is not defined.
+
+* Release 2007-12-13
+
+ - Renamed all include-only assembler modules from *.S to *.inc so that
+ people don't add them to their project sources.
+ - Distribute leap bits in tx loop more evenly for 16 MHz module.
+ - Use "macro" and "endm" instead of ".macro" and ".endm" for IAR
+ - Avoid compiler warnings for constant expr range by casting some values in
+ USB descriptors.
+
+* Release 2008-01-21
+
+ - Fixed bug in 15 and 16 MHz module where the new address set with
+ SET_ADDRESS was already accepted at the next NAK or ACK we send, not at
+ the next data packet we send. This caused problems when the host polled
+ too fast. Thanks to Alexander Neumann for his help and patience debugging
+ this issue!
+
+* Release 2008-02-05
+
+ - Fixed bug in 16.5 MHz module where a register was used in the interrupt
+ handler before it was pushed. This bug was introduced with version
+ 2007-09-19 when common parts were moved to a separate file.
+ - Optimized CRC routine (thanks to Reimar Doeffinger).
+
+* Release 2008-02-16
+
+ - Removed outdated IAR compatibility stuff (code sections).
+ - Added hook macros for USB_RESET_HOOK() and USB_SET_ADDRESS_HOOK().
+ - Added optional routine usbMeasureFrameLength() for calibration of the
+ internal RC oscillator.
+
+* Release 2008-02-28
+
+ - USB_INITIAL_DATATOKEN defaults to USBPID_DATA1 now, which means that we
+ start with sending USBPID_DATA0.
+ - Changed defaults in usbconfig-prototype.h
+ - Added free USB VID/PID pair for MIDI class devices
+ - Restructured AVR-USB as separate package, not part of PowerSwitch any more.
+
+* Release 2008-04-18
+
+ - Restructured usbdrv.c so that it is easier to read and understand.
+ - Better code optimization with gcc 4.
+ - If a second interrupt in endpoint is enabled, also add it to config
+ descriptor.
+ - Added config option for long transfers (above 254 bytes), see
+ USB_CFG_LONG_TRANSFERS in usbconfig.h.
+ - Added 20 MHz module contributed by Jeroen Benschop.
+
+* Release 2008-05-13
+
+ - Fixed bug in libs-host/hiddata.c function usbhidGetReport(): length
+ was not incremented, pointer to length was incremented instead.
+ - Added code to command line tool(s) which claims an interface. This code
+ is disabled by default, but may be necessary on newer Linux kernels.
+ - Added usbconfig.h option "USB_CFG_CHECK_DATA_TOGGLING".
+ - New header "usbportability.h" prepares ports to other development
+ environments.
+ - Long transfers (above 254 bytes) did not work when usbFunctionRead() was
+ used to supply the data. Fixed this bug. [Thanks to Alexander Neumann!]
+ - In hiddata.c (example code for sending/receiving data over HID), use
+ USB_RECIP_DEVICE instead of USB_RECIP_INTERFACE for control transfers so
+ that we need not claim the interface.
+ - in usbPoll() loop 20 times polling for RESET state instead of 10 times.
+ This accounts for the higher clock rates we now support.
+ - Added a module for 12.8 MHz RC oscillator with PLL in receiver loop.
+ - Added hook to SOF code so that oscillator can be tuned to USB frame clock.
+ - Added timeout to waitForJ loop. Helps preventing unexpected hangs.
+ - Added example code for oscillator tuning to libs-device (thanks to
+ Henrik Haftmann for the idea to this routine).
+ - Implemented option USB_CFG_SUPPRESS_INTR_CODE.
+
+* Release 2008-10-22
+
+ - Fixed libs-device/osctune.h: OSCCAL is memory address on ATMega88 and
+ similar, not offset of 0x20 needs to be added.
+ - Allow distribution under GPLv3 for those who have to link against other
+ code distributed under GPLv3.
+
+* Release 2008-11-26
+
+ - Removed libusb-win32 dependency for hid-data example in Makefile.windows.
+ It was never required and confused many people.
+ - Added extern uchar usbRxToken to usbdrv.h.
+ - Integrated a module with CRC checks at 18 MHz by Lukas Schrittwieser.
+
+* Release 2009-03-23
+
+ - Hid-mouse example used settings from hid-data example, fixed that.
+ - Renamed project to V-USB due to a trademark issue with Atmel(r).
+ - Changed CommercialLicense.txt and USBID-License.txt to make the
+ background of USB ID registration clearer.
+
+* Release 2009-04-15
+
+ - Changed CommercialLicense.txt to reflect the new range of PIDs from
+ Jason Kotzin.
+ - Removed USBID-License.txt in favor of USB-IDs-for-free.txt and
+ USB-ID-FAQ.txt
+ - Fixed a bug in the 12.8 MHz module: End Of Packet decection was made in
+ the center between bit 0 and 1 of each byte. This is where the data lines
+ are expected to change and the sampled data may therefore be nonsense.
+ We therefore check EOP ONLY if bits 0 AND 1 have both been read as 0 on D-.
+ - Fixed a bitstuffing problem in the 16 MHz module: If bit 6 was stuffed,
+ the unstuffing code in the receiver routine was 1 cycle too long. If
+ multiple bytes had the unstuffing in bit 6, the error summed up until the
+ receiver was out of sync.
+ - Included option for faster CRC routine.
+ Thanks to Slawomir Fras (BoskiDialer) for this code!
+ - Updated bits in Configuration Descriptor's bmAttributes according to
+ USB 1.1 (in particular bit 7, it is a must-be-set bit now).
+
+* Release 2009-08-22
+
+ - Moved first DBG1() after odDebugInit() in all examples.
+ - Use vector INT0_vect instead of SIG_INTERRUPT0 if defined. This makes
+ V-USB compatible with the new "p" suffix devices (e.g. ATMega328p).
+ - USB_CFG_CLOCK_KHZ setting is now required in usbconfig.h (no default any
+ more).
+ - New option USB_CFG_DRIVER_FLASH_PAGE allows boot loaders on devices with
+ more than 64 kB flash.
+ - Built-in configuration descriptor allows custom definition for second
+ endpoint now.
+
+* Release 2010-07-15
diff --git a/tmk_core/protocol/vusb/usbdrv/CommercialLicense.txt b/tmk_core/protocol/vusb/usbdrv/CommercialLicense.txt
new file mode 100644
index 000000000..11d07d9df
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/CommercialLicense.txt
@@ -0,0 +1,166 @@
+V-USB Driver Software License Agreement
+Version 2009-08-03
+
+THIS LICENSE AGREEMENT GRANTS YOU CERTAIN RIGHTS IN A SOFTWARE. YOU CAN
+ENTER INTO THIS AGREEMENT AND ACQUIRE THE RIGHTS OUTLINED BELOW BY PAYING
+THE AMOUNT ACCORDING TO SECTION 4 ("PAYMENT") TO OBJECTIVE DEVELOPMENT.
+
+
+1 DEFINITIONS
+
+1.1 "OBJECTIVE DEVELOPMENT" shall mean OBJECTIVE DEVELOPMENT Software GmbH,
+Grosse Schiffgasse 1A/7, 1020 Wien, AUSTRIA.
+
+1.2 "You" shall mean the Licensee.
+
+1.3 "V-USB" shall mean all files included in the package distributed under
+the name "vusb" by OBJECTIVE DEVELOPMENT (http://www.obdev.at/vusb/)
+unless otherwise noted. This includes the firmware-only USB device
+implementation for Atmel AVR microcontrollers, some simple device examples
+and host side software examples and libraries.
+
+
+2 LICENSE GRANTS
+
+2.1 Source Code. OBJECTIVE DEVELOPMENT shall furnish you with the source
+code of V-USB.
+
+2.2 Distribution and Use. OBJECTIVE DEVELOPMENT grants you the
+non-exclusive right to use, copy and distribute V-USB with your hardware
+product(s), restricted by the limitations in section 3 below.
+
+2.3 Modifications. OBJECTIVE DEVELOPMENT grants you the right to modify
+the source code and your copy of V-USB according to your needs.
+
+2.4 USB IDs. OBJECTIVE DEVELOPMENT furnishes you with one or two USB
+Product ID(s), sent to you in e-mail. These Product IDs are reserved
+exclusively for you. OBJECTIVE DEVELOPMENT has obtained USB Product ID
+ranges under the Vendor ID 5824 from Wouter van Ooijen (Van Ooijen
+Technische Informatica, www.voti.nl) and under the Vendor ID 8352 from
+Jason Kotzin (Clay Logic, www.claylogic.com). Both owners of the Vendor IDs
+have obtained these IDs from the USB Implementers Forum, Inc.
+(www.usb.org). OBJECTIVE DEVELOPMENT disclaims all liability which might
+arise from the assignment of USB IDs.
+
+2.5 USB Certification. Although not part of this agreement, we want to make
+it clear that you cannot become USB certified when you use V-USB or a USB
+Product ID assigned by OBJECTIVE DEVELOPMENT. AVR microcontrollers don't
+meet the electrical specifications required by the USB specification and
+the USB Implementers Forum certifies only members who bought a Vendor ID of
+their own.
+
+
+3 LICENSE RESTRICTIONS
+
+3.1 Number of Units. Only one of the following three definitions is
+applicable. Which one is determined by the amount you pay to OBJECTIVE
+DEVELOPMENT, see section 4 ("Payment") below.
+
+Hobby License: You may use V-USB according to section 2 above in no more
+than 5 hardware units. These units must not be sold for profit.
+
+Entry Level License: You may use V-USB according to section 2 above in no
+more than 150 hardware units.
+
+Professional License: You may use V-USB according to section 2 above in
+any number of hardware units, except for large scale production ("unlimited
+fair use"). Quantities below 10,000 units are not considered large scale
+production. If your reach quantities which are obviously large scale
+production, you must pay a license fee of 0.10 EUR per unit for all units
+above 10,000.
+
+3.2 Rental. You may not rent, lease, or lend V-USB or otherwise encumber
+any copy of V-USB, or any of the rights granted herein.
+
+3.3 Transfer. You may not transfer your rights under this Agreement to
+another party without OBJECTIVE DEVELOPMENT's prior written consent. If
+such consent is obtained, you may permanently transfer this License to
+another party. The recipient of such transfer must agree to all terms and
+conditions of this Agreement.
+
+3.4 Reservation of Rights. OBJECTIVE DEVELOPMENT retains all rights not
+expressly granted.
+
+3.5 Non-Exclusive Rights. Your license rights under this Agreement are
+non-exclusive.
+
+3.6 Third Party Rights. This Agreement cannot grant you rights controlled
+by third parties. In particular, you are not allowed to use the USB logo or
+other trademarks owned by the USB Implementers Forum, Inc. without their
+consent. Since such consent depends on USB certification, it should be
+noted that V-USB will not pass certification because it does not
+implement checksum verification and the microcontroller ports do not meet
+the electrical specifications.
+
+
+4 PAYMENT
+
+The payment amount depends on the variation of this agreement (according to
+section 3.1) into which you want to enter. Concrete prices are listed on
+OBJECTIVE DEVELOPMENT's web site, usually at
+http://www.obdev.at/vusb/license.html. You agree to pay the amount listed
+there to OBJECTIVE DEVELOPMENT or OBJECTIVE DEVELOPMENT's payment processor
+or reseller.
+
+
+5 COPYRIGHT AND OWNERSHIP
+
+V-USB is protected by copyright laws and international copyright
+treaties, as well as other intellectual property laws and treaties. V-USB
+is licensed, not sold.
+
+
+6 TERM AND TERMINATION
+
+6.1 Term. This Agreement shall continue indefinitely. However, OBJECTIVE
+DEVELOPMENT may terminate this Agreement and revoke the granted license and
+USB-IDs if you fail to comply with any of its terms and conditions.
+
+6.2 Survival of Terms. All provisions regarding secrecy, confidentiality
+and limitation of liability shall survive termination of this agreement.
+
+
+7 DISCLAIMER OF WARRANTY AND LIABILITY
+
+LIMITED WARRANTY. V-USB IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
+KIND. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, OBJECTIVE
+DEVELOPMENT AND ITS SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES, EITHER
+EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, AND
+NON-INFRINGEMENT, WITH REGARD TO V-USB, AND THE PROVISION OF OR FAILURE
+TO PROVIDE SUPPORT SERVICES. THIS LIMITED WARRANTY GIVES YOU SPECIFIC LEGAL
+RIGHTS. YOU MAY HAVE OTHERS, WHICH VARY FROM STATE/JURISDICTION TO
+STATE/JURISDICTION.
+
+LIMITATION OF LIABILITY. TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW,
+IN NO EVENT SHALL OBJECTIVE DEVELOPMENT OR ITS SUPPLIERS BE LIABLE FOR ANY
+SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER
+(INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS,
+BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY
+LOSS) ARISING OUT OF THE USE OF OR INABILITY TO USE V-USB OR THE
+PROVISION OF OR FAILURE TO PROVIDE SUPPORT SERVICES, EVEN IF OBJECTIVE
+DEVELOPMENT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. IN ANY
+CASE, OBJECTIVE DEVELOPMENT'S ENTIRE LIABILITY UNDER ANY PROVISION OF THIS
+AGREEMENT SHALL BE LIMITED TO THE AMOUNT ACTUALLY PAID BY YOU FOR V-USB.
+
+
+8 MISCELLANEOUS TERMS
+
+8.1 Marketing. OBJECTIVE DEVELOPMENT has the right to mention for marketing
+purposes that you entered into this agreement.
+
+8.2 Entire Agreement. This document represents the entire agreement between
+OBJECTIVE DEVELOPMENT and you. It may only be modified in writing signed by
+an authorized representative of both, OBJECTIVE DEVELOPMENT and you.
+
+8.3 Severability. In case a provision of these terms and conditions should
+be or become partly or entirely invalid, ineffective, or not executable,
+the validity of all other provisions shall not be affected.
+
+8.4 Applicable Law. This agreement is governed by the laws of the Republic
+of Austria.
+
+8.5 Responsible Courts. The responsible courts in Vienna/Austria will have
+exclusive jurisdiction regarding all disputes in connection with this
+agreement.
+
diff --git a/tmk_core/protocol/vusb/usbdrv/License.txt b/tmk_core/protocol/vusb/usbdrv/License.txt
new file mode 100644
index 000000000..ce4c3aed4
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/License.txt
@@ -0,0 +1,361 @@
+OBJECTIVE DEVELOPMENT GmbH's V-USB driver software is distributed under the
+terms and conditions of the GNU GPL version 2 or the GNU GPL version 3. It is
+your choice whether you apply the terms of version 2 or version 3. The full
+text of GPLv2 is included below. In addition to the requirements in the GPL,
+we STRONGLY ENCOURAGE you to do the following:
+
+(1) Publish your entire project on a web site and drop us a note with the URL.
+Use the form at http://www.obdev.at/vusb/feedback.html for your submission.
+
+(2) Adhere to minimum publication standards. Please include AT LEAST:
+ - a circuit diagram in PDF, PNG or GIF format
+ - full source code for the host software
+ - a readme.txt file in ASCII format which describes the purpose of the
+ project and what can be found in which directories and which files
+ - a reference to http://www.obdev.at/vusb/
+
+(3) If you improve the driver firmware itself, please give us a free license
+to your modifications for our commercial license offerings.
+
+
+
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the program's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+ Gnomovision version 69, Copyright (C) year name of author
+ Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+ `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+ <signature of Ty Coon>, 1 April 1989
+ Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs. If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library. If this is what you want to do, use the GNU Library General
+Public License instead of this License.
diff --git a/tmk_core/protocol/vusb/usbdrv/Readme.txt b/tmk_core/protocol/vusb/usbdrv/Readme.txt
new file mode 100644
index 000000000..3cff49f6f
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/Readme.txt
@@ -0,0 +1,172 @@
+This is the readme file to Objective Development's firmware-only USB driver
+for Atmel AVR microcontrollers. For more information please visit
+http://www.obdev.at/vusb/
+
+This directory contains the USB firmware only. Copy it as-is to your own
+project and add all .c and .S files to your project (these files are marked
+with an asterisk in the list below). Then copy usbconfig-prototype.h as
+usbconfig.h to your project and edit it according to your configuration.
+
+
+TECHNICAL DOCUMENTATION
+=======================
+The technical documentation (API) for the firmware driver is contained in the
+file "usbdrv.h". Please read all of it carefully! Configuration options are
+documented in "usbconfig-prototype.h".
+
+The driver consists of the following files:
+ readme.txt ............. The file you are currently reading.
+ Changelog.txt .......... Release notes for all versions of the driver.
+ usbdrv.h ............... Driver interface definitions and technical docs.
+* usbdrv.c ............... High level language part of the driver. Link this
+ module to your code!
+* usbdrvasm.S ............ Assembler part of the driver. This module is mostly
+ a stub and includes one of the usbdrvasm*.S files
+ depending on processor clock. Link this module to
+ your code!
+ usbdrvasm*.inc ......... Assembler routines for particular clock frequencies.
+ Included by usbdrvasm.S, don't link it directly!
+ asmcommon.inc .......... Common assembler routines. Included by
+ usbdrvasm*.inc, don't link it directly!
+ usbconfig-prototype.h .. Prototype for your own usbdrv.h file.
+* oddebug.c .............. Debug functions. Only used when DEBUG_LEVEL is
+ defined to a value greater than 0. Link this module
+ to your code!
+ oddebug.h .............. Interface definitions of the debug module.
+ usbportability.h ....... Header with compiler-dependent stuff.
+ usbdrvasm.asm .......... Compatibility stub for IAR-C-compiler. Use this
+ module instead of usbdrvasm.S when you assembler
+ with IAR's tools.
+ License.txt ............ Open Source license for this driver.
+ CommercialLicense.txt .. Optional commercial license for this driver.
+ USB-ID-FAQ.txt ......... General infos about USB Product- and Vendor-IDs.
+ USB-IDs-for-free.txt ... List and terms of use for free shared PIDs.
+
+(*) ... These files should be linked to your project.
+
+
+CPU CORE CLOCK FREQUENCY
+========================
+We supply assembler modules for clock frequencies of 12 MHz, 12.8 MHz, 15 MHz,
+16 MHz, 16.5 MHz 18 MHz and 20 MHz. Other clock rates are not supported. The
+actual clock rate must be configured in usbconfig.h.
+
+12 MHz Clock
+This is the traditional clock rate of V-USB because it's the lowest clock
+rate where the timing constraints of the USB spec can be met.
+
+15 MHz Clock
+Similar to 12 MHz, but some NOPs inserted. On the other hand, the higher clock
+rate allows for some loops which make the resulting code size somewhat smaller
+than the 12 MHz version.
+
+16 MHz Clock
+This clock rate has been added for users of the Arduino board and other
+ready-made boards which come with a fixed 16 MHz crystal. It's also an option
+if you need the slightly higher clock rate for performance reasons. Since
+16 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code
+is somewhat tricky and has to insert a leap cycle every third byte.
+
+12.8 MHz and 16.5 MHz Clock
+The assembler modules for these clock rates differ from the other modules
+because they have been built for an RC oscillator with only 1% precision. The
+receiver code inserts leap cycles to compensate for clock deviations. 1% is
+also the precision which can be achieved by calibrating the internal RC
+oscillator of the AVR. Please note that only AVRs with internal 64 MHz PLL
+oscillator can reach 16.5 MHz with the RC oscillator. This includes the very
+popular ATTiny25, ATTiny45, ATTiny85 series as well as the ATTiny26. Almost
+all AVRs can reach 12.8 MHz, although this is outside the specified range.
+
+See the EasyLogger example at http://www.obdev.at/vusb/easylogger.html for
+code which calibrates the RC oscillator based on the USB frame clock.
+
+18 MHz Clock
+This module is closer to the USB specification because it performs an on the
+fly CRC check for incoming packets. Packets with invalid checksum are
+discarded as required by the spec. If you also implement checks for data
+PID toggling on application level (see option USB_CFG_CHECK_DATA_TOGGLING
+in usbconfig.h for more info), this ensures data integrity. Due to the CRC
+tables and alignment requirements, this code is bigger than modules for other
+clock rates. To activate this module, you must define USB_CFG_CHECK_CRC to 1
+and USB_CFG_CLOCK_KHZ to 18000 in usbconfig.h.
+
+20 MHz Clock
+This module is for people who won't do it with less than the maximum. Since
+20 MHz is not divisible by the USB low speed bit clock of 1.5 MHz, the code
+uses similar tricks as the 16 MHz module to insert leap cycles.
+
+
+USB IDENTIFIERS
+===============
+Every USB device needs a vendor- and a product-identifier (VID and PID). VIDs
+are obtained from usb.org for a price of 1,500 USD. Once you have a VID, you
+can assign PIDs at will.
+
+Since an entry level cost of 1,500 USD is too high for most small companies
+and hobbyists, we provide some VID/PID pairs for free. See the file
+USB-IDs-for-free.txt for details.
+
+Objective Development also has some license offerings which include product
+IDs. See http://www.obdev.at/vusb/ for details.
+
+
+DEVELOPMENT SYSTEM
+==================
+This driver has been developed and optimized for the GNU compiler version 3
+and 4. We recommend that you use the GNU compiler suite because it is freely
+available. V-USB has also been ported to the IAR compiler and assembler. It
+has been tested with IAR 4.10B/W32 and 4.12A/W32 on an ATmega8 with the
+"small" and "tiny" memory model. Not every release is tested with IAR CC and
+the driver may therefore fail to compile with IAR. Please note that gcc is
+more efficient for usbdrv.c because this module has been deliberately
+optimized for gcc.
+
+Gcc version 3 produces smaller code than version 4 due to new optimizing
+capabilities which don't always improve things on 8 bit CPUs. The code size
+generated by gcc 4 can be reduced with the compiler options
+-fno-move-loop-invariants, -fno-tree-scev-cprop and
+-fno-inline-small-functions in addition to -Os. On devices with more than
+8k of flash memory, we also recommend the linker option --relax (written as
+-Wl,--relax for gcc) to convert absolute calls into relative where possible.
+
+For more information about optimizing options see:
+
+ http://www.tty1.net/blog/2008-04-29-avr-gcc-optimisations_en.html
+
+These optimizations are good for gcc 4.x. Version 3.x of gcc does not support
+most of these options and produces good code anyway.
+
+
+USING V-USB FOR FREE
+====================
+The AVR firmware driver is published under the GNU General Public License
+Version 2 (GPL2) and the GNU General Public License Version 3 (GPL3). It is
+your choice whether you apply the terms of version 2 or version 3.
+
+If you decide for the free GPL2 or GPL3, we STRONGLY ENCOURAGE you to do the
+following things IN ADDITION to the obligations from the GPL:
+
+(1) Publish your entire project on a web site and drop us a note with the URL.
+Use the form at http://www.obdev.at/vusb/feedback.html for your submission.
+If you don't have a web site, you can publish the project in obdev's
+documentation wiki at
+http://www.obdev.at/goto.php?t=vusb-wiki&p=hosted-projects.
+
+(2) Adhere to minimum publication standards. Please include AT LEAST:
+ - a circuit diagram in PDF, PNG or GIF format
+ - full source code for the host software
+ - a readme.txt file in ASCII format which describes the purpose of the
+ project and what can be found in which directories and which files
+ - a reference to http://www.obdev.at/vusb/
+
+(3) If you improve the driver firmware itself, please give us a free license
+to your modifications for our commercial license offerings.
+
+
+COMMERCIAL LICENSES FOR V-USB
+=============================
+If you don't want to publish your source code under the terms of the GPL,
+you can simply pay money for V-USB. As an additional benefit you get
+USB PIDs for free, reserved exclusively to you. See the file
+"CommercialLicense.txt" for details.
+
diff --git a/tmk_core/protocol/vusb/usbdrv/USB-ID-FAQ.txt b/tmk_core/protocol/vusb/usbdrv/USB-ID-FAQ.txt
new file mode 100644
index 000000000..d1de8fb61
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/USB-ID-FAQ.txt
@@ -0,0 +1,149 @@
+Version 2009-08-22
+
+==========================
+WHY DO WE NEED THESE IDs?
+==========================
+
+USB is more than a low level protocol for data transport. It also defines a
+common set of requests which must be understood by all devices. And as part
+of these common requests, the specification defines data structures, the
+USB Descriptors, which are used to describe the properties of the device.
+
+From the perspective of an operating system, it is therefore possible to find
+out basic properties of a device (such as e.g. the manufacturer and the name
+of the device) without a device-specific driver. This is essential because
+the operating system can choose a driver to load based on this information
+(Plug-And-Play).
+
+Among the most important properties in the Device Descriptor are the USB
+Vendor- and Product-ID. Both are 16 bit integers. The most simple form of
+driver matching is based on these IDs. The driver announces the Vendor- and
+Product-IDs of the devices it can handle and the operating system loads the
+appropriate driver when the device is connected.
+
+It is obvious that this technique only works if the pair Vendor- plus
+Product-ID is unique: Only devices which require the same driver can have the
+same pair of IDs.
+
+
+=====================================================
+HOW DOES THE USB STANDARD ENSURE THAT IDs ARE UNIQUE?
+=====================================================
+
+Since it is so important that USB IDs are unique, the USB Implementers Forum,
+Inc. (usb.org) needs a way to enforce this legally. It is not forbidden by
+law to build a device and assign it any random numbers as IDs. Usb.org
+therefore needs an agreement to regulate the use of USB IDs. The agreement
+binds only parties who agreed to it, of course. Everybody else is free to use
+any numbers for their IDs.
+
+So how can usb.org ensure that every manufacturer of USB devices enters into
+an agreement with them? They do it via trademark licensing. Usb.org has
+registered the trademark "USB", all associated logos and related terms. If
+you want to put an USB logo on your product or claim that it is USB
+compliant, you must license these trademarks from usb.org. And this is where
+you enter into an agreement. See the "USB-IF Trademark License Agreement and
+Usage Guidelines for the USB-IF Logo" at
+http://www.usb.org/developers/logo_license/.
+
+Licensing the USB trademarks requires that you buy a USB Vendor-ID from
+usb.org (one-time fee of ca. 2,000 USD), that you become a member of usb.org
+(yearly fee of ca. 4,000 USD) and that you meet all the technical
+specifications from the USB spec.
+
+This means that most hobbyists and small companies will never be able to
+become USB compliant, just because membership is so expensive. And you can't
+be compliant with a driver based on V-USB anyway, because the AVR's port pins
+don't meet the electrical specifications for USB. So, in principle, all
+hobbyists and small companies are free to choose any random numbers for their
+IDs. They have nothing to lose...
+
+There is one exception worth noting, though: If you use a sub-component which
+implements USB, the vendor of the sub-components may guarantee USB
+compliance. This might apply to some or all of FTDI's solutions.
+
+
+=======================================================================
+WHY SHOULD YOU OBTAIN USB IDs EVEN IF YOU DON'T LICENSE USB TRADEMARKS?
+=======================================================================
+
+You have learned in the previous section that you are free to choose any
+numbers for your IDs anyway. So why not do exactly this? There is still the
+technical issue. If you choose IDs which are already in use by somebody else,
+operating systems will load the wrong drivers and your device won't work.
+Even if you choose IDs which are not currently in use, they may be in use in
+the next version of the operating system or even after an automatic update.
+
+So what you need is a pair of Vendor- and Product-IDs for which you have the
+guarantee that no USB compliant product uses them. This implies that no
+operating system will ever ship with drivers responsible for these IDs.
+
+
+==============================================
+HOW DOES OBJECTIVE DEVELOPMENT HANDLE USB IDs?
+==============================================
+
+Objective Development gives away pairs of USB-IDs with their V-USB licenses.
+In order to ensure that these IDs are unique, Objective Development has an
+agreement with the company/person who has bought the USB Vendor-ID from
+usb.org. This agreement ensures that a range of USB Product-IDs is reserved
+for assignment by Objective Development and that the owner of the Vendor-ID
+won't give it to anybody else.
+
+This means that you have to trust three parties to ensure uniqueness of
+your IDs:
+
+ - Objective Development, that they don't give the same PID to more than
+ one person.
+ - The owner of the Vendor-ID that they don't assign PIDs from the range
+ assigned to Objective Development to anybody else.
+ - Usb.org that they don't assign the same Vendor-ID a second time.
+
+
+==================================
+WHO IS THE OWNER OF THE VENDOR-ID?
+==================================
+
+Objective Development has obtained ranges of USB Product-IDs under two
+Vendor-IDs: Under Vendor-ID 5824 from Wouter van Ooijen (Van Ooijen
+Technische Informatica, www.voti.nl) and under Vendor-ID 8352 from Jason
+Kotzin (Clay Logic, www.claylogic.com). Both VID owners have received their
+Vendor-ID directly from usb.org.
+
+
+=========================================================================
+CAN I USE USB-IDs FROM OBJECTIVE DEVELOPMENT WITH OTHER DRIVERS/HARDWARE?
+=========================================================================
+
+The short answer is: Yes. All you get is a guarantee that the IDs are never
+assigned to anybody else. What more do you need?
+
+
+============================
+WHAT ABOUT SHARED ID PAIRS?
+============================
+
+Objective Development has reserved some PID/VID pairs for shared use. You
+have no guarantee of uniqueness for them, except that no USB compliant device
+uses them. In order to avoid technical problems, we must ensure that all
+devices with the same pair of IDs use the same driver on kernel level. For
+details, see the file USB-IDs-for-free.txt.
+
+
+======================================================
+I HAVE HEARD THAT SUB-LICENSING OF USB-IDs IS ILLEGAL?
+======================================================
+
+A 16 bit integer number cannot be protected by copyright laws. It is not
+sufficiently complex. And since none of the parties involved entered into the
+USB-IF Trademark License Agreement, we are not bound by this agreement. So
+there is no reason why it should be illegal to sub-license USB-IDs.
+
+
+=============================================
+WHO IS LIABLE IF THERE ARE INCOMPATIBILITIES?
+=============================================
+
+Objective Development disclaims all liabilities which might arise from the
+assignment of IDs. If you guarantee product features to your customers
+without proper disclaimer, YOU are liable for that.
diff --git a/tmk_core/protocol/vusb/usbdrv/USB-IDs-for-free.txt b/tmk_core/protocol/vusb/usbdrv/USB-IDs-for-free.txt
new file mode 100644
index 000000000..2f4d59ad1
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/USB-IDs-for-free.txt
@@ -0,0 +1,148 @@
+Version 2009-08-22
+
+===========================
+FREE USB-IDs FOR SHARED USE
+===========================
+
+Objective Development has reserved a set of USB Product-IDs for use according
+to the guidelines outlined below. For more information about the concept of
+USB IDs please see the file USB-ID-FAQ.txt. Objective Development guarantees
+that the IDs listed below are not used by any USB compliant devices.
+
+
+====================
+MECHANISM OF SHARING
+====================
+
+From a technical point of view, two different devices can share the same USB
+Vendor- and Product-ID if they require the same driver on operating system
+level. We make use of this fact by assigning separate IDs for various device
+classes. On application layer, devices must be distinguished by their textual
+name or serial number. We offer separate sets of IDs for discrimination by
+textual name and for serial number.
+
+Examples for shared use of USB IDs are included with V-USB in the "examples"
+subdirectory.
+
+
+======================================
+IDs FOR DISCRIMINATION BY TEXTUAL NAME
+======================================
+
+If you use one of the IDs listed below, your device and host-side software
+must conform to these rules:
+
+(1) The USB device MUST provide a textual representation of the manufacturer
+and product identification. The manufacturer identification MUST be available
+at least in USB language 0x0409 (English/US).
+
+(2) The textual manufacturer identification MUST contain either an Internet
+domain name (e.g. "mycompany.com") registered and owned by you, or an e-mail
+address under your control (e.g. "myname@gmx.net"). You can embed the domain
+name or e-mail address in any string you like, e.g. "Objective Development
+http://www.obdev.at/vusb/".
+
+(3) You are responsible for retaining ownership of the domain or e-mail
+address for as long as any of your products are in use.
+
+(4) You may choose any string for the textual product identification, as long
+as this string is unique within the scope of your textual manufacturer
+identification.
+
+(5) Application side device look-up MUST be based on the textual manufacturer
+and product identification in addition to VID/PID matching. The driver
+matching MUST be a comparison of the entire strings, NOT a sub-string match.
+
+(6) For devices which implement a particular USB device class (e.g. HID), the
+operating system's default class driver MUST be used. If an operating system
+driver for Vendor Class devices is needed, this driver must be libusb or
+libusb-win32 (see http://libusb.org/ and
+http://libusb-win32.sourceforge.net/).
+
+Table if IDs for discrimination by textual name:
+
+PID dec (hex) | VID dec (hex) | Description of use
+==============+===============+============================================
+1500 (0x05dc) | 5824 (0x16c0) | For Vendor Class devices with libusb
+--------------+---------------+--------------------------------------------
+1503 (0x05df) | 5824 (0x16c0) | For generic HID class devices (which are
+ | | NOT mice, keyboards or joysticks)
+--------------+---------------+--------------------------------------------
+1505 (0x05e1) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
+--------------+---------------+--------------------------------------------
+1508 (0x05e4) | 5824 (0x16c0) | For MIDI class devices
+--------------+---------------+--------------------------------------------
+
+Note that Windows caches the textual product- and vendor-description for
+mice, keyboards and joysticks. Name-bsed discrimination is therefore not
+recommended for these device classes.
+
+
+=======================================
+IDs FOR DISCRIMINATION BY SERIAL NUMBER
+=======================================
+
+If you use one of the IDs listed below, your device and host-side software
+must conform to these rules:
+
+(1) The USB device MUST provide a textual representation of the serial
+number. The serial number string MUST be available at least in USB language
+0x0409 (English/US).
+
+(2) The serial number MUST start with either an Internet domain name (e.g.
+"mycompany.com") registered and owned by you, or an e-mail address under your
+control (e.g. "myname@gmx.net"), both terminated with a colon (":") character.
+You MAY append any string you like for further discrimination of your devices.
+
+(3) You are responsible for retaining ownership of the domain or e-mail
+address for as long as any of your products are in use.
+
+(5) Application side device look-up MUST be based on the serial number string
+in addition to VID/PID matching. The matching must start at the first
+character of the serial number string and include the colon character
+terminating your domain or e-mail address. It MAY stop anywhere after that.
+
+(6) For devices which implement a particular USB device class (e.g. HID), the
+operating system's default class driver MUST be used. If an operating system
+driver for Vendor Class devices is needed, this driver must be libusb or
+libusb-win32 (see http://libusb.org/ and
+http://libusb-win32.sourceforge.net/).
+
+Table if IDs for discrimination by serial number string:
+
+PID dec (hex) | VID dec (hex) | Description of use
+===============+===============+===========================================
+10200 (0x27d8) | 5824 (0x16c0) | For Vendor Class devices with libusb
+---------------+---------------+-------------------------------------------
+10201 (0x27d9) | 5824 (0x16c0) | For generic HID class devices (which are
+ | | NOT mice, keyboards or joysticks)
+---------------+---------------+-------------------------------------------
+10202 (0x27da) | 5824 (0x16c0) | For USB Mice
+---------------+---------------+-------------------------------------------
+10203 (0x27db) | 5824 (0x16c0) | For USB Keyboards
+---------------+---------------+-------------------------------------------
+10204 (0x27db) | 5824 (0x16c0) | For USB Joysticks
+---------------+---------------+-------------------------------------------
+10205 (0x27dc) | 5824 (0x16c0) | For CDC-ACM class devices (modems)
+---------------+---------------+-------------------------------------------
+10206 (0x27dd) | 5824 (0x16c0) | For MIDI class devices
+---------------+---------------+-------------------------------------------
+
+
+=================
+ORIGIN OF USB-IDs
+=================
+
+OBJECTIVE DEVELOPMENT Software GmbH has obtained all VID/PID pairs listed
+here from Wouter van Ooijen (see www.voti.nl) for exclusive disposition.
+Wouter van Ooijen has obtained the VID from the USB Implementers Forum, Inc.
+(see www.usb.org). The VID is registered for the company name "Van Ooijen
+Technische Informatica".
+
+
+==========
+DISCLAIMER
+==========
+
+OBJECTIVE DEVELOPMENT Software GmbH disclaims all liability for any
+problems which are caused by the shared use of these VID/PID pairs.
diff --git a/tmk_core/protocol/vusb/usbdrv/asmcommon.inc b/tmk_core/protocol/vusb/usbdrv/asmcommon.inc
new file mode 100644
index 000000000..07d692be3
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/asmcommon.inc
@@ -0,0 +1,188 @@
+/* Name: asmcommon.inc
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2007-11-05
+ * Tabsize: 4
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * Revision: $Id$
+ */
+
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
+ * appropriate implementation!
+ */
+
+/*
+General Description:
+This file contains assembler code which is shared among the USB driver
+implementations for different CPU cocks. Since the code must be inserted
+in the middle of the module, it's split out into this file and #included.
+
+Jump destinations called from outside:
+ sofError: Called when no start sequence was found.
+ se0: Called when a package has been successfully received.
+ overflow: Called when receive buffer overflows.
+ doReturn: Called after sending data.
+
+Outside jump destinations used by this module:
+ waitForJ: Called to receive an already arriving packet.
+ sendAckAndReti:
+ sendNakAndReti:
+ sendCntAndReti:
+ usbSendAndReti:
+
+The following macros must be defined before this file is included:
+ .macro POP_STANDARD
+ .endm
+ .macro POP_RETI
+ .endm
+*/
+
+#define token x1
+
+overflow:
+ ldi x2, 1<<USB_INTR_PENDING_BIT
+ USB_STORE_PENDING(x2) ; clear any pending interrupts
+ignorePacket:
+ clr token
+ rjmp storeTokenAndReturn
+
+;----------------------------------------------------------------------------
+; Processing of received packet (numbers in brackets are cycles after center of SE0)
+;----------------------------------------------------------------------------
+;This is the only non-error exit point for the software receiver loop
+;we don't check any CRCs here because there is no time left.
+se0:
+ subi cnt, USB_BUFSIZE ;[5]
+ neg cnt ;[6]
+ sub YL, cnt ;[7]
+ sbci YH, 0 ;[8]
+ ldi x2, 1<<USB_INTR_PENDING_BIT ;[9]
+ USB_STORE_PENDING(x2) ;[10] clear pending intr and check flag later. SE0 should be over.
+ ld token, y ;[11]
+ cpi token, USBPID_DATA0 ;[13]
+ breq handleData ;[14]
+ cpi token, USBPID_DATA1 ;[15]
+ breq handleData ;[16]
+ lds shift, usbDeviceAddr;[17]
+ ldd x2, y+1 ;[19] ADDR and 1 bit endpoint number
+ lsl x2 ;[21] shift out 1 bit endpoint number
+ cpse x2, shift ;[22]
+ rjmp ignorePacket ;[23]
+/* only compute endpoint number in x3 if required later */
+#if USB_CFG_HAVE_INTRIN_ENDPOINT || USB_CFG_IMPLEMENT_FN_WRITEOUT
+ ldd x3, y+2 ;[24] endpoint number + crc
+ rol x3 ;[26] shift in LSB of endpoint
+#endif
+ cpi token, USBPID_IN ;[27]
+ breq handleIn ;[28]
+ cpi token, USBPID_SETUP ;[29]
+ breq handleSetupOrOut ;[30]
+ cpi token, USBPID_OUT ;[31]
+ brne ignorePacket ;[32] must be ack, nak or whatever
+; rjmp handleSetupOrOut ; fallthrough
+
+;Setup and Out are followed by a data packet two bit times (16 cycles) after
+;the end of SE0. The sync code allows up to 40 cycles delay from the start of
+;the sync pattern until the first bit is sampled. That's a total of 56 cycles.
+handleSetupOrOut: ;[32]
+#if USB_CFG_IMPLEMENT_FN_WRITEOUT /* if we have data for endpoint != 0, set usbCurrentTok to address */
+ andi x3, 0xf ;[32]
+ breq storeTokenAndReturn ;[33]
+ mov token, x3 ;[34] indicate that this is endpoint x OUT
+#endif
+storeTokenAndReturn:
+ sts usbCurrentTok, token;[35]
+doReturn:
+ POP_STANDARD ;[37] 12...16 cycles
+ USB_LOAD_PENDING(YL) ;[49]
+ sbrc YL, USB_INTR_PENDING_BIT;[50] check whether data is already arriving
+ rjmp waitForJ ;[51] save the pops and pushes -- a new interrupt is already pending
+sofError:
+ POP_RETI ;macro call
+ reti
+
+handleData:
+#if USB_CFG_CHECK_CRC
+ CRC_CLEANUP_AND_CHECK ; jumps to ignorePacket if CRC error
+#endif
+ lds shift, usbCurrentTok;[18]
+ tst shift ;[20]
+ breq doReturn ;[21]
+ lds x2, usbRxLen ;[22]
+ tst x2 ;[24]
+ brne sendNakAndReti ;[25]
+; 2006-03-11: The following two lines fix a problem where the device was not
+; recognized if usbPoll() was called less frequently than once every 4 ms.
+ cpi cnt, 4 ;[26] zero sized data packets are status phase only -- ignore and ack
+ brmi sendAckAndReti ;[27] keep rx buffer clean -- we must not NAK next SETUP
+#if USB_CFG_CHECK_DATA_TOGGLING
+ sts usbCurrentDataToken, token ; store for checking by C code
+#endif
+ sts usbRxLen, cnt ;[28] store received data, swap buffers
+ sts usbRxToken, shift ;[30]
+ lds x2, usbInputBufOffset;[32] swap buffers
+ ldi cnt, USB_BUFSIZE ;[34]
+ sub cnt, x2 ;[35]
+ sts usbInputBufOffset, cnt;[36] buffers now swapped
+ rjmp sendAckAndReti ;[38] 40 + 17 = 57 until SOP
+
+handleIn:
+;We don't send any data as long as the C code has not processed the current
+;input data and potentially updated the output data. That's more efficient
+;in terms of code size than clearing the tx buffers when a packet is received.
+ lds x1, usbRxLen ;[30]
+ cpi x1, 1 ;[32] negative values are flow control, 0 means "buffer free"
+ brge sendNakAndReti ;[33] unprocessed input packet?
+ ldi x1, USBPID_NAK ;[34] prepare value for usbTxLen
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
+ andi x3, 0xf ;[35] x3 contains endpoint
+#if USB_CFG_SUPPRESS_INTR_CODE
+ brne sendNakAndReti ;[36]
+#else
+ brne handleIn1 ;[36]
+#endif
+#endif
+ lds cnt, usbTxLen ;[37]
+ sbrc cnt, 4 ;[39] all handshake tokens have bit 4 set
+ rjmp sendCntAndReti ;[40] 42 + 16 = 58 until SOP
+ sts usbTxLen, x1 ;[41] x1 == USBPID_NAK from above
+ ldi YL, lo8(usbTxBuf) ;[43]
+ ldi YH, hi8(usbTxBuf) ;[44]
+ rjmp usbSendAndReti ;[45] 57 + 12 = 59 until SOP
+
+; Comment about when to set usbTxLen to USBPID_NAK:
+; We should set it back when we receive the ACK from the host. This would
+; be simple to implement: One static variable which stores whether the last
+; tx was for endpoint 0 or 1 and a compare in the receiver to distinguish the
+; ACK. However, we set it back immediately when we send the package,
+; assuming that no error occurs and the host sends an ACK. We save one byte
+; RAM this way and avoid potential problems with endless retries. The rest of
+; the driver assumes error-free transfers anyway.
+
+#if !USB_CFG_SUPPRESS_INTR_CODE && USB_CFG_HAVE_INTRIN_ENDPOINT /* placed here due to relative jump range */
+handleIn1: ;[38]
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
+; 2006-06-10 as suggested by O.Tamura: support second INTR IN / BULK IN endpoint
+ cpi x3, USB_CFG_EP3_NUMBER;[38]
+ breq handleIn3 ;[39]
+#endif
+ lds cnt, usbTxLen1 ;[40]
+ sbrc cnt, 4 ;[42] all handshake tokens have bit 4 set
+ rjmp sendCntAndReti ;[43] 47 + 16 = 63 until SOP
+ sts usbTxLen1, x1 ;[44] x1 == USBPID_NAK from above
+ ldi YL, lo8(usbTxBuf1) ;[46]
+ ldi YH, hi8(usbTxBuf1) ;[47]
+ rjmp usbSendAndReti ;[48] 50 + 12 = 62 until SOP
+
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
+handleIn3:
+ lds cnt, usbTxLen3 ;[41]
+ sbrc cnt, 4 ;[43]
+ rjmp sendCntAndReti ;[44] 49 + 16 = 65 until SOP
+ sts usbTxLen3, x1 ;[45] x1 == USBPID_NAK from above
+ ldi YL, lo8(usbTxBuf3) ;[47]
+ ldi YH, hi8(usbTxBuf3) ;[48]
+ rjmp usbSendAndReti ;[49] 51 + 12 = 63 until SOP
+#endif
+#endif
diff --git a/tmk_core/protocol/vusb/usbdrv/oddebug.c b/tmk_core/protocol/vusb/usbdrv/oddebug.c
new file mode 100644
index 000000000..945457c1f
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/oddebug.c
@@ -0,0 +1,50 @@
+/* Name: oddebug.c
+ * Project: AVR library
+ * Author: Christian Starkjohann
+ * Creation Date: 2005-01-16
+ * Tabsize: 4
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: oddebug.c 692 2008-11-07 15:07:40Z cs $
+ */
+
+#include "oddebug.h"
+
+#if DEBUG_LEVEL > 0
+
+#warning "Never compile production devices with debugging enabled"
+
+static void uartPutc(char c)
+{
+ while(!(ODDBG_USR & (1 << ODDBG_UDRE))); /* wait for data register empty */
+ ODDBG_UDR = c;
+}
+
+static uchar hexAscii(uchar h)
+{
+ h &= 0xf;
+ if(h >= 10)
+ h += 'a' - (uchar)10 - '0';
+ h += '0';
+ return h;
+}
+
+static void printHex(uchar c)
+{
+ uartPutc(hexAscii(c >> 4));
+ uartPutc(hexAscii(c));
+}
+
+void odDebug(uchar prefix, uchar *data, uchar len)
+{
+ printHex(prefix);
+ uartPutc(':');
+ while(len--){
+ uartPutc(' ');
+ printHex(*data++);
+ }
+ uartPutc('\r');
+ uartPutc('\n');
+}
+
+#endif
diff --git a/tmk_core/protocol/vusb/usbdrv/oddebug.h b/tmk_core/protocol/vusb/usbdrv/oddebug.h
new file mode 100644
index 000000000..d61309daa
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/oddebug.h
@@ -0,0 +1,123 @@
+/* Name: oddebug.h
+ * Project: AVR library
+ * Author: Christian Starkjohann
+ * Creation Date: 2005-01-16
+ * Tabsize: 4
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: oddebug.h 692 2008-11-07 15:07:40Z cs $
+ */
+
+#ifndef __oddebug_h_included__
+#define __oddebug_h_included__
+
+/*
+General Description:
+This module implements a function for debug logs on the serial line of the
+AVR microcontroller. Debugging can be configured with the define
+'DEBUG_LEVEL'. If this macro is not defined or defined to 0, all debugging
+calls are no-ops. If it is 1, DBG1 logs will appear, but not DBG2. If it is
+2, DBG1 and DBG2 logs will be printed.
+
+A debug log consists of a label ('prefix') to indicate which debug log created
+the output and a memory block to dump in hex ('data' and 'len').
+*/
+
+
+#ifndef F_CPU
+# define F_CPU 12000000 /* 12 MHz */
+#endif
+
+/* make sure we have the UART defines: */
+#include "usbportability.h"
+
+#ifndef uchar
+# define uchar unsigned char
+#endif
+
+#if DEBUG_LEVEL > 0 && !(defined TXEN || defined TXEN0) /* no UART in device */
+# warning "Debugging disabled because device has no UART"
+# undef DEBUG_LEVEL
+#endif
+
+#ifndef DEBUG_LEVEL
+# define DEBUG_LEVEL 0
+#endif
+
+/* ------------------------------------------------------------------------- */
+
+#if DEBUG_LEVEL > 0
+# define DBG1(prefix, data, len) odDebug(prefix, data, len)
+#else
+# define DBG1(prefix, data, len)
+#endif
+
+#if DEBUG_LEVEL > 1
+# define DBG2(prefix, data, len) odDebug(prefix, data, len)
+#else
+# define DBG2(prefix, data, len)
+#endif
+
+/* ------------------------------------------------------------------------- */
+
+#if DEBUG_LEVEL > 0
+extern void odDebug(uchar prefix, uchar *data, uchar len);
+
+/* Try to find our control registers; ATMEL likes to rename these */
+
+#if defined UBRR
+# define ODDBG_UBRR UBRR
+#elif defined UBRRL
+# define ODDBG_UBRR UBRRL
+#elif defined UBRR0
+# define ODDBG_UBRR UBRR0
+#elif defined UBRR0L
+# define ODDBG_UBRR UBRR0L
+#endif
+
+#if defined UCR
+# define ODDBG_UCR UCR
+#elif defined UCSRB
+# define ODDBG_UCR UCSRB
+#elif defined UCSR0B
+# define ODDBG_UCR UCSR0B
+#endif
+
+#if defined TXEN
+# define ODDBG_TXEN TXEN
+#else
+# define ODDBG_TXEN TXEN0
+#endif
+
+#if defined USR
+# define ODDBG_USR USR
+#elif defined UCSRA
+# define ODDBG_USR UCSRA
+#elif defined UCSR0A
+# define ODDBG_USR UCSR0A
+#endif
+
+#if defined UDRE
+# define ODDBG_UDRE UDRE
+#else
+# define ODDBG_UDRE UDRE0
+#endif
+
+#if defined UDR
+# define ODDBG_UDR UDR
+#elif defined UDR0
+# define ODDBG_UDR UDR0
+#endif
+
+static inline void odDebugInit(void)
+{
+ ODDBG_UCR |= (1<<ODDBG_TXEN);
+ ODDBG_UBRR = F_CPU / (19200 * 16L) - 1;
+}
+#else
+# define odDebugInit()
+#endif
+
+/* ------------------------------------------------------------------------- */
+
+#endif /* __oddebug_h_included__ */
diff --git a/tmk_core/protocol/vusb/usbdrv/usbconfig-prototype.h b/tmk_core/protocol/vusb/usbdrv/usbconfig-prototype.h
new file mode 100644
index 000000000..847710e2a
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbconfig-prototype.h
@@ -0,0 +1,376 @@
+/* Name: usbconfig.h
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2005-04-01
+ * Tabsize: 4
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: usbconfig-prototype.h 785 2010-05-30 17:57:07Z cs $
+ */
+
+#ifndef __usbconfig_h_included__
+#define __usbconfig_h_included__
+
+/*
+General Description:
+This file is an example configuration (with inline documentation) for the USB
+driver. It configures V-USB for USB D+ connected to Port D bit 2 (which is
+also hardware interrupt 0 on many devices) and USB D- to Port D bit 4. You may
+wire the lines to any other port, as long as D+ is also wired to INT0 (or any
+other hardware interrupt, as long as it is the highest level interrupt, see
+section at the end of this file).
++ To create your own usbconfig.h file, copy this file to your project's
++ firmware source directory) and rename it to "usbconfig.h".
++ Then edit it accordingly.
+*/
+
+/* ---------------------------- Hardware Config ---------------------------- */
+
+#define USB_CFG_IOPORTNAME D
+/* This is the port where the USB bus is connected. When you configure it to
+ * "B", the registers PORTB, PINB and DDRB will be used.
+ */
+#define USB_CFG_DMINUS_BIT 4
+/* This is the bit number in USB_CFG_IOPORT where the USB D- line is connected.
+ * This may be any bit in the port.
+ */
+#define USB_CFG_DPLUS_BIT 2
+/* This is the bit number in USB_CFG_IOPORT where the USB D+ line is connected.
+ * This may be any bit in the port. Please note that D+ must also be connected
+ * to interrupt pin INT0! [You can also use other interrupts, see section
+ * "Optional MCU Description" below, or you can connect D- to the interrupt, as
+ * it is required if you use the USB_COUNT_SOF feature. If you use D- for the
+ * interrupt, the USB interrupt will also be triggered at Start-Of-Frame
+ * markers every millisecond.]
+ */
+#define USB_CFG_CLOCK_KHZ (F_CPU/1000)
+/* Clock rate of the AVR in kHz. Legal values are 12000, 12800, 15000, 16000,
+ * 16500, 18000 and 20000. The 12.8 MHz and 16.5 MHz versions of the code
+ * require no crystal, they tolerate +/- 1% deviation from the nominal
+ * frequency. All other rates require a precision of 2000 ppm and thus a
+ * crystal!
+ * Since F_CPU should be defined to your actual clock rate anyway, you should
+ * not need to modify this setting.
+ */
+#define USB_CFG_CHECK_CRC 0
+/* Define this to 1 if you want that the driver checks integrity of incoming
+ * data packets (CRC checks). CRC checks cost quite a bit of code size and are
+ * currently only available for 18 MHz crystal clock. You must choose
+ * USB_CFG_CLOCK_KHZ = 18000 if you enable this option.
+ */
+
+/* ----------------------- Optional Hardware Config ------------------------ */
+
+/* #define USB_CFG_PULLUP_IOPORTNAME D */
+/* If you connect the 1.5k pullup resistor from D- to a port pin instead of
+ * V+, you can connect and disconnect the device from firmware by calling
+ * the macros usbDeviceConnect() and usbDeviceDisconnect() (see usbdrv.h).
+ * This constant defines the port on which the pullup resistor is connected.
+ */
+/* #define USB_CFG_PULLUP_BIT 4 */
+/* This constant defines the bit number in USB_CFG_PULLUP_IOPORT (defined
+ * above) where the 1.5k pullup resistor is connected. See description
+ * above for details.
+ */
+
+/* --------------------------- Functional Range ---------------------------- */
+
+#define USB_CFG_HAVE_INTRIN_ENDPOINT 0
+/* Define this to 1 if you want to compile a version with two endpoints: The
+ * default control endpoint 0 and an interrupt-in endpoint (any other endpoint
+ * number).
+ */
+#define USB_CFG_HAVE_INTRIN_ENDPOINT3 0
+/* Define this to 1 if you want to compile a version with three endpoints: The
+ * default control endpoint 0, an interrupt-in endpoint 3 (or the number
+ * configured below) and a catch-all default interrupt-in endpoint as above.
+ * You must also define USB_CFG_HAVE_INTRIN_ENDPOINT to 1 for this feature.
+ */
+#define USB_CFG_EP3_NUMBER 3
+/* If the so-called endpoint 3 is used, it can now be configured to any other
+ * endpoint number (except 0) with this macro. Default if undefined is 3.
+ */
+/* #define USB_INITIAL_DATATOKEN USBPID_DATA1 */
+/* The above macro defines the startup condition for data toggling on the
+ * interrupt/bulk endpoints 1 and 3. Defaults to USBPID_DATA1.
+ * Since the token is toggled BEFORE sending any data, the first packet is
+ * sent with the oposite value of this configuration!
+ */
+#define USB_CFG_IMPLEMENT_HALT 0
+/* Define this to 1 if you also want to implement the ENDPOINT_HALT feature
+ * for endpoint 1 (interrupt endpoint). Although you may not need this feature,
+ * it is required by the standard. We have made it a config option because it
+ * bloats the code considerably.
+ */
+#define USB_CFG_SUPPRESS_INTR_CODE 0
+/* Define this to 1 if you want to declare interrupt-in endpoints, but don't
+ * want to send any data over them. If this macro is defined to 1, functions
+ * usbSetInterrupt() and usbSetInterrupt3() are omitted. This is useful if
+ * you need the interrupt-in endpoints in order to comply to an interface
+ * (e.g. HID), but never want to send any data. This option saves a couple
+ * of bytes in flash memory and the transmit buffers in RAM.
+ */
+#define USB_CFG_INTR_POLL_INTERVAL 10
+/* If you compile a version with endpoint 1 (interrupt-in), this is the poll
+ * interval. The value is in milliseconds and must not be less than 10 ms for
+ * low speed devices.
+ */
+#define USB_CFG_IS_SELF_POWERED 0
+/* Define this to 1 if the device has its own power supply. Set it to 0 if the
+ * device is powered from the USB bus.
+ */
+#define USB_CFG_MAX_BUS_POWER 100
+/* Set this variable to the maximum USB bus power consumption of your device.
+ * The value is in milliamperes. [It will be divided by two since USB
+ * communicates power requirements in units of 2 mA.]
+ */
+#define USB_CFG_IMPLEMENT_FN_WRITE 0
+/* Set this to 1 if you want usbFunctionWrite() to be called for control-out
+ * transfers. Set it to 0 if you don't need it and want to save a couple of
+ * bytes.
+ */
+#define USB_CFG_IMPLEMENT_FN_READ 0
+/* Set this to 1 if you need to send control replies which are generated
+ * "on the fly" when usbFunctionRead() is called. If you only want to send
+ * data from a static buffer, set it to 0 and return the data from
+ * usbFunctionSetup(). This saves a couple of bytes.
+ */
+#define USB_CFG_IMPLEMENT_FN_WRITEOUT 0
+/* Define this to 1 if you want to use interrupt-out (or bulk out) endpoints.
+ * You must implement the function usbFunctionWriteOut() which receives all
+ * interrupt/bulk data sent to any endpoint other than 0. The endpoint number
+ * can be found in 'usbRxToken'.
+ */
+#define USB_CFG_HAVE_FLOWCONTROL 0
+/* Define this to 1 if you want flowcontrol over USB data. See the definition
+ * of the macros usbDisableAllRequests() and usbEnableAllRequests() in
+ * usbdrv.h.
+ */
+#define USB_CFG_DRIVER_FLASH_PAGE 0
+/* If the device has more than 64 kBytes of flash, define this to the 64 k page
+ * where the driver's constants (descriptors) are located. Or in other words:
+ * Define this to 1 for boot loaders on the ATMega128.
+ */
+#define USB_CFG_LONG_TRANSFERS 0
+/* Define this to 1 if you want to send/receive blocks of more than 254 bytes
+ * in a single control-in or control-out transfer. Note that the capability
+ * for long transfers increases the driver size.
+ */
+/* #define USB_RX_USER_HOOK(data, len) if(usbRxToken == (uchar)USBPID_SETUP) blinkLED(); */
+/* This macro is a hook if you want to do unconventional things. If it is
+ * defined, it's inserted at the beginning of received message processing.
+ * If you eat the received message and don't want default processing to
+ * proceed, do a return after doing your things. One possible application
+ * (besides debugging) is to flash a status LED on each packet.
+ */
+/* #define USB_RESET_HOOK(resetStarts) if(!resetStarts){hadUsbReset();} */
+/* This macro is a hook if you need to know when an USB RESET occurs. It has
+ * one parameter which distinguishes between the start of RESET state and its
+ * end.
+ */
+/* #define USB_SET_ADDRESS_HOOK() hadAddressAssigned(); */
+/* This macro (if defined) is executed when a USB SET_ADDRESS request was
+ * received.
+ */
+#define USB_COUNT_SOF 0
+/* define this macro to 1 if you need the global variable "usbSofCount" which
+ * counts SOF packets. This feature requires that the hardware interrupt is
+ * connected to D- instead of D+.
+ */
+/* #ifdef __ASSEMBLER__
+ * macro myAssemblerMacro
+ * in YL, TCNT0
+ * sts timer0Snapshot, YL
+ * endm
+ * #endif
+ * #define USB_SOF_HOOK myAssemblerMacro
+ * This macro (if defined) is executed in the assembler module when a
+ * Start Of Frame condition is detected. It is recommended to define it to
+ * the name of an assembler macro which is defined here as well so that more
+ * than one assembler instruction can be used. The macro may use the register
+ * YL and modify SREG. If it lasts longer than a couple of cycles, USB messages
+ * immediately after an SOF pulse may be lost and must be retried by the host.
+ * What can you do with this hook? Since the SOF signal occurs exactly every
+ * 1 ms (unless the host is in sleep mode), you can use it to tune OSCCAL in
+ * designs running on the internal RC oscillator.
+ * Please note that Start Of Frame detection works only if D- is wired to the
+ * interrupt, not D+. THIS IS DIFFERENT THAN MOST EXAMPLES!
+ */
+#define USB_CFG_CHECK_DATA_TOGGLING 0
+/* define this macro to 1 if you want to filter out duplicate data packets
+ * sent by the host. Duplicates occur only as a consequence of communication
+ * errors, when the host does not receive an ACK. Please note that you need to
+ * implement the filtering yourself in usbFunctionWriteOut() and
+ * usbFunctionWrite(). Use the global usbCurrentDataToken and a static variable
+ * for each control- and out-endpoint to check for duplicate packets.
+ */
+#define USB_CFG_HAVE_MEASURE_FRAME_LENGTH 0
+/* define this macro to 1 if you want the function usbMeasureFrameLength()
+ * compiled in. This function can be used to calibrate the AVR's RC oscillator.
+ */
+#define USB_USE_FAST_CRC 0
+/* The assembler module has two implementations for the CRC algorithm. One is
+ * faster, the other is smaller. This CRC routine is only used for transmitted
+ * messages where timing is not critical. The faster routine needs 31 cycles
+ * per byte while the smaller one needs 61 to 69 cycles. The faster routine
+ * may be worth the 32 bytes bigger code size if you transmit lots of data and
+ * run the AVR close to its limit.
+ */
+
+/* -------------------------- Device Description --------------------------- */
+
+#define USB_CFG_VENDOR_ID 0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */
+/* USB vendor ID for the device, low byte first. If you have registered your
+ * own Vendor ID, define it here. Otherwise you may use one of obdev's free
+ * shared VID/PID pairs. Be sure to read USB-IDs-for-free.txt for rules!
+ * *** IMPORTANT NOTE ***
+ * This template uses obdev's shared VID/PID pair for Vendor Class devices
+ * with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
+ * the implications!
+ */
+#define USB_CFG_DEVICE_ID 0xdc, 0x05 /* = 0x05dc = 1500 */
+/* This is the ID of the product, low byte first. It is interpreted in the
+ * scope of the vendor ID. If you have registered your own VID with usb.org
+ * or if you have licensed a PID from somebody else, define it here. Otherwise
+ * you may use one of obdev's free shared VID/PID pairs. See the file
+ * USB-IDs-for-free.txt for details!
+ * *** IMPORTANT NOTE ***
+ * This template uses obdev's shared VID/PID pair for Vendor Class devices
+ * with libusb: 0x16c0/0x5dc. Use this VID/PID pair ONLY if you understand
+ * the implications!
+ */
+#define USB_CFG_DEVICE_VERSION 0x00, 0x01
+/* Version number of the device: Minor number first, then major number.
+ */
+#define USB_CFG_VENDOR_NAME 'o', 'b', 'd', 'e', 'v', '.', 'a', 't'
+#define USB_CFG_VENDOR_NAME_LEN 8
+/* These two values define the vendor name returned by the USB device. The name
+ * must be given as a list of characters under single quotes. The characters
+ * are interpreted as Unicode (UTF-16) entities.
+ * If you don't want a vendor name string, undefine these macros.
+ * ALWAYS define a vendor name containing your Internet domain name if you use
+ * obdev's free shared VID/PID pair. See the file USB-IDs-for-free.txt for
+ * details.
+ */
+#define USB_CFG_DEVICE_NAME 'T', 'e', 'm', 'p', 'l', 'a', 't', 'e'
+#define USB_CFG_DEVICE_NAME_LEN 8
+/* Same as above for the device name. If you don't want a device name, undefine
+ * the macros. See the file USB-IDs-for-free.txt before you assign a name if
+ * you use a shared VID/PID.
+ */
+/*#define USB_CFG_SERIAL_NUMBER 'N', 'o', 'n', 'e' */
+/*#define USB_CFG_SERIAL_NUMBER_LEN 0 */
+/* Same as above for the serial number. If you don't want a serial number,
+ * undefine the macros.
+ * It may be useful to provide the serial number through other means than at
+ * compile time. See the section about descriptor properties below for how
+ * to fine tune control over USB descriptors such as the string descriptor
+ * for the serial number.
+ */
+#define USB_CFG_DEVICE_CLASS 0xff /* set to 0 if deferred to interface */
+#define USB_CFG_DEVICE_SUBCLASS 0
+/* See USB specification if you want to conform to an existing device class.
+ * Class 0xff is "vendor specific".
+ */
+#define USB_CFG_INTERFACE_CLASS 0 /* define class here if not at device level */
+#define USB_CFG_INTERFACE_SUBCLASS 0
+#define USB_CFG_INTERFACE_PROTOCOL 0
+/* See USB specification if you want to conform to an existing device class or
+ * protocol. The following classes must be set at interface level:
+ * HID class is 3, no subclass and protocol required (but may be useful!)
+ * CDC class is 2, use subclass 2 and protocol 1 for ACM
+ */
+/* #define USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH 42 */
+/* Define this to the length of the HID report descriptor, if you implement
+ * an HID device. Otherwise don't define it or define it to 0.
+ * If you use this define, you must add a PROGMEM character array named
+ * "usbHidReportDescriptor" to your code which contains the report descriptor.
+ * Don't forget to keep the array and this define in sync!
+ */
+
+/* #define USB_PUBLIC static */
+/* Use the define above if you #include usbdrv.c instead of linking against it.
+ * This technique saves a couple of bytes in flash memory.
+ */
+
+/* ------------------- Fine Control over USB Descriptors ------------------- */
+/* If you don't want to use the driver's default USB descriptors, you can
+ * provide our own. These can be provided as (1) fixed length static data in
+ * flash memory, (2) fixed length static data in RAM or (3) dynamically at
+ * runtime in the function usbFunctionDescriptor(). See usbdrv.h for more
+ * information about this function.
+ * Descriptor handling is configured through the descriptor's properties. If
+ * no properties are defined or if they are 0, the default descriptor is used.
+ * Possible properties are:
+ * + USB_PROP_IS_DYNAMIC: The data for the descriptor should be fetched
+ * at runtime via usbFunctionDescriptor(). If the usbMsgPtr mechanism is
+ * used, the data is in FLASH by default. Add property USB_PROP_IS_RAM if
+ * you want RAM pointers.
+ * + USB_PROP_IS_RAM: The data returned by usbFunctionDescriptor() or found
+ * in static memory is in RAM, not in flash memory.
+ * + USB_PROP_LENGTH(len): If the data is in static memory (RAM or flash),
+ * the driver must know the descriptor's length. The descriptor itself is
+ * found at the address of a well known identifier (see below).
+ * List of static descriptor names (must be declared PROGMEM if in flash):
+ * char usbDescriptorDevice[];
+ * char usbDescriptorConfiguration[];
+ * char usbDescriptorHidReport[];
+ * char usbDescriptorString0[];
+ * int usbDescriptorStringVendor[];
+ * int usbDescriptorStringDevice[];
+ * int usbDescriptorStringSerialNumber[];
+ * Other descriptors can't be provided statically, they must be provided
+ * dynamically at runtime.
+ *
+ * Descriptor properties are or-ed or added together, e.g.:
+ * #define USB_CFG_DESCR_PROPS_DEVICE (USB_PROP_IS_RAM | USB_PROP_LENGTH(18))
+ *
+ * The following descriptors are defined:
+ * USB_CFG_DESCR_PROPS_DEVICE
+ * USB_CFG_DESCR_PROPS_CONFIGURATION
+ * USB_CFG_DESCR_PROPS_STRINGS
+ * USB_CFG_DESCR_PROPS_STRING_0
+ * USB_CFG_DESCR_PROPS_STRING_VENDOR
+ * USB_CFG_DESCR_PROPS_STRING_PRODUCT
+ * USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
+ * USB_CFG_DESCR_PROPS_HID
+ * USB_CFG_DESCR_PROPS_HID_REPORT
+ * USB_CFG_DESCR_PROPS_UNKNOWN (for all descriptors not handled by the driver)
+ *
+ * Note about string descriptors: String descriptors are not just strings, they
+ * are Unicode strings prefixed with a 2 byte header. Example:
+ * int serialNumberDescriptor[] = {
+ * USB_STRING_DESCRIPTOR_HEADER(6),
+ * 'S', 'e', 'r', 'i', 'a', 'l'
+ * };
+ */
+
+#define USB_CFG_DESCR_PROPS_DEVICE 0
+#define USB_CFG_DESCR_PROPS_CONFIGURATION 0
+#define USB_CFG_DESCR_PROPS_STRINGS 0
+#define USB_CFG_DESCR_PROPS_STRING_0 0
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0
+#define USB_CFG_DESCR_PROPS_HID 0
+#define USB_CFG_DESCR_PROPS_HID_REPORT 0
+#define USB_CFG_DESCR_PROPS_UNKNOWN 0
+
+/* ----------------------- Optional MCU Description ------------------------ */
+
+/* The following configurations have working defaults in usbdrv.h. You
+ * usually don't need to set them explicitly. Only if you want to run
+ * the driver on a device which is not yet supported or with a compiler
+ * which is not fully supported (such as IAR C) or if you use a differnt
+ * interrupt than INT0, you may have to define some of these.
+ */
+/* #define USB_INTR_CFG MCUCR */
+/* #define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) */
+/* #define USB_INTR_CFG_CLR 0 */
+/* #define USB_INTR_ENABLE GIMSK */
+/* #define USB_INTR_ENABLE_BIT INT0 */
+/* #define USB_INTR_PENDING GIFR */
+/* #define USB_INTR_PENDING_BIT INTF0 */
+/* #define USB_INTR_VECTOR INT0_vect */
+
+#endif /* __usbconfig_h_included__ */
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrv.c b/tmk_core/protocol/vusb/usbdrv/usbdrv.c
new file mode 100644
index 000000000..2e8dd8756
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrv.c
@@ -0,0 +1,625 @@
+/* Name: usbdrv.c
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2004-12-29
+ * Tabsize: 4
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: usbdrv.c 791 2010-07-15 15:56:13Z cs $
+ */
+
+#include "usbportability.h"
+#include "usbdrv.h"
+#include "oddebug.h"
+
+/*
+General Description:
+This module implements the C-part of the USB driver. See usbdrv.h for a
+documentation of the entire driver.
+*/
+
+/* ------------------------------------------------------------------------- */
+
+/* raw USB registers / interface to assembler code: */
+uchar usbRxBuf[2*USB_BUFSIZE]; /* raw RX buffer: PID, 8 bytes data, 2 bytes CRC */
+uchar usbInputBufOffset; /* offset in usbRxBuf used for low level receiving */
+uchar usbDeviceAddr; /* assigned during enumeration, defaults to 0 */
+uchar usbNewDeviceAddr; /* device ID which should be set after status phase */
+uchar usbConfiguration; /* currently selected configuration. Administered by driver, but not used */
+volatile schar usbRxLen; /* = 0; number of bytes in usbRxBuf; 0 means free, -1 for flow control */
+uchar usbCurrentTok; /* last token received or endpoint number for last OUT token if != 0 */
+uchar usbRxToken; /* token for data we received; or endpont number for last OUT */
+volatile uchar usbTxLen = USBPID_NAK; /* number of bytes to transmit with next IN token or handshake token */
+uchar usbTxBuf[USB_BUFSIZE];/* data to transmit with next IN, free if usbTxLen contains handshake token */
+#if USB_COUNT_SOF
+volatile uchar usbSofCount; /* incremented by assembler module every SOF */
+#endif
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
+usbTxStatus_t usbTxStatus1;
+# if USB_CFG_HAVE_INTRIN_ENDPOINT3
+usbTxStatus_t usbTxStatus3;
+# endif
+#endif
+#if USB_CFG_CHECK_DATA_TOGGLING
+uchar usbCurrentDataToken;/* when we check data toggling to ignore duplicate packets */
+#endif
+
+/* USB status registers / not shared with asm code */
+uchar *usbMsgPtr; /* data to transmit next -- ROM or RAM address */
+static usbMsgLen_t usbMsgLen = USB_NO_MSG; /* remaining number of bytes */
+static uchar usbMsgFlags; /* flag values see below */
+
+#define USB_FLG_MSGPTR_IS_ROM (1<<6)
+#define USB_FLG_USE_USER_RW (1<<7)
+
+/*
+optimizing hints:
+- do not post/pre inc/dec integer values in operations
+- assign value of USB_READ_FLASH() to register variables and don't use side effects in arg
+- use narrow scope for variables which should be in X/Y/Z register
+- assign char sized expressions to variables to force 8 bit arithmetics
+*/
+
+/* -------------------------- String Descriptors --------------------------- */
+
+#if USB_CFG_DESCR_PROPS_STRINGS == 0
+
+#if USB_CFG_DESCR_PROPS_STRING_0 == 0
+#undef USB_CFG_DESCR_PROPS_STRING_0
+#define USB_CFG_DESCR_PROPS_STRING_0 sizeof(usbDescriptorString0)
+const PROGMEM char usbDescriptorString0[] = { /* language descriptor */
+ 4, /* sizeof(usbDescriptorString0): length of descriptor in bytes */
+ 3, /* descriptor type */
+ 0x09, 0x04, /* language index (0x0409 = US-English) */
+};
+#endif
+
+#if USB_CFG_DESCR_PROPS_STRING_VENDOR == 0 && USB_CFG_VENDOR_NAME_LEN
+#undef USB_CFG_DESCR_PROPS_STRING_VENDOR
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR sizeof(usbDescriptorStringVendor)
+const PROGMEM int usbDescriptorStringVendor[] = {
+ USB_STRING_DESCRIPTOR_HEADER(USB_CFG_VENDOR_NAME_LEN),
+ USB_CFG_VENDOR_NAME
+};
+#endif
+
+#if USB_CFG_DESCR_PROPS_STRING_PRODUCT == 0 && USB_CFG_DEVICE_NAME_LEN
+#undef USB_CFG_DESCR_PROPS_STRING_PRODUCT
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT sizeof(usbDescriptorStringDevice)
+const PROGMEM int usbDescriptorStringDevice[] = {
+ USB_STRING_DESCRIPTOR_HEADER(USB_CFG_DEVICE_NAME_LEN),
+ USB_CFG_DEVICE_NAME
+};
+#endif
+
+#if USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER == 0 && USB_CFG_SERIAL_NUMBER_LEN
+#undef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER sizeof(usbDescriptorStringSerialNumber)
+PROGMEM int usbDescriptorStringSerialNumber[] = {
+ USB_STRING_DESCRIPTOR_HEADER(USB_CFG_SERIAL_NUMBER_LEN),
+ USB_CFG_SERIAL_NUMBER
+};
+#endif
+
+#endif /* USB_CFG_DESCR_PROPS_STRINGS == 0 */
+
+/* --------------------------- Device Descriptor --------------------------- */
+
+#if USB_CFG_DESCR_PROPS_DEVICE == 0
+#undef USB_CFG_DESCR_PROPS_DEVICE
+#define USB_CFG_DESCR_PROPS_DEVICE sizeof(usbDescriptorDevice)
+const PROGMEM char usbDescriptorDevice[] = { /* USB device descriptor */
+ 18, /* sizeof(usbDescriptorDevice): length of descriptor in bytes */
+ USBDESCR_DEVICE, /* descriptor type */
+ 0x10, 0x01, /* USB version supported */
+ USB_CFG_DEVICE_CLASS,
+ USB_CFG_DEVICE_SUBCLASS,
+ 0, /* protocol */
+ 8, /* max packet size */
+ /* the following two casts affect the first byte of the constant only, but
+ * that's sufficient to avoid a warning with the default values.
+ */
+ (char)USB_CFG_VENDOR_ID,/* 2 bytes */
+ (char)USB_CFG_DEVICE_ID,/* 2 bytes */
+ USB_CFG_DEVICE_VERSION, /* 2 bytes */
+ USB_CFG_DESCR_PROPS_STRING_VENDOR != 0 ? 1 : 0, /* manufacturer string index */
+ USB_CFG_DESCR_PROPS_STRING_PRODUCT != 0 ? 2 : 0, /* product string index */
+ USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER != 0 ? 3 : 0, /* serial number string index */
+ 1, /* number of configurations */
+};
+#endif
+
+/* ----------------------- Configuration Descriptor ------------------------ */
+
+#if USB_CFG_DESCR_PROPS_HID_REPORT != 0 && USB_CFG_DESCR_PROPS_HID == 0
+#undef USB_CFG_DESCR_PROPS_HID
+#define USB_CFG_DESCR_PROPS_HID 9 /* length of HID descriptor in config descriptor below */
+#endif
+
+#if USB_CFG_DESCR_PROPS_CONFIGURATION == 0
+#undef USB_CFG_DESCR_PROPS_CONFIGURATION
+#define USB_CFG_DESCR_PROPS_CONFIGURATION sizeof(usbDescriptorConfiguration)
+PROGMEM char usbDescriptorConfiguration[] = { /* USB configuration descriptor */
+ 9, /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */
+ USBDESCR_CONFIG, /* descriptor type */
+ 18 + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT3 +
+ (USB_CFG_DESCR_PROPS_HID & 0xff), 0,
+ /* total length of data returned (including inlined descriptors) */
+ 1, /* number of interfaces in this configuration */
+ 1, /* index of this configuration */
+ 0, /* configuration name string index */
+#if USB_CFG_IS_SELF_POWERED
+ (1 << 7) | USBATTR_SELFPOWER, /* attributes */
+#else
+ (1 << 7), /* attributes */
+#endif
+ USB_CFG_MAX_BUS_POWER/2, /* max USB current in 2mA units */
+/* interface descriptor follows inline: */
+ 9, /* sizeof(usbDescrInterface): length of descriptor in bytes */
+ USBDESCR_INTERFACE, /* descriptor type */
+ 0, /* index of this interface */
+ 0, /* alternate setting for this interface */
+ USB_CFG_HAVE_INTRIN_ENDPOINT + USB_CFG_HAVE_INTRIN_ENDPOINT3, /* endpoints excl 0: number of endpoint descriptors to follow */
+ USB_CFG_INTERFACE_CLASS,
+ USB_CFG_INTERFACE_SUBCLASS,
+ USB_CFG_INTERFACE_PROTOCOL,
+ 0, /* string index for interface */
+#if (USB_CFG_DESCR_PROPS_HID & 0xff) /* HID descriptor */
+ 9, /* sizeof(usbDescrHID): length of descriptor in bytes */
+ USBDESCR_HID, /* descriptor type: HID */
+ 0x01, 0x01, /* BCD representation of HID version */
+ 0x00, /* target country code */
+ 0x01, /* number of HID Report (or other HID class) Descriptor infos to follow */
+ 0x22, /* descriptor type: report */
+ USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH, 0, /* total length of report descriptor */
+#endif
+#if USB_CFG_HAVE_INTRIN_ENDPOINT /* endpoint descriptor for endpoint 1 */
+ 7, /* sizeof(usbDescrEndpoint) */
+ USBDESCR_ENDPOINT, /* descriptor type = endpoint */
+ (char)0x81, /* IN endpoint number 1 */
+ 0x03, /* attrib: Interrupt endpoint */
+ 8, 0, /* maximum packet size */
+ USB_CFG_INTR_POLL_INTERVAL, /* in ms */
+#endif
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3 /* endpoint descriptor for endpoint 3 */
+ 7, /* sizeof(usbDescrEndpoint) */
+ USBDESCR_ENDPOINT, /* descriptor type = endpoint */
+ (char)(0x80 | USB_CFG_EP3_NUMBER), /* IN endpoint number 3 */
+ 0x03, /* attrib: Interrupt endpoint */
+ 8, 0, /* maximum packet size */
+ USB_CFG_INTR_POLL_INTERVAL, /* in ms */
+#endif
+};
+#endif
+
+/* ------------------------------------------------------------------------- */
+
+static inline void usbResetDataToggling(void)
+{
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
+ USB_SET_DATATOKEN1(USB_INITIAL_DATATOKEN); /* reset data toggling for interrupt endpoint */
+# if USB_CFG_HAVE_INTRIN_ENDPOINT3
+ USB_SET_DATATOKEN3(USB_INITIAL_DATATOKEN); /* reset data toggling for interrupt endpoint */
+# endif
+#endif
+}
+
+static inline void usbResetStall(void)
+{
+#if USB_CFG_IMPLEMENT_HALT && USB_CFG_HAVE_INTRIN_ENDPOINT
+ usbTxLen1 = USBPID_NAK;
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
+ usbTxLen3 = USBPID_NAK;
+#endif
+#endif
+}
+
+/* ------------------------------------------------------------------------- */
+
+#if !USB_CFG_SUPPRESS_INTR_CODE
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
+static void usbGenericSetInterrupt(uchar *data, uchar len, usbTxStatus_t *txStatus)
+{
+uchar *p;
+char i;
+
+#if USB_CFG_IMPLEMENT_HALT
+ if(usbTxLen1 == USBPID_STALL)
+ return;
+#endif
+ if(txStatus->len & 0x10){ /* packet buffer was empty */
+ txStatus->buffer[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* toggle token */
+ }else{
+ txStatus->len = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */
+ }
+ p = txStatus->buffer + 1;
+ i = len;
+ do{ /* if len == 0, we still copy 1 byte, but that's no problem */
+ *p++ = *data++;
+ }while(--i > 0); /* loop control at the end is 2 bytes shorter than at beginning */
+ usbCrc16Append(&txStatus->buffer[1], len);
+ txStatus->len = len + 4; /* len must be given including sync byte */
+ DBG2(0x21 + (((int)txStatus >> 3) & 3), txStatus->buffer, len + 3);
+}
+
+USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len)
+{
+ usbGenericSetInterrupt(data, len, &usbTxStatus1);
+}
+#endif
+
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
+USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len)
+{
+ usbGenericSetInterrupt(data, len, &usbTxStatus3);
+}
+#endif
+#endif /* USB_CFG_SUPPRESS_INTR_CODE */
+
+/* ------------------ utilities for code following below ------------------- */
+
+/* Use defines for the switch statement so that we can choose between an
+ * if()else if() and a switch/case based implementation. switch() is more
+ * efficient for a LARGE set of sequential choices, if() is better in all other
+ * cases.
+ */
+#if USB_CFG_USE_SWITCH_STATEMENT
+# define SWITCH_START(cmd) switch(cmd){{
+# define SWITCH_CASE(value) }break; case (value):{
+# define SWITCH_CASE2(v1,v2) }break; case (v1): case(v2):{
+# define SWITCH_CASE3(v1,v2,v3) }break; case (v1): case(v2): case(v3):{
+# define SWITCH_DEFAULT }break; default:{
+# define SWITCH_END }}
+#else
+# define SWITCH_START(cmd) {uchar _cmd = cmd; if(0){
+# define SWITCH_CASE(value) }else if(_cmd == (value)){
+# define SWITCH_CASE2(v1,v2) }else if(_cmd == (v1) || _cmd == (v2)){
+# define SWITCH_CASE3(v1,v2,v3) }else if(_cmd == (v1) || _cmd == (v2) || (_cmd == v3)){
+# define SWITCH_DEFAULT }else{
+# define SWITCH_END }}
+#endif
+
+#ifndef USB_RX_USER_HOOK
+#define USB_RX_USER_HOOK(data, len)
+#endif
+#ifndef USB_SET_ADDRESS_HOOK
+#define USB_SET_ADDRESS_HOOK()
+#endif
+
+/* ------------------------------------------------------------------------- */
+
+/* We use if() instead of #if in the macro below because #if can't be used
+ * in macros and the compiler optimizes constant conditions anyway.
+ * This may cause problems with undefined symbols if compiled without
+ * optimizing!
+ */
+#define GET_DESCRIPTOR(cfgProp, staticName) \
+ if(cfgProp){ \
+ if((cfgProp) & USB_PROP_IS_RAM) \
+ flags = 0; \
+ if((cfgProp) & USB_PROP_IS_DYNAMIC){ \
+ len = usbFunctionDescriptor(rq); \
+ }else{ \
+ len = USB_PROP_LENGTH(cfgProp); \
+ usbMsgPtr = (uchar *)(staticName); \
+ } \
+ }
+
+/* usbDriverDescriptor() is similar to usbFunctionDescriptor(), but used
+ * internally for all types of descriptors.
+ */
+static inline usbMsgLen_t usbDriverDescriptor(usbRequest_t *rq)
+{
+usbMsgLen_t len = 0;
+uchar flags = USB_FLG_MSGPTR_IS_ROM;
+
+ SWITCH_START(rq->wValue.bytes[1])
+ SWITCH_CASE(USBDESCR_DEVICE) /* 1 */
+ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_DEVICE, usbDescriptorDevice)
+ SWITCH_CASE(USBDESCR_CONFIG) /* 2 */
+ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_CONFIGURATION, usbDescriptorConfiguration)
+ SWITCH_CASE(USBDESCR_STRING) /* 3 */
+#if USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC
+ if(USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_RAM)
+ flags = 0;
+ len = usbFunctionDescriptor(rq);
+#else /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
+ SWITCH_START(rq->wValue.bytes[0])
+ SWITCH_CASE(0)
+ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_0, usbDescriptorString0)
+ SWITCH_CASE(1)
+ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_VENDOR, usbDescriptorStringVendor)
+ SWITCH_CASE(2)
+ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_PRODUCT, usbDescriptorStringDevice)
+ SWITCH_CASE(3)
+ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER, usbDescriptorStringSerialNumber)
+ SWITCH_DEFAULT
+ if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
+ len = usbFunctionDescriptor(rq);
+ }
+ SWITCH_END
+#endif /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */
+#if USB_CFG_DESCR_PROPS_HID_REPORT /* only support HID descriptors if enabled */
+ SWITCH_CASE(USBDESCR_HID) /* 0x21 */
+ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID, usbDescriptorConfiguration + 18)
+ SWITCH_CASE(USBDESCR_HID_REPORT)/* 0x22 */
+ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID_REPORT, usbDescriptorHidReport)
+#endif
+ SWITCH_DEFAULT
+ if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){
+ len = usbFunctionDescriptor(rq);
+ }
+ SWITCH_END
+ usbMsgFlags = flags;
+ return len;
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* usbDriverSetup() is similar to usbFunctionSetup(), but it's used for
+ * standard requests instead of class and custom requests.
+ */
+static inline usbMsgLen_t usbDriverSetup(usbRequest_t *rq)
+{
+uchar len = 0, *dataPtr = usbTxBuf + 9; /* there are 2 bytes free space at the end of the buffer */
+uchar value = rq->wValue.bytes[0];
+#if USB_CFG_IMPLEMENT_HALT
+uchar index = rq->wIndex.bytes[0];
+#endif
+
+ dataPtr[0] = 0; /* default reply common to USBRQ_GET_STATUS and USBRQ_GET_INTERFACE */
+ SWITCH_START(rq->bRequest)
+ SWITCH_CASE(USBRQ_GET_STATUS) /* 0 */
+ uchar recipient = rq->bmRequestType & USBRQ_RCPT_MASK; /* assign arith ops to variables to enforce byte size */
+ if(USB_CFG_IS_SELF_POWERED && recipient == USBRQ_RCPT_DEVICE)
+ dataPtr[0] = USB_CFG_IS_SELF_POWERED;
+#if USB_CFG_IMPLEMENT_HALT
+ if(recipient == USBRQ_RCPT_ENDPOINT && index == 0x81) /* request status for endpoint 1 */
+ dataPtr[0] = usbTxLen1 == USBPID_STALL;
+#endif
+ dataPtr[1] = 0;
+ len = 2;
+#if USB_CFG_IMPLEMENT_HALT
+ SWITCH_CASE2(USBRQ_CLEAR_FEATURE, USBRQ_SET_FEATURE) /* 1, 3 */
+ if(value == 0 && index == 0x81){ /* feature 0 == HALT for endpoint == 1 */
+ usbTxLen1 = rq->bRequest == USBRQ_CLEAR_FEATURE ? USBPID_NAK : USBPID_STALL;
+ usbResetDataToggling();
+ }
+#endif
+ SWITCH_CASE(USBRQ_SET_ADDRESS) /* 5 */
+ usbNewDeviceAddr = value;
+ USB_SET_ADDRESS_HOOK();
+ SWITCH_CASE(USBRQ_GET_DESCRIPTOR) /* 6 */
+ len = usbDriverDescriptor(rq);
+ goto skipMsgPtrAssignment;
+ SWITCH_CASE(USBRQ_GET_CONFIGURATION) /* 8 */
+ dataPtr = &usbConfiguration; /* send current configuration value */
+ len = 1;
+ SWITCH_CASE(USBRQ_SET_CONFIGURATION) /* 9 */
+ usbConfiguration = value;
+ usbResetStall();
+ SWITCH_CASE(USBRQ_GET_INTERFACE) /* 10 */
+ len = 1;
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
+ SWITCH_CASE(USBRQ_SET_INTERFACE) /* 11 */
+ usbResetDataToggling();
+ usbResetStall();
+#endif
+ SWITCH_DEFAULT /* 7=SET_DESCRIPTOR, 12=SYNC_FRAME */
+ /* Should we add an optional hook here? */
+ SWITCH_END
+ usbMsgPtr = dataPtr;
+skipMsgPtrAssignment:
+ return len;
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* usbProcessRx() is called for every message received by the interrupt
+ * routine. It distinguishes between SETUP and DATA packets and processes
+ * them accordingly.
+ */
+static inline void usbProcessRx(uchar *data, uchar len)
+{
+usbRequest_t *rq = (void *)data;
+
+/* usbRxToken can be:
+ * 0x2d 00101101 (USBPID_SETUP for setup data)
+ * 0xe1 11100001 (USBPID_OUT: data phase of setup transfer)
+ * 0...0x0f for OUT on endpoint X
+ */
+ DBG2(0x10 + (usbRxToken & 0xf), data, len + 2); /* SETUP=1d, SETUP-DATA=11, OUTx=1x */
+ USB_RX_USER_HOOK(data, len)
+#if USB_CFG_IMPLEMENT_FN_WRITEOUT
+ if(usbRxToken < 0x10){ /* OUT to endpoint != 0: endpoint number in usbRxToken */
+ usbFunctionWriteOut(data, len);
+ return;
+ }
+#endif
+ if(usbRxToken == (uchar)USBPID_SETUP){
+ if(len != 8) /* Setup size must be always 8 bytes. Ignore otherwise. */
+ return;
+ usbMsgLen_t replyLen;
+ usbTxBuf[0] = USBPID_DATA0; /* initialize data toggling */
+ usbTxLen = USBPID_NAK; /* abort pending transmit */
+ usbMsgFlags = 0;
+ uchar type = rq->bmRequestType & USBRQ_TYPE_MASK;
+ if(type != USBRQ_TYPE_STANDARD){ /* standard requests are handled by driver */
+ replyLen = usbFunctionSetup(data);
+ }else{
+ replyLen = usbDriverSetup(rq);
+ }
+#if USB_CFG_IMPLEMENT_FN_READ || USB_CFG_IMPLEMENT_FN_WRITE
+ if(replyLen == USB_NO_MSG){ /* use user-supplied read/write function */
+ /* do some conditioning on replyLen, but on IN transfers only */
+ if((rq->bmRequestType & USBRQ_DIR_MASK) != USBRQ_DIR_HOST_TO_DEVICE){
+ if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */
+ replyLen = rq->wLength.bytes[0];
+ }else{
+ replyLen = rq->wLength.word;
+ }
+ }
+ usbMsgFlags = USB_FLG_USE_USER_RW;
+ }else /* The 'else' prevents that we limit a replyLen of USB_NO_MSG to the maximum transfer len. */
+#endif
+ if(sizeof(replyLen) < sizeof(rq->wLength.word)){ /* help compiler with optimizing */
+ if(!rq->wLength.bytes[1] && replyLen > rq->wLength.bytes[0]) /* limit length to max */
+ replyLen = rq->wLength.bytes[0];
+ }else{
+ if(replyLen > rq->wLength.word) /* limit length to max */
+ replyLen = rq->wLength.word;
+ }
+ usbMsgLen = replyLen;
+ }else{ /* usbRxToken must be USBPID_OUT, which means data phase of setup (control-out) */
+#if USB_CFG_IMPLEMENT_FN_WRITE
+ if(usbMsgFlags & USB_FLG_USE_USER_RW){
+ uchar rval = usbFunctionWrite(data, len);
+ if(rval == 0xff){ /* an error occurred */
+ usbTxLen = USBPID_STALL;
+ }else if(rval != 0){ /* This was the final package */
+ usbMsgLen = 0; /* answer with a zero-sized data packet */
+ }
+ }
+#endif
+ }
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* This function is similar to usbFunctionRead(), but it's also called for
+ * data handled automatically by the driver (e.g. descriptor reads).
+ */
+static uchar usbDeviceRead(uchar *data, uchar len)
+{
+ if(len > 0){ /* don't bother app with 0 sized reads */
+#if USB_CFG_IMPLEMENT_FN_READ
+ if(usbMsgFlags & USB_FLG_USE_USER_RW){
+ len = usbFunctionRead(data, len);
+ }else
+#endif
+ {
+ uchar i = len, *r = usbMsgPtr;
+ if(usbMsgFlags & USB_FLG_MSGPTR_IS_ROM){ /* ROM data */
+ do{
+ uchar c = USB_READ_FLASH(r); /* assign to char size variable to enforce byte ops */
+ *data++ = c;
+ r++;
+ }while(--i);
+ }else{ /* RAM data */
+ do{
+ *data++ = *r++;
+ }while(--i);
+ }
+ usbMsgPtr = r;
+ }
+ }
+ return len;
+}
+
+/* ------------------------------------------------------------------------- */
+
+/* usbBuildTxBlock() is called when we have data to transmit and the
+ * interrupt routine's transmit buffer is empty.
+ */
+static inline void usbBuildTxBlock(void)
+{
+usbMsgLen_t wantLen;
+uchar len;
+
+ wantLen = usbMsgLen;
+ if(wantLen > 8)
+ wantLen = 8;
+ usbMsgLen -= wantLen;
+ usbTxBuf[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* DATA toggling */
+ len = usbDeviceRead(usbTxBuf + 1, wantLen);
+ if(len <= 8){ /* valid data packet */
+ usbCrc16Append(&usbTxBuf[1], len);
+ len += 4; /* length including sync byte */
+ if(len < 12) /* a partial package identifies end of message */
+ usbMsgLen = USB_NO_MSG;
+ }else{
+ len = USBPID_STALL; /* stall the endpoint */
+ usbMsgLen = USB_NO_MSG;
+ }
+ usbTxLen = len;
+ DBG2(0x20, usbTxBuf, len-1);
+}
+
+/* ------------------------------------------------------------------------- */
+
+static inline void usbHandleResetHook(uchar notResetState)
+{
+#ifdef USB_RESET_HOOK
+static uchar wasReset;
+uchar isReset = !notResetState;
+
+ if(wasReset != isReset){
+ USB_RESET_HOOK(isReset);
+ wasReset = isReset;
+ }
+#endif
+}
+
+/* ------------------------------------------------------------------------- */
+
+USB_PUBLIC void usbPoll(void)
+{
+schar len;
+uchar i;
+
+ len = usbRxLen - 3;
+ if(len >= 0){
+/* We could check CRC16 here -- but ACK has already been sent anyway. If you
+ * need data integrity checks with this driver, check the CRC in your app
+ * code and report errors back to the host. Since the ACK was already sent,
+ * retries must be handled on application level.
+ * unsigned crc = usbCrc16(buffer + 1, usbRxLen - 3);
+ */
+ usbProcessRx(usbRxBuf + USB_BUFSIZE + 1 - usbInputBufOffset, len);
+#if USB_CFG_HAVE_FLOWCONTROL
+ if(usbRxLen > 0) /* only mark as available if not inactivated */
+ usbRxLen = 0;
+#else
+ usbRxLen = 0; /* mark rx buffer as available */
+#endif
+ }
+ if(usbTxLen & 0x10){ /* transmit system idle */
+ if(usbMsgLen != USB_NO_MSG){ /* transmit data pending? */
+ usbBuildTxBlock();
+ }
+ }
+ for(i = 20; i > 0; i--){
+ uchar usbLineStatus = USBIN & USBMASK;
+ if(usbLineStatus != 0) /* SE0 has ended */
+ goto isNotReset;
+ }
+ /* RESET condition, called multiple times during reset */
+ usbNewDeviceAddr = 0;
+ usbDeviceAddr = 0;
+ usbResetStall();
+ DBG1(0xff, 0, 0);
+isNotReset:
+ usbHandleResetHook(i);
+}
+
+/* ------------------------------------------------------------------------- */
+
+USB_PUBLIC void usbInit(void)
+{
+#if USB_INTR_CFG_SET != 0
+ USB_INTR_CFG |= USB_INTR_CFG_SET;
+#endif
+#if USB_INTR_CFG_CLR != 0
+ USB_INTR_CFG &= ~(USB_INTR_CFG_CLR);
+#endif
+ USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT);
+ usbResetDataToggling();
+#if USB_CFG_HAVE_INTRIN_ENDPOINT && !USB_CFG_SUPPRESS_INTR_CODE
+ usbTxLen1 = USBPID_NAK;
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
+ usbTxLen3 = USBPID_NAK;
+#endif
+#endif
+}
+
+/* ------------------------------------------------------------------------- */
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrv.h b/tmk_core/protocol/vusb/usbdrv/usbdrv.h
new file mode 100644
index 000000000..42fe16372
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrv.h
@@ -0,0 +1,735 @@
+/* Name: usbdrv.h
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2004-12-29
+ * Tabsize: 4
+ * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: usbdrv.h 793 2010-07-15 15:58:11Z cs $
+ */
+
+#ifndef __usbdrv_h_included__
+#define __usbdrv_h_included__
+#include "usbconfig.h"
+#include "usbportability.h"
+
+/*
+Hardware Prerequisites:
+=======================
+USB lines D+ and D- MUST be wired to the same I/O port. We recommend that D+
+triggers the interrupt (best achieved by using INT0 for D+), but it is also
+possible to trigger the interrupt from D-. If D- is used, interrupts are also
+triggered by SOF packets. D- requires a pull-up of 1.5k to +3.5V (and the
+device must be powered at 3.5V) to identify as low-speed USB device. A
+pull-down or pull-up of 1M SHOULD be connected from D+ to +3.5V to prevent
+interference when no USB master is connected. If you use Zener diodes to limit
+the voltage on D+ and D-, you MUST use a pull-down resistor, not a pull-up.
+We use D+ as interrupt source and not D- because it does not trigger on
+keep-alive and RESET states. If you want to count keep-alive events with
+USB_COUNT_SOF, you MUST use D- as an interrupt source.
+
+As a compile time option, the 1.5k pull-up resistor on D- can be made
+switchable to allow the device to disconnect at will. See the definition of
+usbDeviceConnect() and usbDeviceDisconnect() further down in this file.
+
+Please adapt the values in usbconfig.h according to your hardware!
+
+The device MUST be clocked at exactly 12 MHz, 15 MHz, 16 MHz or 20 MHz
+or at 12.8 MHz resp. 16.5 MHz +/- 1%. See usbconfig-prototype.h for details.
+
+
+Limitations:
+============
+Robustness with respect to communication errors:
+The driver assumes error-free communication. It DOES check for errors in
+the PID, but does NOT check bit stuffing errors, SE0 in middle of a byte,
+token CRC (5 bit) and data CRC (16 bit). CRC checks can not be performed due
+to timing constraints: We must start sending a reply within 7 bit times.
+Bit stuffing and misplaced SE0 would have to be checked in real-time, but CPU
+performance does not permit that. The driver does not check Data0/Data1
+toggling, but application software can implement the check.
+
+Input characteristics:
+Since no differential receiver circuit is used, electrical interference
+robustness may suffer. The driver samples only one of the data lines with
+an ordinary I/O pin's input characteristics. However, since this is only a
+low speed USB implementation and the specification allows for 8 times the
+bit rate over the same hardware, we should be on the safe side. Even the spec
+requires detection of asymmetric states at high bit rate for SE0 detection.
+
+Number of endpoints:
+The driver supports the following endpoints:
+
+- Endpoint 0, the default control endpoint.
+- Any number of interrupt- or bulk-out endpoints. The data is sent to
+ usbFunctionWriteOut() and USB_CFG_IMPLEMENT_FN_WRITEOUT must be defined
+ to 1 to activate this feature. The endpoint number can be found in the
+ global variable 'usbRxToken'.
+- One default interrupt- or bulk-in endpoint. This endpoint is used for
+ interrupt- or bulk-in transfers which are not handled by any other endpoint.
+ You must define USB_CFG_HAVE_INTRIN_ENDPOINT in order to activate this
+ feature and call usbSetInterrupt() to send interrupt/bulk data.
+- One additional interrupt- or bulk-in endpoint. This was endpoint 3 in
+ previous versions of this driver but can now be configured to any endpoint
+ number. You must define USB_CFG_HAVE_INTRIN_ENDPOINT3 in order to activate
+ this feature and call usbSetInterrupt3() to send interrupt/bulk data. The
+ endpoint number can be set with USB_CFG_EP3_NUMBER.
+
+Please note that the USB standard forbids bulk endpoints for low speed devices!
+Most operating systems allow them anyway, but the AVR will spend 90% of the CPU
+time in the USB interrupt polling for bulk data.
+
+Maximum data payload:
+Data payload of control in and out transfers may be up to 254 bytes. In order
+to accept payload data of out transfers, you need to implement
+'usbFunctionWrite()'.
+
+USB Suspend Mode supply current:
+The USB standard limits power consumption to 500uA when the bus is in suspend
+mode. This is not a problem for self-powered devices since they don't need
+bus power anyway. Bus-powered devices can achieve this only by putting the
+CPU in sleep mode. The driver does not implement suspend handling by itself.
+However, the application may implement activity monitoring and wakeup from
+sleep. The host sends regular SE0 states on the bus to keep it active. These
+SE0 states can be detected by using D- as the interrupt source. Define
+USB_COUNT_SOF to 1 and use the global variable usbSofCount to check for bus
+activity.
+
+Operation without an USB master:
+The driver behaves neutral without connection to an USB master if D- reads
+as 1. To avoid spurious interrupts, we recommend a high impedance (e.g. 1M)
+pull-down or pull-up resistor on D+ (interrupt). If Zener diodes are used,
+use a pull-down. If D- becomes statically 0, the driver may block in the
+interrupt routine.
+
+Interrupt latency:
+The application must ensure that the USB interrupt is not disabled for more
+than 25 cycles (this is for 12 MHz, faster clocks allow longer latency).
+This implies that all interrupt routines must either have the "ISR_NOBLOCK"
+attribute set (see "avr/interrupt.h") or be written in assembler with "sei"
+as the first instruction.
+
+Maximum interrupt duration / CPU cycle consumption:
+The driver handles all USB communication during the interrupt service
+routine. The routine will not return before an entire USB message is received
+and the reply is sent. This may be up to ca. 1200 cycles @ 12 MHz (= 100us) if
+the host conforms to the standard. The driver will consume CPU cycles for all
+USB messages, even if they address another (low-speed) device on the same bus.
+
+*/
+
+/* ------------------------------------------------------------------------- */
+/* --------------------------- Module Interface ---------------------------- */
+/* ------------------------------------------------------------------------- */
+
+#define USBDRV_VERSION 20100715
+/* This define uniquely identifies a driver version. It is a decimal number
+ * constructed from the driver's release date in the form YYYYMMDD. If the
+ * driver's behavior or interface changes, you can use this constant to
+ * distinguish versions. If it is not defined, the driver's release date is
+ * older than 2006-01-25.
+ */
+
+
+#ifndef USB_PUBLIC
+#define USB_PUBLIC
+#endif
+/* USB_PUBLIC is used as declaration attribute for all functions exported by
+ * the USB driver. The default is no attribute (see above). You may define it
+ * to static either in usbconfig.h or from the command line if you include
+ * usbdrv.c instead of linking against it. Including the C module of the driver
+ * directly in your code saves a couple of bytes in flash memory.
+ */
+
+#ifndef __ASSEMBLER__
+#ifndef uchar
+#define uchar unsigned char
+#endif
+#ifndef schar
+#define schar signed char
+#endif
+/* shortcuts for well defined 8 bit integer types */
+
+#if USB_CFG_LONG_TRANSFERS /* if more than 254 bytes transfer size required */
+# define usbMsgLen_t unsigned
+#else
+# define usbMsgLen_t uchar
+#endif
+/* usbMsgLen_t is the data type used for transfer lengths. By default, it is
+ * defined to uchar, allowing a maximum of 254 bytes (255 is reserved for
+ * USB_NO_MSG below). If the usbconfig.h defines USB_CFG_LONG_TRANSFERS to 1,
+ * a 16 bit data type is used, allowing up to 16384 bytes (the rest is used
+ * for flags in the descriptor configuration).
+ */
+#define USB_NO_MSG ((usbMsgLen_t)-1) /* constant meaning "no message" */
+
+struct usbRequest; /* forward declaration */
+
+USB_PUBLIC void usbInit(void);
+/* This function must be called before interrupts are enabled and the main
+ * loop is entered. We exepct that the PORT and DDR bits for D+ and D- have
+ * not been changed from their default status (which is 0). If you have changed
+ * them, set both back to 0 (configure them as input with no internal pull-up).
+ */
+USB_PUBLIC void usbPoll(void);
+/* This function must be called at regular intervals from the main loop.
+ * Maximum delay between calls is somewhat less than 50ms (USB timeout for
+ * accepting a Setup message). Otherwise the device will not be recognized.
+ * Please note that debug outputs through the UART take ~ 0.5ms per byte
+ * at 19200 bps.
+ */
+extern uchar *usbMsgPtr;
+/* This variable may be used to pass transmit data to the driver from the
+ * implementation of usbFunctionWrite(). It is also used internally by the
+ * driver for standard control requests.
+ */
+USB_PUBLIC usbMsgLen_t usbFunctionSetup(uchar data[8]);
+/* This function is called when the driver receives a SETUP transaction from
+ * the host which is not answered by the driver itself (in practice: class and
+ * vendor requests). All control transfers start with a SETUP transaction where
+ * the host communicates the parameters of the following (optional) data
+ * transfer. The SETUP data is available in the 'data' parameter which can
+ * (and should) be casted to 'usbRequest_t *' for a more user-friendly access
+ * to parameters.
+ *
+ * If the SETUP indicates a control-in transfer, you should provide the
+ * requested data to the driver. There are two ways to transfer this data:
+ * (1) Set the global pointer 'usbMsgPtr' to the base of the static RAM data
+ * block and return the length of the data in 'usbFunctionSetup()'. The driver
+ * will handle the rest. Or (2) return USB_NO_MSG in 'usbFunctionSetup()'. The
+ * driver will then call 'usbFunctionRead()' when data is needed. See the
+ * documentation for usbFunctionRead() for details.
+ *
+ * If the SETUP indicates a control-out transfer, the only way to receive the
+ * data from the host is through the 'usbFunctionWrite()' call. If you
+ * implement this function, you must return USB_NO_MSG in 'usbFunctionSetup()'
+ * to indicate that 'usbFunctionWrite()' should be used. See the documentation
+ * of this function for more information. If you just want to ignore the data
+ * sent by the host, return 0 in 'usbFunctionSetup()'.
+ *
+ * Note that calls to the functions usbFunctionRead() and usbFunctionWrite()
+ * are only done if enabled by the configuration in usbconfig.h.
+ */
+USB_PUBLIC usbMsgLen_t usbFunctionDescriptor(struct usbRequest *rq);
+/* You need to implement this function ONLY if you provide USB descriptors at
+ * runtime (which is an expert feature). It is very similar to
+ * usbFunctionSetup() above, but it is called only to request USB descriptor
+ * data. See the documentation of usbFunctionSetup() above for more info.
+ */
+#if USB_CFG_HAVE_INTRIN_ENDPOINT
+USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len);
+/* This function sets the message which will be sent during the next interrupt
+ * IN transfer. The message is copied to an internal buffer and must not exceed
+ * a length of 8 bytes. The message may be 0 bytes long just to indicate the
+ * interrupt status to the host.
+ * If you need to transfer more bytes, use a control read after the interrupt.
+ */
+#define usbInterruptIsReady() (usbTxLen1 & 0x10)
+/* This macro indicates whether the last interrupt message has already been
+ * sent. If you set a new interrupt message before the old was sent, the
+ * message already buffered will be lost.
+ */
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3
+USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len);
+#define usbInterruptIsReady3() (usbTxLen3 & 0x10)
+/* Same as above for endpoint 3 */
+#endif
+#endif /* USB_CFG_HAVE_INTRIN_ENDPOINT */
+#if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH /* simplified interface for backward compatibility */
+#define usbHidReportDescriptor usbDescriptorHidReport
+/* should be declared as: PROGMEM char usbHidReportDescriptor[]; */
+/* If you implement an HID device, you need to provide a report descriptor.
+ * The HID report descriptor syntax is a bit complex. If you understand how
+ * report descriptors are constructed, we recommend that you use the HID
+ * Descriptor Tool from usb.org, see http://www.usb.org/developers/hidpage/.
+ * Otherwise you should probably start with a working example.
+ */
+#endif /* USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH */
+#if USB_CFG_IMPLEMENT_FN_WRITE
+USB_PUBLIC uchar usbFunctionWrite(uchar *data, uchar len);
+/* This function is called by the driver to provide a control transfer's
+ * payload data (control-out). It is called in chunks of up to 8 bytes. The
+ * total count provided in the current control transfer can be obtained from
+ * the 'length' property in the setup data. If an error occurred during
+ * processing, return 0xff (== -1). The driver will answer the entire transfer
+ * with a STALL token in this case. If you have received the entire payload
+ * successfully, return 1. If you expect more data, return 0. If you don't
+ * know whether the host will send more data (you should know, the total is
+ * provided in the usbFunctionSetup() call!), return 1.
+ * NOTE: If you return 0xff for STALL, 'usbFunctionWrite()' may still be called
+ * for the remaining data. You must continue to return 0xff for STALL in these
+ * calls.
+ * In order to get usbFunctionWrite() called, define USB_CFG_IMPLEMENT_FN_WRITE
+ * to 1 in usbconfig.h and return 0xff in usbFunctionSetup()..
+ */
+#endif /* USB_CFG_IMPLEMENT_FN_WRITE */
+#if USB_CFG_IMPLEMENT_FN_READ
+USB_PUBLIC uchar usbFunctionRead(uchar *data, uchar len);
+/* This function is called by the driver to ask the application for a control
+ * transfer's payload data (control-in). It is called in chunks of up to 8
+ * bytes each. You should copy the data to the location given by 'data' and
+ * return the actual number of bytes copied. If you return less than requested,
+ * the control-in transfer is terminated. If you return 0xff, the driver aborts
+ * the transfer with a STALL token.
+ * In order to get usbFunctionRead() called, define USB_CFG_IMPLEMENT_FN_READ
+ * to 1 in usbconfig.h and return 0xff in usbFunctionSetup()..
+ */
+#endif /* USB_CFG_IMPLEMENT_FN_READ */
+
+extern uchar usbRxToken; /* may be used in usbFunctionWriteOut() below */
+#if USB_CFG_IMPLEMENT_FN_WRITEOUT
+USB_PUBLIC void usbFunctionWriteOut(uchar *data, uchar len);
+/* This function is called by the driver when data is received on an interrupt-
+ * or bulk-out endpoint. The endpoint number can be found in the global
+ * variable usbRxToken. You must define USB_CFG_IMPLEMENT_FN_WRITEOUT to 1 in
+ * usbconfig.h to get this function called.
+ */
+#endif /* USB_CFG_IMPLEMENT_FN_WRITEOUT */
+#ifdef USB_CFG_PULLUP_IOPORTNAME
+#define usbDeviceConnect() ((USB_PULLUP_DDR |= (1<<USB_CFG_PULLUP_BIT)), \
+ (USB_PULLUP_OUT |= (1<<USB_CFG_PULLUP_BIT)))
+#define usbDeviceDisconnect() ((USB_PULLUP_DDR &= ~(1<<USB_CFG_PULLUP_BIT)), \
+ (USB_PULLUP_OUT &= ~(1<<USB_CFG_PULLUP_BIT)))
+#else /* USB_CFG_PULLUP_IOPORTNAME */
+#define usbDeviceConnect() (USBDDR &= ~(1<<USBMINUS))
+#define usbDeviceDisconnect() (USBDDR |= (1<<USBMINUS))
+#endif /* USB_CFG_PULLUP_IOPORTNAME */
+/* The macros usbDeviceConnect() and usbDeviceDisconnect() (intended to look
+ * like a function) connect resp. disconnect the device from the host's USB.
+ * If the constants USB_CFG_PULLUP_IOPORT and USB_CFG_PULLUP_BIT are defined
+ * in usbconfig.h, a disconnect consists of removing the pull-up resisitor
+ * from D-, otherwise the disconnect is done by brute-force pulling D- to GND.
+ * This does not conform to the spec, but it works.
+ * Please note that the USB interrupt must be disabled while the device is
+ * in disconnected state, or the interrupt handler will hang! You can either
+ * turn off the USB interrupt selectively with
+ * USB_INTR_ENABLE &= ~(1 << USB_INTR_ENABLE_BIT)
+ * or use cli() to disable interrupts globally.
+ */
+extern unsigned usbCrc16(unsigned data, uchar len);
+#define usbCrc16(data, len) usbCrc16((unsigned)(data), len)
+/* This function calculates the binary complement of the data CRC used in
+ * USB data packets. The value is used to build raw transmit packets.
+ * You may want to use this function for data checksums or to verify received
+ * data. We enforce 16 bit calling conventions for compatibility with IAR's
+ * tiny memory model.
+ */
+extern unsigned usbCrc16Append(unsigned data, uchar len);
+#define usbCrc16Append(data, len) usbCrc16Append((unsigned)(data), len)
+/* This function is equivalent to usbCrc16() above, except that it appends
+ * the 2 bytes CRC (lowbyte first) in the 'data' buffer after reading 'len'
+ * bytes.
+ */
+#if USB_CFG_HAVE_MEASURE_FRAME_LENGTH
+extern unsigned usbMeasureFrameLength(void);
+/* This function MUST be called IMMEDIATELY AFTER USB reset and measures 1/7 of
+ * the number of CPU cycles during one USB frame minus one low speed bit
+ * length. In other words: return value = 1499 * (F_CPU / 10.5 MHz)
+ * Since this is a busy wait, you MUST disable all interrupts with cli() before
+ * calling this function.
+ * This can be used to calibrate the AVR's RC oscillator.
+ */
+#endif
+extern uchar usbConfiguration;
+/* This value contains the current configuration set by the host. The driver
+ * allows setting and querying of this variable with the USB SET_CONFIGURATION
+ * and GET_CONFIGURATION requests, but does not use it otherwise.
+ * You may want to reflect the "configured" status with a LED on the device or
+ * switch on high power parts of the circuit only if the device is configured.
+ */
+#if USB_COUNT_SOF
+extern volatile uchar usbSofCount;
+/* This variable is incremented on every SOF packet. It is only available if
+ * the macro USB_COUNT_SOF is defined to a value != 0.
+ */
+#endif
+#if USB_CFG_CHECK_DATA_TOGGLING
+extern uchar usbCurrentDataToken;
+/* This variable can be checked in usbFunctionWrite() and usbFunctionWriteOut()
+ * to ignore duplicate packets.
+ */
+#endif
+
+#define USB_STRING_DESCRIPTOR_HEADER(stringLength) ((2*(stringLength)+2) | (3<<8))
+/* This macro builds a descriptor header for a string descriptor given the
+ * string's length. See usbdrv.c for an example how to use it.
+ */
+#if USB_CFG_HAVE_FLOWCONTROL
+extern volatile schar usbRxLen;
+#define usbDisableAllRequests() usbRxLen = -1
+/* Must be called from usbFunctionWrite(). This macro disables all data input
+ * from the USB interface. Requests from the host are answered with a NAK
+ * while they are disabled.
+ */
+#define usbEnableAllRequests() usbRxLen = 0
+/* May only be called if requests are disabled. This macro enables input from
+ * the USB interface after it has been disabled with usbDisableAllRequests().
+ */
+#define usbAllRequestsAreDisabled() (usbRxLen < 0)
+/* Use this macro to find out whether requests are disabled. It may be needed
+ * to ensure that usbEnableAllRequests() is never called when requests are
+ * enabled.
+ */
+#endif
+
+#define USB_SET_DATATOKEN1(token) usbTxBuf1[0] = token
+#define USB_SET_DATATOKEN3(token) usbTxBuf3[0] = token
+/* These two macros can be used by application software to reset data toggling
+ * for interrupt-in endpoints 1 and 3. Since the token is toggled BEFORE
+ * sending data, you must set the opposite value of the token which should come
+ * first.
+ */
+
+#endif /* __ASSEMBLER__ */
+
+
+/* ------------------------------------------------------------------------- */
+/* ----------------- Definitions for Descriptor Properties ----------------- */
+/* ------------------------------------------------------------------------- */
+/* This is advanced stuff. See usbconfig-prototype.h for more information
+ * about the various methods to define USB descriptors. If you do nothing,
+ * the default descriptors will be used.
+ */
+#define USB_PROP_IS_DYNAMIC (1 << 14)
+/* If this property is set for a descriptor, usbFunctionDescriptor() will be
+ * used to obtain the particular descriptor. Data directly returned via
+ * usbMsgPtr are FLASH data by default, combine (OR) with USB_PROP_IS_RAM to
+ * return RAM data.
+ */
+#define USB_PROP_IS_RAM (1 << 15)
+/* If this property is set for a descriptor, the data is read from RAM
+ * memory instead of Flash. The property is used for all methods to provide
+ * external descriptors.
+ */
+#define USB_PROP_LENGTH(len) ((len) & 0x3fff)
+/* If a static external descriptor is used, this is the total length of the
+ * descriptor in bytes.
+ */
+
+/* all descriptors which may have properties: */
+#ifndef USB_CFG_DESCR_PROPS_DEVICE
+#define USB_CFG_DESCR_PROPS_DEVICE 0
+#endif
+#ifndef USB_CFG_DESCR_PROPS_CONFIGURATION
+#define USB_CFG_DESCR_PROPS_CONFIGURATION 0
+#endif
+#ifndef USB_CFG_DESCR_PROPS_STRINGS
+#define USB_CFG_DESCR_PROPS_STRINGS 0
+#endif
+#ifndef USB_CFG_DESCR_PROPS_STRING_0
+#define USB_CFG_DESCR_PROPS_STRING_0 0
+#endif
+#ifndef USB_CFG_DESCR_PROPS_STRING_VENDOR
+#define USB_CFG_DESCR_PROPS_STRING_VENDOR 0
+#endif
+#ifndef USB_CFG_DESCR_PROPS_STRING_PRODUCT
+#define USB_CFG_DESCR_PROPS_STRING_PRODUCT 0
+#endif
+#ifndef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER
+#define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER 0
+#endif
+#ifndef USB_CFG_DESCR_PROPS_HID
+#define USB_CFG_DESCR_PROPS_HID 0
+#endif
+#if !(USB_CFG_DESCR_PROPS_HID_REPORT)
+# undef USB_CFG_DESCR_PROPS_HID_REPORT
+# if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH /* do some backward compatibility tricks */
+# define USB_CFG_DESCR_PROPS_HID_REPORT USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH
+# else
+# define USB_CFG_DESCR_PROPS_HID_REPORT 0
+# endif
+#endif
+#ifndef USB_CFG_DESCR_PROPS_UNKNOWN
+#define USB_CFG_DESCR_PROPS_UNKNOWN 0
+#endif
+
+/* ------------------ forward declaration of descriptors ------------------- */
+/* If you use external static descriptors, they must be stored in global
+ * arrays as declared below:
+ */
+#ifndef __ASSEMBLER__
+extern
+#if !(USB_CFG_DESCR_PROPS_DEVICE & USB_PROP_IS_RAM)
+PROGMEM
+#endif
+const char usbDescriptorDevice[];
+
+extern
+#if !(USB_CFG_DESCR_PROPS_CONFIGURATION & USB_PROP_IS_RAM)
+PROGMEM
+#endif
+const char usbDescriptorConfiguration[];
+
+extern
+#if !(USB_CFG_DESCR_PROPS_HID_REPORT & USB_PROP_IS_RAM)
+PROGMEM
+#endif
+const char usbDescriptorHidReport[];
+
+extern
+#if !(USB_CFG_DESCR_PROPS_STRING_0 & USB_PROP_IS_RAM)
+PROGMEM
+#endif
+const char usbDescriptorString0[];
+
+extern
+#if !(USB_CFG_DESCR_PROPS_STRING_VENDOR & USB_PROP_IS_RAM)
+PROGMEM
+#endif
+const int usbDescriptorStringVendor[];
+
+extern
+#if !(USB_CFG_DESCR_PROPS_STRING_PRODUCT & USB_PROP_IS_RAM)
+PROGMEM
+#endif
+const int usbDescriptorStringDevice[];
+
+extern
+#if !(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER & USB_PROP_IS_RAM)
+PROGMEM
+#endif
+const int usbDescriptorStringSerialNumber[];
+
+#endif /* __ASSEMBLER__ */
+
+/* ------------------------------------------------------------------------- */
+/* ------------------------ General Purpose Macros ------------------------- */
+/* ------------------------------------------------------------------------- */
+
+#define USB_CONCAT(a, b) a ## b
+#define USB_CONCAT_EXPANDED(a, b) USB_CONCAT(a, b)
+
+#define USB_OUTPORT(name) USB_CONCAT(PORT, name)
+#define USB_INPORT(name) USB_CONCAT(PIN, name)
+#define USB_DDRPORT(name) USB_CONCAT(DDR, name)
+/* The double-define trick above lets us concatenate strings which are
+ * defined by macros.
+ */
+
+/* ------------------------------------------------------------------------- */
+/* ------------------------- Constant definitions -------------------------- */
+/* ------------------------------------------------------------------------- */
+
+#if !defined __ASSEMBLER__ && (!defined USB_CFG_VENDOR_ID || !defined USB_CFG_DEVICE_ID)
+#warning "You should define USB_CFG_VENDOR_ID and USB_CFG_DEVICE_ID in usbconfig.h"
+/* If the user has not defined IDs, we default to obdev's free IDs.
+ * See USB-IDs-for-free.txt for details.
+ */
+#endif
+
+/* make sure we have a VID and PID defined, byte order is lowbyte, highbyte */
+#ifndef USB_CFG_VENDOR_ID
+# define USB_CFG_VENDOR_ID 0xc0, 0x16 /* = 0x16c0 = 5824 = voti.nl */
+#endif
+
+#ifndef USB_CFG_DEVICE_ID
+# if USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH
+# define USB_CFG_DEVICE_ID 0xdf, 0x05 /* = 0x5df = 1503, shared PID for HIDs */
+# elif USB_CFG_INTERFACE_CLASS == 2
+# define USB_CFG_DEVICE_ID 0xe1, 0x05 /* = 0x5e1 = 1505, shared PID for CDC Modems */
+# else
+# define USB_CFG_DEVICE_ID 0xdc, 0x05 /* = 0x5dc = 1500, obdev's free PID */
+# endif
+#endif
+
+/* Derive Output, Input and DataDirection ports from port names */
+#ifndef USB_CFG_IOPORTNAME
+#error "You must define USB_CFG_IOPORTNAME in usbconfig.h, see usbconfig-prototype.h"
+#endif
+
+#define USBOUT USB_OUTPORT(USB_CFG_IOPORTNAME)
+#define USB_PULLUP_OUT USB_OUTPORT(USB_CFG_PULLUP_IOPORTNAME)
+#define USBIN USB_INPORT(USB_CFG_IOPORTNAME)
+#define USBDDR USB_DDRPORT(USB_CFG_IOPORTNAME)
+#define USB_PULLUP_DDR USB_DDRPORT(USB_CFG_PULLUP_IOPORTNAME)
+
+#define USBMINUS USB_CFG_DMINUS_BIT
+#define USBPLUS USB_CFG_DPLUS_BIT
+#define USBIDLE (1<<USB_CFG_DMINUS_BIT) /* value representing J state */
+#define USBMASK ((1<<USB_CFG_DPLUS_BIT) | (1<<USB_CFG_DMINUS_BIT)) /* mask for USB I/O bits */
+
+/* defines for backward compatibility with older driver versions: */
+#define USB_CFG_IOPORT USB_OUTPORT(USB_CFG_IOPORTNAME)
+#ifdef USB_CFG_PULLUP_IOPORTNAME
+#define USB_CFG_PULLUP_IOPORT USB_OUTPORT(USB_CFG_PULLUP_IOPORTNAME)
+#endif
+
+#ifndef USB_CFG_EP3_NUMBER /* if not defined in usbconfig.h */
+#define USB_CFG_EP3_NUMBER 3
+#endif
+
+#ifndef USB_CFG_HAVE_INTRIN_ENDPOINT3
+#define USB_CFG_HAVE_INTRIN_ENDPOINT3 0
+#endif
+
+#define USB_BUFSIZE 11 /* PID, 8 bytes data, 2 bytes CRC */
+
+/* ----- Try to find registers and bits responsible for ext interrupt 0 ----- */
+
+#ifndef USB_INTR_CFG /* allow user to override our default */
+# if defined EICRA
+# define USB_INTR_CFG EICRA
+# else
+# define USB_INTR_CFG MCUCR
+# endif
+#endif
+#ifndef USB_INTR_CFG_SET /* allow user to override our default */
+# if defined(USB_COUNT_SOF) || defined(USB_SOF_HOOK)
+# define USB_INTR_CFG_SET (1 << ISC01) /* cfg for falling edge */
+ /* If any SOF logic is used, the interrupt must be wired to D- where
+ * we better trigger on falling edge
+ */
+# else
+# define USB_INTR_CFG_SET ((1 << ISC00) | (1 << ISC01)) /* cfg for rising edge */
+# endif
+#endif
+#ifndef USB_INTR_CFG_CLR /* allow user to override our default */
+# define USB_INTR_CFG_CLR 0 /* no bits to clear */
+#endif
+
+#ifndef USB_INTR_ENABLE /* allow user to override our default */
+# if defined GIMSK
+# define USB_INTR_ENABLE GIMSK
+# elif defined EIMSK
+# define USB_INTR_ENABLE EIMSK
+# else
+# define USB_INTR_ENABLE GICR
+# endif
+#endif
+#ifndef USB_INTR_ENABLE_BIT /* allow user to override our default */
+# define USB_INTR_ENABLE_BIT INT0
+#endif
+
+#ifndef USB_INTR_PENDING /* allow user to override our default */
+# if defined EIFR
+# define USB_INTR_PENDING EIFR
+# else
+# define USB_INTR_PENDING GIFR
+# endif
+#endif
+#ifndef USB_INTR_PENDING_BIT /* allow user to override our default */
+# define USB_INTR_PENDING_BIT INTF0
+#endif
+
+/*
+The defines above don't work for the following chips
+at90c8534: no ISC0?, no PORTB, can't find a data sheet
+at86rf401: no PORTB, no MCUCR etc, low clock rate
+atmega103: no ISC0? (maybe omission in header, can't find data sheet)
+atmega603: not defined in avr-libc
+at43usb320, at43usb355, at76c711: have USB anyway
+at94k: is different...
+
+at90s1200, attiny11, attiny12, attiny15, attiny28: these have no RAM
+*/
+
+/* ------------------------------------------------------------------------- */
+/* ----------------- USB Specification Constants and Types ----------------- */
+/* ------------------------------------------------------------------------- */
+
+/* USB Token values */
+#define USBPID_SETUP 0x2d
+#define USBPID_OUT 0xe1
+#define USBPID_IN 0x69
+#define USBPID_DATA0 0xc3
+#define USBPID_DATA1 0x4b
+
+#define USBPID_ACK 0xd2
+#define USBPID_NAK 0x5a
+#define USBPID_STALL 0x1e
+
+#ifndef USB_INITIAL_DATATOKEN
+#define USB_INITIAL_DATATOKEN USBPID_DATA1
+#endif
+
+#ifndef __ASSEMBLER__
+
+typedef struct usbTxStatus{
+ volatile uchar len;
+ uchar buffer[USB_BUFSIZE];
+}usbTxStatus_t;
+
+extern usbTxStatus_t usbTxStatus1, usbTxStatus3;
+#define usbTxLen1 usbTxStatus1.len
+#define usbTxBuf1 usbTxStatus1.buffer
+#define usbTxLen3 usbTxStatus3.len
+#define usbTxBuf3 usbTxStatus3.buffer
+
+
+typedef union usbWord{
+ unsigned word;
+ uchar bytes[2];
+}usbWord_t;
+
+typedef struct usbRequest{
+ uchar bmRequestType;
+ uchar bRequest;
+ usbWord_t wValue;
+ usbWord_t wIndex;
+ usbWord_t wLength;
+}usbRequest_t;
+/* This structure matches the 8 byte setup request */
+#endif
+
+/* bmRequestType field in USB setup:
+ * d t t r r r r r, where
+ * d ..... direction: 0=host->device, 1=device->host
+ * t ..... type: 0=standard, 1=class, 2=vendor, 3=reserved
+ * r ..... recipient: 0=device, 1=interface, 2=endpoint, 3=other
+ */
+
+/* USB setup recipient values */
+#define USBRQ_RCPT_MASK 0x1f
+#define USBRQ_RCPT_DEVICE 0
+#define USBRQ_RCPT_INTERFACE 1
+#define USBRQ_RCPT_ENDPOINT 2
+
+/* USB request type values */
+#define USBRQ_TYPE_MASK 0x60
+#define USBRQ_TYPE_STANDARD (0<<5)
+#define USBRQ_TYPE_CLASS (1<<5)
+#define USBRQ_TYPE_VENDOR (2<<5)
+
+/* USB direction values: */
+#define USBRQ_DIR_MASK 0x80
+#define USBRQ_DIR_HOST_TO_DEVICE (0<<7)
+#define USBRQ_DIR_DEVICE_TO_HOST (1<<7)
+
+/* USB Standard Requests */
+#define USBRQ_GET_STATUS 0
+#define USBRQ_CLEAR_FEATURE 1
+#define USBRQ_SET_FEATURE 3
+#define USBRQ_SET_ADDRESS 5
+#define USBRQ_GET_DESCRIPTOR 6
+#define USBRQ_SET_DESCRIPTOR 7
+#define USBRQ_GET_CONFIGURATION 8
+#define USBRQ_SET_CONFIGURATION 9
+#define USBRQ_GET_INTERFACE 10
+#define USBRQ_SET_INTERFACE 11
+#define USBRQ_SYNCH_FRAME 12
+
+/* USB descriptor constants */
+#define USBDESCR_DEVICE 1
+#define USBDESCR_CONFIG 2
+#define USBDESCR_STRING 3
+#define USBDESCR_INTERFACE 4
+#define USBDESCR_ENDPOINT 5
+#define USBDESCR_HID 0x21
+#define USBDESCR_HID_REPORT 0x22
+#define USBDESCR_HID_PHYS 0x23
+
+//#define USBATTR_BUSPOWER 0x80 // USB 1.1 does not define this value any more
+#define USBATTR_SELFPOWER 0x40
+#define USBATTR_REMOTEWAKE 0x20
+
+/* USB HID Requests */
+#define USBRQ_HID_GET_REPORT 0x01
+#define USBRQ_HID_GET_IDLE 0x02
+#define USBRQ_HID_GET_PROTOCOL 0x03
+#define USBRQ_HID_SET_REPORT 0x09
+#define USBRQ_HID_SET_IDLE 0x0a
+#define USBRQ_HID_SET_PROTOCOL 0x0b
+
+/* ------------------------------------------------------------------------- */
+
+#endif /* __usbdrv_h_included__ */
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm.S b/tmk_core/protocol/vusb/usbdrv/usbdrvasm.S
new file mode 100644
index 000000000..45fcf1831
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm.S
@@ -0,0 +1,393 @@
+/* Name: usbdrvasm.S
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2007-06-13
+ * Tabsize: 4
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * Revision: $Id: usbdrvasm.S 785 2010-05-30 17:57:07Z cs $
+ */
+
+/*
+General Description:
+This module is the assembler part of the USB driver. This file contains
+general code (preprocessor acrobatics and CRC computation) and then includes
+the file appropriate for the given clock rate.
+*/
+
+#define __SFR_OFFSET 0 /* used by avr-libc's register definitions */
+#include "usbportability.h"
+#include "usbdrv.h" /* for common defs */
+
+/* register names */
+#define x1 r16
+#define x2 r17
+#define shift r18
+#define cnt r19
+#define x3 r20
+#define x4 r21
+#define x5 r22
+#define bitcnt x5
+#define phase x4
+#define leap x4
+
+/* Some assembler dependent definitions and declarations: */
+
+#ifdef __IAR_SYSTEMS_ASM__
+ extern usbRxBuf, usbDeviceAddr, usbNewDeviceAddr, usbInputBufOffset
+ extern usbCurrentTok, usbRxLen, usbRxToken, usbTxLen
+ extern usbTxBuf, usbTxStatus1, usbTxStatus3
+# if USB_COUNT_SOF
+ extern usbSofCount
+# endif
+ public usbCrc16
+ public usbCrc16Append
+
+ COMMON INTVEC
+# ifndef USB_INTR_VECTOR
+ ORG INT0_vect
+# else /* USB_INTR_VECTOR */
+ ORG USB_INTR_VECTOR
+# undef USB_INTR_VECTOR
+# endif /* USB_INTR_VECTOR */
+# define USB_INTR_VECTOR usbInterruptHandler
+ rjmp USB_INTR_VECTOR
+ RSEG CODE
+
+#else /* __IAR_SYSTEMS_ASM__ */
+
+# ifndef USB_INTR_VECTOR /* default to hardware interrupt INT0 */
+# ifdef INT0_vect
+# define USB_INTR_VECTOR INT0_vect // this is the "new" define for the vector
+# else
+# define USB_INTR_VECTOR SIG_INTERRUPT0 // this is the "old" vector
+# endif
+# endif
+ .text
+ .global USB_INTR_VECTOR
+ .type USB_INTR_VECTOR, @function
+ .global usbCrc16
+ .global usbCrc16Append
+#endif /* __IAR_SYSTEMS_ASM__ */
+
+
+#if USB_INTR_PENDING < 0x40 /* This is an I/O address, use in and out */
+# define USB_LOAD_PENDING(reg) in reg, USB_INTR_PENDING
+# define USB_STORE_PENDING(reg) out USB_INTR_PENDING, reg
+#else /* It's a memory address, use lds and sts */
+# define USB_LOAD_PENDING(reg) lds reg, USB_INTR_PENDING
+# define USB_STORE_PENDING(reg) sts USB_INTR_PENDING, reg
+#endif
+
+#define usbTxLen1 usbTxStatus1
+#define usbTxBuf1 (usbTxStatus1 + 1)
+#define usbTxLen3 usbTxStatus3
+#define usbTxBuf3 (usbTxStatus3 + 1)
+
+
+;----------------------------------------------------------------------------
+; Utility functions
+;----------------------------------------------------------------------------
+
+#ifdef __IAR_SYSTEMS_ASM__
+/* Register assignments for usbCrc16 on IAR cc */
+/* Calling conventions on IAR:
+ * First parameter passed in r16/r17, second in r18/r19 and so on.
+ * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer)
+ * Result is passed in r16/r17
+ * In case of the "tiny" memory model, pointers are only 8 bit with no
+ * padding. We therefore pass argument 1 as "16 bit unsigned".
+ */
+RTMODEL "__rt_version", "3"
+/* The line above will generate an error if cc calling conventions change.
+ * The value "3" above is valid for IAR 4.10B/W32
+ */
+# define argLen r18 /* argument 2 */
+# define argPtrL r16 /* argument 1 */
+# define argPtrH r17 /* argument 1 */
+
+# define resCrcL r16 /* result */
+# define resCrcH r17 /* result */
+
+# define ptrL ZL
+# define ptrH ZH
+# define ptr Z
+# define byte r22
+# define bitCnt r19
+# define polyL r20
+# define polyH r21
+# define scratch r23
+
+#else /* __IAR_SYSTEMS_ASM__ */
+/* Register assignments for usbCrc16 on gcc */
+/* Calling conventions on gcc:
+ * First parameter passed in r24/r25, second in r22/23 and so on.
+ * Callee must preserve r1-r17, r28/r29
+ * Result is passed in r24/r25
+ */
+# define argLen r22 /* argument 2 */
+# define argPtrL r24 /* argument 1 */
+# define argPtrH r25 /* argument 1 */
+
+# define resCrcL r24 /* result */
+# define resCrcH r25 /* result */
+
+# define ptrL XL
+# define ptrH XH
+# define ptr x
+# define byte r18
+# define bitCnt r19
+# define polyL r20
+# define polyH r21
+# define scratch r23
+
+#endif
+
+#if USB_USE_FAST_CRC
+
+; This implementation is faster, but has bigger code size
+; Thanks to Slawomir Fras (BoskiDialer) for this code!
+; It implements the following C pseudo-code:
+; unsigned table(unsigned char x)
+; {
+; unsigned value;
+;
+; value = (unsigned)x << 6;
+; value ^= (unsigned)x << 7;
+; if(parity(x))
+; value ^= 0xc001;
+; return value;
+; }
+; unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen)
+; {
+; unsigned crc = 0xffff;
+;
+; while(argLen--)
+; crc = table(lo8(crc) ^ *argPtr++) ^ hi8(crc);
+; return ~crc;
+; }
+
+; extern unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen);
+; argPtr r24+25 / r16+r17
+; argLen r22 / r18
+; temp variables:
+; byte r18 / r22
+; scratch r23
+; resCrc r24+r25 / r16+r17
+; ptr X / Z
+usbCrc16:
+ mov ptrL, argPtrL
+ mov ptrH, argPtrH
+ ldi resCrcL, 0xFF
+ ldi resCrcH, 0xFF
+ rjmp usbCrc16LoopTest
+usbCrc16ByteLoop:
+ ld byte, ptr+
+ eor resCrcL, byte ; resCrcL is now 'x' in table()
+ mov byte, resCrcL ; compute parity of 'x'
+ swap byte
+ eor byte, resCrcL
+ mov scratch, byte
+ lsr byte
+ lsr byte
+ eor byte, scratch
+ inc byte
+ lsr byte
+ andi byte, 1 ; byte is now parity(x)
+ mov scratch, resCrcL
+ mov resCrcL, resCrcH
+ eor resCrcL, byte ; low byte of if(parity(x)) value ^= 0xc001;
+ neg byte
+ andi byte, 0xc0
+ mov resCrcH, byte ; high byte of if(parity(x)) value ^= 0xc001;
+ clr byte
+ lsr scratch
+ ror byte
+ eor resCrcH, scratch
+ eor resCrcL, byte
+ lsr scratch
+ ror byte
+ eor resCrcH, scratch
+ eor resCrcL, byte
+usbCrc16LoopTest:
+ subi argLen, 1
+ brsh usbCrc16ByteLoop
+ com resCrcL
+ com resCrcH
+ ret
+
+#else /* USB_USE_FAST_CRC */
+
+; This implementation is slower, but has less code size
+;
+; extern unsigned usbCrc16(unsigned char *argPtr, unsigned char argLen);
+; argPtr r24+25 / r16+r17
+; argLen r22 / r18
+; temp variables:
+; byte r18 / r22
+; bitCnt r19
+; poly r20+r21
+; scratch r23
+; resCrc r24+r25 / r16+r17
+; ptr X / Z
+usbCrc16:
+ mov ptrL, argPtrL
+ mov ptrH, argPtrH
+ ldi resCrcL, 0
+ ldi resCrcH, 0
+ ldi polyL, lo8(0xa001)
+ ldi polyH, hi8(0xa001)
+ com argLen ; argLen = -argLen - 1: modified loop to ensure that carry is set
+ ldi bitCnt, 0 ; loop counter with starnd condition = end condition
+ rjmp usbCrcLoopEntry
+usbCrcByteLoop:
+ ld byte, ptr+
+ eor resCrcL, byte
+usbCrcBitLoop:
+ ror resCrcH ; carry is always set here (see brcs jumps to here)
+ ror resCrcL
+ brcs usbCrcNoXor
+ eor resCrcL, polyL
+ eor resCrcH, polyH
+usbCrcNoXor:
+ subi bitCnt, 224 ; (8 * 224) % 256 = 0; this loop iterates 8 times
+ brcs usbCrcBitLoop
+usbCrcLoopEntry:
+ subi argLen, -1
+ brcs usbCrcByteLoop
+usbCrcReady:
+ ret
+; Thanks to Reimar Doeffinger for optimizing this CRC routine!
+
+#endif /* USB_USE_FAST_CRC */
+
+; extern unsigned usbCrc16Append(unsigned char *data, unsigned char len);
+usbCrc16Append:
+ rcall usbCrc16
+ st ptr+, resCrcL
+ st ptr+, resCrcH
+ ret
+
+#undef argLen
+#undef argPtrL
+#undef argPtrH
+#undef resCrcL
+#undef resCrcH
+#undef ptrL
+#undef ptrH
+#undef ptr
+#undef byte
+#undef bitCnt
+#undef polyL
+#undef polyH
+#undef scratch
+
+
+#if USB_CFG_HAVE_MEASURE_FRAME_LENGTH
+#ifdef __IAR_SYSTEMS_ASM__
+/* Register assignments for usbMeasureFrameLength on IAR cc */
+/* Calling conventions on IAR:
+ * First parameter passed in r16/r17, second in r18/r19 and so on.
+ * Callee must preserve r4-r15, r24-r29 (r28/r29 is frame pointer)
+ * Result is passed in r16/r17
+ * In case of the "tiny" memory model, pointers are only 8 bit with no
+ * padding. We therefore pass argument 1 as "16 bit unsigned".
+ */
+# define resL r16
+# define resH r17
+# define cnt16L r30
+# define cnt16H r31
+# define cntH r18
+
+#else /* __IAR_SYSTEMS_ASM__ */
+/* Register assignments for usbMeasureFrameLength on gcc */
+/* Calling conventions on gcc:
+ * First parameter passed in r24/r25, second in r22/23 and so on.
+ * Callee must preserve r1-r17, r28/r29
+ * Result is passed in r24/r25
+ */
+# define resL r24
+# define resH r25
+# define cnt16L r24
+# define cnt16H r25
+# define cntH r26
+#endif
+# define cnt16 cnt16L
+
+; extern unsigned usbMeasurePacketLength(void);
+; returns time between two idle strobes in multiples of 7 CPU clocks
+.global usbMeasureFrameLength
+usbMeasureFrameLength:
+ ldi cntH, 6 ; wait ~ 10 ms for D- == 0
+ clr cnt16L
+ clr cnt16H
+usbMFTime16:
+ dec cntH
+ breq usbMFTimeout
+usbMFWaitStrobe: ; first wait for D- == 0 (idle strobe)
+ sbiw cnt16, 1 ;[0] [6]
+ breq usbMFTime16 ;[2]
+ sbic USBIN, USBMINUS ;[3]
+ rjmp usbMFWaitStrobe ;[4]
+usbMFWaitIdle: ; then wait until idle again
+ sbis USBIN, USBMINUS ;1 wait for D- == 1
+ rjmp usbMFWaitIdle ;2
+ ldi cnt16L, 1 ;1 represents cycles so far
+ clr cnt16H ;1
+usbMFWaitLoop:
+ in cntH, USBIN ;[0] [7]
+ adiw cnt16, 1 ;[1]
+ breq usbMFTimeout ;[3]
+ andi cntH, USBMASK ;[4]
+ brne usbMFWaitLoop ;[5]
+usbMFTimeout:
+#if resL != cnt16L
+ mov resL, cnt16L
+ mov resH, cnt16H
+#endif
+ ret
+
+#undef resL
+#undef resH
+#undef cnt16
+#undef cnt16L
+#undef cnt16H
+#undef cntH
+
+#endif /* USB_CFG_HAVE_MEASURE_FRAME_LENGTH */
+
+;----------------------------------------------------------------------------
+; Now include the clock rate specific code
+;----------------------------------------------------------------------------
+
+#ifndef USB_CFG_CLOCK_KHZ
+# ifdef F_CPU
+# define USB_CFG_CLOCK_KHZ (F_CPU/1000)
+# else
+# error "USB_CFG_CLOCK_KHZ not defined in usbconfig.h and no F_CPU set!"
+# endif
+#endif
+
+#if USB_CFG_CHECK_CRC /* separate dispatcher for CRC type modules */
+# if USB_CFG_CLOCK_KHZ == 18000
+# include "usbdrvasm18-crc.inc"
+# else
+# error "USB_CFG_CLOCK_KHZ is not one of the supported crc-rates!"
+# endif
+#else /* USB_CFG_CHECK_CRC */
+# if USB_CFG_CLOCK_KHZ == 12000
+# include "usbdrvasm12.inc"
+# elif USB_CFG_CLOCK_KHZ == 12800
+# include "usbdrvasm128.inc"
+# elif USB_CFG_CLOCK_KHZ == 15000
+# include "usbdrvasm15.inc"
+# elif USB_CFG_CLOCK_KHZ == 16000
+# include "usbdrvasm16.inc"
+# elif USB_CFG_CLOCK_KHZ == 16500
+# include "usbdrvasm165.inc"
+# elif USB_CFG_CLOCK_KHZ == 20000
+# include "usbdrvasm20.inc"
+# else
+# error "USB_CFG_CLOCK_KHZ is not one of the supported non-crc-rates!"
+# endif
+#endif /* USB_CFG_CHECK_CRC */
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm.asm b/tmk_core/protocol/vusb/usbdrv/usbdrvasm.asm
new file mode 100644
index 000000000..9cc4e4d73
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm.asm
@@ -0,0 +1,21 @@
+/* Name: usbdrvasm.asm
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2006-03-01
+ * Tabsize: 4
+ * Copyright: (c) 2006 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id$
+ */
+
+/*
+General Description:
+The IAR compiler/assembler system prefers assembler files with file extension
+".asm". We simply provide this file as an alias for usbdrvasm.S.
+
+Thanks to Oleg Semyonov for his help with the IAR tools port!
+*/
+
+#include "usbdrvasm.S"
+
+end
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm12.inc b/tmk_core/protocol/vusb/usbdrv/usbdrvasm12.inc
new file mode 100644
index 000000000..c1167584c
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm12.inc
@@ -0,0 +1,393 @@
+/* Name: usbdrvasm12.inc
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2004-12-29
+ * Tabsize: 4
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: usbdrvasm12.inc 740 2009-04-13 18:23:31Z cs $
+ */
+
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
+ * appropriate implementation!
+ */
+
+/*
+General Description:
+This file is the 12 MHz version of the asssembler part of the USB driver. It
+requires a 12 MHz crystal (not a ceramic resonator and not a calibrated RC
+oscillator).
+
+See usbdrv.h for a description of the entire driver.
+
+Since almost all of this code is timing critical, don't change unless you
+really know what you are doing! Many parts require not only a maximum number
+of CPU cycles, but even an exact number of cycles!
+
+
+Timing constraints according to spec (in bit times):
+timing subject min max CPUcycles
+---------------------------------------------------------------------------
+EOP of OUT/SETUP to sync pattern of DATA0 (both rx) 2 16 16-128
+EOP of IN to sync pattern of DATA0 (rx, then tx) 2 7.5 16-60
+DATAx (rx) to ACK/NAK/STALL (tx) 2 7.5 16-60
+*/
+
+;Software-receiver engine. Strict timing! Don't change unless you can preserve timing!
+;interrupt response time: 4 cycles + insn running = 7 max if interrupts always enabled
+;max allowable interrupt latency: 34 cycles -> max 25 cycles interrupt disable
+;max stack usage: [ret(2), YL, SREG, YH, shift, x1, x2, x3, cnt, x4] = 11 bytes
+;Numbers in brackets are maximum cycles since SOF.
+USB_INTR_VECTOR:
+;order of registers pushed: YL, SREG [sofError], YH, shift, x1, x2, x3, cnt
+ push YL ;2 [35] push only what is necessary to sync with edge ASAP
+ in YL, SREG ;1 [37]
+ push YL ;2 [39]
+;----------------------------------------------------------------------------
+; Synchronize with sync pattern:
+;----------------------------------------------------------------------------
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
+;sync up with J to K edge during sync pattern -- use fastest possible loops
+;The first part waits at most 1 bit long since we must be in sync pattern.
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
+;waitForJ, ensure that this prerequisite is met.
+waitForJ:
+ inc YL
+ sbis USBIN, USBMINUS
+ brne waitForJ ; just make sure we have ANY timeout
+waitForK:
+;The following code results in a sampling window of 1/4 bit which meets the spec.
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+#if USB_COUNT_SOF
+ lds YL, usbSofCount
+ inc YL
+ sts usbSofCount, YL
+#endif /* USB_COUNT_SOF */
+#ifdef USB_SOF_HOOK
+ USB_SOF_HOOK
+#endif
+ rjmp sofError
+foundK:
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 4 for center sampling]
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
+;are cycles from center of first sync (double K) bit after the instruction
+ push YH ;2 [2]
+ lds YL, usbInputBufOffset;2 [4]
+ clr YH ;1 [5]
+ subi YL, lo8(-(usbRxBuf));1 [6]
+ sbci YH, hi8(-(usbRxBuf));1 [7]
+
+ sbis USBIN, USBMINUS ;1 [8] we want two bits K [sample 1 cycle too early]
+ rjmp haveTwoBitsK ;2 [10]
+ pop YH ;2 [11] undo the push from before
+ rjmp waitForK ;2 [13] this was not the end of sync, retry
+haveTwoBitsK:
+;----------------------------------------------------------------------------
+; push more registers and initialize values while we sample the first bits:
+;----------------------------------------------------------------------------
+ push shift ;2 [16]
+ push x1 ;2 [12]
+ push x2 ;2 [14]
+
+ in x1, USBIN ;1 [17] <-- sample bit 0
+ ldi shift, 0xff ;1 [18]
+ bst x1, USBMINUS ;1 [19]
+ bld shift, 0 ;1 [20]
+ push x3 ;2 [22]
+ push cnt ;2 [24]
+
+ in x2, USBIN ;1 [25] <-- sample bit 1
+ ser x3 ;1 [26] [inserted init instruction]
+ eor x1, x2 ;1 [27]
+ bst x1, USBMINUS ;1 [28]
+ bld shift, 1 ;1 [29]
+ ldi cnt, USB_BUFSIZE;1 [30] [inserted init instruction]
+ rjmp rxbit2 ;2 [32]
+
+;----------------------------------------------------------------------------
+; Receiver loop (numbers in brackets are cycles within byte after instr)
+;----------------------------------------------------------------------------
+
+unstuff0: ;1 (branch taken)
+ andi x3, ~0x01 ;1 [15]
+ mov x1, x2 ;1 [16] x2 contains last sampled (stuffed) bit
+ in x2, USBIN ;1 [17] <-- sample bit 1 again
+ ori shift, 0x01 ;1 [18]
+ rjmp didUnstuff0 ;2 [20]
+
+unstuff1: ;1 (branch taken)
+ mov x2, x1 ;1 [21] x1 contains last sampled (stuffed) bit
+ andi x3, ~0x02 ;1 [22]
+ ori shift, 0x02 ;1 [23]
+ nop ;1 [24]
+ in x1, USBIN ;1 [25] <-- sample bit 2 again
+ rjmp didUnstuff1 ;2 [27]
+
+unstuff2: ;1 (branch taken)
+ andi x3, ~0x04 ;1 [29]
+ ori shift, 0x04 ;1 [30]
+ mov x1, x2 ;1 [31] x2 contains last sampled (stuffed) bit
+ nop ;1 [32]
+ in x2, USBIN ;1 [33] <-- sample bit 3
+ rjmp didUnstuff2 ;2 [35]
+
+unstuff3: ;1 (branch taken)
+ in x2, USBIN ;1 [34] <-- sample stuffed bit 3 [one cycle too late]
+ andi x3, ~0x08 ;1 [35]
+ ori shift, 0x08 ;1 [36]
+ rjmp didUnstuff3 ;2 [38]
+
+unstuff4: ;1 (branch taken)
+ andi x3, ~0x10 ;1 [40]
+ in x1, USBIN ;1 [41] <-- sample stuffed bit 4
+ ori shift, 0x10 ;1 [42]
+ rjmp didUnstuff4 ;2 [44]
+
+unstuff5: ;1 (branch taken)
+ andi x3, ~0x20 ;1 [48]
+ in x2, USBIN ;1 [49] <-- sample stuffed bit 5
+ ori shift, 0x20 ;1 [50]
+ rjmp didUnstuff5 ;2 [52]
+
+unstuff6: ;1 (branch taken)
+ andi x3, ~0x40 ;1 [56]
+ in x1, USBIN ;1 [57] <-- sample stuffed bit 6
+ ori shift, 0x40 ;1 [58]
+ rjmp didUnstuff6 ;2 [60]
+
+; extra jobs done during bit interval:
+; bit 0: store, clear [SE0 is unreliable here due to bit dribbling in hubs]
+; bit 1: se0 check
+; bit 2: overflow check
+; bit 3: recovery from delay [bit 0 tasks took too long]
+; bit 4: none
+; bit 5: none
+; bit 6: none
+; bit 7: jump, eor
+rxLoop:
+ eor x3, shift ;1 [0] reconstruct: x3 is 0 at bit locations we changed, 1 at others
+ in x1, USBIN ;1 [1] <-- sample bit 0
+ st y+, x3 ;2 [3] store data
+ ser x3 ;1 [4]
+ nop ;1 [5]
+ eor x2, x1 ;1 [6]
+ bst x2, USBMINUS;1 [7]
+ bld shift, 0 ;1 [8]
+ in x2, USBIN ;1 [9] <-- sample bit 1 (or possibly bit 0 stuffed)
+ andi x2, USBMASK ;1 [10]
+ breq se0 ;1 [11] SE0 check for bit 1
+ andi shift, 0xf9 ;1 [12]
+didUnstuff0:
+ breq unstuff0 ;1 [13]
+ eor x1, x2 ;1 [14]
+ bst x1, USBMINUS;1 [15]
+ bld shift, 1 ;1 [16]
+rxbit2:
+ in x1, USBIN ;1 [17] <-- sample bit 2 (or possibly bit 1 stuffed)
+ andi shift, 0xf3 ;1 [18]
+ breq unstuff1 ;1 [19] do remaining work for bit 1
+didUnstuff1:
+ subi cnt, 1 ;1 [20]
+ brcs overflow ;1 [21] loop control
+ eor x2, x1 ;1 [22]
+ bst x2, USBMINUS;1 [23]
+ bld shift, 2 ;1 [24]
+ in x2, USBIN ;1 [25] <-- sample bit 3 (or possibly bit 2 stuffed)
+ andi shift, 0xe7 ;1 [26]
+ breq unstuff2 ;1 [27]
+didUnstuff2:
+ eor x1, x2 ;1 [28]
+ bst x1, USBMINUS;1 [29]
+ bld shift, 3 ;1 [30]
+didUnstuff3:
+ andi shift, 0xcf ;1 [31]
+ breq unstuff3 ;1 [32]
+ in x1, USBIN ;1 [33] <-- sample bit 4
+ eor x2, x1 ;1 [34]
+ bst x2, USBMINUS;1 [35]
+ bld shift, 4 ;1 [36]
+didUnstuff4:
+ andi shift, 0x9f ;1 [37]
+ breq unstuff4 ;1 [38]
+ nop2 ;2 [40]
+ in x2, USBIN ;1 [41] <-- sample bit 5
+ eor x1, x2 ;1 [42]
+ bst x1, USBMINUS;1 [43]
+ bld shift, 5 ;1 [44]
+didUnstuff5:
+ andi shift, 0x3f ;1 [45]
+ breq unstuff5 ;1 [46]
+ nop2 ;2 [48]
+ in x1, USBIN ;1 [49] <-- sample bit 6
+ eor x2, x1 ;1 [50]
+ bst x2, USBMINUS;1 [51]
+ bld shift, 6 ;1 [52]
+didUnstuff6:
+ cpi shift, 0x02 ;1 [53]
+ brlo unstuff6 ;1 [54]
+ nop2 ;2 [56]
+ in x2, USBIN ;1 [57] <-- sample bit 7
+ eor x1, x2 ;1 [58]
+ bst x1, USBMINUS;1 [59]
+ bld shift, 7 ;1 [60]
+didUnstuff7:
+ cpi shift, 0x04 ;1 [61]
+ brsh rxLoop ;2 [63] loop control
+unstuff7:
+ andi x3, ~0x80 ;1 [63]
+ ori shift, 0x80 ;1 [64]
+ in x2, USBIN ;1 [65] <-- sample stuffed bit 7
+ nop ;1 [66]
+ rjmp didUnstuff7 ;2 [68]
+
+macro POP_STANDARD ; 12 cycles
+ pop cnt
+ pop x3
+ pop x2
+ pop x1
+ pop shift
+ pop YH
+ endm
+macro POP_RETI ; 5 cycles
+ pop YL
+ out SREG, YL
+ pop YL
+ endm
+
+#include "asmcommon.inc"
+
+;----------------------------------------------------------------------------
+; Transmitting data
+;----------------------------------------------------------------------------
+
+txByteLoop:
+txBitloop:
+stuffN1Delay: ; [03]
+ ror shift ;[-5] [11] [59]
+ brcc doExorN1 ;[-4] [60]
+ subi x4, 1 ;[-3]
+ brne commonN1 ;[-2]
+ lsl shift ;[-1] compensate ror after rjmp stuffDelay
+ nop ;[00] stuffing consists of just waiting 8 cycles
+ rjmp stuffN1Delay ;[01] after ror, C bit is reliably clear
+
+sendNakAndReti: ;0 [-19] 19 cycles until SOP
+ ldi x3, USBPID_NAK ;1 [-18]
+ rjmp usbSendX3 ;2 [-16]
+sendAckAndReti: ;0 [-19] 19 cycles until SOP
+ ldi x3, USBPID_ACK ;1 [-18]
+ rjmp usbSendX3 ;2 [-16]
+sendCntAndReti: ;0 [-17] 17 cycles until SOP
+ mov x3, cnt ;1 [-16]
+usbSendX3: ;0 [-16]
+ ldi YL, 20 ;1 [-15] 'x3' is R20
+ ldi YH, 0 ;1 [-14]
+ ldi cnt, 2 ;1 [-13]
+; rjmp usbSendAndReti fallthrough
+
+; USB spec says:
+; idle = J
+; J = (D+ = 0), (D- = 1) or USBOUT = 0x01
+; K = (D+ = 1), (D- = 0) or USBOUT = 0x02
+; Spec allows 7.5 bit times from EOP to SOP for replies (= 60 cycles)
+
+;usbSend:
+;pointer to data in 'Y'
+;number of bytes in 'cnt' -- including sync byte
+;uses: x1...x2, x4, shift, cnt, Y [x1 = mirror USBOUT, x2 = USBMASK, x4 = bitstuff cnt]
+;Numbers in brackets are time since first bit of sync pattern is sent (start of instruction)
+usbSendAndReti:
+ in x2, USBDDR ;[-12] 12 cycles until SOP
+ ori x2, USBMASK ;[-11]
+ sbi USBOUT, USBMINUS ;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
+ out USBDDR, x2 ;[-8] <--- acquire bus
+ in x1, USBOUT ;[-7] port mirror for tx loop
+ ldi shift, 0x40 ;[-6] sync byte is first byte sent (we enter loop after ror)
+ ldi x2, USBMASK ;[-5]
+ push x4 ;[-4]
+doExorN1:
+ eor x1, x2 ;[-2] [06] [62]
+ ldi x4, 6 ;[-1] [07] [63]
+commonN1:
+stuffN2Delay:
+ out USBOUT, x1 ;[00] [08] [64] <--- set bit
+ ror shift ;[01]
+ brcc doExorN2 ;[02]
+ subi x4, 1 ;[03]
+ brne commonN2 ;[04]
+ lsl shift ;[05] compensate ror after rjmp stuffDelay
+ rjmp stuffN2Delay ;[06] after ror, C bit is reliably clear
+doExorN2:
+ eor x1, x2 ;[04] [12]
+ ldi x4, 6 ;[05] [13]
+commonN2:
+ nop ;[06] [14]
+ subi cnt, 171 ;[07] [15] trick: (3 * 171) & 0xff = 1
+ out USBOUT, x1 ;[08] [16] <--- set bit
+ brcs txBitloop ;[09] [25] [41]
+
+stuff6Delay:
+ ror shift ;[42] [50]
+ brcc doExor6 ;[43]
+ subi x4, 1 ;[44]
+ brne common6 ;[45]
+ lsl shift ;[46] compensate ror after rjmp stuffDelay
+ nop ;[47] stuffing consists of just waiting 8 cycles
+ rjmp stuff6Delay ;[48] after ror, C bit is reliably clear
+doExor6:
+ eor x1, x2 ;[45] [53]
+ ldi x4, 6 ;[46]
+common6:
+stuff7Delay:
+ ror shift ;[47] [55]
+ out USBOUT, x1 ;[48] <--- set bit
+ brcc doExor7 ;[49]
+ subi x4, 1 ;[50]
+ brne common7 ;[51]
+ lsl shift ;[52] compensate ror after rjmp stuffDelay
+ rjmp stuff7Delay ;[53] after ror, C bit is reliably clear
+doExor7:
+ eor x1, x2 ;[51] [59]
+ ldi x4, 6 ;[52]
+common7:
+ ld shift, y+ ;[53]
+ tst cnt ;[55]
+ out USBOUT, x1 ;[56] <--- set bit
+ brne txByteLoop ;[57]
+
+;make SE0:
+ cbr x1, USBMASK ;[58] prepare SE0 [spec says EOP may be 15 to 18 cycles]
+ lds x2, usbNewDeviceAddr;[59]
+ lsl x2 ;[61] we compare with left shifted address
+ subi YL, 2 + 20 ;[62] Only assign address on data packets, not ACK/NAK in x3
+ sbci YH, 0 ;[63]
+ out USBOUT, x1 ;[00] <-- out SE0 -- from now 2 bits = 16 cycles until bus idle
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
+;set address only after data packet was sent, not after handshake
+ breq skipAddrAssign ;[01]
+ sts usbDeviceAddr, x2 ; if not skipped: SE0 is one cycle longer
+skipAddrAssign:
+;end of usbDeviceAddress transfer
+ ldi x2, 1<<USB_INTR_PENDING_BIT;[03] int0 occurred during TX -- clear pending flag
+ USB_STORE_PENDING(x2) ;[04]
+ ori x1, USBIDLE ;[05]
+ in x2, USBDDR ;[06]
+ cbr x2, USBMASK ;[07] set both pins to input
+ mov x3, x1 ;[08]
+ cbr x3, USBMASK ;[09] configure no pullup on both pins
+ pop x4 ;[10]
+ nop2 ;[12]
+ nop2 ;[14]
+ out USBOUT, x1 ;[16] <-- out J (idle) -- end of SE0 (EOP signal)
+ out USBDDR, x2 ;[17] <-- release bus now
+ out USBOUT, x3 ;[18] <-- ensure no pull-up resistors are active
+ rjmp doReturn
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm128.inc b/tmk_core/protocol/vusb/usbdrv/usbdrvasm128.inc
new file mode 100644
index 000000000..bcd6621cc
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm128.inc
@@ -0,0 +1,750 @@
+/* Name: usbdrvasm128.inc
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2008-10-11
+ * Tabsize: 4
+ * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: usbdrvasm128.inc 758 2009-08-06 10:12:54Z cs $
+ */
+
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
+ * appropriate implementation!
+ */
+
+/*
+General Description:
+This file is the 12.8 MHz version of the USB driver. It is intended for use
+with the internal RC oscillator. Although 12.8 MHz is outside the guaranteed
+calibration range of the oscillator, almost all AVRs can reach this frequency.
+This version contains a phase locked loop in the receiver routine to cope with
+slight clock rate deviations of up to +/- 1%.
+
+See usbdrv.h for a description of the entire driver.
+
+LIMITATIONS
+===========
+Although it may seem very handy to save the crystal and use the internal
+RC oscillator of the CPU, this method (and this module) has some serious
+limitations:
+(1) The guaranteed calibration range of the oscillator is only 8.1 MHz.
+They typical range is 14.5 MHz and most AVRs can actually reach this rate.
+(2) Writing EEPROM and Flash may be unreliable (short data lifetime) since
+the write procedure is timed from the RC oscillator.
+(3) End Of Packet detection (SE0) should be in bit 1, bit it is only checked
+if bits 0 and 1 both read as 0 on D- and D+ read as 0 in the middle. This may
+cause problems with old hubs which delay SE0 by up to one cycle.
+(4) Code size is much larger than that of the other modules.
+
+Since almost all of this code is timing critical, don't change unless you
+really know what you are doing! Many parts require not only a maximum number
+of CPU cycles, but even an exact number of cycles!
+
+Implementation notes:
+======================
+min frequency: 67 cycles for 8 bit -> 12.5625 MHz
+max frequency: 69.286 cycles for 8 bit -> 12.99 MHz
+nominal frequency: 12.77 MHz ( = sqrt(min * max))
+
+sampling positions: (next even number in range [+/- 0.5])
+cycle index range: 0 ... 66
+bits:
+.5, 8.875, 17.25, 25.625, 34, 42.375, 50.75, 59.125
+[0/1], [9], [17], [25/+26], [34], [+42/43], [51], [59]
+
+bit number: 0 1 2 3 4 5 6 7
+spare cycles 1 2 1 2 1 1 1 0
+
+operations to perform: duration cycle
+ ----------------
+ eor fix, shift 1 -> 00
+ andi phase, USBMASK 1 -> 08
+ breq se0 1 -> 16 (moved to 11)
+ st y+, data 2 -> 24, 25
+ mov data, fix 1 -> 33
+ ser data 1 -> 41
+ subi cnt, 1 1 -> 49
+ brcs overflow 1 -> 50
+
+layout of samples and operations:
+[##] = sample bit
+<##> = sample phase
+*##* = operation
+
+0: *00* [01] 02 03 04 <05> 06 07
+1: *08* [09] 10 11 12 <13> 14 15 *16*
+2: [17] 18 19 20 <21> 22 23
+3: *24* *25* [26] 27 28 29 <30> 31 32
+4: *33* [34] 35 36 37 <38> 39 40
+5: *41* [42] 43 44 45 <46> 47 48
+6: *49* *50* [51] 52 53 54 <55> 56 57 58
+7: [59] 60 61 62 <63> 64 65 66
+*****************************************************************************/
+
+/* we prefer positive expressions (do if condition) instead of negative
+ * (skip if condition), therefore use defines for skip instructions:
+ */
+#define ifioclr sbis
+#define ifioset sbic
+#define ifrclr sbrs
+#define ifrset sbrc
+
+/* The registers "fix" and "data" swap their meaning during the loop. Use
+ * defines to keep their name constant.
+ */
+#define fix x2
+#define data x1
+#undef phase /* phase has a default definition to x4 */
+#define phase x3
+
+
+USB_INTR_VECTOR:
+;order of registers pushed: YL, SREG [sofError], YH, shift, x1, x2, x3, cnt, r0
+ push YL ;2 push only what is necessary to sync with edge ASAP
+ in YL, SREG ;1
+ push YL ;2
+;----------------------------------------------------------------------------
+; Synchronize with sync pattern:
+;----------------------------------------------------------------------------
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
+;sync up with J to K edge during sync pattern -- use fastest possible loops
+;The first part waits at most 1 bit long since we must be in sync pattern.
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
+;waitForJ, ensure that this prerequisite is met.
+waitForJ:
+ inc YL
+ sbis USBIN, USBMINUS
+ brne waitForJ ; just make sure we have ANY timeout
+waitForK:
+;The following code results in a sampling window of 1/4 bit which meets the spec.
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS ;[0]
+ rjmp foundK ;[1]
+#if USB_COUNT_SOF
+ lds YL, usbSofCount
+ inc YL
+ sts usbSofCount, YL
+#endif /* USB_COUNT_SOF */
+#ifdef USB_SOF_HOOK
+ USB_SOF_HOOK
+#endif
+ rjmp sofError
+
+foundK:
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 4 for center sampling]
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
+;are cycles from center of first sync (double K) bit after the instruction
+ push YH ;[2]
+ lds YL, usbInputBufOffset;[4]
+ clr YH ;[6]
+ subi YL, lo8(-(usbRxBuf));[7]
+ sbci YH, hi8(-(usbRxBuf));[8]
+
+ sbis USBIN, USBMINUS ;[9] we want two bits K [we want to sample at 8 + 4 - 1.5 = 10.5]
+ rjmp haveTwoBitsK ;[10]
+ pop YH ;[11] undo the push from before
+ rjmp waitForK ;[13] this was not the end of sync, retry
+haveTwoBitsK:
+;----------------------------------------------------------------------------
+; push more registers and initialize values while we sample the first bits:
+;----------------------------------------------------------------------------
+#define fix x2
+#define data x1
+
+ push shift ;[12]
+ push x1 ;[14]
+ push x2 ;[16]
+ ldi shift, 0x80 ;[18] prevent bit-unstuffing but init low bits to 0
+ ifioset USBIN, USBMINUS ;[19] [01] <--- bit 0 [10.5 + 8 = 18.5]
+ ori shift, 1<<0 ;[02]
+ push x3 ;[03]
+ push cnt ;[05]
+ push r0 ;[07]
+ ifioset USBIN, USBMINUS ;[09] <--- bit 1
+ ori shift, 1<<1 ;[10]
+ ser fix ;[11]
+ ldi cnt, USB_BUFSIZE ;[12]
+ mov data, shift ;[13]
+ lsl shift ;[14]
+ nop2 ;[15]
+ ifioset USBIN, USBMINUS ;[17] <--- bit 2
+ ori data, 3<<2 ;[18] store in bit 2 AND bit 3
+ eor shift, data ;[19] do nrzi decoding
+ andi data, 1<<3 ;[20]
+ in phase, USBIN ;[21] <- phase
+ brne jumpToEntryAfterSet ;[22] if USBMINS at bit 3 was 1
+ nop ;[23]
+ rjmp entryAfterClr ;[24]
+jumpToEntryAfterSet:
+ rjmp entryAfterSet ;[24]
+
+;----------------------------------------------------------------------------
+; Receiver loop (numbers in brackets are cycles within byte after instr)
+;----------------------------------------------------------------------------
+#undef fix
+#define fix x1
+#undef data
+#define data x2
+
+bit7IsSet:
+ ifrclr phase, USBMINUS ;[62] check phase only if D- changed
+ lpm ;[63]
+ in phase, USBIN ;[64] <- phase (one cycle too late)
+ ori shift, 1 << 7 ;[65]
+ nop ;[66]
+;;;;rjmp bit0AfterSet ; -> [00] == [67] moved block up to save jump
+bit0AfterSet:
+ eor fix, shift ;[00]
+#undef fix
+#define fix x2
+#undef data
+#define data x1 /* we now have result in data, fix is reset to 0xff */
+ ifioclr USBIN, USBMINUS ;[01] <--- sample 0
+ rjmp bit0IsClr ;[02]
+ andi shift, ~(7 << 0) ;[03]
+ breq unstuff0s ;[04]
+ in phase, USBIN ;[05] <- phase
+ rjmp bit1AfterSet ;[06]
+unstuff0s:
+ in phase, USBIN ;[06] <- phase (one cycle too late)
+ andi fix, ~(1 << 0) ;[07]
+ ifioclr USBIN, USBMINUS ;[00]
+ ifioset USBIN, USBPLUS ;[01]
+ rjmp bit0IsClr ;[02] executed if first expr false or second true
+se0AndStore: ; executed only if both bits 0
+ st y+, x1 ;[15/17] cycles after start of byte
+ rjmp se0 ;[17/19]
+
+bit0IsClr:
+ ifrset phase, USBMINUS ;[04] check phase only if D- changed
+ lpm ;[05]
+ in phase, USBIN ;[06] <- phase (one cycle too late)
+ ori shift, 1 << 0 ;[07]
+bit1AfterClr:
+ andi phase, USBMASK ;[08]
+ ifioset USBIN, USBMINUS ;[09] <--- sample 1
+ rjmp bit1IsSet ;[10]
+ breq se0AndStore ;[11] if D- was 0 in bits 0 AND 1 and D+ was 0 in between, we have SE0
+ andi shift, ~(7 << 1) ;[12]
+ in phase, USBIN ;[13] <- phase
+ breq unstuff1c ;[14]
+ rjmp bit2AfterClr ;[15]
+unstuff1c:
+ andi fix, ~(1 << 1) ;[16]
+ nop2 ;[08]
+ nop2 ;[10]
+bit1IsSet:
+ ifrclr phase, USBMINUS ;[12] check phase only if D- changed
+ lpm ;[13]
+ in phase, USBIN ;[14] <- phase (one cycle too late)
+ ori shift, 1 << 1 ;[15]
+ nop ;[16]
+bit2AfterSet:
+ ifioclr USBIN, USBMINUS ;[17] <--- sample 2
+ rjmp bit2IsClr ;[18]
+ andi shift, ~(7 << 2) ;[19]
+ breq unstuff2s ;[20]
+ in phase, USBIN ;[21] <- phase
+ rjmp bit3AfterSet ;[22]
+unstuff2s:
+ in phase, USBIN ;[22] <- phase (one cycle too late)
+ andi fix, ~(1 << 2) ;[23]
+ nop2 ;[16]
+ nop2 ;[18]
+bit2IsClr:
+ ifrset phase, USBMINUS ;[20] check phase only if D- changed
+ lpm ;[21]
+ in phase, USBIN ;[22] <- phase (one cycle too late)
+ ori shift, 1 << 2 ;[23]
+bit3AfterClr:
+ st y+, data ;[24]
+entryAfterClr:
+ ifioset USBIN, USBMINUS ;[26] <--- sample 3
+ rjmp bit3IsSet ;[27]
+ andi shift, ~(7 << 3) ;[28]
+ breq unstuff3c ;[29]
+ in phase, USBIN ;[30] <- phase
+ rjmp bit4AfterClr ;[31]
+unstuff3c:
+ in phase, USBIN ;[31] <- phase (one cycle too late)
+ andi fix, ~(1 << 3) ;[32]
+ nop2 ;[25]
+ nop2 ;[27]
+bit3IsSet:
+ ifrclr phase, USBMINUS ;[29] check phase only if D- changed
+ lpm ;[30]
+ in phase, USBIN ;[31] <- phase (one cycle too late)
+ ori shift, 1 << 3 ;[32]
+bit4AfterSet:
+ mov data, fix ;[33] undo this move by swapping defines
+#undef fix
+#define fix x1
+#undef data
+#define data x2
+ ifioclr USBIN, USBMINUS ;[34] <--- sample 4
+ rjmp bit4IsClr ;[35]
+ andi shift, ~(7 << 4) ;[36]
+ breq unstuff4s ;[37]
+ in phase, USBIN ;[38] <- phase
+ rjmp bit5AfterSet ;[39]
+unstuff4s:
+ in phase, USBIN ;[39] <- phase (one cycle too late)
+ andi fix, ~(1 << 4) ;[40]
+ nop2 ;[33]
+ nop2 ;[35]
+bit4IsClr:
+ ifrset phase, USBMINUS ;[37] check phase only if D- changed
+ lpm ;[38]
+ in phase, USBIN ;[39] <- phase (one cycle too late)
+ ori shift, 1 << 4 ;[40]
+bit5AfterClr:
+ ser data ;[41]
+ ifioset USBIN, USBMINUS ;[42] <--- sample 5
+ rjmp bit5IsSet ;[43]
+ andi shift, ~(7 << 5) ;[44]
+ breq unstuff5c ;[45]
+ in phase, USBIN ;[46] <- phase
+ rjmp bit6AfterClr ;[47]
+unstuff5c:
+ in phase, USBIN ;[47] <- phase (one cycle too late)
+ andi fix, ~(1 << 5) ;[48]
+ nop2 ;[41]
+ nop2 ;[43]
+bit5IsSet:
+ ifrclr phase, USBMINUS ;[45] check phase only if D- changed
+ lpm ;[46]
+ in phase, USBIN ;[47] <- phase (one cycle too late)
+ ori shift, 1 << 5 ;[48]
+bit6AfterSet:
+ subi cnt, 1 ;[49]
+ brcs jumpToOverflow ;[50]
+ ifioclr USBIN, USBMINUS ;[51] <--- sample 6
+ rjmp bit6IsClr ;[52]
+ andi shift, ~(3 << 6) ;[53]
+ cpi shift, 2 ;[54]
+ in phase, USBIN ;[55] <- phase
+ brlt unstuff6s ;[56]
+ rjmp bit7AfterSet ;[57]
+
+jumpToOverflow:
+ rjmp overflow
+
+unstuff6s:
+ andi fix, ~(1 << 6) ;[50]
+ lpm ;[51]
+bit6IsClr:
+ ifrset phase, USBMINUS ;[54] check phase only if D- changed
+ lpm ;[55]
+ in phase, USBIN ;[56] <- phase (one cycle too late)
+ ori shift, 1 << 6 ;[57]
+ nop ;[58]
+bit7AfterClr:
+ ifioset USBIN, USBMINUS ;[59] <--- sample 7
+ rjmp bit7IsSet ;[60]
+ andi shift, ~(1 << 7) ;[61]
+ cpi shift, 4 ;[62]
+ in phase, USBIN ;[63] <- phase
+ brlt unstuff7c ;[64]
+ rjmp bit0AfterClr ;[65] -> [00] == [67]
+unstuff7c:
+ andi fix, ~(1 << 7) ;[58]
+ nop ;[59]
+ rjmp bit7IsSet ;[60]
+
+bit7IsClr:
+ ifrset phase, USBMINUS ;[62] check phase only if D- changed
+ lpm ;[63]
+ in phase, USBIN ;[64] <- phase (one cycle too late)
+ ori shift, 1 << 7 ;[65]
+ nop ;[66]
+;;;;rjmp bit0AfterClr ; -> [00] == [67] moved block up to save jump
+bit0AfterClr:
+ eor fix, shift ;[00]
+#undef fix
+#define fix x2
+#undef data
+#define data x1 /* we now have result in data, fix is reset to 0xff */
+ ifioset USBIN, USBMINUS ;[01] <--- sample 0
+ rjmp bit0IsSet ;[02]
+ andi shift, ~(7 << 0) ;[03]
+ breq unstuff0c ;[04]
+ in phase, USBIN ;[05] <- phase
+ rjmp bit1AfterClr ;[06]
+unstuff0c:
+ in phase, USBIN ;[06] <- phase (one cycle too late)
+ andi fix, ~(1 << 0) ;[07]
+ ifioclr USBIN, USBMINUS ;[00]
+ ifioset USBIN, USBPLUS ;[01]
+ rjmp bit0IsSet ;[02] executed if first expr false or second true
+ rjmp se0AndStore ;[03] executed only if both bits 0
+bit0IsSet:
+ ifrclr phase, USBMINUS ;[04] check phase only if D- changed
+ lpm ;[05]
+ in phase, USBIN ;[06] <- phase (one cycle too late)
+ ori shift, 1 << 0 ;[07]
+bit1AfterSet:
+ andi shift, ~(7 << 1) ;[08] compensated by "ori shift, 1<<1" if bit1IsClr
+ ifioclr USBIN, USBMINUS ;[09] <--- sample 1
+ rjmp bit1IsClr ;[10]
+ breq unstuff1s ;[11]
+ nop2 ;[12] do not check for SE0 if bit 0 was 1
+ in phase, USBIN ;[14] <- phase (one cycle too late)
+ rjmp bit2AfterSet ;[15]
+unstuff1s:
+ in phase, USBIN ;[13] <- phase
+ andi fix, ~(1 << 1) ;[14]
+ lpm ;[07]
+ nop2 ;[10]
+bit1IsClr:
+ ifrset phase, USBMINUS ;[12] check phase only if D- changed
+ lpm ;[13]
+ in phase, USBIN ;[14] <- phase (one cycle too late)
+ ori shift, 1 << 1 ;[15]
+ nop ;[16]
+bit2AfterClr:
+ ifioset USBIN, USBMINUS ;[17] <--- sample 2
+ rjmp bit2IsSet ;[18]
+ andi shift, ~(7 << 2) ;[19]
+ breq unstuff2c ;[20]
+ in phase, USBIN ;[21] <- phase
+ rjmp bit3AfterClr ;[22]
+unstuff2c:
+ in phase, USBIN ;[22] <- phase (one cycle too late)
+ andi fix, ~(1 << 2) ;[23]
+ nop2 ;[16]
+ nop2 ;[18]
+bit2IsSet:
+ ifrclr phase, USBMINUS ;[20] check phase only if D- changed
+ lpm ;[21]
+ in phase, USBIN ;[22] <- phase (one cycle too late)
+ ori shift, 1 << 2 ;[23]
+bit3AfterSet:
+ st y+, data ;[24]
+entryAfterSet:
+ ifioclr USBIN, USBMINUS ;[26] <--- sample 3
+ rjmp bit3IsClr ;[27]
+ andi shift, ~(7 << 3) ;[28]
+ breq unstuff3s ;[29]
+ in phase, USBIN ;[30] <- phase
+ rjmp bit4AfterSet ;[31]
+unstuff3s:
+ in phase, USBIN ;[31] <- phase (one cycle too late)
+ andi fix, ~(1 << 3) ;[32]
+ nop2 ;[25]
+ nop2 ;[27]
+bit3IsClr:
+ ifrset phase, USBMINUS ;[29] check phase only if D- changed
+ lpm ;[30]
+ in phase, USBIN ;[31] <- phase (one cycle too late)
+ ori shift, 1 << 3 ;[32]
+bit4AfterClr:
+ mov data, fix ;[33] undo this move by swapping defines
+#undef fix
+#define fix x1
+#undef data
+#define data x2
+ ifioset USBIN, USBMINUS ;[34] <--- sample 4
+ rjmp bit4IsSet ;[35]
+ andi shift, ~(7 << 4) ;[36]
+ breq unstuff4c ;[37]
+ in phase, USBIN ;[38] <- phase
+ rjmp bit5AfterClr ;[39]
+unstuff4c:
+ in phase, USBIN ;[39] <- phase (one cycle too late)
+ andi fix, ~(1 << 4) ;[40]
+ nop2 ;[33]
+ nop2 ;[35]
+bit4IsSet:
+ ifrclr phase, USBMINUS ;[37] check phase only if D- changed
+ lpm ;[38]
+ in phase, USBIN ;[39] <- phase (one cycle too late)
+ ori shift, 1 << 4 ;[40]
+bit5AfterSet:
+ ser data ;[41]
+ ifioclr USBIN, USBMINUS ;[42] <--- sample 5
+ rjmp bit5IsClr ;[43]
+ andi shift, ~(7 << 5) ;[44]
+ breq unstuff5s ;[45]
+ in phase, USBIN ;[46] <- phase
+ rjmp bit6AfterSet ;[47]
+unstuff5s:
+ in phase, USBIN ;[47] <- phase (one cycle too late)
+ andi fix, ~(1 << 5) ;[48]
+ nop2 ;[41]
+ nop2 ;[43]
+bit5IsClr:
+ ifrset phase, USBMINUS ;[45] check phase only if D- changed
+ lpm ;[46]
+ in phase, USBIN ;[47] <- phase (one cycle too late)
+ ori shift, 1 << 5 ;[48]
+bit6AfterClr:
+ subi cnt, 1 ;[49]
+ brcs overflow ;[50]
+ ifioset USBIN, USBMINUS ;[51] <--- sample 6
+ rjmp bit6IsSet ;[52]
+ andi shift, ~(3 << 6) ;[53]
+ cpi shift, 2 ;[54]
+ in phase, USBIN ;[55] <- phase
+ brlt unstuff6c ;[56]
+ rjmp bit7AfterClr ;[57]
+unstuff6c:
+ andi fix, ~(1 << 6) ;[50]
+ lpm ;[51]
+bit6IsSet:
+ ifrclr phase, USBMINUS ;[54] check phase only if D- changed
+ lpm ;[55]
+ in phase, USBIN ;[56] <- phase (one cycle too late)
+ ori shift, 1 << 6 ;[57]
+bit7AfterSet:
+ ifioclr USBIN, USBMINUS ;[59] <--- sample 7
+ rjmp bit7IsClr ;[60]
+ andi shift, ~(1 << 7) ;[61]
+ cpi shift, 4 ;[62]
+ in phase, USBIN ;[63] <- phase
+ brlt unstuff7s ;[64]
+ rjmp bit0AfterSet ;[65] -> [00] == [67]
+unstuff7s:
+ andi fix, ~(1 << 7) ;[58]
+ nop ;[59]
+ rjmp bit7IsClr ;[60]
+
+macro POP_STANDARD ; 14 cycles
+ pop r0
+ pop cnt
+ pop x3
+ pop x2
+ pop x1
+ pop shift
+ pop YH
+ endm
+macro POP_RETI ; 5 cycles
+ pop YL
+ out SREG, YL
+ pop YL
+ endm
+
+#include "asmcommon.inc"
+
+;----------------------------------------------------------------------------
+; Transmitting data
+;----------------------------------------------------------------------------
+
+txByteLoop:
+txBitloop:
+stuffN1Delay: ; [03]
+ ror shift ;[-5] [11] [63]
+ brcc doExorN1 ;[-4] [64]
+ subi x3, 1 ;[-3]
+ brne commonN1 ;[-2]
+ lsl shift ;[-1] compensate ror after rjmp stuffDelay
+ nop ;[00] stuffing consists of just waiting 8 cycles
+ rjmp stuffN1Delay ;[01] after ror, C bit is reliably clear
+
+sendNakAndReti:
+ ldi cnt, USBPID_NAK ;[-19]
+ rjmp sendCntAndReti ;[-18]
+sendAckAndReti:
+ ldi cnt, USBPID_ACK ;[-17]
+sendCntAndReti:
+ mov r0, cnt ;[-16]
+ ldi YL, 0 ;[-15] R0 address is 0
+ ldi YH, 0 ;[-14]
+ ldi cnt, 2 ;[-13]
+; rjmp usbSendAndReti fallthrough
+
+; USB spec says:
+; idle = J
+; J = (D+ = 0), (D- = 1) or USBOUT = 0x01
+; K = (D+ = 1), (D- = 0) or USBOUT = 0x02
+; Spec allows 7.5 bit times from EOP to SOP for replies (= 60 cycles)
+
+;usbSend:
+;pointer to data in 'Y'
+;number of bytes in 'cnt' -- including sync byte
+;uses: x1...x3, shift, cnt, Y [x1 = mirror USBOUT, x2 = USBMASK, x3 = bitstuff cnt]
+;Numbers in brackets are time since first bit of sync pattern is sent (start of instruction)
+usbSendAndReti:
+ in x2, USBDDR ;[-10] 10 cycles until SOP
+ ori x2, USBMASK ;[-9]
+ sbi USBOUT, USBMINUS ;[-8] prepare idle state; D+ and D- must have been 0 (no pullups)
+ out USBDDR, x2 ;[-6] <--- acquire bus
+ in x1, USBOUT ;[-5] port mirror for tx loop
+ ldi shift, 0x40 ;[-4] sync byte is first byte sent (we enter loop after ror)
+ ldi x2, USBMASK ;[-3]
+doExorN1:
+ eor x1, x2 ;[-2] [06] [62]
+ ldi x3, 6 ;[-1] [07] [63]
+commonN1:
+stuffN2Delay:
+ out USBOUT, x1 ;[00] [08] [64] <--- set bit
+ ror shift ;[01]
+ brcc doExorN2 ;[02]
+ subi x3, 1 ;[03]
+ brne commonN2 ;[04]
+ lsl shift ;[05] compensate ror after rjmp stuffDelay
+ rjmp stuffN2Delay ;[06] after ror, C bit is reliably clear
+doExorN2:
+ eor x1, x2 ;[04] [12]
+ ldi x3, 6 ;[05] [13]
+commonN2:
+ nop2 ;[06] [14]
+ subi cnt, 171 ;[08] [16] trick: (3 * 171) & 0xff = 1
+ out USBOUT, x1 ;[09] [17] <--- set bit
+ brcs txBitloop ;[10] [27] [44]
+
+stuff6Delay:
+ ror shift ;[45] [53]
+ brcc doExor6 ;[46]
+ subi x3, 1 ;[47]
+ brne common6 ;[48]
+ lsl shift ;[49] compensate ror after rjmp stuffDelay
+ nop ;[50] stuffing consists of just waiting 8 cycles
+ rjmp stuff6Delay ;[51] after ror, C bit is reliably clear
+doExor6:
+ eor x1, x2 ;[48] [56]
+ ldi x3, 6 ;[49]
+common6:
+stuff7Delay:
+ ror shift ;[50] [58]
+ out USBOUT, x1 ;[51] <--- set bit
+ brcc doExor7 ;[52]
+ subi x3, 1 ;[53]
+ brne common7 ;[54]
+ lsl shift ;[55] compensate ror after rjmp stuffDelay
+ rjmp stuff7Delay ;[56] after ror, C bit is reliably clear
+doExor7:
+ eor x1, x2 ;[54] [62]
+ ldi x3, 6 ;[55]
+common7:
+ ld shift, y+ ;[56]
+ nop ;[58]
+ tst cnt ;[59]
+ out USBOUT, x1 ;[60] [00]<--- set bit
+ brne txByteLoop ;[61] [01]
+;make SE0:
+ cbr x1, USBMASK ;[02] prepare SE0 [spec says EOP may be 15 to 18 cycles]
+ lds x2, usbNewDeviceAddr;[03]
+ lsl x2 ;[05] we compare with left shifted address
+ subi YL, 2 + 0 ;[06] Only assign address on data packets, not ACK/NAK in r0
+ sbci YH, 0 ;[07]
+ out USBOUT, x1 ;[00] <-- out SE0 -- from now 2 bits = 16 cycles until bus idle
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
+;set address only after data packet was sent, not after handshake
+ breq skipAddrAssign ;[01]
+ sts usbDeviceAddr, x2 ; if not skipped: SE0 is one cycle longer
+skipAddrAssign:
+;end of usbDeviceAddress transfer
+ ldi x2, 1<<USB_INTR_PENDING_BIT;[03] int0 occurred during TX -- clear pending flag
+ USB_STORE_PENDING(x2) ;[04]
+ ori x1, USBIDLE ;[05]
+ in x2, USBDDR ;[06]
+ cbr x2, USBMASK ;[07] set both pins to input
+ mov x3, x1 ;[08]
+ cbr x3, USBMASK ;[09] configure no pullup on both pins
+ lpm ;[10]
+ lpm ;[13]
+ out USBOUT, x1 ;[16] <-- out J (idle) -- end of SE0 (EOP signal)
+ out USBDDR, x2 ;[17] <-- release bus now
+ out USBOUT, x3 ;[18] <-- ensure no pull-up resistors are active
+ rjmp doReturn
+
+
+
+/*****************************************************************************
+The following PHP script generates a code skeleton for the receiver routine:
+
+<?php
+
+function printCmdBuffer($thisBit)
+{
+global $cycle;
+
+ $nextBit = ($thisBit + 1) % 8;
+ $s = ob_get_contents();
+ ob_end_clean();
+ $s = str_replace("#", $thisBit, $s);
+ $s = str_replace("@", $nextBit, $s);
+ $lines = explode("\n", $s);
+ for($i = 0; $i < count($lines); $i++){
+ $s = $lines[$i];
+ if(ereg("\\[([0-9-][0-9])\\]", $s, $regs)){
+ $c = $cycle + (int)$regs[1];
+ $s = ereg_replace("\\[[0-9-][0-9]\\]", sprintf("[%02d]", $c), $s);
+ }
+ if(strlen($s) > 0)
+ echo "$s\n";
+ }
+}
+
+function printBit($isAfterSet, $bitNum)
+{
+ ob_start();
+ if($isAfterSet){
+?>
+ ifioclr USBIN, USBMINUS ;[00] <--- sample
+ rjmp bit#IsClr ;[01]
+ andi shift, ~(7 << #) ;[02]
+ breq unstuff#s ;[03]
+ in phase, USBIN ;[04] <- phase
+ rjmp bit@AfterSet ;[05]
+unstuff#s:
+ in phase, USBIN ;[05] <- phase (one cycle too late)
+ andi fix, ~(1 << #) ;[06]
+ nop2 ;[-1]
+ nop2 ;[01]
+bit#IsClr:
+ ifrset phase, USBMINUS ;[03] check phase only if D- changed
+ lpm ;[04]
+ in phase, USBIN ;[05] <- phase (one cycle too late)
+ ori shift, 1 << # ;[06]
+<?php
+ }else{
+?>
+ ifioset USBIN, USBMINUS ;[00] <--- sample
+ rjmp bit#IsSet ;[01]
+ andi shift, ~(7 << #) ;[02]
+ breq unstuff#c ;[03]
+ in phase, USBIN ;[04] <- phase
+ rjmp bit@AfterClr ;[05]
+unstuff#c:
+ in phase, USBIN ;[05] <- phase (one cycle too late)
+ andi fix, ~(1 << #) ;[06]
+ nop2 ;[-1]
+ nop2 ;[01]
+bit#IsSet:
+ ifrclr phase, USBMINUS ;[03] check phase only if D- changed
+ lpm ;[04]
+ in phase, USBIN ;[05] <- phase (one cycle too late)
+ ori shift, 1 << # ;[06]
+<?php
+ }
+ printCmdBuffer($bitNum);
+}
+
+$bitStartCycles = array(1, 9, 17, 26, 34, 42, 51, 59);
+for($i = 0; $i < 16; $i++){
+ $bit = $i % 8;
+ $emitClrCode = ($i + (int)($i / 8)) % 2;
+ $cycle = $bitStartCycles[$bit];
+ if($emitClrCode){
+ printf("bit%dAfterClr:\n", $bit);
+ }else{
+ printf("bit%dAfterSet:\n", $bit);
+ }
+ ob_start();
+ echo " ***** ;[-1]\n";
+ printCmdBuffer($bit);
+ printBit(!$emitClrCode, $bit);
+ if($i == 7)
+ echo "\n";
+}
+
+?>
+*****************************************************************************/
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm15.inc b/tmk_core/protocol/vusb/usbdrv/usbdrvasm15.inc
new file mode 100644
index 000000000..401b7f8ff
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm15.inc
@@ -0,0 +1,423 @@
+/* Name: usbdrvasm15.inc
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: contributed by V. Bosch
+ * Creation Date: 2007-08-06
+ * Tabsize: 4
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * Revision: $Id: usbdrvasm15.inc 740 2009-04-13 18:23:31Z cs $
+ */
+
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
+ * appropriate implementation!
+ */
+
+/*
+General Description:
+This file is the 15 MHz version of the asssembler part of the USB driver. It
+requires a 15 MHz crystal (not a ceramic resonator and not a calibrated RC
+oscillator).
+
+See usbdrv.h for a description of the entire driver.
+
+Since almost all of this code is timing critical, don't change unless you
+really know what you are doing! Many parts require not only a maximum number
+of CPU cycles, but even an exact number of cycles!
+*/
+
+;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes
+;nominal frequency: 15 MHz -> 10.0 cycles per bit, 80.0 cycles per byte
+; Numbers in brackets are clocks counted from center of last sync bit
+; when instruction starts
+
+;----------------------------------------------------------------------------
+; order of registers pushed:
+; YL, SREG [sofError] YH, shift, x1, x2, x3, bitcnt, cnt, x4
+;----------------------------------------------------------------------------
+USB_INTR_VECTOR:
+ push YL ;2 push only what is necessary to sync with edge ASAP
+ in YL, SREG ;1
+ push YL ;2
+;----------------------------------------------------------------------------
+; Synchronize with sync pattern:
+;
+; sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
+; sync up with J to K edge during sync pattern -- use fastest possible loops
+;The first part waits at most 1 bit long since we must be in sync pattern.
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
+;waitForJ, ensure that this prerequisite is met.
+waitForJ:
+ inc YL
+ sbis USBIN, USBMINUS
+ brne waitForJ ; just make sure we have ANY timeout
+;-------------------------------------------------------------------------------
+; The following code results in a sampling window of < 1/4 bit
+; which meets the spec.
+;-------------------------------------------------------------------------------
+waitForK: ;-
+ sbis USBIN, USBMINUS ;1 [00] <-- sample
+ rjmp foundK ;2 [01]
+ sbis USBIN, USBMINUS ; <-- sample
+ rjmp foundK
+ sbis USBIN, USBMINUS ; <-- sample
+ rjmp foundK
+ sbis USBIN, USBMINUS ; <-- sample
+ rjmp foundK
+ sbis USBIN, USBMINUS ; <-- sample
+ rjmp foundK
+ sbis USBIN, USBMINUS ; <-- sample
+ rjmp foundK
+#if USB_COUNT_SOF
+ lds YL, usbSofCount
+ inc YL
+ sts usbSofCount, YL
+#endif /* USB_COUNT_SOF */
+#ifdef USB_SOF_HOOK
+ USB_SOF_HOOK
+#endif
+ rjmp sofError
+;------------------------------------------------------------------------------
+; {3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for
+; center sampling]
+; we have 1 bit time for setup purposes, then sample again.
+; Numbers in brackets are cycles from center of first sync (double K)
+; bit after the instruction
+;------------------------------------------------------------------------------
+foundK: ;- [02]
+ lds YL, usbInputBufOffset;2 [03+04] tx loop
+ push YH ;2 [05+06]
+ clr YH ;1 [07]
+ subi YL, lo8(-(usbRxBuf)) ;1 [08] [rx loop init]
+ sbci YH, hi8(-(usbRxBuf)) ;1 [09] [rx loop init]
+ push shift ;2 [10+11]
+ ser shift ;1 [12]
+ sbis USBIN, USBMINUS ;1 [-1] [13] <--sample:we want two bits K (sample 1 cycle too early)
+ rjmp haveTwoBitsK ;2 [00] [14]
+ pop shift ;2 [15+16] undo the push from before
+ pop YH ;2 [17+18] undo the push from before
+ rjmp waitForK ;2 [19+20] this was not the end of sync, retry
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
+; bit times (= 20 cycles).
+
+;----------------------------------------------------------------------------
+; push more registers and initialize values while we sample the first bits:
+;----------------------------------------------------------------------------
+haveTwoBitsK: ;- [01]
+ push x1 ;2 [02+03]
+ push x2 ;2 [04+05]
+ push x3 ;2 [06+07]
+ push bitcnt ;2 [08+09]
+ in x1, USBIN ;1 [00] [10] <-- sample bit 0
+ bst x1, USBMINUS ;1 [01]
+ bld shift, 0 ;1 [02]
+ push cnt ;2 [03+04]
+ ldi cnt, USB_BUFSIZE ;1 [05]
+ push x4 ;2 [06+07] tx loop
+ rjmp rxLoop ;2 [08]
+;----------------------------------------------------------------------------
+; Receiver loop (numbers in brackets are cycles within byte after instr)
+;----------------------------------------------------------------------------
+unstuff0: ;- [07] (branch taken)
+ andi x3, ~0x01 ;1 [08]
+ mov x1, x2 ;1 [09] x2 contains last sampled (stuffed) bit
+ in x2, USBIN ;1 [00] [10] <-- sample bit 1 again
+ andi x2, USBMASK ;1 [01]
+ breq se0Hop ;1 [02] SE0 check for bit 1
+ ori shift, 0x01 ;1 [03] 0b00000001
+ nop ;1 [04]
+ rjmp didUnstuff0 ;2 [05]
+;-----------------------------------------------------
+unstuff1: ;- [05] (branch taken)
+ mov x2, x1 ;1 [06] x1 contains last sampled (stuffed) bit
+ andi x3, ~0x02 ;1 [07]
+ ori shift, 0x02 ;1 [08] 0b00000010
+ nop ;1 [09]
+ in x1, USBIN ;1 [00] [10] <-- sample bit 2 again
+ andi x1, USBMASK ;1 [01]
+ breq se0Hop ;1 [02] SE0 check for bit 2
+ rjmp didUnstuff1 ;2 [03]
+;-----------------------------------------------------
+unstuff2: ;- [05] (branch taken)
+ andi x3, ~0x04 ;1 [06]
+ ori shift, 0x04 ;1 [07] 0b00000100
+ mov x1, x2 ;1 [08] x2 contains last sampled (stuffed) bit
+ nop ;1 [09]
+ in x2, USBIN ;1 [00] [10] <-- sample bit 3
+ andi x2, USBMASK ;1 [01]
+ breq se0Hop ;1 [02] SE0 check for bit 3
+ rjmp didUnstuff2 ;2 [03]
+;-----------------------------------------------------
+unstuff3: ;- [00] [10] (branch taken)
+ in x2, USBIN ;1 [01] [11] <-- sample stuffed bit 3 one cycle too late
+ andi x2, USBMASK ;1 [02]
+ breq se0Hop ;1 [03] SE0 check for stuffed bit 3
+ andi x3, ~0x08 ;1 [04]
+ ori shift, 0x08 ;1 [05] 0b00001000
+ rjmp didUnstuff3 ;2 [06]
+;----------------------------------------------------------------------------
+; extra jobs done during bit interval:
+;
+; bit 0: store, clear [SE0 is unreliable here due to bit dribbling in hubs],
+; overflow check, jump to the head of rxLoop
+; bit 1: SE0 check
+; bit 2: SE0 check, recovery from delay [bit 0 tasks took too long]
+; bit 3: SE0 check, recovery from delay [bit 0 tasks took too long]
+; bit 4: SE0 check, none
+; bit 5: SE0 check, none
+; bit 6: SE0 check, none
+; bit 7: SE0 check, reconstruct: x3 is 0 at bit locations we changed, 1 at others
+;----------------------------------------------------------------------------
+rxLoop: ;- [09]
+ in x2, USBIN ;1 [00] [10] <-- sample bit 1 (or possibly bit 0 stuffed)
+ andi x2, USBMASK ;1 [01]
+ brne SkipSe0Hop ;1 [02]
+se0Hop: ;- [02]
+ rjmp se0 ;2 [03] SE0 check for bit 1
+SkipSe0Hop: ;- [03]
+ ser x3 ;1 [04]
+ andi shift, 0xf9 ;1 [05] 0b11111001
+ breq unstuff0 ;1 [06]
+didUnstuff0: ;- [06]
+ eor x1, x2 ;1 [07]
+ bst x1, USBMINUS ;1 [08]
+ bld shift, 1 ;1 [09]
+ in x1, USBIN ;1 [00] [10] <-- sample bit 2 (or possibly bit 1 stuffed)
+ andi x1, USBMASK ;1 [01]
+ breq se0Hop ;1 [02] SE0 check for bit 2
+ andi shift, 0xf3 ;1 [03] 0b11110011
+ breq unstuff1 ;1 [04] do remaining work for bit 1
+didUnstuff1: ;- [04]
+ eor x2, x1 ;1 [05]
+ bst x2, USBMINUS ;1 [06]
+ bld shift, 2 ;1 [07]
+ nop2 ;2 [08+09]
+ in x2, USBIN ;1 [00] [10] <-- sample bit 3 (or possibly bit 2 stuffed)
+ andi x2, USBMASK ;1 [01]
+ breq se0Hop ;1 [02] SE0 check for bit 3
+ andi shift, 0xe7 ;1 [03] 0b11100111
+ breq unstuff2 ;1 [04]
+didUnstuff2: ;- [04]
+ eor x1, x2 ;1 [05]
+ bst x1, USBMINUS ;1 [06]
+ bld shift, 3 ;1 [07]
+didUnstuff3: ;- [07]
+ andi shift, 0xcf ;1 [08] 0b11001111
+ breq unstuff3 ;1 [09]
+ in x1, USBIN ;1 [00] [10] <-- sample bit 4
+ andi x1, USBMASK ;1 [01]
+ breq se0Hop ;1 [02] SE0 check for bit 4
+ eor x2, x1 ;1 [03]
+ bst x2, USBMINUS ;1 [04]
+ bld shift, 4 ;1 [05]
+didUnstuff4: ;- [05]
+ andi shift, 0x9f ;1 [06] 0b10011111
+ breq unstuff4 ;1 [07]
+ nop2 ;2 [08+09]
+ in x2, USBIN ;1 [00] [10] <-- sample bit 5
+ andi x2, USBMASK ;1 [01]
+ breq se0 ;1 [02] SE0 check for bit 5
+ eor x1, x2 ;1 [03]
+ bst x1, USBMINUS ;1 [04]
+ bld shift, 5 ;1 [05]
+didUnstuff5: ;- [05]
+ andi shift, 0x3f ;1 [06] 0b00111111
+ breq unstuff5 ;1 [07]
+ nop2 ;2 [08+09]
+ in x1, USBIN ;1 [00] [10] <-- sample bit 6
+ andi x1, USBMASK ;1 [01]
+ breq se0 ;1 [02] SE0 check for bit 6
+ eor x2, x1 ;1 [03]
+ bst x2, USBMINUS ;1 [04]
+ bld shift, 6 ;1 [05]
+didUnstuff6: ;- [05]
+ cpi shift, 0x02 ;1 [06] 0b00000010
+ brlo unstuff6 ;1 [07]
+ nop2 ;2 [08+09]
+ in x2, USBIN ;1 [00] [10] <-- sample bit 7
+ andi x2, USBMASK ;1 [01]
+ breq se0 ;1 [02] SE0 check for bit 7
+ eor x1, x2 ;1 [03]
+ bst x1, USBMINUS ;1 [04]
+ bld shift, 7 ;1 [05]
+didUnstuff7: ;- [05]
+ cpi shift, 0x04 ;1 [06] 0b00000100
+ brlo unstuff7 ;1 [07]
+ eor x3, shift ;1 [08] reconstruct: x3 is 0 at bit locations we changed, 1 at others
+ nop ;1 [09]
+ in x1, USBIN ;1 [00] [10] <-- sample bit 0
+ st y+, x3 ;2 [01+02] store data
+ eor x2, x1 ;1 [03]
+ bst x2, USBMINUS ;1 [04]
+ bld shift, 0 ;1 [05]
+ subi cnt, 1 ;1 [06]
+ brcs overflow ;1 [07]
+ rjmp rxLoop ;2 [08]
+;-----------------------------------------------------
+unstuff4: ;- [08]
+ andi x3, ~0x10 ;1 [09]
+ in x1, USBIN ;1 [00] [10] <-- sample stuffed bit 4
+ andi x1, USBMASK ;1 [01]
+ breq se0 ;1 [02] SE0 check for stuffed bit 4
+ ori shift, 0x10 ;1 [03]
+ rjmp didUnstuff4 ;2 [04]
+;-----------------------------------------------------
+unstuff5: ;- [08]
+ ori shift, 0x20 ;1 [09]
+ in x2, USBIN ;1 [00] [10] <-- sample stuffed bit 5
+ andi x2, USBMASK ;1 [01]
+ breq se0 ;1 [02] SE0 check for stuffed bit 5
+ andi x3, ~0x20 ;1 [03]
+ rjmp didUnstuff5 ;2 [04]
+;-----------------------------------------------------
+unstuff6: ;- [08]
+ andi x3, ~0x40 ;1 [09]
+ in x1, USBIN ;1 [00] [10] <-- sample stuffed bit 6
+ andi x1, USBMASK ;1 [01]
+ breq se0 ;1 [02] SE0 check for stuffed bit 6
+ ori shift, 0x40 ;1 [03]
+ rjmp didUnstuff6 ;2 [04]
+;-----------------------------------------------------
+unstuff7: ;- [08]
+ andi x3, ~0x80 ;1 [09]
+ in x2, USBIN ;1 [00] [10] <-- sample stuffed bit 7
+ andi x2, USBMASK ;1 [01]
+ breq se0 ;1 [02] SE0 check for stuffed bit 7
+ ori shift, 0x80 ;1 [03]
+ rjmp didUnstuff7 ;2 [04]
+
+macro POP_STANDARD ; 16 cycles
+ pop x4
+ pop cnt
+ pop bitcnt
+ pop x3
+ pop x2
+ pop x1
+ pop shift
+ pop YH
+ endm
+macro POP_RETI ; 5 cycles
+ pop YL
+ out SREG, YL
+ pop YL
+ endm
+
+#include "asmcommon.inc"
+
+;---------------------------------------------------------------------------
+; USB spec says:
+; idle = J
+; J = (D+ = 0), (D- = 1)
+; K = (D+ = 1), (D- = 0)
+; Spec allows 7.5 bit times from EOP to SOP for replies
+;---------------------------------------------------------------------------
+bitstuffN: ;- [04]
+ eor x1, x4 ;1 [05]
+ clr x2 ;1 [06]
+ nop ;1 [07]
+ rjmp didStuffN ;1 [08]
+;---------------------------------------------------------------------------
+bitstuff6: ;- [04]
+ eor x1, x4 ;1 [05]
+ clr x2 ;1 [06]
+ rjmp didStuff6 ;1 [07]
+;---------------------------------------------------------------------------
+bitstuff7: ;- [02]
+ eor x1, x4 ;1 [03]
+ clr x2 ;1 [06]
+ nop ;1 [05]
+ rjmp didStuff7 ;1 [06]
+;---------------------------------------------------------------------------
+sendNakAndReti: ;- [-19]
+ ldi x3, USBPID_NAK ;1 [-18]
+ rjmp sendX3AndReti ;1 [-17]
+;---------------------------------------------------------------------------
+sendAckAndReti: ;- [-17]
+ ldi cnt, USBPID_ACK ;1 [-16]
+sendCntAndReti: ;- [-16]
+ mov x3, cnt ;1 [-15]
+sendX3AndReti: ;- [-15]
+ ldi YL, 20 ;1 [-14] x3==r20 address is 20
+ ldi YH, 0 ;1 [-13]
+ ldi cnt, 2 ;1 [-12]
+; rjmp usbSendAndReti fallthrough
+;---------------------------------------------------------------------------
+;usbSend:
+;pointer to data in 'Y'
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
+;uses: x1...x4, btcnt, shift, cnt, Y
+;Numbers in brackets are time since first bit of sync pattern is sent
+;We need not to match the transfer rate exactly because the spec demands
+;only 1.5% precision anyway.
+usbSendAndReti: ;- [-13] 13 cycles until SOP
+ in x2, USBDDR ;1 [-12]
+ ori x2, USBMASK ;1 [-11]
+ sbi USBOUT, USBMINUS ;2 [-09-10] prepare idle state; D+ and D- must have been 0 (no pullups)
+ in x1, USBOUT ;1 [-08] port mirror for tx loop
+ out USBDDR, x2 ;1 [-07] <- acquire bus
+ ; need not init x2 (bitstuff history) because sync starts with 0
+ ldi x4, USBMASK ;1 [-06] exor mask
+ ldi shift, 0x80 ;1 [-05] sync byte is first byte sent
+ ldi bitcnt, 6 ;1 [-04]
+txBitLoop: ;- [-04] [06]
+ sbrs shift, 0 ;1 [-03] [07]
+ eor x1, x4 ;1 [-02] [08]
+ ror shift ;1 [-01] [09]
+didStuffN: ;- [09]
+ out USBOUT, x1 ;1 [00] [10] <-- out N
+ ror x2 ;1 [01]
+ cpi x2, 0xfc ;1 [02]
+ brcc bitstuffN ;1 [03]
+ dec bitcnt ;1 [04]
+ brne txBitLoop ;1 [05]
+ sbrs shift, 0 ;1 [06]
+ eor x1, x4 ;1 [07]
+ ror shift ;1 [08]
+didStuff6: ;- [08]
+ nop ;1 [09]
+ out USBOUT, x1 ;1 [00] [10] <-- out 6
+ ror x2 ;1 [01]
+ cpi x2, 0xfc ;1 [02]
+ brcc bitstuff6 ;1 [03]
+ sbrs shift, 0 ;1 [04]
+ eor x1, x4 ;1 [05]
+ ror shift ;1 [06]
+ ror x2 ;1 [07]
+didStuff7: ;- [07]
+ ldi bitcnt, 6 ;1 [08]
+ cpi x2, 0xfc ;1 [09]
+ out USBOUT, x1 ;1 [00] [10] <-- out 7
+ brcc bitstuff7 ;1 [01]
+ ld shift, y+ ;2 [02+03]
+ dec cnt ;1 [04]
+ brne txBitLoop ;1 [05]
+makeSE0:
+ cbr x1, USBMASK ;1 [06] prepare SE0 [spec says EOP may be 19 to 23 cycles]
+ lds x2, usbNewDeviceAddr;2 [07+08]
+ lsl x2 ;1 [09] we compare with left shifted address
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
+;set address only after data packet was sent, not after handshake
+ out USBOUT, x1 ;1 [00] [10] <-- out SE0-- from now 2 bits==20 cycl. until bus idle
+ subi YL, 20 + 2 ;1 [01] Only assign address on data packets, not ACK/NAK in x3
+ sbci YH, 0 ;1 [02]
+ breq skipAddrAssign ;1 [03]
+ sts usbDeviceAddr, x2 ;2 [04+05] if not skipped: SE0 is one cycle longer
+;----------------------------------------------------------------------------
+;end of usbDeviceAddress transfer
+skipAddrAssign: ;- [03/04]
+ ldi x2, 1<<USB_INTR_PENDING_BIT ;1 [05] int0 occurred during TX -- clear pending flag
+ USB_STORE_PENDING(x2) ;1 [06]
+ ori x1, USBIDLE ;1 [07]
+ in x2, USBDDR ;1 [08]
+ cbr x2, USBMASK ;1 [09] set both pins to input
+ mov x3, x1 ;1 [10]
+ cbr x3, USBMASK ;1 [11] configure no pullup on both pins
+ ldi x4, 3 ;1 [12]
+se0Delay: ;- [12] [15]
+ dec x4 ;1 [13] [16]
+ brne se0Delay ;1 [14] [17]
+ nop2 ;2 [18+19]
+ out USBOUT, x1 ;1 [20] <--out J (idle) -- end of SE0 (EOP sig.)
+ out USBDDR, x2 ;1 [21] <--release bus now
+ out USBOUT, x3 ;1 [22] <--ensure no pull-up resistors are active
+ rjmp doReturn ;1 [23]
+;---------------------------------------------------------------------------
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm16.inc b/tmk_core/protocol/vusb/usbdrv/usbdrvasm16.inc
new file mode 100644
index 000000000..207b6e48a
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm16.inc
@@ -0,0 +1,346 @@
+/* Name: usbdrvasm16.inc
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2007-06-15
+ * Tabsize: 4
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * Revision: $Id: usbdrvasm16.inc 760 2009-08-09 18:59:43Z cs $
+ */
+
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
+ * appropriate implementation!
+ */
+
+/*
+General Description:
+This file is the 16 MHz version of the asssembler part of the USB driver. It
+requires a 16 MHz crystal (not a ceramic resonator and not a calibrated RC
+oscillator).
+
+See usbdrv.h for a description of the entire driver.
+
+Since almost all of this code is timing critical, don't change unless you
+really know what you are doing! Many parts require not only a maximum number
+of CPU cycles, but even an exact number of cycles!
+*/
+
+;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes
+;nominal frequency: 16 MHz -> 10.6666666 cycles per bit, 85.333333333 cycles per byte
+; Numbers in brackets are clocks counted from center of last sync bit
+; when instruction starts
+
+USB_INTR_VECTOR:
+;order of registers pushed: YL, SREG YH, [sofError], bitcnt, shift, x1, x2, x3, x4, cnt
+ push YL ;[-25] push only what is necessary to sync with edge ASAP
+ in YL, SREG ;[-23]
+ push YL ;[-22]
+ push YH ;[-20]
+;----------------------------------------------------------------------------
+; Synchronize with sync pattern:
+;----------------------------------------------------------------------------
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
+;sync up with J to K edge during sync pattern -- use fastest possible loops
+;The first part waits at most 1 bit long since we must be in sync pattern.
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
+;waitForJ, ensure that this prerequisite is met.
+waitForJ:
+ inc YL
+ sbis USBIN, USBMINUS
+ brne waitForJ ; just make sure we have ANY timeout
+waitForK:
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
+ sbis USBIN, USBMINUS ;[-15]
+ rjmp foundK ;[-14]
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+#if USB_COUNT_SOF
+ lds YL, usbSofCount
+ inc YL
+ sts usbSofCount, YL
+#endif /* USB_COUNT_SOF */
+#ifdef USB_SOF_HOOK
+ USB_SOF_HOOK
+#endif
+ rjmp sofError
+foundK: ;[-12]
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling]
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
+;are cycles from center of first sync (double K) bit after the instruction
+ push bitcnt ;[-12]
+; [---] ;[-11]
+ lds YL, usbInputBufOffset;[-10]
+; [---] ;[-9]
+ clr YH ;[-8]
+ subi YL, lo8(-(usbRxBuf));[-7] [rx loop init]
+ sbci YH, hi8(-(usbRxBuf));[-6] [rx loop init]
+ push shift ;[-5]
+; [---] ;[-4]
+ ldi bitcnt, 0x55 ;[-3] [rx loop init]
+ sbis USBIN, USBMINUS ;[-2] we want two bits K (sample 2 cycles too early)
+ rjmp haveTwoBitsK ;[-1]
+ pop shift ;[0] undo the push from before
+ pop bitcnt ;[2] undo the push from before
+ rjmp waitForK ;[4] this was not the end of sync, retry
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
+; bit times (= 21 cycles).
+
+;----------------------------------------------------------------------------
+; push more registers and initialize values while we sample the first bits:
+;----------------------------------------------------------------------------
+haveTwoBitsK:
+ push x1 ;[1]
+ push x2 ;[3]
+ push x3 ;[5]
+ ldi shift, 0 ;[7]
+ ldi x3, 1<<4 ;[8] [rx loop init] first sample is inverse bit, compensate that
+ push x4 ;[9] == leap
+
+ in x1, USBIN ;[11] <-- sample bit 0
+ andi x1, USBMASK ;[12]
+ bst x1, USBMINUS ;[13]
+ bld shift, 7 ;[14]
+ push cnt ;[15]
+ ldi leap, 0 ;[17] [rx loop init]
+ ldi cnt, USB_BUFSIZE;[18] [rx loop init]
+ rjmp rxbit1 ;[19] arrives at [21]
+
+;----------------------------------------------------------------------------
+; Receiver loop (numbers in brackets are cycles within byte after instr)
+;----------------------------------------------------------------------------
+
+; duration of unstuffing code should be 10.66666667 cycles. We adjust "leap"
+; accordingly to approximate this value in the long run.
+
+unstuff6:
+ andi x2, USBMASK ;[03]
+ ori x3, 1<<6 ;[04] will not be shifted any more
+ andi shift, ~0x80;[05]
+ mov x1, x2 ;[06] sampled bit 7 is actually re-sampled bit 6
+ subi leap, -1 ;[07] total duration = 11 bits -> subtract 1/3
+ rjmp didUnstuff6 ;[08]
+
+unstuff7:
+ ori x3, 1<<7 ;[09] will not be shifted any more
+ in x2, USBIN ;[00] [10] re-sample bit 7
+ andi x2, USBMASK ;[01]
+ andi shift, ~0x80;[02]
+ subi leap, 2 ;[03] total duration = 10 bits -> add 1/3
+ rjmp didUnstuff7 ;[04]
+
+unstuffEven:
+ ori x3, 1<<6 ;[09] will be shifted right 6 times for bit 0
+ in x1, USBIN ;[00] [10]
+ andi shift, ~0x80;[01]
+ andi x1, USBMASK ;[02]
+ breq se0 ;[03]
+ subi leap, -1 ;[04] total duration = 11 bits -> subtract 1/3
+ nop2 ;[05]
+ rjmp didUnstuffE ;[06]
+
+unstuffOdd:
+ ori x3, 1<<5 ;[09] will be shifted right 4 times for bit 1
+ in x2, USBIN ;[00] [10]
+ andi shift, ~0x80;[01]
+ andi x2, USBMASK ;[02]
+ breq se0 ;[03]
+ subi leap, -1 ;[04] total duration = 11 bits -> subtract 1/3
+ nop2 ;[05]
+ rjmp didUnstuffO ;[06]
+
+rxByteLoop:
+ andi x1, USBMASK ;[03]
+ eor x2, x1 ;[04]
+ subi leap, 1 ;[05]
+ brpl skipLeap ;[06]
+ subi leap, -3 ;1 one leap cycle every 3rd byte -> 85 + 1/3 cycles per byte
+ nop ;1
+skipLeap:
+ subi x2, 1 ;[08]
+ ror shift ;[09]
+didUnstuff6:
+ cpi shift, 0xfc ;[10]
+ in x2, USBIN ;[00] [11] <-- sample bit 7
+ brcc unstuff6 ;[01]
+ andi x2, USBMASK ;[02]
+ eor x1, x2 ;[03]
+ subi x1, 1 ;[04]
+ ror shift ;[05]
+didUnstuff7:
+ cpi shift, 0xfc ;[06]
+ brcc unstuff7 ;[07]
+ eor x3, shift ;[08] reconstruct: x3 is 1 at bit locations we changed, 0 at others
+ st y+, x3 ;[09] store data
+rxBitLoop:
+ in x1, USBIN ;[00] [11] <-- sample bit 0/2/4
+ andi x1, USBMASK ;[01]
+ eor x2, x1 ;[02]
+ andi x3, 0x3f ;[03] topmost two bits reserved for 6 and 7
+ subi x2, 1 ;[04]
+ ror shift ;[05]
+ cpi shift, 0xfc ;[06]
+ brcc unstuffEven ;[07]
+didUnstuffE:
+ lsr x3 ;[08]
+ lsr x3 ;[09]
+rxbit1:
+ in x2, USBIN ;[00] [10] <-- sample bit 1/3/5
+ andi x2, USBMASK ;[01]
+ breq se0 ;[02]
+ eor x1, x2 ;[03]
+ subi x1, 1 ;[04]
+ ror shift ;[05]
+ cpi shift, 0xfc ;[06]
+ brcc unstuffOdd ;[07]
+didUnstuffO:
+ subi bitcnt, 0xab;[08] == addi 0x55, 0x55 = 0x100/3
+ brcs rxBitLoop ;[09]
+
+ subi cnt, 1 ;[10]
+ in x1, USBIN ;[00] [11] <-- sample bit 6
+ brcc rxByteLoop ;[01]
+ rjmp overflow
+
+macro POP_STANDARD ; 14 cycles
+ pop cnt
+ pop x4
+ pop x3
+ pop x2
+ pop x1
+ pop shift
+ pop bitcnt
+ endm
+macro POP_RETI ; 7 cycles
+ pop YH
+ pop YL
+ out SREG, YL
+ pop YL
+ endm
+
+#include "asmcommon.inc"
+
+; USB spec says:
+; idle = J
+; J = (D+ = 0), (D- = 1)
+; K = (D+ = 1), (D- = 0)
+; Spec allows 7.5 bit times from EOP to SOP for replies
+
+bitstuffN:
+ eor x1, x4 ;[5]
+ ldi x2, 0 ;[6]
+ nop2 ;[7]
+ nop ;[9]
+ out USBOUT, x1 ;[10] <-- out
+ rjmp didStuffN ;[0]
+
+bitstuff6:
+ eor x1, x4 ;[5]
+ ldi x2, 0 ;[6] Carry is zero due to brcc
+ rol shift ;[7] compensate for ror shift at branch destination
+ rjmp didStuff6 ;[8]
+
+bitstuff7:
+ ldi x2, 0 ;[2] Carry is zero due to brcc
+ rjmp didStuff7 ;[3]
+
+
+sendNakAndReti:
+ ldi x3, USBPID_NAK ;[-18]
+ rjmp sendX3AndReti ;[-17]
+sendAckAndReti:
+ ldi cnt, USBPID_ACK ;[-17]
+sendCntAndReti:
+ mov x3, cnt ;[-16]
+sendX3AndReti:
+ ldi YL, 20 ;[-15] x3==r20 address is 20
+ ldi YH, 0 ;[-14]
+ ldi cnt, 2 ;[-13]
+; rjmp usbSendAndReti fallthrough
+
+;usbSend:
+;pointer to data in 'Y'
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
+;uses: x1...x4, btcnt, shift, cnt, Y
+;Numbers in brackets are time since first bit of sync pattern is sent
+;We don't match the transfer rate exactly (don't insert leap cycles every third
+;byte) because the spec demands only 1.5% precision anyway.
+usbSendAndReti: ; 12 cycles until SOP
+ in x2, USBDDR ;[-12]
+ ori x2, USBMASK ;[-11]
+ sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
+ in x1, USBOUT ;[-8] port mirror for tx loop
+ out USBDDR, x2 ;[-7] <- acquire bus
+; need not init x2 (bitstuff history) because sync starts with 0
+ ldi x4, USBMASK ;[-6] exor mask
+ ldi shift, 0x80 ;[-5] sync byte is first byte sent
+txByteLoop:
+ ldi bitcnt, 0x35 ;[-4] [6] binary 0011 0101
+txBitLoop:
+ sbrs shift, 0 ;[-3] [7]
+ eor x1, x4 ;[-2] [8]
+ out USBOUT, x1 ;[-1] [9] <-- out N
+ ror shift ;[0] [10]
+ ror x2 ;[1]
+didStuffN:
+ cpi x2, 0xfc ;[2]
+ brcc bitstuffN ;[3]
+ lsr bitcnt ;[4]
+ brcc txBitLoop ;[5]
+ brne txBitLoop ;[6]
+
+ sbrs shift, 0 ;[7]
+ eor x1, x4 ;[8]
+didStuff6:
+ out USBOUT, x1 ;[-1] [9] <-- out 6
+ ror shift ;[0] [10]
+ ror x2 ;[1]
+ cpi x2, 0xfc ;[2]
+ brcc bitstuff6 ;[3]
+ ror shift ;[4]
+didStuff7:
+ ror x2 ;[5]
+ sbrs x2, 7 ;[6]
+ eor x1, x4 ;[7]
+ nop ;[8]
+ cpi x2, 0xfc ;[9]
+ out USBOUT, x1 ;[-1][10] <-- out 7
+ brcc bitstuff7 ;[0] [11]
+ ld shift, y+ ;[1]
+ dec cnt ;[3]
+ brne txByteLoop ;[4]
+;make SE0:
+ cbr x1, USBMASK ;[5] prepare SE0 [spec says EOP may be 21 to 25 cycles]
+ lds x2, usbNewDeviceAddr;[6]
+ lsl x2 ;[8] we compare with left shifted address
+ subi YL, 20 + 2 ;[9] Only assign address on data packets, not ACK/NAK in x3
+ sbci YH, 0 ;[10]
+ out USBOUT, x1 ;[11] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
+;set address only after data packet was sent, not after handshake
+ breq skipAddrAssign ;[0]
+ sts usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer
+skipAddrAssign:
+;end of usbDeviceAddress transfer
+ ldi x2, 1<<USB_INTR_PENDING_BIT;[2] int0 occurred during TX -- clear pending flag
+ USB_STORE_PENDING(x2) ;[3]
+ ori x1, USBIDLE ;[4]
+ in x2, USBDDR ;[5]
+ cbr x2, USBMASK ;[6] set both pins to input
+ mov x3, x1 ;[7]
+ cbr x3, USBMASK ;[8] configure no pullup on both pins
+ ldi x4, 4 ;[9]
+se0Delay:
+ dec x4 ;[10] [13] [16] [19]
+ brne se0Delay ;[11] [14] [17] [20]
+ out USBOUT, x1 ;[21] <-- out J (idle) -- end of SE0 (EOP signal)
+ out USBDDR, x2 ;[22] <-- release bus now
+ out USBOUT, x3 ;[23] <-- ensure no pull-up resistors are active
+ rjmp doReturn
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm165.inc b/tmk_core/protocol/vusb/usbdrv/usbdrvasm165.inc
new file mode 100644
index 000000000..79b3c61cf
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm165.inc
@@ -0,0 +1,453 @@
+/* Name: usbdrvasm165.inc
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2007-04-22
+ * Tabsize: 4
+ * Copyright: (c) 2007 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * Revision: $Id: usbdrvasm165.inc 740 2009-04-13 18:23:31Z cs $
+ */
+
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
+ * appropriate implementation!
+ */
+
+/*
+General Description:
+This file is the 16.5 MHz version of the USB driver. It is intended for the
+ATTiny45 and similar controllers running on 16.5 MHz internal RC oscillator.
+This version contains a phase locked loop in the receiver routine to cope with
+slight clock rate deviations of up to +/- 1%.
+
+See usbdrv.h for a description of the entire driver.
+
+Since almost all of this code is timing critical, don't change unless you
+really know what you are doing! Many parts require not only a maximum number
+of CPU cycles, but even an exact number of cycles!
+*/
+
+;Software-receiver engine. Strict timing! Don't change unless you can preserve timing!
+;interrupt response time: 4 cycles + insn running = 7 max if interrupts always enabled
+;max allowable interrupt latency: 59 cycles -> max 52 cycles interrupt disable
+;max stack usage: [ret(2), r0, SREG, YL, YH, shift, x1, x2, x3, x4, cnt] = 12 bytes
+;nominal frequency: 16.5 MHz -> 11 cycles per bit
+; 16.3125 MHz < F_CPU < 16.6875 MHz (+/- 1.1%)
+; Numbers in brackets are clocks counted from center of last sync bit
+; when instruction starts
+
+
+USB_INTR_VECTOR:
+;order of registers pushed: YL, SREG [sofError], r0, YH, shift, x1, x2, x3, x4, cnt
+ push YL ;[-23] push only what is necessary to sync with edge ASAP
+ in YL, SREG ;[-21]
+ push YL ;[-20]
+;----------------------------------------------------------------------------
+; Synchronize with sync pattern:
+;----------------------------------------------------------------------------
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
+;sync up with J to K edge during sync pattern -- use fastest possible loops
+;The first part waits at most 1 bit long since we must be in sync pattern.
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
+;waitForJ, ensure that this prerequisite is met.
+waitForJ:
+ inc YL
+ sbis USBIN, USBMINUS
+ brne waitForJ ; just make sure we have ANY timeout
+waitForK:
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
+ sbis USBIN, USBMINUS ;[-15]
+ rjmp foundK ;[-14]
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+#if USB_COUNT_SOF
+ lds YL, usbSofCount
+ inc YL
+ sts usbSofCount, YL
+#endif /* USB_COUNT_SOF */
+#ifdef USB_SOF_HOOK
+ USB_SOF_HOOK
+#endif
+ rjmp sofError
+foundK: ;[-12]
+;{3, 5} after falling D- edge, average delay: 4 cycles [we want 5 for center sampling]
+;we have 1 bit time for setup purposes, then sample again. Numbers in brackets
+;are cycles from center of first sync (double K) bit after the instruction
+ push r0 ;[-12]
+; [---] ;[-11]
+ push YH ;[-10]
+; [---] ;[-9]
+ lds YL, usbInputBufOffset;[-8]
+; [---] ;[-7]
+ clr YH ;[-6]
+ subi YL, lo8(-(usbRxBuf));[-5] [rx loop init]
+ sbci YH, hi8(-(usbRxBuf));[-4] [rx loop init]
+ mov r0, x2 ;[-3] [rx loop init]
+ sbis USBIN, USBMINUS ;[-2] we want two bits K (sample 2 cycles too early)
+ rjmp haveTwoBitsK ;[-1]
+ pop YH ;[0] undo the pushes from before
+ pop r0 ;[2]
+ rjmp waitForK ;[4] this was not the end of sync, retry
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
+; bit times (= 22 cycles).
+
+;----------------------------------------------------------------------------
+; push more registers and initialize values while we sample the first bits:
+;----------------------------------------------------------------------------
+haveTwoBitsK: ;[1]
+ push shift ;[1]
+ push x1 ;[3]
+ push x2 ;[5]
+ push x3 ;[7]
+ ldi shift, 0xff ;[9] [rx loop init]
+ ori x3, 0xff ;[10] [rx loop init] == ser x3, clear zero flag
+
+ in x1, USBIN ;[11] <-- sample bit 0
+ bst x1, USBMINUS ;[12]
+ bld shift, 0 ;[13]
+ push x4 ;[14] == phase
+; [---] ;[15]
+ push cnt ;[16]
+; [---] ;[17]
+ ldi phase, 0 ;[18] [rx loop init]
+ ldi cnt, USB_BUFSIZE;[19] [rx loop init]
+ rjmp rxbit1 ;[20]
+; [---] ;[21]
+
+;----------------------------------------------------------------------------
+; Receiver loop (numbers in brackets are cycles within byte after instr)
+;----------------------------------------------------------------------------
+/*
+byte oriented operations done during loop:
+bit 0: store data
+bit 1: SE0 check
+bit 2: overflow check
+bit 3: catch up
+bit 4: rjmp to achieve conditional jump range
+bit 5: PLL
+bit 6: catch up
+bit 7: jump, fixup bitstuff
+; 87 [+ 2] cycles
+------------------------------------------------------------------
+*/
+continueWithBit5:
+ in x2, USBIN ;[055] <-- bit 5
+ eor r0, x2 ;[056]
+ or phase, r0 ;[057]
+ sbrc phase, USBMINUS ;[058]
+ lpm ;[059] optional nop3; modifies r0
+ in phase, USBIN ;[060] <-- phase
+ eor x1, x2 ;[061]
+ bst x1, USBMINUS ;[062]
+ bld shift, 5 ;[063]
+ andi shift, 0x3f ;[064]
+ in x1, USBIN ;[065] <-- bit 6
+ breq unstuff5 ;[066] *** unstuff escape
+ eor phase, x1 ;[067]
+ eor x2, x1 ;[068]
+ bst x2, USBMINUS ;[069]
+ bld shift, 6 ;[070]
+didUnstuff6: ;[ ]
+ in r0, USBIN ;[071] <-- phase
+ cpi shift, 0x02 ;[072]
+ brlo unstuff6 ;[073] *** unstuff escape
+didUnstuff5: ;[ ]
+ nop2 ;[074]
+; [---] ;[075]
+ in x2, USBIN ;[076] <-- bit 7
+ eor x1, x2 ;[077]
+ bst x1, USBMINUS ;[078]
+ bld shift, 7 ;[079]
+didUnstuff7: ;[ ]
+ eor r0, x2 ;[080]
+ or phase, r0 ;[081]
+ in r0, USBIN ;[082] <-- phase
+ cpi shift, 0x04 ;[083]
+ brsh rxLoop ;[084]
+; [---] ;[085]
+unstuff7: ;[ ]
+ andi x3, ~0x80 ;[085]
+ ori shift, 0x80 ;[086]
+ in x2, USBIN ;[087] <-- sample stuffed bit 7
+ nop ;[088]
+ rjmp didUnstuff7 ;[089]
+; [---] ;[090]
+ ;[080]
+
+unstuff5: ;[067]
+ eor phase, x1 ;[068]
+ andi x3, ~0x20 ;[069]
+ ori shift, 0x20 ;[070]
+ in r0, USBIN ;[071] <-- phase
+ mov x2, x1 ;[072]
+ nop ;[073]
+ nop2 ;[074]
+; [---] ;[075]
+ in x1, USBIN ;[076] <-- bit 6
+ eor r0, x1 ;[077]
+ or phase, r0 ;[078]
+ eor x2, x1 ;[079]
+ bst x2, USBMINUS ;[080]
+ bld shift, 6 ;[081] no need to check bitstuffing, we just had one
+ in r0, USBIN ;[082] <-- phase
+ rjmp didUnstuff5 ;[083]
+; [---] ;[084]
+ ;[074]
+
+unstuff6: ;[074]
+ andi x3, ~0x40 ;[075]
+ in x1, USBIN ;[076] <-- bit 6 again
+ ori shift, 0x40 ;[077]
+ nop2 ;[078]
+; [---] ;[079]
+ rjmp didUnstuff6 ;[080]
+; [---] ;[081]
+ ;[071]
+
+unstuff0: ;[013]
+ eor r0, x2 ;[014]
+ or phase, r0 ;[015]
+ andi x2, USBMASK ;[016] check for SE0
+ in r0, USBIN ;[017] <-- phase
+ breq didUnstuff0 ;[018] direct jump to se0 would be too long
+ andi x3, ~0x01 ;[019]
+ ori shift, 0x01 ;[020]
+ mov x1, x2 ;[021] mov existing sample
+ in x2, USBIN ;[022] <-- bit 1 again
+ rjmp didUnstuff0 ;[023]
+; [---] ;[024]
+ ;[014]
+
+unstuff1: ;[024]
+ eor r0, x1 ;[025]
+ or phase, r0 ;[026]
+ andi x3, ~0x02 ;[027]
+ in r0, USBIN ;[028] <-- phase
+ ori shift, 0x02 ;[029]
+ mov x2, x1 ;[030]
+ rjmp didUnstuff1 ;[031]
+; [---] ;[032]
+ ;[022]
+
+unstuff2: ;[035]
+ eor r0, x2 ;[036]
+ or phase, r0 ;[037]
+ andi x3, ~0x04 ;[038]
+ in r0, USBIN ;[039] <-- phase
+ ori shift, 0x04 ;[040]
+ mov x1, x2 ;[041]
+ rjmp didUnstuff2 ;[042]
+; [---] ;[043]
+ ;[033]
+
+unstuff3: ;[043]
+ in x2, USBIN ;[044] <-- bit 3 again
+ eor r0, x2 ;[045]
+ or phase, r0 ;[046]
+ andi x3, ~0x08 ;[047]
+ ori shift, 0x08 ;[048]
+ nop ;[049]
+ in r0, USBIN ;[050] <-- phase
+ rjmp didUnstuff3 ;[051]
+; [---] ;[052]
+ ;[042]
+
+unstuff4: ;[053]
+ andi x3, ~0x10 ;[054]
+ in x1, USBIN ;[055] <-- bit 4 again
+ ori shift, 0x10 ;[056]
+ rjmp didUnstuff4 ;[057]
+; [---] ;[058]
+ ;[048]
+
+rxLoop: ;[085]
+ eor x3, shift ;[086] reconstruct: x3 is 0 at bit locations we changed, 1 at others
+ in x1, USBIN ;[000] <-- bit 0
+ st y+, x3 ;[001]
+; [---] ;[002]
+ eor r0, x1 ;[003]
+ or phase, r0 ;[004]
+ eor x2, x1 ;[005]
+ in r0, USBIN ;[006] <-- phase
+ ser x3 ;[007]
+ bst x2, USBMINUS ;[008]
+ bld shift, 0 ;[009]
+ andi shift, 0xf9 ;[010]
+rxbit1: ;[ ]
+ in x2, USBIN ;[011] <-- bit 1
+ breq unstuff0 ;[012] *** unstuff escape
+ andi x2, USBMASK ;[013] SE0 check for bit 1
+didUnstuff0: ;[ ] Z only set if we detected SE0 in bitstuff
+ breq se0 ;[014]
+ eor r0, x2 ;[015]
+ or phase, r0 ;[016]
+ in r0, USBIN ;[017] <-- phase
+ eor x1, x2 ;[018]
+ bst x1, USBMINUS ;[019]
+ bld shift, 1 ;[020]
+ andi shift, 0xf3 ;[021]
+didUnstuff1: ;[ ]
+ in x1, USBIN ;[022] <-- bit 2
+ breq unstuff1 ;[023] *** unstuff escape
+ eor r0, x1 ;[024]
+ or phase, r0 ;[025]
+ subi cnt, 1 ;[026] overflow check
+ brcs overflow ;[027]
+ in r0, USBIN ;[028] <-- phase
+ eor x2, x1 ;[029]
+ bst x2, USBMINUS ;[030]
+ bld shift, 2 ;[031]
+ andi shift, 0xe7 ;[032]
+didUnstuff2: ;[ ]
+ in x2, USBIN ;[033] <-- bit 3
+ breq unstuff2 ;[034] *** unstuff escape
+ eor r0, x2 ;[035]
+ or phase, r0 ;[036]
+ eor x1, x2 ;[037]
+ bst x1, USBMINUS ;[038]
+ in r0, USBIN ;[039] <-- phase
+ bld shift, 3 ;[040]
+ andi shift, 0xcf ;[041]
+didUnstuff3: ;[ ]
+ breq unstuff3 ;[042] *** unstuff escape
+ nop ;[043]
+ in x1, USBIN ;[044] <-- bit 4
+ eor x2, x1 ;[045]
+ bst x2, USBMINUS ;[046]
+ bld shift, 4 ;[047]
+didUnstuff4: ;[ ]
+ eor r0, x1 ;[048]
+ or phase, r0 ;[049]
+ in r0, USBIN ;[050] <-- phase
+ andi shift, 0x9f ;[051]
+ breq unstuff4 ;[052] *** unstuff escape
+ rjmp continueWithBit5;[053]
+; [---] ;[054]
+
+macro POP_STANDARD ; 16 cycles
+ pop cnt
+ pop x4
+ pop x3
+ pop x2
+ pop x1
+ pop shift
+ pop YH
+ pop r0
+ endm
+macro POP_RETI ; 5 cycles
+ pop YL
+ out SREG, YL
+ pop YL
+ endm
+
+#include "asmcommon.inc"
+
+
+; USB spec says:
+; idle = J
+; J = (D+ = 0), (D- = 1)
+; K = (D+ = 1), (D- = 0)
+; Spec allows 7.5 bit times from EOP to SOP for replies
+
+bitstuff7:
+ eor x1, x4 ;[4]
+ ldi x2, 0 ;[5]
+ nop2 ;[6] C is zero (brcc)
+ rjmp didStuff7 ;[8]
+
+bitstuffN:
+ eor x1, x4 ;[5]
+ ldi x2, 0 ;[6]
+ lpm ;[7] 3 cycle NOP, modifies r0
+ out USBOUT, x1 ;[10] <-- out
+ rjmp didStuffN ;[0]
+
+#define bitStatus x3
+
+sendNakAndReti:
+ ldi cnt, USBPID_NAK ;[-19]
+ rjmp sendCntAndReti ;[-18]
+sendAckAndReti:
+ ldi cnt, USBPID_ACK ;[-17]
+sendCntAndReti:
+ mov r0, cnt ;[-16]
+ ldi YL, 0 ;[-15] R0 address is 0
+ ldi YH, 0 ;[-14]
+ ldi cnt, 2 ;[-13]
+; rjmp usbSendAndReti fallthrough
+
+;usbSend:
+;pointer to data in 'Y'
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
+;uses: x1...x4, shift, cnt, Y
+;Numbers in brackets are time since first bit of sync pattern is sent
+usbSendAndReti: ; 12 cycles until SOP
+ in x2, USBDDR ;[-12]
+ ori x2, USBMASK ;[-11]
+ sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
+ in x1, USBOUT ;[-8] port mirror for tx loop
+ out USBDDR, x2 ;[-7] <- acquire bus
+; need not init x2 (bitstuff history) because sync starts with 0
+ ldi x4, USBMASK ;[-6] exor mask
+ ldi shift, 0x80 ;[-5] sync byte is first byte sent
+ ldi bitStatus, 0xff ;[-4] init bit loop counter, works for up to 12 bytes
+byteloop:
+bitloop:
+ sbrs shift, 0 ;[8] [-3]
+ eor x1, x4 ;[9] [-2]
+ out USBOUT, x1 ;[10] [-1] <-- out
+ ror shift ;[0]
+ ror x2 ;[1]
+didStuffN:
+ cpi x2, 0xfc ;[2]
+ brcc bitstuffN ;[3]
+ nop ;[4]
+ subi bitStatus, 37 ;[5] 256 / 7 ~=~ 37
+ brcc bitloop ;[6] when we leave the loop, bitStatus has almost the initial value
+ sbrs shift, 0 ;[7]
+ eor x1, x4 ;[8]
+ ror shift ;[9]
+didStuff7:
+ out USBOUT, x1 ;[10] <-- out
+ ror x2 ;[0]
+ cpi x2, 0xfc ;[1]
+ brcc bitstuff7 ;[2]
+ ld shift, y+ ;[3]
+ dec cnt ;[5]
+ brne byteloop ;[6]
+;make SE0:
+ cbr x1, USBMASK ;[7] prepare SE0 [spec says EOP may be 21 to 25 cycles]
+ lds x2, usbNewDeviceAddr;[8]
+ lsl x2 ;[10] we compare with left shifted address
+ out USBOUT, x1 ;[11] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
+;set address only after data packet was sent, not after handshake
+ subi YL, 2 ;[0] Only assign address on data packets, not ACK/NAK in r0
+ sbci YH, 0 ;[1]
+ breq skipAddrAssign ;[2]
+ sts usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer
+skipAddrAssign:
+;end of usbDeviceAddress transfer
+ ldi x2, 1<<USB_INTR_PENDING_BIT;[4] int0 occurred during TX -- clear pending flag
+ USB_STORE_PENDING(x2) ;[5]
+ ori x1, USBIDLE ;[6]
+ in x2, USBDDR ;[7]
+ cbr x2, USBMASK ;[8] set both pins to input
+ mov x3, x1 ;[9]
+ cbr x3, USBMASK ;[10] configure no pullup on both pins
+ ldi x4, 4 ;[11]
+se0Delay:
+ dec x4 ;[12] [15] [18] [21]
+ brne se0Delay ;[13] [16] [19] [22]
+ out USBOUT, x1 ;[23] <-- out J (idle) -- end of SE0 (EOP signal)
+ out USBDDR, x2 ;[24] <-- release bus now
+ out USBOUT, x3 ;[25] <-- ensure no pull-up resistors are active
+ rjmp doReturn
+
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm18-crc.inc b/tmk_core/protocol/vusb/usbdrv/usbdrvasm18-crc.inc
new file mode 100644
index 000000000..f83347df7
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm18-crc.inc
@@ -0,0 +1,707 @@
+/* Name: usbdrvasm18.inc
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Lukas Schrittwieser (based on 20 MHz usbdrvasm20.inc by Jeroen Benschop)
+ * Creation Date: 2009-01-20
+ * Tabsize: 4
+ * Copyright: (c) 2008 by Lukas Schrittwieser and OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * Revision: $Id: usbdrvasm18-crc.inc 740 2009-04-13 18:23:31Z cs $
+ */
+
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
+ * appropriate implementation!
+ */
+
+/*
+General Description:
+This file is the 18 MHz version of the asssembler part of the USB driver. It
+requires a 18 MHz crystal (not a ceramic resonator and not a calibrated RC
+oscillator).
+
+See usbdrv.h for a description of the entire driver.
+
+Since almost all of this code is timing critical, don't change unless you
+really know what you are doing! Many parts require not only a maximum number
+of CPU cycles, but even an exact number of cycles!
+*/
+
+
+;max stack usage: [ret(2), YL, SREG, YH, [sofError], bitcnt(x5), shift, x1, x2, x3, x4, cnt, ZL, ZH] = 14 bytes
+;nominal frequency: 18 MHz -> 12 cycles per bit
+; Numbers in brackets are clocks counted from center of last sync bit
+; when instruction starts
+;register use in receive loop to receive the data bytes:
+; shift assembles the byte currently being received
+; x1 holds the D+ and D- line state
+; x2 holds the previous line state
+; cnt holds the number of bytes left in the receive buffer
+; x3 holds the higher crc byte (see algorithm below)
+; x4 is used as temporary register for the crc algorithm
+; x5 is used for unstuffing: when unstuffing the last received bit is inverted in shift (to prevent further
+; unstuffing calls. In the same time the corresponding bit in x5 is cleared to mark the bit as beening iverted
+; zl lower crc value and crc table index
+; zh used for crc table accesses
+
+;--------------------------------------------------------------------------------------------------------------
+; CRC mods:
+; table driven crc checker, Z points to table in prog space
+; ZL is the lower crc byte, x3 is the higher crc byte
+; x4 is used as temp register to store different results
+; the initialization of the crc register is not 0xFFFF but 0xFE54. This is because during the receipt of the
+; first data byte an virtual zero data byte is added to the crc register, this results in the correct initial
+; value of 0xFFFF at beginning of the second data byte before the first data byte is added to the crc.
+; The magic number 0xFE54 results form the crc table: At tabH[0x54] = 0xFF = crcH (required) and
+; tabL[0x54] = 0x01 -> crcL = 0x01 xor 0xFE = 0xFF
+; bitcnt is renamed to x5 and is used for unstuffing purposes, the unstuffing works like in the 12MHz version
+;--------------------------------------------------------------------------------------------------------------
+; CRC algorithm:
+; The crc register is formed by x3 (higher byte) and ZL (lower byte). The algorithm uses a 'reversed' form
+; i.e. that it takes the least significant bit first and shifts to the right. So in fact the highest order
+; bit seen from the polynomial devision point of view is the lsb of ZL. (If this sounds strange to you i
+; propose a research on CRC :-) )
+; Each data byte received is xored to ZL, the lower crc byte. This byte now builds the crc
+; table index. Next the new high byte is loaded from the table and stored in x4 until we have space in x3
+; (its destination).
+; Afterwards the lower table is loaded from the table and stored in ZL (the old index is overwritten as
+; we don't need it anymore. In fact this is a right shift by 8 bits.) Now the old crc high value is xored
+; to ZL, this is the second shift of the old crc value. Now x4 (the temp reg) is moved to x3 and the crc
+; calculation is done.
+; Prior to the first byte the two CRC register have to be initialized to 0xFFFF (as defined in usb spec)
+; however the crc engine also runs during the receipt of the first byte, therefore x3 and zl are initialized
+; to a magic number which results in a crc value of 0xFFFF after the first complete byte.
+;
+; This algorithm is split into the extra cycles of the different bits:
+; bit7: XOR the received byte to ZL
+; bit5: load the new high byte to x4
+; bit6: load the lower xor byte from the table, xor zl and x3, store result in zl (=the new crc low value)
+; move x4 (the new high byte) to x3, the crc value is ready
+;
+
+
+macro POP_STANDARD ; 18 cycles
+ pop ZH
+ pop ZL
+ pop cnt
+ pop x5
+ pop x3
+ pop x2
+ pop x1
+ pop shift
+ pop x4
+ endm
+macro POP_RETI ; 7 cycles
+ pop YH
+ pop YL
+ out SREG, YL
+ pop YL
+ endm
+
+macro CRC_CLEANUP_AND_CHECK
+ ; the last byte has already been xored with the lower crc byte, we have to do the table lookup and xor
+ ; x3 is the higher crc byte, zl the lower one
+ ldi ZH, hi8(usbCrcTableHigh);[+1] get the new high byte from the table
+ lpm x2, Z ;[+2][+3][+4]
+ ldi ZH, hi8(usbCrcTableLow);[+5] get the new low xor byte from the table
+ lpm ZL, Z ;[+6][+7][+8]
+ eor ZL, x3 ;[+7] xor the old high byte with the value from the table, x2:ZL now holds the crc value
+ cpi ZL, 0x01 ;[+8] if the crc is ok we have a fixed remainder value of 0xb001 in x2:ZL (see usb spec)
+ brne ignorePacket ;[+9] detected a crc fault -> paket is ignored and retransmitted by the host
+ cpi x2, 0xb0 ;[+10]
+ brne ignorePacket ;[+11] detected a crc fault -> paket is ignored and retransmitted by the host
+ endm
+
+
+USB_INTR_VECTOR:
+;order of registers pushed: YL, SREG, YH, [sofError], x4, shift, x1, x2, x3, x5, cnt, ZL, ZH
+ push YL ;[-28] push only what is necessary to sync with edge ASAP
+ in YL, SREG ;[-26]
+ push YL ;[-25]
+ push YH ;[-23]
+;----------------------------------------------------------------------------
+; Synchronize with sync pattern:
+;----------------------------------------------------------------------------
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
+;sync up with J to K edge during sync pattern -- use fastest possible loops
+;The first part waits at most 1 bit long since we must be in sync pattern.
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
+;waitForJ, ensure that this prerequisite is met.
+waitForJ:
+ inc YL
+ sbis USBIN, USBMINUS
+ brne waitForJ ; just make sure we have ANY timeout
+waitForK:
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
+ sbis USBIN, USBMINUS ;[-17]
+ rjmp foundK ;[-16]
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+#if USB_COUNT_SOF
+ lds YL, usbSofCount
+ inc YL
+ sts usbSofCount, YL
+#endif /* USB_COUNT_SOF */
+#ifdef USB_SOF_HOOK
+ USB_SOF_HOOK
+#endif
+ rjmp sofError
+foundK: ;[-15]
+;{3, 5} after falling D- edge, average delay: 4 cycles
+;bit0 should be at 30 (2.5 bits) for center sampling. Currently at 4 so 26 cylces till bit 0 sample
+;use 1 bit time for setup purposes, then sample again. Numbers in brackets
+;are cycles from center of first sync (double K) bit after the instruction
+ push x4 ;[-14]
+; [---] ;[-13]
+ lds YL, usbInputBufOffset;[-12] used to toggle the two usb receive buffers
+; [---] ;[-11]
+ clr YH ;[-10]
+ subi YL, lo8(-(usbRxBuf));[-9] [rx loop init]
+ sbci YH, hi8(-(usbRxBuf));[-8] [rx loop init]
+ push shift ;[-7]
+; [---] ;[-6]
+ ldi shift, 0x80 ;[-5] the last bit is the end of byte marker for the pid receiver loop
+ clc ;[-4] the carry has to be clear for receipt of pid bit 0
+ sbis USBIN, USBMINUS ;[-3] we want two bits K (sample 3 cycles too early)
+ rjmp haveTwoBitsK ;[-2]
+ pop shift ;[-1] undo the push from before
+ pop x4 ;[1]
+ rjmp waitForK ;[3] this was not the end of sync, retry
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
+; bit times (= 24 cycles).
+
+;----------------------------------------------------------------------------
+; push more registers and initialize values while we sample the first bits:
+;----------------------------------------------------------------------------
+haveTwoBitsK:
+ push x1 ;[0]
+ push x2 ;[2]
+ push x3 ;[4] crc high byte
+ ldi x2, 1<<USBPLUS ;[6] [rx loop init] current line state is K state. D+=="1", D-=="0"
+ push x5 ;[7]
+ push cnt ;[9]
+ ldi cnt, USB_BUFSIZE ;[11]
+
+
+;--------------------------------------------------------------------------------------------------------------
+; receives the pid byte
+; there is no real unstuffing algorithm implemented here as a stuffing bit is impossible in the pid byte.
+; That's because the last four bits of the byte are the inverted of the first four bits. If we detect a
+; unstuffing condition something went wrong and abort
+; shift has to be initialized to 0x80
+;--------------------------------------------------------------------------------------------------------------
+
+; pid bit 0 - used for even more register saving (we need the z pointer)
+ in x1, USBIN ;[0] sample line state
+ andi x1, USBMASK ;[1] filter only D+ and D- bits
+ eor x2, x1 ;[2] generate inverted of actual bit
+ sbrc x2, USBMINUS ;[3] if the bit is set we received a zero
+ sec ;[4]
+ ror shift ;[5] we perform no unstuffing check here as this is the first bit
+ mov x2, x1 ;[6]
+ push ZL ;[7]
+ ;[8]
+ push ZH ;[9]
+ ;[10]
+ ldi x3, 0xFE ;[11] x3 is the high order crc value
+
+
+bitloopPid:
+ in x1, USBIN ;[0] sample line state
+ andi x1, USBMASK ;[1] filter only D+ and D- bits
+ breq nse0 ;[2] both lines are low so handle se0
+ eor x2, x1 ;[3] generate inverted of actual bit
+ sbrc x2, USBMINUS ;[4] set the carry if we received a zero
+ sec ;[5]
+ ror shift ;[6]
+ ldi ZL, 0x54 ;[7] ZL is the low order crc value
+ ser x4 ;[8] the is no bit stuffing check here as the pid bit can't be stuffed. if so
+ ; some error occured. In this case the paket is discarded later on anyway.
+ mov x2, x1 ;[9] prepare for the next cycle
+ brcc bitloopPid ;[10] while 0s drop out of shift we get the next bit
+ eor x4, shift ;[11] invert all bits in shift and store result in x4
+
+;--------------------------------------------------------------------------------------------------------------
+; receives data bytes and calculates the crc
+; the last USBIN state has to be in x2
+; this is only the first half, due to branch distanc limitations the second half of the loop is near the end
+; of this asm file
+;--------------------------------------------------------------------------------------------------------------
+
+rxDataStart:
+ in x1, USBIN ;[0] sample line state (note: a se0 check is not useful due to bit dribbling)
+ ser x5 ;[1] prepare the unstuff marker register
+ eor x2, x1 ;[2] generates the inverted of the actual bit
+ bst x2, USBMINUS ;[3] copy the bit from x2
+ bld shift, 0 ;[4] and store it in shift
+ mov x2, shift ;[5] make a copy of shift for unstuffing check
+ andi x2, 0xF9 ;[6] mask the last six bits, if we got six zeros (which are six ones in fact)
+ breq unstuff0 ;[7] then Z is set now and we branch to the unstuffing handler
+didunstuff0:
+ subi cnt, 1 ;[8] cannot use dec because it doesn't affect the carry flag
+ brcs nOverflow ;[9] Too many bytes received. Ignore packet
+ st Y+, x4 ;[10] store the last received byte
+ ;[11] st needs two cycles
+
+; bit1
+ in x2, USBIN ;[0] sample line state
+ andi x1, USBMASK ;[1] check for se0 during bit 0
+ breq nse0 ;[2]
+ andi x2, USBMASK ;[3] check se0 during bit 1
+ breq nse0 ;[4]
+ eor x1, x2 ;[5]
+ bst x1, USBMINUS ;[6]
+ bld shift, 1 ;[7]
+ mov x1, shift ;[8]
+ andi x1, 0xF3 ;[9]
+ breq unstuff1 ;[10]
+didunstuff1:
+ nop ;[11]
+
+; bit2
+ in x1, USBIN ;[0] sample line state
+ andi x1, USBMASK ;[1] check for se0 (as there is nothing else to do here
+ breq nOverflow ;[2]
+ eor x2, x1 ;[3] generates the inverted of the actual bit
+ bst x2, USBMINUS ;[4]
+ bld shift, 2 ;[5] store the bit
+ mov x2, shift ;[6]
+ andi x2, 0xE7 ;[7] if we have six zeros here (which means six 1 in the stream)
+ breq unstuff2 ;[8] the next bit is a stuffing bit
+didunstuff2:
+ nop2 ;[9]
+ ;[10]
+ nop ;[11]
+
+; bit3
+ in x2, USBIN ;[0] sample line state
+ andi x2, USBMASK ;[1] check for se0
+ breq nOverflow ;[2]
+ eor x1, x2 ;[3]
+ bst x1, USBMINUS ;[4]
+ bld shift, 3 ;[5]
+ mov x1, shift ;[6]
+ andi x1, 0xCF ;[7]
+ breq unstuff3 ;[8]
+didunstuff3:
+ nop ;[9]
+ rjmp rxDataBit4 ;[10]
+ ;[11]
+
+; the avr branch instructions allow an offset of +63 insturction only, so we need this
+; 'local copy' of se0
+nse0:
+ rjmp se0 ;[4]
+ ;[5]
+; the same same as for se0 is needed for overflow and StuffErr
+nOverflow:
+stuffErr:
+ rjmp overflow
+
+
+unstuff0: ;[8] this is the branch delay of breq unstuffX
+ andi x1, USBMASK ;[9] do an se0 check here (if the last crc byte ends with 5 one's we might end up here
+ breq didunstuff0 ;[10] event tough the message is complete -> jump back and store the byte
+ ori shift, 0x01 ;[11] invert the last received bit to prevent furhter unstuffing
+ in x2, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors
+ andi x5, 0xFE ;[1] mark this bit as inverted (will be corrected before storing shift)
+ eor x1, x2 ;[2] x1 and x2 have to be different because the stuff bit is always a zero
+ andi x1, USBMASK ;[3] mask the interesting bits
+ breq stuffErr ;[4] if the stuff bit is a 1-bit something went wrong
+ mov x1, x2 ;[5] the next bit expects the last state to be in x1
+ rjmp didunstuff0 ;[6]
+ ;[7] jump delay of rjmp didunstuffX
+
+unstuff1: ;[11] this is the jump delay of breq unstuffX
+ in x1, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors
+ ori shift, 0x02 ;[1] invert the last received bit to prevent furhter unstuffing
+ andi x5, 0xFD ;[2] mark this bit as inverted (will be corrected before storing shift)
+ eor x2, x1 ;[3] x1 and x2 have to be different because the stuff bit is always a zero
+ andi x2, USBMASK ;[4] mask the interesting bits
+ breq stuffErr ;[5] if the stuff bit is a 1-bit something went wrong
+ mov x2, x1 ;[6] the next bit expects the last state to be in x2
+ nop2 ;[7]
+ ;[8]
+ rjmp didunstuff1 ;[9]
+ ;[10] jump delay of rjmp didunstuffX
+
+unstuff2: ;[9] this is the jump delay of breq unstuffX
+ ori shift, 0x04 ;[10] invert the last received bit to prevent furhter unstuffing
+ andi x5, 0xFB ;[11] mark this bit as inverted (will be corrected before storing shift)
+ in x2, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors
+ eor x1, x2 ;[1] x1 and x2 have to be different because the stuff bit is always a zero
+ andi x1, USBMASK ;[2] mask the interesting bits
+ breq stuffErr ;[3] if the stuff bit is a 1-bit something went wrong
+ mov x1, x2 ;[4] the next bit expects the last state to be in x1
+ nop2 ;[5]
+ ;[6]
+ rjmp didunstuff2 ;[7]
+ ;[8] jump delay of rjmp didunstuffX
+
+unstuff3: ;[9] this is the jump delay of breq unstuffX
+ ori shift, 0x08 ;[10] invert the last received bit to prevent furhter unstuffing
+ andi x5, 0xF7 ;[11] mark this bit as inverted (will be corrected before storing shift)
+ in x1, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors
+ eor x2, x1 ;[1] x1 and x2 have to be different because the stuff bit is always a zero
+ andi x2, USBMASK ;[2] mask the interesting bits
+ breq stuffErr ;[3] if the stuff bit is a 1-bit something went wrong
+ mov x2, x1 ;[4] the next bit expects the last state to be in x2
+ nop2 ;[5]
+ ;[6]
+ rjmp didunstuff3 ;[7]
+ ;[8] jump delay of rjmp didunstuffX
+
+
+
+; the include has to be here due to branch distance restirctions
+#define __USE_CRC__
+#include "asmcommon.inc"
+
+
+
+; USB spec says:
+; idle = J
+; J = (D+ = 0), (D- = 1)
+; K = (D+ = 1), (D- = 0)
+; Spec allows 7.5 bit times from EOP to SOP for replies
+; 7.5 bit times is 90 cycles. ...there is plenty of time
+
+
+sendNakAndReti:
+ ldi x3, USBPID_NAK ;[-18]
+ rjmp sendX3AndReti ;[-17]
+sendAckAndReti:
+ ldi cnt, USBPID_ACK ;[-17]
+sendCntAndReti:
+ mov x3, cnt ;[-16]
+sendX3AndReti:
+ ldi YL, 20 ;[-15] x3==r20 address is 20
+ ldi YH, 0 ;[-14]
+ ldi cnt, 2 ;[-13]
+; rjmp usbSendAndReti fallthrough
+
+;usbSend:
+;pointer to data in 'Y'
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
+;uses: x1...x4, btcnt, shift, cnt, Y
+;Numbers in brackets are time since first bit of sync pattern is sent
+
+usbSendAndReti: ; 12 cycles until SOP
+ in x2, USBDDR ;[-12]
+ ori x2, USBMASK ;[-11]
+ sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
+ in x1, USBOUT ;[-8] port mirror for tx loop
+ out USBDDR, x2 ;[-6] <- acquire bus
+ ldi x2, 0 ;[-6] init x2 (bitstuff history) because sync starts with 0
+ ldi x4, USBMASK ;[-5] exor mask
+ ldi shift, 0x80 ;[-4] sync byte is first byte sent
+txByteLoop:
+ ldi bitcnt, 0x40 ;[-3]=[9] binary 01000000
+txBitLoop: ; the loop sends the first 7 bits of the byte
+ sbrs shift, 0 ;[-2]=[10] if we have to send a 1 don't change the line state
+ eor x1, x4 ;[-1]=[11]
+ out USBOUT, x1 ;[0]
+ ror shift ;[1]
+ ror x2 ;[2] transfers the last sent bit to the stuffing history
+didStuffN:
+ nop ;[3]
+ nop ;[4]
+ cpi x2, 0xfc ;[5] if we sent six consecutive ones
+ brcc bitstuffN ;[6]
+ lsr bitcnt ;[7]
+ brne txBitLoop ;[8] restart the loop while the 1 is still in the bitcount
+
+; transmit bit 7
+ sbrs shift, 0 ;[9]
+ eor x1, x4 ;[10]
+didStuff7:
+ ror shift ;[11]
+ out USBOUT, x1 ;[0] transfer bit 7 to the pins
+ ror x2 ;[1] move the bit into the stuffing history
+ cpi x2, 0xfc ;[2]
+ brcc bitstuff7 ;[3]
+ ld shift, y+ ;[4] get next byte to transmit
+ dec cnt ;[5] decrement byte counter
+ brne txByteLoop ;[7] if we have more bytes start next one
+ ;[8] branch delay
+
+;make SE0:
+ cbr x1, USBMASK ;[8] prepare SE0 [spec says EOP may be 25 to 30 cycles]
+ lds x2, usbNewDeviceAddr;[9]
+ lsl x2 ;[11] we compare with left shifted address
+ out USBOUT, x1 ;[0] <-- out SE0 -- from now 2 bits = 24 cycles until bus idle
+ subi YL, 20 + 2 ;[1] Only assign address on data packets, not ACK/NAK in x3
+ sbci YH, 0 ;[2]
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
+;set address only after data packet was sent, not after handshake
+ breq skipAddrAssign ;[3]
+ sts usbDeviceAddr, x2 ; if not skipped: SE0 is one cycle longer
+skipAddrAssign:
+;end of usbDeviceAddress transfer
+ ldi x2, 1<<USB_INTR_PENDING_BIT;[5] int0 occurred during TX -- clear pending flag
+ USB_STORE_PENDING(x2) ;[6]
+ ori x1, USBIDLE ;[7]
+ in x2, USBDDR ;[8]
+ cbr x2, USBMASK ;[9] set both pins to input
+ mov x3, x1 ;[10]
+ cbr x3, USBMASK ;[11] configure no pullup on both pins
+ ldi x4, 4 ;[12]
+se0Delay:
+ dec x4 ;[13] [16] [19] [22]
+ brne se0Delay ;[14] [17] [20] [23]
+ out USBOUT, x1 ;[24] <-- out J (idle) -- end of SE0 (EOP signal)
+ out USBDDR, x2 ;[25] <-- release bus now
+ out USBOUT, x3 ;[26] <-- ensure no pull-up resistors are active
+ rjmp doReturn
+
+bitstuffN:
+ eor x1, x4 ;[8] generate a zero
+ ldi x2, 0 ;[9] reset the bit stuffing history
+ nop2 ;[10]
+ out USBOUT, x1 ;[0] <-- send the stuffing bit
+ rjmp didStuffN ;[1]
+
+bitstuff7:
+ eor x1, x4 ;[5]
+ ldi x2, 0 ;[6] reset bit stuffing history
+ clc ;[7] fill a zero into the shift register
+ rol shift ;[8] compensate for ror shift at branch destination
+ rjmp didStuff7 ;[9]
+ ;[10] jump delay
+
+;--------------------------------------------------------------------------------------------------------------
+; receives data bytes and calculates the crc
+; second half of the data byte receiver loop
+; most parts of the crc algorithm are here
+;--------------------------------------------------------------------------------------------------------------
+
+nOverflow2:
+ rjmp overflow
+
+rxDataBit4:
+ in x1, USBIN ;[0] sample line state
+ andi x1, USBMASK ;[1] check for se0
+ breq nOverflow2 ;[2]
+ eor x2, x1 ;[3]
+ bst x2, USBMINUS ;[4]
+ bld shift, 4 ;[5]
+ mov x2, shift ;[6]
+ andi x2, 0x9F ;[7]
+ breq unstuff4 ;[8]
+didunstuff4:
+ nop2 ;[9][10]
+ nop ;[11]
+
+; bit5
+ in x2, USBIN ;[0] sample line state
+ ldi ZH, hi8(usbCrcTableHigh);[1] use the table for the higher byte
+ eor x1, x2 ;[2]
+ bst x1, USBMINUS ;[3]
+ bld shift, 5 ;[4]
+ mov x1, shift ;[5]
+ andi x1, 0x3F ;[6]
+ breq unstuff5 ;[7]
+didunstuff5:
+ lpm x4, Z ;[8] load the higher crc xor-byte and store it for later use
+ ;[9] lpm needs 3 cycles
+ ;[10]
+ ldi ZH, hi8(usbCrcTableLow);[11] load the lower crc xor byte adress
+
+; bit6
+ in x1, USBIN ;[0] sample line state
+ eor x2, x1 ;[1]
+ bst x2, USBMINUS ;[2]
+ bld shift, 6 ;[3]
+ mov x2, shift ;[4]
+ andi x2, 0x7E ;[5]
+ breq unstuff6 ;[6]
+didunstuff6:
+ lpm ZL, Z ;[7] load the lower xor crc byte
+ ;[8] lpm needs 3 cycles
+ ;[9]
+ eor ZL, x3 ;[10] xor the old high crc byte with the low xor-byte
+ mov x3, x4 ;[11] move the new high order crc value from temp to its destination
+
+; bit7
+ in x2, USBIN ;[0] sample line state
+ eor x1, x2 ;[1]
+ bst x1, USBMINUS ;[2]
+ bld shift, 7 ;[3] now shift holds the complete but inverted data byte
+ mov x1, shift ;[4]
+ andi x1, 0xFC ;[5]
+ breq unstuff7 ;[6]
+didunstuff7:
+ eor x5, shift ;[7] x5 marks all bits which have not been inverted by the unstuffing subs
+ mov x4, x5 ;[8] keep a copy of the data byte it will be stored during next bit0
+ eor ZL, x4 ;[9] feed the actual byte into the crc algorithm
+ rjmp rxDataStart ;[10] next byte
+ ;[11] during the reception of the next byte this one will be fed int the crc algorithm
+
+unstuff4: ;[9] this is the jump delay of rjmp unstuffX
+ ori shift, 0x10 ;[10] invert the last received bit to prevent furhter unstuffing
+ andi x5, 0xEF ;[11] mark this bit as inverted (will be corrected before storing shift)
+ in x2, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors
+ eor x1, x2 ;[1] x1 and x2 have to be different because the stuff bit is always a zero
+ andi x1, USBMASK ;[2] mask the interesting bits
+ breq stuffErr2 ;[3] if the stuff bit is a 1-bit something went wrong
+ mov x1, x2 ;[4] the next bit expects the last state to be in x1
+ nop2 ;[5]
+ ;[6]
+ rjmp didunstuff4 ;[7]
+ ;[8] jump delay of rjmp didunstuffX
+
+unstuff5: ;[8] this is the jump delay of rjmp unstuffX
+ nop ;[9]
+ ori shift, 0x20 ;[10] invert the last received bit to prevent furhter unstuffing
+ andi x5, 0xDF ;[11] mark this bit as inverted (will be corrected before storing shift)
+ in x1, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors
+ eor x2, x1 ;[1] x1 and x2 have to be different because the stuff bit is always a zero
+ andi x2, USBMASK ;[2] mask the interesting bits
+ breq stuffErr2 ;[3] if the stuff bit is a 1-bit something went wrong
+ mov x2, x1 ;[4] the next bit expects the last state to be in x2
+ nop ;[5]
+ rjmp didunstuff5 ;[6]
+ ;[7] jump delay of rjmp didunstuffX
+
+unstuff6: ;[7] this is the jump delay of rjmp unstuffX
+ nop2 ;[8]
+ ;[9]
+ ori shift, 0x40 ;[10] invert the last received bit to prevent furhter unstuffing
+ andi x5, 0xBF ;[11] mark this bit as inverted (will be corrected before storing shift)
+ in x2, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors
+ eor x1, x2 ;[1] x1 and x2 have to be different because the stuff bit is always a zero
+ andi x1, USBMASK ;[2] mask the interesting bits
+ breq stuffErr2 ;[3] if the stuff bit is a 1-bit something went wrong
+ mov x1, x2 ;[4] the next bit expects the last state to be in x1
+ rjmp didunstuff6 ;[5]
+ ;[6] jump delay of rjmp didunstuffX
+
+unstuff7: ;[7] this is the jump delay of rjmp unstuffX
+ nop ;[8]
+ nop ;[9]
+ ori shift, 0x80 ;[10] invert the last received bit to prevent furhter unstuffing
+ andi x5, 0x7F ;[11] mark this bit as inverted (will be corrected before storing shift)
+ in x1, USBIN ;[0] we have some free cycles so we could check for bit stuffing errors
+ eor x2, x1 ;[1] x1 and x2 have to be different because the stuff bit is always a zero
+ andi x2, USBMASK ;[2] mask the interesting bits
+ breq stuffErr2 ;[3] if the stuff bit is a 1-bit something went wrong
+ mov x2, x1 ;[4] the next bit expects the last state to be in x2
+ rjmp didunstuff7 ;[5]
+ ;[6] jump delay of rjmp didunstuff7
+
+; local copy of the stuffErr desitnation for the second half of the receiver loop
+stuffErr2:
+ rjmp stuffErr
+
+;--------------------------------------------------------------------------------------------------------------
+; The crc table follows. It has to be aligned to enable a fast loading of the needed bytes.
+; There are two tables of 256 entries each, the low and the high byte table.
+; Table values were generated with the following C code:
+/*
+#include <stdio.h>
+int main (int argc, char **argv)
+{
+ int i, j;
+ for (i=0; i<512; i++){
+ unsigned short crc = i & 0xff;
+ for(j=0; j<8; j++) crc = (crc >> 1) ^ ((crc & 1) ? 0xa001 : 0);
+ if((i & 7) == 0) printf("\n.byte ");
+ printf("0x%02x, ", (i > 0xff ? (crc >> 8) : crc) & 0xff);
+ if(i == 255) printf("\n");
+ }
+ return 0;
+}
+
+// Use the following algorithm to compute CRC values:
+ushort computeCrc(uchar *msg, uchar msgLen)
+{
+ uchar i;
+ ushort crc = 0xffff;
+ for(i = 0; i < msgLen; i++)
+ crc = usbCrcTable16[lo8(crc) ^ msg[i]] ^ hi8(crc);
+ return crc;
+}
+*/
+
+.balign 256
+usbCrcTableLow:
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x00, 0xC1, 0x81, 0x40, 0x01, 0xC0, 0x80, 0x41
+.byte 0x01, 0xC0, 0x80, 0x41, 0x00, 0xC1, 0x81, 0x40
+
+; .balign 256
+usbCrcTableHigh:
+.byte 0x00, 0xC0, 0xC1, 0x01, 0xC3, 0x03, 0x02, 0xC2
+.byte 0xC6, 0x06, 0x07, 0xC7, 0x05, 0xC5, 0xC4, 0x04
+.byte 0xCC, 0x0C, 0x0D, 0xCD, 0x0F, 0xCF, 0xCE, 0x0E
+.byte 0x0A, 0xCA, 0xCB, 0x0B, 0xC9, 0x09, 0x08, 0xC8
+.byte 0xD8, 0x18, 0x19, 0xD9, 0x1B, 0xDB, 0xDA, 0x1A
+.byte 0x1E, 0xDE, 0xDF, 0x1F, 0xDD, 0x1D, 0x1C, 0xDC
+.byte 0x14, 0xD4, 0xD5, 0x15, 0xD7, 0x17, 0x16, 0xD6
+.byte 0xD2, 0x12, 0x13, 0xD3, 0x11, 0xD1, 0xD0, 0x10
+.byte 0xF0, 0x30, 0x31, 0xF1, 0x33, 0xF3, 0xF2, 0x32
+.byte 0x36, 0xF6, 0xF7, 0x37, 0xF5, 0x35, 0x34, 0xF4
+.byte 0x3C, 0xFC, 0xFD, 0x3D, 0xFF, 0x3F, 0x3E, 0xFE
+.byte 0xFA, 0x3A, 0x3B, 0xFB, 0x39, 0xF9, 0xF8, 0x38
+.byte 0x28, 0xE8, 0xE9, 0x29, 0xEB, 0x2B, 0x2A, 0xEA
+.byte 0xEE, 0x2E, 0x2F, 0xEF, 0x2D, 0xED, 0xEC, 0x2C
+.byte 0xE4, 0x24, 0x25, 0xE5, 0x27, 0xE7, 0xE6, 0x26
+.byte 0x22, 0xE2, 0xE3, 0x23, 0xE1, 0x21, 0x20, 0xE0
+.byte 0xA0, 0x60, 0x61, 0xA1, 0x63, 0xA3, 0xA2, 0x62
+.byte 0x66, 0xA6, 0xA7, 0x67, 0xA5, 0x65, 0x64, 0xA4
+.byte 0x6C, 0xAC, 0xAD, 0x6D, 0xAF, 0x6F, 0x6E, 0xAE
+.byte 0xAA, 0x6A, 0x6B, 0xAB, 0x69, 0xA9, 0xA8, 0x68
+.byte 0x78, 0xB8, 0xB9, 0x79, 0xBB, 0x7B, 0x7A, 0xBA
+.byte 0xBE, 0x7E, 0x7F, 0xBF, 0x7D, 0xBD, 0xBC, 0x7C
+.byte 0xB4, 0x74, 0x75, 0xB5, 0x77, 0xB7, 0xB6, 0x76
+.byte 0x72, 0xB2, 0xB3, 0x73, 0xB1, 0x71, 0x70, 0xB0
+.byte 0x50, 0x90, 0x91, 0x51, 0x93, 0x53, 0x52, 0x92
+.byte 0x96, 0x56, 0x57, 0x97, 0x55, 0x95, 0x94, 0x54
+.byte 0x9C, 0x5C, 0x5D, 0x9D, 0x5F, 0x9F, 0x9E, 0x5E
+.byte 0x5A, 0x9A, 0x9B, 0x5B, 0x99, 0x59, 0x58, 0x98
+.byte 0x88, 0x48, 0x49, 0x89, 0x4B, 0x8B, 0x8A, 0x4A
+.byte 0x4E, 0x8E, 0x8F, 0x4F, 0x8D, 0x4D, 0x4C, 0x8C
+.byte 0x44, 0x84, 0x85, 0x45, 0x87, 0x47, 0x46, 0x86
+.byte 0x82, 0x42, 0x43, 0x83, 0x41, 0x81, 0x80, 0x40
+
diff --git a/tmk_core/protocol/vusb/usbdrv/usbdrvasm20.inc b/tmk_core/protocol/vusb/usbdrv/usbdrvasm20.inc
new file mode 100644
index 000000000..303abaf64
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbdrvasm20.inc
@@ -0,0 +1,360 @@
+/* Name: usbdrvasm20.inc
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Jeroen Benschop
+ * Based on usbdrvasm16.inc from Christian Starkjohann
+ * Creation Date: 2008-03-05
+ * Tabsize: 4
+ * Copyright: (c) 2008 by Jeroen Benschop and OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * Revision: $Id: usbdrvasm20.inc 740 2009-04-13 18:23:31Z cs $
+ */
+
+/* Do not link this file! Link usbdrvasm.S instead, which includes the
+ * appropriate implementation!
+ */
+
+/*
+General Description:
+This file is the 20 MHz version of the asssembler part of the USB driver. It
+requires a 20 MHz crystal (not a ceramic resonator and not a calibrated RC
+oscillator).
+
+See usbdrv.h for a description of the entire driver.
+
+Since almost all of this code is timing critical, don't change unless you
+really know what you are doing! Many parts require not only a maximum number
+of CPU cycles, but even an exact number of cycles!
+*/
+
+#define leap2 x3
+#ifdef __IAR_SYSTEMS_ASM__
+#define nextInst $+2
+#else
+#define nextInst .+0
+#endif
+
+;max stack usage: [ret(2), YL, SREG, YH, bitcnt, shift, x1, x2, x3, x4, cnt] = 12 bytes
+;nominal frequency: 20 MHz -> 13.333333 cycles per bit, 106.666667 cycles per byte
+; Numbers in brackets are clocks counted from center of last sync bit
+; when instruction starts
+;register use in receive loop:
+; shift assembles the byte currently being received
+; x1 holds the D+ and D- line state
+; x2 holds the previous line state
+; x4 (leap) is used to add a leap cycle once every three bytes received
+; X3 (leap2) is used to add a leap cycle once every three stuff bits received
+; bitcnt is used to determine when a stuff bit is due
+; cnt holds the number of bytes left in the receive buffer
+
+USB_INTR_VECTOR:
+;order of registers pushed: YL, SREG YH, [sofError], bitcnt, shift, x1, x2, x3, x4, cnt
+ push YL ;[-28] push only what is necessary to sync with edge ASAP
+ in YL, SREG ;[-26]
+ push YL ;[-25]
+ push YH ;[-23]
+;----------------------------------------------------------------------------
+; Synchronize with sync pattern:
+;----------------------------------------------------------------------------
+;sync byte (D-) pattern LSb to MSb: 01010100 [1 = idle = J, 0 = K]
+;sync up with J to K edge during sync pattern -- use fastest possible loops
+;The first part waits at most 1 bit long since we must be in sync pattern.
+;YL is guarenteed to be < 0x80 because I flag is clear. When we jump to
+;waitForJ, ensure that this prerequisite is met.
+waitForJ:
+ inc YL
+ sbis USBIN, USBMINUS
+ brne waitForJ ; just make sure we have ANY timeout
+waitForK:
+;The following code results in a sampling window of < 1/4 bit which meets the spec.
+ sbis USBIN, USBMINUS ;[-19]
+ rjmp foundK ;[-18]
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+ sbis USBIN, USBMINUS
+ rjmp foundK
+#if USB_COUNT_SOF
+ lds YL, usbSofCount
+ inc YL
+ sts usbSofCount, YL
+#endif /* USB_COUNT_SOF */
+#ifdef USB_SOF_HOOK
+ USB_SOF_HOOK
+#endif
+ rjmp sofError
+foundK: ;[-16]
+;{3, 5} after falling D- edge, average delay: 4 cycles
+;bit0 should be at 34 for center sampling. Currently at 4 so 30 cylces till bit 0 sample
+;use 1 bit time for setup purposes, then sample again. Numbers in brackets
+;are cycles from center of first sync (double K) bit after the instruction
+ push bitcnt ;[-16]
+; [---] ;[-15]
+ lds YL, usbInputBufOffset;[-14]
+; [---] ;[-13]
+ clr YH ;[-12]
+ subi YL, lo8(-(usbRxBuf));[-11] [rx loop init]
+ sbci YH, hi8(-(usbRxBuf));[-10] [rx loop init]
+ push shift ;[-9]
+; [---] ;[-8]
+ ldi shift,0x40 ;[-7] set msb to "1" so processing bit7 can be detected
+ nop2 ;[-6]
+; [---] ;[-5]
+ ldi bitcnt, 5 ;[-4] [rx loop init]
+ sbis USBIN, USBMINUS ;[-3] we want two bits K (sample 3 cycles too early)
+ rjmp haveTwoBitsK ;[-2]
+ pop shift ;[-1] undo the push from before
+ pop bitcnt ;[1]
+ rjmp waitForK ;[3] this was not the end of sync, retry
+; The entire loop from waitForK until rjmp waitForK above must not exceed two
+; bit times (= 27 cycles).
+
+;----------------------------------------------------------------------------
+; push more registers and initialize values while we sample the first bits:
+;----------------------------------------------------------------------------
+haveTwoBitsK:
+ push x1 ;[0]
+ push x2 ;[2]
+ push x3 ;[4] (leap2)
+ ldi leap2, 0x55 ;[6] add leap cycle on 2nd,5th,8th,... stuff bit
+ push x4 ;[7] == leap
+ ldi leap, 0x55 ;[9] skip leap cycle on 2nd,5th,8th,... byte received
+ push cnt ;[10]
+ ldi cnt, USB_BUFSIZE ;[12] [rx loop init]
+ ldi x2, 1<<USBPLUS ;[13] current line state is K state. D+=="1", D-=="0"
+bit0:
+ in x1, USBIN ;[0] sample line state
+ andi x1, USBMASK ;[1] filter only D+ and D- bits
+ rjmp handleBit ;[2] make bit0 14 cycles long
+
+;----------------------------------------------------------------------------
+; Process bit7. However, bit 6 still may need unstuffing.
+;----------------------------------------------------------------------------
+
+b6checkUnstuff:
+ dec bitcnt ;[9]
+ breq unstuff6 ;[10]
+bit7:
+ subi cnt, 1 ;[11] cannot use dec becaus it does not affect the carry flag
+ brcs overflow ;[12] Too many bytes received. Ignore packet
+ in x1, USBIN ;[0] sample line state
+ andi x1, USBMASK ;[1] filter only D+ and D- bits
+ cpse x1, x2 ;[2] when previous line state equals current line state, handle "1"
+ rjmp b7handle0 ;[3] when line state differs, handle "0"
+ sec ;[4]
+ ror shift ;[5] shift "1" into the data
+ st y+, shift ;[6] store the data into the buffer
+ ldi shift, 0x40 ;[7] reset data for receiving the next byte
+ subi leap, 0x55 ;[9] trick to introduce a leap cycle every 3 bytes
+ brcc nextInst ;[10 or 11] it will fail after 85 bytes. However low speed can only receive 11
+ dec bitcnt ;[11 or 12]
+ brne bit0 ;[12 or 13]
+ ldi x1, 1 ;[13 or 14] unstuffing bit 7
+ in bitcnt, USBIN ;[0] sample stuff bit
+ rjmp unstuff ;[1]
+
+b7handle0:
+ mov x2,x1 ;[5] Set x2 to current line state
+ ldi bitcnt, 6 ;[6]
+ lsr shift ;[7] shift "0" into the data
+ st y+, shift ;[8] store data into the buffer
+ ldi shift, 0x40 ;[10] reset data for receiving the next byte
+ subi leap, 0x55 ;[11] trick to introduce a leap cycle every 3 bytes
+ brcs bit0 ;[12] it will fail after 85 bytes. However low speed can only receive 11
+ rjmp bit0 ;[13]
+
+
+;----------------------------------------------------------------------------
+; Handle unstuff
+; x1==0xFF indicate unstuffing bit6
+;----------------------------------------------------------------------------
+
+unstuff6:
+ ldi x1,0xFF ;[12] indicate unstuffing bit 6
+ in bitcnt, USBIN ;[0] sample stuff bit
+ nop ;[1] fix timing
+unstuff: ;b0-5 b6 b7
+ mov x2,bitcnt ;[3] [2] [3] Set x2 to match line state
+ subi leap2, 0x55 ;[4] [3] [4] delay loop
+ brcs nextInst ;[5] [4] [5] add one cycle every three stuff bits
+ sbci leap2,0 ;[6] [5] [6]
+ ldi bitcnt,6 ;[7] [6] [7] reset bit stuff counter
+ andi x2, USBMASK ;[8] [7] [8] only keep D+ and D-
+ cpi x1,0 ;[9] [8] [9]
+ brmi bit7 ;[10] [9] [10] finished unstuffing bit6 When x1<0
+ breq bitloop ;[11] --- [11] finished unstuffing bit0-5 when x1=0
+ nop ;--- --- [12]
+ in x1, USBIN ;--- --- [0] sample line state for bit0
+ andi x1, USBMASK ;--- --- [1] filter only D+ and D- bits
+ rjmp handleBit ;--- --- [2] make bit0 14 cycles long
+
+;----------------------------------------------------------------------------
+; Receiver loop (numbers in brackets are cycles within byte after instr)
+;----------------------------------------------------------------------------
+bitloop:
+ in x1, USBIN ;[0] sample line state
+ andi x1, USBMASK ;[1] filter only D+ and D- bits
+ breq se0 ;[2] both lines are low so handle se0
+handleBit:
+ cpse x1, x2 ;[3] when previous line state equals current line state, handle "1"
+ rjmp handle0 ;[4] when line state differs, handle "0"
+ sec ;[5]
+ ror shift ;[6] shift "1" into the data
+ brcs b6checkUnstuff ;[7] When after shift C is set, next bit is bit7
+ nop2 ;[8]
+ dec bitcnt ;[10]
+ brne bitloop ;[11]
+ ldi x1,0 ;[12] indicate unstuff for bit other than bit6 or bit7
+ in bitcnt, USBIN ;[0] sample stuff bit
+ rjmp unstuff ;[1]
+
+handle0:
+ mov x2, x1 ;[6] Set x2 to current line state
+ ldi bitcnt, 6 ;[7] reset unstuff counter.
+ lsr shift ;[8] shift "0" into the data
+ brcs bit7 ;[9] When after shift C is set, next bit is bit7
+ nop ;[10]
+ rjmp bitloop ;[11]
+
+;----------------------------------------------------------------------------
+; End of receive loop. Now start handling EOP
+;----------------------------------------------------------------------------
+
+macro POP_STANDARD ; 14 cycles
+ pop cnt
+ pop x4
+ pop x3
+ pop x2
+ pop x1
+ pop shift
+ pop bitcnt
+ endm
+macro POP_RETI ; 7 cycles
+ pop YH
+ pop YL
+ out SREG, YL
+ pop YL
+ endm
+
+
+
+#include "asmcommon.inc"
+
+; USB spec says:
+; idle = J
+; J = (D+ = 0), (D- = 1)
+; K = (D+ = 1), (D- = 0)
+; Spec allows 7.5 bit times from EOP to SOP for replies
+; 7.5 bit times is 100 cycles. This implementation arrives a bit later at se0
+; then specified in the include file but there is plenty of time
+
+bitstuffN:
+ eor x1, x4 ;[8]
+ ldi x2, 0 ;[9]
+ nop2 ;[10]
+ out USBOUT, x1 ;[12] <-- out
+ rjmp didStuffN ;[0]
+
+bitstuff7:
+ eor x1, x4 ;[6]
+ ldi x2, 0 ;[7] Carry is zero due to brcc
+ rol shift ;[8] compensate for ror shift at branch destination
+ nop2 ;[9]
+ rjmp didStuff7 ;[11]
+
+sendNakAndReti:
+ ldi x3, USBPID_NAK ;[-18]
+ rjmp sendX3AndReti ;[-17]
+sendAckAndReti:
+ ldi cnt, USBPID_ACK ;[-17]
+sendCntAndReti:
+ mov x3, cnt ;[-16]
+sendX3AndReti:
+ ldi YL, 20 ;[-15] x3==r20 address is 20
+ ldi YH, 0 ;[-14]
+ ldi cnt, 2 ;[-13]
+; rjmp usbSendAndReti fallthrough
+
+;usbSend:
+;pointer to data in 'Y'
+;number of bytes in 'cnt' -- including sync byte [range 2 ... 12]
+;uses: x1...x4, btcnt, shift, cnt, Y
+;Numbers in brackets are time since first bit of sync pattern is sent
+;We don't match the transfer rate exactly (don't insert leap cycles every third
+;byte) because the spec demands only 1.5% precision anyway.
+usbSendAndReti: ; 12 cycles until SOP
+ in x2, USBDDR ;[-12]
+ ori x2, USBMASK ;[-11]
+ sbi USBOUT, USBMINUS;[-10] prepare idle state; D+ and D- must have been 0 (no pullups)
+ in x1, USBOUT ;[-8] port mirror for tx loop
+ out USBDDR, x2 ;[-7] <- acquire bus
+; need not init x2 (bitstuff history) because sync starts with 0
+ ldi x4, USBMASK ;[-6] exor mask
+ ldi shift, 0x80 ;[-5] sync byte is first byte sent
+txByteLoop:
+ ldi bitcnt, 0x49 ;[-4] [10] binary 01001001
+txBitLoop:
+ sbrs shift, 0 ;[-3] [10] [11]
+ eor x1, x4 ;[-2] [11] [12]
+ out USBOUT, x1 ;[-1] [12] [13] <-- out N
+ ror shift ;[0] [13] [14]
+ ror x2 ;[1]
+didStuffN:
+ nop2 ;[2]
+ nop ;[4]
+ cpi x2, 0xfc ;[5]
+ brcc bitstuffN ;[6]
+ lsr bitcnt ;[7]
+ brcc txBitLoop ;[8]
+ brne txBitLoop ;[9]
+
+ sbrs shift, 0 ;[10]
+ eor x1, x4 ;[11]
+didStuff7:
+ out USBOUT, x1 ;[-1] [13] <-- out 7
+ ror shift ;[0] [14]
+ ror x2 ;[1]
+ nop ;[2]
+ cpi x2, 0xfc ;[3]
+ brcc bitstuff7 ;[4]
+ ld shift, y+ ;[5]
+ dec cnt ;[7]
+ brne txByteLoop ;[8]
+;make SE0:
+ cbr x1, USBMASK ;[9] prepare SE0 [spec says EOP may be 25 to 30 cycles]
+ lds x2, usbNewDeviceAddr;[10]
+ lsl x2 ;[12] we compare with left shifted address
+ out USBOUT, x1 ;[13] <-- out SE0 -- from now 2 bits = 22 cycles until bus idle
+ subi YL, 20 + 2 ;[0] Only assign address on data packets, not ACK/NAK in x3
+ sbci YH, 0 ;[1]
+;2006-03-06: moved transfer of new address to usbDeviceAddr from C-Code to asm:
+;set address only after data packet was sent, not after handshake
+ breq skipAddrAssign ;[2]
+ sts usbDeviceAddr, x2; if not skipped: SE0 is one cycle longer
+skipAddrAssign:
+;end of usbDeviceAddress transfer
+ ldi x2, 1<<USB_INTR_PENDING_BIT;[4] int0 occurred during TX -- clear pending flag
+ USB_STORE_PENDING(x2) ;[5]
+ ori x1, USBIDLE ;[6]
+ in x2, USBDDR ;[7]
+ cbr x2, USBMASK ;[8] set both pins to input
+ mov x3, x1 ;[9]
+ cbr x3, USBMASK ;[10] configure no pullup on both pins
+ ldi x4, 5 ;[11]
+se0Delay:
+ dec x4 ;[12] [15] [18] [21] [24]
+ brne se0Delay ;[13] [16] [19] [22] [25]
+ out USBOUT, x1 ;[26] <-- out J (idle) -- end of SE0 (EOP signal)
+ out USBDDR, x2 ;[27] <-- release bus now
+ out USBOUT, x3 ;[28] <-- ensure no pull-up resistors are active
+ rjmp doReturn
diff --git a/tmk_core/protocol/vusb/usbdrv/usbportability.h b/tmk_core/protocol/vusb/usbdrv/usbportability.h
new file mode 100644
index 000000000..476184dc6
--- /dev/null
+++ b/tmk_core/protocol/vusb/usbdrv/usbportability.h
@@ -0,0 +1,144 @@
+/* Name: usbportability.h
+ * Project: V-USB, virtual USB port for Atmel's(r) AVR(r) microcontrollers
+ * Author: Christian Starkjohann
+ * Creation Date: 2008-06-17
+ * Tabsize: 4
+ * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH
+ * License: GNU GPL v2 (see License.txt), GNU GPL v3 or proprietary (CommercialLicense.txt)
+ * This Revision: $Id: usbportability.h 785 2010-05-30 17:57:07Z cs $
+ */
+
+/*
+General Description:
+This header is intended to contain all (or at least most of) the compiler
+and library dependent stuff. The C code is written for avr-gcc and avr-libc.
+The API of other development environments is converted to gcc's and avr-libc's
+API by means of defines.
+
+This header also contains all system includes since they depend on the
+development environment.
+
+Thanks to Oleg Semyonov for his help with the IAR tools port!
+*/
+
+#ifndef __usbportability_h_INCLUDED__
+#define __usbportability_h_INCLUDED__
+
+/* We check explicitly for IAR and CodeVision. Default is avr-gcc/avr-libc. */
+
+/* ------------------------------------------------------------------------- */
+#if defined __IAR_SYSTEMS_ICC__ || defined __IAR_SYSTEMS_ASM__ /* check for IAR */
+/* ------------------------------------------------------------------------- */
+
+#ifndef ENABLE_BIT_DEFINITIONS
+# define ENABLE_BIT_DEFINITIONS 1 /* Enable bit definitions */
+#endif
+
+/* Include IAR headers */
+#include <ioavr.h>
+#ifndef __IAR_SYSTEMS_ASM__
+# include <inavr.h>
+#endif
+
+#define __attribute__(arg) /* not supported on IAR */
+
+#ifdef __IAR_SYSTEMS_ASM__
+# define __ASSEMBLER__ /* IAR does not define standard macro for asm */
+#endif
+
+#ifdef __HAS_ELPM__
+# define PROGMEM __farflash
+#else
+# define PROGMEM __flash
+#endif
+
+#define USB_READ_FLASH(addr) (*(PROGMEM char *)(addr))
+
+/* The following definitions are not needed by the driver, but may be of some
+ * help if you port a gcc based project to IAR.
+ */
+#define cli() __disable_interrupt()
+#define sei() __enable_interrupt()
+#define wdt_reset() __watchdog_reset()
+#define _BV(x) (1 << (x))
+
+/* assembler compatibility macros */
+#define nop2 rjmp $+2 /* jump to next instruction */
+#define XL r26
+#define XH r27
+#define YL r28
+#define YH r29
+#define ZL r30
+#define ZH r31
+#define lo8(x) LOW(x)
+#define hi8(x) (((x)>>8) & 0xff) /* not HIGH to allow XLINK to make a proper range check */
+
+/* Depending on the device you use, you may get problems with the way usbdrv.h
+ * handles the differences between devices. Since IAR does not use #defines
+ * for MCU registers, we can't check for the existence of a particular
+ * register with an #ifdef. If the autodetection mechanism fails, include
+ * definitions for the required USB_INTR_* macros in your usbconfig.h. See
+ * usbconfig-prototype.h and usbdrv.h for details.
+ */
+
+/* ------------------------------------------------------------------------- */
+#elif __CODEVISIONAVR__ /* check for CodeVision AVR */
+/* ------------------------------------------------------------------------- */
+/* This port is not working (yet) */
+
+/* #define F_CPU _MCU_CLOCK_FREQUENCY_ seems to be defined automatically */
+
+#include <io.h>
+#include <delay.h>
+
+#define __attribute__(arg) /* not supported on IAR */
+
+#define PROGMEM __flash
+#define USB_READ_FLASH(addr) (*(PROGMEM char *)(addr))
+
+#ifndef __ASSEMBLER__
+static inline void cli(void)
+{
+ #asm("cli");
+}
+static inline void sei(void)
+{
+ #asm("sei");
+}
+#endif
+#define _delay_ms(t) delay_ms(t)
+#define _BV(x) (1 << (x))
+#define USB_CFG_USE_SWITCH_STATEMENT 1 /* macro for if() cascase fails for unknown reason */
+
+#define macro .macro
+#define endm .endmacro
+#define nop2 rjmp .+0 /* jump to next instruction */
+
+/* ------------------------------------------------------------------------- */
+#else /* default development environment is avr-gcc/avr-libc */
+/* ------------------------------------------------------------------------- */
+
+#include <avr/io.h>
+#ifdef __ASSEMBLER__
+# define _VECTOR(N) __vector_ ## N /* io.h does not define this for asm */
+#else
+# include <avr/pgmspace.h>
+#endif
+
+#if USB_CFG_DRIVER_FLASH_PAGE
+# define USB_READ_FLASH(addr) pgm_read_byte_far(((long)USB_CFG_DRIVER_FLASH_PAGE << 16) | (long)(addr))
+#else
+# define USB_READ_FLASH(addr) pgm_read_byte(addr)
+#endif
+
+#define macro .macro
+#define endm .endm
+#define nop2 rjmp .+0 /* jump to next instruction */
+
+#endif /* development environment */
+
+/* for conveniecne, ensure that PRG_RDB exists */
+#ifndef PRG_RDB
+# define PRG_RDB(addr) USB_READ_FLASH(addr)
+#endif
+#endif /* __usbportability_h_INCLUDED__ */
diff --git a/tmk_core/protocol/vusb/vusb.c b/tmk_core/protocol/vusb/vusb.c
new file mode 100644
index 000000000..022ac6f6b
--- /dev/null
+++ b/tmk_core/protocol/vusb/vusb.c
@@ -0,0 +1,510 @@
+/*
+Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include <avr/eeprom.h>
+#include <avr/wdt.h>
+#include <stdint.h>
+#include "usbdrv.h"
+#include "usbconfig.h"
+#include "host.h"
+#include "report.h"
+#include "print.h"
+#include "debug.h"
+#include "host_driver.h"
+#include "vusb.h"
+#include "bootloader.h"
+
+
+static uint8_t vusb_keyboard_leds = 0;
+static uint8_t vusb_idle_rate = 0;
+
+/* Keyboard report send buffer */
+#define KBUF_SIZE 16
+static report_keyboard_t kbuf[KBUF_SIZE];
+static uint8_t kbuf_head = 0;
+static uint8_t kbuf_tail = 0;
+
+typedef struct {
+ uint8_t modifier;
+ uint8_t reserved;
+ uint8_t keycode[6];
+} keyboard_report_t;
+
+static keyboard_report_t keyboard_report; // sent to PC
+
+/* transfer keyboard report from buffer */
+void vusb_transfer_keyboard(void)
+{
+ if (usbInterruptIsReady()) {
+ if (kbuf_head != kbuf_tail) {
+ usbSetInterrupt((void *)&kbuf[kbuf_tail], sizeof(report_keyboard_t));
+ kbuf_tail = (kbuf_tail + 1) % KBUF_SIZE;
+ if (debug_keyboard) {
+ print("V-USB: kbuf["); pdec(kbuf_tail); print("->"); pdec(kbuf_head); print("](");
+ phex((kbuf_head < kbuf_tail) ? (KBUF_SIZE - kbuf_tail + kbuf_head) : (kbuf_head - kbuf_tail));
+ print(")\n");
+ }
+ }
+ }
+}
+
+
+/*------------------------------------------------------------------*
+ * Host driver
+ *------------------------------------------------------------------*/
+static uint8_t keyboard_leds(void);
+static void send_keyboard(report_keyboard_t *report);
+static void send_mouse(report_mouse_t *report);
+static void send_system(uint16_t data);
+static void send_consumer(uint16_t data);
+
+static host_driver_t driver = {
+ keyboard_leds,
+ send_keyboard,
+ send_mouse,
+ send_system,
+ send_consumer
+};
+
+host_driver_t *vusb_driver(void)
+{
+ return &driver;
+}
+
+static uint8_t keyboard_leds(void) {
+ return vusb_keyboard_leds;
+}
+
+static void send_keyboard(report_keyboard_t *report)
+{
+ uint8_t next = (kbuf_head + 1) % KBUF_SIZE;
+ if (next != kbuf_tail) {
+ kbuf[kbuf_head] = *report;
+ kbuf_head = next;
+ } else {
+ debug("kbuf: full\n");
+ }
+
+ // NOTE: send key strokes of Macro
+ usbPoll();
+ vusb_transfer_keyboard();
+}
+
+
+typedef struct {
+ uint8_t report_id;
+ report_mouse_t report;
+} __attribute__ ((packed)) vusb_mouse_report_t;
+
+static void send_mouse(report_mouse_t *report)
+{
+ vusb_mouse_report_t r = {
+ .report_id = REPORT_ID_MOUSE,
+ .report = *report
+ };
+ if (usbInterruptIsReady3()) {
+ usbSetInterrupt3((void *)&r, sizeof(vusb_mouse_report_t));
+ }
+}
+
+
+typedef struct {
+ uint8_t report_id;
+ uint16_t usage;
+} __attribute__ ((packed)) report_extra_t;
+
+static void send_system(uint16_t data)
+{
+ static uint16_t last_data = 0;
+ if (data == last_data) return;
+ last_data = data;
+
+ report_extra_t report = {
+ .report_id = REPORT_ID_SYSTEM,
+ .usage = data
+ };
+ if (usbInterruptIsReady3()) {
+ usbSetInterrupt3((void *)&report, sizeof(report));
+ }
+}
+
+static void send_consumer(uint16_t data)
+{
+ static uint16_t last_data = 0;
+ if (data == last_data) return;
+ last_data = data;
+
+ report_extra_t report = {
+ .report_id = REPORT_ID_CONSUMER,
+ .usage = data
+ };
+ if (usbInterruptIsReady3()) {
+ usbSetInterrupt3((void *)&report, sizeof(report));
+ }
+}
+
+
+
+/*------------------------------------------------------------------*
+ * Request from host *
+ *------------------------------------------------------------------*/
+static struct {
+ uint16_t len;
+ enum {
+ NONE,
+ BOOTLOADER,
+ SET_LED
+ } kind;
+} last_req;
+
+usbMsgLen_t usbFunctionSetup(uchar data[8])
+{
+usbRequest_t *rq = (void *)data;
+
+ if((rq->bmRequestType & USBRQ_TYPE_MASK) == USBRQ_TYPE_CLASS){ /* class request type */
+ if(rq->bRequest == USBRQ_HID_GET_REPORT){
+ debug("GET_REPORT:");
+ /* we only have one report type, so don't look at wValue */
+ usbMsgPtr = (void *)&keyboard_report;
+ return sizeof(keyboard_report);
+ }else if(rq->bRequest == USBRQ_HID_GET_IDLE){
+ debug("GET_IDLE: ");
+ //debug_hex(vusb_idle_rate);
+ usbMsgPtr = &vusb_idle_rate;
+ return 1;
+ }else if(rq->bRequest == USBRQ_HID_SET_IDLE){
+ vusb_idle_rate = rq->wValue.bytes[1];
+ debug("SET_IDLE: ");
+ debug_hex(vusb_idle_rate);
+ }else if(rq->bRequest == USBRQ_HID_SET_REPORT){
+ debug("SET_REPORT: ");
+ // Report Type: 0x02(Out)/ReportID: 0x00(none) && Interface: 0(keyboard)
+ if (rq->wValue.word == 0x0200 && rq->wIndex.word == 0) {
+ debug("SET_LED: ");
+ last_req.kind = SET_LED;
+ last_req.len = rq->wLength.word;
+#ifdef BOOTLOADER_SIZE
+ } else if(rq->wValue.word == 0x0301) {
+ last_req.kind = BOOTLOADER;
+ last_req.len = rq->wLength.word;
+#endif
+ }
+ return USB_NO_MSG; // to get data in usbFunctionWrite
+ } else {
+ debug("UNKNOWN:");
+ }
+ }else{
+ debug("VENDOR:");
+ /* no vendor specific requests implemented */
+ }
+ debug("\n");
+ return 0; /* default for not implemented requests: return no data back to host */
+}
+
+uchar usbFunctionWrite(uchar *data, uchar len)
+{
+ if (last_req.len == 0) {
+ return -1;
+ }
+ switch (last_req.kind) {
+ case SET_LED:
+ debug("SET_LED: ");
+ debug_hex(data[0]);
+ debug("\n");
+ vusb_keyboard_leds = data[0];
+ last_req.len = 0;
+ return 1;
+ break;
+ case BOOTLOADER:
+ usbDeviceDisconnect();
+ bootloader_jump();
+ return 1;
+ break;
+ case NONE:
+ default:
+ return -1;
+ break;
+ }
+ return 1;
+}
+
+
+
+/*------------------------------------------------------------------*
+ * Descriptors *
+ *------------------------------------------------------------------*/
+
+/*
+ * Report Descriptor for keyboard
+ *
+ * from an example in HID spec appendix
+ */
+const PROGMEM uchar keyboard_hid_report[] = {
+ 0x05, 0x01, // Usage Page (Generic Desktop),
+ 0x09, 0x06, // Usage (Keyboard),
+ 0xA1, 0x01, // Collection (Application),
+ 0x75, 0x01, // Report Size (1),
+ 0x95, 0x08, // Report Count (8),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0xE0, // Usage Minimum (224),
+ 0x29, 0xE7, // Usage Maximum (231),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x25, 0x01, // Logical Maximum (1),
+ 0x81, 0x02, // Input (Data, Variable, Absolute), ;Modifier byte
+ 0x95, 0x01, // Report Count (1),
+ 0x75, 0x08, // Report Size (8),
+ 0x81, 0x03, // Input (Constant), ;Reserved byte
+ 0x95, 0x05, // Report Count (5),
+ 0x75, 0x01, // Report Size (1),
+ 0x05, 0x08, // Usage Page (LEDs),
+ 0x19, 0x01, // Usage Minimum (1),
+ 0x29, 0x05, // Usage Maximum (5),
+ 0x91, 0x02, // Output (Data, Variable, Absolute), ;LED report
+ 0x95, 0x01, // Report Count (1),
+ 0x75, 0x03, // Report Size (3),
+ 0x91, 0x03, // Output (Constant), ;LED report padding
+ 0x95, 0x06, // Report Count (6),
+ 0x75, 0x08, // Report Size (8),
+ 0x15, 0x00, // Logical Minimum (0),
+ 0x26, 0xFF, 0x00, // Logical Maximum(255),
+ 0x05, 0x07, // Usage Page (Key Codes),
+ 0x19, 0x00, // Usage Minimum (0),
+ 0x29, 0xFF, // Usage Maximum (255),
+ 0x81, 0x00, // Input (Data, Array),
+ 0xc0 // End Collection
+};
+
+/*
+ * Report Descriptor for mouse
+ *
+ * Mouse Protocol 1, HID 1.11 spec, Appendix B, page 59-60, with wheel extension
+ * http://www.microchip.com/forums/tm.aspx?high=&m=391435&mpage=1#391521
+ * http://www.keil.com/forum/15671/
+ * http://www.microsoft.com/whdc/device/input/wheel.mspx
+ */
+const PROGMEM uchar mouse_hid_report[] = {
+ /* mouse */
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x02, // USAGE (Mouse)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x85, REPORT_ID_MOUSE, // REPORT_ID (1)
+ 0x09, 0x01, // USAGE (Pointer)
+ 0xa1, 0x00, // COLLECTION (Physical)
+ // ---------------------------- Buttons
+ 0x05, 0x09, // USAGE_PAGE (Button)
+ 0x19, 0x01, // USAGE_MINIMUM (Button 1)
+ 0x29, 0x05, // USAGE_MAXIMUM (Button 5)
+ 0x15, 0x00, // LOGICAL_MINIMUM (0)
+ 0x25, 0x01, // LOGICAL_MAXIMUM (1)
+ 0x75, 0x01, // REPORT_SIZE (1)
+ 0x95, 0x05, // REPORT_COUNT (5)
+ 0x81, 0x02, // INPUT (Data,Var,Abs)
+ 0x75, 0x03, // REPORT_SIZE (3)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x03, // INPUT (Cnst,Var,Abs)
+ // ---------------------------- X,Y position
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x30, // USAGE (X)
+ 0x09, 0x31, // USAGE (Y)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x02, // REPORT_COUNT (2)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ // ---------------------------- Vertical wheel
+ 0x09, 0x38, // USAGE (Wheel)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x35, 0x00, // PHYSICAL_MINIMUM (0) - reset physical
+ 0x45, 0x00, // PHYSICAL_MAXIMUM (0)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ // ---------------------------- Horizontal wheel
+ 0x05, 0x0c, // USAGE_PAGE (Consumer Devices)
+ 0x0a, 0x38, 0x02, // USAGE (AC Pan)
+ 0x15, 0x81, // LOGICAL_MINIMUM (-127)
+ 0x25, 0x7f, // LOGICAL_MAXIMUM (127)
+ 0x75, 0x08, // REPORT_SIZE (8)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x06, // INPUT (Data,Var,Rel)
+ 0xc0, // END_COLLECTION
+ 0xc0, // END_COLLECTION
+ /* system control */
+ 0x05, 0x01, // USAGE_PAGE (Generic Desktop)
+ 0x09, 0x80, // USAGE (System Control)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x85, REPORT_ID_SYSTEM, // REPORT_ID (2)
+ 0x15, 0x01, // LOGICAL_MINIMUM (0x1)
+ 0x26, 0xb7, 0x00, // LOGICAL_MAXIMUM (0xb7)
+ 0x19, 0x01, // USAGE_MINIMUM (0x1)
+ 0x29, 0xb7, // USAGE_MAXIMUM (0xb7)
+ 0x75, 0x10, // REPORT_SIZE (16)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x00, // INPUT (Data,Array,Abs)
+ 0xc0, // END_COLLECTION
+ /* consumer */
+ 0x05, 0x0c, // USAGE_PAGE (Consumer Devices)
+ 0x09, 0x01, // USAGE (Consumer Control)
+ 0xa1, 0x01, // COLLECTION (Application)
+ 0x85, REPORT_ID_CONSUMER, // REPORT_ID (3)
+ 0x15, 0x01, // LOGICAL_MINIMUM (0x1)
+ 0x26, 0x9c, 0x02, // LOGICAL_MAXIMUM (0x29c)
+ 0x19, 0x01, // USAGE_MINIMUM (0x1)
+ 0x2a, 0x9c, 0x02, // USAGE_MAXIMUM (0x29c)
+ 0x75, 0x10, // REPORT_SIZE (16)
+ 0x95, 0x01, // REPORT_COUNT (1)
+ 0x81, 0x00, // INPUT (Data,Array,Abs)
+ 0xc0, // END_COLLECTION
+};
+
+
+/*
+ * Descriptor for compite device: Keyboard + Mouse
+ *
+ * contains: device, interface, HID and endpoint descriptors
+ */
+#if USB_CFG_DESCR_PROPS_CONFIGURATION
+const PROGMEM char usbDescriptorConfiguration[] = { /* USB configuration descriptor */
+ 9, /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */
+ USBDESCR_CONFIG, /* descriptor type */
+ 9 + (9 + 9 + 7) + (9 + 9 + 7), 0,
+ //18 + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT3 + 9, 0,
+ /* total length of data returned (including inlined descriptors) */
+ 2, /* number of interfaces in this configuration */
+ 1, /* index of this configuration */
+ 0, /* configuration name string index */
+#if USB_CFG_IS_SELF_POWERED
+ (1 << 7) | USBATTR_SELFPOWER, /* attributes */
+#else
+ (1 << 7), /* attributes */
+#endif
+ USB_CFG_MAX_BUS_POWER/2, /* max USB current in 2mA units */
+
+ /*
+ * Keyboard interface
+ */
+ /* Interface descriptor */
+ 9, /* sizeof(usbDescrInterface): length of descriptor in bytes */
+ USBDESCR_INTERFACE, /* descriptor type */
+ 0, /* index of this interface */
+ 0, /* alternate setting for this interface */
+ USB_CFG_HAVE_INTRIN_ENDPOINT, /* endpoints excl 0: number of endpoint descriptors to follow */
+ USB_CFG_INTERFACE_CLASS,
+ USB_CFG_INTERFACE_SUBCLASS,
+ USB_CFG_INTERFACE_PROTOCOL,
+ 0, /* string index for interface */
+ /* HID descriptor */
+ 9, /* sizeof(usbDescrHID): length of descriptor in bytes */
+ USBDESCR_HID, /* descriptor type: HID */
+ 0x01, 0x01, /* BCD representation of HID version */
+ 0x00, /* target country code */
+ 0x01, /* number of HID Report (or other HID class) Descriptor infos to follow */
+ 0x22, /* descriptor type: report */
+ sizeof(keyboard_hid_report), 0, /* total length of report descriptor */
+ /* Endpoint descriptor */
+#if USB_CFG_HAVE_INTRIN_ENDPOINT /* endpoint descriptor for endpoint 1 */
+ 7, /* sizeof(usbDescrEndpoint) */
+ USBDESCR_ENDPOINT, /* descriptor type = endpoint */
+ (char)0x81, /* IN endpoint number 1 */
+ 0x03, /* attrib: Interrupt endpoint */
+ 8, 0, /* maximum packet size */
+ USB_CFG_INTR_POLL_INTERVAL, /* in ms */
+#endif
+
+ /*
+ * Mouse interface
+ */
+ /* Interface descriptor */
+ 9, /* sizeof(usbDescrInterface): length of descriptor in bytes */
+ USBDESCR_INTERFACE, /* descriptor type */
+ 1, /* index of this interface */
+ 0, /* alternate setting for this interface */
+ USB_CFG_HAVE_INTRIN_ENDPOINT3, /* endpoints excl 0: number of endpoint descriptors to follow */
+ 0x03, /* CLASS: HID */
+ 0, /* SUBCLASS: none */
+ 0, /* PROTOCOL: none */
+ 0, /* string index for interface */
+ /* HID descriptor */
+ 9, /* sizeof(usbDescrHID): length of descriptor in bytes */
+ USBDESCR_HID, /* descriptor type: HID */
+ 0x01, 0x01, /* BCD representation of HID version */
+ 0x00, /* target country code */
+ 0x01, /* number of HID Report (or other HID class) Descriptor infos to follow */
+ 0x22, /* descriptor type: report */
+ sizeof(mouse_hid_report), 0, /* total length of report descriptor */
+#if USB_CFG_HAVE_INTRIN_ENDPOINT3 /* endpoint descriptor for endpoint 3 */
+ /* Endpoint descriptor */
+ 7, /* sizeof(usbDescrEndpoint) */
+ USBDESCR_ENDPOINT, /* descriptor type = endpoint */
+ (char)(0x80 | USB_CFG_EP3_NUMBER), /* IN endpoint number 3 */
+ 0x03, /* attrib: Interrupt endpoint */
+ 8, 0, /* maximum packet size */
+ USB_CFG_INTR_POLL_INTERVAL, /* in ms */
+#endif
+};
+#endif
+
+
+USB_PUBLIC usbMsgLen_t usbFunctionDescriptor(struct usbRequest *rq)
+{
+ usbMsgLen_t len = 0;
+
+/*
+ debug("usbFunctionDescriptor: ");
+ debug_hex(rq->bmRequestType); debug(" ");
+ debug_hex(rq->bRequest); debug(" ");
+ debug_hex16(rq->wValue.word); debug(" ");
+ debug_hex16(rq->wIndex.word); debug(" ");
+ debug_hex16(rq->wLength.word); debug("\n");
+*/
+ switch (rq->wValue.bytes[1]) {
+#if USB_CFG_DESCR_PROPS_CONFIGURATION
+ case USBDESCR_CONFIG:
+ usbMsgPtr = (unsigned char *)usbDescriptorConfiguration;
+ len = sizeof(usbDescriptorConfiguration);
+ break;
+#endif
+ case USBDESCR_HID:
+ switch (rq->wValue.bytes[0]) {
+ case 0:
+ usbMsgPtr = (unsigned char *)(usbDescriptorConfiguration + 9 + 9);
+ len = 9;
+ break;
+ case 1:
+ usbMsgPtr = (unsigned char *)(usbDescriptorConfiguration + 9 + (9 + 9 + 7) + 9);
+ len = 9;
+ break;
+ }
+ break;
+ case USBDESCR_HID_REPORT:
+ /* interface index */
+ switch (rq->wIndex.word) {
+ case 0:
+ usbMsgPtr = (unsigned char *)keyboard_hid_report;
+ len = sizeof(keyboard_hid_report);
+ break;
+ case 1:
+ usbMsgPtr = (unsigned char *)mouse_hid_report;
+ len = sizeof(mouse_hid_report);
+ break;
+ }
+ break;
+ }
+ //debug("desc len: "); debug_hex(len); debug("\n");
+ return len;
+}
diff --git a/tmk_core/protocol/vusb/vusb.h b/tmk_core/protocol/vusb/vusb.h
new file mode 100644
index 000000000..5accf233b
--- /dev/null
+++ b/tmk_core/protocol/vusb/vusb.h
@@ -0,0 +1,27 @@
+/*
+Copyright 2011 Jun Wako <wakojun@gmail.com>
+
+This program is free software: you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation, either version 2 of the License, or
+(at your option) any later version.
+
+This program is distributed in the hope that it will be useful,
+but WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+GNU General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#ifndef VUSB_H
+#define VUSB_H
+
+#include "host_driver.h"
+
+
+host_driver_t *vusb_driver(void);
+void vusb_transfer_keyboard(void);
+
+#endif