3      Copyright (C) Dean Camera, 2009. 
   5   dean [at] fourwalledcubicle [dot] com 
   6       www.fourwalledcubicle.com 
  10   Copyright 2009  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  12   Permission to use, copy, modify, and distribute this software 
  13   and its documentation for any purpose and without fee is hereby 
  14   granted, provided that the above copyright notice appear in all 
  15   copies and that both that the copyright notice and this 
  16   permission notice and warranty disclaimer appear in supporting 
  17   documentation, and that the name of the author not be used in 
  18   advertising or publicity pertaining to distribution of the 
  19   software without specific, written prior permission. 
  21   The author disclaim all warranties with regard to this 
  22   software, including all implied warranties of merchantability 
  23   and fitness.  In no event shall the author be liable for any 
  24   special, indirect or consequential damages or any damages 
  25   whatsoever resulting from loss of use, data or profits, whether 
  26   in an action of contract, negligence or other tortious action, 
  27   arising out of or in connection with the use or performance of 
  33  *  Main source file for the KeyboardHost demo. This file contains the main tasks of 
  34  *  the demo and is responsible for the initial application hardware configuration. 
  37 #include "KeyboardHost.h" 
  39 /* Scheduler Task List */ 
  42         { .Task 
= USB_USBTask          
, .TaskStatus 
= TASK_STOP 
}, 
  43         { .Task 
= USB_Keyboard_Host    
, .TaskStatus 
= TASK_STOP 
}, 
  47 /** Main program entry point. This routine configures the hardware required by the application, then 
  48  *  starts the scheduler to run the application tasks. 
  52         /* Disable watchdog if enabled by bootloader/fuses */ 
  53         MCUSR 
&= ~(1 << WDRF
); 
  56         /* Disable clock division */ 
  57         clock_prescale_set(clock_div_1
); 
  59         /* Hardware Initialization */ 
  60         SerialStream_Init(9600, false); 
  63         /* Indicate USB not ready */ 
  64         UpdateStatus(Status_USBNotReady
); 
  66         /* Initialize Scheduler so that it can be used */ 
  69         /* Initialize USB Subsystem */ 
  72         /* Start-up message */ 
  73         puts_P(PSTR(ESC_RESET ESC_BG_WHITE ESC_INVERSE_ON ESC_ERASE_DISPLAY
 
  74                "Keyboard Host Demo running.\r\n" ESC_INVERSE_OFF
)); 
  76         /* Scheduling - routine never returns, so put this last in the main function */ 
  80 /** Event handler for the USB_DeviceAttached event. This indicates that a device has been attached to the host, and 
  81  *  starts the library USB task to begin the enumeration and USB management process. 
  83 void EVENT_USB_DeviceAttached(void) 
  85         puts_P(PSTR("Device Attached.\r\n")); 
  86         UpdateStatus(Status_USBEnumerating
); 
  88         /* Start USB management task to enumerate the device */ 
  89         Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
); 
  92 /** Event handler for the USB_DeviceUnattached event. This indicates that a device has been removed from the host, and 
  93  *  stops the library USB task management process. 
  95 void EVENT_USB_DeviceUnattached(void) 
  97         /* Stop Keyboard and USB management task */ 
  98         Scheduler_SetTaskMode(USB_USBTask
, TASK_STOP
); 
  99         Scheduler_SetTaskMode(USB_Keyboard_Host
, TASK_STOP
); 
 101         puts_P(PSTR("Device Unattached.\r\n")); 
 102         UpdateStatus(Status_USBNotReady
); 
 105 /** Event handler for the USB_DeviceEnumerationComplete event. This indicates that a device has been successfully 
 106  *  enumerated by the host and is now ready to be used by the application. 
 108 void EVENT_USB_DeviceEnumerationComplete(void) 
 110         /* Start Keyboard Host task */ 
 111         Scheduler_SetTaskMode(USB_Keyboard_Host
, TASK_RUN
); 
 113         /* Indicate device enumeration complete */ 
 114         UpdateStatus(Status_USBReady
); 
 117 /** Event handler for the USB_HostError event. This indicates that a hardware error occurred while in host mode. */ 
 118 void EVENT_USB_HostError(const uint8_t ErrorCode
) 
 122         puts_P(PSTR(ESC_BG_RED 
"Host Mode Error\r\n")); 
 123         printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
); 
 125         UpdateStatus(Status_HardwareError
); 
 129 /** Event handler for the USB_DeviceEnumerationFailed event. This indicates that a problem occurred while 
 130  *  enumerating an attached USB device. 
 132 void EVENT_USB_DeviceEnumerationFailed(const uint8_t ErrorCode
, const uint8_t SubErrorCode
) 
 134         puts_P(PSTR(ESC_BG_RED 
"Dev Enum Error\r\n")); 
 135         printf_P(PSTR(" -- Error Code %d\r\n"), ErrorCode
); 
 136         printf_P(PSTR(" -- Sub Error Code %d\r\n"), SubErrorCode
); 
 137         printf_P(PSTR(" -- In State %d\r\n"), USB_HostState
); 
 139         UpdateStatus(Status_EnumerationError
); 
 142 /** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to 
 143  *  log to a serial port, or anything else that is suitable for status updates. 
 145  *  \param CurrentStatus  Current status of the system, from the KeyboardHost_StatusCodes_t enum 
 147 void UpdateStatus(uint8_t CurrentStatus
) 
 149         uint8_t LEDMask 
= LEDS_NO_LEDS
; 
 151         /* Set the LED mask to the appropriate LED mask based on the given status code */ 
 152         switch (CurrentStatus
) 
 154                 case Status_USBNotReady
