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 */ 
 158         switch (USB_ControlRequest
.bRequest
) 
 161                         if (USB_ControlRequest
.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                                 Endpoint_ClearSETUP(); 
 170                                 /* Write the report data to the control endpoint */ 
 171                                 Endpoint_Write_Control_Stream_LE(&KeyboardReportData
, sizeof(KeyboardReportData
)); 
 173                                 /* Finalize the stream transfer to send the last packet or clear the host abort */ 
 178                 case REQ_GetProtocol
: 
 179                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 181                                 Endpoint_ClearSETUP(); 
 183                                 /* Write the current protocol flag to the host */ 
 184                                 Endpoint_Write_Byte(UsingReportProtocol
); 
 186                                 /* Send the flag to the host */ 
 189                                 /* Acknowledge status stage */ 
 190                                 while (!(Endpoint_IsOUTReceived())); 
 195                 case REQ_SetProtocol
: 
 196                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 198                                 Endpoint_ClearSETUP(); 
 200                                 /* Set or clear the flag depending on what the host indicates that the current Protocol should be */ 
 201                                 UsingReportProtocol 
= (USB_ControlRequest
.wValue 
!= 0x0000); 
 203                                 /* Acknowledge status stage */ 
 204                                 while (!(Endpoint_IsINReady())); 
 210                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_HOSTTODEVICE 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 212                                 Endpoint_ClearSETUP(); 
 214                                 /* Get idle period in MSB */ 
 215                                 IdleCount 
= (USB_ControlRequest
.wValue 
>> 8); 
 217                                 /* Acknowledge status stage */ 
 218                                 while (!(Endpoint_IsINReady())); 
 224                         if (USB_ControlRequest
.bmRequestType 
== (REQDIR_DEVICETOHOST 
| REQTYPE_CLASS 
| REQREC_INTERFACE
)) 
 226                                 Endpoint_ClearSETUP(); 
 228                                 /* Write the current idle duration to the host */ 
 229                                 Endpoint_Write_Byte(IdleCount
); 
 231                                 /* Send the flag to the host */ 
 234                                 /* Acknowledge status stage */ 
 235                                 while (!(Endpoint_IsOUTReceived())); 
 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. 
 247 ISR(TIMER0_COMPA_vect
, ISR_BLOCK
) 
 249         /* One millisecond has elapsed, decrement the idle time remaining counter if it has not already elapsed */ 
 253         if (KeyDelayRemaining
) 
 257 /** Constructs a keyboard report indicating the currently pressed keyboard keys to the host. 
 259  *  \param ReportData  Pointer to a USB_KeyboardReport_Data_t report structure where the resulting report should 
 262  *  \return Boolean true if the current report is different to the previous report, false otherwise 
 264 bool GetNextReport(USB_KeyboardReport_Data_t
* ReportData
) 
 266         static bool OddReport   
= false; 
 267         static bool MustRelease 
= false; 
 269         BitBuffer_t
* Buffer     
= NULL
; 
 271         /* Clear the report contents */ 
 272         memset(ReportData
, 0, sizeof(USB_KeyboardReport_Data_t
)); 
 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
; 
 284                 /* Toggle the odd report number indicator */ 
 285                 OddReport   
= !OddReport
; 
 287                 /* Set the flag indicating that a null report must eventually be sent to release all pressed keys */ 
 290                 /* Only send the next key on odd reports, so that they are interspersed with null reports to release keys */ 
 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
; 
 296                         /* If buffer is now empty, a new line must be sent instead of the terminating bit */ 
 297                         if (!(Buffer
->Elements
)) 
 299                                 /* Set the keycode to the code for an enter key press */ 
 300                                 ReportData
->KeyCode 
= KEY_ENTER
;                                 
 306         else if (MustRelease
) 
 308                 /* Leave key code to null (0), to release all pressed keys */ 
 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. 
 320         /* Arrays to hold the buffer pointers, clock and data bit masks for the separate card tracks */ 
 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
}}; 
 330         /* Previous magnetic card control line' status, for later comparison */ 
 331         uint8_t Magstripe_Prev 
= 0; 
 333         /* Buffered current card reader control line' status */ 
 334         uint8_t Magstripe_LCL  
= Magstripe_GetStatus(); 
 336         /* Exit the task early if no card is present in the reader */ 
 337         if (!(Magstripe_LCL 
& MAG_CARDPRESENT
)) 
 340         /* Read out card data while a card is present */ 
 341         while (Magstripe_LCL 
& MAG_CARDPRESENT
) 
 343                 /* Read out the next bit for each track of the card */ 
 344                 for (uint8_t Track 
= 0; Track 
< 3; Track
++) 
 346                         /* Current data line status for the current card track */ 
 347                         bool DataLevel    
= ((Magstripe_LCL 
& TrackInfo
[Track
].DataMask
) != 0); 
 349                         /* Current clock line status for the current card track */ 
 350                         bool ClockLevel   
= ((Magstripe_LCL 
& TrackInfo
[Track
].ClockMask
) != 0); 
 352                         /* Current track clock transition check */ 
 353                         bool ClockChanged 
= (((Magstripe_LCL 
^ Magstripe_Prev
) & TrackInfo
[Track
].ClockMask
) != 0); 
 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
); 
 360                 /* Retain the current card reader control line states for later edge detection */ 
 361                 Magstripe_Prev 
= Magstripe_LCL
; 
 363                 /* Retrieve the new card reader control line states */ 
 364                 Magstripe_LCL  
= Magstripe_GetStatus(); 
 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); 
 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. 
 376 TASK(USB_Keyboard_Report
) 
 378         USB_KeyboardReport_Data_t KeyboardReportData
; 
 379         bool                      SendReport 
= false; 
 381         /* Check if the USB system is connected to a host */ 
 384                 /* Select the Keyboard Report Endpoint */ 
 385                 Endpoint_SelectEndpoint(KEYBOARD_EPNUM
); 
 387                 /* Check if Keyboard Endpoint Ready for Read/Write */ 
 388                 if (Endpoint_IsReadWriteAllowed()) 
 390                         /* Only fetch the next key to send once the period between key presses has elapsed */ 
 391                         if (!(KeyDelayRemaining
)) 
 393                                 /* Create the next keyboard report for transmission to the host */ 
 394                                 SendReport 
= GetNextReport(&KeyboardReportData
); 
 397                         /* Check if the idle period is set and has elapsed */ 
 398                         if (IdleCount 
&& !(IdleMSRemaining
)) 
 400                                 /* Idle period elapsed, indicate that a report must be sent */ 
 403                                 /* Reset the idle time remaining counter, must multiply by 4 to get the duration in milliseconds */ 
 404                                 IdleMSRemaining 
= (IdleCount 
<< 2); 
 407                         /* Write the keyboard report if a report is to be sent to the host */ 
 410                                 /* Write Keyboard Report Data */ 
 411                                 Endpoint_Write_Stream_LE(&KeyboardReportData
, sizeof(USB_KeyboardReport_Data_t
)); 
 413                                 /* Finalize the stream transfer to send the last packet */ 
 416                                 /* Reset the key delay period counter */ 
 417                                 KeyDelayRemaining 
= 2;