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