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