Merge branch 'new_iso_init' (sniffer not working)

Conflicts:
	firmware/src_simtrace/phone.c
	firmware/src_simtrace/simtrace.h
diff --git a/firmware/Makefile b/firmware/Makefile
index addbaf0..4380703 100644
--- a/firmware/Makefile
+++ b/firmware/Makefile
@@ -52,6 +52,8 @@
 #FIXME: Remove this variable
 NOAUTOCALLBACK=no
 
+DEBUG_PHONE_SNIFF=0
+
 #CFLAGS+=-DUSB_NO_DEBUG=1
 
 # Optimization level, put in comment for debugging
@@ -117,7 +119,7 @@
 #CFLAGS += -save-temps -fverbose-asm
 #CFLAGS += -Wa,-a,-ad
 CFLAGS += --param max-inline-insns-single=500 -mcpu=cortex-m3 -mthumb # -mfix-cortex-m3-ldrd
-CFLAGS += -ffunction-sections -g $(OPTIMIZATION) $(INCLUDES) -D$(CHIP) -DTRACE_LEVEL=$(TRACE_LEVEL)
+CFLAGS += -ffunction-sections -g $(OPTIMIZATION) $(INCLUDES) -D$(CHIP) -DTRACE_LEVEL=$(TRACE_LEVEL) -DDEBUG_PHONE_SNIFF=$(DEBUG_PHONE_SNIFF)
 ASFLAGS = -mcpu=cortex-m3 -mthumb -Wall -g $(OPTIMIZATION) $(INCLUDES) -D$(CHIP) -D__ASSEMBLY__
 LDFLAGS = -mcpu=cortex-m3 -mthumb -Wl,--cref -Wl,--check-sections -Wl,--gc-sections -Wl,--entry=ResetException -Wl,--unresolved-symbols=report-all -Wl,--warn-common -Wl,--warn-section-align -Wl,--warn-unresolved-symbols $(LIB)
 #LD_OPTIONAL=-Wl,--print-gc-sections -Wl,--stats
@@ -136,7 +138,7 @@
 C_LOWLEVEL = board_cstartup_gnu.o board_lowlevel.o syscalls.o exceptions.o
 C_LIBLEVEL = spi.o pio.o pmc.o usart.o pio_it.o pio_capture.o uart_console.o iso7816_4.o wdt.o led.o tc.o
 C_CCID = cciddriver.o USBD.o USBDDriver.o USBD_HAL.o USBRequests.o USBDCallbacks.o USBDescriptors.o USBDDriverCallbacks.o
-C_SIMTRACE = simtrace_iso7816.o usb.o ccid.o sniffer.o phone.o tc_etu.o mitm.o
+C_SIMTRACE = simtrace_iso7816.o usb.o ccid.o sniffer.o phone.o mitm.o ringbuffer.o host_communication.o #tc_etu.o
 C_APPLEVEL = main.o
 C_OBJECTS  = $(C_CMSIS) $(C_LOWLEVEL) $(C_LIBLEVEL) $(C_APPLEVEL) $(C_CCID) $(C_SIMTRACE)
 
diff --git a/firmware/include_board/board.h b/firmware/include_board/board.h
index 80d0d75..d8fffd8 100644
--- a/firmware/include_board/board.h
+++ b/firmware/include_board/board.h
@@ -136,9 +136,10 @@
 //#define PINS_ISO7816            PIN_USART1_TXD, PIN_USART1_SCK, PIN_ISO7816_RSTMC
 #define PINS_ISO7816        PIN_SIM_IO,  PIN_SIM_CLK,  PIN_ISO7816_RSTMC // SIM_PWEN_PIN, PIN_SIM_IO2, PIN_SIM_CLK2
 
+#define PINS_TC             PIN_SIM_IO_INPUT, PIN_SIM_CLK_INPUT
 
 #define VCC_PHONE                   {PIO_PA25, PIOA, ID_PIOA, PIO_INPUT, PIO_DEFAULT}
-#define PIN_ISO7816_RST_PHONE       {PIO_PA24, PIOA, ID_PIOA, PIO_INPUT, PIO_IT_RISE_EDGE }
+#define PIN_ISO7816_RST_PHONE       {PIO_PA24, PIOA, ID_PIOA, PIO_INPUT, PIO_IT_RISE_EDGE | PIO_DEGLITCH }
 #define PIN_PHONE_IO_INPUT          {PIO_PA21, PIOA, ID_PIOA, PIO_INPUT, PIO_DEFAULT}
 #define PIN_PHONE_IO                {PIO_PA22, PIOA, ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}
 #define PIN_PHONE_CLK               {PIO_PA23A_SCK1, PIOA, ID_PIOA, PIO_PERIPH_A, PIO_DEFAULT}     // External Clock Input on PA28
