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 sucessive 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         SetSystemClockPrescaler(0); 
  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(); 
 210                 case REQ_SetProtocol
: 
 211                         if (bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 213                                 /* Read in the wValue parameter containing the new protocol mode */ 
 214                                 uint16_t wValue 
= Endpoint_Read_Word_LE(); 
 216                                 Endpoint_ClearSetupReceived(); 
 218                                 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */ 
 219                                 UsingReportProtocol 
= (wValue 
!= 0x0000); 
 221                                 /* Send an empty packet to acknowedge the command */ 
 222                                 Endpoint_ClearSetupIN(); 
 227                         if (bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 229                                 /* Read in the wValue parameter containing the idle period */ 
 230                                 uint16_t wValue 
= Endpoint_Read_Word_LE(); 
 232                                 Endpoint_ClearSetupReceived(); 
 234                                 /* Get idle period in MSB */ 
 235                                 IdleCount 
= (wValue 
>> 8); 
 237                                 /* Send an empty packet to acknowedge the command */ 
 238                                 Endpoint_ClearSetupIN(); 
 243                         if (bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 245                                 Endpoint_ClearSetupReceived(); 
 247                                 /* Write the current idle duration to the host */ 
 248                                 Endpoint_Write_Byte(IdleCount
); 
 250                                 /* Send the flag to the host */ 
 251                                 Endpoint_ClearSetupIN(); 
 258 /** ISR for the timer 0 compare vector. This ISR fires once each millisecond, and decrements the counter indicating 
 259  *  the number of milliseconds left to idle (not send the host reports) if the device has been instructed to idle 
 260  *  by the host via a SetIdle class specific request. 
 262 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
) 
 264         /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */ 
 268         if (KeyDelayRemaining
) 
 272 /** Constructs a keyboard report indicating the currently pressed keyboard keys to the host. 
 274  *  \param ReportData  Pointer to a USB_KeyboardReport_Data_t report structure where the resulting report should 
 277  *  \return Boolean true if the current report is different to the previous report, false otherwise 
 279 bool GetNextReport(USB_KeyboardReport_Data_t
* ReportData
) 
 281         static bool OddReport   
= false; 
 282         static bool MustRelease 
= false; 
 284         BitBuffer_t
* Buffer     
= NULL
; 
 286         /* Clear the report contents */ 
 287         memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
)); 
 289         /* Get the next non-empty track data buffer */ 
 290         if (Track1Data
.Elements
) 
 291           Buffer 
= &Track1Data
; 
 292         else if (Track2Data
.Elements
) 
 293           Buffer 
= &Track2Data
;                  
 294         else if (Track3Data
.Elements
) 
 295           Buffer 
= &Track3Data
; 
 299                 /* Toggle the odd report number indicator */ 
 300                 OddReport   
= !OddReport
; 
 302                 /* Set the flag indicating that a null report must eventually be sent to release all pressed keys */ 
 305                 /* Only send the next key on odd reports, so that they are interpersed with null reports to release keys */ 
 308                         /* Set the report key code to the key code for the next data bit */ 
 309                         ReportData
->KeyCode
[0] = BitBuffer_GetNextBit(Buffer
) ? KEY_1 
: KEY_0
; 
 311                         /* If buffer is now empty, a new line must be sent instead of the terminating bit */ 
 312                         if (!(Buffer
->Elements
)) 
 314                                 /* Set the keycode to the code for an enter key press */ 
 315                                 ReportData
->KeyCode
[0] = KEY_ENTER
;                              
 321         else if (MustRelease
) 
 323                 /* Leave key code to null (0), to release all pressed keys */ 
 330 /** Task to read out data from inserted magnetic cards and place the seperate track data into their respective 
 331  *  data buffers for later sending to the host as keyboard key presses. 
 335         /* Arrays to hold the buffer pointers, clock and data bit masks for the seperate card tracks */ 
 341         } TrackInfo
