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