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