diff --git a/firmware/src_simtrace/host_communication.c b/firmware/src_simtrace/host_communication.c
new file mode 100644
index 0000000..c0e0373
--- /dev/null
+++ b/firmware/src_simtrace/host_communication.c
@@ -0,0 +1,42 @@
+#include "board.h"
+
+static volatile bool write_to_host_in_progress = false;
+
+void USB_write_callback(uint8_t *pArg, uint8_t status, uint32_t transferred, uint32_t remaining)
+{
+    if (status != USBD_STATUS_SUCCESS) {
+        TRACE_ERROR("USB err status: %d (%s)\n", __FUNCTION__, status);
+    }
+    write_to_host_in_progress = false;
+    printf("WR_CB\n");
+}
+
+int send_to_host()
+{
+    static uint8_t msg[RING_BUFLEN];
+    int ret = 0;
+    unsigned int i;
+
+    for(i = 0; !rbuf_is_empty(&sim_rcv_buf) && i < sizeof(msg); i++) {
+        msg[i] = rbuf_read(&sim_rcv_buf);
+    }
+    printf("Wr %d\n", i);
+    write_to_host_in_progress = true;
+    ret = USBD_Write( PHONE_DATAIN, msg, i, (TransferCallback)&USB_write_callback, 0 );
+    if (ret != USBD_STATUS_SUCCESS) {
+        TRACE_ERROR("Error sending to host (%x)\n", ret);
+        write_to_host_in_progress = false;
+    }
+    return ret;
+}
+
+int check_data_from_phone()
+{
+    int ret = 0;
+
+    if((rbuf_is_empty(&sim_rcv_buf) || write_to_host_in_progress == true)) {
+        return ret;
+    }
+    ret = send_to_host();
+    return ret;
+}
diff --git a/firmware/src_simtrace/phone.c b/firmware/src_simtrace/phone.c
index 7c1adeb..861129c 100644
--- a/firmware/src_simtrace/phone.c
+++ b/firmware/src_simtrace/phone.c
@@ -73,6 +73,7 @@
 bulk-in endpoint. On failure to do so, some of the wait time extension responses, will not be queued to
 the driver. 
 */
+extern volatile uint8_t timeout_occured;
 
 /*------------------------------------------------------------------------------
  *         Internal variables
@@ -83,9 +84,14 @@
 /** ISO7816 pins */
 static const Pin pinsISO7816_PHONE[]    = {PINS_ISO7816_PHONE};
 /** Bus switch pins */
+
+#if DEBUG_PHONE_SNIFF
+# warning "Debug phone sniff via logic analyzer is enabled"
+// Logic analyzer probes are easier to attach to the SIM card slot
+static const Pin pins_bus[]    = {PINS_BUS_SNIFF};
+#else
 static const Pin pins_bus[]    = {PINS_BUS_DEFAULT};
-// FIXME: temporary enable bus switch 
-//static const Pin pins_bus[]    = {PINS_BUS_SNIFF};
+#endif
 
 /** ISO7816 RST pin */
 static const Pin pinIso7816RstMC  = PIN_ISO7816_RST_PHONE;
@@ -99,6 +105,7 @@
     {VCC_FWD, PIOA, ID_PIOA, PIO_OUTPUT_1, PIO_DEFAULT}
 };
 
+
 static const Pin pinPhoneRST = PIN_ISO7816_RST_PHONE;
 
 static struct Usart_info usart_info = {.base = USART_PHONE, .id = ID_USART_PHONE};
@@ -112,30 +119,22 @@
 #define USART_SEND 0
 #define USART_RCV  1
 
-enum states{
-    WAIT_FOR_RST            = 9,
-    RST_RCVD        = 10,
-    WAIT_CMD_PHONE  = 11,
-    WAIT_CMD_PC     = 12,
-    WAIT_ATR        = 13,
-};
-
+// FIXME: Comments
 /*-----------------------------------------------------------------------------
  *          Internal variables
  *-----------------------------------------------------------------------------*/
 /** Variable for state of send and receive froom USART */
 static uint8_t StateUsartGlobal = USART_RCV;
 
-static enum states state;
-
-extern volatile uint8_t timeout_occured;
+static uint8_t host_to_sim_buf[BUFLEN];
 
 /*-----------------------------------------------------------------------------
  *          Interrupt routines
  *-----------------------------------------------------------------------------*/
-#define     RESET   'R'
 static void ISR_PhoneRST( const Pin *pPin)
 {
+    int ret;
+    // FIXME: no printfs in ISRs?
     printf("+++ Int!! %x\n\r", pinPhoneRST.pio->PIO_ISR);
     if ( ((pinPhoneRST.pio->PIO_ISR & pinPhoneRST.mask) != 0)  )
     {
@@ -145,10 +144,41 @@
             printf(" 1 ");
         }
     }
