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