[] = {{&Track1Data
, MAG_T1_CLOCK
, MAG_T1_DATA
}, 
 342                          {&Track2Data
, MAG_T2_CLOCK
, MAG_T2_DATA
}, 
 343                          {&Track3Data
, MAG_T3_CLOCK
, MAG_T3_DATA
}}; 
 345         /* Previous magnetic card control line' status, for later comparison */ 
 346         uint8_t Magstripe_Prev 
= 0; 
 348         /* Buffered current card reader control line' status */ 
 349         uint8_t Magstripe_LCL  
= Magstripe_GetStatus(); 
 351         /* Exit the task early if no card is present in the reader */ 
 352         if (!(Magstripe_LCL 
& MAG_CARDPRESENT
)) 
 355         /* Read out card data while a card is present */ 
 356         while (Magstripe_LCL 
& MAG_CARDPRESENT
) 
 358                 /* Read out the next bit for each track of the card */ 
 359                 for (uint8_t Track 
= 0; Track 
< 3; Track
++) 
 361                         /* Current data line status for the current card track */ 
 362                         bool DataLevel    
= ((Magstripe_LCL 
& TrackInfo
[Track
].DataMask
) != 0); 
 364                         /* Current clock line status for the current card track */ 
 365                         bool ClockLevel   
= ((Magstripe_LCL 
& TrackInfo
[Track
].ClockMask
) != 0); 
 367                         /* Current track clock transition check */ 
 368                         bool ClockChanged 
= (((Magstripe_LCL 
^ Magstripe_Prev
) & TrackInfo
[Track
].ClockMask
) != 0); 
 370                         /* Sample the next bit on the falling edge of the track's clock line, store key code into the track's buffer */ 
 371                         if (ClockLevel 
&& ClockChanged
) 
 372                           BitBuffer_StoreNextBit(TrackInfo
[Track
].Buffer
, DataLevel
); 
 375                 /* Retain the current card reader control line states for later edge detection */ 
 376                 Magstripe_Prev 
= Magstripe_LCL
; 
 378                 /* Retrieve the new card reader control line states */ 
 379                 Magstripe_LCL  
= Magstripe_GetStatus(); 
 382         /* Add terminators to the end of each track buffer */ 
 383         BitBuffer_StoreNextBit(&Track1Data
, 0); 
 384         BitBuffer_StoreNextBit(&Track2Data
, 0); 
 385         BitBuffer_StoreNextBit(&Track3Data
, 0); 
 388 /** Task for the magnetic card reading and keyboard report generation. This task waits until a card is inserted, 
 389  *  then reads off the card data and sends it to the host as a series of keyboard keypresses via keyboard reports. 
 391 TASK(USB_Keyboard_Report
) 
 393         USB_KeyboardReport_Data_t KeyboardReportData
; 
 394         bool                      SendReport 
= false; 
 396         /* Check if the USB system is connected to a host */ 
 399                 /* Select the Keyboard Report Endpoint */ 
 400                 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
); 
 402                 /* Check if Keyboard Endpoint Ready for Read/Write */ 
 403                 if (Endpoint_ReadWriteAllowed()) 
 405                         /* Only fetch the next key to send once the period between key presses has elapsed */ 
 406                         if (!(KeyDelayRemaining
)) 
 408                                 /* Create the next keyboard report for transmission to the host */ 
 409                                 SendReport 
= GetNextReport(&KeyboardReportData
); 
 412                         /* Check if the idle period is set and has elapsed */ 
 413                         if (IdleCount 
&& !(IdleMSRemaining
)) 
 415                                 /* Idle period elapsed, indicate that a report must be sent */ 
 418                                 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */ 
 419                                 IdleMSRemaining 
= (IdleCount 
<< 2); 
 422                         /* Write the keyboard report if a report is to be sent to the host */ 
 425                                 /* Write Keyboard Report Data */ 
 426                                 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
)); 
 428                                 /* Finalize the stream transfer to send the last packet */ 
 429                                 Endpoint_ClearCurrentBank(); 
 431                                 /* Reset the key delay period counter */ 
 432                                 KeyDelayRemaining 
= 2;