-    state = RST_RCVD;
+
+    if ((ret = USBD_Write( PHONE_INT, "R", 1, 0, 0 )) != USBD_STATUS_SUCCESS) {
+        TRACE_ERROR("USB err status: %d (%s)\n", ret, __FUNCTION__);
+        return;
+    }
 
     /* Interrupt enabled after ATR is sent to phone */
-    PIO_DisableIt( &pinPhoneRST ) ;
+   // PIO_DisableIt( &pinPhoneRST ) ;
+}
+
+void receive_from_host( void );
+void sendResponse_to_phone( uint8_t *pArg, uint8_t status, uint32_t transferred, uint32_t remaining)
+{
+    if (status != USBD_STATUS_SUCCESS) {
+        TRACE_ERROR("USB err status: %d (%s)\n", __FUNCTION__, status);
+        return;
+    }
+    PR("sendResp, stat: %X, trnsf: %x, rem: %x\n\r", status, transferred, remaining);
+    PR("Resp: %x %x %x .. %x\n", host_to_sim_buf[0], host_to_sim_buf[1], host_to_sim_buf[2], host_to_sim_buf[transferred-1]);
+
+    for (uint32_t i = 0; i < transferred; i++ ) {
+        ISO7816_SendChar(host_to_sim_buf[i], &usart_info);
+    }
+
+    receive_from_host();
+}
+
+void receive_from_host()
+{
+    int ret;
+    if ((ret = USBD_Read(PHONE_DATAOUT, &host_to_sim_buf, sizeof(host_to_sim_buf),
+                (TransferCallback)&sendResponse_to_phone, 0)) == USBD_STATUS_SUCCESS) {
+    } else {
+        TRACE_ERROR("USB Err: %X\n", ret);
+    }
 }
 
 void Phone_configure( void ) {
@@ -158,7 +188,7 @@
 
 void Phone_exit( void ) {
     PIO_DisableIt( &pinPhoneRST ) ;
-    USART_DisableIt( USART_PHONE, US_IER_RXRDY);
+    USART_DisableIt( USART_PHONE, US_IER_RXRDY) ;
     USART_SetTransmitterEnabled(USART_PHONE, 0);
     USART_SetReceiverEnabled(USART_PHONE, 0);
 }
@@ -178,93 +208,16 @@
     /*  Configure ISO7816 driver */
     // FIXME:    PIO_Configure(pPwr, PIO_LISTSIZE( pPwr ));
 
-    state = WAIT_FOR_RST;
-
-
 // FIXME: Or do I need to call VBUS_CONFIGURE() here instead, which will call USBD_Connect() later?
 //    USBD_Connect();
 
     USART_EnableIt( USART_PHONE, US_IER_RXRDY) ;
 
-    Timer_Init();
+    //Timer_Init();
+
+    receive_from_host();
 }
 
