]> git.zerfleddert.de Git - proxmark3-svn/blobdiff - armsrc/iso15693.c
fixing iso15693
[proxmark3-svn] / armsrc / iso15693.c
index 761340e92c74aa2109353cb205176e96660c413c..f16698bbb901f66120d67a528f6a077fad2118bc 100644 (file)
@@ -58,7 +58,7 @@
 #include "string.h"
 #include "iso15693tools.h"
 #include "protocols.h"
-#include "cmd.h"
+#include "usb_cdc.h"
 #include "BigBuf.h"
 #include "fpgaloader.h"
 
 #define DELAY_TAG_TO_ARM_SNOOP           32
 #define DELAY_READER_TO_ARM_SNOOP        32
 
-static int DEBUG = 0;
+// times in samples @ 212kHz when acting as reader
+//#define ISO15693_READER_TIMEOUT              80 // 80/212kHz = 378us, nominal t1_max=313,9us
+#define ISO15693_READER_TIMEOUT             330 // 330/212kHz = 1558us, should be even enough for iClass tags responding to ACTALL
+#define ISO15693_READER_TIMEOUT_WRITE      4700 // 4700/212kHz = 22ms, nominal 20ms
 
 
-// specific LogTrace function for ISO15693: the duration needs to be scaled because otherwise it won't fit into a uint16_t
-bool LogTrace_ISO15693(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag) {
-       uint32_t duration = timestamp_end - timestamp_start;
-       duration /= 32;
-       timestamp_end = timestamp_start + duration;
-       return LogTrace(btBytes, iLen, timestamp_start, timestamp_end, parity, readerToTag);
-}
+static int DEBUG = 0;
 
 
 ///////////////////////////////////////////////////////////////////////
