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