Keyboard.c 13.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/*
             LUFA Library
     Copyright (C) Dean Camera, 2009.
              
  dean [at] fourwalledcubicle [dot] com
      www.fourwalledcubicle.com
*/

/*
  Copyright 2009  Denver Gingerich (denver [at] ossguy [dot] com)
      Based on code by Dean Camera (dean [at] fourwalledcubicle [dot] com)

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

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
34
 *  Main source file for the Keyboard demo. This file contains the main tasks of the demo and
35
36
37
38
39
40
41
42
 *  is responsible for the initial application hardware configuration.
 */
 
#include "Keyboard.h"

/* Scheduler Task List */
TASK_LIST
{
43
	{ .Task = USB_USBTask          , .TaskStatus = TASK_STOP },	
44
	{ .Task = USB_Keyboard_Report  , .TaskStatus = TASK_STOP },
45
46
47
48
49
50
51
52
53
};

/* Global Variables */
/** Indicates what report mode the host has requested, true for normal HID reporting mode, false for special boot
 *  protocol reporting mode.
 */
bool UsingReportProtocol = true;

/** Current Idle period. This is set by the host via a Set Idle HID class request to silence the device's reports
54
 *  for either the entire idle duration, or until the report status changes (e.g. the user presses a key).
55
 */
56
uint16_t IdleCount = 500;
57
58

/** Current Idle period remaining. When the IdleCount value is set, this tracks the remaining number of idle
59
 *  milliseconds. This is separate to the IdleCount timer and is incremented and compared as the host may request 
60
61
62
63
64
65
 *  the current idle period via a Get Idle HID class request, thus its value must be preserved.
 */
uint16_t IdleMSRemaining = 0;


/** Main program entry point. This routine configures the hardware required by the application, then
66
 *  starts the scheduler to run the USB management task.
67
68
69
70
71
72
73
 */
int main(void)
{
	/* Disable watchdog if enabled by bootloader/fuses */
	MCUSR &= ~(1 << WDRF);
	wdt_disable();

74
75
	/* Disable clock division */
	clock_prescale_set(clock_div_1);
76
77
78
79
80
81
82
83
84
85
86
87
88

	/* Hardware Initialization */
	Joystick_Init();
	LEDs_Init();
	
	/* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
	OCR0A  = 0x7D;
	TCCR0A = (1 << WGM01);
	TCCR0B = ((1 << CS01) | (1 << CS00));
	TIMSK0 = (1 << OCIE0A);

	/* Indicate USB not ready */
	UpdateStatus(Status_USBNotReady);
89

90
91
92
93
94
95
96
97
98
99
100
101
102
	/* Initialize Scheduler so that it can be used */
	Scheduler_Init();

	/* Initialize USB Subsystem */
	USB_Init();
	
	/* Scheduling - routine never returns, so put this last in the main function */
	Scheduler_Start();
}

/** Event handler for the USB_Connect event. This indicates that the device is enumerating via the status LEDs and
 *  starts the library USB task to begin the enumeration and USB management process.
 */
103
void EVENT_USB_Connect(void)
104
{
105
106
107
	/* Start USB management task */
	Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);

108
109
	/* Indicate USB enumerating */
	UpdateStatus(Status_USBEnumerating);
110
111
112
113
114

	/* Default to report protocol on connect */
	UsingReportProtocol = true;
}

115
/** Event handler for the USB_Disconnect event. This indicates that the device is no longer connected to a host via
116
 *  the status LEDs.
117
 */
118
void EVENT_USB_Disconnect(void)
119
{
120
121
122
123
	/* Stop running keyboard reporting and USB management tasks */
	Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_STOP);
	Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
	
124
125
126
127
	/* Indicate USB not ready */
	UpdateStatus(Status_USBNotReady);
}

128
129
130
/** Event handler for the USB_ConfigurationChanged event. This is fired when the host sets the current configuration
 *  of the USB device after enumeration, and configures the keyboard device endpoints.
 */
131
void EVENT_USB_ConfigurationChanged(void)
132
133
134
135
136
137
138
139
140
141
142
143
144
{
	/* Setup Keyboard Keycode Report Endpoint */
	Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
		                       ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
	                           ENDPOINT_BANK_SINGLE);

	/* Setup Keyboard LED Report Endpoint */
	Endpoint_ConfigureEndpoint(KEYBOARD_LEDS_EPNUM, EP_TYPE_INTERRUPT,
		                       ENDPOINT_DIR_OUT, KEYBOARD_EPSIZE,
	                           ENDPOINT_BANK_SINGLE);

	/* Indicate USB connected and ready */
	UpdateStatus(Status_USBReady);
145
146
147

	/* Start running keyboard reporting task */
	Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_RUN);
148
149
150
151
152
153
}

/** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
 *  control requests that are not handled internally by the USB library (including the HID commands, which are
 *  all issued via the control endpoint), so that they can be handled appropriately for the application.
 */
154
void EVENT_USB_UnhandledControlPacket(void)
155
156
{
	/* Handle HID Class specific requests */
157
	switch (USB_ControlRequest.bRequest)
158
159
	{
		case REQ_GetReport:
160
			if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
161
162
163
			{
				USB_KeyboardReport_Data_t KeyboardReportData;

164
165
				Endpoint_ClearSETUP();
	
166
				/* Create the next keyboard report for transmission to the host */
167
				CreateKeyboardReport(&KeyboardReportData);
168
169

				/* Write the report data to the control endpoint */
170
				Endpoint_Write_Control_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
171
172
				
				/* Finalize the stream transfer to send the last packet or clear the host abort */
173
				Endpoint_ClearOUT();
174
175
176
177
			}
		
			break;
		case REQ_SetReport:
178
			if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
179
			{
180
				Endpoint_ClearSETUP();
181
182
				
				/* Wait until the LED report has been sent by the host */
183
				while (!(Endpoint_IsOUTReceived()));
184
185
186
187

				/* Read in the LED report from the host */
				uint8_t LEDStatus = Endpoint_Read_Byte();

188
				/* Process the incoming LED report */
189
190
191
				ProcessLEDReport(LEDStatus);
			
				/* Clear the endpoint data */
192
				Endpoint_ClearOUT();
193

194
				/* Acknowledge status stage */
195
				while (!(Endpoint_IsINReady()));
196
				Endpoint_ClearIN();
197
198
199
200
			}
			
			break;
		case REQ_GetProtocol:
201
			if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
202
			{
203
				Endpoint_ClearSETUP();
204
205
206
207
208
				
				/* Write the current protocol flag to the host */
				Endpoint_Write_Byte(UsingReportProtocol);
				
				/* Send the flag to the host */
209
				Endpoint_ClearIN();
210

211
				/* Acknowledge status stage */
212
				while (!(Endpoint_IsOUTReceived()));
213
				Endpoint_ClearOUT();
214
215
216
217
			}
			
			break;
		case REQ_SetProtocol:
218
			if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
219
			{
220
				Endpoint_ClearSETUP();
221
222

				/* Set or clear the flag depending on what the host indicates that the current Protocol should be */
223
				UsingReportProtocol = (USB_ControlRequest.wValue != 0);
224

225
				/* Acknowledge status stage */
226
				while (!(Endpoint_IsINReady()));
227
				Endpoint_ClearIN();
228
229
230
231
			}
			
			break;
		case REQ_SetIdle:
232
			if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
233
			{
234
				Endpoint_ClearSETUP();
235
236
				
				/* Get idle period in MSB */
237
				IdleCount = (USB_ControlRequest.wValue >> 8);
238
				
239
				/* Acknowledge status stage */
240
				while (!(Endpoint_IsINReady()));
241
				Endpoint_ClearIN();
242
243
244
245
			}
			
			break;
		case REQ_GetIdle:
246
			if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
247
			{		
248
				Endpoint_ClearSETUP();
249
250
251
252
253
				
				/* Write the current idle duration to the host */
				Endpoint_Write_Byte(IdleCount);
				
				/* Send the flag to the host */
254
				Endpoint_ClearIN();
255
256

				/* Acknowledge status stage */
257
				while (!(Endpoint_IsOUTReceived()));
258
				Endpoint_ClearOUT();
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
			}

			break;
	}
}

/** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and increments the
 *  scheduler elapsed idle period counter when the host has set an idle period.
 */
ISR(TIMER0_COMPA_vect, ISR_BLOCK)
{
	/* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
	if (IdleMSRemaining)
	  IdleMSRemaining--;
}

/** Fills the given HID report data structure with the next HID report to send to the host.
 *
 *  \param ReportData  Pointer to a HID report data structure to be filled
 */
279
void CreateKeyboardReport(USB_KeyboardReport_Data_t* ReportData)
280
{
281
	uint8_t JoyStatus_LCL = Joystick_GetStatus();
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299

	/* Clear the report contents */
	memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));

	if (JoyStatus_LCL & JOY_UP)
	  ReportData->KeyCode[0] = 0x04; // A
	else if (JoyStatus_LCL & JOY_DOWN)
	  ReportData->KeyCode[0] = 0x05; // B

	if (JoyStatus_LCL & JOY_LEFT)
	  ReportData->KeyCode[0] = 0x06; // C
	else if (JoyStatus_LCL & JOY_RIGHT)
	  ReportData->KeyCode[0] = 0x07; // D

	if (JoyStatus_LCL & JOY_PRESS)
	  ReportData->KeyCode[0] = 0x08; // E
}