-void send_ATR(uint8_t *ATR, uint8_t status, uint32_t transferred, uint32_t remaining)
-{
-    uint32_t i;
-
-    if (status != USBD_STATUS_SUCCESS) {
-        TRACE_ERROR("USB err status: %d (%s)", __FUNCTION__, status);
-        return;
-    }
-    PR("Send %x %x .. %x (tr: %d, st: %x)", ATR[0], ATR[1], ATR[transferred-1], transferred, status);
-    for ( i = 0; i < transferred; i++ ) {
-        ISO7816_SendChar(*(ATR++), &usart_info);
-    }
-    state = WAIT_CMD_PHONE;
-    PIO_EnableIt( &pinPhoneRST ) ;
-}
-
-void sendResponse( uint8_t *pArg, uint8_t status, uint32_t transferred, uint32_t remaining)
-{
-    uint32_t i;
-
-    if (status != USBD_STATUS_SUCCESS) {
-        TRACE_ERROR("USB err status: %d (%s)", __FUNCTION__, status);
-        return;
-    }
-    PR("sendResp, stat: %X, trnsf: %x, rem: %x\n\r", status, transferred, remaining);
-    PR("Resp: %x %x %x .. %x", pArg[0], pArg[1], pArg[2], pArg[transferred-1]);
-
-    for ( i = 0; i < transferred; i++ ) {
-        ISO7816_SendChar(*(pArg++), &usart_info);
-    }
-    state = WAIT_CMD_PHONE;
-}
-
-#define     MAX_MSG_LEN     64
-
-void wait_for_response(uint8_t pBuffer[]) {
-    int ret = 0;
-    if (rcvdChar != 0) {
-        printf(" rr ");
-
-        /*  DATA_IN for host side is data_out for simtrace side   */
-        ret = USBD_Write( PHONE_DATAIN, (void *)buf.buf, BUFLEN, 0, 0 );
-        if (ret != USBD_STATUS_SUCCESS) {
-            TRACE_ERROR("USB err status: %d (%s)", __FUNCTION__, ret);
-            return;
-        }
-        PR("b:%x %x %x %x %x.\n\r", buf.buf[0], buf.buf[1],buf.buf[2], buf.buf[3], buf.buf[4]);
-
-        rcvdChar = 0;
-    } else if (timeout_occured && buf.idx != 0) {
-        printf(" to ");
-
-        ret = USBD_Write( PHONE_DATAIN, (void *) buf.buf, buf.idx, 0, 0 );
-        if (ret != USBD_STATUS_SUCCESS) {
-            TRACE_ERROR("USB err status: %d (%s)", __FUNCTION__, ret);
-            return;
-        }
-
-        timeout_occured = 0;
-        buf.idx = 0;
-        rcvdChar = 0;
-        PR("b:%x %x %x %x %x.\n\r", buf.buf[0], buf.buf[1],buf.buf[2], buf.buf[3], buf.buf[4]);
-    } else {
-        return;
-    }
-    if ((ret = USBD_Read(PHONE_DATAOUT, pBuffer, MAX_MSG_LEN,
-                (TransferCallback)&sendResponse, pBuffer)) == USBD_STATUS_SUCCESS) {
-        PR("wait_rsp\n\r");
-//        state = WAIT_CMD_PC;
-        buf.idx = 0;
-        TC0_Counter_Reset();
-    } else {
-        PR("USB Err: %X", ret);
-        return;
-    }
-}
 
 // Sniffed Phone to SIM card communication:
 // phone > sim : RST
@@ -281,38 +234,5 @@
 
 void Phone_run( void )
 {
-    int ret;
-    uint8_t pBuffer[MAX_MSG_LEN];
-    int msg = RESET;
-// FIXME: remove:
-//    uint8_t ATR[] = {0x3B, 0x9A, 0x94, 0x00, 0x92, 0x02, 0x75, 0x93, 0x11, 0x00, 0x01, 0x02, 0x02, 0x19}; 
-//    send_ATR(ATR, (sizeof(ATR)/sizeof(ATR[0])));
-    switch (state) {
-        case RST_RCVD:
-            if ((ret = USBD_Write( PHONE_INT, &msg, 1, 0, 0 )) != USBD_STATUS_SUCCESS) {
-                TRACE_ERROR("USB err status: %d (%s)", __FUNCTION__, ret);
-                return;
-            }
-            //buf.idx = 0;
-            //rcvdChar = 0;
-//            TC0_Counter_Reset();
-            // send_ATR sets state to WAIT_CMD
-            if ((ret = USBD_Read(PHONE_DATAOUT, pBuffer, MAX_MSG_LEN, (TransferCallback)&send_ATR, pBuffer)) == USBD_STATUS_SUCCESS) {
-                PR("Reading started sucessfully (ATR)");
-                state = WAIT_ATR;
-            } else {
-                TRACE_ERROR("USB err status: %d (%s)", __FUNCTION__, ret);
-                return;
-            }
-            break;
-        case WAIT_CMD_PHONE:
-// FIXME:            TC0_Counter_Reset();
-            wait_for_response(pBuffer);
-            break;
-        case WAIT_FOR_RST:
-            break;
-        default:
-//            PR(":(");
-            break;
-    }
+    check_data_from_phone();
 }
