Statistics
| Branch: | Tag: | Revision:

root / Keyboard.c @ master

History | View | Annotate | Download (10.1 KB)

1 6ebafa20 imp
/*
2
             LUFA Library
3
     Copyright (C) Dean Camera, 2011.
4

5
  dean [at] fourwalledcubicle [dot] com
6
           www.lufa-lib.org
7
*/
8
9
/*
10
  Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com)
11
  Copyright 2010  Denver Gingerich (denver [at] ossguy [dot] com)
12

13
  Permission to use, copy, modify, distribute, and sell this
14
  software and its documentation for any purpose is hereby granted
15
  without fee, provided that the above copyright notice appear in
16
  all copies and that both that the copyright notice and this
17
  permission notice and warranty disclaimer appear in supporting
18
  documentation, and that the name of the author not be used in
19
  advertising or publicity pertaining to distribution of the
20
  software without specific, written prior permission.
21

22
  The author disclaim all warranties with regard to this
23
  software, including all implied warranties of merchantability
24
  and fitness.  In no event shall the author be liable for any
25
  special, indirect or consequential damages or any damages
26
  whatsoever resulting from loss of use, data or profits, whether
27
  in an action of contract, negligence or other tortious action,
28
  arising out of or in connection with the use or performance of
29
  this software.
30
*/
31
32
/** \file
33
 *
34
 *  Main source file for the Keyboard demo. This file contains the main tasks of the demo and
35
 *  is responsible for the initial application hardware configuration.
36
 */
37
38
#include "Keyboard.h"
39
40
/** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
41
 *  protocol reporting mode.
42
 */
43
static bool UsingReportProtocol = true;
44
45
/** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
46
 *  for either the entire idle duration, or until the report status changes (e.g. the user presses a key).
47
 */
48
static uint16_t IdleCount = 500;
49
50
/** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
51
 *  milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request
52
 *  the current idle period via a Get Idle HID class request, thus its value must be preserved.
53
 */
54
static uint16_t IdleMSRemaining = 0;
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
        sei();
64
65
        for (;;)
66
        {
67
                HID_Task();
68
                USB_USBTask();
69
        }
70
}
71
72
/** Configures the board hardware and chip peripherals for the demo's functionality. */
73
void SetupHardware(void)
74
{
75
        /* Disable watchdog if enabled by bootloader/fuses */
76
        MCUSR &= ~(1 << WDRF);
77
        wdt_disable();
78
79
        /* Disable clock division */
80
        clock_prescale_set(clock_div_1);
81
82
        /* Hardware Initialization */
83
        USB_Init();
84 2e93ce57 imp
        setupMatrix();
85 6ebafa20 imp
}
86
87
/** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
88
 *  starts the library USB task to begin the enumeration and USB management process.
89
 */
90
void EVENT_USB_Device_Connect(void)
91
{
92
        /* Default to report protocol on connect */
93
        UsingReportProtocol = true;
94
}
95
96
/** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
97
 *  the status LEDs.
98
 */
99
void EVENT_USB_Device_Disconnect(void)
100
{
101 2bdaeeb5 imp
        return;
102 6ebafa20 imp
}
103
104
/** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
105
 *  of the USB device after enumeration, and configures the keyboard device endpoints.
106
 */