300
/** Processes a received LED report, and updates the board LEDs states to match.
301
 *
302
 *  \param LEDReport  LED status report from the host
303
304
305
 */
void ProcessLEDReport(uint8_t LEDReport)
{
306
	uint8_t LEDMask = LEDS_LED2;
307
308
309
310
311
312
313
314
315
316
317
318
319
320
	
	if (LEDReport & 0x01) // NUM Lock
	  LEDMask |= LEDS_LED1;
	
	if (LEDReport & 0x02) // CAPS Lock
	  LEDMask |= LEDS_LED3;

	if (LEDReport & 0x04) // SCROLL Lock
	  LEDMask |= LEDS_LED4;

	/* Set the status LEDs to the current Keyboard LED status */
	LEDs_SetAllLEDs(LEDMask);
}

321
/** Sends the next HID report to the host, via the keyboard data endpoint. */
322
void SendNextReport(void)
323
{
324
325
326
	static USB_KeyboardReport_Data_t PrevKeyboardReportData;
	USB_KeyboardReport_Data_t        KeyboardReportData;
	bool                             SendReport = true;
327
328
	
	/* Create the next keyboard report for transmission to the host */
329
	CreateKeyboardReport(&KeyboardReportData);
330
	
331
332
	/* Check to see if the report data has changed - if so a report MUST be sent */
	SendReport = (memcmp(&PrevKeyboardReportData, &KeyboardReportData, sizeof(USB_KeyboardReport_Data_t)) != 0);
333
	
334
335
	/* Save the current report data for later comparison to check for changes */
	PrevKeyboardReportData = KeyboardReportData;
336
337
338
339
340
341
342
343
344
345
346
	
	/* Check if the idle period is set and has elapsed */
	if ((IdleCount != HID_IDLE_CHANGESONLY) && (!(IdleMSRemaining)))
	{
		/* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
		IdleMSRemaining = (IdleCount << 2);
		
		/* Idle period is set and has elapsed, must send a report to the host */
		SendReport = true;
	}
	
347
348
349
	/* Select the Keyboard Report Endpoint */
	Endpoint_SelectEndpoint(KEYBOARD_EPNUM);

350
	/* Check if Keyboard Endpoint Ready for Read/Write and if we should send a new report */
351
	if (Endpoint_IsReadWriteAllowed() && SendReport)
352
353
354
	{
		/* Write Keyboard Report Data */
		Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(KeyboardReportData));
355
		
356
		/* Finalize the stream transfer to send the last packet */
357
		Endpoint_ClearIN();
358
359
360
361
	}
}

/** Reads the next LED status report from the host from the LED data endpoint, if one has been sent. */
362
void ReceiveNextReport(void)
363
364
365
366
{
	/* Select the Keyboard LED Report Endpoint */
	Endpoint_SelectEndpoint(KEYBOARD_LEDS_EPNUM);

367
368
369
370
371
372
373
374
	/* Check if Keyboard LED Endpoint contains a packet */
	if (Endpoint_IsOUTReceived())
	{
		/* Check to see if the packet contains data */
		if (Endpoint_IsReadWriteAllowed())
		{
			/* Read in the LED report from the host */
			uint8_t LEDReport = Endpoint_Read_Byte();
375

376
377
378
			/* Process the read LED report from the host */
			ProcessLEDReport(LEDReport);
		}
379

380
381
382
		/* Handshake the OUT Endpoint - clear endpoint and ready for next report */
		Endpoint_ClearOUT();
	}
383
384
}

385
386
387
/** Function to manage status updates to the user. This is done via LEDs on the given board, if available, but may be changed to
 *  log to a serial port, or anything else that is suitable for status updates.
 *
388
 *  \param CurrentStatus  Current status of the system, from the Keyboard_StatusCodes_t enum
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
 */
void UpdateStatus(uint8_t CurrentStatus)
{
	uint8_t LEDMask = LEDS_NO_LEDS;
	
	/* Set the LED mask to the appropriate LED mask based on the given status code */
	switch (CurrentStatus)
	{
		case Status_USBNotReady:
			LEDMask = (LEDS_LED1);
			break;
		case Status_USBEnumerating:
			LEDMask = (LEDS_LED1 | LEDS_LED2);
			break;
		case Status_USBReady:
			LEDMask = (LEDS_LED2 | LEDS_LED4);
			break;
	}
	
	/* Set the board LEDs to the new LED mask */
	LEDs_SetAllLEDs(LEDMask);
}

/** Function to manage HID report generation and transmission to the host, when in report mode. */
TASK(USB_Keyboard_Report)
{
415
416
	/* Check if the USB system is connected to a host */
	if (USB_IsConnected)
417
	{
418
419
		/* Send the next keypress report to the host */
		SendNextReport();
420
		
421
422
		/* Process the LED report sent from the host */
		ReceiveNextReport();
423
	}
424
}