3      Copyright (C) Dean Camera, 2010. 
   5   dean [at] fourwalledcubicle [dot] com 
   6       www.fourwalledcubicle.com 
  10   Copyright 2010  Dean Camera (dean [at] fourwalledcubicle [dot] com) 
  12   Permission to use, copy, modify, distribute, and sell this  
  13   software and its documentation for any purpose is hereby granted 
  14   without fee, provided that the above copyright notice appear in  
  15   all 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 Mouse demo. This file contains the main tasks of the demo and 
  34  *  is responsible for the initial application hardware configuration. 
  39 /** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot 
  40  *  protocol reporting mode. 
  42 bool UsingReportProtocol 
= true; 
  44 /** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports 
  45  *  for either the entire idle duration, or until the report status changes (e.g. the user moves the mouse). 
  47 uint16_t IdleCount 
= HID_IDLE_CHANGESONLY
; 
  49 /** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle 
  50  *  milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request  
  51  *  the current idle period via a Get Idle HID class request, thus its value must be preserved. 
  53 uint16_t IdleMSRemaining 
= 0; 
  56 /** Main program entry point. This routine configures the hardware required by the application, then 
  57  *  enters a loop to run the application tasks in sequence. 
  63         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
  73 /** Configures the board hardware and chip peripherals for the demo's functionality. */ 
  74 void SetupHardware(void) 
  76         /* Disable watchdog if enabled by bootloader/fuses */ 
  77         MCUSR 
&= ~(1 << WDRF
); 
  80         /* Disable clock division */ 
  81         clock_prescale_set(clock_div_1
); 
  83         /* Hardware Initialization */ 
  90 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and 
  91  *  starts the library USB task to begin the enumeration and USB management process. 
  93 void EVENT_USB_Device_Connect(void) 
  95         /* Indicate USB enumerating */ 
  96         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING
); 
  98         /* Default to report protocol on connect */ 
  99         UsingReportProtocol 
= true; 
 102 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via 
 103  *  the status LEDs and stops the USB management and Mouse reporting tasks. 
 105 void EVENT_USB_Device_Disconnect(void) 
 107         /* Indicate USB not ready */ 
 108         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY
); 
 111 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration 
 112  *  of the USB device after enumeration - the device endpoints are configured and the mouse reporting task started. 
 114 void EVENT_USB_Device_ConfigurationChanged(void) 
 116         /* Indicate USB connected and ready */ 
 117         LEDs_SetAllLEDs(LEDMASK_USB_READY
); 
 119         /* Setup Mouse Report Endpoint */ 
 120         if (!(Endpoint_ConfigureEndpoint(MOUSE_EPNUM
, EP_TYPE_INTERRUPT
, 
 121                                              ENDPOINT_DIR_IN
, MOUSE_EPSIZE
, 
 122                                          ENDPOINT_BANK_SINGLE
))) 
 124                 LEDs_SetAllLEDs(LEDMASK_USB_ERROR
); 
 127         USB_Device_EnableSOFEvents(); 
 130 /** Event handler for the USB_UnhandledControlRequest event. This is used to catch standard and class specific 
 131  *  control requests that are not handled internally by the USB library (including the HID commands, which are 
 132  *  all issued via the control endpoint), so that they can be handled appropriately for the application. 
 134 void EVENT_USB_Device_UnhandledControlRequest(void) 
 136         /* Handle HID Class specific requests */ 
 137         switch (USB_ControlRequest
.bRequest
) 
 140                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 142                                 USB_MouseReport_Data_t MouseReportData
; 
 144                                 Endpoint_ClearSETUP(); 
 146                                 /* Create the next mouse report for transmission to the host */ 
 147                                 CreateMouseReport(&MouseReportData
); 
 149                                 /* Write the report data to the control endpoint */ 
 150                                 Endpoint_Write_Control_Stream_LE(&MouseReportData
, sizeof(MouseReportData
)); 
 152                                 /* Clear the report data afterwards */ 
 153                                 memset(&MouseReportData
, 0, sizeof(MouseReportData
)); 
 155                                 /* Finalize the stream transfer to send the last packet or clear the host abort */ 
 160                 case REQ_GetProtocol
: 
 161                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 163                                 Endpoint_ClearSETUP(); 
 165                                 /* Write the current protocol flag to the host */ 
 166                                 Endpoint_Write_Byte(UsingReportProtocol
); 
 168                                 /* Send the flag to the host */ 
 171                                 Endpoint_ClearStatusStage(); 
 175                 case REQ_SetProtocol
