Fixed interrupt driven HID device demos not clearing the interrupt flags in all circu...
[pub/USBasp.git] / Projects / Magstripe / Magstripe.c
1 /*
2 LUFA Library
3 Copyright (C) Dean Camera, 2009.
4
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
7 */
8
9 /*
10 Copyright 2009 Denver Gingerich (denver [at] ossguy [dot] com)
11 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
12
13 Permission to use, copy, modify, and distribute this software
14 and its documentation for any purpose and without fee is hereby
15 granted, provided that the above copyright notice appear in all
16 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 MagStripe application. This file contains the code which drives
35 * the USB keyboard interface from the magnetic card stripe reader device.
36 */
37
38 #include "Magstripe.h"
39
40 /* Project Tags, for reading out using the ButtLoad project */
41 BUTTLOADTAG(ProjName, "Magstripe Reader");
42 BUTTLOADTAG(BuildTime, __TIME__);
43 BUTTLOADTAG(BuildDate, __DATE__);
44 BUTTLOADTAG(LUFAVersion, "LUFA V" LUFA_VERSION_STRING);
45
46 /* Scheduler Task List */
47 TASK_LIST
48 {
49 { Task: USB_USBTask , TaskStatus: TASK_STOP },
50 { Task: USB_Keyboard_Report , TaskStatus: TASK_STOP },
51 { Task: Magstripe_Read , TaskStatus: TASK_STOP },
52 };
53
54 /* Global Variables */
55 /** Indicates if the device is using Report Protocol mode, instead of Boot Protocol mode. Boot Protocol mode
56 * is a special reporting mode used by compatible PC BIOS to support USB keyboards before a full OS and USB
57 * driver has been loaded, by using predefined report structures indicated in the USB HID standard.
58 */
59 bool UsingReportProtocol = true;
60
61 /** Total idle period in milliseconds set by the host via a SetIdle request, used to silence the report endpoint
62 * until the report data changes or the idle period elapsed. Generally used to implement hardware key repeats, or
63 * by some BIOS to reduce the number of reports when in Boot Protocol mode.
64 */
65 uint8_t IdleCount = 0;
66
67 /** Milliseconds remaining counter for the HID class SetIdle and GetIdle requests, used to silence the report
68 * endpoint for an amount of time indicated by the host or until the report changes.
69 */
70 uint16_t IdleMSRemaining = 0;
71
72 /** Circular buffer to hold the read bits from track 1 of the inserted magnetic card. */
73 BitBuffer_t Track1Data;
74
75 /** Circular buffer to hold the read bits from track 2 of the inserted magnetic card. */
76 BitBuffer_t Track2Data;
77
78 /** Circular buffer to hold the read bits from track 3 of the inserted magnetic card. */
79 BitBuffer_t Track3Data;
80
81 /** Delay counter between sucessive key strokes. This is to prevent the OS from ignoring multiple keys in a short
82 * period of time due to key repeats. Two milliseconds works for most OSes.
83 */
84 uint8_t KeyDelayRemaining;
85
86
87 /** Main program entry point. This routine configures the hardware required by the application, then
88 * starts the scheduler to run the application tasks.
89 */
90 int main(void)
91 {
92 /* Disable watchdog if enabled by bootloader/fuses */
93 MCUSR &= ~(1 << WDRF);
94 wdt_disable();
95
96 /* Disable Clock Division */
97 SetSystemClockPrescaler(0);
98
99 /* Hardware Initialization */
100 Magstripe_Init();
101
102 /* Buffer Initialization */
103 BitBuffer_Init(&Track1Data);
104 BitBuffer_Init(&Track2Data);
105 BitBuffer_Init(&Track3Data);
106
107 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
108 OCR0A = 0xFA;
109 TCCR0A = (1 << WGM01);
110 TCCR0B = ((1 << CS01) | (1 << CS00));
111 TIMSK0 = (1 << OCIE0A);
112
113 /* Initialize Scheduler so that it can be used */
114 Scheduler_Init();
115
116 /* Initialize USB Subsystem */
117 USB_Init();
118
119 /* Scheduling - routine never returns, so put this last in the main function */
120 Scheduler_Start();
121 }
122
123 /** Event handler for the USB_Connect event. This starts the USB task. */
124 EVENT_HANDLER(USB_Connect)
125 {
126 /* Start USB management task */
127 Scheduler_SetTaskMode(USB_USBTask, TASK_RUN);
128 }
129
130 /** Event handler for the USB_Disconnect event. This stops the USB and keyboard report tasks. */
131 EVENT_HANDLER(USB_Disconnect)
132 {
133 /* Stop running keyboard reporting, card reading and USB management tasks */
134 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_STOP);
135 Scheduler_SetTaskMode(USB_USBTask, TASK_STOP);
136 Scheduler_SetTaskMode(Magstripe_Read, TASK_STOP);
137 }
138
139 /** Event handler for the USB_ConfigurationChanged event. This configures the device's endpoints ready
140 * to relay reports to the host, and starts the keyboard report task.
141 */
142 EVENT_HANDLER(USB_ConfigurationChanged)
143 {
144 /* Setup Keyboard Keycode Report Endpoint */
145 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM, EP_TYPE_INTERRUPT,
146 ENDPOINT_DIR_IN, KEYBOARD_EPSIZE,
147 ENDPOINT_BANK_SINGLE);
148
149 /* Default to report protocol on connect */
150 UsingReportProtocol = true;
151
152 /* Start Keyboard reporting and card reading tasks */
153 Scheduler_SetTaskMode(USB_Keyboard_Report, TASK_RUN);
154 Scheduler_SetTaskMode(Magstripe_Read, TASK_RUN);
155 }
156
157 /** Event handler for the USB_UnhandledControlPacket event. This is used to catch standard and class specific
158 * control requests that are not handled internally by the USB library, so that they can be handled appropriately
159 * for the application.
160 */
161 EVENT_HANDLER(USB_UnhandledControlPacket)
162 {
163 /* Handle HID Class specific requests */
164 switch (bRequest)
165 {
166 case REQ_GetReport:
167 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
168 {
169 USB_KeyboardReport_Data_t KeyboardReportData;
170
171 /* Create the next keyboard report for transmission to the host */
172 GetNextReport(&KeyboardReportData);
173
174 /* Ignore report type and ID number value */
175 Endpoint_Discard_Word();
176
177 /* Ignore unused Interface number value */
178 Endpoint_Discard_Word();
179
180 /* Read in the number of bytes in the report to send to the host */
181 uint16_t wLength = Endpoint_Read_Word_LE();
182
183 /* If trying to send more bytes than exist to the host, clamp the value at the report size */
184 if (wLength > sizeof(KeyboardReportData))
185 wLength = sizeof(KeyboardReportData);
186
187 Endpoint_ClearSetupReceived();
188
189 /* Write the report data to the control endpoint */
190 Endpoint_Write_Control_Stream_LE(&KeyboardReportData, wLength);
191
192 /* Finalize the stream transfer to send the last packet or clear the host abort */
193 Endpoint_ClearSetupOUT();
194 }
195
196 break;
197 case REQ_GetProtocol:
198 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
199 {
200 Endpoint_ClearSetupReceived();
201
202 /* Write the current protocol flag to the host */
203 Endpoint_Write_Byte(UsingReportProtocol);
204
205 /* Send the flag to the host */
206 Endpoint_ClearSetupIN();
207 }
208
209 break;
210 case REQ_SetProtocol:
211 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
212 {
213 /* Read in the wValue parameter containing the new protocol mode */
214 uint16_t wValue = Endpoint_Read_Word_LE();
215
216 Endpoint_ClearSetupReceived();
217
218 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
219 UsingReportProtocol = (wValue != 0x0000);
220
221 /* Send an empty packet to acknowedge the command */
222 Endpoint_ClearSetupIN();
223 }
224
225 break;
226 case REQ_SetIdle:
227 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
228 {
229 /* Read in the wValue parameter containing the idle period */
230 uint16_t wValue = Endpoint_Read_Word_LE();
231
232 Endpoint_ClearSetupReceived();
233
234 /* Get idle period in MSB */
235 IdleCount = (wValue >> 8);
236
237 /* Send an empty packet to acknowedge the command */
238 Endpoint_ClearSetupIN();
239 }
240
241 break;
242 case REQ_GetIdle:
243 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
244 {
245 Endpoint_ClearSetupReceived();
246
247 /* Write the current idle duration to the host */
248 Endpoint_Write_Byte(IdleCount);
249
250 /* Send the flag to the host */
251 Endpoint_ClearSetupIN();
252 }
253
254 break;
255 }
256 }
257
258 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and decrements the counter indicating
259 * the number of milliseconds left to idle (not send the host reports) if the device has been instructed to idle
260 * by the host via a SetIdle class specific request.
261 */
262 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
263 {
264 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
265 if (IdleMSRemaining)
266 IdleMSRemaining--;
267
268 if (KeyDelayRemaining)
269 KeyDelayRemaining--;
270 }
271
272 /** Constructs a keyboard report indicating the currently pressed keyboard keys to the host.
273 *
274 * \param ReportData Pointer to a USB_KeyboardReport_Data_t report structure where the resulting report should
275 * be stored
276 *
277 * \return Boolean true if the current report is different to the previous report, false otherwise
278 */
279 bool GetNextReport(USB_KeyboardReport_Data_t* ReportData)
280 {
281 static bool OddReport = false;
282 static bool MustRelease = false;
283
284 BitBuffer_t* Buffer = NULL;
285
286 /* Clear the report contents */
287 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
288
289 /* Get the next non-empty track data buffer */
290 if (Track1Data.Elements)
291 Buffer = &Track1Data;
292 else if (Track2Data.Elements)
293 Buffer = &Track2Data;
294 else if (Track3Data.Elements)
295 Buffer = &Track3Data;
296
297 if (Buffer != NULL)
298 {
299 /* Toggle the odd report number indicator */
300 OddReport = !OddReport;
301
302 /* Set the flag indicating that a null report must eventually be sent to release all pressed keys */
303 MustRelease = true;
304
305 /* Only send the next key on odd reports, so that they are interpersed with null reports to release keys */
306 if (OddReport)
307 {
308 /* Set the report key code to the key code for the next data bit */
309 ReportData->KeyCode[0] = BitBuffer_GetNextBit(Buffer) ? KEY_1 : KEY_0;
310
311 /* If buffer is now empty, a new line must be sent instead of the terminating bit */
312 if (!(Buffer->Elements))
313 {
314 /* Set the keycode to the code for an enter key press */
315 ReportData->KeyCode[0] = KEY_ENTER;
316 }
317 }
318
319 return true;
320 }
321 else if (MustRelease)
322 {
323 /* Leave key code to null (0), to release all pressed keys */
324 return true;
325 }
326
327 return false;
328 }
329
330 /** Task to read out data from inserted magnetic cards and place the seperate track data into their respective
331 * data buffers for later sending to the host as keyboard key presses.
332 */
333 TASK(Magstripe_Read)
334 {
335 /* Arrays to hold the buffer pointers, clock and data bit masks for the seperate card tracks */
336 const struct
337 {
338 BitBuffer_t* Buffer;
339 uint8_t ClockMask;
340 uint8_t DataMask;
341 } TrackInfo[] = {{&Track1Data, MAG_T1_CLOCK, MAG_T1_DATA},
342 {&Track2Data, MAG_T2_CLOCK, MAG_T2_DATA},
343 {&Track3Data, MAG_T3_CLOCK, MAG_T3_DATA}};
344
345 /* Previous magnetic card control line' status, for later comparison */
346 uint8_t Magstripe_Prev = 0;
347
348 /* Buffered current card reader control line' status */
349 uint8_t Magstripe_LCL = Magstripe_GetStatus();
350
351 /* Exit the task early if no card is present in the reader */
352 if (!(Magstripe_LCL & MAG_CARDPRESENT))
353 return;
354
355 /* Read out card data while a card is present */
356 while (Magstripe_LCL & MAG_CARDPRESENT)
357 {
358 /* Read out the next bit for each track of the card */
359 for (uint8_t Track = 0; Track < 3; Track++)
360 {
361 /* Current data line status for the current card track */
362 bool DataLevel = ((Magstripe_LCL & TrackInfo[Track].DataMask) != 0);
363
364 /* Current clock line status for the current card track */
365 bool ClockLevel = ((Magstripe_LCL & TrackInfo[Track].ClockMask) != 0);
366
367 /* Current track clock transition check */
368 bool ClockChanged = (((Magstripe_LCL ^ Magstripe_Prev) & TrackInfo[Track].ClockMask) != 0);
369
370 /* Sample the next bit on the falling edge of the track's clock line, store key code into the track's buffer */
371 if (ClockLevel && ClockChanged)
372 BitBuffer_StoreNextBit(TrackInfo[Track].Buffer, DataLevel);
373 }
374
375 /* Retain the current card reader control line states for later edge detection */
376 Magstripe_Prev = Magstripe_LCL;
377
378 /* Retrieve the new card reader control line states */
379 Magstripe_LCL = Magstripe_GetStatus();
380 }
381
382 /* Add terminators to the end of each track buffer */
383 BitBuffer_StoreNextBit(&Track1Data, 0);
384 BitBuffer_StoreNextBit(&Track2Data, 0);
385 BitBuffer_StoreNextBit(&Track3Data, 0);
386 }
387
388 /** Task for the magnetic card reading and keyboard report generation. This task waits until a card is inserted,
389 * then reads off the card data and sends it to the host as a series of keyboard keypresses via keyboard reports.
390 */
391 TASK(USB_Keyboard_Report)
392 {
393 USB_KeyboardReport_Data_t KeyboardReportData;
394 bool SendReport = false;
395
396 /* Check if the USB system is connected to a host */
397 if (USB_IsConnected)
398 {
399 /* Select the Keyboard Report Endpoint */
400 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
401
402 /* Check if Keyboard Endpoint Ready for Read/Write */
403 if (Endpoint_ReadWriteAllowed())
404 {
405 /* Only fetch the next key to send once the period between key presses has elapsed */
406 if (!(KeyDelayRemaining))
407 {
408 /* Create the next keyboard report for transmission to the host */
409 SendReport = GetNextReport(&KeyboardReportData);
410 }
411
412 /* Check if the idle period is set and has elapsed */
413 if (IdleCount && !(IdleMSRemaining))
414 {
415 /* Idle period elapsed, indicate that a report must be sent */
416 SendReport = true;
417
418 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
419 IdleMSRemaining = (IdleCount << 2);
420 }
421
422 /* Write the keyboard report if a report is to be sent to the host */
423 if (SendReport)
424 {
425 /* Write Keyboard Report Data */
426 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(USB_KeyboardReport_Data_t));
427
428 /* Finalize the stream transfer to send the last packet */
429 Endpoint_ClearCurrentBank();
430
431 /* Reset the key delay period counter */
432 KeyDelayRemaining = 2;
433 }
434 }
435 }
436 }