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