diff --git a/firmware/src_simtrace/ringbuffer.c b/firmware/src_simtrace/ringbuffer.c
new file mode 100644
index 0000000..f6e9985
--- /dev/null
+++ b/firmware/src_simtrace/ringbuffer.c
@@ -0,0 +1,35 @@
+#include "ringbuffer.h"
+#include "trace.h"
+
+void rbuf_reset(volatile ringbuf *rb)
+{
+    rb->ird = 0;
+    rb->iwr = 0;
+}
+
+uint8_t rbuf_read(volatile ringbuf *rb)
+{
+    uint8_t val = rb->buf[rb->ird];
+    rb->ird = (rb->ird + 1)%RING_BUFLEN;
+    return val;
+}
+
+void rbuf_write(volatile volatile ringbuf *rb, uint8_t item)
+{
+    if(!rbuf_is_full(rb)) {
+        rb->buf[rb->iwr] = item;
+        rb->iwr = (rb->iwr + 1)%RING_BUFLEN;
+    } else {
+        TRACE_ERROR("Ringbuffer full, losing bytes!");
+    }
+}
+
+bool rbuf_is_empty(volatile ringbuf *rb)
+{
+    return rb->ird == rb->iwr;
+}
+
+bool rbuf_is_full(volatile ringbuf *rb)
+{
+    return rb->ird == (rb->iwr+1)%RING_BUFLEN;
+}
diff --git a/firmware/src_simtrace/ringbuffer.h b/firmware/src_simtrace/ringbuffer.h
new file mode 100644
index 0000000..771c73f
--- /dev/null
+++ b/firmware/src_simtrace/ringbuffer.h
@@ -0,0 +1,22 @@
+#ifndef SIMTRACE_RINGBUF_H
+#define SIMTRACE_RINGBUF_H
+
+#include <stdint.h>
+#include <stdbool.h>
+#include <sys/types.h>
+
+#define RING_BUFLEN 1024
+
+typedef struct ringbuf {
+    uint8_t buf[RING_BUFLEN];
+    size_t ird;
+    size_t iwr;
+} ringbuf;
+
+void rbuf_reset(volatile ringbuf *rb);
+uint8_t rbuf_read(volatile ringbuf *rb);
+void rbuf_write(volatile ringbuf *rb, uint8_t item);
+bool rbuf_is_empty(volatile ringbuf *rb);
+bool rbuf_is_full(volatile ringbuf *rb);
+
+#endif /* end of include guard: SIMTRACE_RINGBUF_H */
diff --git a/firmware/src_simtrace/simtrace.h b/firmware/src_simtrace/simtrace.h
index bc2dbe0..32c9fc3 100644
--- a/firmware/src_simtrace/simtrace.h
+++ b/firmware/src_simtrace/simtrace.h
@@ -1,12 +1,14 @@
 #ifndef SIMTRACE_H
 #define SIMTRACE_H
 
+#include "ringbuffer.h"
+
 /* Endpoint numbers */
 #define DATAOUT     1
 #define DATAIN      2
 #define INT         3
 
-#define BUFLEN  5
+#define BUFLEN  64
 
 #define PHONE_DATAOUT     4
 #define PHONE_DATAIN      5
@@ -15,13 +17,7 @@
 #define CLK_MASTER      1
 #define CLK_SLAVE       0
 
-typedef struct ring_buffer
-{
-    uint8_t     buf[BUFLEN*2];   // data buffer
-    uint8_t     idx;                // number of items in the buffer
-} ring_buffer;
-
-extern volatile ring_buffer buf;
+extern volatile ringbuf sim_rcv_buf;
 
 extern volatile bool rcvdChar;
 extern volatile uint32_t char_stat;
@@ -52,7 +48,8 @@
 
 extern const USBConfigurationDescriptor *configurationDescriptorsArr[];
 
-/**  Helper functions    **/
+int check_data_from_phone();
+
 /*  Configure functions   */
 extern void Sniffer_configure( void );
 extern void CCID_configure( void );
diff --git a/firmware/src_simtrace/simtrace_iso7816.c b/firmware/src_simtrace/simtrace_iso7816.c
index bddceed..b0f3e79 100644
--- a/firmware/src_simtrace/simtrace_iso7816.c
+++ b/firmware/src_simtrace/simtrace_iso7816.c
@@ -36,27 +36,12 @@
 #include <string.h>
 
 volatile uint32_t char_stat;
-volatile bool rcvdChar = 0;
 
-//#define BUFLEN  14
 // FIXME: Remove:
 #define PR TRACE_INFO
 //#define PR printf 
 
-/*typedef struct ring_buffer
-{
-    uint8_t     buf[BUFLEN*2];   // data buffer
-    uint8_t     idx;                // number of items in the buffer
-} ring_buffer;
-*/
-volatile ring_buffer buf = { {0}, 0 };
-
-void buf_push(uint8_t item)
-{
-    buf.buf[buf.idx % (BUFLEN*2)] = item;
-    PR("Psh: %x %x\n\r", buf.idx, buf.buf[buf.idx]);
-    buf.idx = (buf.idx+1) % (BUFLEN*2);
-}
+volatile ringbuf sim_rcv_buf = { {0}, 0, 0 };
 
 /** Initializes a ISO driver
  */ 
@@ -102,50 +87,40 @@
 //    USART_PHONE->US_IER = US_IER_RXRDY | US_IER_OVRE | US_IER_FRAME | US_IER_PARE | US_IER_NACK | US_IER_ITER;
 }
 
-/* 
- *  Initializes rcvdChar with the char received on USART interface                            
- *  char_stat is zero if no error occured. 
- *  Otherwise it is filled with the content of the status register.                           
+/*
+ *  char_stat is zero if no error occured.
+ *  Otherwise it is filled with the content of the status register.
  */
