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