: 
 176                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 178                                 Endpoint_ClearSETUP(); 
 180                                 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */ 
 181                                 UsingReportProtocol 
= (USB_ControlRequest
.wValue 
!= 0); 
 183                                 Endpoint_ClearStatusStage(); 
 188                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 190                                 Endpoint_ClearSETUP(); 
 192                                 /* Get idle period in MSB, must multiply by 4 to get the duration in milliseconds */ 
 193                                 IdleCount 
= ((USB_ControlRequest
.wValue 
& 0xFF00) >> 6); 
 195                                 Endpoint_ClearStatusStage(); 
 200                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 202                                 Endpoint_ClearSETUP(); 
 204                                 /* Write the current idle duration to the host, must be divided by 4 before sent to host */ 
 205                                 Endpoint_Write_Byte(IdleCount 
>> 2); 
 207                                 /* Send the flag to the host */ 
 210                                 Endpoint_ClearStatusStage(); 
 217 /** Event handler for the USB device Start Of Frame event. */ 
 218 void EVENT_USB_Device_StartOfFrame(void) 
 220         /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */ 
 225 /** Fills the given HID report data structure with the next HID report to send to the host. 
 227  *  \param[out] ReportData  Pointer to a HID report data structure to be filled 
 229 void CreateMouseReport(USB_MouseReport_Data_t
* ReportData
) 
 231         uint8_t JoyStatus_LCL    
= Joystick_GetStatus(); 
 232         uint8_t ButtonStatus_LCL 
= Buttons_GetStatus(); 
 234         /* Clear the report contents */ 
 235         memset(ReportData
, 0, sizeof(USB_MouseReport_Data_t
)); 
 237         if (JoyStatus_LCL 
& JOY_UP
) 
 239         else if (JoyStatus_LCL 
& JOY_DOWN
) 
 242         if (JoyStatus_LCL 
& JOY_LEFT
) 
 244         else if (JoyStatus_LCL 
& JOY_RIGHT
) 
 247         if (JoyStatus_LCL 
& JOY_PRESS
) 
 248           ReportData
->Button  
= (1 << 0); 
 250         if (ButtonStatus_LCL 
& BUTTONS_BUTTON1
) 
 251           ReportData
->Button 
|= (1 << 1); 
 254 /** Sends the next HID report to the host, via the keyboard data endpoint. */ 
 255 void SendNextReport(void) 
 257         static USB_MouseReport_Data_t PrevMouseReportData
; 
 258         USB_MouseReport_Data_t        MouseReportData
; 
 261         /* Create the next mouse report for transmission to the host */ 
 262         CreateMouseReport(&MouseReportData
); 
 264         /* Check to see if the report data has changed - if so a report MUST be sent */ 
 265         SendReport 
= (memcmp(&PrevMouseReportData
, &MouseReportData
, sizeof(USB_MouseReport_Data_t
)) != 0); 
 267         /* Override the check if the Y or X values are non-zero - we want continuous movement while the joystick 
 268          * is being held down (via continuous reports), otherwise the cursor will only move once per joystick toggle */ 
 269         if ((MouseReportData
.Y 
!= 0) || (MouseReportData
.X 
!= 0)) 
 272         /* Check if the idle period is set and has elapsed */ 
 273         if ((IdleCount 
!= HID_IDLE_CHANGESONLY
) && (!(IdleMSRemaining
))) 
 275                 /* Reset the idle time remaining counter */ 
 276                 IdleMSRemaining 
= IdleCount
; 
 278                 /* Idle period is set and has elapsed, must send a report to the host */ 
 282         /* Select the Mouse Report Endpoint */ 
 283         Endpoint_SelectEndpoint(MOUSE_EPNUM
); 
 285         /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */ 
 286         if (Endpoint_IsReadWriteAllowed() && SendReport
) 
 288                 /* Save the current report data for later comparison to check for changes */ 
 289                 PrevMouseReportData 
= MouseReportData
; 
 291                 /* Write Mouse Report Data */ 
 292                 Endpoint_Write_Stream_LE(&MouseReportData
, sizeof(MouseReportData
)); 
 294                 /* Finalize the stream transfer to send the last packet */ 
 299 /** Task to manage HID report generation and transmission to the host, when in report mode. */ 
 300 void Mouse_Task(void) 
 302         /* Device must be connected and configured for the task to run */ 
 303         if (USB_DeviceState 
!= DEVICE_STATE_Configured
) 
 306         /* Send the next mouse report to the host */