]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/lfops.c
6c9a36f7e51f42019173256eef92c3001f1251a5
[proxmark3-svn] / armsrc / lfops.c
1 //-----------------------------------------------------------------------------
2 // Miscellaneous routines for low frequency tag operations.
3 // Tags supported here so far are Texas Instruments (TI), HID
4 // Also routines for raw mode reading/simulating of LF waveform
5 //
6 //-----------------------------------------------------------------------------
7 #include <proxmark3.h>
8 #include "apps.h"
9 #include "hitag2.h"
10 #include "../common/crc16.c"
11
12 int sprintf(char *dest, const char *fmt, ...);
13
14 void AcquireRawAdcSamples125k(BOOL at134khz)
15 {
16 if(at134khz) {
17 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 88); //134.8Khz
18 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
19 } else {
20 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
21 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
22 }
23
24 // Connect the A/D to the peak-detected low-frequency path.
25 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
26
27 // Give it a bit of time for the resonant antenna to settle.
28 SpinDelay(50);
29
30 // Now set up the SSC to get the ADC samples that are now streaming at us.
31 FpgaSetupSsc();
32
33 // Now call the acquisition routine
34 DoAcquisition125k(at134khz);
35 }
36
37 // split into two routines so we can avoid timing issues after sending commands //
38 void DoAcquisition125k(BOOL at134khz)
39 {
40 BYTE *dest = (BYTE *)BigBuf;
41 int n = sizeof(BigBuf);
42 int i;
43 char output_string[64];
44
45 memset(dest,0,n);
46 i = 0;
47 for(;;) {
48 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
49 AT91C_BASE_SSC->SSC_THR = 0x43;
50 LED_D_ON();
51 }
52 if(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) {
53 dest[i] = (BYTE)AT91C_BASE_SSC->SSC_RHR;
54 i++;
55 LED_D_OFF();
56 if (i >= n) break;
57 }
58 }
59 sprintf(output_string, "read samples, dest[0]=%x dest[1]=%x at134khz=%d",
60 dest[0], dest[1], at134khz);
61 DbpString(output_string);
62 }
63
64 void ModThenAcquireRawAdcSamples125k(int delay_off,int period_0,int period_1,BYTE *command)
65 {
66 BOOL at134khz;
67
68 /* Make sure the tag is reset */
69 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
70 SpinDelay(2500);
71
72 // see if 'h' was specified
73 if(command[strlen((char *) command) - 1] == 'h')
74 at134khz= TRUE;
75 else
76 at134khz= FALSE;
77
78 if(at134khz) {
79 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 88); //134.8Khz
80 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
81 } else {
82 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
83 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
84 }
85
86 // Give it a bit of time for the resonant antenna to settle.
87 SpinDelay(50);
88 // And a little more time for the tag to fully power up
89 SpinDelay(2000);
90
91 // Now set up the SSC to get the ADC samples that are now streaming at us.
92 FpgaSetupSsc();
93
94 // now modulate the reader field
95 while(*command != '\0' && *command != ' ')
96 {
97 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
98 LED_D_OFF();
99 SpinDelayUs(delay_off);
100 if(at134khz) {
101 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 88); //134.8Khz
102 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
103 } else {
104 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
105 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
106 }
107 LED_D_ON();
108 if(*(command++) == '0') {
109 SpinDelayUs(period_0);
110 } else {
111 SpinDelayUs(period_1);
112 }
113 }
114 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
115 LED_D_OFF();
116 SpinDelayUs(delay_off);
117 if(at134khz) {
118 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 88); //134.8Khz
119 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
120 } else {
121 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
122 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
123 }
124
125 // now do the read
126 DoAcquisition125k(at134khz);
127 }
128
129 /* blank r/w tag data stream
130 ...0000000000000000 01111111
131 1010101010101010101010101010101010101010101010101010101010101010
132 0011010010100001
133 01111111
134 101010101010101[0]000...
135
136 [5555fe852c5555555555555555fe0000]
137 */
138 void ReadTItag()
139 {
140 // some hardcoded initial params
141 // when we read a TI tag we sample the zerocross line at 2Mhz
142 // TI tags modulate a 1 as 16 cycles of 123.2Khz
143 // TI tags modulate a 0 as 16 cycles of 134.2Khz
144 #define FSAMPLE 2000000
145 #define FREQLO 123200
146 #define FREQHI 134200
147
148 signed char *dest = (signed char *)BigBuf;
149 int n = sizeof(BigBuf);
150 // int *dest = GraphBuffer;
151 // int n = GraphTraceLen;
152
153 // 128 bit shift register [shift3:shift2:shift1:shift0]
154 DWORD shift3 = 0, shift2 = 0, shift1 = 0, shift0 = 0;
155
156 int i, cycles=0, samples=0;
157 // how many sample points fit in 16 cycles of each frequency
158 DWORD sampleslo = (FSAMPLE<<4)/FREQLO, sampleshi = (FSAMPLE<<4)/FREQHI;
159 // when to tell if we're close enough to one freq or another
160 DWORD threshold = (sampleslo - sampleshi + 1)>>1;
161
162 // TI tags charge at 134.2Khz
163 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 88); //134.8Khz
164
165 // Place FPGA in passthrough mode, in this mode the CROSS_LO line
166 // connects to SSP_DIN and the SSP_DOUT logic level controls
167 // whether we're modulating the antenna (high)
168 // or listening to the antenna (low)
169 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_PASSTHRU);
170
171 // get TI tag data into the buffer
172 AcquireTiType();
173
174 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
175
176 for (i=0; i<n-1; i++) {
177 // count cycles by looking for lo to hi zero crossings
178 if ( (dest[i]<0) && (dest[i+1]>0) ) {
179 cycles++;
180 // after 16 cycles, measure the frequency
181 if (cycles>15) {
182 cycles=0;
183 samples=i-samples; // number of samples in these 16 cycles
184
185 // TI bits are coming to us lsb first so shift them
186 // right through our 128 bit right shift register
187 shift0 = (shift0>>1) | (shift1 << 31);
188 shift1 = (shift1>>1) | (shift2 << 31);
189 shift2 = (shift2>>1) | (shift3 << 31);
190 shift3 >>= 1;
191
192 // check if the cycles fall close to the number
193 // expected for either the low or high frequency
194 if ( (samples>(sampleslo-threshold)) && (samples<(sampleslo+threshold)) ) {
195 // low frequency represents a 1
196 shift3 |= (1<<31);
197 } else if ( (samples>(sampleshi-threshold)) && (samples<(sampleshi+threshold)) ) {
198 // high frequency represents a 0
199 } else {
200 // probably detected a gay waveform or noise
201 // use this as gaydar or discard shift register and start again
202 shift3 = shift2 = shift1 = shift0 = 0;
203 }
204 samples = i;
205
206 // for each bit we receive, test if we've detected a valid tag
207
208 // if we see 17 zeroes followed by 6 ones, we might have a tag
209 // remember the bits are backwards
210 if ( ((shift0 & 0x7fffff) == 0x7e0000) ) {
211 // if start and end bytes match, we have a tag so break out of the loop
212 if ( ((shift0>>16)&0xff) == ((shift3>>8)&0xff) ) {
213 cycles = 0xF0B; //use this as a flag (ugly but whatever)
214 break;
215 }
216 }
217 }
218 }
219 }
220
221 // if flag is set we have a tag
222 if (cycles!=0xF0B) {
223 DbpString("Info: No valid tag detected.");
224 } else {
225 // put 64 bit data into shift1 and shift0
226 shift0 = (shift0>>24) | (shift1 << 8);
227 shift1 = (shift1>>24) | (shift2 << 8);
228
229 // align 16 bit crc into lower half of shift2
230 shift2 = ((shift2>>24) | (shift3 << 8)) & 0x0ffff;
231
232 // if r/w tag, check ident match
233 if ( shift3&(1<<15) ) {
234 DbpString("Info: TI tag is rewriteable");
235 // only 15 bits compare, last bit of ident is not valid
236 if ( ((shift3>>16)^shift0)&0x7fff ) {
237 DbpString("Error: Ident mismatch!");
238 } else {
239 DbpString("Info: TI tag ident is valid");
240 }
241 } else {
242 DbpString("Info: TI tag is readonly");
243 }
244
245 // WARNING the order of the bytes in which we calc crc below needs checking
246 // i'm 99% sure the crc algorithm is correct, but it may need to eat the
247 // bytes in reverse or something
248 // calculate CRC
249 DWORD crc=0;
250
251 crc = update_crc16(crc, (shift0)&0xff);
252 crc = update_crc16(crc, (shift0>>8)&0xff);
253 crc = update_crc16(crc, (shift0>>16)&0xff);
254 crc = update_crc16(crc, (shift0>>24)&0xff);
255 crc = update_crc16(crc, (shift1)&0xff);
256 crc = update_crc16(crc, (shift1>>8)&0xff);
257 crc = update_crc16(crc, (shift1>>16)&0xff);
258 crc = update_crc16(crc, (shift1>>24)&0xff);
259
260 char output_string[64];
261 sprintf(output_string, "Info: Tag data_hi=%x, data_lo=%x, crc=%x",
262 (unsigned int)shift1, (unsigned int)shift0, (unsigned int)shift2 & 0xFFFF);
263 DbpString(output_string);
264 if (crc != (shift2&0xffff)) {
265 sprintf(output_string, "Error: CRC mismatch, expected %x", (unsigned int)crc);
266 DbpString(output_string);
267 } else {
268 DbpString("Info: CRC is good");
269 }
270 }
271 }
272
273 void WriteTIbyte(BYTE b)
274 {
275 int i = 0;
276
277 // modulate 8 bits out to the antenna
278 for (i=0; i<8; i++)
279 {
280 if (b&(1<<i)) {
281 // stop modulating antenna
282 LOW(GPIO_SSC_DOUT);
283 SpinDelayUs(1000);
284 // modulate antenna
285 HIGH(GPIO_SSC_DOUT);
286 SpinDelayUs(1000);
287 } else {
288 // stop modulating antenna
289 LOW(GPIO_SSC_DOUT);
290 SpinDelayUs(300);
291 // modulate antenna
292 HIGH(GPIO_SSC_DOUT);
293 SpinDelayUs(1700);
294 }
295 }
296 }
297
298 void AcquireTiType(void)
299 {
300 int i, j, n;
301 // tag transmission is <20ms, sampling at 2M gives us 40K samples max
302 // each sample is 1 bit stuffed into a DWORD so we need 1250 DWORDS
303 #define TIBUFLEN 1250
304
305 // clear buffer
306 memset(BigBuf,0,sizeof(BigBuf));
307
308 // Set up the synchronous serial port
309 AT91C_BASE_PIOA->PIO_PDR = GPIO_SSC_DIN;
310 AT91C_BASE_PIOA->PIO_ASR = GPIO_SSC_DIN;
311
312 // steal this pin from the SSP and use it to control the modulation
313 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
314 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
315
316 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_SWRST;
317 AT91C_BASE_SSC->SSC_CR = AT91C_SSC_RXEN | AT91C_SSC_TXEN;
318
319 // Sample at 2 Mbit/s, so TI tags are 16.2 vs. 14.9 clocks long
320 // 48/2 = 24 MHz clock must be divided by 12
321 AT91C_BASE_SSC->SSC_CMR = 12;
322
323 AT91C_BASE_SSC->SSC_RCMR = SSC_CLOCK_MODE_SELECT(0);
324 AT91C_BASE_SSC->SSC_RFMR = SSC_FRAME_MODE_BITS_IN_WORD(32) | AT91C_SSC_MSBF;
325 AT91C_BASE_SSC->SSC_TCMR = 0;
326 AT91C_BASE_SSC->SSC_TFMR = 0;
327
328 LED_D_ON();
329
330 // modulate antenna
331 HIGH(GPIO_SSC_DOUT);
332
333 // Charge TI tag for 50ms.
334 SpinDelay(50);
335
336 // stop modulating antenna and listen
337 LOW(GPIO_SSC_DOUT);
338
339 LED_D_OFF();
340
341 i = 0;
342 for(;;) {
343 if(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY) {
344 BigBuf[i] = AT91C_BASE_SSC->SSC_RHR; // store 32 bit values in buffer
345 i++; if(i >= TIBUFLEN) break;
346 }
347 WDT_HIT();
348 }
349
350 // return stolen pin to SSP
351 AT91C_BASE_PIOA->PIO_PDR = GPIO_SSC_DOUT;
352 AT91C_BASE_PIOA->PIO_ASR = GPIO_SSC_DIN | GPIO_SSC_DOUT;
353
354 char *dest = (char *)BigBuf;
355 n = TIBUFLEN*32;
356 // unpack buffer
357 for (i=TIBUFLEN-1; i>=0; i--) {
358 // DbpIntegers(0, 0, BigBuf[i]);
359 for (j=0; j<32; j++) {
360 if(BigBuf[i] & (1 << j)) {
361 dest[--n] = 1;
362 } else {
363 dest[--n] = -1;
364 }
365 }
366 }
367 }
368
369 // arguments: 64bit data split into 32bit idhi:idlo and optional 16bit crc
370 // if crc provided, it will be written with the data verbatim (even if bogus)
371 // if not provided a valid crc will be computed from the data and written.
372 void WriteTItag(DWORD idhi, DWORD idlo, WORD crc)
373 {
374
375 // WARNING the order of the bytes in which we calc crc below needs checking
376 // i'm 99% sure the crc algorithm is correct, but it may need to eat the
377 // bytes in reverse or something
378
379 if(crc == 0) {
380 crc = update_crc16(crc, (idlo)&0xff);
381 crc = update_crc16(crc, (idlo>>8)&0xff);
382 crc = update_crc16(crc, (idlo>>16)&0xff);
383 crc = update_crc16(crc, (idlo>>24)&0xff);
384 crc = update_crc16(crc, (idhi)&0xff);
385 crc = update_crc16(crc, (idhi>>8)&0xff);
386 crc = update_crc16(crc, (idhi>>16)&0xff);
387 crc = update_crc16(crc, (idhi>>24)&0xff);
388 }
389 char output_string[64];
390 sprintf(output_string, "Writing the following data to tag: %x, %x, %x",
391 (unsigned int) idhi, (unsigned int) idlo, crc);
392 DbpString(output_string);
393
394 // TI tags charge at 134.2Khz
395 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 88); //134.8Khz
396 // Place FPGA in passthrough mode, in this mode the CROSS_LO line
397 // connects to SSP_DIN and the SSP_DOUT logic level controls
398 // whether we're modulating the antenna (high)
399 // or listening to the antenna (low)
400 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_PASSTHRU);
401 LED_A_ON();
402
403 // steal this pin from the SSP and use it to control the modulation
404 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
405 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
406
407 // writing algorithm:
408 // a high bit consists of a field off for 1ms and field on for 1ms
409 // a low bit consists of a field off for 0.3ms and field on for 1.7ms
410 // initiate a charge time of 50ms (field on) then immediately start writing bits
411 // start by writing 0xBB (keyword) and 0xEB (password)
412 // then write 80 bits of data (or 64 bit data + 16 bit crc if you prefer)
413 // finally end with 0x0300 (write frame)
414 // all data is sent lsb firts
415 // finish with 15ms programming time
416
417 // modulate antenna
418 HIGH(GPIO_SSC_DOUT);
419 SpinDelay(50); // charge time
420
421 WriteTIbyte(0xbb); // keyword
422 WriteTIbyte(0xeb); // password
423 WriteTIbyte( (idlo )&0xff );
424 WriteTIbyte( (idlo>>8 )&0xff );
425 WriteTIbyte( (idlo>>16)&0xff );
426 WriteTIbyte( (idlo>>24)&0xff );
427 WriteTIbyte( (idhi )&0xff );
428 WriteTIbyte( (idhi>>8 )&0xff );
429 WriteTIbyte( (idhi>>16)&0xff );
430 WriteTIbyte( (idhi>>24)&0xff ); // data hi to lo
431 WriteTIbyte( (crc )&0xff ); // crc lo
432 WriteTIbyte( (crc>>8 )&0xff ); // crc hi
433 WriteTIbyte(0x00); // write frame lo
434 WriteTIbyte(0x03); // write frame hi
435 HIGH(GPIO_SSC_DOUT);
436 SpinDelay(50); // programming time
437
438 LED_A_OFF();
439
440 // get TI tag data into the buffer
441 AcquireTiType();
442
443 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
444 DbpString("Now use tiread to check");
445 }
446
447 void SimulateTagLowFrequency(int period, int ledcontrol)
448 {
449 int i;
450 BYTE *tab = (BYTE *)BigBuf;
451
452 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_SIMULATOR);
453
454 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT | GPIO_SSC_CLK;
455
456 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
457 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_CLK;
458
459 #define SHORT_COIL() LOW(GPIO_SSC_DOUT)
460 #define OPEN_COIL() HIGH(GPIO_SSC_DOUT)
461
462 i = 0;
463 for(;;) {
464 while(!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK)) {
465 if(BUTTON_PRESS()) {
466 DbpString("Stopped");
467 return;
468 }
469 WDT_HIT();
470 }
471
472 if (ledcontrol)
473 LED_D_ON();
474
475 if(tab[i])
476 OPEN_COIL();
477 else
478 SHORT_COIL();
479
480 if (ledcontrol)
481 LED_D_OFF();
482
483 while(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_CLK) {
484 if(BUTTON_PRESS()) {
485 DbpString("Stopped");
486 return;
487 }
488 WDT_HIT();
489 }
490
491 i++;
492 if(i == period) i = 0;
493 }
494 }
495
496 /* Provides a framework for bidirectional LF tag communication
497 * Encoding is currently Hitag2, but the general idea can probably
498 * be transferred to other encodings.
499 *
500 * The new FPGA code will, for the LF simulator mode, give on SSC_FRAME
501 * (PA15) a thresholded version of the signal from the ADC. Setting the
502 * ADC path to the low frequency peak detection signal, will enable a
503 * somewhat reasonable receiver for modulation on the carrier signal
504 * that is generated by the reader. The signal is low when the reader
505 * field is switched off, and high when the reader field is active. Due
506 * to the way that the signal looks like, mostly only the rising edge is
507 * useful, your mileage may vary.
508 *
509 * Neat perk: PA15 can not only be used as a bit-banging GPIO, but is also
510 * TIOA1, which can be used as the capture input for timer 1. This should
511 * make it possible to measure the exact edge-to-edge time, without processor
512 * intervention.
513 *
514 * Arguments: divisor is the divisor to be sent to the FPGA (e.g. 95 for 125kHz)
515 * t0 is the carrier frequency cycle duration in terms of MCK (384 for 125kHz)
516 *
517 * The following defines are in carrier periods:
518 */
519 #define HITAG_T_0_MIN 15 /* T[0] should be 18..22 */
520 #define HITAG_T_1_MIN 24 /* T[1] should be 26..30 */
521 #define HITAG_T_EOF 40 /* T_EOF should be > 36 */
522 #define HITAG_T_WRESP 208 /* T_wresp should be 204..212 */
523
524 static void hitag_handle_frame(int t0, int frame_len, char *frame);
525 //#define DEBUG_RA_VALUES 1
526 #define DEBUG_FRAME_CONTENTS 1
527 void SimulateTagLowFrequencyBidir(int divisor, int t0)
528 {
529 #if DEBUG_RA_VALUES || DEBUG_FRAME_CONTENTS
530 int i = 0;
531 #endif
532 char frame[10];
533 int frame_pos=0;
534
535 DbpString("Starting Hitag2 emulator, press button to end");
536 hitag2_init();
537
538 /* Set up simulator mode, frequency divisor which will drive the FPGA
539 * and analog mux selection.
540 */
541 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_SIMULATOR);
542 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, divisor);
543 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
544 RELAY_OFF();
545
546 /* Set up Timer 1:
547 * Capture mode, timer source MCK/2 (TIMER_CLOCK1), TIOA is external trigger,
548 * external trigger rising edge, load RA on rising edge of TIOA, load RB on rising
549 * edge of TIOA. Assign PA15 to TIOA1 (peripheral B)
550 */
551
552 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
553 AT91C_BASE_PIOA->PIO_BSR = GPIO_SSC_FRAME;
554 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKDIS;
555 AT91C_BASE_TC1->TC_CMR = TC_CMR_TCCLKS_TIMER_CLOCK1 |
556 AT91C_TC_ETRGEDG_RISING |
557 AT91C_TC_ABETRG |
558 AT91C_TC_LDRA_RISING |
559 AT91C_TC_LDRB_RISING;
560 AT91C_BASE_TC1->TC_CCR = AT91C_TC_CLKEN |
561 AT91C_TC_SWTRG;
562
563 /* calculate the new value for the carrier period in terms of TC1 values */
564 t0 = t0/2;
565
566 int overflow = 0;
567 while(!BUTTON_PRESS()) {
568 WDT_HIT();
569 if(AT91C_BASE_TC1->TC_SR & AT91C_TC_LDRAS) {
570 int ra = AT91C_BASE_TC1->TC_RA;
571 if((ra > t0*HITAG_T_EOF) | overflow) ra = t0*HITAG_T_EOF+1;
572 #if DEBUG_RA_VALUES
573 if(ra > 255 || overflow) ra = 255;
574 ((char*)BigBuf)[i] = ra;
575 i = (i+1) % 8000;
576 #endif
577
578 if(overflow || (ra > t0*HITAG_T_EOF) || (ra < t0*HITAG_T_0_MIN)) {
579 /* Ignore */
580 } else if(ra >= t0*HITAG_T_1_MIN ) {
581 /* '1' bit */
582 if(frame_pos < 8*sizeof(frame)) {
583 frame[frame_pos / 8] |= 1<<( 7-(frame_pos%8) );
584 frame_pos++;
585 }
586 } else if(ra >= t0*HITAG_T_0_MIN) {
587 /* '0' bit */
588 if(frame_pos < 8*sizeof(frame)) {
589 frame[frame_pos / 8] |= 0<<( 7-(frame_pos%8) );
590 frame_pos++;
591 }
592 }
593
594 overflow = 0;
595 LED_D_ON();
596 } else {
597 if(AT91C_BASE_TC1->TC_CV > t0*HITAG_T_EOF) {
598 /* Minor nuisance: In Capture mode, the timer can not be
599 * stopped by a Compare C. There's no way to stop the clock
600 * in software, so we'll just have to note the fact that an
601 * overflow happened and the next loaded timer value might
602 * have wrapped. Also, this marks the end of frame, and the
603 * still running counter can be used to determine the correct
604 * time for the start of the reply.
605 */
606 overflow = 1;
607
608 if(frame_pos > 0) {
609 /* Have a frame, do something with it */
610 #if DEBUG_FRAME_CONTENTS
611 ((char*)BigBuf)[i++] = frame_pos;
612 memcpy( ((char*)BigBuf)+i, frame, 7);
613 i+=7;
614 i = i % sizeof(BigBuf);
615 #endif
616 hitag_handle_frame(t0, frame_pos, frame);
617 memset(frame, 0, sizeof(frame));
618 }
619 frame_pos = 0;
620
621 }
622 LED_D_OFF();
623 }
624 }
625 DbpString("All done");
626 }
627
628 static void hitag_send_bit(int t0, int bit) {
629 if(bit == 1) {
630 /* Manchester: Loaded, then unloaded */
631 LED_A_ON();
632 SHORT_COIL();
633 while(AT91C_BASE_TC1->TC_CV < t0*15);
634 OPEN_COIL();
635 while(AT91C_BASE_TC1->TC_CV < t0*31);
636 LED_A_OFF();
637 } else if(bit == 0) {
638 /* Manchester: Unloaded, then loaded */
639 LED_B_ON();
640 OPEN_COIL();
641 while(AT91C_BASE_TC1->TC_CV < t0*15);
642 SHORT_COIL();
643 while(AT91C_BASE_TC1->TC_CV < t0*31);
644 LED_B_OFF();
645 }
646 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG; /* Reset clock for the next bit */
647
648 }
649 static void hitag_send_frame(int t0, int frame_len, const char const * frame, int fdt)
650 {
651 OPEN_COIL();
652 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
653
654 /* Wait for HITAG_T_WRESP carrier periods after the last reader bit,
655 * not that since the clock counts since the rising edge, but T_wresp is
656 * with respect to the falling edge, we need to wait actually (T_wresp - T_g)
657 * periods. The gap time T_g varies (4..10).
658 */
659 while(AT91C_BASE_TC1->TC_CV < t0*(fdt-8));
660
661 int saved_cmr = AT91C_BASE_TC1->TC_CMR;
662 AT91C_BASE_TC1->TC_CMR &= ~AT91C_TC_ETRGEDG; /* Disable external trigger for the clock */
663 AT91C_BASE_TC1->TC_CCR = AT91C_TC_SWTRG; /* Reset the clock and use it for response timing */
664
665 int i;
666 for(i=0; i<5; i++)
667 hitag_send_bit(t0, 1); /* Start of frame */
668
669 for(i=0; i<frame_len; i++) {
670 hitag_send_bit(t0, !!(frame[i/ 8] & (1<<( 7-(i%8) ))) );
671 }
672
673 OPEN_COIL();
674 AT91C_BASE_TC1->TC_CMR = saved_cmr;
675 }
676
677 /* Callback structure to cleanly separate tag emulation code from the radio layer. */
678 static int hitag_cb(const char* response_data, const int response_length, const int fdt, void *cb_cookie)
679 {
680 hitag_send_frame(*(int*)cb_cookie, response_length, response_data, fdt);
681 return 0;
682 }
683 /* Frame length in bits, frame contents in MSBit first format */
684 static void hitag_handle_frame(int t0, int frame_len, char *frame)
685 {
686 hitag2_handle_command(frame, frame_len, hitag_cb, &t0);
687 }
688
689 // compose fc/8 fc/10 waveform
690 static void fc(int c, int *n) {
691 BYTE *dest = (BYTE *)BigBuf;
692 int idx;
693
694 // for when we want an fc8 pattern every 4 logical bits
695 if(c==0) {
696 dest[((*n)++)]=1;
697 dest[((*n)++)]=1;
698 dest[((*n)++)]=0;
699 dest[((*n)++)]=0;
700 dest[((*n)++)]=0;
701 dest[((*n)++)]=0;
702 dest[((*n)++)]=0;
703 dest[((*n)++)]=0;
704 }
705 // an fc/8 encoded bit is a bit pattern of 11000000 x6 = 48 samples
706 if(c==8) {
707 for (idx=0; idx<6; idx++) {
708 dest[((*n)++)]=1;
709 dest[((*n)++)]=1;
710 dest[((*n)++)]=0;
711 dest[((*n)++)]=0;
712 dest[((*n)++)]=0;
713 dest[((*n)++)]=0;
714 dest[((*n)++)]=0;
715 dest[((*n)++)]=0;
716 }
717 }
718
719 // an fc/10 encoded bit is a bit pattern of 1110000000 x5 = 50 samples
720 if(c==10) {
721 for (idx=0; idx<5; idx++) {
722 dest[((*n)++)]=1;
723 dest[((*n)++)]=1;
724 dest[((*n)++)]=1;
725 dest[((*n)++)]=0;
726 dest[((*n)++)]=0;
727 dest[((*n)++)]=0;
728 dest[((*n)++)]=0;
729 dest[((*n)++)]=0;
730 dest[((*n)++)]=0;
731 dest[((*n)++)]=0;
732 }
733 }
734 }
735
736 // prepare a waveform pattern in the buffer based on the ID given then
737 // simulate a HID tag until the button is pressed
738 void CmdHIDsimTAG(int hi, int lo, int ledcontrol)
739 {
740 int n=0, i=0;
741 /*
742 HID tag bitstream format
743 The tag contains a 44bit unique code. This is sent out MSB first in sets of 4 bits
744 A 1 bit is represented as 6 fc8 and 5 fc10 patterns
745 A 0 bit is represented as 5 fc10 and 6 fc8 patterns
746 A fc8 is inserted before every 4 bits
747 A special start of frame pattern is used consisting a0b0 where a and b are neither 0
748 nor 1 bits, they are special patterns (a = set of 12 fc8 and b = set of 10 fc10)
749 */
750
751 if (hi>0xFFF) {
752 DbpString("Tags can only have 44 bits.");
753 return;
754 }
755 fc(0,&n);
756 // special start of frame marker containing invalid bit sequences
757 fc(8, &n); fc(8, &n); // invalid
758 fc(8, &n); fc(10, &n); // logical 0
759 fc(10, &n); fc(10, &n); // invalid
760 fc(8, &n); fc(10, &n); // logical 0
761
762 WDT_HIT();
763 // manchester encode bits 43 to 32
764 for (i=11; i>=0; i--) {
765 if ((i%4)==3) fc(0,&n);
766 if ((hi>>i)&1) {
767 fc(10, &n); fc(8, &n); // low-high transition
768 } else {
769 fc(8, &n); fc(10, &n); // high-low transition
770 }
771 }
772
773 WDT_HIT();
774 // manchester encode bits 31 to 0
775 for (i=31; i>=0; i--) {
776 if ((i%4)==3) fc(0,&n);
777 if ((lo>>i)&1) {
778 fc(10, &n); fc(8, &n); // low-high transition
779 } else {
780 fc(8, &n); fc(10, &n); // high-low transition
781 }
782 }
783
784 if (ledcontrol)
785 LED_A_ON();
786 SimulateTagLowFrequency(n, ledcontrol);
787
788 if (ledcontrol)
789 LED_A_OFF();
790 }
791
792
793 // loop to capture raw HID waveform then FSK demodulate the TAG ID from it
794 void CmdHIDdemodFSK(int findone, int *high, int *low, int ledcontrol)
795 {
796 BYTE *dest = (BYTE *)BigBuf;
797 int m=0, n=0, i=0, idx=0, found=0, lastval=0;
798 DWORD hi=0, lo=0;
799
800 FpgaSendCommand(FPGA_CMD_SET_DIVISOR, 95); //125Khz
801 FpgaWriteConfWord(FPGA_MAJOR_MODE_LF_READER);
802
803 // Connect the A/D to the peak-detected low-frequency path.
804 SetAdcMuxFor(GPIO_MUXSEL_LOPKD);
805
806 // Give it a bit of time for the resonant antenna to settle.
807 SpinDelay(50);
808
809 // Now set up the SSC to get the ADC samples that are now streaming at us.
810 FpgaSetupSsc();
811
812 for(;;) {
813 WDT_HIT();
814 if (ledcontrol)
815 LED_A_ON();
816 if(BUTTON_PRESS()) {
817 DbpString("Stopped");
818 if (ledcontrol)
819 LED_A_OFF();
820 return;
821 }
822
823 i = 0;
824 m = sizeof(BigBuf);
825 memset(dest,128,m);
826 for(;;) {
827 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
828 AT91C_BASE_SSC->SSC_THR = 0x43;
829 if (ledcontrol)
830 LED_D_ON();
831 }
832 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
833 dest[i] = (BYTE)AT91C_BASE_SSC->SSC_RHR;
834 // we don't care about actual value, only if it's more or less than a
835 // threshold essentially we capture zero crossings for later analysis
836 if(dest[i] < 127) dest[i] = 0; else dest[i] = 1;
837 i++;
838 if (ledcontrol)
839 LED_D_OFF();
840 if(i >= m) {
841 break;
842 }
843 }
844 }
845
846 // FSK demodulator
847
848 // sync to first lo-hi transition
849 for( idx=1; idx<m; idx++) {
850 if (dest[idx-1]<dest[idx])
851 lastval=idx;
852 break;
853 }
854 WDT_HIT();
855
856 // count cycles between consecutive lo-hi transitions, there should be either 8 (fc/8)
857 // or 10 (fc/10) cycles but in practice due to noise etc we may end up with with anywhere
858 // between 7 to 11 cycles so fuzz it by treat anything <9 as 8 and anything else as 10
859 for( i=0; idx<m; idx++) {
860 if (dest[idx-1]<dest[idx]) {
861 dest[i]=idx-lastval;
862 if (dest[i] <= 8) {
863 dest[i]=1;
864 } else {
865 dest[i]=0;
866 }
867
868 lastval=idx;
869 i++;
870 }
871 }
872 m=i;
873 WDT_HIT();
874
875 // we now have a set of cycle counts, loop over previous results and aggregate data into bit patterns
876 lastval=dest[0];
877 idx=0;
878 i=0;
879 n=0;
880 for( idx=0; idx<m; idx++) {
881 if (dest[idx]==lastval) {
882 n++;
883 } else {
884 // a bit time is five fc/10 or six fc/8 cycles so figure out how many bits a pattern width represents,
885 // an extra fc/8 pattern preceeds every 4 bits (about 200 cycles) just to complicate things but it gets
886 // swallowed up by rounding
887 // expected results are 1 or 2 bits, any more and it's an invalid manchester encoding
888 // special start of frame markers use invalid manchester states (no transitions) by using sequences
889 // like 111000
890 if (dest[idx-1]) {
891 n=(n+1)/6; // fc/8 in sets of 6
892 } else {
893 n=(n+1)/5; // fc/10 in sets of 5
894 }
895 switch (n) { // stuff appropriate bits in buffer
896 case 0:
897 case 1: // one bit
898 dest[i++]=dest[idx-1];
899 break;
900 case 2: // two bits
901 dest[i++]=dest[idx-1];
902 dest[i++]=dest[idx-1];
903 break;
904 case 3: // 3 bit start of frame markers
905 dest[i++]=dest[idx-1];
906 dest[i++]=dest[idx-1];
907 dest[i++]=dest[idx-1];
908 break;
909 // When a logic 0 is immediately followed by the start of the next transmisson
910 // (special pattern) a pattern of 4 bit duration lengths is created.
911 case 4:
912 dest[i++]=dest[idx-1];
913 dest[i++]=dest[idx-1];
914 dest[i++]=dest[idx-1];
915 dest[i++]=dest[idx-1];
916 break;
917 default: // this shouldn't happen, don't stuff any bits
918 break;
919 }
920 n=0;
921 lastval=dest[idx];
922 }
923 }
924 m=i;
925 WDT_HIT();
926
927 // final loop, go over previously decoded manchester data and decode into usable tag ID
928 // 111000 bit pattern represent start of frame, 01 pattern represents a 1 and 10 represents a 0
929 for( idx=0; idx<m-6; idx++) {
930 // search for a start of frame marker
931 if ( dest[idx] && dest[idx+1] && dest[idx+2] && (!dest[idx+3]) && (!dest[idx+4]) && (!dest[idx+5]) )
932 {
933 found=1;
934 idx+=6;
935 if (found && (hi|lo)) {
936 char output_string[64];
937 sprintf(output_string, "TAG ID: %x %x %x",
938 (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF);
939 DbpString(output_string);
940 /* if we're only looking for one tag */
941 if (findone)
942 {
943 *high = hi;
944 *low = lo;
945 return;
946 }
947 hi=0;
948 lo=0;
949 found=0;
950 }
951 }
952 if (found) {
953 if (dest[idx] && (!dest[idx+1]) ) {
954 hi=(hi<<1)|(lo>>31);
955 lo=(lo<<1)|0;
956 } else if ( (!dest[idx]) && dest[idx+1]) {
957 hi=(hi<<1)|(lo>>31);
958 lo=(lo<<1)|1;
959 } else {
960 found=0;
961 hi=0;
962 lo=0;
963 }
964 idx++;
965 }
966 if ( dest[idx] && dest[idx+1] && dest[idx+2] && (!dest[idx+3]) && (!dest[idx+4]) && (!dest[idx+5]) )
967 {
968 found=1;
969 idx+=6;
970 if (found && (hi|lo)) {
971 char output_string[64];
972 sprintf(output_string, "TAG ID: %x %x %x",
973 (unsigned int) hi, (unsigned int) lo, (unsigned int) (lo>>1) & 0xFFFF);
974 DbpString(output_string);
975 /* if we're only looking for one tag */
976 if (findone)
977 {
978 *high = hi;
979 *low = lo;
980 return;
981 }
982 hi=0;
983 lo=0;
984 found=0;
985 }
986 }
987 }
988 WDT_HIT();
989 }
990 }
Impressum, Datenschutz