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