]> git.zerfleddert.de Git - proxmark3-svn/blob - armsrc/legicrf.c
UPD: got the latest updates (@badboy) from @zhovner mfdread.
[proxmark3-svn] / armsrc / legicrf.c
1 //-----------------------------------------------------------------------------
2 // (c) 2009 Henryk Plötz <henryk@ploetzli.ch>
3 //
4 // This code is licensed to you under the terms of the GNU GPL, version 2 or,
5 // at your option, any later version. See the LICENSE.txt file for the text of
6 // the license.
7 //-----------------------------------------------------------------------------
8 // LEGIC RF simulation code
9 //-----------------------------------------------------------------------------
10 #include "legicrf.h"
11
12 static struct legic_frame {
13 uint8_t bits;
14 uint32_t data;
15 } current_frame;
16
17 static enum {
18 STATE_DISCON,
19 STATE_IV,
20 STATE_CON,
21 } legic_state;
22
23 static crc_t legic_crc;
24 static int legic_read_count;
25 static uint32_t legic_prng_bc;
26 static uint32_t legic_prng_iv;
27
28 static int legic_phase_drift;
29 static int legic_frame_drift;
30 static int legic_reqresp_drift;
31
32 AT91PS_TC timer;
33 AT91PS_TC prng_timer;
34
35 /*
36 static void setup_timer(void) {
37 // Set up Timer 1 to use for measuring time between pulses. Since we're bit-banging
38 // this it won't be terribly accurate but should be good enough.
39 //
40 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC1);
41 timer = AT91C_BASE_TC1;
42 timer->TC_CCR = AT91C_TC_CLKDIS;
43 timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK;
44 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
45
46 //
47 // Set up Timer 2 to use for measuring time between frames in
48 // tag simulation mode. Runs 4x faster as Timer 1
49 //
50 AT91C_BASE_PMC->PMC_PCER = (1 << AT91C_ID_TC2);
51 prng_timer = AT91C_BASE_TC2;
52 prng_timer->TC_CCR = AT91C_TC_CLKDIS;
53 prng_timer->TC_CMR = AT91C_TC_CLKS_TIMER_DIV2_CLOCK;
54 prng_timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
55 }
56
57 AT91C_BASE_PMC->PMC_PCER |= (0x1 << 12) | (0x1 << 13) | (0x1 << 14);
58 AT91C_BASE_TCB->TCB_BMR = AT91C_TCB_TC0XC0S_NONE | AT91C_TCB_TC1XC1S_TIOA0 | AT91C_TCB_TC2XC2S_NONE;
59
60 // fast clock
61 AT91C_BASE_TC0->TC_CCR = AT91C_TC_CLKDIS; // timer disable
62 AT91C_BASE_TC0->TC_CMR = AT91C_TC_CLKS_TIMER_DIV3_CLOCK | // MCK(48MHz)/32 -- tick=1.5mks
63 AT91C_TC_WAVE | AT91C_TC_WAVESEL_UP_AUTO | AT91C_TC_ACPA_CLEAR |
64 AT91C_TC_ACPC_SET | AT91C_TC_ASWTRG_SET;
65 AT91C_BASE_TC0->TC_RA = 1;
66 AT91C_BASE_TC0->TC_RC = 0xBFFF + 1; // 0xC000
67
68 */
69
70 // At TIMER_CLOCK3 (MCK/32)
71 // testing calculating in (us) microseconds.
72 #define RWD_TIME_1 120 // READER_TIME_PAUSE 20us off, 80us on = 100us 80 * 1.5 == 120ticks
73 #define RWD_TIME_0 60 // READER_TIME_PAUSE 20us off, 40us on = 60us 40 * 1.5 == 60ticks
74 #define RWD_TIME_PAUSE 30 // 20us == 20 * 1.5 == 30ticks */
75 #define TAG_BIT_PERIOD 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 isOK = 1;
530 legic_card_select_t card;
531
532 LegicCommonInit();
533
534 if ( legic_select_card(&card) ) {
535 isOK = 0;
536 goto OUT;
537 }
538
539 switch_off_tag_rwd();
540
541 if (bytes == -1)
542 bytes = card.cardsize;
543
544 if (bytes + offset >= card.cardsize)
545 bytes = card.cardsize - offset;
546
547 // Start setup and read bytes.
548 setup_phase_reader(iv);
549
550 LED_B_ON();
551 while (byte_index < bytes) {
552 int r = legic_read_byte(byte_index + offset, card.cmdsize);
553
554 if (r == -1 || BUTTON_PRESS()) {
555 if ( MF_DBGLEVEL >= 3) DbpString("operation aborted");
556 isOK = 0;
557 goto OUT;
558 }
559 cardmem[byte_index++] = r;
560 WDT_HIT();
561 }
562
563 OUT:
564 WDT_HIT();
565 switch_off_tag_rwd();
566 LEDsoff();
567 uint8_t len = (bytes & 0x3FF);
568 cmd_send(CMD_ACK,isOK,len,0,cardmem,len);
569 return 0;
570 }
571
572 /*int _LegicRfWriter(int offset, int bytes, int addr_sz, uint8_t *BigBuf, int RoundBruteforceValue) {
573 int byte_index=0;
574
575 LED_B_ON();
576 setup_phase_reader(iv);
577 //legic_prng_forward(2);
578 while(byte_index < bytes) {
579 int r;
580
581 //check if the DCF should be changed
582 if ( (offset == 0x05) && (bytes == 0x02) ) {
583 //write DCF in reverse order (addr 0x06 before 0x05)
584 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
585 //legic_prng_forward(1);
586 if(r == 0) {
587 byte_index++;
588 r = legic_write_byte(BigBuf[(0x06-byte_index)], (0x06-byte_index), addr_sz, RoundBruteforceValue);
589 }
590 //legic_prng_forward(1);
591 }
592 else {
593 r = legic_write_byte(BigBuf[byte_index+offset], byte_index+offset, addr_sz, RoundBruteforceValue);
594 }
595 if((r != 0) || BUTTON_PRESS()) {
596 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
597 switch_off_tag_rwd();
598 LED_B_OFF();
599 LED_C_OFF();
600 return -1;
601 }
602
603 WDT_HIT();
604 byte_index++;
605 if(byte_index & 0x10) LED_C_ON(); else LED_C_OFF();
606 }
607 LED_B_OFF();
608 LED_C_OFF();
609 DbpString("write successful");
610 return 0;
611 }*/
612
613 void LegicRfWriter(int offset, int bytes, int iv) {
614
615 int byte_index = 0, addr_sz = 0;
616
617 LegicCommonInit();
618
619 if ( MF_DBGLEVEL >= 2) DbpString("setting up legic card");
620
621 uint32_t tag_type = setup_phase_reader(iv);
622
623 switch_off_tag_rwd();
624
625 switch(tag_type) {
626 case 0x0d:
627 if(offset+bytes > 22) {
628 Dbprintf("Error: can not write to 0x%03.3x on MIM22", offset + bytes);
629 return;
630 }
631 addr_sz = 5;
632 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM22 card found, writing 0x%02.2x - 0x%02.2x ...", offset, offset + bytes);
633 break;
634 case 0x1d:
635 if(offset+bytes > 0x100) {
636 Dbprintf("Error: can not write to 0x%03.3x on MIM256", offset + bytes);
637 return;
638 }
639 addr_sz = 8;
640 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM256 card found, writing 0x%02.2x - 0x%02.2x ...", offset, offset + bytes);
641 break;
642 case 0x3d:
643 if(offset+bytes > 0x400) {
644 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", offset + bytes);
645 return;
646 }
647 addr_sz = 10;
648 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM1024 card found, writing 0x%03.3x - 0x%03.3x ...", offset, offset + bytes);
649 break;
650 default:
651 Dbprintf("No or unknown card found, aborting");
652 return;
653 }
654
655 LED_B_ON();
656 setup_phase_reader(iv);
657 int r = 0;
658 while(byte_index < bytes) {
659
660 //check if the DCF should be changed
661 if ( ((byte_index+offset) == 0x05) && (bytes >= 0x02) ) {
662 //write DCF in reverse order (addr 0x06 before 0x05)
663 r = legic_write_byte(cardmem[(0x06-byte_index)], (0x06-byte_index), addr_sz);
664
665 // write second byte on success...
666 if(r == 0) {
667 byte_index++;
668 r = legic_write_byte(cardmem[(0x06-byte_index)], (0x06-byte_index), addr_sz);
669 }
670 }
671 else {
672 r = legic_write_byte(cardmem[byte_index+offset], byte_index+offset, addr_sz);
673 }
674
675 if ((r != 0) || BUTTON_PRESS()) {
676 Dbprintf("operation aborted @ 0x%03.3x", byte_index);
677 switch_off_tag_rwd();
678 LEDsoff();
679 return;
680 }
681
682 WDT_HIT();
683 byte_index++;
684 }
685 LEDsoff();
686 if ( MF_DBGLEVEL >= 1) DbpString("write successful");
687 }
688
689 void LegicRfRawWriter(int address, int byte, int iv) {
690
691 int byte_index = 0, addr_sz = 0;
692
693 LegicCommonInit();
694
695 if ( MF_DBGLEVEL >= 2) DbpString("setting up legic card");
696
697 uint32_t tag_type = setup_phase_reader(iv);
698
699 switch_off_tag_rwd();
700
701 switch(tag_type) {
702 case 0x0d:
703 if(address > 22) {
704 Dbprintf("Error: can not write to 0x%03.3x on MIM22", address);
705 return;
706 }
707 addr_sz = 5;
708 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM22 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address, byte);
709 break;
710 case 0x1d:
711 if(address > 0x100) {
712 Dbprintf("Error: can not write to 0x%03.3x on MIM256", address);
713 return;
714 }
715 addr_sz = 8;
716 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM256 card found, writing at addr 0x%02.2x - value 0x%02.2x ...", address, byte);
717 break;
718 case 0x3d:
719 if(address > 0x400) {
720 Dbprintf("Error: can not write to 0x%03.3x on MIM1024", address);
721 return;
722 }
723 addr_sz = 10;
724 if ( MF_DBGLEVEL >= 2) Dbprintf("MIM1024 card found, writing at addr 0x%03.3x - value 0x%03.3x ...", address, byte);
725 break;
726 default:
727 Dbprintf("No or unknown card found, aborting");
728 return;
729 }
730
731 Dbprintf("integer value: %d address: %d addr_sz: %d", byte, address, addr_sz);
732 LED_B_ON();
733
734 setup_phase_reader(iv);
735
736 int r = legic_write_byte(byte, address, addr_sz);
737
738 if((r != 0) || BUTTON_PRESS()) {
739 Dbprintf("operation aborted @ 0x%03.3x (%1d)", byte_index, r);
740 switch_off_tag_rwd();
741 LEDsoff();
742 return;
743 }
744
745 LEDsoff();
746 if ( MF_DBGLEVEL >= 1) DbpString("write successful");
747 }
748
749 int legic_select_card(legic_card_select_t *p_card){
750
751 if ( p_card == NULL ) return 1;
752
753 p_card->tagtype = setup_phase_reader(0x1);
754
755 switch(p_card->tagtype) {
756 case 0x0d:
757 p_card->cmdsize = 6;
758 p_card->cardsize = 22;
759 break;
760 case 0x1d:
761 p_card->cmdsize = 9;
762 p_card->cardsize = 256;
763 break;
764 case 0x3d:
765 p_card->cmdsize = 11;
766 p_card->cardsize = 1024;
767 break;
768 default:
769 p_card->cmdsize = 0;
770 p_card->cardsize = 0;
771 return 2;
772 break;
773 }
774 return 0;
775 }
776
777 void LegicRfInfo(void){
778
779 uint8_t buf[sizeof(legic_card_select_t)] = {0x00};
780 legic_card_select_t *card = (legic_card_select_t*) buf;
781
782 LegicCommonInit();
783
784 if ( legic_select_card(card) ) {
785 cmd_send(CMD_ACK,0,0,0,0,0);
786 goto OUT;
787 }
788
789 // read UID bytes.
790 for ( uint8_t i = 0; i < sizeof(card->uid); ++i) {
791 int r = legic_read_byte(i, card->cmdsize);
792 if ( r == -1 ) {
793 cmd_send(CMD_ACK,0,0,0,0,0);
794 goto OUT;
795 }
796 card->uid[i] = r & 0xFF;
797 }
798
799 cmd_send(CMD_ACK, 1 ,0 , 0, buf, sizeof(legic_card_select_t));
800
801 OUT:
802 switch_off_tag_rwd();
803 LEDsoff();
804 }
805
806 /* Handle (whether to respond) a frame in tag mode
807 * Only called when simulating a tag.
808 */
809 static void frame_handle_tag(struct legic_frame const * const f)
810 {
811 uint8_t *BigBuf = BigBuf_get_addr();
812
813 /* First Part of Handshake (IV) */
814 if(f->bits == 7) {
815
816 LED_C_ON();
817
818 // Reset prng timer
819 ResetTimer(prng_timer);
820
821 legic_prng_init(f->data);
822 frame_send_tag(0x3d, 6, 1); /* 0x3d^0x26 = 0x1B */
823 legic_state = STATE_IV;
824 legic_read_count = 0;
825 legic_prng_bc = 0;
826 legic_prng_iv = f->data;
827
828
829 ResetTimer(timer);
830 WaitUS(280);
831 return;
832 }
833
834 /* 0x19==??? */
835 if(legic_state == STATE_IV) {
836 int local_key = get_key_stream(3, 6);
837 int xored = 0x39 ^ local_key;
838 if((f->bits == 6) && (f->data == xored)) {
839 legic_state = STATE_CON;
840
841 ResetTimer(timer);
842 WaitUS(200);
843 return;
844
845 } else {
846 legic_state = STATE_DISCON;
847 LED_C_OFF();
848 Dbprintf("iv: %02x frame: %02x key: %02x xored: %02x", legic_prng_iv, f->data, local_key, xored);
849 return;
850 }
851 }
852
853 /* Read */
854 if(f->bits == 11) {
855 if(legic_state == STATE_CON) {
856 int key = get_key_stream(2, 11); //legic_phase_drift, 11);
857 int addr = f->data ^ key; addr = addr >> 1;
858 int data = BigBuf[addr];
859 int hash = legic4Crc(LEGIC_READ, addr, data, 11) << 8;
860 BigBuf[OFFSET_LOG+legic_read_count] = (uint8_t)addr;
861 legic_read_count++;
862
863 //Dbprintf("Data:%03.3x, key:%03.3x, addr: %03.3x, read_c:%u", f->data, key, addr, read_c);
864 legic_prng_forward(legic_reqresp_drift);
865
866 frame_send_tag(hash | data, 12, 1);
867
868 ResetTimer(timer);
869 legic_prng_forward(2);
870 WaitUS(180);
871 return;
872 }
873 }
874
875 /* Write */
876 if(f->bits == 23) {
877 int key = get_key_stream(-1, 23); //legic_frame_drift, 23);
878 int addr = f->data ^ key; addr = addr >> 1; addr = addr & 0x3ff;
879 int data = f->data ^ key; data = data >> 11; data = data & 0xff;
880
881 /* write command */
882 legic_state = STATE_DISCON;
883 LED_C_OFF();
884 Dbprintf("write - addr: %x, data: %x", addr, data);
885 return;
886 }
887
888 if(legic_state != STATE_DISCON) {
889 Dbprintf("Unexpected: sz:%u, Data:%03.3x, State:%u, Count:%u", f->bits, f->data, legic_state, legic_read_count);
890 int i;
891 Dbprintf("IV: %03.3x", legic_prng_iv);
892 for(i = 0; i<legic_read_count; i++) {
893 Dbprintf("Read Nb: %u, Addr: %u", i, BigBuf[OFFSET_LOG+i]);
894 }
895
896 for(i = -1; i<legic_read_count; i++) {
897 uint32_t t;
898 t = BigBuf[OFFSET_LOG+256+i*4];
899 t |= BigBuf[OFFSET_LOG+256+i*4+1] << 8;
900 t |= BigBuf[OFFSET_LOG+256+i*4+2] <<16;
901 t |= BigBuf[OFFSET_LOG+256+i*4+3] <<24;
902
903 Dbprintf("Cycles: %u, Frame Length: %u, Time: %u",
904 BigBuf[OFFSET_LOG+128+i],
905 BigBuf[OFFSET_LOG+384+i],
906 t);
907 }
908 }
909 legic_state = STATE_DISCON;
910 legic_read_count = 0;
911 SpinDelay(10);
912 LED_C_OFF();
913 return;
914 }
915
916 /* Read bit by bit untill full frame is received
917 * Call to process frame end answer
918 */
919 static void emit(int bit) {
920
921 switch (bit) {
922 case 1:
923 frame_append_bit(&current_frame, 1);
924 break;
925 case 0:
926 frame_append_bit(&current_frame, 0);
927 break;
928 default:
929 if(current_frame.bits <= 4) {
930 frame_clean(&current_frame);
931 } else {
932 frame_handle_tag(&current_frame);
933 frame_clean(&current_frame);
934 }
935 WDT_HIT();
936 break;
937 }
938 }
939
940 void LegicRfSimulate(int phase, int frame, int reqresp)
941 {
942 /* ADC path high-frequency peak detector, FPGA in high-frequency simulator mode,
943 * modulation mode set to 212kHz subcarrier. We are getting the incoming raw
944 * envelope waveform on DIN and should send our response on DOUT.
945 *
946 * The LEGIC RF protocol is pulse-pause-encoding from reader to card, so we'll
947 * measure the time between two rising edges on DIN, and no encoding on the
948 * subcarrier from card to reader, so we'll just shift out our verbatim data
949 * on DOUT, 1 bit is 100us. The time from reader to card frame is still unclear,
950 * seems to be 300us-ish.
951 */
952
953 legic_phase_drift = phase;
954 legic_frame_drift = frame;
955 legic_reqresp_drift = reqresp;
956
957 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
958 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
959 FpgaSetupSsc();
960 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_212K);
961
962 /* Bitbang the receiver */
963 AT91C_BASE_PIOA->PIO_ODR = GPIO_SSC_DIN;
964 AT91C_BASE_PIOA->PIO_PER = GPIO_SSC_DIN;
965
966 //setup_timer();
967 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
968
969 int old_level = 0;
970 int active = 0;
971 legic_state = STATE_DISCON;
972
973 LED_B_ON();
974 DbpString("Starting Legic emulator, press button to end");
975
976 while(!BUTTON_PRESS() && !usb_poll_validate_length()) {
977 int level = !!(AT91C_BASE_PIOA->PIO_PDSR & GPIO_SSC_DIN);
978 int time = timer->TC_CV;
979
980 if(level != old_level) {
981 if(level == 1) {
982 timer->TC_CCR = AT91C_TC_CLKEN | AT91C_TC_SWTRG;
983
984 if (FUZZ_EQUAL(time, RWD_TIME_1, RWD_TIME_FUZZ)) {
985 /* 1 bit */
986 emit(1);
987 active = 1;
988 LED_A_ON();
989 } else if (FUZZ_EQUAL(time, RWD_TIME_0, RWD_TIME_FUZZ)) {
990 /* 0 bit */
991 emit(0);
992 active = 1;
993 LED_A_ON();
994 } else if (active) {
995 /* invalid */
996 emit(-1);
997 active = 0;
998 LED_A_OFF();
999 }
1000 }
1001 }
1002
1003 /* Frame end */
1004 if(time >= (RWD_TIME_1+RWD_TIME_FUZZ) && active) {
1005 emit(-1);
1006 active = 0;
1007 LED_A_OFF();
1008 }
1009
1010 if(time >= (20*RWD_TIME_1) && (timer->TC_SR & AT91C_TC_CLKSTA)) {
1011 timer->TC_CCR = AT91C_TC_CLKDIS;
1012 }
1013
1014 old_level = level;
1015 WDT_HIT();
1016 }
1017 if ( MF_DBGLEVEL >= 1) DbpString("Stopped");
1018 LEDsoff();
1019 }
1020
1021 //-----------------------------------------------------------------------------
1022 // Code up a string of octets at layer 2 (including CRC, we don't generate
1023 // that here) so that they can be transmitted to the reader. Doesn't transmit
1024 // them yet, just leaves them ready to send in ToSend[].
1025 //-----------------------------------------------------------------------------
1026 // static void CodeLegicAsTag(const uint8_t *cmd, int len)
1027 // {
1028 // int i;
1029
1030 // ToSendReset();
1031
1032 // // Transmit a burst of ones, as the initial thing that lets the
1033 // // reader get phase sync. This (TR1) must be > 80/fs, per spec,
1034 // // but tag that I've tried (a Paypass) exceeds that by a fair bit,
1035 // // so I will too.
1036 // for(i = 0; i < 20; i++) {
1037 // ToSendStuffBit(1);
1038 // ToSendStuffBit(1);
1039 // ToSendStuffBit(1);
1040 // ToSendStuffBit(1);
1041 // }
1042
1043 // // Send SOF.
1044 // for(i = 0; i < 10; i++) {
1045 // ToSendStuffBit(0);
1046 // ToSendStuffBit(0);
1047 // ToSendStuffBit(0);
1048 // ToSendStuffBit(0);
1049 // }
1050 // for(i = 0; i < 2; i++) {
1051 // ToSendStuffBit(1);
1052 // ToSendStuffBit(1);
1053 // ToSendStuffBit(1);
1054 // ToSendStuffBit(1);
1055 // }
1056
1057 // for(i = 0; i < len; i++) {
1058 // int j;
1059 // uint8_t b = cmd[i];
1060
1061 // // Start bit
1062 // ToSendStuffBit(0);
1063 // ToSendStuffBit(0);
1064 // ToSendStuffBit(0);
1065 // ToSendStuffBit(0);
1066
1067 // // Data bits
1068 // for(j = 0; j < 8; j++) {
1069 // if(b & 1) {
1070 // ToSendStuffBit(1);
1071 // ToSendStuffBit(1);
1072 // ToSendStuffBit(1);
1073 // ToSendStuffBit(1);
1074 // } else {
1075 // ToSendStuffBit(0);
1076 // ToSendStuffBit(0);
1077 // ToSendStuffBit(0);
1078 // ToSendStuffBit(0);
1079 // }
1080 // b >>= 1;
1081 // }
1082
1083 // // Stop bit
1084 // ToSendStuffBit(1);
1085 // ToSendStuffBit(1);
1086 // ToSendStuffBit(1);
1087 // ToSendStuffBit(1);
1088 // }
1089
1090 // // Send EOF.
1091 // for(i = 0; i < 10; i++) {
1092 // ToSendStuffBit(0);
1093 // ToSendStuffBit(0);
1094 // ToSendStuffBit(0);
1095 // ToSendStuffBit(0);
1096 // }
1097 // for(i = 0; i < 2; i++) {
1098 // ToSendStuffBit(1);
1099 // ToSendStuffBit(1);
1100 // ToSendStuffBit(1);
1101 // ToSendStuffBit(1);
1102 // }
1103
1104 // // Convert from last byte pos to length
1105 // ToSendMax++;
1106 // }
1107
1108 //-----------------------------------------------------------------------------
1109 // The software UART that receives commands from the reader, and its state
1110 // variables.
1111 //-----------------------------------------------------------------------------
1112 /*
1113 static struct {
1114 enum {
1115 STATE_UNSYNCD,
1116 STATE_GOT_FALLING_EDGE_OF_SOF,
1117 STATE_AWAITING_START_BIT,
1118 STATE_RECEIVING_DATA
1119 } state;
1120 uint16_t shiftReg;
1121 int bitCnt;
1122 int byteCnt;
1123 int byteCntMax;
1124 int posCnt;
1125 uint8_t *output;
1126 } Uart;
1127 */
1128 /* Receive & handle a bit coming from the reader.
1129 *
1130 * This function is called 4 times per bit (every 2 subcarrier cycles).
1131 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1132 *
1133 * LED handling:
1134 * LED A -> ON once we have received the SOF and are expecting the rest.
1135 * LED A -> OFF once we have received EOF or are in error state or unsynced
1136 *
1137 * Returns: true if we received a EOF
1138 * false if we are still waiting for some more
1139 */
1140 // static RAMFUNC int HandleLegicUartBit(uint8_t bit)
1141 // {
1142 // switch(Uart.state) {
1143 // case STATE_UNSYNCD:
1144 // if(!bit) {
1145 // // we went low, so this could be the beginning of an SOF
1146 // Uart.state = STATE_GOT_FALLING_EDGE_OF_SOF;
1147 // Uart.posCnt = 0;
1148 // Uart.bitCnt = 0;
1149 // }
1150 // break;
1151
1152 // case STATE_GOT_FALLING_EDGE_OF_SOF:
1153 // Uart.posCnt++;
1154 // if(Uart.posCnt == 2) { // sample every 4 1/fs in the middle of a bit
1155 // if(bit) {
1156 // if(Uart.bitCnt > 9) {
1157 // // we've seen enough consecutive
1158 // // zeros that it's a valid SOF
1159 // Uart.posCnt = 0;
1160 // Uart.byteCnt = 0;
1161 // Uart.state = STATE_AWAITING_START_BIT;
1162 // LED_A_ON(); // Indicate we got a valid SOF
1163 // } else {
1164 // // didn't stay down long enough
1165 // // before going high, error
1166 // Uart.state = STATE_UNSYNCD;
1167 // }
1168 // } else {
1169 // // do nothing, keep waiting
1170 // }
1171 // Uart.bitCnt++;
1172 // }
1173 // if(Uart.posCnt >= 4) Uart.posCnt = 0;
1174 // if(Uart.bitCnt > 12) {
1175 // // Give up if we see too many zeros without
1176 // // a one, too.
1177 // LED_A_OFF();
1178 // Uart.state = STATE_UNSYNCD;
1179 // }
1180 // break;
1181
1182 // case STATE_AWAITING_START_BIT:
1183 // Uart.posCnt++;
1184 // if(bit) {
1185 // if(Uart.posCnt > 50/2) { // max 57us between characters = 49 1/fs, max 3 etus after low phase of SOF = 24 1/fs
1186 // // stayed high for too long between
1187 // // characters, error
1188 // Uart.state = STATE_UNSYNCD;
1189 // }
1190 // } else {
1191 // // falling edge, this starts the data byte
1192 // Uart.posCnt = 0;
1193 // Uart.bitCnt = 0;
1194 // Uart.shiftReg = 0;
1195 // Uart.state = STATE_RECEIVING_DATA;
1196 // }
1197 // break;
1198
1199 // case STATE_RECEIVING_DATA:
1200 // Uart.posCnt++;
1201 // if(Uart.posCnt == 2) {
1202 // // time to sample a bit
1203 // Uart.shiftReg >>= 1;
1204 // if(bit) {
1205 // Uart.shiftReg |= 0x200;
1206 // }
1207 // Uart.bitCnt++;
1208 // }
1209 // if(Uart.posCnt >= 4) {
1210 // Uart.posCnt = 0;
1211 // }
1212 // if(Uart.bitCnt == 10) {
1213 // if((Uart.shiftReg & 0x200) && !(Uart.shiftReg & 0x001))
1214 // {
1215 // // this is a data byte, with correct
1216 // // start and stop bits
1217 // Uart.output[Uart.byteCnt] = (Uart.shiftReg >> 1) & 0xff;
1218 // Uart.byteCnt++;
1219
1220 // if(Uart.byteCnt >= Uart.byteCntMax) {
1221 // // Buffer overflowed, give up
1222 // LED_A_OFF();
1223 // Uart.state = STATE_UNSYNCD;
1224 // } else {
1225 // // so get the next byte now
1226 // Uart.posCnt = 0;
1227 // Uart.state = STATE_AWAITING_START_BIT;
1228 // }
1229 // } else if (Uart.shiftReg == 0x000) {
1230 // // this is an EOF byte
1231 // LED_A_OFF(); // Finished receiving
1232 // Uart.state = STATE_UNSYNCD;
1233 // if (Uart.byteCnt != 0) {
1234 // return TRUE;
1235 // }
1236 // } else {
1237 // // this is an error
1238 // LED_A_OFF();
1239 // Uart.state = STATE_UNSYNCD;
1240 // }
1241 // }
1242 // break;
1243
1244 // default:
1245 // LED_A_OFF();
1246 // Uart.state = STATE_UNSYNCD;
1247 // break;
1248 // }
1249
1250 // return FALSE;
1251 // }
1252 /*
1253
1254 static void UartReset() {
1255 Uart.byteCntMax = 3;
1256 Uart.state = STATE_UNSYNCD;
1257 Uart.byteCnt = 0;
1258 Uart.bitCnt = 0;
1259 Uart.posCnt = 0;
1260 memset(Uart.output, 0x00, 3);
1261 }
1262 */
1263 // static void UartInit(uint8_t *data) {
1264 // Uart.output = data;
1265 // UartReset();
1266 // }
1267
1268 //=============================================================================
1269 // An LEGIC reader. We take layer two commands, code them
1270 // appropriately, and then send them to the tag. We then listen for the
1271 // tag's response, which we leave in the buffer to be demodulated on the
1272 // PC side.
1273 //=============================================================================
1274 /*
1275 static struct {
1276 enum {
1277 DEMOD_UNSYNCD,
1278 DEMOD_PHASE_REF_TRAINING,
1279 DEMOD_AWAITING_FALLING_EDGE_OF_SOF,
1280 DEMOD_GOT_FALLING_EDGE_OF_SOF,
1281 DEMOD_AWAITING_START_BIT,
1282 DEMOD_RECEIVING_DATA
1283 } state;
1284 int bitCount;
1285 int posCount;
1286 int thisBit;
1287 uint16_t shiftReg;
1288 uint8_t *output;
1289 int len;
1290 int sumI;
1291 int sumQ;
1292 } Demod;
1293 */
1294 /*
1295 * Handles reception of a bit from the tag
1296 *
1297 * This function is called 2 times per bit (every 4 subcarrier cycles).
1298 * Subcarrier frequency fs is 212kHz, 1/fs = 4,72us, i.e. function is called every 9,44us
1299 *
1300 * LED handling:
1301 * LED C -> ON once we have received the SOF and are expecting the rest.
1302 * LED C -> OFF once we have received EOF or are unsynced
1303 *
1304 * Returns: true if we received a EOF
1305 * false if we are still waiting for some more
1306 *
1307 */
1308
1309 /*
1310 static RAMFUNC int HandleLegicSamplesDemod(int ci, int cq)
1311 {
1312 int v = 0;
1313 int ai = ABS(ci);
1314 int aq = ABS(cq);
1315 int halfci = (ai >> 1);
1316 int halfcq = (aq >> 1);
1317
1318 switch(Demod.state) {
1319 case DEMOD_UNSYNCD:
1320
1321 CHECK_FOR_SUBCARRIER()
1322
1323 if(v > SUBCARRIER_DETECT_THRESHOLD) { // subcarrier detected
1324 Demod.state = DEMOD_PHASE_REF_TRAINING;
1325 Demod.sumI = ci;
1326 Demod.sumQ = cq;
1327 Demod.posCount = 1;
1328 }
1329 break;
1330
1331 case DEMOD_PHASE_REF_TRAINING:
1332 if(Demod.posCount < 8) {
1333
1334 CHECK_FOR_SUBCARRIER()
1335
1336 if (v > SUBCARRIER_DETECT_THRESHOLD) {
1337 // set the reference phase (will code a logic '1') by averaging over 32 1/fs.
1338 // note: synchronization time > 80 1/fs
1339 Demod.sumI += ci;
1340 Demod.sumQ += cq;
1341 ++Demod.posCount;
1342 } else {
1343 // subcarrier lost
1344 Demod.state = DEMOD_UNSYNCD;
1345 }
1346 } else {
1347 Demod.state = DEMOD_AWAITING_FALLING_EDGE_OF_SOF;
1348 }
1349 break;
1350
1351 case DEMOD_AWAITING_FALLING_EDGE_OF_SOF:
1352
1353 MAKE_SOFT_DECISION()
1354
1355 //Dbprintf("ICE: %d %d %d %d %d", v, Demod.sumI, Demod.sumQ, ci, cq );
1356 // logic '0' detected
1357 if (v <= 0) {
1358
1359 Demod.state = DEMOD_GOT_FALLING_EDGE_OF_SOF;
1360
1361 // start of SOF sequence
1362 Demod.posCount = 0;
1363 } else {
1364 // maximum length of TR1 = 200 1/fs
1365 if(Demod.posCount > 25*2) Demod.state = DEMOD_UNSYNCD;
1366 }
1367 ++Demod.posCount;
1368 break;
1369
1370 case DEMOD_GOT_FALLING_EDGE_OF_SOF:
1371 ++Demod.posCount;
1372
1373 MAKE_SOFT_DECISION()
1374
1375 if(v > 0) {
1376 // low phase of SOF too short (< 9 etu). Note: spec is >= 10, but FPGA tends to "smear" edges
1377 if(Demod.posCount < 10*2) {
1378 Demod.state = DEMOD_UNSYNCD;
1379 } else {
1380 LED_C_ON(); // Got SOF
1381 Demod.state = DEMOD_AWAITING_START_BIT;
1382 Demod.posCount = 0;
1383 Demod.len = 0;
1384 }
1385 } else {
1386 // low phase of SOF too long (> 12 etu)
1387 if(Demod.posCount > 13*2) {
1388 Demod.state = DEMOD_UNSYNCD;
1389 LED_C_OFF();
1390 }
1391 }
1392 break;
1393
1394 case DEMOD_AWAITING_START_BIT:
1395 ++Demod.posCount;
1396
1397 MAKE_SOFT_DECISION()
1398
1399 if(v > 0) {
1400 // max 19us between characters = 16 1/fs, max 3 etu after low phase of SOF = 24 1/fs
1401 if(Demod.posCount > 3*2) {
1402 Demod.state = DEMOD_UNSYNCD;
1403 LED_C_OFF();
1404 }
1405 } else {
1406 // start bit detected
1407 Demod.bitCount = 0;
1408 Demod.posCount = 1; // this was the first half
1409 Demod.thisBit = v;
1410 Demod.shiftReg = 0;
1411 Demod.state = DEMOD_RECEIVING_DATA;
1412 }
1413 break;
1414
1415 case DEMOD_RECEIVING_DATA:
1416
1417 MAKE_SOFT_DECISION()
1418
1419 if(Demod.posCount == 0) {
1420 // first half of bit
1421 Demod.thisBit = v;
1422 Demod.posCount = 1;
1423 } else {
1424 // second half of bit
1425 Demod.thisBit += v;
1426 Demod.shiftReg >>= 1;
1427 // logic '1'
1428 if(Demod.thisBit > 0)
1429 Demod.shiftReg |= 0x200;
1430
1431 ++Demod.bitCount;
1432
1433 if(Demod.bitCount == 10) {
1434
1435 uint16_t s = Demod.shiftReg;
1436
1437 if((s & 0x200) && !(s & 0x001)) {
1438 // stop bit == '1', start bit == '0'
1439 uint8_t b = (s >> 1);
1440 Demod.output[Demod.len] = b;
1441 ++Demod.len;
1442 Demod.state = DEMOD_AWAITING_START_BIT;
1443 } else {
1444 Demod.state = DEMOD_UNSYNCD;
1445 LED_C_OFF();
1446
1447 if(s == 0x000) {
1448 // This is EOF (start, stop and all data bits == '0'
1449 return TRUE;
1450 }
1451 }
1452 }
1453 Demod.posCount = 0;
1454 }
1455 break;
1456
1457 default:
1458 Demod.state = DEMOD_UNSYNCD;
1459 LED_C_OFF();
1460 break;
1461 }
1462 return FALSE;
1463 }
1464 */
1465 /*
1466 // Clear out the state of the "UART" that receives from the tag.
1467 static void DemodReset() {
1468 Demod.len = 0;
1469 Demod.state = DEMOD_UNSYNCD;
1470 Demod.posCount = 0;
1471 Demod.sumI = 0;
1472 Demod.sumQ = 0;
1473 Demod.bitCount = 0;
1474 Demod.thisBit = 0;
1475 Demod.shiftReg = 0;
1476 memset(Demod.output, 0x00, 3);
1477 }
1478
1479 static void DemodInit(uint8_t *data) {
1480 Demod.output = data;
1481 DemodReset();
1482 }
1483 */
1484
1485 /*
1486 * Demodulate the samples we received from the tag, also log to tracebuffer
1487 * quiet: set to 'TRUE' to disable debug output
1488 */
1489
1490 /*
1491 #define LEGIC_DMA_BUFFER_SIZE 256
1492
1493 static void GetSamplesForLegicDemod(int n, bool quiet)
1494 {
1495 int max = 0;
1496 bool gotFrame = FALSE;
1497 int lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1498 int ci, cq, samples = 0;
1499
1500 BigBuf_free();
1501
1502 // And put the FPGA in the appropriate mode
1503 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_RX_XCORR | FPGA_HF_READER_RX_XCORR_QUARTER_FREQ);
1504
1505 // The response (tag -> reader) that we're receiving.
1506 // Set up the demodulator for tag -> reader responses.
1507 DemodInit(BigBuf_malloc(MAX_FRAME_SIZE));
1508
1509 // The DMA buffer, used to stream samples from the FPGA
1510 int8_t *dmaBuf = (int8_t*) BigBuf_malloc(LEGIC_DMA_BUFFER_SIZE);
1511 int8_t *upTo = dmaBuf;
1512
1513 // Setup and start DMA.
1514 if ( !FpgaSetupSscDma((uint8_t*) dmaBuf, LEGIC_DMA_BUFFER_SIZE) ){
1515 if (MF_DBGLEVEL > 1) Dbprintf("FpgaSetupSscDma failed. Exiting");
1516 return;
1517 }
1518
1519 // Signal field is ON with the appropriate LED:
1520 LED_D_ON();
1521 for(;;) {
1522 int behindBy = lastRxCounter - AT91C_BASE_PDC_SSC->PDC_RCR;
1523 if(behindBy > max) max = behindBy;
1524
1525 while(((lastRxCounter-AT91C_BASE_PDC_SSC->PDC_RCR) & (LEGIC_DMA_BUFFER_SIZE-1)) > 2) {
1526 ci = upTo[0];
1527 cq = upTo[1];
1528 upTo += 2;
1529 if(upTo >= dmaBuf + LEGIC_DMA_BUFFER_SIZE) {
1530 upTo = dmaBuf;
1531 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) upTo;
1532 AT91C_BASE_PDC_SSC->PDC_RNCR = LEGIC_DMA_BUFFER_SIZE;
1533 }
1534 lastRxCounter -= 2;
1535 if(lastRxCounter <= 0)
1536 lastRxCounter = LEGIC_DMA_BUFFER_SIZE;
1537
1538 samples += 2;
1539
1540 gotFrame = HandleLegicSamplesDemod(ci , cq );
1541 if ( gotFrame )
1542 break;
1543 }
1544
1545 if(samples > n || gotFrame)
1546 break;
1547 }
1548
1549 FpgaDisableSscDma();
1550
1551 if (!quiet && Demod.len == 0) {
1552 Dbprintf("max behindby = %d, samples = %d, gotFrame = %d, Demod.len = %d, Demod.sumI = %d, Demod.sumQ = %d",
1553 max,
1554 samples,
1555 gotFrame,
1556 Demod.len,
1557 Demod.sumI,
1558 Demod.sumQ
1559 );
1560 }
1561
1562 //Tracing
1563 if (Demod.len > 0) {
1564 uint8_t parity[MAX_PARITY_SIZE] = {0x00};
1565 LogTrace(Demod.output, Demod.len, 0, 0, parity, FALSE);
1566 }
1567 }
1568
1569 */
1570
1571 //-----------------------------------------------------------------------------
1572 // Transmit the command (to the tag) that was placed in ToSend[].
1573 //-----------------------------------------------------------------------------
1574 /*
1575 static void TransmitForLegic(void)
1576 {
1577 int c;
1578
1579 FpgaSetupSsc();
1580
1581 while(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))
1582 AT91C_BASE_SSC->SSC_THR = 0xff;
1583
1584 // Signal field is ON with the appropriate Red LED
1585 LED_D_ON();
1586
1587 // Signal we are transmitting with the Green LED
1588 LED_B_ON();
1589 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1590
1591 for(c = 0; c < 10;) {
1592 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1593 AT91C_BASE_SSC->SSC_THR = 0xff;
1594 c++;
1595 }
1596 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1597 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1598 (void)r;
1599 }
1600 WDT_HIT();
1601 }
1602
1603 c = 0;
1604 for(;;) {
1605 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY)) {
1606 AT91C_BASE_SSC->SSC_THR = ToSend[c];
1607 legic_prng_forward(1); // forward the lfsr
1608 c++;
1609 if(c >= ToSendMax) {
1610 break;
1611 }
1612 }
1613 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
1614 volatile uint32_t r = AT91C_BASE_SSC->SSC_RHR;
1615 (void)r;
1616 }
1617 WDT_HIT();
1618 }
1619 LED_B_OFF();
1620 }
1621 */
1622
1623 //-----------------------------------------------------------------------------
1624 // Code a layer 2 command (string of octets, including CRC) into ToSend[],
1625 // so that it is ready to transmit to the tag using TransmitForLegic().
1626 //-----------------------------------------------------------------------------
1627 /*
1628 static void CodeLegicBitsAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1629 {
1630 int i, j;
1631 uint8_t b;
1632
1633 ToSendReset();
1634
1635 // Send SOF
1636 for(i = 0; i < 7; i++)
1637 ToSendStuffBit(1);
1638
1639
1640 for(i = 0; i < cmdlen; i++) {
1641 // Start bit
1642 ToSendStuffBit(0);
1643
1644 // Data bits
1645 b = cmd[i];
1646 for(j = 0; j < bits; j++) {
1647 if(b & 1) {
1648 ToSendStuffBit(1);
1649 } else {
1650 ToSendStuffBit(0);
1651 }
1652 b >>= 1;
1653 }
1654 }
1655
1656 // Convert from last character reference to length
1657 ++ToSendMax;
1658 }
1659 */
1660 /**
1661 Convenience function to encode, transmit and trace Legic comms
1662 **/
1663 /*
1664 static void CodeAndTransmitLegicAsReader(const uint8_t *cmd, uint8_t cmdlen, int bits)
1665 {
1666 CodeLegicBitsAsReader(cmd, cmdlen, bits);
1667 TransmitForLegic();
1668 if (tracing) {
1669 uint8_t parity[1] = {0x00};
1670 LogTrace(cmd, cmdlen, 0, 0, parity, TRUE);
1671 }
1672 }
1673
1674 */
1675 // Set up LEGIC communication
1676 /*
1677 void ice_legic_setup() {
1678
1679 // standard things.
1680 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1681 BigBuf_free(); BigBuf_Clear_ext(false);
1682 clear_trace();
1683 set_tracing(TRUE);
1684 DemodReset();
1685 UartReset();
1686
1687 // Set up the synchronous serial port
1688 FpgaSetupSsc();
1689
1690 // connect Demodulated Signal to ADC:
1691 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1692
1693 // Signal field is on with the appropriate LED
1694 LED_D_ON();
1695 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER_TX | FPGA_HF_READER_TX_SHALLOW_MOD);
1696 SpinDelay(20);
1697 // Start the timer
1698 //StartCountSspClk();
1699
1700 // initalize CRC
1701 crc_init(&legic_crc, 4, 0x19 >> 1, 0x5, 0);
1702
1703 // initalize prng
1704 legic_prng_init(0);
1705 }
1706 */
Impressum, Datenschutz