-void USART1_IrqHandler( void )                                                                
-{   
-    uint32_t stat;                                                                            
+void USART1_IrqHandler( void )
+{
+    uint32_t stat;
     char_stat = 0;
     // Rcv buf full
-/*    if((stat & US_CSR_RXBUFF) == US_CSR_RXBUFF) {                                           
+/*    if((stat & US_CSR_RXBUFF) == US_CSR_RXBUFF) {
         TRACE_DEBUG("Rcv buf full");
-        USART_DisableIt(USART1, US_IDR_RXBUFF);                                               
-    }                                                                                         
-*/  
-    uint32_t csr = USART_PHONE->US_CSR;                                                       
-    
-//    PR("---- stat: %x\n\r", csr);
+        USART_DisableIt(USART1, US_IDR_RXBUFF);
+    }
+*/
+    uint32_t csr = USART_PHONE->US_CSR;
 
     if (csr & US_CSR_TXRDY) {
-        /* transmit buffer empty, nothing to transmit */                                      
-    }  
+        /* transmit buffer empty, nothing to transmit */
+    }
     if (csr & US_CSR_RXRDY) {
         stat = (csr&(US_CSR_OVRE|US_CSR_FRAME|
                         US_CSR_PARE|US_CSR_TIMEOUT|US_CSR_NACK|
                         (1<<10)));
-        int c = (USART_PHONE->US_RHR) & 0xFF;
+        uint8_t c = (USART_PHONE->US_RHR) & 0xFF;
 //        printf(" %x", c);
 
         if (stat == 0 ) {
             /* Fill char into buffer */
-            buf_push((USART_PHONE->US_RHR) & 0xFF);
+            rbuf_write(&sim_rcv_buf, c);
         } else {
-//            buf_push((USART_PHONE->US_RHR) & 0xFF);
-            PR("e");
-            PR("%x\n\r", (USART_PHONE->US_RHR) & 0xFF);
-            PR("st: %x ", stat);
+            rbuf_write(&sim_rcv_buf, c);
+            PR("e %x st: %x\n", c, stat);
         } /* else: error occured */
 
-        if ((buf.idx % BUFLEN) == BUFLEN-1) {
-            rcvdChar = 1;
-            printf("r. ");
-        }
-
         char_stat = stat;
     }
 }
diff --git a/firmware/src_simtrace/sniffer.c b/firmware/src_simtrace/sniffer.c
index a352a15..cce427c 100644
--- a/firmware/src_simtrace/sniffer.c
+++ b/firmware/src_simtrace/sniffer.c
@@ -60,40 +60,36 @@
     {VCC_FWD, PIOA, ID_PIOA, PIO_OUTPUT_1, PIO_DEFAULT}
 };
 
-static struct Usart_info usart_info = {.base = USART_SIM, .id = ID_USART_SIM};
+static struct Usart_info usart_info = {.base = USART_PHONE, .id = ID_USART_PHONE};
 
 /*-----------------------------------------------------------------------------
  *          Initialization routine
  *-----------------------------------------------------------------------------*/
 
 void Sniffer_configure( void ){
+    TRACE_INFO("Sniffer config\n");
 }
 
 void Sniffer_exit( void ){
+    TRACE_INFO("Sniffer exit\n");
     USART_SetReceiverEnabled(USART_PHONE, 0);
 }
 
 void Sniffer_init( void )
 {
+    TRACE_INFO("Sniffer Init\n");
     /*  Configure ISO7816 driver */
     PIO_Configure( pinsISO7816_sniff, PIO_LISTSIZE( pinsISO7816_sniff ) ) ;
     PIO_Configure( pins_bus, PIO_LISTSIZE( pins_bus) ) ;
 
     PIO_Configure(pPwr, PIO_LISTSIZE( pPwr ));
 
-    ISO7816_Init(&usart_info, CLK_MASTER);
+    ISO7816_Init(&usart_info, CLK_SLAVE);
 
     USART_SetReceiverEnabled(USART_PHONE, 1);
 }
 
 void Sniffer_run( void )
 {
-    if (rcvdChar != 0) {
-        /*  DATA_IN for host side is data_out for simtrace side   */
-        /* FIXME: Performancewise sending a USB packet for every byte is a disaster */
-        PR("----- %x %x %x ..\n\r", buf.buf[0], buf.buf[1],buf.buf[2] );
-        USBD_Write( DATAIN, (void *) buf.buf, BUFLEN, 0, 0 );
-        PR("----- Rcvd char\n\r");
-        rcvdChar = 0;
-    }
+    check_data_from_phone();
 }
