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