]> cvs.zerfleddert.de Git - proxmark3-svn/blob - armsrc/legicrf.c
f9092103ea1f0b1a70037731ba64fd81b2b0f3d3
[proxmark3-svn] / armsrc / legicrf.c
1 //-----------------------------------------------------------------------------
2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
3 // 2016 Iceman
4 //
5 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
6 // at your option, any later version. See the LICENSE.txt file for the text of
7 // the license.
8 //-----------------------------------------------------------------------------
9 // LEGIC RF simulation code
10 //-----------------------------------------------------------------------------
11 #include "legicrf.h"
12
13 static struct legic_frame {
14 uint8_t bits;
15 uint32_t data;
16 } current_frame;
17
18 static enum {
19 STATE_DISCON,
20 STATE_IV,
21 STATE_CON,
22 } legic_state;
23
24 static crc_t legic_crc;
25 static int legic_read_count;
26 static uint32_t legic_prng_bc;
27 static uint32_t legic_prng_iv;
28
29 static int legic_phase_drift;
30 static int legic_frame_drift;
31 static int legic_reqresp_drift;
32
33 AT91PS_TC timer;
34 AT91PS_TC prng_timer;
35
36 /*
37 static void setup_timer(void) {
38 // Set up Timer 1 to use for measuring time between pulses. Since we're bit-banging
39 // this it won't be terribly accurate but should be good enough.
40 //
41 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
42 timer = AT91C_BASE_TC1;
43 timer->TC_CCR = AT91C_TC_CLKDIS;
44 timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK;
45 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
46
47 //
48 // Set up Timer 2 to use for measuring time between frames in
49 // tag simulation mode. Runs 4x faster as Timer 1
50 //
51 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC2);
52 prng_timer = AT91C_BASE_TC2;
53 prng_timer->TC_CCR = AT91C_TC_CLKDIS;
54 prng_timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV2_CLOCK;
55 prng_timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
56 }
57
58 AT91C_BASE_PMC->PMC_PCER |= (0x1 << 12) | (0x1 << 13) | (0x1 << 14);
59 AT91C_BASE_TCB->TCB_BMR = AT91C_TCB_TC0XC0S_NONE | AT91C_TCB_TC1XC1S_TIOA0 | AT91C_TCB_TC2XC2S_NONE;
60
61 // fast clock
62 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; // timer disable
63 AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK(48MHz)/32 -- tick=1.5mks
64 AT91C_TC_WAVE | AT91C_TC_WAVESEL_UP_AUTO | AT91C_TC_ACPA_CLEAR |
65 AT91C_TC_ACPC_SET | AT91C_TC_ASWTRG_SET;
66 AT91C_BASE_TC0->TC_RA = 1;
67 AT91C_BASE_TC0->TC_RC = 0xBFFF + 1; // 0xC000
68
69 */
70
71 // At TIMER_CLOCK3 (MCK/32)
72 // testing calculating in (us) microseconds.
73 #define RWD_TIME_1 120 // READER_TIME_PAUSE 20us off, 80us on = 100us 80 * 1.5 == 120ticks
74 #define RWD_TIME_0 60 // READER_TIME_PAUSE 20us off, 40us on = 60us 40 * 1.5 == 60ticks
75 #define RWD_TIME_PAUSE 30 // 20us == 20 * 1.5 == 30ticks */
76 #define TAG_BIT_PERIOD 142 // 100us == 100 * 1.5 == 150ticks
77 #define TAG_FRAME_WAIT 495 // 330us from READER frame end to TAG frame start. 330 * 1.5 == 495
78
79 #define RWD_TIME_FUZZ 20 // rather generous 13us, since the peak detector + hysteresis fuzz quite a bit
80
81 #define SIM_DIVISOR 586 /* prng_time/SIM_DIVISOR count prng needs to be forwared */
82 #define SIM_SHIFT 900 /* prng_time+SIM_SHIFT shift of delayed start */
83
84 #define OFFSET_LOG 1024
85
86 #define FUZZ_EQUAL(value, target, fuzz) ((value) > ((target)-(fuzz)) && (value) < ((target)+(fuzz)))
87
88 #ifndef SHORT_COIL
89 # define SHORT_COIL LOW(GPIO_SSC_DOUT);
90 #endif
91 #ifndef OPEN_COIL
92 # define OPEN_COIL HIGH(GPIO_SSC_DOUT);
93 #endif
94 #ifndef LINE_IN
95 # define LINE_IN AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN;
96 #endif
97 // Pause pulse, off in 20us / 30ticks,
98 // ONE / ZERO bit pulse,
99 // one == 80us / 120ticks
100 // zero == 40us / 60ticks
101 #ifndef COIL_PULSE
102 # define COIL_PULSE(x) \
103 do { \
104 SHORT_COIL; \
105 WaitTicks( (RWD_TIME_PAUSE) ); \
106 OPEN_COIL; \
107 WaitTicks((x)); \
108 } while (0);
109 #endif
110
111 // ToDo: define a meaningful maximum size for auth_table. The bigger this is, the lower will be the available memory for traces.
112 // Historically it used to be FREE_BUFFER_SIZE, which was 2744.
113 #define LEGIC_CARD_MEMSIZE 1024
114 static uint8_t* cardmem;
115
116 static void frame_append_bit(struct legic_frame * const f, uint8_t bit) {
117 // Overflow, won't happen
118 if (f->bits >= 31) return;
119
120 f->data |= (bit << f->bits);
121 f->bits++;
122 }
123
124 static void frame_clean(struct legic_frame * const f) {
125 f->data = 0;
126 f->bits = 0;
127 }
128
129 // Prng works when waiting in 99.1us cycles.
130 // and while sending/receiving in bit frames (100, 60)
131 /*static void CalibratePrng( uint32_t time){
132 // Calculate Cycles based on timer 100us
133 uint32_t i = (time - sendFrameStop) / 100 ;
134
135 // substract cycles of finished frames
136 int k = i - legic_prng_count()+1;
137
138 // substract current frame length, rewind to beginning
139 if ( k > 0 )
140 legic_prng_forward(k);
141 }
142 */
143
144 /* Generate Keystream */
145 uint32_t get_key_stream(int skip, int count) {
146
147 int i;
148
149 // Use int to enlarge timer tc to 32bit
150 legic_prng_bc += prng_timer->TC_CV;
151
152 // reset the prng timer.
153
154 /* If skip == -1, forward prng time based */
155 if(skip == -1) {
156 i = (legic_prng_bc + SIM_SHIFT)/SIM_DIVISOR; /* Calculate Cycles based on timer */
157 i -= legic_prng_count(); /* substract cycles of finished frames */
158 i -= count; /* substract current frame length, rewind to beginning */
159 legic_prng_forward(i);
160 } else {
161 legic_prng_forward(skip);
162 }
163
164 i = (count == 6) ? -1 : legic_read_count;
165
166 /* Generate KeyStream */
167 return legic_prng_get_bits(count);
168 }
169
170 /* Send a frame in tag mode, the FPGA must have been set up by
171 * LegicRfSimulate
172 */
173 void frame_send_tag(uint16_t response, uint8_t bits) {
174
175 uint16_t mask = 1;
176
177 /* Bitbang the response */
178 SHORT_COIL;
179 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
180 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
181
182 /* TAG_FRAME_WAIT -> shift by 2 */
183 legic_prng_forward(2);
184 response ^= legic_prng_get_bits(bits);
185
186 /* Wait for the frame start */
187 WaitTicks( TAG_FRAME_WAIT );
188
189 for (; mask < BITMASK(bits); mask <<= 1) {
190 if (response & mask)
191 OPEN_COIL
192 else
193 SHORT_COIL
194 WaitTicks(TAG_BIT_PERIOD);
195 }
196 SHORT_COIL;
197 }
198
199 /* Send a frame in reader mode, the FPGA must have been set up by
200 * LegicRfReader
201 */
202 void frame_sendAsReader(uint32_t data, uint8_t bits){
203
204 uint32_t starttime = GET_TICKS, send = 0, mask = 1;
205
206 // xor lsfr onto data.
207 send = data ^ legic_prng_get_bits(bits);
208
209 for (; mask < BITMASK(bits); mask <<= 1) {
210 if (send & mask)
211 COIL_PULSE(RWD_TIME_1)
212 else
213 COIL_PULSE(RWD_TIME_0)
214 }
215
216 // Final pause to mark the end of the frame
217 COIL_PULSE(0);
218
219 // log
220 uint8_t cmdbytes[] = {bits, BYTEx(data,0), BYTEx(data,1), BYTEx(data,2), BYTEx(send,0), BYTEx(send,1), BYTEx(send,2)};
221 LogTrace(cmdbytes, sizeof(cmdbytes), starttime, GET_TICKS, NULL, TRUE);
222 }
223
224 /* Receive a frame from the card in reader emulation mode, the FPGA and
225 * timer must have been set up by LegicRfReader and frame_sendAsReader.
226 *
227 * The LEGIC RF protocol from card to reader does not include explicit
228 * frame start/stop information or length information. The reader must
229 * know beforehand how many bits it wants to receive. (Notably: a card
230 * sending a stream of 0-bits is indistinguishable from no card present.)
231 *
232 * Receive methodology: There is a fancy correlator in hi_read_rx_xcorr, but
233 * I'm not smart enough to use it. Instead I have patched hi_read_tx to output
234 * the ADC signal with hysteresis on SSP_DIN. Bit-bang that signal and look
235 * for edges. Count the edges in each bit interval. If they are approximately
236 * 0 this was a 0-bit, if they are approximately equal to the number of edges
237 * expected for a 212kHz subcarrier, this was a 1-bit. For timing we use the
238 * timer that's still running from frame_sendAsReader in order to get a synchronization
239 * with the frame that we just sent.
240 *
241 * FIXME: Because we're relying on the hysteresis to just do the right thing
242 * the range is severely reduced (and you'll probably also need a good antenna).
243 * So this should be fixed some time in the future for a proper receiver.
244 */
245 static void frame_receiveAsReader(struct legic_frame * const f, uint8_t bits) {
246
247 if ( bits > 32 ) return;
248
249 uint8_t i = bits, edges = 0;
250 uint32_t the_bit = 1, next_bit_at = 0, data = 0;
251 uint32_t old_level = 0;
252 volatile uint32_t level = 0;
253
254 frame_clean(f);
255
256 // calibrate the prng.
257 legic_prng_forward(2);
258 data = legic_prng_get_bits(bits);
259
260 //FIXED time between sending frame and now listening frame. 330us
261 uint32_t starttime = GET_TICKS;
262 // its about 9+9 ticks delay from end-send to here.
263 WaitTicks( 477 );
264
265 next_bit_at = GET_TICKS + TAG_BIT_PERIOD;
266
267 while ( i-- ){
268 edges = 0;
269 while ( GET_TICKS < next_bit_at) {
270
271 level = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
272
273 if (level != old_level)
274 ++edges;
275
276 old_level = level;
277 }
278
279 next_bit_at += TAG_BIT_PERIOD;
280
281 // We expect 42 edges (ONE)
282 if ( edges > 20 )
283 data ^= the_bit;
284
285 the_bit <<= 1;
286 }
287
288 // output
289 f->data = data;
290 f->bits = bits;
291
292 // log
293 uint8_t cmdbytes[] = {bits, BYTEx(data, 0), BYTEx(data, 1)};
294 LogTrace(cmdbytes, sizeof(cmdbytes), starttime, GET_TICKS, NULL, FALSE);
295 }
296
297 // Setup pm3 as a Legic Reader
298 static uint32_t setup_phase_reader(uint8_t iv) {
299
300 // Switch on carrier and let the tag charge for 1ms
301 HIGH(GPIO_SSC_DOUT);
302 WaitUS(5000);
303
304 ResetTicks();
305
306 // no keystream yet
307 legic_prng_init(0);
308
309 // send IV handshake
310 frame_sendAsReader(iv, 7);
311
312 // Now both tag and reader has same IV. Prng can start.
313 legic_prng_init(iv);
314
315 frame_receiveAsReader(&current_frame, 6);
316
317 // 292us (438t) - fixed delay before sending ack.
318 // minus log and stuff 100tick?
319 WaitTicks(338);
320 legic_prng_forward(3);
321
322 // Send obsfuscated acknowledgment frame.
323 // 0x19 = 0x18 MIM22, 0x01 LSB READCMD
324 // 0x39 = 0x38 MIM256, MIM1024 0x01 LSB READCMD
325 switch ( current_frame.data ) {
326 case 0x0D: frame_sendAsReader(0x19, 6); break;
327 case 0x1D:
328 case 0x3D: frame_sendAsReader(0x39, 6); break;
329 default: break;
330 }
331
332 legic_prng_forward(2);
333 return current_frame.data;
334 }
335
336 static void LegicCommonInit(void) {
337
338 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
339 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX);
340 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
341
342 /* Bitbang the transmitter */
343 SHORT_COIL;
344 AT91C_BASE_PIOA->PIO_OER = GPIO_SSC_DOUT;
345 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DOUT;
346 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_DIN;
347
348 // reserve a cardmem, meaning we can use the tracelog function in bigbuff easier.
349 cardmem = BigBuf_get_EM_addr();
350 memset(cardmem, 0x00, LEGIC_CARD_MEMSIZE);
351
352 clear_trace();
353 set_tracing(TRUE);
354 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
355
356 StartTicks();
357 }
358
359 // Switch off carrier, make sure tag is reset
360 static void switch_off_tag_rwd(void) {
361 SHORT_COIL;
362 WaitUS(20);
363 WDT_HIT();
364 }
365
366 // calculate crc4 for a legic READ command
367 static uint32_t legic4Crc(uint8_t cmd, uint16_t byte_index, uint8_t value, uint8_t cmd_sz) {
368 crc_clear(&legic_crc);
369 uint32_t temp = (value << cmd_sz) | (byte_index << 1) | cmd;
370 crc_update(&legic_crc, temp, cmd_sz + 8 );
371 return crc_finish(&legic_crc);
372 }
373
374 int legic_read_byte( uint16_t index, uint8_t cmd_sz) {
375
376 uint8_t byte, crc, calcCrc = 0;
377 uint32_t cmd = (index << 1) | LEGIC_READ;
378
379 // 90ticks = 60us (should be 100us but crc calc takes time.)
380 //WaitTicks(330); // 330ticks prng(4) - works
381 WaitTicks(240); // 240ticks prng(3) - works
382
383 frame_sendAsReader(cmd, cmd_sz);
384 frame_receiveAsReader(&current_frame, 12);
385
386 // CRC check.
387 byte = BYTEx(current_frame.data, 0);
388 crc = BYTEx(current_frame.data, 1);
389 calcCrc = legic4Crc(LEGIC_READ, index, byte, cmd_sz);
390
391 if( calcCrc != crc ) {
392 Dbprintf("!!! crc mismatch: %x != %x !!!", calcCrc, crc);
393 return -1;
394 }
395
396 legic_prng_forward(3);
397 return byte;
398 }
399
400 /*
401 * - assemble a write_cmd_frame with crc and send it
402 * - wait until the tag sends back an ACK ('1' bit unencrypted)
403 * - forward the prng based on the timing
404 */
405 bool legic_write_byte(uint16_t index, uint8_t byte, uint8_t addr_sz) {
406
407 bool isOK = false;
408 int8_t i = 40;
409 uint8_t edges = 0;
410 uint8_t cmd_sz = addr_sz+1+8+4; //crc+data+cmd;
411 uint32_t steps = 0, next_bit_at, start, crc, old_level = 0;
412
413 crc = legic4Crc(LEGIC_WRITE, index, byte, addr_sz+1);
414
415 // send write command
416 uint32_t cmd = LEGIC_WRITE;
417 cmd |= index << 1; // index
418 cmd |= byte << (addr_sz+1); // Data
419 cmd |= (crc & 0xF ) << (addr_sz+1+8); // CRC
420
421 WaitTicks(240);
422
423 frame_sendAsReader(cmd, cmd_sz);
424
425 LINE_IN;
426
427 start = GET_TICKS;
428
429 // ACK, - one single "1" bit after 3.6ms
430 // 3.6ms = 3600us * 1.5 = 5400ticks.
431 WaitTicks(5400);
432
433 next_bit_at = GET_TICKS + TAG_BIT_PERIOD;
434
435 while ( i-- ) {
436 WDT_HIT();
437 edges = 0;
438 while ( GET_TICKS < next_bit_at) {
439
440 volatile uint32_t level = (AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
441
442 if (level != old_level)
443 ++edges;
444
445 old_level = level;
446 }
447
448 next_bit_at += TAG_BIT_PERIOD;
449
450 // We expect 42 edges (ONE)
451 if(edges > 20 ) {
452 steps = ( (GET_TICKS - start) / TAG_BIT_PERIOD);
453 legic_prng_forward(steps);
454 isOK = true;
455 goto OUT;
456 }
457 }
458
459 OUT: ;
460 legic_prng_forward(1);
461
462 uint8_t cmdbytes[] = {1, isOK, BYTEx(steps, 0), BYTEx(steps, 1) };
463 LogTrace(cmdbytes, sizeof(cmdbytes), start, GET_TICKS, NULL, FALSE);
464 return isOK;
465 }
466
467 int LegicRfReader(uint16_t offset, uint16_t len, uint8_t iv) {
468
469 uint16_t i = 0;
470 uint8_t isOK = 1;
471 legic_card_select_t card;
472
473 LegicCommonInit();
474
475 if ( legic_select_card_iv(&card, iv) ) {
476 isOK = 0;
477 goto OUT;
478 }
479
480 if (len + offset >= card.cardsize)
481 len = card.cardsize - offset;
482
483 LED_B_ON();
484 while (i < len) {
485 int r = legic_read_byte(offset + i, card.cmdsize);
486
487 if (r == -1 || BUTTON_PRESS()) {
488 if ( MF_DBGLEVEL >= 2) DbpString("operation aborted");
489 isOK = 0;
490 goto OUT;
491 }
492 cardmem[i++] = r;
493 WDT_HIT();
494 }
495
496 OUT:
497 WDT_HIT();
498 switch_off_tag_rwd();
499 LEDsoff();
500 cmd_send(CMD_ACK, isOK, len, 0, cardmem, len);
501 return 0;
502 }
503
504 void LegicRfWriter(uint16_t offset, uint16_t len, uint8_t iv, uint8_t *data) {
505
506 #define LOWERLIMIT 4
507 uint8_t isOK = 1;
508 legic_card_select_t card;
509
510 // uid NOT is writeable.
511 if ( offset <= LOWERLIMIT ) {
512 isOK = 0;
513 goto OUT;
514 }
515
516 LegicCommonInit();
517
518 if ( legic_select_card_iv(&card, iv) ) {
519 isOK = 0;
520 goto OUT;
521 }
522
523 if ( len + offset + LOWERLIMIT >= card.cardsize) {
524 isOK = 0;
525 goto OUT;
526 }
527
528 LED_B_ON();
529 while( len > 0 ) {
530 --len;
531 if ( !legic_write_byte( len + offset, data[len], card.addrsize) ) {
532 Dbprintf("operation failed | %02X | %02X | %02X", len + offset, len, data[len] );
533 isOK = 0;
534 goto OUT;
535 }
536 WDT_HIT();
537 }
538 OUT:
539 cmd_send(CMD_ACK, isOK, 0,0,0,0);
540 switch_off_tag_rwd();
541 LEDsoff();
542 }
543
544 int legic_select_card_iv(legic_card_select_t *p_card, uint8_t iv){
545
546 if ( p_card == NULL ) return 1;
547
548 p_card->tagtype = setup_phase_reader(iv);
549
550 switch(p_card->tagtype) {
551 case 0x0d:
552 p_card->cmdsize = 6;
553 p_card->addrsize = 5;
554 p_card->cardsize = 22;
555 break;
556 case 0x1d:
557 p_card->cmdsize = 9;
558 p_card->addrsize = 8;
559 p_card->cardsize = 256;
560 break;
561 case 0x3d:
562 p_card->cmdsize = 11;
563 p_card->addrsize = 10;
564 p_card->cardsize = 1024;
565 break;
566 default:
567 p_card->cmdsize = 0;
568 p_card->addrsize = 0;
569 p_card->cardsize = 0;
570 return 2;
571 }
572 return 0;
573 }
574 int legic_select_card(legic_card_select_t *p_card){
575 return legic_select_card_iv(p_card, 0x01);
576 }
577
578 //-----------------------------------------------------------------------------
579 // Work with emulator memory
580 //
581 // Note: we call FpgaDownloadAndGo(FPGA_BITSTREAM_HF) here although FPGA is not
582 // involved in dealing with emulator memory. But if it is called later, it might
583 // destroy the Emulator Memory.
584 //-----------------------------------------------------------------------------
585 // arg0 = offset
586 // arg1 = num of bytes
587 void LegicEMemSet(uint32_t arg0, uint32_t arg1, uint8_t *data) {
588 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
589 legic_emlset_mem(data, arg0, arg1);
590 }
591 // arg0 = offset
592 // arg1 = num of bytes
593 void LegicEMemGet(uint32_t arg0, uint32_t arg1) {
594 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
595 uint8_t buf[USB_CMD_DATA_SIZE] = {0x00};
596 legic_emlget_mem(buf, arg0, arg1);
597 LED_B_ON();
598 cmd_send(CMD_ACK, arg0, arg1, 0, buf, USB_CMD_DATA_SIZE);
599 LED_B_OFF();
600 }
601 void legic_emlset_mem(uint8_t *data, int offset, int numofbytes) {
602 cardmem = BigBuf_get_EM_addr();
603 memcpy(cardmem + offset, data, numofbytes);
604 }
605 void legic_emlget_mem(uint8_t *data, int offset, int numofbytes) {
606 cardmem = BigBuf_get_EM_addr();
607 memcpy(data, cardmem + offset, numofbytes);
608 }
609
610 void LegicRfInfo(void){
611
612 int r;
613
614 uint8_t buf[sizeof(legic_card_select_t)] = {0x00};
615 legic_card_select_t *card = (legic_card_select_t*) buf;
616
617 LegicCommonInit();
618
619 if ( legic_select_card(card) ) {
620 cmd_send(CMD_ACK,0,0,0,0,0);
621 goto OUT;
622 }
623
624 // read UID bytes
625 for ( uint8_t i = 0; i < sizeof(card->uid); ++i) {
626 r = legic_read_byte(i, card->cmdsize);
627 if ( r == -1 ) {
628 cmd_send(CMD_ACK,0,0,0,0,0);
629 goto OUT;
630 }
631 card->uid[i] = r & 0xFF;
632 }
633
634 // MCC byte.
635 r = legic_read_byte(4, card->cmdsize);
636 uint32_t calc_mcc = CRC8Legic(card->uid, 4);;
637 if ( r != calc_mcc) {
638 cmd_send(CMD_ACK,0,0,0,0,0);
639 goto OUT;
640 }
641
642 // OK
643 cmd_send(CMD_ACK, 1, 0, 0, buf, sizeof(legic_card_select_t));
644
645 OUT:
646 switch_off_tag_rwd();
647 LEDsoff();
648 }
649
650 /* Handle (whether to respond) a frame in tag mode
651 * Only called when simulating a tag.
652 */
653 static void frame_handle_tag(struct legic_frame const * const f)
654 {
655 // log
656 //uint8_t cmdbytes[] = {bits, BYTEx(data, 0), BYTEx(data, 1)};
657 //LogTrace(cmdbytes, sizeof(cmdbytes), starttime, GET_TICKS, NULL, FALSE);
658
659 cardmem = BigBuf_get_EM_addr();
660
661 /* First Part of Handshake (IV) */
662 if(f->bits == 7) {
663
664 LED_C_ON();
665
666 // Reset prng timer
667 ResetTimer(prng_timer);
668
669 // IV from reader.
670 legic_prng_init(f->data);
671
672 // We should have three tagtypes with three different answers.
673 frame_send_tag(0x3d, 6); /* 0x3d^0x26 = 0x1B */
674
675 legic_state = STATE_IV;
676 legic_read_count = 0;
677 legic_prng_bc = 0;
678 legic_prng_iv = f->data;
679
680
681 ResetTimer(timer);
682 WaitUS(280);
683 return;
684 }
685
686 /* 0x19==??? */
687 if(legic_state == STATE_IV) {
688 uint32_t local_key = get_key_stream(3, 6);
689 int xored = 0x39 ^ local_key;
690 if((f->bits == 6) && (f->data == xored)) {
691 legic_state = STATE_CON;
692
693 ResetTimer(timer);
694 WaitUS(200);
695 return;
696
697 } else {
698 legic_state = STATE_DISCON;
699 LED_C_OFF();
700 Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv, f->data, local_key, xored);
701 return;
702 }
703 }
704
705 /* Read */
706 if(f->bits == 11) {
707 if(legic_state == STATE_CON) {
708 uint32_t key = get_key_stream(2, 11); //legic_phase_drift, 11);
709 uint16_t addr = f->data ^ key;
710 addr >>= 1;
711 uint8_t data = cardmem[addr];
712 int hash = legic4Crc(LEGIC_READ, addr, data, 11) << 8;
713
714 legic_read_count++;
715 legic_prng_forward(legic_reqresp_drift);
716
717 frame_send_tag(hash | data, 12);
718 ResetTimer(timer);
719 legic_prng_forward(2);
720 WaitTicks(330);
721 return;
722 }
723 }
724
725 /* Write */
726 if(f->bits == 23) {
727 uint32_t key = get_key_stream(-1, 23); //legic_frame_drift, 23);
728 uint16_t addr = f->data ^ key;
729 addr >>= 1;
730 addr &= 0x3ff;
731 uint32_t data = f->data ^ key;
732 data >>= 11;
733 data &= 0xff;
734
735 cardmem[addr] = data;
736 /* write command */
737 legic_state = STATE_DISCON;
738 LED_C_OFF();
739 Dbprintf("write - addr: %x, data: %x", addr, data);
740 // should send a ACK within 3.5ms too
741 return;
742 }
743
744 if(legic_state != STATE_DISCON) {
745 Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f->bits, f->data, legic_state, legic_read_count);
746 Dbprintf("IV: %03.3x", legic_prng_iv);
747 }
748
749 legic_state = STATE_DISCON;
750 legic_read_count = 0;
751 SpinDelay(10);
752 LED_C_OFF();
753 return;
754 }
755
756 /* Read bit by bit untill full frame is received
757 * Call to process frame end answer
758 */
759 static void emit(int bit) {
760
761 switch (bit) {
762 case 1:
763 frame_append_bit(&current_frame, 1);
764 break;
765 case 0:
766 frame_append_bit(&current_frame, 0);
767 break;
768 default:
769 if(current_frame.bits <= 4) {
770 frame_clean(&current_frame);
771 } else {
772 frame_handle_tag(&current_frame);
773 frame_clean(&current_frame);
774 }
775 WDT_HIT();
776 break;
777 }
778 }
779
780 void LegicRfSimulate(int phase, int frame, int reqresp)
781 {
782 /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,
783 * modulation mode set to 212kHz subcarrier. We are getting the incoming raw
784 * envelope waveform on DIN and should send our response on DOUT.
785 *
786 * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll
787 * measure the time between two rising edges on DIN, and no encoding on the
788 * subcarrier from card to reader, so we'll just shift out our verbatim data
789 * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear,
790 * seems to be 300us-ish.
791 */
792
793 int old_level = 0, active = 0;
794 legic_state = STATE_DISCON;
795
796 legic_phase_drift = phase;
797 legic_frame_drift = frame;
798 legic_reqresp_drift = reqresp;
799
800 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
801 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
802 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_212K);
803
804 /* Bitbang the receiver */
805 LINE_IN;
806
807 // need a way to determine which tagtype we are simulating
808
809 // hook up emulator memory
810 cardmem = BigBuf_get_EM_addr();
811
812 clear_trace();
813 set_tracing(TRUE);
814
815 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
816
817 StartTicks();
818
819 LED_B_ON();
820 DbpString("Starting Legic emulator, press button to end");
821
822 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
823 volatile uint32_t level = !!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
824
825 uint32_t time = GET_TICKS;
826
827 if (level != old_level) {
828
829 if (level) {
830
831 ResetTicks();
832
833 if (FUZZ_EQUAL(time, RWD_TIME_1, RWD_TIME_FUZZ)) {
834 /* 1 bit */
835 emit(1);
836 active = 1;
837 LED_A_ON();
838 } else if (FUZZ_EQUAL(time, RWD_TIME_0, RWD_TIME_FUZZ)) {
839 /* 0 bit */
840 emit(0);
841 active = 1;
842 LED_A_ON();
843 } else if (active) {
844 /* invalid */
845 emit(-1);
846 active = 0;
847 LED_A_OFF();
848 }
849 }
850 }
851
852 /* Frame end */
853 if(time >= (RWD_TIME_1+RWD_TIME_FUZZ) && active) {
854 emit(-1);
855 active = 0;
856 LED_A_OFF();
857 }
858
859 /*
860 * Disable the counter, Then wait for the clock to acknowledge the
861 * shutdown in its status register. Reading the SR has the
862 * side-effect of clearing any pending state in there.
863 */
864 if(time >= (20*RWD_TIME_1) && (timer->TC_SR & AT91C_TC_CLKSTA))
865 StopTicks();
866
867 old_level = level;
868 WDT_HIT();
869 }
870
871 WDT_HIT();
872 switch_off_tag_rwd();
873 LEDsoff();
874 cmd_send(CMD_ACK, 1, 0, 0, 0, 0);
875 }
876
877 //-----------------------------------------------------------------------------
878 // Code up a string of octets at layer 2 (including CRC, we don't generate
879 // that here) so that they can be transmitted to the reader. Doesn't transmit
880 // them yet, just leaves them ready to send in ToSend[].
881 //-----------------------------------------------------------------------------
882 // static void CodeLegicAsTag(const uint8_t *cmd, int len)
883 // {
884 // int i;
885
886 // ToSendReset();
887
888 // // Transmit a burst of ones, as the initial thing that lets the
889 // // reader get phase sync. This (TR1) must be > 80/fs, per spec,
890 // // but tag that I've tried (a Paypass) exceeds that by a fair bit,
891 // // so I will too.
892 // for(i = 0; i < 20; i++) {
893 // ToSendStuffBit(1);
894 // ToSendStuffBit(1);
895 // ToSendStuffBit(1);
896 // ToSendStuffBit(1);
897 // }
898
899 // // Send SOF.
900 // for(i = 0; i < 10; i++) {
901 // ToSendStuffBit(0);
902 // ToSendStuffBit(0);
903 // ToSendStuffBit(0);
904 // ToSendStuffBit(0);
905 // }
906 // for(i = 0; i < 2; i++) {
907 // ToSendStuffBit(1);
908 // ToSendStuffBit(1);
909 // ToSendStuffBit(1);
910 // ToSendStuffBit(1);
911 // }
912
913 // for(i = 0; i < len; i++) {
914 // int j;
915 // uint8_t b = cmd[i];
916
917 // // Start bit
918 // ToSendStuffBit(0);
919 // ToSendStuffBit(0);
920 // ToSendStuffBit(0);
921 // ToSendStuffBit(0);
922
923 // // Data bits
924 // for(j = 0; j < 8; j++) {
925 // if(b & 1) {
926 // ToSendStuffBit(1);
927 // ToSendStuffBit(1);
928 // ToSendStuffBit(1);
929 // ToSendStuffBit(1);
930 // } else {
931 // ToSendStuffBit(0);
932 // ToSendStuffBit(0);
933 // ToSendStuffBit(0);
934 // ToSendStuffBit(0);
935 // }
936 // b >>= 1;
937 // }
938
939 // // Stop bit
940 // ToSendStuffBit(1);
941 // ToSendStuffBit(1);
942 // ToSendStuffBit(1);
943 // ToSendStuffBit(1);
944 // }
945
946 // // Send EOF.
947 // for(i = 0; i < 10; i++) {
948 // ToSendStuffBit(0);
949 // ToSendStuffBit(0);
950 // ToSendStuffBit(0);
951 // ToSendStuffBit(0);
952 // }
953 // for(i = 0; i < 2; i++) {
954 // ToSendStuffBit(1);
955 // ToSendStuffBit(1);
956 // ToSendStuffBit(1);
957 // ToSendStuffBit(1);
958 // }
959
960 // // Convert from last byte pos to length
961 // ToSendMax++;
962 // }
963
964 //-----------------------------------------------------------------------------
965 // The software UART that receives commands from the reader, and its state
966 // variables.
967 //-----------------------------------------------------------------------------
968 /*
969 static struct {
970 enum {
971 STATE_UNSYNCD,
972 STATE_GOT_FALLING_EDGE_OF_SOF,
973 STATE_AWAITING_START_BIT,
974 STATE_RECEIVING_DATA
975 } state;
976 uint16_t shiftReg;
977 int bitCnt;
978 int byteCnt;
979 int byteCntMax;
980 int posCnt;
981 uint8_t *output;
982 } Uart;
983 */
984 /* Receive & handle a bit coming from the reader.
985 *
986 * This function is called 4 times per bit (every 2 subcarrier cycles).
987 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
988 *
989 * LED handling:
990 * LED A -> ON once we have received the SOF and are expecting the rest.
991 * LED A -> OFF once we have received EOF or are in error state or unsynced
992 *
993 * Returns: true if we received a EOF
994 * false if we are still waiting for some more
995 */
996 // static RAMFUNC int HandleLegicUartBit(uint8_t bit)
997 // {
998 // switch(Uart.state) {
999 // case STATE_UNSYNCD:
1000 // if(!bit) {
1001 // // we went low, so this could be the beginning of an SOF
1002 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
1003 // Uart.posCnt = 0;
1004 // Uart.bitCnt = 0;
1005 // }
1006 // break;
1007
1008 // case STATE_GOT_FALLING_EDGE_OF_SOF:
1009 // Uart.posCnt++;
1010 // if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
1011 // if(bit) {
1012 // if(Uart.bitCnt > 9) {
1013 // // we've seen enough consecutive
1014 // // zeros that it's a valid SOF
1015 // Uart.posCnt = 0;
1016 // Uart.byteCnt = 0;
1017 // Uart.state = STATE_AWAITING_START_BIT;
1018 // LED_A_ON(); // Indicate we got a valid SOF
1019 // } else {
1020 // // didn't stay down long enough
1021 // // before going high, error
1022 // Uart.state = STATE_UNSYNCD;
1023 // }
1024 // } else {
1025 // // do nothing, keep waiting
1026 // }
1027 // Uart.bitCnt++;
1028 // }
1029 // if(Uart.posCnt >= 4) Uart.posCnt = 0;
1030 // if(Uart.bitCnt > 12) {
1031 // // Give up if we see too many zeros without
1032 // // a one, too.
1033 // LED_A_OFF();
1034 // Uart.state = STATE_UNSYNCD;
1035 // }
1036 // break;
1037
1038 // case STATE_AWAITING_START_BIT:
1039 // Uart.posCnt++;
1040 // if(bit) {
1041 // if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
1042 // // stayed high for too long between
1043 // // characters, error
1044 // Uart.state = STATE_UNSYNCD;
1045 // }
1046 // } else {
1047 // // falling edge, this starts the data byte
1048 // Uart.posCnt = 0;
1049 // Uart.bitCnt = 0;
1050 // Uart.shiftReg = 0;
1051 // Uart.state = STATE_RECEIVING_DATA;
1052 // }
1053 // break;
1054
1055 // case STATE_RECEIVING_DATA:
1056 // Uart.posCnt++;
1057 // if(Uart.posCnt == 2) {
1058 // // time to sample a bit
1059 // Uart.shiftReg >>= 1;
1060 // if(bit) {
1061 // Uart.shiftReg |= 0x200;
1062 // }
1063 // Uart.bitCnt++;
1064 // }
1065 // if(Uart.posCnt >= 4) {
1066 // Uart.posCnt = 0;
1067 // }
1068 // if(Uart.bitCnt == 10) {
1069 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
1070 // {
1071 // // this is a data byte, with correct
1072 // // start and stop bits
1073 // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
1074 // Uart.byteCnt++;
1075
1076 // if(Uart.byteCnt >= Uart.byteCntMax) {
1077 // // Buffer overflowed, give up
1078 // LED_A_OFF();
1079 // Uart.state = STATE_UNSYNCD;
1080 // } else {
1081 // // so get the next byte now
1082 // Uart.posCnt = 0;
1083 // Uart.state = STATE_AWAITING_START_BIT;
1084 // }
1085 // } else if (Uart.shiftReg == 0x000) {
1086 // // this is an EOF byte
1087 // LED_A_OFF(); // Finished receiving
1088 // Uart.state = STATE_UNSYNCD;
1089 // if (Uart.byteCnt != 0) {
1090 // return TRUE;
1091 // }
1092 // } else {
1093 // // this is an error
1094 // LED_A_OFF();
1095 // Uart.state = STATE_UNSYNCD;
1096 // }
1097 // }
1098 // break;
1099
1100 // default:
1101 // LED_A_OFF();
1102 // Uart.state = STATE_UNSYNCD;
1103 // break;
1104 // }
1105
1106 // return FALSE;
1107 // }
1108 /*
1109
1110 static void UartReset() {
1111 Uart.byteCntMax = 3;
1112 Uart.state = STATE_UNSYNCD;
1113 Uart.byteCnt = 0;
1114 Uart.bitCnt = 0;
1115 Uart.posCnt = 0;
1116 memset(Uart.output, 0x00, 3);
1117 }
1118 */
1119 // static void UartInit(uint8_t *data) {
1120 // Uart.output = data;
1121 // UartReset();
1122 // }
1123
1124 //=============================================================================
1125 // An LEGIC reader. We take layer two commands, code them
1126 // appropriately, and then send them to the tag. We then listen for the
1127 // tag's response, which we leave in the buffer to be demodulated on the
1128 // PC side.
1129 //=============================================================================
1130 /*
1131 static struct {
1132 enum {
1133 DEMOD_UNSYNCD,
1134 DEMOD_PHASE_REF_TRAINING,
1135 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
1136 DEMOD_GOT_FALLING_EDGE_OF_SOF,
1137 DEMOD_AWAITING_START_BIT,
1138 DEMOD_RECEIVING_DATA
1139 } state;
1140 int bitCount;
1141 int posCount;
1142 int thisBit;
1143 uint16_t shiftReg;
1144 uint8_t *output;
1145 int len;
1146 int sumI;
1147 int sumQ;
1148 } Demod;
1149 */
1150 /*
1151 * Handles reception of a bit from the tag
1152 *
1153 * This function is called 2 times per bit (every 4 subcarrier cycles).
1154 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1155 *
1156 * LED handling:
1157 * LED C -> ON once we have received the SOF and are expecting the rest.
1158 * LED C -> OFF once we have received EOF or are unsynced
1159 *
1160 * Returns: true if we received a EOF
1161 * false if we are still waiting for some more
1162 *
1163 */
1164
1165 /*
1166 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq)
1167 {
1168 int v = 0;
1169 int ai = ABS(ci);
1170 int aq = ABS(cq);
1171 int halfci = (ai >> 1);
1172 int halfcq = (aq >> 1);
1173
1174 switch(Demod.state) {
1175 case DEMOD_UNSYNCD:
1176
1177 CHECK_FOR_SUBCARRIER()
1178
1179 if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1180 Demod.state = DEMOD_PHASE_REF_TRAINING;
1181 Demod.sumI = ci;
1182 Demod.sumQ = cq;
1183 Demod.posCount = 1;
1184 }
1185 break;
1186
1187 case DEMOD_PHASE_REF_TRAINING:
1188 if(Demod.posCount < 8) {
1189
1190 CHECK_FOR_SUBCARRIER()
1191
1192 if (v > SUBCARRIER_DETECT_THRESHOLD) {
1193 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
1194 // note: synchronization time > 80 1/fs
1195 Demod.sumI += ci;
1196 Demod.sumQ += cq;
1197 ++Demod.posCount;
1198 } else {
1199 // subcarrier lost
1200 Demod.state = DEMOD_UNSYNCD;
1201 }
1202 } else {
1203 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
1204 }
1205 break;
1206
1207 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
1208
1209 MAKE_SOFT_DECISION()
1210
1211 //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq );
1212 // logic '0' detected
1213 if (v <= 0) {
1214
1215 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
1216
1217 // start of SOF sequence
1218 Demod.posCount = 0;
1219 } else {
1220 // maximum length of TR1 = 200 1/fs
1221 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD;
1222 }
1223 ++Demod.posCount;
1224 break;
1225
1226 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
1227 ++Demod.posCount;
1228
1229 MAKE_SOFT_DECISION()
1230
1231 if(v > 0) {
1232 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1233 if(Demod.posCount < 10*2) {
1234 Demod.state = DEMOD_UNSYNCD;
1235 } else {
1236 LED_C_ON(); // Got SOF
1237 Demod.state = DEMOD_AWAITING_START_BIT;
1238 Demod.posCount = 0;
1239 Demod.len = 0;
1240 }
1241 } else {
1242 // low phase of SOF too long (> 12 etu)
1243 if(Demod.posCount > 13*2) {
1244 Demod.state = DEMOD_UNSYNCD;
1245 LED_C_OFF();
1246 }
1247 }
1248 break;
1249
1250 case DEMOD_AWAITING_START_BIT:
1251 ++Demod.posCount;
1252
1253 MAKE_SOFT_DECISION()
1254
1255 if(v > 0) {
1256 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1257 if(Demod.posCount > 3*2) {
1258 Demod.state = DEMOD_UNSYNCD;
1259 LED_C_OFF();
1260 }
1261 } else {
1262 // start bit detected
1263 Demod.bitCount = 0;
1264 Demod.posCount = 1; // this was the first half
1265 Demod.thisBit = v;
1266 Demod.shiftReg = 0;
1267 Demod.state = DEMOD_RECEIVING_DATA;
1268 }
1269 break;
1270
1271 case DEMOD_RECEIVING_DATA:
1272
1273 MAKE_SOFT_DECISION()
1274
1275 if(Demod.posCount == 0) {
1276 // first half of bit
1277 Demod.thisBit = v;
1278 Demod.posCount = 1;
1279 } else {
1280 // second half of bit
1281 Demod.thisBit += v;
1282 Demod.shiftReg >>= 1;
1283 // logic '1'
1284 if(Demod.thisBit > 0)
1285 Demod.shiftReg |= 0x200;
1286
1287 ++Demod.bitCount;
1288
1289 if(Demod.bitCount == 10) {
1290
1291 uint16_t s = Demod.shiftReg;
1292
1293 if((s & 0x200) && !(s & 0x001)) {
1294 // stop bit == '1', start bit == '0'
1295 uint8_t b = (s >> 1);
1296 Demod.output[Demod.len] = b;
1297 ++Demod.len;
1298 Demod.state = DEMOD_AWAITING_START_BIT;
1299 } else {
1300 Demod.state = DEMOD_UNSYNCD;
1301 LED_C_OFF();
1302
1303 if(s == 0x000) {
1304 // This is EOF (start, stop and all data bits == '0'
1305 return TRUE;
1306 }
1307 }
1308 }
1309 Demod.posCount = 0;
1310 }
1311 break;
1312
1313 default:
1314 Demod.state = DEMOD_UNSYNCD;
1315 LED_C_OFF();
1316 break;
1317 }
1318 return FALSE;
1319 }
1320 */
1321 /*
1322 // Clear out the state of the "UART" that receives from the tag.
1323 static void DemodReset() {
1324 Demod.len = 0;
1325 Demod.state = DEMOD_UNSYNCD;
1326 Demod.posCount = 0;
1327 Demod.sumI = 0;
1328 Demod.sumQ = 0;
1329 Demod.bitCount = 0;
1330 Demod.thisBit = 0;
1331 Demod.shiftReg = 0;
1332 memset(Demod.output, 0x00, 3);
1333 }
1334
1335 static void DemodInit(uint8_t *data) {
1336 Demod.output = data;
1337 DemodReset();
1338 }
1339 */
1340
1341 /*
1342 * Demodulate the samples we received from the tag, also log to tracebuffer
1343 * quiet: set to 'TRUE' to disable debug output
1344 */
1345
1346 /*
1347 #define LEGIC_DMA_BUFFER_SIZE 256
1348
1349 static void GetSamplesForLegicDemod(int n, bool quiet)
1350 {
1351 int max = 0;
1352 bool gotFrame = FALSE;
1353 int lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1354 int ci, cq, samples = 0;
1355
1356 BigBuf_free();
1357
1358 // And put the FPGA in the appropriate mode
1359 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
1360
1361 // The response (tag -> reader) that we're receiving.
1362 // Set up the demodulator for tag -> reader responses.
1363 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1364
1365 // The DMA buffer, used to stream samples from the FPGA
1366 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE);
1367 int8_t *upTo = dmaBuf;
1368
1369 // Setup and start DMA.
1370 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){
1371 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1372 return;
1373 }
1374
1375 // Signal field is ON with the appropriate LED:
1376 LED_D_ON();
1377 for(;;) {
1378 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
1379 if(behindBy > max) max = behindBy;
1380
1381 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) {
1382 ci = upTo[0];
1383 cq = upTo[1];
1384 upTo += 2;
1385 if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) {
1386 upTo = dmaBuf;
1387 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1388 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE;
1389 }
1390 lastRxCounter -= 2;
1391 if(lastRxCounter <= 0)
1392 lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1393
1394 samples += 2;
1395
1396 gotFrame = HandleLegicSamplesDemod(ci , cq );
1397 if ( gotFrame )
1398 break;
1399 }
1400
1401 if(samples > n || gotFrame)
1402 break;
1403 }
1404
1405 FpgaDisableSscDma();
1406
1407 if (!quiet && Demod.len == 0) {
1408 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d",
1409 max,
1410 samples,
1411 gotFrame,
1412 Demod.len,
1413 Demod.sumI,
1414 Demod.sumQ
1415 );
1416 }
1417
1418 //Tracing
1419 if (Demod.len > 0) {
1420 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
1421 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE);
1422 }
1423 }
1424
1425 */
1426
1427 //-----------------------------------------------------------------------------
1428 // Transmit the command (to the tag) that was placed in ToSend[].
1429 //-----------------------------------------------------------------------------
1430 /*
1431 static void TransmitForLegic(void)
1432 {
1433 int c;
1434
1435 FpgaSetupSsc();
1436
1437 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
1438 AT91C_BASE_SSC->SSC_THR = 0xff;
1439
1440 // Signal field is ON with the appropriate Red LED
1441 LED_D_ON();
1442
1443 // Signal we are transmitting with the Green LED
1444 LED_B_ON();
1445 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1446
1447 for(c = 0; c < 10;) {
1448 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1449 AT91C_BASE_SSC->SSC_THR = 0xff;
1450 c++;
1451 }
1452 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1453 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1454 (void)r;
1455 }
1456 WDT_HIT();
1457 }
1458
1459 c = 0;
1460 for(;;) {
1461 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1462 AT91C_BASE_SSC->SSC_THR = ToSend[c];
1463 legic_prng_forward(1); // forward the lfsr
1464 c++;
1465 if(c >= ToSendMax) {
1466 break;
1467 }
1468 }
1469 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1470 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1471 (void)r;
1472 }
1473 WDT_HIT();
1474 }
1475 LED_B_OFF();
1476 }
1477 */
1478
1479 //-----------------------------------------------------------------------------
1480 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1481 // so that it is ready to transmit to the tag using TransmitForLegic().
1482 //-----------------------------------------------------------------------------
1483 /*
1484 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1485 {
1486 int i, j;
1487 uint8_t b;
1488
1489 ToSendReset();
1490
1491 // Send SOF
1492 for(i = 0; i < 7; i++)
1493 ToSendStuffBit(1);
1494
1495
1496 for(i = 0; i < cmdlen; i++) {
1497 // Start bit
1498 ToSendStuffBit(0);
1499
1500 // Data bits
1501 b = cmd[i];
1502 for(j = 0; j < bits; j++) {
1503 if(b & 1) {
1504 ToSendStuffBit(1);
1505 } else {
1506 ToSendStuffBit(0);
1507 }
1508 b >>= 1;
1509 }
1510 }
1511
1512 // Convert from last character reference to length
1513 ++ToSendMax;
1514 }
1515 */
1516 /**
1517 Convenience function to encode, transmit and trace Legic comms
1518 **/
1519 /*
1520 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1521 {
1522 CodeLegicBitsAsReader(cmd, cmdlen, bits);
1523 TransmitForLegic();
1524 if (tracing) {
1525 uint8_t parity[1] = {0x00};
1526 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE);
1527 }
1528 }
1529
1530 */
1531 // Set up LEGIC communication
1532 /*
1533 void ice_legic_setup() {
1534
1535 // standard things.
1536 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1537 BigBuf_free(); BigBuf_Clear_ext(false);
1538 clear_trace();
1539 set_tracing(TRUE);
1540 DemodReset();
1541 UartReset();
1542
1543 // Set up the synchronous serial port
1544 FpgaSetupSsc();
1545
1546 // connect Demodulated Signal to ADC:
1547 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1548
1549 // Signal field is on with the appropriate LED
1550 LED_D_ON();
1551 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1552 SpinDelay(20);
1553 // Start the timer
1554 //StartCountSspClk();
1555
1556 // initalize CRC
1557 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
1558
1559 // initalize prng
1560 legic_prng_init(0);
1561 }
1562 */
Impressum, Datenschutz