diff --git a/firmware/src_simtrace/tc_etu.c b/firmware/src_simtrace/tc_etu.c
index dd359af..2e000e3 100644
--- a/firmware/src_simtrace/tc_etu.c
+++ b/firmware/src_simtrace/tc_etu.c
@@ -24,8 +24,7 @@
 
 #include <string.h>
 
-//FIXME:
-static const Pin pTC[] = {{PIO_PA4B_TCLK0, PIO_PA0B_TIOA0, PIO_PA1B_TIOB0}};
+static const Pin pTC[] = {PINS_TC};
 
 /** Global timestamp in milliseconds since start of application */
 volatile uint32_t dwTimeStamp = 0;
@@ -41,7 +40,6 @@
 void SysTick_Handler( void )
 {
     dwTimeStamp ++;
-    
 }
 
 
diff --git a/firmware/src_simtrace/usb.c b/firmware/src_simtrace/usb.c
index ef18441..ffc44e0 100644
--- a/firmware/src_simtrace/usb.c
+++ b/firmware/src_simtrace/usb.c
@@ -200,9 +200,9 @@
         sizeof(USBEndpointDescriptor),
         USBGenericDescriptor_ENDPOINT,
         USBEndpointDescriptor_ADDRESS(USBEndpointDescriptor_OUT,
-                                      DATAOUT),
+                                      PHONE_DATAOUT),
         USBEndpointDescriptor_BULK,
-        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(DATAOUT),
+        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(PHONE_DATAOUT),
             USBEndpointDescriptor_MAXBULKSIZE_FS),
         0 /* Must be 0 for full-speed bulk endpoints */
     },
@@ -211,9 +211,9 @@
         sizeof(USBEndpointDescriptor),
         USBGenericDescriptor_ENDPOINT,
         USBEndpointDescriptor_ADDRESS(USBEndpointDescriptor_IN,
-                                      DATAIN),
+                                      PHONE_DATAIN),
         USBEndpointDescriptor_BULK,
-        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(DATAIN),
+        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(PHONE_DATAIN),
             USBEndpointDescriptor_MAXBULKSIZE_FS),
         0 /* Must be 0 for full-speed bulk endpoints */
     },
@@ -221,9 +221,9 @@
     {
         sizeof(USBEndpointDescriptor),
         USBGenericDescriptor_ENDPOINT,
-        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, INT ),
+        USBEndpointDescriptor_ADDRESS( USBEndpointDescriptor_IN, PHONE_INT ),
         USBEndpointDescriptor_INTERRUPT,
-        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(INT),
+        MIN(BOARD_USB_ENDPOINTS_MAXPACKETSIZE(PHONE_INT),
             USBEndpointDescriptor_MAXINTERRUPTSIZE_FS),
         0x10
     }
diff --git a/usb_application/ccid_raw.py b/usb_application/ccid_raw.py
index 1a51b68..4447e34 100755
--- a/usb_application/ccid_raw.py
+++ b/usb_application/ccid_raw.py
@@ -5,6 +5,8 @@
 
 import array
 
+from util import HEX
+
 class SmartcardException(Exception):
     pass
 
@@ -22,7 +24,7 @@
         print 'Reader:', reader
         print 'State:', state
         print 'Protocol:', protocol
-        print 'ATR:', smartcard.util.toHexString(atr, smartcard.util.HEX)
+        print 'ATR:', HEX(atr)
         return array.array('B', atr)
 
     def reset_card(self):
@@ -67,14 +69,13 @@
         print 'Released context.'
 
     def send_receive_cmd(self, cmd):
-        print("Cmd: ")
+        print("Cmd to SIM: " + HEX(cmd))
         hresult, resp = SCardTransmit(self.hcard, self.dwActiveProtocol,
             cmd.tolist())
         if hresult != SCARD_S_SUCCESS:
             raise SmartcardException('Failed to transmit: ' +
                 SCardGetErrorMessage(hresult))
-        print 'Ans: ' + smartcard.util.toHexString(resp,
-            smartcard.util.HEX)
+        print 'SIM Ans: ' + HEX(resp)
         return array.array('B', resp)
 
     def disconnect_card(self):
diff --git a/usb_application/constants.py b/usb_application/constants.py
index d4c1fd4..ac5a0a2 100644
--- a/usb_application/constants.py
+++ b/usb_application/constants.py
@@ -1,5 +1,14 @@
 from array import array
 
+SIM_WR = 0x1
+SIM_RD = 0x82
+SIM_INT = 0x83
+
+PHONE_WR = 0x4
+PHONE_RD = 0x85
+PHONE_INT = 0x86
+
+
 CMD_SEL_ROOT = array('B', [0xA0, 0xA4, 0x00, 0x00, 0x02, 0x3F, 0x00])
 CMD_SEL_FILE = array('B', [0xA0, 0xA4, 0x00, 0x00, 0x02, 0x7F, 0x20])
 CMD_GET_DATA = array('B', [0xA0, 0xC0, 0x00, 0x00, 0x16])
