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