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