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 /* 0: Boot Protocol, 1: Report Protocol(default) */
57 uint8_t keyboard_protocol = 1;
58 static uint8_t keyboard_led_stats = 0;
60 static report_keyboard_t keyboard_report_sent;
64 static uint8_t keyboard_leds(void);
65 static void send_keyboard(report_keyboard_t *report);
66 static void send_mouse(report_mouse_t *report);
67 static void send_system(uint16_t data);
68 static void send_consumer(uint16_t data);
69 host_driver_t lufa_driver = {
78 /*******************************************************************************
80 ******************************************************************************/
82 static void Console_Task(void)
84 /* Device must be connected and configured for the task to run */
85 if (USB_DeviceState != DEVICE_STATE_Configured)
88 uint8_t ep = Endpoint_GetCurrentEndpoint();
91 // TODO: impl receivechar()/recvchar()
92 Endpoint_SelectEndpoint(CONSOLE_OUT_EPNUM);
94 /* Check to see if a packet has been sent from the host */
95 if (Endpoint_IsOUTReceived())
97 /* Check to see if the packet contains data */
98 if (Endpoint_IsReadWriteAllowed())
100 /* Create a temporary buffer to hold the read in report from the host */
101 uint8_t ConsoleData[CONSOLE_EPSIZE];
103 /* Read Console Report Data */
104 Endpoint_Read_Stream_LE(&ConsoleData, sizeof(ConsoleData), NULL);
106 /* Process Console Report Data */
107 //ProcessConsoleHIDReport(ConsoleData);
110 /* Finalize the stream transfer to send the last packet */
116 Endpoint_SelectEndpoint(CONSOLE_IN_EPNUM);
117 if (!Endpoint_IsEnabled() || !Endpoint_IsConfigured()) {
118 Endpoint_SelectEndpoint(ep);
123 while (Endpoint_IsReadWriteAllowed())
126 // flash senchar packet
127 if (Endpoint_IsINReady()) {
131 Endpoint_SelectEndpoint(ep);
134 static void Console_Task(void)
140 /*******************************************************************************
142 ******************************************************************************/
144 * Event Order of Plug in:
145 * 0) EVENT_USB_Device_Connect
146 * 1) EVENT_USB_Device_Suspend
147 * 2) EVENT_USB_Device_Reset
148 * 3) EVENT_USB_Device_Wake
150 void EVENT_USB_Device_Connect(void)
153 /* For battery powered device */
154 if (!USB_IsInitialized) {
157 USB_Device_EnableSOFEvents();
161 void EVENT_USB_Device_Disconnect(void)
164 /* For battery powered device */
165 USB_IsInitialized = false;
166 /* TODO: This doesn't work. After several plug in/outs can not be enumerated.
167 if (USB_IsInitialized) {
168 USB_Disable(); // Disable all interrupts
169 USB_Controller_Enable();
170 USB_INT_Enable(USB_INT_VBUSTI);
175 void EVENT_USB_Device_Reset(void)
180 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 * ATMega32u2 supports dual bank(ping-pong mode) only on endpoint 3 and 4,
223 * it is safe to use singl bank for all endpoints.
225 void EVENT_USB_Device_ConfigurationChanged(void)
227 bool ConfigSuccess = true;
229 /* Setup Keyboard HID Report Endpoints */
230 ConfigSuccess &= ENDPOINT_CONFIG(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
231 KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
234 /* Setup Mouse HID Report Endpoint */
235 ConfigSuccess &= ENDPOINT_CONFIG(MOUSE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
236 MOUSE_EPSIZE, ENDPOINT_BANK_SINGLE);
239 #ifdef EXTRAKEY_ENABLE
240 /* Setup Extra HID Report Endpoint */
241 ConfigSuccess &= ENDPOINT_CONFIG(EXTRAKEY_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
242 EXTRAKEY_EPSIZE, ENDPOINT_BANK_SINGLE);
245 #ifdef CONSOLE_ENABLE
246 /* Setup Console HID Report Endpoints */
247 ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
248 CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
250 ConfigSuccess &= ENDPOINT_CONFIG(CONSOLE_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
251 CONSOLE_EPSIZE, ENDPOINT_BANK_SINGLE);
256 /* Setup NKRO HID Report Endpoints */
257 ConfigSuccess &= ENDPOINT_CONFIG(NKRO_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
258 NKRO_EPSIZE, ENDPOINT_BANK_SINGLE);
263 Appendix G: HID Request Support Requirements
265 The following table enumerates the requests that need to be supported by various types of HID class devices.
267 Device type GetReport SetReport GetIdle SetIdle GetProtocol SetProtocol
268 ------------------------------------------------------------------------------------------
269 Boot Mouse Required Optional Optional Optional Required Required
270 Non-Boot Mouse Required Optional Optional Optional Optional Optional
271 Boot Keyboard Required Optional Required Required Required Required
272 Non-Boot Keybrd Required Optional Required Required Optional Optional
273 Other Device Required Optional Optional Optional Optional Optional
275 /** Event handler for the USB_ControlRequest event.
276 * This is fired before passing along unhandled control requests to the library for processing internally.
278 void EVENT_USB_Device_ControlRequest(void)
280 uint8_t* ReportData = NULL;
281 uint8_t ReportSize = 0;
283 /* Handle HID Class specific requests */
284 switch (USB_ControlRequest.bRequest)
286 case HID_REQ_GetReport:
287 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
289 Endpoint_ClearSETUP();
292 switch (USB_ControlRequest.wIndex) {
293 case KEYBOARD_INTERFACE:
295 ReportData = (uint8_t*)&keyboard_report_sent;
296 ReportSize = sizeof(keyboard_report_sent);
300 /* Write the report data to the control endpoint */
301 Endpoint_Write_Control_Stream_LE(ReportData, ReportSize);
306 case HID_REQ_SetReport:
307 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
311 switch (USB_ControlRequest.wIndex) {
312 case KEYBOARD_INTERFACE:
316 Endpoint_ClearSETUP();
318 while (!(Endpoint_IsOUTReceived())) {
319 if (USB_DeviceState == DEVICE_STATE_Unattached)
322 keyboard_led_stats = Endpoint_Read_8();
325 Endpoint_ClearStatusStage();
333 case HID_REQ_GetProtocol:
334 if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
336 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
337 Endpoint_ClearSETUP();
338 while (!(Endpoint_IsINReady()));
339 Endpoint_Write_8(keyboard_protocol);
341 Endpoint_ClearStatusStage();
346 case HID_REQ_SetProtocol:
347 if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
349 if (USB_ControlRequest.wIndex == KEYBOARD_INTERFACE) {
350 Endpoint_ClearSETUP();
351 Endpoint_ClearStatusStage();
353 keyboard_protocol = (USB_ControlRequest.wValue & 0xFF);
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 */
400 if (keyboard_protocol && keyboard_nkro) {
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)