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 #ifdef CONSOLE_ENABLE
201 static bool console_flush = false;
202 #define CONSOLE_FLUSH_SET(b) do { \
203 uint8_t sreg = SREG; cli(); console_flush = b; SREG = sreg; \
207 void EVENT_USB_Device_StartOfFrame(void)
209 static uint8_t count;
210 if (++count % 50) return;
213 if (!console_flush) return;
215 console_flush = false;
219 /** Event handler for the USB_ConfigurationChanged event.
220 * This is fired when the host sets the current configuration of the USB device after enumeration.
222 void EVENT_USB_Device_ConfigurationChanged(void)
224 bool ConfigSuccess = true;
226 /* Setup Keyboard HID Report Endpoints */
227 ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
228 KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
231 /* Setup Mouse HID Report Endpoint */
232 ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
233 MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
236 #ifdef EXTRAKEY_ENABLE
237 /* Setup Extra HID Report Endpoint */
238 ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
239 EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
242 #ifdef CONSOLE_ENABLE
243 /* Setup Console HID Report Endpoints */
244 ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
245 CONSOLE_EPSIZE, ENDPOINT_BANK_DOUBLE);
247 ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
248 CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
253 /* Setup NKRO HID Report Endpoints */
254 ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
255 NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
260 Appendix G: HID Request Support Requirements
262 The following table enumerates the requests that need to be supported by various types of HID class devices.
264 Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
265 ------------------------------------------------------------------------------------------
266 Boot Mouse Required Optional Optional Optional Required Required
267 Non-Boot Mouse Required Optional Optional Optional Optional Optional
268 Boot Keyboard Required Optional Required Required Required Required
269 Non-Boot Keybrd Required Optional Required Required Optional Optional
270 Other Device Required Optional Optional Optional Optional Optional
272 /** Event handler for the USB_ControlRequest event.
273 * This is fired before passing along unhandled control requests to the library for processing internally.
275 void EVENT_USB_Device_ControlRequest(void)
277 uint8_t* ReportData = NULL;
278 uint8_t ReportSize = 0;
280 /* Handle HID Class specific requests */
281 switch (USB_ControlRequest.bRequest)
283 case HID_REQ_GetReport:
284 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
286 Endpoint_ClearSETUP();
289 switch (USB_ControlRequest.wIndex) {
290 case KEYBOARD_INTERFACE:
292 ReportData = (uint8_t*)&keyboard_report_sent;
293 ReportSize = sizeof(keyboard_report_sent);
297 /* Write the report data to the control endpoint */
298 Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
303 case HID_REQ_SetReport:
304 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
308 switch (USB_ControlRequest.wIndex) {
309 case KEYBOARD_INTERFACE:
313 Endpoint_ClearSETUP();
315 while (!(Endpoint_IsOUTReceived())) {
316 if (USB_DeviceState == DEVICE_STATE_Unattached)
319 keyboard_led_stats = Endpoint_Read_8();
322 Endpoint_ClearStatusStage();
330 case HID_REQ_GetProtocol:
331 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
333 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
334 Endpoint_ClearSETUP();
335 while (!(Endpoint_IsINReady()));
336 Endpoint_Write_8(keyboard_protocol);
338 Endpoint_ClearStatusStage();
343 case HID_REQ_SetProtocol:
344 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
346 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
347 Endpoint_ClearSETUP();
348 Endpoint_ClearStatusStage();
350 keyboard_protocol = ((USB_ControlRequest.wValue & 0xFF) != 0x00);
352 keyboard_nkro = !!keyboard_protocol;
359 case HID_REQ_SetIdle:
360 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
362 Endpoint_ClearSETUP();
363 Endpoint_ClearStatusStage();
365 keyboard_idle = ((USB_ControlRequest.wValue & 0xFF00) >> 8);
369 case HID_REQ_GetIdle:
370 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
372 Endpoint_ClearSETUP();
373 while (!(Endpoint_IsINReady()));
374 Endpoint_Write_8(keyboard_idle);
376 Endpoint_ClearStatusStage();
383 /*******************************************************************************
385 ******************************************************************************/
386 static uint8_t keyboard_leds(void)
388 return keyboard_led_stats;
391 static void send_keyboard(report_keyboard_t *report)
393 uint8_t timeout = 255;
395 if (USB_DeviceState != DEVICE_STATE_Configured)
398 /* Select the Keyboard Report Endpoint */
401 /* Report protocol - NKRO */
402 Endpoint_SelectEndpoint(NKRO_IN_EPNUM);
404 /* Check if write ready for a polling interval around 1ms */
405 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(4);
406 if (!Endpoint_IsReadWriteAllowed()) return;
408 /* Write Keyboard Report Data */
409 Endpoint_Write_Stream_LE(report, NKRO_EPSIZE, NULL);
415 Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
417 /* Check if write ready for a polling interval around 10ms */
418 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
419 if (!Endpoint_IsReadWriteAllowed()) return;
421 /* Write Keyboard Report Data */
422 Endpoint_Write_Stream_LE(report, KEYBOARD_EPSIZE, NULL);
425 /* Finalize the stream transfer to send the last packet */
428 keyboard_report_sent = *report;
431 static void send_mouse(report_mouse_t *report)
434 uint8_t timeout = 255;
436 if (USB_DeviceState != DEVICE_STATE_Configured)
439 /* Select the Mouse Report Endpoint */
440 Endpoint_SelectEndpoint(MOUSE_IN_EPNUM);
442 /* Check if write ready for a polling interval around 10ms */
443 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
444 if (!Endpoint_IsReadWriteAllowed()) return;
446 /* Write Mouse Report Data */
447 Endpoint_Write_Stream_LE(report, sizeof(report_mouse_t), NULL);
449 /* Finalize the stream transfer to send the last packet */
454 static void send_system(uint16_t data)
456 uint8_t timeout = 255;
458 if (USB_DeviceState != DEVICE_STATE_Configured)
462 .report_id = REPORT_ID_SYSTEM,
465 Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
467 /* Check if write ready for a polling interval around 10ms */
468 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
469 if (!Endpoint_IsReadWriteAllowed()) return;
471 Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
475 static void send_consumer(uint16_t data)
477 uint8_t timeout = 255;
479 if (USB_DeviceState != DEVICE_STATE_Configured)
483 .report_id = REPORT_ID_CONSUMER,
486 Endpoint_SelectEndpoint(EXTRAKEY_IN_EPNUM);
488 /* Check if write ready for a polling interval around 10ms */
489 while (timeout-- && !Endpoint_IsReadWriteAllowed()) _delay_us(40);
490 if (!Endpoint_IsReadWriteAllowed()) return;
492 Endpoint_Write_Stream_LE(&r, sizeof(report_extra_t), NULL);
497 /*******************************************************************************
499 ******************************************************************************/
500 #ifdef CONSOLE_ENABLE
501 #define SEND_TIMEOUT 5
502 int8_t sendchar(uint8_t c)
504 // Not wait once timeouted.
505 // Because sendchar() is called so many times, waiting each call causes big lag.
506 static bool timeouted = false;
508 // prevents Console_Task() from running during sendchar() runs.
509 // or char will be lost. These two function is mutually exclusive.
510 CONSOLE_FLUSH_SET(false);
512 if (USB_DeviceState != DEVICE_STATE_Configured)
515 uint8_t ep = Endpoint_GetCurrentEndpoint();
516 Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
517 if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
521 if (timeouted && !Endpoint_IsReadWriteAllowed()) {
527 uint8_t timeout = SEND_TIMEOUT;
528 while (!Endpoint_IsReadWriteAllowed()) {
529 if (USB_DeviceState != DEVICE_STATE_Configured) {
532 if (Endpoint_IsStalled()) {
544 // send when bank is full
545 if (!Endpoint_IsReadWriteAllowed()) {
546 while (!(Endpoint_IsINReady()));
549 CONSOLE_FLUSH_SET(true);
552 Endpoint_SelectEndpoint(ep);
555 Endpoint_SelectEndpoint(ep);
559 int8_t sendchar(uint8_t c)
566 /*******************************************************************************
568 ******************************************************************************/
569 static void setup_mcu(void)
571 /* Disable watchdog if enabled by bootloader/fuses */
572 MCUSR &= ~(1 << WDRF);
575 /* Disable clock division */
576 clock_prescale_set(clock_div_1);
579 static void setup_usb(void)
581 // Leonardo needs. Without this USB device is not recognized.
587 USB_Device_EnableSOFEvents();
588 print_set_sendchar(sendchar);
591 int main(void) __attribute__ ((weak));
599 /* wait for USB startup & debug output */
600 while (USB_DeviceState != DEVICE_STATE_Configured) {
601 #if defined(INTERRUPT_CONTROL_ENDPOINT)
607 print("USB configured.\n");
611 host_set_driver(&lufa_driver);
612 #ifdef SLEEP_LED_ENABLE
616 print("Keyboard start.\n");
618 while (USB_DeviceState == DEVICE_STATE_Suspended) {
620 suspend_power_down();
621 if (USB_Device_RemoteWakeupEnabled && suspend_wakeup_condition()) {
622 USB_Device_SendRemoteWakeup();
628 #if !defined(INTERRUPT_CONTROL_ENDPOINT)