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