107
void EVENT_USB_Device_ConfigurationChanged(void)
108
{
109
        bool ConfigSuccess = true;
110
111
        /* Setup HID Report Endpoints */
112
        ConfigSuccess &= Endpoint_ConfigureEndpoint(KEYBOARD_IN_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_IN,
113
                                                    KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
114
        ConfigSuccess &= Endpoint_ConfigureEndpoint(KEYBOARD_OUT_EPNUM, EP_TYPE_INTERRUPT, ENDPOINT_DIR_OUT,
115
                                                    KEYBOARD_EPSIZE, ENDPOINT_BANK_SINGLE);
116
117
        /* Turn on Start-of-Frame events for tracking HID report period expiry */
118
        USB_Device_EnableSOFEvents();
119
}
120
121
/** Event handler for the USB_ControlRequest event. This is used to catch and process control requests sent to
122
 *  the device from the USB host before passing along unhandled control requests to the library for processing
123
 *  internally.
124
 */
125
void EVENT_USB_Device_ControlRequest(void)
126
{
127
        /* Handle HID Class specific requests */
128
        switch (USB_ControlRequest.bRequest)
129
        {
130
                case HID_REQ_GetReport:
131
                        if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
132
                        {
133
                                USB_KeyboardReport_Data_t KeyboardReportData;
134
135
                                /* Create the next keyboard report for transmission to the host */
136
                                CreateKeyboardReport(&KeyboardReportData);
137
138
                                Endpoint_ClearSETUP();
139
140
                                /* Write the report data to the control endpoint */
141
                                Endpoint_Write_Control_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
142
                                Endpoint_ClearOUT();
143
                        }
144
145
                        break;
146
                case HID_REQ_SetReport:
147
                        if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
148
                        {
149
                                Endpoint_ClearSETUP();
150
151
                                /* Wait until the LED report has been sent by the host */
152
                                while (!(Endpoint_IsOUTReceived()))
153
                                {
154
                                        if (USB_DeviceState == DEVICE_STATE_Unattached)
155
                                          return;
156
                                }
157
158
                                Endpoint_ClearOUT();
159
                                Endpoint_ClearStatusStage();
160
                        }
161
162
                        break;
163
                case HID_REQ_GetProtocol:
164
                        if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
165
                        {
166
                                Endpoint_ClearSETUP();
167
168
                                /* Write the current protocol flag to the host */
169
                                Endpoint_Write_8(UsingReportProtocol);
170
171
                                Endpoint_ClearIN();
172
                                Endpoint_ClearStatusStage();
173
                        }
174
175
                        break;
176
                case HID_REQ_SetProtocol:
177
                        if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
178
                        {
179
                                Endpoint_ClearSETUP();
180
                                Endpoint_ClearStatusStage();
181
182
                                /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
183
                                UsingReportProtocol = (USB_ControlRequest.wValue != 0);
184
                        }
185
186
                        break;
187
                case HID_REQ_SetIdle:
188
                        if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
189
                        {
190
                                Endpoint_ClearSETUP();
191
                                Endpoint_ClearStatusStage();
192
193
                                /* Get idle period in MSB, IdleCount must be multiplied by 4 to get number of milliseconds */
194
                                IdleCount = ((USB_ControlRequest.wValue & 0xFF00) >> 6);
195
                        }
196
197
                        break;
198
                case HID_REQ_GetIdle:
199
                        if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
200
                        {
201
                                Endpoint_ClearSETUP();
202
203
                                /* Write the current idle duration to the host, must be divided by 4 before sent to host */
204
                                Endpoint_Write_8(IdleCount >> 2);
205
206
                                Endpoint_ClearIN();
207
                                Endpoint_ClearStatusStage();
208
                        }
209
210
                        break;
211
        }
212
}
213
214
/** Event handler for the USB device Start Of Frame event. */
215
void EVENT_USB_Device_StartOfFrame(void)
216
{
217
        /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
218
        if (IdleMSRemaining)
219
          IdleMSRemaining--;
220
}
221
222
/** Fills the given HID report data structure with the next HID report to send to the host.
223
 *
224
 *  \param[out] ReportData  Pointer to a HID report data structure to be filled
225
 */
226
void CreateKeyboardReport(USB_KeyboardReport_Data_t* const ReportData)
227
{
228
        /* Clear the report contents */
229
        memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
230 2e93ce57 imp
        setReportData(ReportData);
231 6ebafa20 imp
}
232
233
/** Processes a received LED report, and updates the board LEDs states to match.
234
 *
235
 *  \param[in] LEDReport  LED status report from the host
236
 */
237
void ProcessLEDReport(const uint8_t LEDReport)
238
{
239 2bdaeeb5 imp
        // TODO use this to poll the bigramm stats later
240 2e93ce57 imp
        return;
241 6ebafa20 imp
}
242
243
/** Sends the next HID report to the host, via the keyboard data endpoint. */
244
void SendNextReport(void)
245
{
246
        static USB_KeyboardReport_Data_t PrevKeyboardReportData;
247
        USB_KeyboardReport_Data_t        KeyboardReportData;
248
        bool                             SendReport = true;
249
250
        /* Create the next keyboard report for transmission to the host */
251
        CreateKeyboardReport(&KeyboardReportData);
252
253
        /* Check to see if the report data has changed - if so a report MUST be sent */
254
        SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
255
256
        /* Check if the idle period is set and has elapsed */
257
        if (IdleCount && (!(IdleMSRemaining)))
258
        {
259
                /* Reset the idle time remaining counter */
260
                IdleMSRemaining = IdleCount;
261
262
                /* Idle period is set and has elapsed, must send a report to the host */
263
                SendReport = true;
264
        }
265
266
        /* Select the Keyboard Report Endpoint */
267
        Endpoint_SelectEndpoint(KEYBOARD_IN_EPNUM);
268
269
        /* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
270
        if (Endpoint_IsReadWriteAllowed() && SendReport)
271
        {
272
                /* Save the current report data for later comparison to check for changes */
273
                PrevKeyboardReportData = KeyboardReportData;
274
275
                /* Write Keyboard Report Data */
276
                Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData), NULL);
277
278
                /* Finalize the stream transfer to send the last packet */
279
                Endpoint_ClearIN();
280
        }
281
}
282
283
/** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
284
void ReceiveNextReport(void)
285
{
286
        /* Select the Keyboard LED Report Endpoint */
287
        Endpoint_SelectEndpoint(KEYBOARD_OUT_EPNUM);
288
289
        /* Check if Keyboard LED Endpoint contains a packet */
290
        if (Endpoint_IsOUTReceived())
291
        {
292
                /* Check to see if the packet contains data */
293
                if (Endpoint_IsReadWriteAllowed())
294
                {
295
                        /* Read in the LED report from the host */
296
                        uint8_t LEDReport = Endpoint_Read_8();
297
298
                        /* Process the read LED report from the host */
299
                        ProcessLEDReport(LEDReport);
300
                }
301
302
                /* Handshake the OUT Endpoint - clear endpoint and ready for next report */
303
                Endpoint_ClearOUT();
304
        }
305
}
306
307
/** Function to manage HID report generation and transmission to the host, when in report mode. */
308
void HID_Task(void)
309
{
310
        /* Device must be connected and configured for the task to run */
311
        if (USB_DeviceState != DEVICE_STATE_Configured)
312
          return;
313
314
        /* Send the next keypress report to the host */
315
        SendNextReport();
316
317
        /* Process the LED report sent from the host */
318
        ReceiveNextReport();
319
}