: 
 155                         LEDMask 
= (LEDS_LED1
); 
 157                 case Status_USBEnumerating
: 
 158                         LEDMask 
= (LEDS_LED1 
| LEDS_LED2
); 
 160                 case Status_USBReady
: 
 161                         LEDMask 
= (LEDS_LED2
); 
 163                 case Status_EnumerationError
: 
 164                 case Status_HardwareError
: 
 165                         LEDMask 
= (LEDS_LED1 
| LEDS_LED3
); 
 169         /* Set the board LEDs to the new LED mask */ 
 170         LEDs_SetAllLEDs(LEDMask
); 
 173 /** Reads in and processes the next report from the attached device, displaying the report 
 174  *  contents on the board LEDs and via the serial port. 
 176 void ReadNextReport(void) 
 178         USB_KeyboardReport_Data_t KeyboardReport
; 
 180         /* Select keyboard data pipe */ 
 181         Pipe_SelectPipe(KEYBOARD_DATAPIPE
);      
 183         /* Unfreeze keyboard data pipe */ 
 186         /* Check to see if a packet has been received */ 
 187         if (!(Pipe_IsINReceived())) 
 189                 /* Refreeze HID data IN pipe */ 
 195         /* Ensure pipe contains data before trying to read from it */ 
 196         if (Pipe_IsReadWriteAllowed()) 
 198                 /* Read in keyboard report data */ 
 199                 Pipe_Read_Stream_LE(&KeyboardReport
, sizeof(KeyboardReport
)); 
 201                 /* Indicate if the modifier byte is non-zero (special key such as shift is being pressed) */ 
 202                 LEDs_ChangeLEDs(LEDS_LED1
, (KeyboardReport
.Modifier
) ? LEDS_LED1 
: 0); 
 204                 /* Check if a key has been pressed */ 
 205                 if (KeyboardReport
.KeyCode
) 
 207                         /* Toggle status LED to indicate keypress */ 
 208                         if (LEDs_GetLEDs() & LEDS_LED2
) 
 209                           LEDs_TurnOffLEDs(LEDS_LED2
); 
 211                           LEDs_TurnOnLEDs(LEDS_LED2
); 
 215                         /* Retrieve pressed key character if alphanumeric */ 
 216                         if ((KeyboardReport
.KeyCode 
>= 0x04) && (KeyboardReport
.KeyCode 
<= 0x1D)) 
 217                           PressedKey 
