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