2 * Copyright 2012 Jun Wako <wakojun@gmail.com>
3 * This file is based on:
4 * LUFA-120219/Demos/Device/Lowlevel/KeyboardMouse
5 * LUFA-120219/Demos/Device/Lowlevel/GenericHID
10 Copyright (C) Dean Camera, 2012.
12 dean [at] fourwalledcubicle [dot] com
17 Copyright 2012 Dean Camera (dean [at] fourwalledcubicle [dot] com)
18 Copyright 2010 Denver Gingerich (denver [at] ossguy [dot] com)
20 Permission to use, copy, modify, distribute, and sell this
21 software and its documentation for any purpose is hereby granted
22 without fee, provided that the above copyright notice appear in
23 all copies and that both that the copyright notice and this
24 permission notice and warranty disclaimer appear in supporting
25 documentation, and that the name of the author not be used in
26 advertising or publicity pertaining to distribution of the
27 software without specific, written prior permission.
29 The author disclaim all warranties with regard to this
30 software, including all implied warranties of merchantability
31 and fitness. In no event shall the author be liable for any
32 special, indirect or consequential damages or any damages
33 whatsoever resulting from loss of use, data or profits, whether
34 in an action of contract, negligence or other tortious action,
35 arising out of or in connection with the use or performance of
41 #include "host_driver.h"
47 #ifdef SLEEP_LED_ENABLE
48 #include "sleep_led.h"
52 #include "descriptor.h"
55 uint8_t keyboard_idle
= 0;
56 uint8_t keyboard_protocol
= 1;
57 static uint8_t keyboard_led_stats
= 0;
59 static report_keyboard_t keyboard_report_sent
;
63 static uint8_t keyboard_leds(void);
64 static void send_keyboard(report_keyboard_t
*report
);
65 static void send_mouse(report_mouse_t
*report
);
66 static void send_system(uint16_t data
);
67 static void send_consumer(uint16_t data
);
68 host_driver_t lufa_driver
= {
77 /*******************************************************************************
79 ******************************************************************************/
81 static void Console_Task(void)
83 /* Device must be connected and configured for the task to run */
84 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
87 uint8_t ep
= Endpoint_GetCurrentEndpoint();
90 // TODO: impl receivechar()/recvchar()
91 Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM
);
93 /* Check to see if a packet has been sent from the host */
94 if (Endpoint_IsOUTReceived())
96 /* Check to see if the packet contains data */
97 if (Endpoint_IsReadWriteAllowed())
99 /* Create a temporary buffer to hold the read in report from the host */
100 uint8_t ConsoleData
[CONSOLE_EPSIZE
];
102 /* Read Console Report Data */
103 Endpoint_Read_Stream_LE(&ConsoleData
, sizeof(ConsoleData
), NULL
);
105 /* Process Console Report Data */
106 //ProcessConsoleHIDReport(ConsoleData);
109 /* Finalize the stream transfer to send the last packet */
115 Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM
);
116 if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
117 Endpoint_SelectEndpoint(ep
);
122 while (Endpoint_IsReadWriteAllowed())
125 // flash senchar packet
126 if (Endpoint_IsINReady()) {
130 Endpoint_SelectEndpoint(ep
);
133 static void Console_Task(void)
139 /*******************************************************************************
141 ******************************************************************************/
143 * Event Order of Plug in:
144 * 0) EVENT_USB_Device_Connect
145 * 1) EVENT_USB_Device_Suspend
146 * 2) EVENT_USB_Device_Reset
147 * 3) EVENT_USB_Device_Wake
149 void EVENT_USB_Device_Connect(void)
152 /* For battery powered device */
153 if (!USB_IsInitialized
) {
156 USB_Device_EnableSOFEvents();
160 void EVENT_USB_Device_Disconnect(void)
163 /* For battery powered device */
164 USB_IsInitialized
= false;
165 /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
166 if (USB_IsInitialized) {
167 USB_Disable(); // Disable all interrupts
168 USB_Controller_Enable();
169 USB_INT_Enable(USB_INT_VBUSTI);
174 void EVENT_USB_Device_Reset(void)
179 void EVENT_USB_Device_Suspend()
182 #ifdef SLEEP_LED_ENABLE
187 void EVENT_USB_Device_WakeUp()
190 suspend_wakeup_init();
192 #ifdef SLEEP_LED_ENABLE
194 // NOTE: converters may not accept this
195 led_set(host_keyboard_leds());
199 #ifdef CONSOLE_ENABLE
200 static bool console_flush
= false;
201 #define CONSOLE_FLUSH_SET(b) do { \
202 uint8_t sreg = SREG; cli(); console_flush = b; SREG = sreg; \
206 void EVENT_USB_Device_StartOfFrame(void)
208 static uint8_t count
;
209 if (++count
% 50) return;
212 if (!console_flush
) return;
214 console_flush
= false;
218 /** Event handler for the USB_ConfigurationChanged event.
219 * This is fired when the host sets the current configuration of the USB device after enumeration.
221 void EVENT_USB_Device_ConfigurationChanged(void)
223 bool ConfigSuccess
= true;
225 /* Setup Keyboard HID Report Endpoints */
226 ConfigSuccess
&= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
227 KEYBOARD_EPSIZE
, ENDPOINT_BANK_SINGLE
);
230 /* Setup Mouse HID Report Endpoint */
231 ConfigSuccess
&= ENDPOINT_CONFIG(MOUSE_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
232 MOUSE_EPSIZE
, ENDPOINT_BANK_SINGLE
);
235 #ifdef EXTRAKEY_ENABLE
236 /* Setup Extra HID Report Endpoint */
237 ConfigSuccess
&= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
238 EXTRAKEY_EPSIZE
, ENDPOINT_BANK_SINGLE
);
241 #ifdef CONSOLE_ENABLE
242 /* Setup Console HID Report Endpoints */
243 ConfigSuccess
&= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
244 CONSOLE_EPSIZE
, ENDPOINT_BANK_DOUBLE
);
246 ConfigSuccess
&= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_OUT
,
247 CONSOLE_EPSIZE
, ENDPOINT_BANK_SINGLE
);
252 /* Setup NKRO HID Report Endpoints */
253 ConfigSuccess
&= ENDPOINT_CONFIG(NKRO_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
254 NKRO_EPSIZE
, ENDPOINT_BANK_SINGLE
);
259 Appendix G: HID Request Support Requirements
261 The following table enumerates the requests that need to be supported by various types of HID class devices.
263 Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
264 ------------------------------------------------------------------------------------------
265 Boot Mouse Required Optional Optional Optional Required Required
266 Non-Boot Mouse Required Optional Optional Optional Optional Optional
267 Boot Keyboard Required Optional Required Required Required Required
268 Non-Boot Keybrd Required Optional Required Required Optional Optional
269 Other Device Required Optional Optional Optional Optional Optional
271 /** Event handler for the USB_ControlRequest event.
272 * This is fired before passing along unhandled control requests to the library for processing internally.
274 void EVENT_USB_Device_ControlRequest(void)
276 uint8_t* ReportData
= NULL
;
277 uint8_t ReportSize
= 0;
279 /* Handle HID Class specific requests */
280 switch (USB_ControlRequest
.bRequest
)
282 case HID_REQ_GetReport
:
283 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
285 Endpoint_ClearSETUP();
288 switch (USB_ControlRequest
.wIndex
) {
289 case KEYBOARD_INTERFACE
:
291 ReportData
= (uint8_t*)&keyboard_report_sent
;
292 ReportSize
= sizeof(keyboard_report_sent
);
296 /* Write the report data to the control endpoint */
297 Endpoint_Write_Control_Stream_LE(ReportData
, ReportSize
);
302 case HID_REQ_SetReport
:
303 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
307 switch (USB_ControlRequest
.wIndex
) {
308 case KEYBOARD_INTERFACE
:
312 Endpoint_ClearSETUP();
314 while (!(Endpoint_IsOUTReceived())) {
315 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
318 keyboard_led_stats
= Endpoint_Read_8();
321 Endpoint_ClearStatusStage();
329 case HID_REQ_GetProtocol
:
330 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
332 if (USB_ControlRequest
.wIndex
== KEYBOARD_INTERFACE
) {
333 Endpoint_ClearSETUP();
334 while (!(Endpoint_IsINReady()));
335 Endpoint_Write_8(keyboard_protocol
);
337 Endpoint_ClearStatusStage();
342 case HID_REQ_SetProtocol
:
343 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
345 if (USB_ControlRequest
.wIndex
== KEYBOARD_INTERFACE
) {
346 Endpoint_ClearSETUP();
347 Endpoint_ClearStatusStage();
349 keyboard_protocol
= ((USB_ControlRequest
.wValue
& 0xFF) != 0x00);
351 keyboard_nkro
= !!keyboard_protocol
;
358 case HID_REQ_SetIdle
:
359 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
361 Endpoint_ClearSETUP();
362 Endpoint_ClearStatusStage();
364 keyboard_idle
= ((USB_ControlRequest
.wValue
& 0xFF00) >> 8);
368 case HID_REQ_GetIdle
:
369 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
371 Endpoint_ClearSETUP();
372 while (!(Endpoint_IsINReady()));
373 Endpoint_Write_8(keyboard_idle
);
375 Endpoint_ClearStatusStage();
382 /*******************************************************************************
384 ******************************************************************************/
385 static uint8_t keyboard_leds(void)
387 return keyboard_led_stats
;
390 static void send_keyboard(report_keyboard_t
*report
)
392 uint8_t timeout
= 255;
394 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
397 /* Select the Keyboard Report Endpoint */
400 /* Report protocol - NKRO */
401 Endpoint_SelectEndpoint(NKRO_IN_EPNUM
);
403 /* Check if write ready for a polling interval around 1ms */
404 while (timeout
-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
405 if (!Endpoint_IsReadWriteAllowed()) return;
407 /* Write Keyboard Report Data */
408 Endpoint_Write_Stream_LE(report
, NKRO_EPSIZE
, NULL
);
414 Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM
);
416 /* Check if write ready for a polling interval around 10ms */
417 while (timeout
-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
418 if (!Endpoint_IsReadWriteAllowed()) return;
420 /* Write Keyboard Report Data */
421 Endpoint_Write_Stream_LE(report
, KEYBOARD_EPSIZE
, NULL
);
424 /* Finalize the stream transfer to send the last packet */
427 keyboard_report_sent
= *report
;
430 static void send_mouse(report_mouse_t
*report
)
433 uint8_t timeout
= 255;
435 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
438 /* Select the Mouse Report Endpoint */
439 Endpoint_SelectEndpoint(MOUSE_IN_EPNUM
);
441 /* Check if write ready for a polling interval around 10ms */
442 while (timeout
-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
443 if (!Endpoint_IsReadWriteAllowed()) return;
445 /* Write Mouse Report Data */
446 Endpoint_Write_Stream_LE(report
, sizeof(report_mouse_t
), NULL
);
448 /* Finalize the stream transfer to send the last packet */
453 static void send_system(uint16_t data
)
455 uint8_t timeout
= 255;
457 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
461 .report_id
= REPORT_ID_SYSTEM
,
464 Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM
);
466 /* Check if write ready for a polling interval around 10ms */
467 while (timeout
-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
468 if (!Endpoint_IsReadWriteAllowed()) return;
470 Endpoint_Write_Stream_LE(&r
, sizeof(report_extra_t
), NULL
);
474 static void send_consumer(uint16_t data
)
476 uint8_t timeout
= 255;
478 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
482 .report_id
= REPORT_ID_CONSUMER
,
485 Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM
);
487 /* Check if write ready for a polling interval around 10ms */
488 while (timeout
-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
489 if (!Endpoint_IsReadWriteAllowed()) return;
491 Endpoint_Write_Stream_LE(&r
, sizeof(report_extra_t
), NULL
);
496 /*******************************************************************************
498 ******************************************************************************/
499 #ifdef CONSOLE_ENABLE
500 #define SEND_TIMEOUT 5
501 int8_t sendchar(uint8_t c
)
503 // Not wait once timeouted.
504 // Because sendchar() is called so many times, waiting each call causes big lag.
505 static bool timeouted
= false;
507 // prevents Console_Task() from running during sendchar() runs.
508 // or char will be lost. These two function is mutually exclusive.
509 CONSOLE_FLUSH_SET(false);
511 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
514 uint8_t ep
= Endpoint_GetCurrentEndpoint();
515 Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM
);
516 if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
520 if (timeouted
&& !Endpoint_IsReadWriteAllowed()) {
526 uint8_t timeout
= SEND_TIMEOUT
;
527 while (!Endpoint_IsReadWriteAllowed()) {
528 if (USB_DeviceState
!= DEVICE_STATE_Configured
) {
531 if (Endpoint_IsStalled()) {
543 // send when bank is full
544 if (!Endpoint_IsReadWriteAllowed()) {
545 while (!(Endpoint_IsINReady()));
548 CONSOLE_FLUSH_SET(true);
551 Endpoint_SelectEndpoint(ep
);
554 Endpoint_SelectEndpoint(ep
);
558 int8_t sendchar(uint8_t c
)
565 /*******************************************************************************
567 ******************************************************************************/
568 static void setup_mcu(void)
570 /* Disable watchdog if enabled by bootloader/fuses */
571 MCUSR
&= ~(1 << WDRF
);
574 /* Disable clock division */
575 clock_prescale_set(clock_div_1
);
578 static void setup_usb(void)
580 // Leonardo needs. Without this USB device is not recognized.
586 USB_Device_EnableSOFEvents();
587 print_set_sendchar(sendchar
);
590 int main(void) __attribute__ ((weak
));
598 /* wait for USB startup & debug output */
599 while (USB_DeviceState
!= DEVICE_STATE_Configured
) {
600 #if defined(INTERRUPT_CONTROL_ENDPOINT)
606 print("USB configured.\n");
610 host_set_driver(&lufa_driver
);
611 #ifdef SLEEP_LED_ENABLE
615 print("Keyboard start.\n");
617 while (USB_DeviceState
== DEVICE_STATE_Suspended
) {
619 suspend_power_down();
620 if (USB_Device_RemoteWakeupEnabled
&& suspend_wakeup_condition()) {
621 USB_Device_SendRemoteWakeup();
627 #if !defined(INTERRUPT_CONTROL_ENDPOINT)