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"
53 #ifdef LUFA_DEBUG_SUART
54 #include "avr/suart.h"
57 #include "descriptor.h"
60 uint8_t keyboard_idle
= 0;
61 /* 0: Boot Protocol, 1: Report Protocol(default) */
62 uint8_t keyboard_protocol
= 1;
63 static uint8_t keyboard_led_stats
= 0;
65 static report_keyboard_t keyboard_report_sent
;
69 static uint8_t keyboard_leds(void);
70 static void send_keyboard(report_keyboard_t
*report
);
71 static void send_mouse(report_mouse_t
*report
);
72 static void send_system(uint16_t data
);
73 static void send_consumer(uint16_t data
);
74 host_driver_t lufa_driver
= {
83 /*******************************************************************************
85 ******************************************************************************/
87 static void Console_Task(void)
89 /* Device must be connected and configured for the task to run */
90 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
93 uint8_t ep
= Endpoint_GetCurrentEndpoint();
96 // TODO: impl receivechar()/recvchar()
97 Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM
);
99 /* Check to see if a packet has been sent from the host */
100 if (Endpoint_IsOUTReceived())
102 /* Check to see if the packet contains data */
103 if (Endpoint_IsReadWriteAllowed())
105 /* Create a temporary buffer to hold the read in report from the host */
106 uint8_t ConsoleData
[CONSOLE_EPSIZE
];
108 /* Read Console Report Data */
109 Endpoint_Read_Stream_LE(&ConsoleData
, sizeof(ConsoleData
), NULL
);
111 /* Process Console Report Data */
112 //ProcessConsoleHIDReport(ConsoleData);
115 /* Finalize the stream transfer to send the last packet */
121 Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM
);
122 if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
123 Endpoint_SelectEndpoint(ep
);
128 while (Endpoint_IsReadWriteAllowed())
131 // flash senchar packet
132 if (Endpoint_IsINReady()) {
136 Endpoint_SelectEndpoint(ep
);
139 static void Console_Task(void)
145 /*******************************************************************************
147 ******************************************************************************/
149 * Event Order of Plug in:
150 * 0) EVENT_USB_Device_Connect
151 * 1) EVENT_USB_Device_Suspend
152 * 2) EVENT_USB_Device_Reset
153 * 3) EVENT_USB_Device_Wake
155 void EVENT_USB_Device_Connect(void)
158 /* For battery powered device */
159 if (!USB_IsInitialized
) {
162 USB_Device_EnableSOFEvents();
166 void EVENT_USB_Device_Disconnect(void)
169 /* For battery powered device */
170 USB_IsInitialized
= false;
171 /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
172 if (USB_IsInitialized) {
173 USB_Disable(); // Disable all interrupts
174 USB_Controller_Enable();
175 USB_INT_Enable(USB_INT_VBUSTI);
180 void EVENT_USB_Device_Reset(void)
185 void EVENT_USB_Device_Suspend()
188 hook_usb_suspend_entry();
191 void EVENT_USB_Device_WakeUp()
197 #ifdef CONSOLE_ENABLE
198 static bool console_flush
= false;
199 #define CONSOLE_FLUSH_SET(b) do { \
200 uint8_t sreg = SREG; cli(); console_flush = b; SREG = sreg; \
204 void EVENT_USB_Device_StartOfFrame(void)
206 static uint8_t count
;
207 if (++count
% 50) return;
210 if (!console_flush
) return;
212 console_flush
= false;
216 /** Event handler for the USB_ConfigurationChanged event.
217 * This is fired when the host sets the current configuration of the USB device after enumeration.
219 * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
220 * it is safe to use singl bank for all endpoints.
222 void EVENT_USB_Device_ConfigurationChanged(void)
225 bool ConfigSuccess
= true;
227 /* Setup Keyboard HID Report Endpoints */
228 ConfigSuccess
&= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
229 KEYBOARD_EPSIZE
, ENDPOINT_BANK_SINGLE
);
232 /* Setup Mouse HID Report Endpoint */
233 ConfigSuccess
&= ENDPOINT_CONFIG(MOUSE_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
234 MOUSE_EPSIZE
, ENDPOINT_BANK_SINGLE
);
237 #ifdef EXTRAKEY_ENABLE
238 /* Setup Extra HID Report Endpoint */
239 ConfigSuccess
&= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
240 EXTRAKEY_EPSIZE
, ENDPOINT_BANK_SINGLE
);
243 #ifdef CONSOLE_ENABLE
244 /* Setup Console HID Report Endpoints */
245 ConfigSuccess
&= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
246 CONSOLE_EPSIZE
, ENDPOINT_BANK_SINGLE
);
248 ConfigSuccess
&= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_OUT
,
249 CONSOLE_EPSIZE
, ENDPOINT_BANK_SINGLE
);
254 /* Setup NKRO HID Report Endpoints */
255 ConfigSuccess
&= ENDPOINT_CONFIG(NKRO_IN_EPNUM
, EP_TYPE_INTERRUPT
, ENDPOINT_DIR_IN
,
256 NKRO_EPSIZE
, ENDPOINT_BANK_SINGLE
);
261 Appendix G: HID Request Support Requirements
263 The following table enumerates the requests that need to be supported by various types of HID class devices.
265 Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
266 ------------------------------------------------------------------------------------------
267 Boot Mouse Required Optional Optional Optional Required Required
268 Non-Boot Mouse Required Optional Optional Optional Optional Optional
269 Boot Keyboard Required Optional Required Required Required Required
270 Non-Boot Keybrd Required Optional Required Required Optional Optional
271 Other Device Required Optional Optional Optional Optional Optional
273 /** Event handler for the USB_ControlRequest event.
274 * This is fired before passing along unhandled control requests to the library for processing internally.
276 void EVENT_USB_Device_ControlRequest(void)
279 uint8_t* ReportData
= NULL
;
280 uint8_t ReportSize
= 0;
282 /* Handle HID Class specific requests */
283 switch (USB_ControlRequest
.bRequest
)
285 case HID_REQ_GetReport
:
286 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
288 Endpoint_ClearSETUP();
291 switch (USB_ControlRequest
.wIndex
) {
292 case KEYBOARD_INTERFACE
:
294 ReportData
= (uint8_t*)&keyboard_report_sent
;
295 ReportSize
= sizeof(keyboard_report_sent
);
299 /* Write the report data to the control endpoint */
300 Endpoint_Write_Control_Stream_LE(ReportData
, ReportSize
);
305 case HID_REQ_SetReport
:
306 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
310 switch (USB_ControlRequest
.wIndex
) {
311 case KEYBOARD_INTERFACE
:
315 Endpoint_ClearSETUP();
317 while (!(Endpoint_IsOUTReceived())) {
318 if (USB_DeviceState
== DEVICE_STATE_Unattached
)
321 keyboard_led_stats
= Endpoint_Read_8();
324 Endpoint_ClearStatusStage();
332 case HID_REQ_GetProtocol
:
333 if (USB_ControlRequest
.bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
335 if (USB_ControlRequest
.wIndex
== KEYBOARD_INTERFACE
) {
336 Endpoint_ClearSETUP();
337 while (!(Endpoint_IsINReady()));
338 Endpoint_Write_8(keyboard_protocol
);
340 Endpoint_ClearStatusStage();
345 case HID_REQ_SetProtocol
:
346 if (USB_ControlRequest
.bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
348 if (USB_ControlRequest
.wIndex
== KEYBOARD_INTERFACE
) {
349 Endpoint_ClearSETUP();
350 Endpoint_ClearStatusStage();
352 keyboard_protocol
= (USB_ControlRequest
.wValue
& 0xFF);
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 */
399 if (keyboard_protocol
&& keyboard_nkro
) {
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 #ifdef LUFA_DEBUG_SUART
506 // Not wait once timeouted.
507 // Because sendchar() is called so many times, waiting each call causes big lag.
508 static bool timeouted
= false;
510 // prevents Console_Task() from running during sendchar() runs.
511 // or char will be lost. These two function is mutually exclusive.
512 CONSOLE_FLUSH_SET(false);
514 if (USB_DeviceState
!= DEVICE_STATE_Configured
)
517 uint8_t ep
= Endpoint_GetCurrentEndpoint();
518 Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM
);
519 if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
523 if (timeouted
&& !Endpoint_IsReadWriteAllowed()) {
529 uint8_t timeout
= SEND_TIMEOUT
;
530 while (!Endpoint_IsReadWriteAllowed()) {
531 if (USB_DeviceState
!= DEVICE_STATE_Configured
) {
534 if (Endpoint_IsStalled()) {
546 // send when bank is full
547 if (!Endpoint_IsReadWriteAllowed()) {
548 while (!(Endpoint_IsINReady()));
551 CONSOLE_FLUSH_SET(true);
554 Endpoint_SelectEndpoint(ep
);
557 Endpoint_SelectEndpoint(ep
);
561 int8_t sendchar(uint8_t c
)
563 #ifdef LUFA_DEBUG_SUART
571 /*******************************************************************************
573 ******************************************************************************/
574 static void setup_mcu(void)
576 /* Disable watchdog if enabled by bootloader/fuses */
577 MCUSR
&= ~(1 << WDRF
);
580 /* Disable clock division */
581 clock_prescale_set(clock_div_1
);
584 static void setup_usb(void)
586 // Leonardo needs. Without this USB device is not recognized.
592 USB_Device_EnableSOFEvents();
595 int main(void) __attribute__ ((weak
));
598 #ifdef LUFA_DEBUG_SUART
599 DDRD
|= (1<<SUART_OUT_BIT
);
601 print_set_sendchar(sendchar
);
608 /* wait for USB startup & debug output */
609 while (USB_DeviceState
!= DEVICE_STATE_Configured
) {
610 #if defined(INTERRUPT_CONTROL_ENDPOINT)
616 print("USB configured.\n");
620 host_set_driver(&lufa_driver
);
621 #ifdef SLEEP_LED_ENABLE
625 print("Keyboard start.\n");
628 while (USB_DeviceState
== DEVICE_STATE_Suspended
) {
630 hook_usb_suspend_loop();
635 #if !defined(INTERRUPT_CONTROL_ENDPOINT)
643 __attribute__((weak
))
644 void hook_early_init(void) {}
646 __attribute__((weak
))
647 void hook_late_init(void) {}
649 __attribute__((weak
))
650 void hook_usb_suspend_entry(void)
652 #ifdef SLEEP_LED_ENABLE
657 __attribute__((weak
))
658 void hook_usb_suspend_loop(void)
660 suspend_power_down();
661 if (USB_Device_RemoteWakeupEnabled
&& suspend_wakeup_condition()) {
662 USB_Device_SendRemoteWakeup();
666 __attribute__((weak
))
667 void hook_usb_wakeup(void)
669 suspend_wakeup_init();
670 #ifdef SLEEP_LED_ENABLE
672 // NOTE: converters may not accept this
673 led_set(host_keyboard_leds());