]> git.zerfleddert.de Git - proxmark3-svn/blame - armsrc/iso15693.c
iso14443b: trying to approach iClass
[proxmark3-svn] / armsrc / iso15693.c
CommitLineData
15c4dc5a 1//-----------------------------------------------------------------------------
bd20f8f4 2// Jonathan Westhues, split Nov 2006
3// Modified by Greg Jones, Jan 2009
e6304bca 4// Modified by Adrian Dabrowski "atrox", Mar-Sept 2010,Oct 2011
a66f26da 5// Modified by piwi, Oct 2018
bd20f8f4 6//
7// This code is licensed to you under the terms of the GNU GPL, version 2 or,
8// at your option, any later version. See the LICENSE.txt file for the text of
9// the license.
10//-----------------------------------------------------------------------------
15c4dc5a 11// Routines to support ISO 15693. This includes both the reader software and
8c6cca0b 12// the `fake tag' modes.
15c4dc5a 13//-----------------------------------------------------------------------------
8c6cca0b 14
15// The ISO 15693 describes two transmission modes from reader to tag, and four
16// transmission modes from tag to reader. As of Oct 2018 this code supports
17// both reader modes and the high speed variant with one subcarrier from card to reader.
18// As long as the card fully support ISO 15693 this is no problem, since the
a66f26da 19// reader chooses both data rates, but some non-standard tags do not.
8c6cca0b 20// For card simulation, the code supports both high and low speed modes with one subcarrier.
9455b51c 21//
22// VCD (reader) -> VICC (tag)
23// 1 out of 256:
a66f26da 24// data rate: 1,66 kbit/s (fc/8192)
25// used for long range
9455b51c 26// 1 out of 4:
a66f26da 27// data rate: 26,48 kbit/s (fc/512)
28// used for short range, high speed
8c6cca0b 29//
9455b51c 30// VICC (tag) -> VCD (reader)
31// Modulation:
a66f26da 32// ASK / one subcarrier (423,75 khz)
33// FSK / two subcarriers (423,75 khz && 484,28 khz)
9455b51c 34// Data Rates / Modes:
a66f26da 35// low ASK: 6,62 kbit/s
36// low FSK: 6.67 kbit/s
37// high ASK: 26,48 kbit/s
38// high FSK: 26,69 kbit/s
9455b51c 39//-----------------------------------------------------------------------------
9455b51c 40
41
42// Random Remarks:
43// *) UID is always used "transmission order" (LSB), which is reverse to display order
44
45// TODO / BUGS / ISSUES:
8c6cca0b 46// *) signal decoding is unable to detect collisions.
47// *) add anti-collision support for inventory-commands
e6304bca 48// *) read security status of a block
8c6cca0b 49// *) sniffing and simulation do not support two subcarrier modes.
d9de20fa 50// *) remove or refactor code under "deprecated"
9455b51c 51// *) document all the functions
52
d9de20fa 53#include "iso15693.h"
bd20f8f4 54
e30c654b 55#include "proxmark3.h"
f7e3ed82 56#include "util.h"
15c4dc5a 57#include "apps.h"
9ab7a6c7 58#include "string.h"
9455b51c 59#include "iso15693tools.h"
8c6cca0b 60#include "protocols.h"
902cb3c0 61#include "cmd.h"
d9de20fa 62#include "BigBuf.h"
fc52fbd4 63#include "fpgaloader.h"
15c4dc5a 64
15c4dc5a 65#define arraylen(x) (sizeof(x)/sizeof((x)[0]))
66
c41dd5f9 67// Delays in SSP_CLK ticks.
68// SSP_CLK runs at 13,56MHz / 32 = 423.75kHz when simulating a tag
69#define DELAY_READER_TO_ARM 8
70#define DELAY_ARM_TO_READER 0
71//SSP_CLK runs at 13.56MHz / 4 = 3,39MHz when acting as reader. All values should be multiples of 16
72#define DELAY_TAG_TO_ARM 32
73#define DELAY_ARM_TO_TAG 16
74
70b2fc0a 75static int DEBUG = 0;
76
c41dd5f9 77
78// specific LogTrace function for ISO15693: the duration needs to be scaled because otherwise it won't fit into a uint16_t
79bool LogTrace_ISO15693(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag) {
80 uint32_t duration = timestamp_end - timestamp_start;
81 duration /= 32;
82 timestamp_end = timestamp_start + duration;
83 return LogTrace(btBytes, iLen, timestamp_start, timestamp_end, parity, readerToTag);
84}
85
86
9455b51c 87///////////////////////////////////////////////////////////////////////
88// ISO 15693 Part 2 - Air Interface
3d2c9c9b 89// This section basically contains transmission and receiving of bits
9455b51c 90///////////////////////////////////////////////////////////////////////
91
8c6cca0b 92// buffers
3d2c9c9b 93#define ISO15693_DMA_BUFFER_SIZE 2048 // must be a power of 2
d9de20fa 94#define ISO15693_MAX_RESPONSE_LENGTH 36 // allows read single block with the maximum block size of 256bits. Read multiple blocks not supported yet
95#define ISO15693_MAX_COMMAND_LENGTH 45 // allows write single block with the maximum block size of 256bits. Write multiple blocks not supported yet
8c6cca0b 96
9455b51c 97// ---------------------------
8c6cca0b 98// Signal Processing
9455b51c 99// ---------------------------
100
101// prepare data using "1 out of 4" code for later transmission
8c6cca0b 102// resulting data rate is 26.48 kbit/s (fc/512)
9455b51c 103// cmd ... data
104// n ... length of data
c41dd5f9 105void CodeIso15693AsReader(uint8_t *cmd, int n) {
15c4dc5a 106
107 ToSendReset();
108
9455b51c 109 // SOF for 1of4
c41dd5f9 110 ToSend[++ToSendMax] = 0x84; //10000100
111
112 // data
113 for (int i = 0; i < n; i++) {
114 for (int j = 0; j < 8; j += 2) {
115 int these = (cmd[i] >> j) & 0x03;
15c4dc5a 116 switch(these) {
117 case 0:
c41dd5f9 118 ToSend[++ToSendMax] = 0x40; //01000000
15c4dc5a 119 break;
120 case 1:
c41dd5f9 121 ToSend[++ToSendMax] = 0x10; //00010000
15c4dc5a 122 break;
123 case 2:
c41dd5f9 124 ToSend[++ToSendMax] = 0x04; //00000100
15c4dc5a 125 break;
126 case 3:
c41dd5f9 127 ToSend[++ToSendMax] = 0x01; //00000001
15c4dc5a 128 break;
129 }
130 }
131 }
a66f26da 132
c41dd5f9 133 // EOF
134 ToSend[++ToSendMax] = 0x20; //0010 + 0000 padding
135
bdf96aae 136 ToSendMax++;
15c4dc5a 137}
138
70b2fc0a 139// encode data using "1 out of 256" scheme
8c6cca0b 140// data rate is 1,66 kbit/s (fc/8192)
9455b51c 141// is designed for more robust communication over longer distances
142static void CodeIso15693AsReader256(uint8_t *cmd, int n)
15c4dc5a 143{
9455b51c 144 ToSendReset();
145
9455b51c 146 // SOF for 1of256
c41dd5f9 147 ToSend[++ToSendMax] = 0x81; //10000001
148
149 // data
150 for(int i = 0; i < n; i++) {
151 for (int j = 0; j <= 255; j++) {
152 if (cmd[i] == j) {
9455b51c 153 ToSendStuffBit(0);
9455b51c 154 ToSendStuffBit(1);
c41dd5f9 155 } else {
156 ToSendStuffBit(0);
157 ToSendStuffBit(0);
8c6cca0b 158 }
159 }
15c4dc5a 160 }
c41dd5f9 161
9455b51c 162 // EOF
c41dd5f9 163 ToSend[++ToSendMax] = 0x20; //0010 + 0000 padding
8c6cca0b 164
165 ToSendMax++;
166}
167
168
3d2c9c9b 169// static uint8_t encode4Bits(const uint8_t b) {
170 // uint8_t c = b & 0xF;
171 // // OTA, the least significant bits first
172 // // The columns are
173 // // 1 - Bit value to send
174 // // 2 - Reversed (big-endian)
175 // // 3 - Manchester Encoded
176 // // 4 - Hex values
177
178 // switch(c){
179 // // 1 2 3 4
180 // case 15: return 0x55; // 1111 -> 1111 -> 01010101 -> 0x55
181 // case 14: return 0x95; // 1110 -> 0111 -> 10010101 -> 0x95
182 // case 13: return 0x65; // 1101 -> 1011 -> 01100101 -> 0x65
183 // case 12: return 0xa5; // 1100 -> 0011 -> 10100101 -> 0xa5
184 // case 11: return 0x59; // 1011 -> 1101 -> 01011001 -> 0x59
185 // case 10: return 0x99; // 1010 -> 0101 -> 10011001 -> 0x99
186 // case 9: return 0x69; // 1001 -> 1001 -> 01101001 -> 0x69
187 // case 8: return 0xa9; // 1000 -> 0001 -> 10101001 -> 0xa9
188 // case 7: return 0x56; // 0111 -> 1110 -> 01010110 -> 0x56
189 // case 6: return 0x96; // 0110 -> 0110 -> 10010110 -> 0x96
190 // case 5: return 0x66; // 0101 -> 1010 -> 01100110 -> 0x66
191 // case 4: return 0xa6; // 0100 -> 0010 -> 10100110 -> 0xa6
192 // case 3: return 0x5a; // 0011 -> 1100 -> 01011010 -> 0x5a
193 // case 2: return 0x9a; // 0010 -> 0100 -> 10011010 -> 0x9a
194 // case 1: return 0x6a; // 0001 -> 1000 -> 01101010 -> 0x6a
195 // default: return 0xaa; // 0000 -> 0000 -> 10101010 -> 0xaa
196
197 // }
198// }
199
8efd0b80 200static const uint8_t encode_4bits[16] = { 0xaa, 0x6a, 0x9a, 0x5a, 0xa6, 0x66, 0x96, 0x56, 0xa9, 0x69, 0x99, 0x59, 0xa5, 0x65, 0x95, 0x55 };
201
3d2c9c9b 202void CodeIso15693AsTag(uint8_t *cmd, size_t len) {
203 /*
204 * SOF comprises 3 parts;
205 * * An unmodulated time of 56.64 us
206 * * 24 pulses of 423.75 kHz (fc/32)
207 * * A logic 1, which starts with an unmodulated time of 18.88us
208 * followed by 8 pulses of 423.75kHz (fc/32)
209 *
210 * EOF comprises 3 parts:
211 * - A logic 0 (which starts with 8 pulses of fc/32 followed by an unmodulated
212 * time of 18.88us.
213 * - 24 pulses of fc/32
214 * - An unmodulated time of 56.64 us
215 *
216 * A logic 0 starts with 8 pulses of fc/32
217 * followed by an unmodulated time of 256/fc (~18,88us).
218 *
219 * A logic 0 starts with unmodulated time of 256/fc (~18,88us) followed by
220 * 8 pulses of fc/32 (also 18.88us)
221 *
222 * A bit here becomes 8 pulses of fc/32. Therefore:
223 * The SOF can be written as 00011101 = 0x1D
224 * The EOF can be written as 10111000 = 0xb8
225 * A logic 1 is 01
226 * A logic 0 is 10
227 *
228 * */
229
8c6cca0b 230 ToSendReset();
231
232 // SOF
3d2c9c9b 233 ToSend[++ToSendMax] = 0x1D; // 00011101
8c6cca0b 234
235 // data
8efd0b80 236 for (int i = 0; i < len; i++) {
237 ToSend[++ToSendMax] = encode_4bits[cmd[i] & 0xF];
238 ToSend[++ToSendMax] = encode_4bits[cmd[i] >> 4];
8c6cca0b 239 }
240
241 // EOF
3d2c9c9b 242 ToSend[++ToSendMax] = 0xB8; // 10111000
8c6cca0b 243
244 ToSendMax++;
15c4dc5a 245}
246
9455b51c 247
70b2fc0a 248// Transmit the command (to the tag) that was placed in cmd[].
c41dd5f9 249void TransmitTo15693Tag(const uint8_t *cmd, int len, uint32_t *start_time) {
250
5ea2a248 251 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_FULL_MOD);
c41dd5f9 252
253 *start_time = (*start_time - DELAY_ARM_TO_TAG) & 0xfffffff0;
254
255 while (GetCountSspClk() > *start_time) { // we may miss the intended time
256 *start_time += 16; // next possible time
257 }
15c4dc5a 258
c41dd5f9 259
260 while (GetCountSspClk() < *start_time)
261 /* wait */ ;
d9de20fa 262
70b2fc0a 263 LED_B_ON();
c41dd5f9 264 for (int c = 0; c < len; c++) {
5ea2a248 265 uint8_t data = cmd[c];
266 for (int i = 0; i < 8; i++) {
c41dd5f9 267 uint16_t send_word = (data & 0x80) ? 0xffff : 0x0000;
5ea2a248 268 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
269 AT91C_BASE_SSC->SSC_THR = send_word;
270 while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
271 AT91C_BASE_SSC->SSC_THR = send_word;
c41dd5f9 272
5ea2a248 273 data <<= 1;
274 }
275 WDT_HIT();
276 }
70b2fc0a 277 LED_B_OFF();
c41dd5f9 278
279 *start_time = *start_time + DELAY_ARM_TO_TAG;
280
15c4dc5a 281}
282
5ea2a248 283
15c4dc5a 284//-----------------------------------------------------------------------------
8c6cca0b 285// Transmit the tag response (to the reader) that was placed in cmd[].
15c4dc5a 286//-----------------------------------------------------------------------------
8efd0b80 287void TransmitTo15693Reader(const uint8_t *cmd, size_t len, uint32_t *start_time, uint32_t slot_time, bool slow) {
8c6cca0b 288 // don't use the FPGA_HF_SIMULATOR_MODULATE_424K_8BIT minor mode. It would spoil GetCountSspClk()
70b2fc0a 289 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_MODULATE_424K);
15c4dc5a 290
c41dd5f9 291 uint32_t modulation_start_time = *start_time - DELAY_ARM_TO_READER + 3 * 8; // no need to transfer the unmodulated start of SOF
8efd0b80 292
293 while (GetCountSspClk() > (modulation_start_time & 0xfffffff8) + 3) { // we will miss the intended time
294 if (slot_time) {
295 modulation_start_time += slot_time; // use next available slot
296 } else {
297 modulation_start_time = (modulation_start_time & 0xfffffff8) + 8; // next possible time
298 }
299 }
300
301 while (GetCountSspClk() < (modulation_start_time & 0xfffffff8))
302 /* wait */ ;
8c6cca0b 303
8efd0b80 304 uint8_t shift_delay = modulation_start_time & 0x00000007;
305
c41dd5f9 306 *start_time = modulation_start_time + DELAY_ARM_TO_READER - 3 * 8;
d9de20fa 307
70b2fc0a 308 LED_C_ON();
8c6cca0b 309 uint8_t bits_to_shift = 0x00;
3d2c9c9b 310 uint8_t bits_to_send = 0x00;
8efd0b80 311 for (size_t c = 0; c < len; c++) {
312 for (int i = (c==0?4:7); i >= 0; i--) {
3d2c9c9b 313 uint8_t cmd_bits = ((cmd[c] >> i) & 0x01) ? 0xff : 0x00;
8c6cca0b 314 for (int j = 0; j < (slow?4:1); ) {
315 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
a66f26da 316 bits_to_send = bits_to_shift << (8 - shift_delay) | cmd_bits >> shift_delay;
3d2c9c9b 317 AT91C_BASE_SSC->SSC_THR = bits_to_send;
a66f26da 318 bits_to_shift = cmd_bits;
8c6cca0b 319 j++;
320 }
8c6cca0b 321 }
a66f26da 322 }
3d2c9c9b 323 WDT_HIT();
a66f26da 324 }
3d2c9c9b 325 // send the remaining bits, padded with 0:
326 bits_to_send = bits_to_shift << (8 - shift_delay);
327 for ( ; ; ) {
328 if (AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXRDY) {
329 AT91C_BASE_SSC->SSC_THR = bits_to_send;
330 break;
331 }
332 }
70b2fc0a 333 LED_C_OFF();
15c4dc5a 334}
335
9455b51c 336
70b2fc0a 337//=============================================================================
8c6cca0b 338// An ISO 15693 decoder for tag responses (one subcarrier only).
d9de20fa 339// Uses cross correlation to identify each bit and EOF.
70b2fc0a 340// This function is called 8 times per bit (every 2 subcarrier cycles).
8c6cca0b 341// Subcarrier frequency fs is 424kHz, 1/fs = 2,36us,
70b2fc0a 342// i.e. function is called every 4,72us
343// LED handling:
344// LED C -> ON once we have received the SOF and are expecting the rest.
345// LED C -> OFF once we have received EOF or are unsynced
346//
347// Returns: true if we received a EOF
348// false if we are still waiting for some more
349//=============================================================================
350
c41dd5f9 351#define NOISE_THRESHOLD 160 // don't try to correlate noise
352#define MAX_PREVIOUS_AMPLITUDE (-1 - NOISE_THRESHOLD)
70b2fc0a 353
8c6cca0b 354typedef struct DecodeTag {
70b2fc0a 355 enum {
d9de20fa 356 STATE_TAG_SOF_LOW,
c41dd5f9 357 STATE_TAG_SOF_RISING_EDGE,
d9de20fa 358 STATE_TAG_SOF_HIGH,
359 STATE_TAG_SOF_HIGH_END,
8c6cca0b 360 STATE_TAG_RECEIVING_DATA,
c41dd5f9 361 STATE_TAG_EOF,
362 STATE_TAG_EOF_TAIL
70b2fc0a 363 } state;
364 int bitCount;
365 int posCount;
366 enum {
367 LOGIC0,
368 LOGIC1,
369 SOF_PART1,
370 SOF_PART2
371 } lastBit;
372 uint16_t shiftReg;
d9de20fa 373 uint16_t max_len;
70b2fc0a 374 uint8_t *output;
375 int len;
376 int sum1, sum2;
c41dd5f9 377 int threshold_sof;
378 int threshold_half;
379 uint16_t previous_amplitude;
8c6cca0b 380} DecodeTag_t;
70b2fc0a 381
d9de20fa 382
383static int inline __attribute__((always_inline)) Handle15693SamplesFromTag(uint16_t amplitude, DecodeTag_t *DecodeTag)
15c4dc5a 384{
8c6cca0b 385 switch(DecodeTag->state) {
a66f26da 386 case STATE_TAG_SOF_LOW:
c41dd5f9 387 // waiting for a rising edge
388 if (amplitude > NOISE_THRESHOLD + DecodeTag->previous_amplitude) {
d9de20fa 389 if (DecodeTag->posCount > 10) {
c41dd5f9 390 DecodeTag->threshold_sof = amplitude - DecodeTag->previous_amplitude;
391 DecodeTag->threshold_half = 0;
392 DecodeTag->state = STATE_TAG_SOF_RISING_EDGE;
d9de20fa 393 } else {
394 DecodeTag->posCount = 0;
395 }
c41dd5f9 396 } else {
397 DecodeTag->posCount++;
398 DecodeTag->previous_amplitude = amplitude;
15c4dc5a 399 }
d9de20fa 400 break;
a66f26da 401
c41dd5f9 402 case STATE_TAG_SOF_RISING_EDGE:
403 if (amplitude - DecodeTag->previous_amplitude > DecodeTag->threshold_sof) { // edge still rising
404 if (amplitude - DecodeTag->threshold_sof > DecodeTag->threshold_sof) { // steeper edge, take this as time reference
405 DecodeTag->posCount = 1;
406 } else {
407 DecodeTag->posCount = 2;
408 }
409 DecodeTag->threshold_sof = (amplitude - DecodeTag->previous_amplitude) / 2;
410 } else {
411 DecodeTag->posCount = 2;
412 DecodeTag->threshold_sof = DecodeTag->threshold_sof/2;
413 }
414 // DecodeTag->posCount = 2;
415 DecodeTag->state = STATE_TAG_SOF_HIGH;
416 break;
417
d9de20fa 418 case STATE_TAG_SOF_HIGH:
419 // waiting for 10 times high. Take average over the last 8
c41dd5f9 420 if (amplitude > DecodeTag->threshold_sof) {
d9de20fa 421 DecodeTag->posCount++;
422 if (DecodeTag->posCount > 2) {
c41dd5f9 423 DecodeTag->threshold_half += amplitude; // keep track of average high value
d9de20fa 424 }
425 if (DecodeTag->posCount == 10) {
c41dd5f9 426 DecodeTag->threshold_half >>= 2; // (4 times 1/2 average)
d9de20fa 427 DecodeTag->state = STATE_TAG_SOF_HIGH_END;
428 }
429 } else { // high phase was too short
430 DecodeTag->posCount = 1;
c41dd5f9 431 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
d9de20fa 432 DecodeTag->state = STATE_TAG_SOF_LOW;
70b2fc0a 433 }
70b2fc0a 434 break;
435
d9de20fa 436 case STATE_TAG_SOF_HIGH_END:
c41dd5f9 437 // check for falling edge
438 if (DecodeTag->posCount == 13 && amplitude < DecodeTag->threshold_sof) {
d9de20fa 439 DecodeTag->lastBit = SOF_PART1; // detected 1st part of SOF (12 samples low and 12 samples high)
440 DecodeTag->shiftReg = 0;
441 DecodeTag->bitCount = 0;
442 DecodeTag->len = 0;
443 DecodeTag->sum1 = amplitude;
8c6cca0b 444 DecodeTag->sum2 = 0;
445 DecodeTag->posCount = 2;
446 DecodeTag->state = STATE_TAG_RECEIVING_DATA;
c41dd5f9 447 // FpgaDisableTracing(); // DEBUGGING
448 // Dbprintf("amplitude = %d, threshold_sof = %d, threshold_half/4 = %d, previous_amplitude = %d",
449 // amplitude,
450 // DecodeTag->threshold_sof,
451 // DecodeTag->threshold_half/4,
452 // DecodeTag->previous_amplitude); // DEBUGGING
70b2fc0a 453 LED_C_ON();
d9de20fa 454 } else {
455 DecodeTag->posCount++;
456 if (DecodeTag->posCount > 13) { // high phase too long
457 DecodeTag->posCount = 0;
c41dd5f9 458 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
d9de20fa 459 DecodeTag->state = STATE_TAG_SOF_LOW;
460 LED_C_OFF();
461 }
70b2fc0a 462 }
70b2fc0a 463 break;
15c4dc5a 464
8c6cca0b 465 case STATE_TAG_RECEIVING_DATA:
466 if (DecodeTag->posCount == 1) {
467 DecodeTag->sum1 = 0;
468 DecodeTag->sum2 = 0;
70b2fc0a 469 }
8c6cca0b 470 if (DecodeTag->posCount <= 4) {
d9de20fa 471 DecodeTag->sum1 += amplitude;
70b2fc0a 472 } else {
d9de20fa 473 DecodeTag->sum2 += amplitude;
70b2fc0a 474 }
8c6cca0b 475 if (DecodeTag->posCount == 8) {
c41dd5f9 476 if (DecodeTag->sum1 > DecodeTag->threshold_half && DecodeTag->sum2 > DecodeTag->threshold_half) { // modulation in both halves
d9de20fa 477 if (DecodeTag->lastBit == LOGIC0) { // this was already part of EOF
478 DecodeTag->state = STATE_TAG_EOF;
479 } else {
480 DecodeTag->posCount = 0;
c41dd5f9 481 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
d9de20fa 482 DecodeTag->state = STATE_TAG_SOF_LOW;
483 LED_C_OFF();
484 }
c41dd5f9 485 } else if (DecodeTag->sum1 < DecodeTag->threshold_half && DecodeTag->sum2 > DecodeTag->threshold_half) { // modulation in second half
70b2fc0a 486 // logic 1
8c6cca0b 487 if (DecodeTag->lastBit == SOF_PART1) { // still part of SOF
d9de20fa 488 DecodeTag->lastBit = SOF_PART2; // SOF completed
70b2fc0a 489 } else {
8c6cca0b 490 DecodeTag->lastBit = LOGIC1;
491 DecodeTag->shiftReg >>= 1;
492 DecodeTag->shiftReg |= 0x80;
493 DecodeTag->bitCount++;
494 if (DecodeTag->bitCount == 8) {
495 DecodeTag->output[DecodeTag->len] = DecodeTag->shiftReg;
496 DecodeTag->len++;
c41dd5f9 497 // if (DecodeTag->shiftReg == 0x12 && DecodeTag->len == 1) FpgaDisableTracing(); // DEBUGGING
d9de20fa 498 if (DecodeTag->len > DecodeTag->max_len) {
499 // buffer overflow, give up
d9de20fa 500 LED_C_OFF();
c41dd5f9 501 return true;
d9de20fa 502 }
8c6cca0b 503 DecodeTag->bitCount = 0;
504 DecodeTag->shiftReg = 0;
70b2fc0a 505 }
506 }
c41dd5f9 507 } else if (DecodeTag->sum1 > DecodeTag->threshold_half && DecodeTag->sum2 < DecodeTag->threshold_half) { // modulation in first half
70b2fc0a 508 // logic 0
8c6cca0b 509 if (DecodeTag->lastBit == SOF_PART1) { // incomplete SOF
d9de20fa 510 DecodeTag->posCount = 0;
c41dd5f9 511 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
d9de20fa 512 DecodeTag->state = STATE_TAG_SOF_LOW;
70b2fc0a 513 LED_C_OFF();
514 } else {
8c6cca0b 515 DecodeTag->lastBit = LOGIC0;
516 DecodeTag->shiftReg >>= 1;
517 DecodeTag->bitCount++;
518 if (DecodeTag->bitCount == 8) {
519 DecodeTag->output[DecodeTag->len] = DecodeTag->shiftReg;
520 DecodeTag->len++;
c41dd5f9 521 // if (DecodeTag->shiftReg == 0x12 && DecodeTag->len == 1) FpgaDisableTracing(); // DEBUGGING
d9de20fa 522 if (DecodeTag->len > DecodeTag->max_len) {
523 // buffer overflow, give up
524 DecodeTag->posCount = 0;
c41dd5f9 525 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
d9de20fa 526 DecodeTag->state = STATE_TAG_SOF_LOW;
527 LED_C_OFF();
528 }
8c6cca0b 529 DecodeTag->bitCount = 0;
530 DecodeTag->shiftReg = 0;
70b2fc0a 531 }
532 }
c41dd5f9 533 } else { // no modulation
534 if (DecodeTag->lastBit == SOF_PART2) { // only SOF (this is OK for iClass)
535 LED_C_OFF();
536 return true;
537 } else {
538 DecodeTag->posCount = 0;
539 DecodeTag->state = STATE_TAG_SOF_LOW;
540 LED_C_OFF();
541 }
70b2fc0a 542 }
8c6cca0b 543 DecodeTag->posCount = 0;
70b2fc0a 544 }
8c6cca0b 545 DecodeTag->posCount++;
70b2fc0a 546 break;
8c6cca0b 547
d9de20fa 548 case STATE_TAG_EOF:
549 if (DecodeTag->posCount == 1) {
550 DecodeTag->sum1 = 0;
551 DecodeTag->sum2 = 0;
552 }
553 if (DecodeTag->posCount <= 4) {
554 DecodeTag->sum1 += amplitude;
70b2fc0a 555 } else {
d9de20fa 556 DecodeTag->sum2 += amplitude;
70b2fc0a 557 }
d9de20fa 558 if (DecodeTag->posCount == 8) {
c41dd5f9 559 if (DecodeTag->sum1 > DecodeTag->threshold_half && DecodeTag->sum2 < DecodeTag->threshold_half) { // modulation in first half
d9de20fa 560 DecodeTag->posCount = 0;
c41dd5f9 561 DecodeTag->state = STATE_TAG_EOF_TAIL;
562 } else {
563 DecodeTag->posCount = 0;
564 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
d9de20fa 565 DecodeTag->state = STATE_TAG_SOF_LOW;
566 LED_C_OFF();
c41dd5f9 567 }
568 }
569 DecodeTag->posCount++;
570 break;
571
572 case STATE_TAG_EOF_TAIL:
573 if (DecodeTag->posCount == 1) {
574 DecodeTag->sum1 = 0;
575 DecodeTag->sum2 = 0;
576 }
577 if (DecodeTag->posCount <= 4) {
578 DecodeTag->sum1 += amplitude;
579 } else {
580 DecodeTag->sum2 += amplitude;
581 }
582 if (DecodeTag->posCount == 8) {
583 if (DecodeTag->sum1 < DecodeTag->threshold_half && DecodeTag->sum2 < DecodeTag->threshold_half) { // no modulation in both halves
d9de20fa 584 LED_C_OFF();
585 return true;
c41dd5f9 586 } else {
587 DecodeTag->posCount = 0;
588 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
589 DecodeTag->state = STATE_TAG_SOF_LOW;
590 LED_C_OFF();
d9de20fa 591 }
592 }
593 DecodeTag->posCount++;
70b2fc0a 594 break;
15c4dc5a 595 }
15c4dc5a 596
70b2fc0a 597 return false;
598}
15c4dc5a 599
15c4dc5a 600
d9de20fa 601static void DecodeTagInit(DecodeTag_t *DecodeTag, uint8_t *data, uint16_t max_len)
70b2fc0a 602{
c41dd5f9 603 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
d9de20fa 604 DecodeTag->posCount = 0;
605 DecodeTag->state = STATE_TAG_SOF_LOW;
8c6cca0b 606 DecodeTag->output = data;
d9de20fa 607 DecodeTag->max_len = max_len;
608}
609
610
611static void DecodeTagReset(DecodeTag_t *DecodeTag)
612{
613 DecodeTag->posCount = 0;
614 DecodeTag->state = STATE_TAG_SOF_LOW;
c41dd5f9 615 DecodeTag->previous_amplitude = MAX_PREVIOUS_AMPLITUDE;
70b2fc0a 616}
617
d9de20fa 618
70b2fc0a 619/*
8c6cca0b 620 * Receive and decode the tag response, also log to tracebuffer
70b2fc0a 621 */
c41dd5f9 622int GetIso15693AnswerFromTag(uint8_t* response, uint16_t max_len, uint16_t timeout, uint32_t *eof_time) {
623
d9de20fa 624 int samples = 0;
c41dd5f9 625 int ret = 0;
70b2fc0a 626
c41dd5f9 627 uint16_t dmaBuf[ISO15693_DMA_BUFFER_SIZE];
a66f26da 628
8c6cca0b 629 // the Decoder data structure
d9de20fa 630 DecodeTag_t DecodeTag = { 0 };
631 DecodeTagInit(&DecodeTag, response, max_len);
70b2fc0a 632
633 // wait for last transfer to complete
634 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
635
636 // And put the FPGA in the appropriate mode
5ea2a248 637 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_424_KHZ | FPGA_HF_READER_MODE_RECEIVE_AMPLITUDE);
70b2fc0a 638
639 // Setup and start DMA.
5ea2a248 640 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
70b2fc0a 641 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
c41dd5f9 642 uint32_t dma_start_time = 0;
70b2fc0a 643 uint16_t *upTo = dmaBuf;
70b2fc0a 644
645 for(;;) {
d9de20fa 646 uint16_t behindBy = ((uint16_t*)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (ISO15693_DMA_BUFFER_SIZE-1);
70b2fc0a 647
d9de20fa 648 if (behindBy == 0) continue;
8c6cca0b 649
c41dd5f9 650 samples++;
651 if (samples == 1) {
652 // DMA has transferred the very first data
653 dma_start_time = GetCountSspClk() & 0xfffffff0;
654 }
655
d9de20fa 656 uint16_t tagdata = *upTo++;
70b2fc0a 657
70b2fc0a 658 if(upTo >= dmaBuf + ISO15693_DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
659 upTo = dmaBuf; // start reading the circular buffer from the beginning
d9de20fa 660 if(behindBy > (9*ISO15693_DMA_BUFFER_SIZE/10)) {
661 Dbprintf("About to blow circular buffer - aborted! behindBy=%d", behindBy);
c41dd5f9 662 ret = -1;
d9de20fa 663 break;
664 }
15c4dc5a 665 }
70b2fc0a 666 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
667 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
668 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO15693_DMA_BUFFER_SIZE; // DMA Next Counter registers
15c4dc5a 669 }
d9de20fa 670
d9de20fa 671 if (Handle15693SamplesFromTag(tagdata, &DecodeTag)) {
c41dd5f9 672 *eof_time = dma_start_time + samples*16 - DELAY_TAG_TO_ARM; // end of EOF
673 if (DecodeTag.lastBit == SOF_PART2) {
674 *eof_time -= 8*16; // needed 8 additional samples to confirm single SOF (iCLASS)
675 }
676 if (DecodeTag.len > DecodeTag.max_len) {
677 ret = -2; // buffer overflow
678 }
70b2fc0a 679 break;
680 }
15c4dc5a 681
d9de20fa 682 if (samples > timeout && DecodeTag.state < STATE_TAG_RECEIVING_DATA) {
c41dd5f9 683 ret = -1; // timeout
70b2fc0a 684 break;
685 }
8c6cca0b 686
70b2fc0a 687 }
688
689 FpgaDisableSscDma();
a66f26da 690
c41dd5f9 691 if (DEBUG) Dbprintf("samples = %d, ret = %d, Decoder: state = %d, lastBit = %d, len = %d, bitCount = %d, posCount = %d",
692 samples, ret, DecodeTag.state, DecodeTag.lastBit, DecodeTag.len, DecodeTag.bitCount, DecodeTag.posCount);
70b2fc0a 693
c41dd5f9 694 if (ret < 0) {
695 return ret;
70b2fc0a 696 }
697
c41dd5f9 698 uint32_t sof_time = *eof_time
699 - DecodeTag.len * 8 * 8 * 16 // time for byte transfers
700 - 32 * 16 // time for SOF transfer
701 - (DecodeTag.lastBit != SOF_PART2?32*16:0); // time for EOF transfer
702
703 if (DEBUG) Dbprintf("timing: sof_time = %d, eof_time = %d", sof_time, *eof_time);
704
705 LogTrace_ISO15693(DecodeTag.output, DecodeTag.len, sof_time*4, *eof_time*4, NULL, false);
706
8c6cca0b 707 return DecodeTag.len;
15c4dc5a 708}
709
9455b51c 710
8c6cca0b 711//=============================================================================
712// An ISO15693 decoder for reader commands.
713//
714// This function is called 4 times per bit (every 2 subcarrier cycles).
715// Subcarrier frequency fs is 848kHz, 1/fs = 1,18us, i.e. function is called every 2,36us
716// LED handling:
717// LED B -> ON once we have received the SOF and are expecting the rest.
718// LED B -> OFF once we have received EOF or are in error state or unsynced
719//
720// Returns: true if we received a EOF
721// false if we are still waiting for some more
722//=============================================================================
723
724typedef struct DecodeReader {
725 enum {
726 STATE_READER_UNSYNCD,
5b12974a 727 STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF,
8c6cca0b 728 STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF,
729 STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF,
730 STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF,
731 STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4,
732 STATE_READER_RECEIVE_DATA_1_OUT_OF_4,
733 STATE_READER_RECEIVE_DATA_1_OUT_OF_256
734 } state;
735 enum {
736 CODING_1_OUT_OF_4,
737 CODING_1_OUT_OF_256
738 } Coding;
739 uint8_t shiftReg;
740 uint8_t bitCount;
741 int byteCount;
742 int byteCountMax;
743 int posCount;
a66f26da 744 int sum1, sum2;
8c6cca0b 745 uint8_t *output;
746} DecodeReader_t;
747
748
d9de20fa 749static void DecodeReaderInit(DecodeReader_t* DecodeReader, uint8_t *data, uint16_t max_len)
750{
751 DecodeReader->output = data;
752 DecodeReader->byteCountMax = max_len;
753 DecodeReader->state = STATE_READER_UNSYNCD;
754 DecodeReader->byteCount = 0;
755 DecodeReader->bitCount = 0;
756 DecodeReader->posCount = 1;
757 DecodeReader->shiftReg = 0;
758}
759
760
761static void DecodeReaderReset(DecodeReader_t* DecodeReader)
762{
763 DecodeReader->state = STATE_READER_UNSYNCD;
764}
765
766
767static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uint8_t bit, DecodeReader_t *restrict DecodeReader)
15c4dc5a 768{
3d2c9c9b 769 switch (DecodeReader->state) {
8c6cca0b 770 case STATE_READER_UNSYNCD:
5b12974a 771 // wait for unmodulated carrier
772 if (bit) {
773 DecodeReader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
774 }
775 break;
776
777 case STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF:
3d2c9c9b 778 if (!bit) {
8c6cca0b 779 // we went low, so this could be the beginning of a SOF
8c6cca0b 780 DecodeReader->posCount = 1;
d9de20fa 781 DecodeReader->state = STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF;
8c6cca0b 782 }
783 break;
15c4dc5a 784
8c6cca0b 785 case STATE_READER_AWAIT_1ST_RISING_EDGE_OF_SOF:
786 DecodeReader->posCount++;
3d2c9c9b 787 if (bit) { // detected rising edge
788 if (DecodeReader->posCount < 4) { // rising edge too early (nominally expected at 5)
5b12974a 789 DecodeReader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
8c6cca0b 790 } else { // SOF
791 DecodeReader->state = STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF;
792 }
793 } else {
3d2c9c9b 794 if (DecodeReader->posCount > 5) { // stayed low for too long
d9de20fa 795 DecodeReaderReset(DecodeReader);
8c6cca0b 796 } else {
797 // do nothing, keep waiting
798 }
799 }
800 break;
801
802 case STATE_READER_AWAIT_2ND_FALLING_EDGE_OF_SOF:
803 DecodeReader->posCount++;
3d2c9c9b 804 if (!bit) { // detected a falling edge
8c6cca0b 805 if (DecodeReader->posCount < 20) { // falling edge too early (nominally expected at 21 earliest)
d9de20fa 806 DecodeReaderReset(DecodeReader);
8c6cca0b 807 } else if (DecodeReader->posCount < 23) { // SOF for 1 out of 4 coding
808 DecodeReader->Coding = CODING_1_OUT_OF_4;
809 DecodeReader->state = STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF;
810 } else if (DecodeReader->posCount < 28) { // falling edge too early (nominally expected at 29 latest)
d9de20fa 811 DecodeReaderReset(DecodeReader);
5b12974a 812 } else { // SOF for 1 out of 256 coding
8c6cca0b 813 DecodeReader->Coding = CODING_1_OUT_OF_256;
814 DecodeReader->state = STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF;
815 }
816 } else {
3d2c9c9b 817 if (DecodeReader->posCount > 29) { // stayed high for too long
5b12974a 818 DecodeReader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
8c6cca0b 819 } else {
820 // do nothing, keep waiting
821 }
822 }
823 break;
824
825 case STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF:
826 DecodeReader->posCount++;
827 if (bit) { // detected rising edge
828 if (DecodeReader->Coding == CODING_1_OUT_OF_256) {
829 if (DecodeReader->posCount < 32) { // rising edge too early (nominally expected at 33)
5b12974a 830 DecodeReader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
8c6cca0b 831 } else {
832 DecodeReader->posCount = 1;
833 DecodeReader->bitCount = 0;
834 DecodeReader->byteCount = 0;
835 DecodeReader->sum1 = 1;
836 DecodeReader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_256;
837 LED_B_ON();
838 }
839 } else { // CODING_1_OUT_OF_4
840 if (DecodeReader->posCount < 24) { // rising edge too early (nominally expected at 25)
5b12974a 841 DecodeReader->state = STATE_READER_AWAIT_1ST_FALLING_EDGE_OF_SOF;
8c6cca0b 842 } else {
5b12974a 843 DecodeReader->posCount = 1;
8c6cca0b 844 DecodeReader->state = STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4;
845 }
846 }
847 } else {
848 if (DecodeReader->Coding == CODING_1_OUT_OF_256) {
849 if (DecodeReader->posCount > 34) { // signal stayed low for too long
5b12974a 850 DecodeReaderReset(DecodeReader);
8c6cca0b 851 } else {
852 // do nothing, keep waiting
853 }
854 } else { // CODING_1_OUT_OF_4
855 if (DecodeReader->posCount > 26) { // signal stayed low for too long
5b12974a 856 DecodeReaderReset(DecodeReader);
8c6cca0b 857 } else {
858 // do nothing, keep waiting
859 }
860 }
861 }
862 break;
863
864 case STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4:
865 DecodeReader->posCount++;
866 if (bit) {
5b12974a 867 if (DecodeReader->posCount == 9) {
8c6cca0b 868 DecodeReader->posCount = 1;
869 DecodeReader->bitCount = 0;
870 DecodeReader->byteCount = 0;
871 DecodeReader->sum1 = 1;
872 DecodeReader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_4;
873 LED_B_ON();
874 } else {
875 // do nothing, keep waiting
876 }
877 } else { // unexpected falling edge
d9de20fa 878 DecodeReaderReset(DecodeReader);
8c6cca0b 879 }
880 break;
881
882 case STATE_READER_RECEIVE_DATA_1_OUT_OF_4:
e49d31c0 883 bit = !!bit;
8c6cca0b 884 DecodeReader->posCount++;
885 if (DecodeReader->posCount == 1) {
886 DecodeReader->sum1 = bit;
887 } else if (DecodeReader->posCount <= 4) {
888 DecodeReader->sum1 += bit;
889 } else if (DecodeReader->posCount == 5) {
890 DecodeReader->sum2 = bit;
891 } else {
892 DecodeReader->sum2 += bit;
893 }
894 if (DecodeReader->posCount == 8) {
895 DecodeReader->posCount = 0;
e49d31c0 896 if (DecodeReader->sum1 <= 1 && DecodeReader->sum2 >= 3) { // EOF
8c6cca0b 897 LED_B_OFF(); // Finished receiving
d9de20fa 898 DecodeReaderReset(DecodeReader);
8c6cca0b 899 if (DecodeReader->byteCount != 0) {
900 return true;
901 }
902 }
e49d31c0 903 if (DecodeReader->sum1 >= 3 && DecodeReader->sum2 <= 1) { // detected a 2bit position
8c6cca0b 904 DecodeReader->shiftReg >>= 2;
905 DecodeReader->shiftReg |= (DecodeReader->bitCount << 6);
906 }
907 if (DecodeReader->bitCount == 15) { // we have a full byte
908 DecodeReader->output[DecodeReader->byteCount++] = DecodeReader->shiftReg;
909 if (DecodeReader->byteCount > DecodeReader->byteCountMax) {
910 // buffer overflow, give up
911 LED_B_OFF();
d9de20fa 912 DecodeReaderReset(DecodeReader);
8c6cca0b 913 }
914 DecodeReader->bitCount = 0;
d9de20fa 915 DecodeReader->shiftReg = 0;
8c6cca0b 916 } else {
917 DecodeReader->bitCount++;
918 }
919 }
920 break;
921
922 case STATE_READER_RECEIVE_DATA_1_OUT_OF_256:
e49d31c0 923 bit = !!bit;
8c6cca0b 924 DecodeReader->posCount++;
925 if (DecodeReader->posCount == 1) {
926 DecodeReader->sum1 = bit;
927 } else if (DecodeReader->posCount <= 4) {
928 DecodeReader->sum1 += bit;
929 } else if (DecodeReader->posCount == 5) {
930 DecodeReader->sum2 = bit;
931 } else {
932 DecodeReader->sum2 += bit;
933 }
934 if (DecodeReader->posCount == 8) {
935 DecodeReader->posCount = 0;
e49d31c0 936 if (DecodeReader->sum1 <= 1 && DecodeReader->sum2 >= 3) { // EOF
8c6cca0b 937 LED_B_OFF(); // Finished receiving
d9de20fa 938 DecodeReaderReset(DecodeReader);
8c6cca0b 939 if (DecodeReader->byteCount != 0) {
940 return true;
941 }
942 }
e49d31c0 943 if (DecodeReader->sum1 >= 3 && DecodeReader->sum2 <= 1) { // detected the bit position
8c6cca0b 944 DecodeReader->shiftReg = DecodeReader->bitCount;
945 }
946 if (DecodeReader->bitCount == 255) { // we have a full byte
947 DecodeReader->output[DecodeReader->byteCount++] = DecodeReader->shiftReg;
948 if (DecodeReader->byteCount > DecodeReader->byteCountMax) {
949 // buffer overflow, give up
950 LED_B_OFF();
d9de20fa 951 DecodeReaderReset(DecodeReader);
8c6cca0b 952 }
953 }
954 DecodeReader->bitCount++;
955 }
956 break;
957
958 default:
959 LED_B_OFF();
d9de20fa 960 DecodeReaderReset(DecodeReader);
8c6cca0b 961 break;
15c4dc5a 962 }
8c6cca0b 963
964 return false;
965}
966
967
8c6cca0b 968//-----------------------------------------------------------------------------
969// Receive a command (from the reader to us, where we are the simulated tag),
970// and store it in the given buffer, up to the given maximum length. Keeps
971// spinning, waiting for a well-framed command, until either we get one
3d2c9c9b 972// (returns len) or someone presses the pushbutton on the board (returns -1).
8c6cca0b 973//
974// Assume that we're called with the SSC (to the FPGA) and ADC path set
975// correctly.
976//-----------------------------------------------------------------------------
977
3d2c9c9b 978int GetIso15693CommandFromReader(uint8_t *received, size_t max_len, uint32_t *eof_time) {
d9de20fa 979 int samples = 0;
8c6cca0b 980 bool gotFrame = false;
981 uint8_t b;
982
3d2c9c9b 983 uint8_t dmaBuf[ISO15693_DMA_BUFFER_SIZE];
8c6cca0b 984
985 // the decoder data structure
6eeb5f1c 986 DecodeReader_t DecodeReader = {0};
d9de20fa 987 DecodeReaderInit(&DecodeReader, received, max_len);
8c6cca0b 988
989 // wait for last transfer to complete
990 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
991
70b2fc0a 992 LED_D_OFF();
8c6cca0b 993 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
15c4dc5a 994
8c6cca0b 995 // clear receive register and wait for next transfer
996 uint32_t temp = AT91C_BASE_SSC->SSC_RHR;
997 (void) temp;
998 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_RXRDY)) ;
15c4dc5a 999
3d2c9c9b 1000 uint32_t dma_start_time = GetCountSspClk() & 0xfffffff8;
15c4dc5a 1001
8c6cca0b 1002 // Setup and start DMA.
1003 FpgaSetupSscDma(dmaBuf, ISO15693_DMA_BUFFER_SIZE);
1004 uint8_t *upTo = dmaBuf;
15c4dc5a 1005
3d2c9c9b 1006 for (;;) {
d9de20fa 1007 uint16_t behindBy = ((uint8_t*)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (ISO15693_DMA_BUFFER_SIZE-1);
70b2fc0a 1008
d9de20fa 1009 if (behindBy == 0) continue;
15c4dc5a 1010
8c6cca0b 1011 b = *upTo++;
3d2c9c9b 1012 if (upTo >= dmaBuf + ISO15693_DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
8c6cca0b 1013 upTo = dmaBuf; // start reading the circular buffer from the beginning
3d2c9c9b 1014 if (behindBy > (9*ISO15693_DMA_BUFFER_SIZE/10)) {
d9de20fa 1015 Dbprintf("About to blow circular buffer - aborted! behindBy=%d", behindBy);
1016 break;
1017 }
8c6cca0b 1018 }
1019 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
1020 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
1021 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO15693_DMA_BUFFER_SIZE; // DMA Next Counter registers
1022 }
15c4dc5a 1023
8c6cca0b 1024 for (int i = 7; i >= 0; i--) {
1025 if (Handle15693SampleFromReader((b >> i) & 0x01, &DecodeReader)) {
c41dd5f9 1026 *eof_time = dma_start_time + samples - DELAY_READER_TO_ARM; // end of EOF
8c6cca0b 1027 gotFrame = true;
9455b51c 1028 break;
1029 }
8c6cca0b 1030 samples++;
15c4dc5a 1031 }
8c6cca0b 1032
1033 if (gotFrame) {
1034 break;
15c4dc5a 1035 }
8c6cca0b 1036
1037 if (BUTTON_PRESS()) {
3d2c9c9b 1038 DecodeReader.byteCount = -1;
8c6cca0b 1039 break;
15c4dc5a 1040 }
15c4dc5a 1041
8c6cca0b 1042 WDT_HIT();
1043 }
1044
8c6cca0b 1045 FpgaDisableSscDma();
a66f26da 1046
d9de20fa 1047 if (DEBUG) Dbprintf("samples = %d, gotFrame = %d, Decoder: state = %d, len = %d, bitCount = %d, posCount = %d",
a66f26da 1048 samples, gotFrame, DecodeReader.state, DecodeReader.byteCount, DecodeReader.bitCount, DecodeReader.posCount);
8c6cca0b 1049
d9de20fa 1050 if (DecodeReader.byteCount > 0) {
a66f26da 1051 uint32_t sof_time = *eof_time
3d2c9c9b 1052 - DecodeReader.byteCount * (DecodeReader.Coding==CODING_1_OUT_OF_4?128:2048) // time for byte transfers
1053 - 32 // time for SOF transfer
1054 - 16; // time for EOF transfer
c41dd5f9 1055 LogTrace_ISO15693(DecodeReader.output, DecodeReader.byteCount, sof_time*32, *eof_time*32, NULL, true);
8c6cca0b 1056 }
1057
1058 return DecodeReader.byteCount;
15c4dc5a 1059}
1060
9455b51c 1061
d9de20fa 1062// Encode (into the ToSend buffers) an identify request, which is the first
1063// thing that you must send to a tag to get a response.
1064static void BuildIdentifyRequest(void)
1065{
1066 uint8_t cmd[5];
1067
1068 uint16_t crc;
1069 // one sub-carrier, inventory, 1 slot, fast rate
1070 // AFI is at bit 5 (1<<4) when doing an INVENTORY
1071 cmd[0] = (1 << 2) | (1 << 5) | (1 << 1);
1072 // inventory command code
1073 cmd[1] = 0x01;
1074 // no mask
1075 cmd[2] = 0x00;
1076 //Now the CRC
3d2c9c9b 1077 crc = Iso15693Crc(cmd, 3);
d9de20fa 1078 cmd[3] = crc & 0xff;
1079 cmd[4] = crc >> 8;
1080
1081 CodeIso15693AsReader(cmd, sizeof(cmd));
1082}
1083
1084
15c4dc5a 1085//-----------------------------------------------------------------------------
1086// Start to read an ISO 15693 tag. We send an identify request, then wait
1087// for the response. The response is not demodulated, just left in the buffer
1088// so that it can be downloaded to a PC and processed there.
1089//-----------------------------------------------------------------------------
1090void AcquireRawAdcSamplesIso15693(void)
1091{
70b2fc0a 1092 LEDsoff();
1093 LED_A_ON();
8c6cca0b 1094
117d9ec2 1095 uint8_t *dest = BigBuf_get_addr();
15c4dc5a 1096
7cc204bf 1097 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
5ea2a248 1098 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
1099 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
15c4dc5a 1100 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1101
5ea2a248 1102 BuildIdentifyRequest();
1103
15c4dc5a 1104 // Give the tags time to energize
70b2fc0a 1105 LED_D_ON();
15c4dc5a 1106 SpinDelay(100);
1107
1108 // Now send the command
c41dd5f9 1109 uint32_t start_time = 0;
1110 TransmitTo15693Tag(ToSend, ToSendMax, &start_time);
70b2fc0a 1111
1112 // wait for last transfer to complete
5ea2a248 1113 while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY)) ;
15c4dc5a 1114
5ea2a248 1115 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_SUBCARRIER_424_KHZ | FPGA_HF_READER_MODE_RECEIVE_AMPLITUDE);
15c4dc5a 1116
70b2fc0a 1117 for(int c = 0; c < 4000; ) {
15c4dc5a 1118 if(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_RXRDY)) {
d9de20fa 1119 uint16_t r = AT91C_BASE_SSC->SSC_RHR;
1120 dest[c++] = r >> 5;
9455b51c 1121 }
1122 }
70b2fc0a 1123
1124 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1125 LEDsoff();
9455b51c 1126}
1127
1128
d9de20fa 1129void SnoopIso15693(void)
9455b51c 1130{
1523527f 1131 LED_A_ON();
d9de20fa 1132 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
1133 BigBuf_free();
8c6cca0b 1134
d9de20fa 1135 clear_trace();
1136 set_tracing(true);
3fe4ff4f 1137
d9de20fa 1138 // The DMA buffer, used to stream samples from the FPGA
1139 uint16_t* dmaBuf = (uint16_t*)BigBuf_malloc(ISO15693_DMA_BUFFER_SIZE*sizeof(uint16_t));
1140 uint16_t *upTo;
1141
1142 // Count of samples received so far, so that we can include timing
1143 // information in the trace buffer.
1144 int samples = 0;
1145
1146 DecodeTag_t DecodeTag = {0};
1147 uint8_t response[ISO15693_MAX_RESPONSE_LENGTH];
1148 DecodeTagInit(&DecodeTag, response, sizeof(response));
9455b51c 1149
d9de20fa 1150 DecodeReader_t DecodeReader = {0};;
1151 uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH];
1152 DecodeReaderInit(&DecodeReader, cmd, sizeof(cmd));
1153
1154 // Print some debug information about the buffer sizes
1155 if (DEBUG) {
1156 Dbprintf("Snooping buffers initialized:");
1157 Dbprintf(" Trace: %i bytes", BigBuf_max_traceLen());
1158 Dbprintf(" Reader -> tag: %i bytes", ISO15693_MAX_COMMAND_LENGTH);
1159 Dbprintf(" tag -> Reader: %i bytes", ISO15693_MAX_RESPONSE_LENGTH);
1160 Dbprintf(" DMA: %i bytes", ISO15693_DMA_BUFFER_SIZE * sizeof(uint16_t));
1161 }
5ea2a248 1162 Dbprintf("Snoop started. Press PM3 Button to stop.");
a66f26da 1163
5ea2a248 1164 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNOOP_AMPLITUDE);
9455b51c 1165 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
1166
d9de20fa 1167 // Setup for the DMA.
5ea2a248 1168 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
d9de20fa 1169 upTo = dmaBuf;
1170 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
9455b51c 1171
d9de20fa 1172 bool TagIsActive = false;
1173 bool ReaderIsActive = false;
1174 bool ExpectTagAnswer = false;
9455b51c 1175
d9de20fa 1176 // And now we loop, receiving samples.
1177 for(;;) {
1178 uint16_t behindBy = ((uint16_t*)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (ISO15693_DMA_BUFFER_SIZE-1);
1179
1180 if (behindBy == 0) continue;
1181
1182 uint16_t snoopdata = *upTo++;
1183
1184 if(upTo >= dmaBuf + ISO15693_DMA_BUFFER_SIZE) { // we have read all of the DMA buffer content.
1185 upTo = dmaBuf; // start reading the circular buffer from the beginning
1186 if(behindBy > (9*ISO15693_DMA_BUFFER_SIZE/10)) {
1187 Dbprintf("About to blow circular buffer - aborted! behindBy=%d, samples=%d", behindBy, samples);
1188 break;
1189 }
1190 if (AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_ENDRX)) { // DMA Counter Register had reached 0, already rotated.
1191 AT91C_BASE_PDC_SSC->PDC_RNPR = (uint32_t) dmaBuf; // refresh the DMA Next Buffer and
1192 AT91C_BASE_PDC_SSC->PDC_RNCR = ISO15693_DMA_BUFFER_SIZE; // DMA Next Counter registers
1193 WDT_HIT();
1194 if(BUTTON_PRESS()) {
1195 DbpString("Snoop stopped.");
1196 break;
1197 }
1198 }
1199 }
1200 samples++;
a66f26da 1201
d9de20fa 1202 if (!TagIsActive) { // no need to try decoding reader data if the tag is sending
1203 if (Handle15693SampleFromReader(snoopdata & 0x02, &DecodeReader)) {
1204 FpgaDisableSscDma();
1205 ExpectTagAnswer = true;
c41dd5f9 1206 LogTrace_ISO15693(DecodeReader.output, DecodeReader.byteCount, samples*64, samples*64, NULL, true);
d9de20fa 1207 /* And ready to receive another command. */
1208 DecodeReaderReset(&DecodeReader);
1209 /* And also reset the demod code, which might have been */
1210 /* false-triggered by the commands from the reader. */
1211 DecodeTagReset(&DecodeTag);
1212 upTo = dmaBuf;
1213 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
1214 }
1215 if (Handle15693SampleFromReader(snoopdata & 0x01, &DecodeReader)) {
1216 FpgaDisableSscDma();
1217 ExpectTagAnswer = true;
c41dd5f9 1218 LogTrace_ISO15693(DecodeReader.output, DecodeReader.byteCount, samples*64, samples*64, NULL, true);
d9de20fa 1219 /* And ready to receive another command. */
1220 DecodeReaderReset(&DecodeReader);
1221 /* And also reset the demod code, which might have been */
1222 /* false-triggered by the commands from the reader. */
1223 DecodeTagReset(&DecodeTag);
1224 upTo = dmaBuf;
1225 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
1226 }
1227 ReaderIsActive = (DecodeReader.state >= STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF);
9455b51c 1228 }
d9de20fa 1229
a66f26da 1230 if (!ReaderIsActive && ExpectTagAnswer) { // no need to try decoding tag data if the reader is currently sending or no answer expected yet
d9de20fa 1231 if (Handle15693SamplesFromTag(snoopdata >> 2, &DecodeTag)) {
1232 FpgaDisableSscDma();
1233 //Use samples as a time measurement
c41dd5f9 1234 LogTrace_ISO15693(DecodeTag.output, DecodeTag.len, samples*64, samples*64, NULL, false);
d9de20fa 1235 // And ready to receive another response.
1236 DecodeTagReset(&DecodeTag);
1237 DecodeReaderReset(&DecodeReader);
1238 ExpectTagAnswer = false;
1239 upTo = dmaBuf;
1240 FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
1241 }
1242 TagIsActive = (DecodeTag.state >= STATE_TAG_RECEIVING_DATA);
1243 }
1244
9455b51c 1245 }
70b2fc0a 1246
d9de20fa 1247 FpgaDisableSscDma();
1248 BigBuf_free();
a66f26da 1249
d9de20fa 1250 LEDsoff();
1251
1252 DbpString("Snoop statistics:");
1253 Dbprintf(" ExpectTagAnswer: %d", ExpectTagAnswer);
1254 Dbprintf(" DecodeTag State: %d", DecodeTag.state);
1255 Dbprintf(" DecodeTag byteCnt: %d", DecodeTag.len);
1256 Dbprintf(" DecodeReader State: %d", DecodeReader.state);
1257 Dbprintf(" DecodeReader byteCnt: %d", DecodeReader.byteCount);
1258 Dbprintf(" Trace length: %d", BigBuf_get_traceLen());
9455b51c 1259}
1260
1261
8c6cca0b 1262// Initialize the proxmark as iso15k reader
c41dd5f9 1263void Iso15693InitReader() {
7cc204bf 1264 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
9455b51c 1265
1266 // Start from off (no field generated)
70b2fc0a 1267 LED_D_OFF();
9455b51c 1268 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
e6304bca 1269 SpinDelay(10);
9455b51c 1270
1271 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
5ea2a248 1272 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
9455b51c 1273
1274 // Give the tags time to energize
70b2fc0a 1275 LED_D_ON();
5ea2a248 1276 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
e6304bca 1277 SpinDelay(250);
9455b51c 1278}
1279
1280///////////////////////////////////////////////////////////////////////
1281// ISO 15693 Part 3 - Air Interface
70b2fc0a 1282// This section basically contains transmission and receiving of bits
9455b51c 1283///////////////////////////////////////////////////////////////////////
1284
9455b51c 1285
1286// uid is in transmission order (which is reverse of display order)
1287static void BuildReadBlockRequest(uint8_t *uid, uint8_t blockNumber )
1288{
1289 uint8_t cmd[13];
1290
1291 uint16_t crc;
d9de20fa 1292 // If we set the Option_Flag in this request, the VICC will respond with the security status of the block
1293 // followed by the block data
a66f26da 1294 cmd[0] = ISO15693_REQ_OPTION | ISO15693_REQ_ADDRESS | ISO15693_REQ_DATARATE_HIGH;
9455b51c 1295 // READ BLOCK command code
d9de20fa 1296 cmd[1] = ISO15693_READBLOCK;
9455b51c 1297 // UID may be optionally specified here
1298 // 64-bit UID
1299 cmd[2] = uid[0];
1300 cmd[3] = uid[1];
1301 cmd[4] = uid[2];
1302 cmd[5] = uid[3];
1303 cmd[6] = uid[4];
1304 cmd[7] = uid[5];
1305 cmd[8] = uid[6];
1306 cmd[9] = uid[7]; // 0xe0; // always e0 (not exactly unique)
1307 // Block number to read
d9de20fa 1308 cmd[10] = blockNumber;
9455b51c 1309 //Now the CRC
3d2c9c9b 1310 crc = Iso15693Crc(cmd, 11); // the crc needs to be calculated over 11 bytes
9455b51c 1311 cmd[11] = crc & 0xff;
1312 cmd[12] = crc >> 8;
1313
1314 CodeIso15693AsReader(cmd, sizeof(cmd));
1315}
1316
70b2fc0a 1317
9455b51c 1318// Now the VICC>VCD responses when we are simulating a tag
8c6cca0b 1319static void BuildInventoryResponse(uint8_t *uid)
9455b51c 1320{
1321 uint8_t cmd[12];
1322
1323 uint16_t crc;
8c6cca0b 1324
1325 cmd[0] = 0; // No error, no protocol format extension
3fe4ff4f 1326 cmd[1] = 0; // DSFID (data storage format identifier). 0x00 = not supported
9455b51c 1327 // 64-bit UID
3fe4ff4f 1328 cmd[2] = uid[7]; //0x32;
1329 cmd[3] = uid[6]; //0x4b;
1330 cmd[4] = uid[5]; //0x03;
1331 cmd[5] = uid[4]; //0x01;
1332 cmd[6] = uid[3]; //0x00;
1333 cmd[7] = uid[2]; //0x10;
1334 cmd[8] = uid[1]; //0x05;
1335 cmd[9] = uid[0]; //0xe0;
9455b51c 1336 //Now the CRC
3d2c9c9b 1337 crc = Iso15693Crc(cmd, 10);
9455b51c 1338 cmd[10] = crc & 0xff;
1339 cmd[11] = crc >> 8;
1340
8c6cca0b 1341 CodeIso15693AsTag(cmd, sizeof(cmd));
9455b51c 1342}
1343
e6304bca 1344// Universal Method for sending to and recv bytes from a tag
a66f26da 1345// init ... should we initialize the reader?
1346// speed ... 0 low speed, 1 hi speed
1347// *recv will contain the tag's answer
c41dd5f9 1348// return: length of received data, or -1 for timeout
1349int SendDataTag(uint8_t *send, int sendlen, bool init, int speed, uint8_t *recv, uint16_t max_recv_len, uint32_t start_time, uint32_t *eof_time) {
9455b51c 1350
9455b51c 1351 LED_A_ON();
70b2fc0a 1352 LED_B_OFF();
9455b51c 1353 LED_C_OFF();
8c6cca0b 1354
c41dd5f9 1355 if (init) {
1356 Iso15693InitReader();
1357 StartCountSspClk();
1358 }
1359
1360 int answerLen = 0;
1361
9455b51c 1362 if (!speed) {
1363 // low speed (1 out of 256)
1364 CodeIso15693AsReader256(send, sendlen);
1365 } else {
1366 // high speed (1 out of 4)
1367 CodeIso15693AsReader(send, sendlen);
1368 }
8c6cca0b 1369
c41dd5f9 1370 if (start_time == 0) {
1371 start_time = GetCountSspClk();
1372 }
1373 TransmitTo15693Tag(ToSend, ToSendMax, &start_time);
d9de20fa 1374
9455b51c 1375 // Now wait for a response
d9de20fa 1376 if (recv != NULL) {
c41dd5f9 1377 answerLen = GetIso15693AnswerFromTag(recv, max_recv_len, DELAY_ISO15693_VCD_TO_VICC_READER * 2, eof_time);
9455b51c 1378 }
1379
1380 LED_A_OFF();
8c6cca0b 1381
9455b51c 1382 return answerLen;
1383}
15c4dc5a 1384
15c4dc5a 1385
9455b51c 1386// --------------------------------------------------------------------
8c6cca0b 1387// Debug Functions
9455b51c 1388// --------------------------------------------------------------------
15c4dc5a 1389
9455b51c 1390// Decodes a message from a tag and displays its metadata and content
1391#define DBD15STATLEN 48
1392void DbdecodeIso15693Answer(int len, uint8_t *d) {
1393 char status[DBD15STATLEN+1]={0};
1394 uint16_t crc;
1395
d9de20fa 1396 if (len > 3) {
1397 if (d[0] & ISO15693_RES_EXT)
1398 strncat(status,"ProtExt ", DBD15STATLEN);
1399 if (d[0] & ISO15693_RES_ERROR) {
9455b51c 1400 // error
d9de20fa 1401 strncat(status,"Error ", DBD15STATLEN);
9455b51c 1402 switch (d[1]) {
8c6cca0b 1403 case 0x01:
d9de20fa 1404 strncat(status,"01:notSupp", DBD15STATLEN);
15c4dc5a 1405 break;
8c6cca0b 1406 case 0x02:
d9de20fa 1407 strncat(status,"02:notRecog", DBD15STATLEN);
9455b51c 1408 break;
8c6cca0b 1409 case 0x03:
d9de20fa 1410 strncat(status,"03:optNotSupp", DBD15STATLEN);
9455b51c 1411 break;
8c6cca0b 1412 case 0x0f:
d9de20fa 1413 strncat(status,"0f:noInfo", DBD15STATLEN);
9455b51c 1414 break;
8c6cca0b 1415 case 0x10:
d9de20fa 1416 strncat(status,"10:doesn'tExist", DBD15STATLEN);
9455b51c 1417 break;
8c6cca0b 1418 case 0x11:
d9de20fa 1419 strncat(status,"11:lockAgain", DBD15STATLEN);
9455b51c 1420 break;
8c6cca0b 1421 case 0x12:
d9de20fa 1422 strncat(status,"12:locked", DBD15STATLEN);
9455b51c 1423 break;
8c6cca0b 1424 case 0x13:
d9de20fa 1425 strncat(status,"13:progErr", DBD15STATLEN);
9455b51c 1426 break;
8c6cca0b 1427 case 0x14:
d9de20fa 1428 strncat(status,"14:lockErr", DBD15STATLEN);
9455b51c 1429 break;
1430 default:
d9de20fa 1431 strncat(status,"unknownErr", DBD15STATLEN);
15c4dc5a 1432 }
d9de20fa 1433 strncat(status," ", DBD15STATLEN);
9455b51c 1434 } else {
d9de20fa 1435 strncat(status,"NoErr ", DBD15STATLEN);
15c4dc5a 1436 }
8c6cca0b 1437
3d2c9c9b 1438 crc=Iso15693Crc(d,len-2);
8c6cca0b 1439 if ( (( crc & 0xff ) == d[len-2]) && (( crc >> 8 ) == d[len-1]) )
9455b51c 1440 strncat(status,"CrcOK",DBD15STATLEN);
1441 else
8c6cca0b 1442 strncat(status,"CrcFail!",DBD15STATLEN);
9455b51c 1443
1444 Dbprintf("%s",status);
15c4dc5a 1445 }
1446}
1447
9455b51c 1448
1449
1450///////////////////////////////////////////////////////////////////////
1451// Functions called via USB/Client
1452///////////////////////////////////////////////////////////////////////
1453
1454void SetDebugIso15693(uint32_t debug) {
1455 DEBUG=debug;
1456 Dbprintf("Iso15693 Debug is now %s",DEBUG?"on":"off");
1457 return;
1458}
1459
d9de20fa 1460
5ea2a248 1461//---------------------------------------------------------------------------------------
1462// Simulate an ISO15693 reader, perform anti-collision and then attempt to read a sector.
15c4dc5a 1463// all demodulation performed in arm rather than host. - greg
5ea2a248 1464//---------------------------------------------------------------------------------------
f7e3ed82 1465void ReaderIso15693(uint32_t parameter)
15c4dc5a 1466{
70b2fc0a 1467 LEDsoff();
15c4dc5a 1468 LED_A_ON();
15c4dc5a 1469
d9de20fa 1470 set_tracing(true);
a66f26da 1471
d9de20fa 1472 int answerLen = 0;
3fe4ff4f 1473 uint8_t TagUID[8] = {0x00};
1474
09ffd16e 1475 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
15c4dc5a 1476
d9de20fa 1477 uint8_t answer[ISO15693_MAX_RESPONSE_LENGTH];
15c4dc5a 1478
3fe4ff4f 1479 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
15c4dc5a 1480 // Setup SSC
5ea2a248 1481 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
15c4dc5a 1482
1483 // Start from off (no field generated)
a66f26da 1484 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1485 SpinDelay(200);
15c4dc5a 1486
15c4dc5a 1487 // Give the tags time to energize
70b2fc0a 1488 LED_D_ON();
5ea2a248 1489 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
15c4dc5a 1490 SpinDelay(200);
d9de20fa 1491 StartCountSspClk();
1492
15c4dc5a 1493
15c4dc5a 1494 // FIRST WE RUN AN INVENTORY TO GET THE TAG UID
1495 // THIS MEANS WE CAN PRE-BUILD REQUESTS TO SAVE CPU TIME
15c4dc5a 1496
1497 // Now send the IDENTIFY command
1498 BuildIdentifyRequest();
c41dd5f9 1499 uint32_t start_time = 0;
1500 TransmitTo15693Tag(ToSend, ToSendMax, &start_time);
a66f26da 1501
15c4dc5a 1502 // Now wait for a response
c41dd5f9 1503 uint32_t eof_time;
1504 answerLen = GetIso15693AnswerFromTag(answer, sizeof(answer), DELAY_ISO15693_VCD_TO_VICC_READER * 2, &eof_time) ;
1505 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
15c4dc5a 1506
d9de20fa 1507 if (answerLen >=12) // we should do a better check than this
15c4dc5a 1508 {
d9de20fa 1509 TagUID[0] = answer[2];
1510 TagUID[1] = answer[3];
1511 TagUID[2] = answer[4];
1512 TagUID[3] = answer[5];
1513 TagUID[4] = answer[6];
1514 TagUID[5] = answer[7];
1515 TagUID[6] = answer[8]; // IC Manufacturer code
1516 TagUID[7] = answer[9]; // always E0
15c4dc5a 1517
15c4dc5a 1518 }
1519
d9de20fa 1520 Dbprintf("%d octets read from IDENTIFY request:", answerLen);
1521 DbdecodeIso15693Answer(answerLen, answer);
1522 Dbhexdump(answerLen, answer, false);
9455b51c 1523
1524 // UID is reverse
d9de20fa 1525 if (answerLen >= 12)
3fe4ff4f 1526 Dbprintf("UID = %02hX%02hX%02hX%02hX%02hX%02hX%02hX%02hX",
1527 TagUID[7],TagUID[6],TagUID[5],TagUID[4],
1528 TagUID[3],TagUID[2],TagUID[1],TagUID[0]);
9455b51c 1529
1530
315e18e6 1531 // Dbprintf("%d octets read from SELECT request:", answerLen2);
1532 // DbdecodeIso15693Answer(answerLen2,answer2);
1533 // Dbhexdump(answerLen2,answer2,true);
9455b51c 1534
315e18e6 1535 // Dbprintf("%d octets read from XXX request:", answerLen3);
1536 // DbdecodeIso15693Answer(answerLen3,answer3);
1537 // Dbhexdump(answerLen3,answer3,true);
9455b51c 1538
9455b51c 1539 // read all pages
d9de20fa 1540 if (answerLen >= 12 && DEBUG) {
5ea2a248 1541 for (int i = 0; i < 32; i++) { // sanity check, assume max 32 pages
8c6cca0b 1542 BuildReadBlockRequest(TagUID, i);
c41dd5f9 1543 TransmitTo15693Tag(ToSend, ToSendMax, &start_time);
1544 int answerLen = GetIso15693AnswerFromTag(answer, sizeof(answer), DELAY_ISO15693_VCD_TO_VICC_READER * 2, &eof_time);
1545 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
d9de20fa 1546 if (answerLen > 0) {
1547 Dbprintf("READ SINGLE BLOCK %d returned %d octets:", i, answerLen);
1548 DbdecodeIso15693Answer(answerLen, answer);
1549 Dbhexdump(answerLen, answer, false);
1550 if ( *((uint32_t*) answer) == 0x07160101 ) break; // exit on NoPageErr
8c6cca0b 1551 }
8c6cca0b 1552 }
9455b51c 1553 }
15c4dc5a 1554
8c6cca0b 1555 // for the time being, switch field off to protect rdv4.0
70b2fc0a 1556 // note: this prevents using hf 15 cmd with s option - which isn't implemented yet anyway
a66f26da 1557 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
15c4dc5a 1558 LED_D_OFF();
8c6cca0b 1559
70b2fc0a 1560 LED_A_OFF();
15c4dc5a 1561}
1562
8c6cca0b 1563
1564// Simulate an ISO15693 TAG.
1565// For Inventory command: print command and send Inventory Response with given UID
1566// TODO: interpret other reader commands and send appropriate response
3fe4ff4f 1567void SimTagIso15693(uint32_t parameter, uint8_t *uid)
15c4dc5a 1568{
70b2fc0a 1569 LEDsoff();
15c4dc5a 1570 LED_A_ON();
15c4dc5a 1571
7cc204bf 1572 FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
15c4dc5a 1573 SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
a66f26da 1574 FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
8c6cca0b 1575 FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
15c4dc5a 1576
8c6cca0b 1577 StartCountSspClk();
15c4dc5a 1578
8c6cca0b 1579 uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH];
15c4dc5a 1580
8c6cca0b 1581 // Build a suitable response to the reader INVENTORY command
1582 BuildInventoryResponse(uid);
15c4dc5a 1583
8c6cca0b 1584 // Listen to reader
1585 while (!BUTTON_PRESS()) {
1586 uint32_t eof_time = 0, start_time = 0;
1587 int cmd_len = GetIso15693CommandFromReader(cmd, sizeof(cmd), &eof_time);
1588
1589 if ((cmd_len >= 5) && (cmd[0] & ISO15693_REQ_INVENTORY) && (cmd[1] == ISO15693_INVENTORY)) { // TODO: check more flags
1590 bool slow = !(cmd[0] & ISO15693_REQ_DATARATE_HIGH);
c41dd5f9 1591 start_time = eof_time + DELAY_ISO15693_VCD_TO_VICC_SIM;
8efd0b80 1592 TransmitTo15693Reader(ToSend, ToSendMax, &start_time, 0, slow);
8c6cca0b 1593 }
3fe4ff4f 1594
8c6cca0b 1595 Dbprintf("%d bytes read from reader:", cmd_len);
1596 Dbhexdump(cmd_len, cmd, false);
1597 }
15c4dc5a 1598
a66f26da 1599 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
70b2fc0a 1600 LEDsoff();
15c4dc5a 1601}
9455b51c 1602
1603
1604// Since there is no standardized way of reading the AFI out of a tag, we will brute force it
1605// (some manufactures offer a way to read the AFI, though)
8c6cca0b 1606void BruteforceIso15693Afi(uint32_t speed)
1607{
70b2fc0a 1608 LEDsoff();
1609 LED_A_ON();
8c6cca0b 1610
d9de20fa 1611 uint8_t data[6];
1612 uint8_t recv[ISO15693_MAX_RESPONSE_LENGTH];
c41dd5f9 1613 int datalen = 0, recvlen = 0;
1614 uint32_t eof_time;
a66f26da 1615
9455b51c 1616 // first without AFI
8c6cca0b 1617 // Tags should respond without AFI and with AFI=0 even when AFI is active
1618
1619 data[0] = ISO15693_REQ_DATARATE_HIGH | ISO15693_REQ_INVENTORY | ISO15693_REQINV_SLOT1;
1620 data[1] = ISO15693_INVENTORY;
1621 data[2] = 0; // mask length
3d2c9c9b 1622 datalen = Iso15693AddCrc(data,3);
c41dd5f9 1623 uint32_t start_time = GetCountSspClk();
1624 recvlen = SendDataTag(data, datalen, true, speed, recv, sizeof(recv), 0, &eof_time);
1625 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
9455b51c 1626 WDT_HIT();
1627 if (recvlen>=12) {
3d2c9c9b 1628 Dbprintf("NoAFI UID=%s", Iso15693sprintUID(NULL, &recv[2]));
9455b51c 1629 }
8c6cca0b 1630
9455b51c 1631 // now with AFI
8c6cca0b 1632
1633 data[0] = ISO15693_REQ_DATARATE_HIGH | ISO15693_REQ_INVENTORY | ISO15693_REQINV_AFI | ISO15693_REQINV_SLOT1;
1634 data[1] = ISO15693_INVENTORY;
1635 data[2] = 0; // AFI
1636 data[3] = 0; // mask length
1637
d9de20fa 1638 for (int i = 0; i < 256; i++) {
1639 data[2] = i & 0xFF;
3d2c9c9b 1640 datalen = Iso15693AddCrc(data,4);
c41dd5f9 1641 recvlen = SendDataTag(data, datalen, false, speed, recv, sizeof(recv), start_time, &eof_time);
1642 start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
9455b51c 1643 WDT_HIT();
d9de20fa 1644 if (recvlen >= 12) {
3d2c9c9b 1645 Dbprintf("AFI=%i UID=%s", i, Iso15693sprintUID(NULL, &recv[2]));
9455b51c 1646 }
8c6cca0b 1647 }
9455b51c 1648 Dbprintf("AFI Bruteforcing done.");
8c6cca0b 1649
a66f26da 1650 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
70b2fc0a 1651 LEDsoff();
9455b51c 1652}
1653
1654// Allows to directly send commands to the tag via the client
70b2fc0a 1655void DirectTag15693Command(uint32_t datalen, uint32_t speed, uint32_t recv, uint8_t data[]) {
9455b51c 1656
d9de20fa 1657 int recvlen = 0;
1658 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
c41dd5f9 1659 uint32_t eof_time;
1660
70b2fc0a 1661 LED_A_ON();
8c6cca0b 1662
9455b51c 1663 if (DEBUG) {
d9de20fa 1664 Dbprintf("SEND:");
8c6cca0b 1665 Dbhexdump(datalen, data, false);
9455b51c 1666 }
8c6cca0b 1667
c41dd5f9 1668 recvlen = SendDataTag(data, datalen, true, speed, (recv?recvbuf:NULL), sizeof(recvbuf), 0, &eof_time);
1669
1670 // for the time being, switch field off to protect rdv4.0
1671 // note: this prevents using hf 15 cmd with s option - which isn't implemented yet anyway
1672 FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
1673 LED_D_OFF();
9455b51c 1674
8c6cca0b 1675 if (recv) {
9455b51c 1676 if (DEBUG) {
d9de20fa 1677 Dbprintf("RECV:");
c41dd5f9 1678 if (recvlen > 0) {
1679 Dbhexdump(recvlen, recvbuf, false);
1680 DbdecodeIso15693Answer(recvlen, recvbuf);
1681 }
9455b51c 1682 }
c41dd5f9 1683 if (recvlen > ISO15693_MAX_RESPONSE_LENGTH) {
1684 recvlen = ISO15693_MAX_RESPONSE_LENGTH;
1685 }
1686 cmd_send(CMD_ACK, recvlen, 0, 0, recvbuf, ISO15693_MAX_RESPONSE_LENGTH);
9455b51c 1687 }
1688
70b2fc0a 1689 LED_A_OFF();
9455b51c 1690}
1691
096dee17 1692//-----------------------------------------------------------------------------
1693// Work with "magic Chinese" card.
1694//
1695//-----------------------------------------------------------------------------
1696
1697// Set the UID to the tag (based on Iceman work).
1698void SetTag15693Uid(uint8_t *uid)
1699{
a66f26da 1700 uint8_t cmd[4][9] = {0x00};
1701
1702 uint16_t crc;
1703
1704 int recvlen = 0;
1705 uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
c41dd5f9 1706 uint32_t eof_time;
1707
a66f26da 1708 LED_A_ON();
1709
1710 // Command 1 : 02213E00000000
1711 cmd[0][0] = 0x02;
1712 cmd[0][1] = 0x21;
1713 cmd[0][2] = 0x3e;
1714 cmd[0][3] = 0x00;
1715 cmd[0][4] = 0x00;
1716 cmd[0][5] = 0x00;
1717 cmd[0][6] = 0x00;
1718
1719 // Command 2 : 02213F69960000
1720 cmd[1][0] = 0x02;
1721 cmd[1][1] = 0x21;
1722 cmd[1][2] = 0x3f;
1723 cmd[1][3] = 0x69;
1724 cmd[1][4] = 0x96;
1725 cmd[1][5] = 0x00;
1726 cmd[1][6] = 0x00;
1727
1728 // Command 3 : 022138u8u7u6u5 (where uX = uid byte X)
1729 cmd[2][0] = 0x02;
1730 cmd[2][1] = 0x21;
1731 cmd[2][2] = 0x38;
1732 cmd[2][3] = uid[7];
1733 cmd[2][4] = uid[6];
1734 cmd[2][5] = uid[5];
1735 cmd[2][6] = uid[4];
1736
1737 // Command 4 : 022139u4u3u2u1 (where uX = uid byte X)
1738 cmd[3][0] = 0x02;
1739 cmd[3][1] = 0x21;
1740 cmd[3][2] = 0x39;
1741 cmd[3][3] = uid[3];
1742 cmd[3][4] = uid[2];
1743 cmd[3][5] = uid[1];
1744 cmd[3][6] = uid[0];
1745
c41dd5f9 1746 for (int i = 0; i < 4; i++) {
a66f26da 1747 // Add the CRC
1748 crc = Iso15693Crc(cmd[i], 7);
1749 cmd[i][7] = crc & 0xff;
1750 cmd[i][8] = crc >> 8;
1751
1752 if (DEBUG) {
1753 Dbprintf("SEND:");
1754 Dbhexdump(sizeof(cmd[i]), cmd[i], false);
1755 }
1756
c41dd5f9 1757 recvlen = SendDataTag(cmd[i], sizeof(cmd[i]), true, 1, recvbuf, sizeof(recvbuf), 0, &eof_time);
a66f26da 1758
1759 if (DEBUG) {
1760 Dbprintf("RECV:");
c41dd5f9 1761 if (recvlen > 0) {
1762 Dbhexdump(recvlen, recvbuf, false);
1763 DbdecodeIso15693Answer(recvlen, recvbuf);
1764 }
a66f26da 1765 }
1766
1767 cmd_send(CMD_ACK, recvlen>ISO15693_MAX_RESPONSE_LENGTH?ISO15693_MAX_RESPONSE_LENGTH:recvlen, 0, 0, recvbuf, ISO15693_MAX_RESPONSE_LENGTH);
1768 }
1769
1770 LED_D_OFF();
1771
1772 LED_A_OFF();
096dee17 1773}
9455b51c 1774
1775
1776
1777// --------------------------------------------------------------------
1778// -- Misc & deprecated functions
1779// --------------------------------------------------------------------
1780
e6304bca 1781/*
9455b51c 1782
1783// do not use; has a fix UID
1784static void __attribute__((unused)) BuildSysInfoRequest(uint8_t *uid)
1785{
1786 uint8_t cmd[12];
1787
1788 uint16_t crc;
5ea2a248 1789 // If we set the Option_Flag in this request, the VICC will respond with the security status of the block
1790 // followed by the block data
9455b51c 1791 // one sub-carrier, inventory, 1 slot, fast rate
1792 cmd[0] = (1 << 5) | (1 << 1); // no SELECT bit
1793 // System Information command code
1794 cmd[1] = 0x2B;
1795 // UID may be optionally specified here
1796 // 64-bit UID
1797 cmd[2] = 0x32;
1798 cmd[3]= 0x4b;
1799 cmd[4] = 0x03;
1800 cmd[5] = 0x01;
1801 cmd[6] = 0x00;
1802 cmd[7] = 0x10;
1803 cmd[8] = 0x05;
1804 cmd[9]= 0xe0; // always e0 (not exactly unique)
1805 //Now the CRC
3d2c9c9b 1806 crc = Iso15693Crc(cmd, 10); // the crc needs to be calculated over 2 bytes
9455b51c 1807 cmd[10] = crc & 0xff;
1808 cmd[11] = crc >> 8;
1809
1810 CodeIso15693AsReader(cmd, sizeof(cmd));
1811}
1812
9455b51c 1813
1814// do not use; has a fix UID
1815static void __attribute__((unused)) BuildReadMultiBlockRequest(uint8_t *uid)
1816{
1817 uint8_t cmd[14];
1818
1819 uint16_t crc;
5ea2a248 1820 // If we set the Option_Flag in this request, the VICC will respond with the security status of the block
1821 // followed by the block data
9455b51c 1822 // one sub-carrier, inventory, 1 slot, fast rate
1823 cmd[0] = (1 << 5) | (1 << 1); // no SELECT bit
1824 // READ Multi BLOCK command code
1825 cmd[1] = 0x23;
1826 // UID may be optionally specified here
1827 // 64-bit UID
1828 cmd[2] = 0x32;
1829 cmd[3]= 0x4b;
1830 cmd[4] = 0x03;
1831 cmd[5] = 0x01;
1832 cmd[6] = 0x00;
1833 cmd[7] = 0x10;
1834 cmd[8] = 0x05;
1835 cmd[9]= 0xe0; // always e0 (not exactly unique)
1836 // First Block number to read
1837 cmd[10] = 0x00;
1838 // Number of Blocks to read
1839 cmd[11] = 0x2f; // read quite a few
1840 //Now the CRC
3d2c9c9b 1841 crc = Iso15693Crc(cmd, 12); // the crc needs to be calculated over 2 bytes
9455b51c 1842 cmd[12] = crc & 0xff;
1843 cmd[13] = crc >> 8;
1844
1845 CodeIso15693AsReader(cmd, sizeof(cmd));
1846}
1847
1848// do not use; has a fix UID
1849static void __attribute__((unused)) BuildArbitraryRequest(uint8_t *uid,uint8_t CmdCode)
1850{
1851 uint8_t cmd[14];
1852
1853 uint16_t crc;
5ea2a248 1854 // If we set the Option_Flag in this request, the VICC will respond with the security status of the block
1855 // followed by the block data
9455b51c 1856 // one sub-carrier, inventory, 1 slot, fast rate
1857 cmd[0] = (1 << 5) | (1 << 1); // no SELECT bit
1858 // READ BLOCK command code
1859 cmd[1] = CmdCode;
1860 // UID may be optionally specified here
1861 // 64-bit UID
1862 cmd[2] = 0x32;
1863 cmd[3]= 0x4b;
1864 cmd[4] = 0x03;
1865 cmd[5] = 0x01;
1866 cmd[6] = 0x00;
1867 cmd[7] = 0x10;
1868 cmd[8] = 0x05;
1869 cmd[9]= 0xe0; // always e0 (not exactly unique)
1870 // Parameter
1871 cmd[10] = 0x00;
1872 cmd[11] = 0x0a;
1873
a66f26da 1874// cmd[12] = 0x00;
1875// cmd[13] = 0x00; //Now the CRC
3d2c9c9b 1876 crc = Iso15693Crc(cmd, 12); // the crc needs to be calculated over 2 bytes
9455b51c 1877 cmd[12] = crc & 0xff;
1878 cmd[13] = crc >> 8;
1879
1880 CodeIso15693AsReader(cmd, sizeof(cmd));
1881}
1882
1883// do not use; has a fix UID
1884static void __attribute__((unused)) BuildArbitraryCustomRequest(uint8_t uid[], uint8_t CmdCode)
1885{
1886 uint8_t cmd[14];
1887
1888 uint16_t crc;
5ea2a248 1889 // If we set the Option_Flag in this request, the VICC will respond with the security status of the block
1890 // followed by the block data
9455b51c 1891 // one sub-carrier, inventory, 1 slot, fast rate
1892 cmd[0] = (1 << 5) | (1 << 1); // no SELECT bit
1893 // READ BLOCK command code
1894 cmd[1] = CmdCode;
1895 // UID may be optionally specified here
1896 // 64-bit UID
1897 cmd[2] = 0x32;
1898 cmd[3]= 0x4b;
1899 cmd[4] = 0x03;
1900 cmd[5] = 0x01;
1901 cmd[6] = 0x00;
1902 cmd[7] = 0x10;
1903 cmd[8] = 0x05;
1904 cmd[9]= 0xe0; // always e0 (not exactly unique)
1905 // Parameter
5ea2a248 1906 cmd[10] = 0x05; // for custom codes this must be manufacturer code
9455b51c 1907 cmd[11] = 0x00;
1908
a66f26da 1909// cmd[12] = 0x00;
1910// cmd[13] = 0x00; //Now the CRC
3d2c9c9b 1911 crc = Iso15693Crc(cmd, 12); // the crc needs to be calculated over 2 bytes
9455b51c 1912 cmd[12] = crc & 0xff;
1913 cmd[13] = crc >> 8;
1914
1915 CodeIso15693AsReader(cmd, sizeof(cmd));
1916}
1917
1918
1919
1920
e6304bca 1921*/
9455b51c 1922
1923
Impressum, Datenschutz