@@ -10,4 +19,4 @@
 ATR_SYSMOCOM1 = array('B', [0x3B, 0x99, 0x18, 0x00, 0x11, 0x88, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x60])
 ATR_SYSMOCOM2 = array('B', [0x3B, 0x99, 0x11, 0x00, 0x11, 0x88, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x60])
 NEW_ATR = ATR_SYSMOCOM2
-
+ATR_STRANGE_SIM = array('B', [0x3B, 0x0B, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x68, 0x2E, 0x00, 0x20, 0x68])
diff --git a/usb_application/mitm.py b/usb_application/mitm.py
index 962bf88..abbe05c 100755
--- a/usb_application/mitm.py
+++ b/usb_application/mitm.py
@@ -6,6 +6,8 @@
 
 from contextlib import closing
 
+from util import HEX
+from constants import PHONE_WR, PHONE_RD, PHONE_INT, SIM_WR, SIM_RD, SIM_INT
 
 def find_dev():
     dev = usb.core.find(idVendor=0x03eb, idProduct=0x6004)
@@ -17,33 +19,31 @@
 
 def pattern_match(inpt):
     print("Matching inpt", inpt)
-    if (inpt == ATR_SYSMOCOM1):
+    if (inpt == ATR_SYSMOCOM1) or (inpt == ATR_STRANGE_SIM):
+        print("ATR: ", inpt)
         return NEW_ATR
     elif (inpt == CMD_SEL_FILE):
+        print("CMD_SEL_FILE:", inpt)
+        return CMD_SEL_ROOT
+    elif (inpt == CMD_GET_DATA):
+        print("CMD_DATA:", inpt)
         return CMD_SEL_ROOT
     else:
         return inpt
 
-SIM_WR = 0x1
-SIM_RD = 0x82
-SIM_INT = 0x83
-
-PHONE_WR = 0x4
-PHONE_RD = 0x85
-PHONE_INT = 0x86
-
 ERR_TIMEOUT = 110
 
 def poll_ep(dev, ep):
     try:
-        return dev.read(ep, 64, 1000)
+        return dev.read(ep, 64, 10)
     except usb.core.USBError as e:
         if e.errno != ERR_TIMEOUT:
             raise
         return None
 
 def write_phone(dev, resp):
-    dev.write(PHONE_WR, resp, 1000)
+    print("WR: ", HEX(resp))
+    dev.write(PHONE_WR, resp, 10)
 
 def do_mitm():
     dev = find_dev()
@@ -52,14 +52,15 @@
         while True:
             cmd = poll_ep(dev, PHONE_INT)
             if cmd is not None:
-                print(cmd)
+                print("Int line ", HEX(cmd))
                 assert cmd[0] == ord('R')
 # FIXME: restart card anyways?
 #               sm_con.reset_card()
+                print("Write atr: ", HEX(atr))
                 write_phone(dev, atr)
 
             cmd = poll_ep(dev, PHONE_RD)
             if cmd is not None:
-                print(cmd)
+                print("RD: ", HEX(cmd))
                 sim_data = sm_con.send_receive_cmd(cmd)
                 write_phone(dev, sim_data)
diff --git a/usb_application/sniffer.py b/usb_application/sniffer.py
index 9c1f72f..f4c22cc 100755
--- a/usb_application/sniffer.py
+++ b/usb_application/sniffer.py
@@ -3,7 +3,9 @@
 import usb.core
 import usb.util
 import sys
+import array
 
+from constants import PHONE_RD
 
 def find_dev():
     dev = usb.core.find(idVendor=0x03eb, idProduct=0x6004)
@@ -46,14 +48,18 @@
 # main code
 def sniff():
     dev = find_dev()
+    ans = array.array('B', [])
 
     while True:
         #ep_out.write("Hello")
         try:
-            ans = dev.read(0x82, 64, 1000)
-            print("".join("%02x " % b for b in ans))
+            ans += dev.read(PHONE_RD, 64, 1000)
         except KeyboardInterrupt:
             print("Bye")
             sys.exit()
-        except: 
-            print("Timeout")
+        except Exception as e:
+            print e
+
+        if len(ans) >= 15:
+            print("".join("%02x " % b for b in ans))
+            ans = array.array('B', [])
diff --git a/usb_application/util.py b/usb_application/util.py
new file mode 100644
index 0000000..b6ef5a7
--- /dev/null
+++ b/usb_application/util.py
@@ -0,0 +1,5 @@
+
+def HEX(vals):
+    if vals is not None:
+        return ' '.join('%.2x'%x for x in vals)
+