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()
183 #ifdef SLEEP_LED_ENABLE
188 void EVENT_USB_Device_WakeUp()
191 suspend_wakeup_init();
193 #ifdef SLEEP_LED_ENABLE
195 // NOTE: converters may not accept this
196 led_set(host_keyboard_leds());
200 void EVENT_USB_Device_StartOfFrame(void)
205 /** Event handler for the USB_ConfigurationChanged event.
206 * This is fired when the host sets the current configuration of the USB device after enumeration.
208 void EVENT_USB_Device_ConfigurationChanged(void)
210 bool ConfigSuccess = true;
212 /* Setup Keyboard HID Report Endpoints */
213 ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
214 KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
217 /* Setup Mouse HID Report Endpoint */
218 ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
219 MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
222 #ifdef EXTRAKEY_ENABLE
223 /* Setup Extra HID Report Endpoint */
224 ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
225 EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
228 #ifdef CONSOLE_ENABLE
229 /* Setup Console HID Report Endpoints */
230 ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
231 CONSOLE_EPSIZE, ENDPOINT_BANK_DOUBLE);
233 ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
234 CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
239 /* Setup NKRO HID Report Endpoints */
240 ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
241 NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
246 Appendix G: HID Request Support Requirements
248 The following table enumerates the requests that need to be supported by various types of HID class devices.
250 Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
251 ------------------------------------------------------------------------------------------
252 Boot Mouse Required Optional Optional Optional Required Required
253 Non-Boot Mouse Required Optional Optional Optional Optional Optional
254 Boot Keyboard Required Optional Required Required Required Required
255 Non-Boot Keybrd Required Optional Required Required Optional Optional
256 Other Device Required Optional Optional Optional Optional Optional
258 /** Event handler for the USB_ControlRequest event.
259 * This is fired before passing along unhandled control requests to the library for processing internally.
261 void EVENT_USB_Device_ControlRequest(void)
263 uint8_t* ReportData = NULL;
264 uint8_t ReportSize = 0;
266 /* Handle HID Class specific requests */
267 switch (USB_ControlRequest.bRequest)
269 case HID_REQ_GetReport:
270 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
272 Endpoint_ClearSETUP();
275 switch (USB_ControlRequest.wIndex) {
276 case KEYBOARD_INTERFACE:
278 ReportData = (uint8_t*)&keyboard_report_sent;
279 ReportSize = sizeof(keyboard_report_sent);
283 /* Write the report data to the control endpoint */
284 Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
289 case HID_REQ_SetReport:
290 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
294 switch (USB_ControlRequest.wIndex) {
295 case KEYBOARD_INTERFACE:
299 Endpoint_ClearSETUP();
301 while (!(Endpoint_IsOUTReceived())) {
302 if (USB_DeviceState == DEVICE_STATE_Unattached)
305 keyboard_led_stats = Endpoint_Read_8();
308 Endpoint_ClearStatusStage();
316 case HID_REQ_GetProtocol:
317 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
319 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
320 Endpoint_ClearSETUP();
321 while (!(Endpoint_IsINReady()));
322 Endpoint_Write_8(keyboard_protocol);
324 Endpoint_ClearStatusStage();
329 case HID_REQ_SetProtocol:
330 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
332 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
333 Endpoint_ClearSETUP();
334 Endpoint_ClearStatusStage();
336 keyboard_protocol = ((USB_ControlRequest.wValue & 0xFF) != 0x00);
338 keyboard_nkro = !!keyboard_protocol;
345 case HID_REQ_SetIdle:
346 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
348 Endpoint_ClearSETUP();
349 Endpoint_ClearStatusStage();
351 keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
355 case HID_REQ_GetIdle:
356 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
358 Endpoint_ClearSETUP();
359 while (!(Endpoint_IsINReady()));
360 Endpoint_Write_8(keyboard_idle);
362 Endpoint_ClearStatusStage();
369 /*******************************************************************************
371 ******************************************************************************/
372 static uint8_t keyboard_leds(void)
374 return keyboard_led_stats;
377 static void send_keyboard(report_keyboard_t *report)
379 uint8_t timeout = 255;
381 if (USB_DeviceState != DEVICE_STATE_Configured)
384 /* Select the Keyboard Report Endpoint */
387 /* Report protocol - NKRO */
388 Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
390 /* Check if write ready for a polling interval around 1ms */
391 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
392 if (!Endpoint_IsReadWriteAllowed()) return;
394 /* Write Keyboard Report Data */
395 Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
401 Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
403 /* Check if write ready for a polling interval around 10ms */
404 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
405 if (!Endpoint_IsReadWriteAllowed()) return;
407 /* Write Keyboard Report Data */
408 Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
411 /* Finalize the stream transfer to send the last packet */
414 keyboard_report_sent = *report;
417 static void send_mouse(report_mouse_t *report)
420 uint8_t timeout = 255;
422 if (USB_DeviceState != DEVICE_STATE_Configured)
425 /* Select the Mouse Report Endpoint */
426 Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
428 /* Check if write ready for a polling interval around 10ms */
429 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
430 if (!Endpoint_IsReadWriteAllowed()) return;
432 /* Write Mouse Report Data */
433 Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
435 /* Finalize the stream transfer to send the last packet */
440 static void send_system(uint16_t data)
442 uint8_t timeout = 255;
444 if (USB_DeviceState != DEVICE_STATE_Configured)
448 .report_id = REPORT_ID_SYSTEM,
451 Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
453 /* Check if write ready for a polling interval around 10ms */
454 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
455 if (!Endpoint_IsReadWriteAllowed()) return;
457 Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
461 static void send_consumer(uint16_t data)
463 uint8_t timeout = 255;
465 if (USB_DeviceState != DEVICE_STATE_Configured)
469 .report_id = REPORT_ID_CONSUMER,
472 Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
474 /* Check if write ready for a polling interval around 10ms */
475 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
476 if (!Endpoint_IsReadWriteAllowed()) return;
478 Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
483 /*******************************************************************************
485 ******************************************************************************/
486 #ifdef CONSOLE_ENABLE
487 #define SEND_TIMEOUT 5
488 int8_t sendchar(uint8_t c)
490 // Not wait once timeouted.
491 // Because sendchar() is called so many times, waiting each call causes big lag.
492 static bool timeouted = false;
494 if (USB_DeviceState != DEVICE_STATE_Configured)
497 uint8_t ep = Endpoint_GetCurrentEndpoint();
498 Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
499 if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
503 if (timeouted && !Endpoint_IsReadWriteAllowed()) {
509 uint8_t timeout = SEND_TIMEOUT;
510 while (!Endpoint_IsReadWriteAllowed()) {
511 if (USB_DeviceState != DEVICE_STATE_Configured) {
514 if (Endpoint_IsStalled()) {
526 // send when bank is full
527 if (!Endpoint_IsReadWriteAllowed())
530 Endpoint_SelectEndpoint(ep);
533 Endpoint_SelectEndpoint(ep);
537 int8_t sendchar(uint8_t c)
544 /*******************************************************************************
546 ******************************************************************************/
547 static void SetupHardware(void)
549 /* Disable watchdog if enabled by bootloader/fuses */
550 MCUSR &= ~(1 << WDRF);
553 /* Disable clock division */
554 clock_prescale_set(clock_div_1);
556 // Leonardo needs. Without this USB device is not recognized.
562 USB_Device_EnableSOFEvents();
563 print_set_sendchar(sendchar);
566 int main(void) __attribute__ ((weak));
572 /* wait for USB startup & debug output */
573 while (USB_DeviceState != DEVICE_STATE_Configured) {
574 #if defined(INTERRUPT_CONTROL_ENDPOINT)
580 print("USB configured.\n");
584 host_set_driver(&lufa_driver);
585 #ifdef SLEEP_LED_ENABLE
589 print("Keyboard start.\n");
591 while (USB_DeviceState == DEVICE_STATE_Suspended) {
593 suspend_power_down();
594 if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
595 USB_Device_SendRemoteWakeup();
601 #if !defined(INTERRUPT_CONTROL_ENDPOINT)