]> git.friedersdorff.com Git - max/tmk_keyboard.git/blob - tmk_core/protocol/lufa/LUFA-git/Demos/Device/LowLevel/Mouse/Mouse.c
Merge commit '5a0132f1c1c9a14fd2941f0a5e29bbf5e31da20c' into master-core-pull
[max/tmk_keyboard.git] / tmk_core / protocol / lufa / LUFA-git / Demos / Device / LowLevel / Mouse / Mouse.c
1 /*
2              LUFA Library
3      Copyright (C) Dean Camera, 2014.
4
5   dean [at] fourwalledcubicle [dot] com
6            www.lufa-lib.org
7 */
8
9 /*
10   Copyright 2014  Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
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.
20
21   The author disclaims 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
28   this software.
29 */
30
31 /** \file
32  *
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.
35  */
36
37 #include "Mouse.h"
38
39 /** Indicates what report mode the host has requested, true for normal HID reporting mode, \c false for special boot
40  *  protocol reporting mode.
41  */
42 static bool UsingReportProtocol = true;
43
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).
46  */
47 static uint16_t IdleCount = 0;
48
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.
52  */
53 static uint16_t IdleMSRemaining = 0;
54
55
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.
58  */
59 int main(void)
60 {
61         SetupHardware();
62
63         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
64         GlobalInterruptEnable();
65
66         for (;;)
67         {
68                 Mouse_Task();
69                 USB_USBTask();
70         }
71 }
72
73 /** Configures the board hardware and chip peripherals for the demo's functionality. */
74 void SetupHardware(void)
75 {
76 #if (ARCH == ARCH_AVR8)
77         /* Disable watchdog if enabled by bootloader/fuses */
78         MCUSR &= ~(1 << WDRF);
79         wdt_disable();
80
81         /* Disable clock division */
82         clock_prescale_set(clock_div_1);
83 #elif (ARCH == ARCH_XMEGA)
84         /* Start the PLL to multiply the 2MHz RC oscillator to 32MHz and switch the CPU core to run from it */
85         XMEGACLK_StartPLL(CLOCK_SRC_INT_RC2MHZ, 2000000, F_CPU);
86         XMEGACLK_SetCPUClockSource(CLOCK_SRC_PLL);
87
88         /* Start the 32MHz internal RC oscillator and start the DFLL to increase it to 48MHz using the USB SOF as a reference */
89         XMEGACLK_StartInternalOscillator(CLOCK_SRC_INT_RC32MHZ);
90         XMEGACLK_StartDFLL(CLOCK_SRC_INT_RC32MHZ, DFLL_REF_INT_USBSOF, F_USB);
91
92         PMIC.CTRL = PMIC_LOLVLEN_bm | PMIC_MEDLVLEN_bm | PMIC_HILVLEN_bm;
93 #endif
94
95         /* Hardware Initialization */
96         Joystick_Init();
97         LEDs_Init();
98         Buttons_Init();
99         USB_Init();
100 }
101
102 /** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
103  *  starts the library USB task to begin the enumeration and USB management process.
104  */
105 void EVENT_USB_Device_Connect(void)
106 {
107         /* Indicate USB enumerating */
108         LEDs_SetAllLEDs(LEDMASK_USB_ENUMERATING);
109
110         /* Default to report protocol on connect */
111         UsingReportProtocol = true;
112 }
113
114 /** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
115  *  the status LEDs and stops the USB management and Mouse reporting tasks.
116  */
117 void EVENT_USB_Device_Disconnect(void)
118 {
119         /* Indicate USB not ready */
120         LEDs_SetAllLEDs(LEDMASK_USB_NOTREADY);
121 }
122
123 /** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
124  *  of the USB device after enumeration - the device endpoints are configured and the mouse reporting task started.
125  */
126 void EVENT_USB_Device_ConfigurationChanged(void)
127 {
128         bool ConfigSuccess = true;
129
130         /* Setup HID Report Endpoint */
131         ConfigSuccess &= Endpoint_ConfigureEndpoint(MOUSE_EPADDR, EP_TYPE_INTERRUPT, MOUSE_EPSIZE, 1);
132
133         /* Turn on Start-of-Frame events for tracking HID report period expiry */
134         USB_Device_EnableSOFEvents();
135
136         /* Indicate endpoint configuration success or failure */
137         LEDs_SetAllLEDs(ConfigSuccess ? LEDMASK_USB_READY : LEDMASK_USB_ERROR);
138 }
139
140 /** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
141  *  the device from the USB host before passing along unhandled control requests to the library for processing
142  *  internally.
143  */
144 void EVENT_USB_Device_ControlRequest(void)
145 {
146         /* Handle HID Class specific requests */
147         switch (USB_ControlRequest.bRequest)
148         {
149                 case HID_REQ_GetReport:
150                         if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
151                         {
152                                 USB_MouseReport_Data_t MouseReportData;
153
154                                 /* Create the next mouse report for transmission to the host */
155                                 CreateMouseReport(&MouseReportData);
156
157                                 Endpoint_ClearSETUP();
158
159                                 /* Write the report data to the control endpoint */
160                                 Endpoint_Write_Control_Stream_LE(&MouseReportData, sizeof(MouseReportData));
161                                 Endpoint_ClearOUT();
162
163                                 /* Clear the report data afterwards */
164                                 memset(&MouseReportData, 0, sizeof(MouseReportData));
165                         }
166
167                         break;
168                 case HID_REQ_GetProtocol:
169                         if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
170                         {
171                                 Endpoint_ClearSETUP();
172
173                                 /* Write the current protocol flag to the host */
174                                 Endpoint_Write_8(UsingReportProtocol);
175
176                                 Endpoint_ClearIN();
177                                 Endpoint_ClearStatusStage();
178                         }
179
180                         break;
181                 case HID_REQ_SetProtocol:
182                         if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
183                         {
184                                 Endpoint_ClearSETUP();
185                                 Endpoint_ClearStatusStage();
186
187                                 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
188                                 UsingReportProtocol = (USB_ControlRequest.wValue != 0);
189                         }
190
191                         break;
192                 case HID_REQ_SetIdle:
193                         if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
194                         {
195                                 Endpoint_ClearSETUP();
196                                 Endpoint_ClearStatusStage();
197
198                                 /* Get idle period in MSB, must multiply by 4 to get the duration in milliseconds */
199                                 IdleCount = ((USB_ControlRequest.wValue & 0xFF00) >> 6);
200                         }
201
202                         break;
203                 case HID_REQ_GetIdle:
204                         if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
205                         {
206                                 Endpoint_ClearSETUP();
207
208                                 /* Write the current idle duration to the host, must be divided by 4 before sent to host */
209                                 Endpoint_Write_8(IdleCount >> 2);
210
211                                 Endpoint_ClearIN();
212                                 Endpoint_ClearStatusStage();
213                         }
214
215                         break;
216         }
217 }
218
219 /** Event handler for the USB device Start Of Frame event. */
220 void EVENT_USB_Device_StartOfFrame(void)
221 {
222         /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
223         if (IdleMSRemaining)
224           IdleMSRemaining--;
225 }
226
227 /** Fills the given HID report data structure with the next HID report to send to the host.
228  *
229  *  \param[out] ReportData  Pointer to a HID report data structure to be filled
230  */
231 void CreateMouseReport(USB_MouseReport_Data_t* const ReportData)
232 {
233         uint8_t JoyStatus_LCL    = Joystick_GetStatus();
234         uint8_t ButtonStatus_LCL = Buttons_GetStatus();
235
236         /* Clear the report contents */
237         memset(ReportData, 0, sizeof(USB_MouseReport_Data_t));
238
239         if (JoyStatus_LCL & JOY_UP)
240           ReportData->Y = -1;
241         else if (JoyStatus_LCL & JOY_DOWN)
242           ReportData->Y =  1;
243
244         if (JoyStatus_LCL & JOY_LEFT)
245           ReportData->X = -1;
246         else if (JoyStatus_LCL & JOY_RIGHT)
247           ReportData->X =  1;
248
249         if (JoyStatus_LCL & JOY_PRESS)
250           ReportData->Button |= (1 << 0);
251
252         if (ButtonStatus_LCL & BUTTONS_BUTTON1)
253           ReportData->Button |= (1 << 1);
254 }
255
256 /** Sends the next HID report to the host, via the keyboard data endpoint. */
257 void SendNextReport(void)
258 {
259         static USB_MouseReport_Data_t PrevMouseReportData;
260         USB_MouseReport_Data_t        MouseReportData;
261         bool                          SendReport;
262
263         /* Create the next mouse report for transmission to the host */
264         CreateMouseReport(&MouseReportData);
265
266         /* Check to see if the report data has changed - if so a report MUST be sent */
267         SendReport = (memcmp(&PrevMouseReportData, &MouseReportData, sizeof(USB_MouseReport_Data_t)) != 0);
268
269         /* Override the check if the Y or X values are non-zero - we want continuous movement while the joystick
270          * is being held down (via continuous reports), otherwise the cursor will only move once per joystick toggle */
271         if ((MouseReportData.Y != 0) || (MouseReportData.X != 0))
272           SendReport = true;
273
274         /* Check if the idle period is set and has elapsed */
275         if (IdleCount && (!(IdleMSRemaining)))
276         {
277                 /* Reset the idle time remaining counter */
278                 IdleMSRemaining = IdleCount;
279
280                 /* Idle period is set and has elapsed, must send a report to the host */
281                 SendReport = true;
282         }
283
284         /* Select the Mouse Report Endpoint */
285         Endpoint_SelectEndpoint(MOUSE_EPADDR);
286
287         /* Check if Mouse Endpoint Ready for Read/Write and if we should send a new report */
288         if (Endpoint_IsReadWriteAllowed() && SendReport)
289         {
290                 /* Save the current report data for later comparison to check for changes */
291                 PrevMouseReportData = MouseReportData;
292
293                 /* Write Mouse Report Data */
294                 Endpoint_Write_Stream_LE(&MouseReportData, sizeof(MouseReportData), NULL);
295
296                 /* Finalize the stream transfer to send the last packet */
297                 Endpoint_ClearIN();
298         }
299 }
300
301 /** Task to manage HID report generation and transmission to the host, when in report mode. */
302 void Mouse_Task(void)
303 {
304         /* Device must be connected and configured for the task to run */
305         if (USB_DeviceState != DEVICE_STATE_Configured)
306           return;
307
308         /* Send the next mouse report to the host */
309         SendNextReport();
310 }
311