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 /* Scheduler Task List */
43 { Task
: USB_USBTask
, TaskStatus
: TASK_STOP
},
44 { Task
: USB_Keyboard_Report
, TaskStatus
: TASK_STOP
},
45 { Task
: Magstripe_Read
, TaskStatus
: TASK_STOP
},
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.
53 bool UsingReportProtocol
= true;
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.
59 uint8_t IdleCount
= 0;
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.
64 uint16_t IdleMSRemaining
= 0;
66 /** Circular buffer to hold the read bits from track 1 of the inserted magnetic card. */
67 BitBuffer_t Track1Data
;
69 /** Circular buffer to hold the read bits from track 2 of the inserted magnetic card. */
70 BitBuffer_t Track2Data
;
72 /** Circular buffer to hold the read bits from track 3 of the inserted magnetic card. */
73 BitBuffer_t Track3Data
;
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.
78 uint8_t KeyDelayRemaining
;
81 /** Main program entry point. This routine configures the hardware required by the application, then
82 * starts the scheduler to run the application tasks.
86 /* Disable watchdog if enabled by bootloader/fuses */
87 MCUSR
&= ~(1 << WDRF
);
90 /* Disable clock division */
91 clock_prescale_set(clock_div_1
);
93 /* Hardware Initialization */
96 /* Buffer Initialization */
97 BitBuffer_Init(&Track1Data
);
98 BitBuffer_Init(&Track2Data
);
99 BitBuffer_Init(&Track3Data
);
101 /* Millisecond timer initialization, with output compare interrupt enabled for the idle timing */
103 TCCR0A
= (1 << WGM01
);
104 TCCR0B
= ((1 << CS01
) | (1 << CS00
));
105 TIMSK0
= (1 << OCIE0A
);
107 /* Initialize Scheduler so that it can be used */
110 /* Initialize USB Subsystem */
113 /* Scheduling - routine never returns, so put this last in the main function */
117 /** Event handler for the USB_Connect event. This starts the USB task. */
118 EVENT_HANDLER(USB_Connect
)
120 /* Start USB management task */
121 Scheduler_SetTaskMode(USB_USBTask
, TASK_RUN
);
124 /** Event handler for the USB_Disconnect event. This stops the USB and keyboard report tasks. */
125 EVENT_HANDLER(USB_Disconnect
)
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
);
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.
136 EVENT_HANDLER(USB_ConfigurationChanged
)
138 /* Setup Keyboard Keycode Report Endpoint */
139 Endpoint_ConfigureEndpoint(KEYBOARD_EPNUM
, EP_TYPE_INTERRUPT
,
140 ENDPOINT_DIR_IN
, KEYBOARD_EPSIZE
,
141 ENDPOINT_BANK_SINGLE
);
143 /* Default to report protocol on connect */
144 UsingReportProtocol
= true;
146 /* Start Keyboard reporting and card reading tasks */
147 Scheduler_SetTaskMode(USB_Keyboard_Report
, TASK_RUN
);
148 Scheduler_SetTaskMode(Magstripe_Read
, TASK_RUN
);
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.
155 EVENT_HANDLER(USB_UnhandledControlPacket
)
157 /* Handle HID Class specific requests */
161 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
163 USB_KeyboardReport_Data_t KeyboardReportData
;
165 /* Create the next keyboard report for transmission to the host */
166 GetNextReport(&KeyboardReportData
);
168 /* Ignore report type and ID number value */
169 Endpoint_Discard_Word();
171 /* Ignore unused Interface number value */
172 Endpoint_Discard_Word();
174 /* Read in the number of bytes in the report to send to the host */
175 uint16_t wLength
= Endpoint_Read_Word_LE();
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
);
181 Endpoint_ClearControlSETUP();
183 /* Write the report data to the control endpoint */
184 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, wLength
);
186 /* Finalize the stream transfer to send the last packet or clear the host abort */
187 Endpoint_ClearControlOUT();
191 case REQ_GetProtocol
:
192 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
194 Endpoint_ClearControlSETUP();
196 /* Write the current protocol flag to the host */
197 Endpoint_Write_Byte(UsingReportProtocol
);
199 /* Send the flag to the host */
200 Endpoint_ClearControlIN();
202 /* Acknowledge status stage */
203 while (!(Endpoint_IsOUTReceived()));
204 Endpoint_ClearControlOUT();
208 case REQ_SetProtocol
:
209 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
211 /* Read in the wValue parameter containing the new protocol mode */
212 uint16_t wValue
= Endpoint_Read_Word_LE();
214 Endpoint_ClearControlSETUP();
216 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */
217 UsingReportProtocol
= (wValue
!= 0x0000);
219 /* Acknowledge status stage */
220 while (!(Endpoint_IsINReady()));
221 Endpoint_ClearControlIN();
226 if (bmRequestType
== (REQDIR_HOSTTODEVICE
| REQTYPE_CLASS
| REQREC_INTERFACE
))
228 /* Read in the wValue parameter containing the idle period */
229 uint16_t wValue
= Endpoint_Read_Word_LE();
231 Endpoint_ClearControlSETUP();
233 /* Get idle period in MSB */
234 IdleCount
= (wValue
>> 8);
236 /* Acknowledge status stage */
237 while (!(Endpoint_IsINReady()));
238 Endpoint_ClearControlIN();
243 if (bmRequestType
== (REQDIR_DEVICETOHOST
| REQTYPE_CLASS
| REQREC_INTERFACE
))
245 Endpoint_ClearControlSETUP();
247 /* Write the current idle duration to the host */
248 Endpoint_Write_Byte(IdleCount
);
250 /* Send the flag to the host */
251 Endpoint_ClearControlIN();
253 /* Acknowledge status stage */
254 while (!(Endpoint_IsOUTReceived()));
255 Endpoint_ClearControlOUT();
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.
266 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
)
268 /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */
272 if (KeyDelayRemaining
)
276 /** Constructs a keyboard report indicating the currently pressed keyboard keys to the host.
278 * \param ReportData Pointer to a USB_KeyboardReport_Data_t report structure where the resulting report should
281 * \return Boolean true if the current report is different to the previous report, false otherwise
283 bool GetNextReport(USB_KeyboardReport_Data_t
* ReportData
)
285 static bool OddReport
= false;
286 static bool MustRelease
= false;
288 BitBuffer_t
* Buffer
= NULL
;
290 /* Clear the report contents */
291 memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
));
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
;
303 /* Toggle the odd report number indicator */
304 OddReport
= !OddReport
;
306 /* Set the flag indicating that a null report must eventually be sent to release all pressed keys */
309 /* Only send the next key on odd reports, so that they are interspersed with null reports to release keys */
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
;
315 /* If buffer is now empty, a new line must be sent instead of the terminating bit */
316 if (!(Buffer
->Elements
))
318 /* Set the keycode to the code for an enter key press */
319 ReportData
->KeyCode
= KEY_ENTER
;
325 else if (MustRelease
)
327 /* Leave key code to null (0), to release all pressed keys */
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.
339 /* Arrays to hold the buffer pointers, clock and data bit masks for the separate card tracks */
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
}};
349 /* Previous magnetic card control line' status, for later comparison */
350 uint8_t Magstripe_Prev
= 0;
352 /* Buffered current card reader control line' status */
353 uint8_t Magstripe_LCL
= Magstripe_GetStatus();
355 /* Exit the task early if no card is present in the reader */
356 if (!(Magstripe_LCL
& MAG_CARDPRESENT
))
359 /* Read out card data while a card is present */
360 while (Magstripe_LCL
& MAG_CARDPRESENT
)
362 /* Read out the next bit for each track of the card */
363 for (uint8_t Track
= 0; Track
< 3; Track
++)
365 /* Current data line status for the current card track */
366 bool DataLevel
= ((Magstripe_LCL
& TrackInfo
[Track
].DataMask
) != 0);
368 /* Current clock line status for the current card track */
369 bool ClockLevel
= ((Magstripe_LCL
& TrackInfo
[Track
].ClockMask
) != 0);
371 /* Current track clock transition check */
372 bool ClockChanged
= (((Magstripe_LCL
^ Magstripe_Prev
) & TrackInfo
[Track
].ClockMask
) != 0);
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
);
379 /* Retain the current card reader control line states for later edge detection */
380 Magstripe_Prev
= Magstripe_LCL
;
382 /* Retrieve the new card reader control line states */
383 Magstripe_LCL
= Magstripe_GetStatus();
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);
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.
395 TASK(USB_Keyboard_Report
)
397 USB_KeyboardReport_Data_t KeyboardReportData
;
398 bool SendReport
= false;
400 /* Check if the USB system is connected to a host */
403 /* Select the Keyboard Report Endpoint */
404 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
);
406 /* Check if Keyboard Endpoint Ready for Read/Write */
407 if (Endpoint_IsReadWriteAllowed())
409 /* Only fetch the next key to send once the period between key presses has elapsed */
410 if (!(KeyDelayRemaining
))
412 /* Create the next keyboard report for transmission to the host */
413 SendReport
= GetNextReport(&KeyboardReportData
);
416 /* Check if the idle period is set and has elapsed */
417 if (IdleCount
&& !(IdleMSRemaining
))
419 /* Idle period elapsed, indicate that a report must be sent */
422 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */
423 IdleMSRemaining
= (IdleCount
<< 2);
426 /* Write the keyboard report if a report is to be sent to the host */
429 /* Write Keyboard Report Data */
430 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
));
432 /* Finalize the stream transfer to send the last packet */
435 /* Reset the key delay period counter */
436 KeyDelayRemaining
= 2;