3 Copyright (C) Dean Camera, 2009.
5 dean [at] fourwalledcubicle [dot] com
6 www.fourwalledcubicle.com
10 Copyright 2009 Denver Gingerich (denver [at] ossguy [dot] com)
11 Copyright 2009 Dean Camera (dean [at] fourwalledcubicle [dot] com)
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.
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
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.
38 #include "Magstripe.h"
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
);
46 /* Scheduler Task List */
49 { Task
: USB_USBTask
, TaskStatus
: TASK_STOP
},
50 { Task
: USB_Keyboard_Report
, TaskStatus
: TASK_STOP
},
51 { Task
: Magstripe_Read
, TaskStatus
: TASK_STOP
},
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.
59 bool UsingReportProtocol
= true;
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.
65 uint8_t IdleCount
= 0;
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.
70 uint16_t IdleMSRemaining
= 0;
72 /** Circular buffer to hold the read bits from track 1 of the inserted magnetic card. */
73 BitBuffer_t Track1Data
;
75 /** Circular buffer to hold the read bits from track 2 of the inserted magnetic card. */
76 BitBuffer_t Track2Data
;
78 /** Circular buffer to hold the read bits from track 3 of the inserted magnetic card. */
79 BitBuffer_t Track3Data
;
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.
84 uint8_t KeyDelayRemaining
;
87 /** Main program entry point. This routine configures the hardware required by the application, then
88 * starts the scheduler to run the application tasks.
92 /* Disable watchdog if enabled by bootloader/fuses */
93 MCUSR
&= ~(1 << WDRF
);
96 /* Disable clock division */
97 clock_prescale_set(clock_div_1
);
99 /* Hardware Initialization */
102 /* Buffer Initialization */
103 BitBuffer_Init(&Track1Data
);
104 BitBuffer_Init(&Track2Data
);
105 BitBuffer_Init(&Track3Data
);
107 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
109 TCCR0A
= (1 << WGM01
);
110 TCCR0B
= ((1 << CS01
) | (1 << CS00
));
111 TIMSK0
= (1 << OCIE0A
);
113 /* Initialize Scheduler so that it can be used */
116 /* Initialize USB Subsystem */
119 /* Scheduling - routine never returns, so put this last in the main function */
123 /** Event handler for the USB_Connect event. This starts the USB task. */
124 EVENT_HANDLER(USB_Connect
)
126 /* Start USB management task */
127 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
130 /** Event handler for the USB_Disconnect event. This stops the USB and keyboard report tasks. */
131 EVENT_HANDLER(USB_Disconnect
)
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
);
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.
142 EVENT_HANDLER(USB_ConfigurationChanged
)
144 /* Setup Keyboard Keycode Report Endpoint */
145 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
,
146 ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
,
147 ENDPOINT_BANK_SINGLE
);
149 /* Default to report protocol on connect */
150 UsingReportProtocol
= true;
152 /* Start Keyboard reporting and card reading tasks */
153 Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_RUN
);
154 Scheduler_SetTaskMode(Magstripe_Read
, TASK_RUN
);
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.
161 EVENT_HANDLER(USB_UnhandledControlPacket
)
163 /* Handle HID Class specific requests */
167 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
169 USB_KeyboardReport_Data_t KeyboardReportData
;
171 /* Create the next keyboard report for transmission to the host */
172 GetNextReport(&KeyboardReportData
);
174 /* Ignore report type and ID number value */
175 Endpoint_Discard_Word();
177 /* Ignore unused Interface number value */
178 Endpoint_Discard_Word();
180 /* Read in the number of bytes in the report to send to the host */
181 uint16_t wLength
= Endpoint_Read_Word_LE();
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
);
187 Endpoint_ClearSetupReceived();
189 /* Write the report data to the control endpoint */
190 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, wLength
);
192 /* Finalize the stream transfer to send the last packet or clear the host abort */
193 Endpoint_ClearSetupOUT();
197 case REQ_GetProtocol
:
198 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
200 Endpoint_ClearSetupReceived();
202 /* Write the current protocol flag to the host */
203 Endpoint_Write_Byte(UsingReportProtocol
);
205 /* Send the flag to the host */
206 Endpoint_ClearSetupIN();
208 /* Acknowledge status stage */
209 while (!(Endpoint_IsSetupOUTReceived()));
210 Endpoint_ClearSetupOUT();
214 case REQ_SetProtocol
:
215 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
217 /* Read in the wValue parameter containing the new protocol mode */
218 uint16_t wValue
= Endpoint_Read_Word_LE();
220 Endpoint_ClearSetupReceived();
222 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
223 UsingReportProtocol
= (wValue
!= 0x0000);
225 /* Acknowledge status stage */
226 while (!(Endpoint_IsSetupINReady()));
227 Endpoint_ClearSetupIN();
232 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
234 /* Read in the wValue parameter containing the idle period */
235 uint16_t wValue
= Endpoint_Read_Word_LE();
237 Endpoint_ClearSetupReceived();
239 /* Get idle period in MSB */
240 IdleCount
= (wValue
>> 8);
242 /* Acknowledge status stage */
243 while (!(Endpoint_IsSetupINReady()));
244 Endpoint_ClearSetupIN();
249 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
251 Endpoint_ClearSetupReceived();
253 /* Write the current idle duration to the host */
254 Endpoint_Write_Byte(IdleCount
);
256 /* Send the flag to the host */
257 Endpoint_ClearSetupIN();
259 /* Acknowledge status stage */
260 while (!(Endpoint_IsSetupOUTReceived()));
261 Endpoint_ClearSetupOUT();
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.
272 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
274 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
278 if (KeyDelayRemaining
)
282 /** Constructs a keyboard report indicating the currently pressed keyboard keys to the host.
284 * \param ReportData Pointer to a USB_KeyboardReport_Data_t report structure where the resulting report should
287 * \return Boolean true if the current report is different to the previous report, false otherwise
289 bool GetNextReport(USB_KeyboardReport_Data_t
* ReportData
)
291 static bool OddReport
= false;
292 static bool MustRelease
= false;
294 BitBuffer_t
* Buffer
= NULL
;
296 /* Clear the report contents */
297 memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
));
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
;
309 /* Toggle the odd report number indicator */
310 OddReport
= !OddReport
;
312 /* Set the flag indicating that a null report must eventually be sent to release all pressed keys */
315 /* Only send the next key on odd reports, so that they are interspersed with null reports to release keys */
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
;
321 /* If buffer is now empty, a new line must be sent instead of the terminating bit */
322 if (!(Buffer
->Elements
))
324 /* Set the keycode to the code for an enter key press */
325 ReportData
->KeyCode
= KEY_ENTER
;
331 else if (MustRelease
)
333 /* Leave key code to null (0), to release all pressed keys */
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.
345 /* Arrays to hold the buffer pointers, clock and data bit masks for the separate card tracks */
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
}};
355 /* Previous magnetic card control line' status, for later comparison */
356 uint8_t Magstripe_Prev
= 0;
358 /* Buffered current card reader control line' status */
359 uint8_t Magstripe_LCL
= Magstripe_GetStatus();
361 /* Exit the task early if no card is present in the reader */
362 if (!(Magstripe_LCL
& MAG_CARDPRESENT
))
365 /* Read out card data while a card is present */
366 while (Magstripe_LCL
& MAG_CARDPRESENT
)
368 /* Read out the next bit for each track of the card */
369 for (uint8_t Track
= 0; Track
< 3; Track
++)
371 /* Current data line status for the current card track */
372 bool DataLevel
= ((Magstripe_LCL
& TrackInfo
[Track
].DataMask
) != 0);
374 /* Current clock line status for the current card track */
375 bool ClockLevel
= ((Magstripe_LCL
& TrackInfo
[Track
].ClockMask
) != 0);
377 /* Current track clock transition check */
378 bool ClockChanged
= (((Magstripe_LCL
^ Magstripe_Prev
) & TrackInfo
[Track
].ClockMask
) != 0);
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
);
385 /* Retain the current card reader control line states for later edge detection */
386 Magstripe_Prev
= Magstripe_LCL
;
388 /* Retrieve the new card reader control line states */
389 Magstripe_LCL
= Magstripe_GetStatus();
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);
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.
401 TASK(USB_Keyboard_Report
)
403 USB_KeyboardReport_Data_t KeyboardReportData
;
404 bool SendReport
= false;
406 /* Check if the USB system is connected to a host */
409 /* Select the Keyboard Report Endpoint */
410 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
);
412 /* Check if Keyboard Endpoint Ready for Read/Write */
413 if (Endpoint_ReadWriteAllowed())
415 /* Only fetch the next key to send once the period between key presses has elapsed */
416 if (!(KeyDelayRemaining
))
418 /* Create the next keyboard report for transmission to the host */
419 SendReport
= GetNextReport(&KeyboardReportData
);
422 /* Check if the idle period is set and has elapsed */
423 if (IdleCount
&& !(IdleMSRemaining
))
425 /* Idle period elapsed, indicate that a report must be sent */
428 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
429 IdleMSRemaining
= (IdleCount
<< 2);
432 /* Write the keyboard report if a report is to be sent to the host */
435 /* Write Keyboard Report Data */
436 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
));
438 /* Finalize the stream transfer to send the last packet */
439 Endpoint_ClearCurrentBank();
441 /* Reset the key delay period counter */
442 KeyDelayRemaining
= 2;