@@ -93,10 +90,20 @@ bool LogTrace_ISO15693(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp
 ///////////////////////////////////////////////////////////////////////
 
 // buffers
-#define ISO15693_DMA_BUFFER_SIZE       2048 // must be a power of 2
+#define ISO15693_DMA_BUFFER_SIZE        256 // must be a power of 2
 #define ISO15693_MAX_RESPONSE_LENGTH     36 // allows read single block with the maximum block size of 256bits. Read multiple blocks not supported yet
 #define ISO15693_MAX_COMMAND_LENGTH      45 // allows write single block with the maximum block size of 256bits. Write multiple blocks not supported yet
 
+
+// specific LogTrace function for ISO15693: the duration needs to be scaled because otherwise it won't fit into a uint16_t
+bool LogTrace_ISO15693(const uint8_t *btBytes, uint16_t iLen, uint32_t timestamp_start, uint32_t timestamp_end, uint8_t *parity, bool readerToTag) {
+       uint32_t duration = timestamp_end - timestamp_start;
+       duration /= 32;
+       timestamp_end = timestamp_start + duration;
+       return LogTrace(btBytes, iLen, timestamp_start, timestamp_end, parity, readerToTag);
+}
+
+
 // ---------------------------
 // Signal Processing
 // ---------------------------
@@ -139,6 +146,15 @@ void CodeIso15693AsReader(uint8_t *cmd, int n) {
        ToSendMax++;
 }
 
+
+// Encode EOF only
+static void CodeIso15693AsReaderEOF() {
+       ToSendReset();
+       ToSend[++ToSendMax] = 0x20;
+       ToSendMax++;
+}
+
+
 // encode data using "1 out of 256" scheme
 // data rate is 1,66 kbit/s (fc/8192)
 // is designed for more robust communication over longer distances
@@ -275,7 +291,6 @@ void TransmitTo15693Tag(const uint8_t *cmd, int len, uint32_t *start_time) {
                        AT91C_BASE_SSC->SSC_THR = send_word;
                        while (!(AT91C_BASE_SSC->SSC_SR & (AT91C_SSC_TXRDY))) ;
                        AT91C_BASE_SSC->SSC_THR = send_word;
-
                        data <<= 1;
                }
                WDT_HIT();
@@ -283,7 +298,6 @@ void TransmitTo15693Tag(const uint8_t *cmd, int len, uint32_t *start_time) {
        LED_B_OFF();
 
        *start_time = *start_time + DELAY_ARM_TO_TAG;
-
 }
 
 
@@ -354,7 +368,7 @@ void TransmitTo15693Reader(const uint8_t *cmd, size_t len, uint32_t *start_time,
 //          false if we are still waiting for some more
 //=============================================================================
 
-#define NOISE_THRESHOLD          160                   // don't try to correlate noise
+#define NOISE_THRESHOLD          80                   // don't try to correlate noise
 #define MAX_PREVIOUS_AMPLITUDE   (-1 - NOISE_THRESHOLD)
 
 typedef struct DecodeTag {
@@ -387,7 +401,7 @@ typedef struct DecodeTag {
 
 
 static int inline __attribute__((always_inline)) Handle15693SamplesFromTag(uint16_t amplitude, DecodeTag_t *DecodeTag) {
-       switch(DecodeTag->state) {
+       switch (DecodeTag->state) {
                case STATE_TAG_SOF_LOW:
                        // waiting for a rising edge
                        if (amplitude > NOISE_THRESHOLD + DecodeTag->previous_amplitude) {
@@ -739,7 +753,8 @@ typedef struct DecodeReader {
                STATE_READER_AWAIT_2ND_RISING_EDGE_OF_SOF,
                STATE_READER_AWAIT_END_OF_SOF_1_OUT_OF_4,
                STATE_READER_RECEIVE_DATA_1_OUT_OF_4,
-               STATE_READER_RECEIVE_DATA_1_OUT_OF_256
+               STATE_READER_RECEIVE_DATA_1_OUT_OF_256,
+               STATE_READER_RECEIVE_JAMMING
        }           state;
        enum {
                CODING_1_OUT_OF_4,
@@ -752,11 +767,12 @@ typedef struct DecodeReader {
        int         posCount;
        int         sum1, sum2;
        uint8_t     *output;
+       uint8_t     jam_search_len;
+       uint8_t     *jam_search_string;
 } DecodeReader_t;
 
 
-static void DecodeReaderInit(DecodeReader_t* DecodeReader, uint8_t *data, uint16_t max_len)
-{
+static void DecodeReaderInit(DecodeReader_t* DecodeReader, uint8_t *data, uint16_t max_len, uint8_t jam_search_len, uint8_t *jam_search_string) {
        DecodeReader->output = data;
        DecodeReader->byteCountMax = max_len;
        DecodeReader->state = STATE_READER_UNSYNCD;
@@ -764,17 +780,17 @@ static void DecodeReaderInit(DecodeReader_t* DecodeReader, uint8_t *data, uint16
        DecodeReader->bitCount = 0;
        DecodeReader->posCount = 1;
        DecodeReader->shiftReg = 0;
+       DecodeReader->jam_search_len = jam_search_len;
+       DecodeReader->jam_search_string = jam_search_string;
 }
 
 
-static void DecodeReaderReset(DecodeReader_t* DecodeReader)
-{
+static void DecodeReaderReset(DecodeReader_t* DecodeReader) {
        DecodeReader->state = STATE_READER_UNSYNCD;
 }
 
 
-static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uint8_t bit, DecodeReader_t *restrict DecodeReader)
-{
+static int inline __attribute__((always_inline)) Handle15693SampleFromReader(bool bit, DecodeReader_t *DecodeReader) {
        switch (DecodeReader->state) {
                case STATE_READER_UNSYNCD:
                        // wait for unmodulated carrier
@@ -889,16 +905,15 @@ static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uin
                        break;
 
                case STATE_READER_RECEIVE_DATA_1_OUT_OF_4:
-                       bit = !!bit;
                        DecodeReader->posCount++;
                        if (DecodeReader->posCount == 1) {
-                               DecodeReader->sum1 = bit;
+                               DecodeReader->sum1 = bit?1:0;
                        } else if (DecodeReader->posCount <= 4) {
-                               DecodeReader->sum1 += bit;
+                               if (bit) DecodeReader->sum1++;
                        } else if (DecodeReader->posCount == 5) {
-                               DecodeReader->sum2 = bit;
+                               DecodeReader->sum2 = bit?1:0;
                        } else {
-                               DecodeReader->sum2 += bit;
+                               if (bit) DecodeReader->sum2++;
                        }
                        if (DecodeReader->posCount == 8) {
                                DecodeReader->posCount = 0;
@@ -908,8 +923,7 @@ static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uin
                                        if (DecodeReader->byteCount != 0) {
                                                return true;
                                        }
-                               }
-                               if (DecodeReader->sum1 >= 3 && DecodeReader->sum2 <= 1) { // detected a 2bit position
+                               } else if (DecodeReader->sum1 >= 3 && DecodeReader->sum2 <= 1) { // detected a 2bit position
                                        DecodeReader->shiftReg >>= 2;
                                        DecodeReader->shiftReg |= (DecodeReader->bitCount << 6);
                                }
@@ -922,6 +936,13 @@ static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uin
                                        }
                                        DecodeReader->bitCount = 0;
                                        DecodeReader->shiftReg = 0;
+                                       if (DecodeReader->byteCount == DecodeReader->jam_search_len) {
+                                               if (!memcmp(DecodeReader->output, DecodeReader->jam_search_string, DecodeReader->jam_search_len)) {
+                                                       LED_D_ON();
+                                                       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_JAM);
+                                                       DecodeReader->state = STATE_READER_RECEIVE_JAMMING;
+                                               }
+                                       }
                                } else {
                                        DecodeReader->bitCount++;
                                }
@@ -929,16 +950,15 @@ static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uin
                        break;
 
                case STATE_READER_RECEIVE_DATA_1_OUT_OF_256:
-                       bit = !!bit;
                        DecodeReader->posCount++;
                        if (DecodeReader->posCount == 1) {
-                               DecodeReader->sum1 = bit;
+                               DecodeReader->sum1 = bit?1:0;
                        } else if (DecodeReader->posCount <= 4) {
-                               DecodeReader->sum1 += bit;
+                               if (bit) DecodeReader->sum1++;
                        } else if (DecodeReader->posCount == 5) {
-                               DecodeReader->sum2 = bit;
-                       } else {
-                               DecodeReader->sum2 += bit;
+                               DecodeReader->sum2 = bit?1:0;
+                       } else if (bit) {
+                               DecodeReader->sum2++;
                        }
                        if (DecodeReader->posCount == 8) {
                                DecodeReader->posCount = 0;
@@ -948,8 +968,7 @@ static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uin
                                        if (DecodeReader->byteCount != 0) {
                                                return true;
                                        }
-                               }
-                               if (DecodeReader->sum1 >= 3 && DecodeReader->sum2 <= 1) { // detected the bit position
+                               } else if (DecodeReader->sum1 >= 3 && DecodeReader->sum2 <= 1) { // detected the bit position
                                        DecodeReader->shiftReg = DecodeReader->bitCount;
                                }
                                if (DecodeReader->bitCount == 255) { // we have a full byte
@@ -959,11 +978,42 @@ static int inline __attribute__((always_inline)) Handle15693SampleFromReader(uin
                                                LED_B_OFF();
                                                DecodeReaderReset(DecodeReader);
                                        }
+                                       if (DecodeReader->byteCount == DecodeReader->jam_search_len) {
+                                               if (!memcmp(DecodeReader->output, DecodeReader->jam_search_string, DecodeReader->jam_search_len)) {
+                                                       LED_D_ON();
+                                                       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SEND_JAM);
+                                                       DecodeReader->state = STATE_READER_RECEIVE_JAMMING;
+                                               }
+                                       }
                                }
                                DecodeReader->bitCount++;
                        }
                        break;
 
+               case STATE_READER_RECEIVE_JAMMING:
+                       DecodeReader->posCount++;
+                       if (DecodeReader->Coding == CODING_1_OUT_OF_4) {
+                               if (DecodeReader->posCount == 7*16) { // 7 bits jammed
+                                       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNOOP_AMPLITUDE); // stop jamming
+                                       // FpgaDisableTracing();
+                                       LED_D_OFF();
+                               } else if (DecodeReader->posCount == 8*16) {
+                                       DecodeReader->posCount = 0;
+                                       DecodeReader->output[DecodeReader->byteCount++] = 0x00;
+                                       DecodeReader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_4;
+                               }
+                       } else {
+                               if (DecodeReader->posCount == 7*256) { // 7 bits jammend
+                                       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER | FPGA_HF_READER_MODE_SNOOP_AMPLITUDE); // stop jamming
+                                       LED_D_OFF();
+                               } else if (DecodeReader->posCount == 8*256) {
+                                       DecodeReader->posCount = 0;
+                                       DecodeReader->output[DecodeReader->byteCount++] = 0x00;
+                                       DecodeReader->state = STATE_READER_RECEIVE_DATA_1_OUT_OF_256;
+                               }
+                       }
+                       break;
+
                default:
                        LED_B_OFF();
                        DecodeReaderReset(DecodeReader);
@@ -993,7 +1043,7 @@ int GetIso15693CommandFromReader(uint8_t *received, size_t max_len, uint32_t *eo
 
        // the decoder data structure
        DecodeReader_t DecodeReader = {0};
-       DecodeReaderInit(&DecodeReader, received, max_len);
+       DecodeReaderInit(&DecodeReader, received, max_len, 0, NULL);
 
        // wait for last transfer to complete
        while (!(AT91C_BASE_SSC->SSC_SR & AT91C_SSC_TXEMPTY));
@@ -1068,16 +1118,12 @@ int GetIso15693CommandFromReader(uint8_t *received, size_t max_len, uint32_t *eo
 }
 
 
-// Encode (into the ToSend buffers) an identify request, which is the first
+// Construct an identify (Inventory) request, which is the first
 // thing that you must send to a tag to get a response.
-static void BuildIdentifyRequest(void)
-{
-       uint8_t cmd[5];
-
+static void BuildIdentifyRequest(uint8_t *cmd) {
        uint16_t crc;
        // one sub-carrier, inventory, 1 slot, fast rate
-       // AFI is at bit 5 (1<<4) when doing an INVENTORY
-       cmd[0] = (1 << 2) | (1 << 5) | (1 << 1);
+       cmd[0] = ISO15693_REQ_INVENTORY | ISO15693_REQINV_SLOT1 | ISO15693_REQ_DATARATE_HIGH;
        // inventory command code
        cmd[1] = 0x01;
        // no mask
@@ -1086,8 +1132,6 @@ static void BuildIdentifyRequest(void)
        crc = Iso15693Crc(cmd, 3);
        cmd[3] = crc & 0xff;
        cmd[4] = crc >> 8;
-
-       CodeIso15693AsReader(cmd, sizeof(cmd));
 }
 
 
@@ -1096,8 +1140,7 @@ static void BuildIdentifyRequest(void)
 // for the response. The response is not demodulated, just left in the buffer
 // so that it can be downloaded to a PC and processed there.
 //-----------------------------------------------------------------------------
-void AcquireRawAdcSamplesIso15693(void)
-{
+void AcquireRawAdcSamplesIso15693(void) {
        LED_A_ON();
 
        uint8_t *dest = BigBuf_get_addr();
@@ -1108,7 +1151,9 @@ void AcquireRawAdcSamplesIso15693(void)
        FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
        SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
 
-       BuildIdentifyRequest();
+       uint8_t cmd[5];
+       BuildIdentifyRequest(cmd);
+       CodeIso15693AsReader(cmd, sizeof(cmd));
 
        // Give the tags time to energize
        SpinDelay(100);
@@ -1134,10 +1179,10 @@ void AcquireRawAdcSamplesIso15693(void)
 }
 
 
-void SnoopIso15693(void) {
+void SnoopIso15693(uint8_t jam_search_len, uint8_t *jam_search_string) {
 
        LED_A_ON();
-       
+
        FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
 
        clear_trace();
@@ -1154,9 +1199,9 @@ void SnoopIso15693(void) {
        uint8_t response[ISO15693_MAX_RESPONSE_LENGTH];
        DecodeTagInit(&DecodeTag, response, sizeof(response));
 
-       DecodeReader_t DecodeReader = {0};;
+       DecodeReader_t DecodeReader = {0};
        uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH];
-       DecodeReaderInit(&DecodeReader, cmd, sizeof(cmd));
+       DecodeReaderInit(&DecodeReader, cmd, sizeof(cmd), jam_search_len, jam_search_string);
 
        // Print some debug information about the buffer sizes
        if (DEBUG) {
@@ -1174,17 +1219,22 @@ void SnoopIso15693(void) {
        FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
        StartCountSspClk();
        FpgaSetupSscDma((uint8_t*) dmaBuf, ISO15693_DMA_BUFFER_SIZE);
-       
+
        bool TagIsActive = false;
        bool ReaderIsActive = false;
        bool ExpectTagAnswer = false;
        uint32_t dma_start_time = 0;
        uint16_t *upTo = dmaBuf;
+
+       uint16_t max_behindBy = 0;
        
        // And now we loop, receiving samples.
        for(;;) {
                uint16_t behindBy = ((uint16_t*)AT91C_BASE_PDC_SSC->PDC_RPR - upTo) & (ISO15693_DMA_BUFFER_SIZE-1);
-
+               if (behindBy > max_behindBy) {
+                       max_behindBy = behindBy;
+               }
+               
                if (behindBy == 0) continue;
 
                samples++;
@@ -1192,12 +1242,13 @@ void SnoopIso15693(void) {
                        // DMA has transferred the very first data
                        dma_start_time = GetCountSspClk() & 0xfffffff0;
                }
-               
+
                uint16_t snoopdata = *upTo++;
 
                if (upTo >= dmaBuf + ISO15693_DMA_BUFFER_SIZE) {                   // we have read all of the DMA buffer content.
                        upTo = dmaBuf;                                                 // start reading the circular buffer from the beginning
                        if (behindBy > (9*ISO15693_DMA_BUFFER_SIZE/10)) {
+                               // FpgaDisableTracing();
                                Dbprintf("About to blow circular buffer - aborted! behindBy=%d, samples=%d", behindBy, samples);
                                break;
                        }
@@ -1212,7 +1263,7 @@ void SnoopIso15693(void) {
                        }
                }
 
-               if (!TagIsActive) {                                            // no need to try decoding reader data if the tag is sending
+               if (!TagIsActive) {                                                // no need to try decoding reader data if the tag is sending
                        if (Handle15693SampleFromReader(snoopdata & 0x02, &DecodeReader)) {
                                // FpgaDisableSscDma();
                                uint32_t eof_time = dma_start_time + samples*16 + 8 - DELAY_READER_TO_ARM_SNOOP; // end of EOF
@@ -1290,33 +1341,37 @@ void SnoopIso15693(void) {
 
        FpgaDisableSscDma();
 
-       LEDsoff();
-
        DbpString("Snoop statistics:");
-       Dbprintf("  ExpectTagAnswer: %d", ExpectTagAnswer);
+       Dbprintf("  ExpectTagAnswer: %d, TagIsActive: %d, ReaderIsActive: %d", ExpectTagAnswer, TagIsActive, ReaderIsActive);
        Dbprintf("  DecodeTag State: %d", DecodeTag.state);
        Dbprintf("  DecodeTag byteCnt: %d", DecodeTag.len);
+       Dbprintf("  DecodeTag posCount: %d", DecodeTag.posCount);
        Dbprintf("  DecodeReader State: %d", DecodeReader.state);
        Dbprintf("  DecodeReader byteCnt: %d", DecodeReader.byteCount);
+       Dbprintf("  DecodeReader posCount: %d", DecodeReader.posCount);
        Dbprintf("  Trace length: %d", BigBuf_get_traceLen());
+       Dbprintf("  Max behindBy: %d", max_behindBy);
 }
 
 
 // Initialize the proxmark as iso15k reader
-void Iso15693InitReader() {
+void Iso15693InitReader(void) {
        FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
 
-       // Start from off (no field generated)
-       LED_D_OFF();
+       // switch field off and wait until tag resets
        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
+       LED_D_OFF();
        SpinDelay(10);
 
-       SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
+       // switch field on
+       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
+       LED_D_ON();
+       
+       // initialize SSC and select proper AD input
        FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
+       SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
 
-       // Give the tags time to energize
-       LED_D_ON();
-       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
+       // give tags some time to energize
        SpinDelay(250);
 }
 
@@ -1327,10 +1382,7 @@ void Iso15693InitReader() {
 
 
 // uid is in transmission order (which is reverse of display order)
-static void BuildReadBlockRequest(uint8_t *uid, uint8_t blockNumber )
-{
-       uint8_t cmd[13];
-
+static void BuildReadBlockRequest(uint8_t *uid, uint8_t blockNumber, uint8_t *cmd) {
        uint16_t crc;
        // If we set the Option_Flag in this request, the VICC will respond with the security status of the block
        // followed by the block data
@@ -1354,13 +1406,11 @@ static void BuildReadBlockRequest(uint8_t *uid, uint8_t blockNumber )
        cmd[11] = crc & 0xff;
        cmd[12] = crc >> 8;
 
-       CodeIso15693AsReader(cmd, sizeof(cmd));
 }
 
 
 // Now the VICC>VCD responses when we are simulating a tag
-static void BuildInventoryResponse(uint8_t *uid)
-{
+static void BuildInventoryResponse(uint8_t *uid) {
        uint8_t cmd[12];
 
        uint16_t crc;
@@ -1389,7 +1439,7 @@ static void BuildInventoryResponse(uint8_t *uid)
 //  speed ... 0 low speed, 1 hi speed
 //  *recv will contain the tag's answer
 //  return: length of received data, or -1 for timeout
-int 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) {
+int SendDataTag(uint8_t *send, int sendlen, bool init, bool speed_fast, uint8_t *recv, uint16_t max_recv_len, uint32_t start_time, uint16_t timeout, uint32_t *eof_time) {
 
        if (init) {
                Iso15693InitReader();
@@ -1398,19 +1448,40 @@ int SendDataTag(uint8_t *send, int sendlen, bool init, int speed, uint8_t *recv,
 
        int answerLen = 0;
 
-       if (!speed) {
-               // low speed (1 out of 256)
-               CodeIso15693AsReader256(send, sendlen);
-       } else {
+       if (speed_fast) {
                // high speed (1 out of 4)
                CodeIso15693AsReader(send, sendlen);
+       } else {
+               // low speed (1 out of 256)
+               CodeIso15693AsReader256(send, sendlen);
+       }
+
+       TransmitTo15693Tag(ToSend, ToSendMax, &start_time);
+       uint32_t end_time = start_time + 32*(8*ToSendMax-4); // substract the 4 padding bits after EOF
+       LogTrace_ISO15693(send, sendlen, start_time*4, end_time*4, NULL, true);
+
+       // Now wait for a response
+       if (recv != NULL) {
+               answerLen = GetIso15693AnswerFromTag(recv, max_recv_len, timeout, eof_time);
        }
 
+       return answerLen;
+}
+
+
+int SendDataTagEOF(uint8_t *recv, uint16_t max_recv_len, uint32_t start_time, uint16_t timeout, uint32_t *eof_time) {
+
+       int answerLen = 0;
+
+       CodeIso15693AsReaderEOF();
+
        TransmitTo15693Tag(ToSend, ToSendMax, &start_time);
+       uint32_t end_time = start_time + 32*(8*ToSendMax-4); // substract the 4 padding bits after EOF
+       LogTrace_ISO15693(NULL, 0, start_time*4, end_time*4, NULL, true);
 
        // Now wait for a response
        if (recv != NULL) {
-               answerLen = GetIso15693AnswerFromTag(recv, max_recv_len, ISO15693_READER_TIMEOUT, eof_time);
+               answerLen = GetIso15693AnswerFromTag(recv, max_recv_len, timeout, eof_time);
        }
 
        return answerLen;
@@ -1502,43 +1573,21 @@ void ReaderIso15693(uint32_t parameter) {
 
        set_tracing(true);
 
-       int answerLen = 0;
        uint8_t TagUID[8] = {0x00};
-
-       FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
-
        uint8_t answer[ISO15693_MAX_RESPONSE_LENGTH];
 
-       SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
-       // Setup SSC
-       FpgaSetupSsc(FPGA_MAJOR_MODE_HF_READER);
-
-       // Start from off (no field generated)
-       FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
-       SpinDelay(200);
-
-       // Give the tags time to energize
-       LED_D_ON();
-       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_READER);
-       SpinDelay(200);
-       StartCountSspClk();
-
-
        // FIRST WE RUN AN INVENTORY TO GET THE TAG UID
        // THIS MEANS WE CAN PRE-BUILD REQUESTS TO SAVE CPU TIME
 
        // Now send the IDENTIFY command
-       BuildIdentifyRequest();
+       uint8_t cmd[5];
+       BuildIdentifyRequest(cmd);
        uint32_t start_time = 0;
-       TransmitTo15693Tag(ToSend, ToSendMax, &start_time);
-
-       // Now wait for a response
        uint32_t eof_time;
-       answerLen = GetIso15693AnswerFromTag(answer, sizeof(answer), DELAY_ISO15693_VCD_TO_VICC_READER * 2, &eof_time) ;
+       int answerLen = SendDataTag(cmd, sizeof(cmd), true, true, answer, sizeof(answer), start_time, ISO15693_READER_TIMEOUT, &eof_time);
        start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
 
-       if (answerLen >=12) // we should do a better check than this
-       {
+       if (answerLen >= 12) { // we should do a better check than this
                TagUID[0] = answer[2];
                TagUID[1] = answer[3];
                TagUID[2] = answer[4];
@@ -1547,7 +1596,6 @@ void ReaderIso15693(uint32_t parameter) {
                TagUID[5] = answer[7];
                TagUID[6] = answer[8]; // IC Manufacturer code
                TagUID[7] = answer[9]; // always E0
-
        }
 
        Dbprintf("%d octets read from IDENTIFY request:", answerLen);
@@ -1560,21 +1608,12 @@ void ReaderIso15693(uint32_t parameter) {
                        TagUID[7],TagUID[6],TagUID[5],TagUID[4],
                        TagUID[3],TagUID[2],TagUID[1],TagUID[0]);
 
-
-       // Dbprintf("%d octets read from SELECT request:", answerLen2);
-       // DbdecodeIso15693Answer(answerLen2,answer2);
-       // Dbhexdump(answerLen2,answer2,true);
-
-       // Dbprintf("%d octets read from XXX request:", answerLen3);
-       // DbdecodeIso15693Answer(answerLen3,answer3);
-       // Dbhexdump(answerLen3,answer3,true);
-
        // read all pages
        if (answerLen >= 12 && DEBUG) {
                for (int i = 0; i < 32; i++) {  // sanity check, assume max 32 pages
-                       BuildReadBlockRequest(TagUID, i);
-                       TransmitTo15693Tag(ToSend, ToSendMax, &start_time);
-                       int answerLen = GetIso15693AnswerFromTag(answer, sizeof(answer), DELAY_ISO15693_VCD_TO_VICC_READER * 2, &eof_time);
+                       uint8_t cmd[13];
+                       BuildReadBlockRequest(TagUID, i, cmd);
+                       answerLen = SendDataTag(cmd, sizeof(cmd), false, true, answer, sizeof(answer), start_time, ISO15693_READER_TIMEOUT, &eof_time);
                        start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
                        if (answerLen > 0) {
                                Dbprintf("READ SINGLE BLOCK %d returned %d octets:", i, answerLen);
@@ -1585,7 +1624,7 @@ void ReaderIso15693(uint32_t parameter) {
                }
        }
 
-       // for the time being, switch field off to protect rdv4.0
+       // for the time being, switch field off to protect RDV4
        // note: this prevents using hf 15 cmd with s option - which isn't implemented yet anyway
        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
        LED_D_OFF();
@@ -1594,6 +1633,17 @@ void ReaderIso15693(uint32_t parameter) {
 }
 
 
+// Initialize the proxmark as iso15k tag
+void Iso15693InitTag(void) {
+       FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
+       SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
+       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
+       LED_D_OFF();
+       FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
+       StartCountSspClk();
+}
+
+
 // Simulate an ISO15693 TAG.
 // For Inventory command: print command and send Inventory Response with given UID
 // TODO: interpret other reader commands and send appropriate response
@@ -1601,20 +1651,14 @@ void SimTagIso15693(uint32_t parameter, uint8_t *uid) {
 
        LED_A_ON();
 
-       FpgaDownloadAndGo(FPGA_BITSTREAM_HF);
-       SetAdcMuxFor(GPIO_MUXSEL_HIPKD);
-       FpgaWriteConfWord(FPGA_MAJOR_MODE_HF_SIMULATOR | FPGA_HF_SIMULATOR_NO_MODULATION);
-       FpgaSetupSsc(FPGA_MAJOR_MODE_HF_SIMULATOR);
-
-       StartCountSspClk();
-
-       uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH];
+       Iso15693InitTag();
 
        // Build a suitable response to the reader INVENTORY command
        BuildInventoryResponse(uid);
 
        // Listen to reader
        while (!BUTTON_PRESS()) {
+               uint8_t cmd[ISO15693_MAX_COMMAND_LENGTH];
                uint32_t eof_time = 0, start_time = 0;
                int cmd_len = GetIso15693CommandFromReader(cmd, sizeof(cmd), &eof_time);
 
@@ -1636,8 +1680,7 @@ void SimTagIso15693(uint32_t parameter, uint8_t *uid) {
 
 // Since there is no standardized way of reading the AFI out of a tag, we will brute force it
 // (some manufactures offer a way to read the AFI, though)
-void BruteforceIso15693Afi(uint32_t speed)
-{
+void BruteforceIso15693Afi(uint32_t speed) {
        LED_A_ON();
 
        uint8_t data[6];
@@ -1653,7 +1696,7 @@ void BruteforceIso15693Afi(uint32_t speed)
        data[2] = 0; // mask length
        datalen = Iso15693AddCrc(data,3);
        uint32_t start_time = GetCountSspClk();
-       recvlen = SendDataTag(data, datalen, true, speed, recv, sizeof(recv), 0, &eof_time);
+       recvlen = SendDataTag(data, datalen, true, speed, recv, sizeof(recv), 0, ISO15693_READER_TIMEOUT, &eof_time);
        start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
        WDT_HIT();
        if (recvlen>=12) {
@@ -1670,7 +1713,7 @@ void BruteforceIso15693Afi(uint32_t speed)
        for (int i = 0; i < 256; i++) {
                data[2] = i & 0xFF;
                datalen = Iso15693AddCrc(data,4);
-               recvlen = SendDataTag(data, datalen, false, speed, recv, sizeof(recv), start_time, &eof_time);
+               recvlen = SendDataTag(data, datalen, false, speed, recv, sizeof(recv), start_time, ISO15693_READER_TIMEOUT, &eof_time);
                start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
                WDT_HIT();
                if (recvlen >= 12) {
@@ -1694,13 +1737,35 @@ void DirectTag15693Command(uint32_t datalen, uint32_t speed, uint32_t recv, uint
        uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
        uint32_t eof_time;
 
+       uint16_t timeout;
+    bool request_answer = false;
+       
+       switch (data[1]) {
+               case ISO15693_WRITEBLOCK:
+               case ISO15693_LOCKBLOCK:
+               case ISO15693_WRITE_MULTI_BLOCK:
+               case ISO15693_WRITE_AFI:
+               case ISO15693_LOCK_AFI:
+               case ISO15693_WRITE_DSFID:
+               case ISO15693_LOCK_DSFID:
+                       timeout = ISO15693_READER_TIMEOUT_WRITE;
+                       request_answer = data[0] & ISO15693_REQ_OPTION;
+                       break;
+               default:
+                       timeout = ISO15693_READER_TIMEOUT;
+       }               
+
        if (DEBUG) {
                Dbprintf("SEND:");
                Dbhexdump(datalen, data, false);
        }
 
-       recvlen = SendDataTag(data, datalen, true, speed, (recv?recvbuf:NULL), sizeof(recvbuf), 0, &eof_time);
+       recvlen = SendDataTag(data, datalen, true, speed, (recv?recvbuf:NULL), sizeof(recvbuf), 0, timeout, &eof_time);
 
+       if (request_answer) { // send a single EOF to get the tag response
+               recvlen = SendDataTagEOF((recv?recvbuf:NULL), sizeof(recvbuf), 0, ISO15693_READER_TIMEOUT, &eof_time);
+       }
+       
        // for the time being, switch field off to protect rdv4.0
        // note: this prevents using hf 15 cmd with s option - which isn't implemented yet anyway
        FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
@@ -1728,78 +1793,65 @@ void DirectTag15693Command(uint32_t datalen, uint32_t speed, uint32_t recv, uint
 //
 //-----------------------------------------------------------------------------
 
-// Set the UID to the tag (based on Iceman work).
+// Set the UID on Magic ISO15693 tag (based on Iceman's LUA-script).
 void SetTag15693Uid(uint8_t *uid) {
 
        LED_A_ON();
 
-       uint8_t cmd[4][9] = {0x00};
+       uint8_t cmd[4][9] = {
+               {ISO15693_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x3e, 0x00, 0x00, 0x00, 0x00},
+               {ISO15693_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x3f, 0x69, 0x96, 0x00, 0x00},
+               {ISO15693_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x38},
+               {ISO15693_REQ_DATARATE_HIGH, ISO15693_WRITEBLOCK, 0x39}
+       };
+
        uint16_t crc;
 
        int recvlen = 0;
        uint8_t recvbuf[ISO15693_MAX_RESPONSE_LENGTH];
        uint32_t eof_time;
 
-       // Command 1 : 02213E00000000
-       cmd[0][0] = 0x02;
-       cmd[0][1] = 0x21;
-       cmd[0][2] = 0x3e;
-       cmd[0][3] = 0x00;
-       cmd[0][4] = 0x00;
-       cmd[0][5] = 0x00;
-       cmd[0][6] = 0x00;
-
-       // Command 2 : 02213F69960000
-       cmd[1][0] = 0x02;
-       cmd[1][1] = 0x21;
-       cmd[1][2] = 0x3f;
-       cmd[1][3] = 0x69;
-       cmd[1][4] = 0x96;
-       cmd[1][5] = 0x00;
-       cmd[1][6] = 0x00;
-
        // Command 3 : 022138u8u7u6u5 (where uX = uid byte X)
-       cmd[2][0] = 0x02;
-       cmd[2][1] = 0x21;
-       cmd[2][2] = 0x38;
        cmd[2][3] = uid[7];
        cmd[2][4] = uid[6];
        cmd[2][5] = uid[5];
        cmd[2][6] = uid[4];
 
        // Command 4 : 022139u4u3u2u1 (where uX = uid byte X)
-       cmd[3][0] = 0x02;
-       cmd[3][1] = 0x21;
-       cmd[3][2] = 0x39;
        cmd[3][3] = uid[3];
        cmd[3][4] = uid[2];
        cmd[3][5] = uid[1];
        cmd[3][6] = uid[0];
 
+       uint32_t start_time = 0;
+       
        for (int i = 0; i < 4; i++) {
                // Add the CRC
                crc = Iso15693Crc(cmd[i], 7);
                cmd[i][7] = crc & 0xff;
                cmd[i][8] = crc >> 8;
 
+               recvlen = SendDataTag(cmd[i], sizeof(cmd[i]), i==0?true:false, true, recvbuf, sizeof(recvbuf), start_time, ISO15693_READER_TIMEOUT_WRITE, &eof_time);
+               start_time = eof_time + DELAY_ISO15693_VICC_TO_VCD_READER;
                if (DEBUG) {
                        Dbprintf("SEND:");
                        Dbhexdump(sizeof(cmd[i]), cmd[i], false);
-               }
-
-               recvlen = SendDataTag(cmd[i], sizeof(cmd[i]), true, 1, recvbuf, sizeof(recvbuf), 0, &eof_time);
-
-               if (DEBUG) {
                        Dbprintf("RECV:");
                        if (recvlen > 0) {
                                Dbhexdump(recvlen, recvbuf, false);
                                DbdecodeIso15693Answer(recvlen, recvbuf);
                        }
                }
-
-               cmd_send(CMD_ACK, recvlen>ISO15693_MAX_RESPONSE_LENGTH?ISO15693_MAX_RESPONSE_LENGTH:recvlen, 0, 0, recvbuf, ISO15693_MAX_RESPONSE_LENGTH);
+               // Note: need to know if we expect an answer from one of the magic commands
+               // if (recvlen < 0) {
+                       // break;
+               // }
        }
 
+       FpgaWriteConfWord(FPGA_MAJOR_MODE_OFF);
+       LED_D_OFF();
+
+       cmd_send(CMD_ACK, recvlen, 0, 0, recvbuf, recvlen);
        LED_A_OFF();
 }
 
Impressum, Datenschutz