= (KeyboardReport
.KeyCode 
- 0x04) + 'A'; 
 218                         else if ((KeyboardReport
.KeyCode 
>= 0x1E) && (KeyboardReport
.KeyCode 
<= 0x27)) 
 219                           PressedKey 
= (KeyboardReport
.KeyCode 
- 0x1E) + '0'; 
 220                         else if (KeyboardReport
.KeyCode 
== 0x2C) 
 222                         else if (KeyboardReport
.KeyCode 
== 0x28) 
 225                         /* Print the pressed key character out through the serial port if valid */ 
 231         /* Clear the IN endpoint, ready for next data packet */ 
 234         /* Refreeze keyboard data pipe */ 
 238 /** Task to set the configuration of the attached device after it has been enumerated, and to read and process 
 239  *  HID reports from the device and display the results onto the board LEDs. 
 241 TASK(USB_Keyboard_Host
) 
 245         switch (USB_HostState
) 
 247                 case HOST_STATE_Addressed
: 
 248                         /* Standard request to set the device configuration to configuration 1 */ 
 249                         USB_ControlRequest 
= (USB_Request_Header_t
) 
 251                                         .bmRequestType 
= (REQDIR_HOSTTODEVICE 
| REQTYPE_STANDARD 
| REQREC_DEVICE
), 
 252                                         .bRequest      
= REQ_SetConfiguration
, 
 258                         /* Select the control pipe for the request transfer */ 
 259                         Pipe_SelectPipe(PIPE_CONTROLPIPE
); 
 261                         /* Send the request, display error and wait for device detach if request fails */ 
 262                         if ((ErrorCode 
= USB_Host_SendControlRequest(NULL
)) != HOST_SENDCONTROL_Successful
) 
 264                                 puts_P(PSTR("Control Error (Set Configuration).\r\n")); 
 265                                 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
); 
 267                                 /* Indicate error status */ 
 268                                 UpdateStatus(Status_EnumerationError
); 
 270                                 /* Wait until USB device disconnected */ 
 271                                 while (USB_IsConnected
); 
 275                         USB_HostState 
= HOST_STATE_Configured
; 
 277                 case HOST_STATE_Configured
: 
 278                         puts_P(PSTR("Getting Config Data.\r\n")); 
 280                         /* Get and process the configuration descriptor data */ 
 281                         if ((ErrorCode 
= ProcessConfigurationDescriptor()) != SuccessfulConfigRead
) 
 283                                 if (ErrorCode 
== ControlError
) 
 284                                   puts_P(PSTR("Control Error (Get Configuration).\r\n")); 
 286                                   puts_P(PSTR("Invalid Device.\r\n")); 
 288                                 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
); 
 290                                 /* Indicate error status */ 
 291                                 UpdateStatus(Status_EnumerationError
); 
 293                                 /* Wait until USB device disconnected */ 
 294                                 while (USB_IsConnected
); 
 298                         /* HID class request to set the keyboard protocol to the Boot Protocol */ 
 299                         USB_ControlRequest 
= (USB_Request_Header_t
) 
 301                                         .bmRequestType 
= (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
), 
 302                                         .bRequest      
= REQ_SetProtocol
, 
 308                         /* Select the control pipe for the request transfer */ 
 309                         Pipe_SelectPipe(PIPE_CONTROLPIPE
); 
 311                         /* Send the request, display error and wait for device detach if request fails */ 
 312                         if ((ErrorCode 
= USB_Host_SendControlRequest(NULL
)) != HOST_SENDCONTROL_Successful
) 
 314                                 puts_P(PSTR("Control Error (Set Protocol).\r\n")); 
 315                                 printf_P(PSTR(" -- Error Code: %d\r\n"), ErrorCode
); 
 317                                 /* Indicate error status */ 
 318                                 UpdateStatus(Status_EnumerationError
); 
 320                                 /* Wait until USB device disconnected */ 
 321                                 while (USB_IsConnected
); 
 325                         puts_P(PSTR("Keyboard Enumerated.\r\n")); 
 327                         USB_HostState 
= HOST_STATE_Ready
; 
 329                 case HOST_STATE_Ready
: 
 330                         /* If a report has been received, read and process it */