Fixed minor issue with the RNDISEthernet demo DHCP protocol decoder routine using...
[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 successive 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 clock_prescale_set(clock_div_1);
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 /* Acknowledge status stage */
209 while (!(Endpoint_IsSetupOUTReceived()));
210 Endpoint_ClearSetupOUT();
211 }
212
213 break;
214 case REQ_SetProtocol:
215 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
216 {
217 /* Read in the wValue parameter containing the new protocol mode */
218 uint16_t wValue = Endpoint_Read_Word_LE();
219
220 Endpoint_ClearSetupReceived();
221
222 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
223 UsingReportProtocol = (wValue != 0x0000);
224
225 /* Acknowledge status stage */
226 while (!(Endpoint_IsSetupINReady()));
227 Endpoint_ClearSetupIN();
228 }
229
230 break;
231 case REQ_SetIdle:
232 if (bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
233 {
234 /* Read in the wValue parameter containing the idle period */
235 uint16_t wValue = Endpoint_Read_Word_LE();
236
237 Endpoint_ClearSetupReceived();
238
239 /* Get idle period in MSB */
240 IdleCount = (wValue >> 8);
241
242 /* Acknowledge status stage */
243 while (!(Endpoint_IsSetupINReady()));
244 Endpoint_ClearSetupIN();
245 }
246
247 break;
248 case REQ_GetIdle:
249 if (bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
250 {
251 Endpoint_ClearSetupReceived();
252
253 /* Write the current idle duration to the host */
254 Endpoint_Write_Byte(IdleCount);
255
256 /* Send the flag to the host */
257 Endpoint_ClearSetupIN();
258
259 /* Acknowledge status stage */
260 while (!(Endpoint_IsSetupOUTReceived()));
261 Endpoint_ClearSetupOUT();
262 }
263
264 break;
265 }
266 }
267
268 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and decrements the counter indicating
269 * the number of milliseconds left to idle (not send the host reports) if the device has been instructed to idle
270 * by the host via a SetIdle class specific request.
271 */
272 ISR(TIMER0_COMPA_vect, ISR_BLOCK)
273 {
274 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
275 if (IdleMSRemaining)
276 IdleMSRemaining--;
277
278 if (KeyDelayRemaining)
279 KeyDelayRemaining--;
280 }
281
282 /** Constructs a keyboard report indicating the currently pressed keyboard keys to the host.
283 *
284 * \param ReportData Pointer to a USB_KeyboardReport_Data_t report structure where the resulting report should
285 * be stored
286 *
287 * \return Boolean true if the current report is different to the previous report, false otherwise
288 */
289 bool GetNextReport(USB_KeyboardReport_Data_t* ReportData)
290 {
291 static bool OddReport = false;
292 static bool MustRelease = false;
293
294 BitBuffer_t* Buffer = NULL;
295
296 /* Clear the report contents */
297 memset(ReportData, 0, sizeof(USB_KeyboardReport_Data_t));
298
299 /* Get the next non-empty track data buffer */
300 if (Track1Data.Elements)
301 Buffer = &Track1Data;
302 else if (Track2Data.Elements)
303 Buffer = &Track2Data;
304 else if (Track3Data.Elements)
305 Buffer = &Track3Data;
306
307 if (Buffer != NULL)
308 {
309 /* Toggle the odd report number indicator */
310 OddReport = !OddReport;
311
312 /* Set the flag indicating that a null report must eventually be sent to release all pressed keys */
313 MustRelease = true;
314
315 /* Only send the next key on odd reports, so that they are interspersed with null reports to release keys */
316 if (OddReport)
317 {
318 /* Set the report key code to the key code for the next data bit */
319 ReportData->KeyCode = BitBuffer_GetNextBit(Buffer) ? KEY_1 : KEY_0;
320
321 /* If buffer is now empty, a new line must be sent instead of the terminating bit */
322 if (!(Buffer->Elements))
323 {
324 /* Set the keycode to the code for an enter key press */
325 ReportData->KeyCode = KEY_ENTER;
326 }
327 }
328
329 return true;
330 }
331 else if (MustRelease)
332 {
333 /* Leave key code to null (0), to release all pressed keys */
334 return true;
335 }
336
337 return false;
338 }
339
340 /** Task to read out data from inserted magnetic cards and place the separate track data into their respective
341 * data buffers for later sending to the host as keyboard key presses.
342 */
343 TASK(Magstripe_Read)
344 {
345 /* Arrays to hold the buffer pointers, clock and data bit masks for the separate card tracks */
346 const struct
347 {
348 BitBuffer_t* Buffer;
349 uint8_t ClockMask;
350 uint8_t DataMask;
351 } TrackInfo[] = {{&Track1Data, MAG_T1_CLOCK, MAG_T1_DATA},
352 {&Track2Data, MAG_T2_CLOCK, MAG_T2_DATA},
353 {&Track3Data, MAG_T3_CLOCK, MAG_T3_DATA}};
354
355 /* Previous magnetic card control line' status, for later comparison */
356 uint8_t Magstripe_Prev = 0;
357
358 /* Buffered current card reader control line' status */
359 uint8_t Magstripe_LCL = Magstripe_GetStatus();
360
361 /* Exit the task early if no card is present in the reader */
362 if (!(Magstripe_LCL & MAG_CARDPRESENT))
363 return;
364
365 /* Read out card data while a card is present */
366 while (Magstripe_LCL & MAG_CARDPRESENT)
367 {
368 /* Read out the next bit for each track of the card */
369 for (uint8_t Track = 0; Track < 3; Track++)
370 {
371 /* Current data line status for the current card track */
372 bool DataLevel = ((Magstripe_LCL & TrackInfo[Track].DataMask) != 0);
373
374 /* Current clock line status for the current card track */
375 bool ClockLevel = ((Magstripe_LCL & TrackInfo[Track].ClockMask) != 0);
376
377 /* Current track clock transition check */
378 bool ClockChanged = (((Magstripe_LCL ^ Magstripe_Prev) & TrackInfo[Track].ClockMask) != 0);
379
380 /* Sample the next bit on the falling edge of the track's clock line, store key code into the track's buffer */
381 if (ClockLevel && ClockChanged)
382 BitBuffer_StoreNextBit(TrackInfo[Track].Buffer, DataLevel);
383 }
384
385 /* Retain the current card reader control line states for later edge detection */
386 Magstripe_Prev = Magstripe_LCL;
387
388 /* Retrieve the new card reader control line states */
389 Magstripe_LCL = Magstripe_GetStatus();
390 }
391
392 /* Add terminators to the end of each track buffer */
393 BitBuffer_StoreNextBit(&Track1Data, 0);
394 BitBuffer_StoreNextBit(&Track2Data, 0);
395 BitBuffer_StoreNextBit(&Track3Data, 0);
396 }
397
398 /** Task for the magnetic card reading and keyboard report generation. This task waits until a card is inserted,
399 * then reads off the card data and sends it to the host as a series of keyboard key presses via keyboard reports.
400 */
401 TASK(USB_Keyboard_Report)
402 {
403 USB_KeyboardReport_Data_t KeyboardReportData;
404 bool SendReport = false;
405
406 /* Check if the USB system is connected to a host */
407 if (USB_IsConnected)
408 {
409 /* Select the Keyboard Report Endpoint */
410 Endpoint_SelectEndpoint(KEYBOARD_EPNUM);
411
412 /* Check if Keyboard Endpoint Ready for Read/Write */
413 if (Endpoint_ReadWriteAllowed())
414 {
415 /* Only fetch the next key to send once the period between key presses has elapsed */
416 if (!(KeyDelayRemaining))
417 {
418 /* Create the next keyboard report for transmission to the host */
419 SendReport = GetNextReport(&KeyboardReportData);
420 }
421
422 /* Check if the idle period is set and has elapsed */
423 if (IdleCount && !(IdleMSRemaining))
424 {
425 /* Idle period elapsed, indicate that a report must be sent */
426 SendReport = true;
427
428 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
429 IdleMSRemaining = (IdleCount << 2);
430 }
431
432 /* Write the keyboard report if a report is to be sent to the host */
433 if (SendReport)
434 {
435 /* Write Keyboard Report Data */
436 Endpoint_Write_Stream_LE(&KeyboardReportData, sizeof(USB_KeyboardReport_Data_t));
437
438 /* Finalize the stream transfer to send the last packet */
439 Endpoint_ClearCurrentBank();
440
441 /* Reset the key delay period counter */
442 KeyDelayRemaining = 2;
443 }
444 }
445 }
446 }