/*******************************************************************************
**
** Function         rw_t2t_proc_data
**
** Description      This function handles data evt received from NFC Controller.
**
** Returns          none
**
*******************************************************************************/
static void rw_t2t_proc_data (UINT8 conn_id, tNFC_DATA_CEVT *p_data)
{
    tRW_EVENT               rw_event    = RW_RAW_FRAME_EVT;
    tRW_T2T_CB              *p_t2t      = &rw_cb.tcb.t2t;
    BT_HDR                  *p_pkt      = p_data->p_data;
    BOOLEAN                 b_notify    = TRUE;
    BOOLEAN                 b_release   = TRUE;
    UINT8                   *p;
    tRW_READ_DATA           evt_data = {0};
    tT2T_CMD_RSP_INFO       *p_cmd_rsp_info = (tT2T_CMD_RSP_INFO *) rw_cb.tcb.t2t.p_cmd_rsp_info;
    tRW_DETECT_NDEF_DATA    ndef_data;
#if (BT_TRACE_VERBOSE == TRUE)
    UINT8                   begin_state     = p_t2t->state;
#endif

    if (  (p_t2t->state == RW_T2T_STATE_IDLE)
        ||(p_cmd_rsp_info == NULL)  )
    {

#if (BT_TRACE_VERBOSE == TRUE)
        RW_TRACE_DEBUG2 ("RW T2T Raw Frame: Len [0x%X] Status [%s]", p_pkt->len, NFC_GetStatusName (p_data->status));
#else
        RW_TRACE_DEBUG2 ("RW T2T Raw Frame: Len [0x%X] Status [0x%X]", p_pkt->len, p_data->status);
#endif
        evt_data.status = p_data->status;
        evt_data.p_data = p_pkt;
        (*rw_cb.p_cback) (RW_T2T_RAW_FRAME_EVT, (tRW_DATA *)&evt_data);
        return;
    }
#if (defined (RW_STATS_INCLUDED) && (RW_STATS_INCLUDED == TRUE))
    /* Update rx stats */
    rw_main_update_rx_stats (p_pkt->len);
#endif
    /* Stop timer as response is received */
    nfc_stop_quick_timer (&p_t2t->t2_timer);

    RW_TRACE_EVENT2 ("RW RECV [%s]:0x%x RSP", t2t_info_to_str (p_cmd_rsp_info), p_cmd_rsp_info->opcode);

    if (  (  (p_pkt->len != p_cmd_rsp_info->rsp_len)
           &&(p_pkt->len != p_cmd_rsp_info->nack_rsp_len)
           &&(p_t2t->substate != RW_T2T_SUBSTATE_WAIT_SELECT_SECTOR)  )
        ||(p_t2t->state == RW_T2T_STATE_HALT)  )
    {
#if (BT_TRACE_VERBOSE == TRUE)
        RW_TRACE_ERROR1 ("T2T Frame error. state=%s ", rw_t2t_get_state_name (p_t2t->state));
#else
        RW_TRACE_ERROR1 ("T2T Frame error. state=0x%02X command=0x%02X ", p_t2t->state);
#endif
        if (p_t2t->state != RW_T2T_STATE_HALT)
        {
            /* Retrasmit the last sent command if retry-count < max retry */
            rw_t2t_process_frame_error ();
            p_t2t->check_tag_halt = FALSE;
        }
        GKI_freebuf (p_pkt);
        return;
    }
    rw_cb.cur_retry = 0;

    /* Assume the data is just the response byte sequence */
    p = (UINT8 *) (p_pkt + 1) + p_pkt->offset;


    RW_TRACE_EVENT4 ("rw_t2t_proc_data State: %u  conn_id: %u  len: %u  data[0]: 0x%02x",
                      p_t2t->state, conn_id, p_pkt->len, *p);

    evt_data.p_data     = NULL;

    if (p_t2t->substate == RW_T2T_SUBSTATE_WAIT_SELECT_SECTOR_SUPPORT)
    {
        /* The select process happens in two steps */
        if ((*p & 0x0f) == T2T_RSP_ACK)
        {
            if (rw_t2t_sector_change (p_t2t->select_sector) == NFC_STATUS_OK)
                b_notify = FALSE;
            else
                evt_data.status = NFC_STATUS_FAILED;
        }
        else
        {
            RW_TRACE_EVENT1 ("rw_t2t_proc_data - Received NACK response(0x%x) to SEC-SELCT CMD", (*p & 0x0f));
            evt_data.status = NFC_STATUS_REJECTED;
        }
    }
    else if (p_t2t->substate == RW_T2T_SUBSTATE_WAIT_SELECT_SECTOR)
    {
        evt_data.status = NFC_STATUS_FAILED;
    }
    else if (  (p_pkt->len != p_cmd_rsp_info->rsp_len)
             ||((p_cmd_rsp_info->opcode == T2T_CMD_WRITE) && ((*p & 0x0f) != T2T_RSP_ACK))  )
    {
        /* Received NACK response */
        evt_data.p_data = p_pkt;
        if (p_t2t->state == RW_T2T_STATE_READ)
            b_release = FALSE;

        RW_TRACE_EVENT1 ("rw_t2t_proc_data - Received NACK response(0x%x)", (*p & 0x0f));

        if (!p_t2t->check_tag_halt)
        {
            /* Just received first NACK. Retry just one time to find if tag went in to HALT State */
            b_notify =  FALSE;
            rw_t2t_process_error ();
            /* Assume Tag is in HALT State, untill we get response to retry command */
            p_t2t->check_tag_halt = TRUE;
        }
        else
        {
            p_t2t->check_tag_halt = FALSE;
            /* Got consecutive NACK so tag not really halt after first NACK, but current operation failed */
            evt_data.status = NFC_STATUS_FAILED;
        }
    }
    else
    {
        /* If the response length indicates positive response or cannot be known from length then assume success */
        evt_data.status  = NFC_STATUS_OK;
        p_t2t->check_tag_halt = FALSE;

        /* The response data depends on what the current operation was */
        switch (p_t2t->state)
        {
        case RW_T2T_STATE_CHECK_PRESENCE:
            b_notify = FALSE;
            rw_t2t_handle_presence_check_rsp (NFC_STATUS_OK);
            break;

        case RW_T2T_STATE_READ:
            evt_data.p_data = p_pkt;
            b_release = FALSE;
            if (p_t2t->block_read == 0)
            {
                p_t2t->b_read_hdr = TRUE;
                memcpy (p_t2t->tag_hdr,  p, T2T_READ_DATA_LEN);
#if(NFC_NXP_NOT_OPEN_INCLUDED == TRUE)
                /* On Ultralight - C tag, if CC is corrupt, correct it */
                if (  (p_t2t->tag_hdr[0] == TAG_MIFARE_MID)
                    &&(p_t2t->tag_hdr[T2T_CC2_TMS_BYTE] >= T2T_INVALID_CC_TMS_VAL0)
                    &&(p_t2t->tag_hdr[T2T_CC2_TMS_BYTE] <= T2T_INVALID_CC_TMS_VAL1)  )
                {
                    p_t2t->tag_hdr[T2T_CC2_TMS_BYTE] = T2T_CC2_TMS_MULC;
                }
#endif
            }
            break;

        case RW_T2T_STATE_WRITE:
            /* Write operation completed successfully */
            break;

        default:
            /* NDEF/other Tlv Operation/Format-Tag/Config Tag as Read only */
            b_notify = FALSE;
            rw_t2t_handle_rsp (p);
            break;
        }
    }

    if (b_notify)
    {
        rw_event = rw_t2t_info_to_event (p_cmd_rsp_info);

        if (rw_event == RW_T2T_NDEF_DETECT_EVT)
        {
            ndef_data.status    = evt_data.status;
            ndef_data.protocol  = NFC_PROTOCOL_T2T;
            ndef_data.flags     = RW_NDEF_FL_UNKNOWN;
            if (p_t2t->substate == RW_T2T_SUBSTATE_WAIT_READ_LOCKS)
                ndef_data.flags = RW_NDEF_FL_FORMATED;
            ndef_data.max_size  = 0;
            ndef_data.cur_size  = 0;
            /* Move back to idle state */
            rw_t2t_handle_op_complete ();
            (*rw_cb.p_cback) (rw_event, (tRW_DATA *) &ndef_data);
        }
        else
        {
            /* Move back to idle state */
            rw_t2t_handle_op_complete ();
            (*rw_cb.p_cback) (rw_event, (tRW_DATA *) &evt_data);
        }
    }

    if (b_release)
        GKI_freebuf (p_pkt);

#if (BT_TRACE_VERBOSE == TRUE)
    if (begin_state != p_t2t->state)
    {
        RW_TRACE_DEBUG2 ("RW T2T state changed:<%s> -> <%s>",
                          rw_t2t_get_state_name (begin_state),
                          rw_t2t_get_state_name (p_t2t->state));
    }
#endif
}
/*******************************************************************************
**
** Function         rw_t1t_data_cback
**
** Description      This callback function handles data from NFCC.
**
** Returns          none
**
*******************************************************************************/
static void rw_t1t_data_cback (UINT8 conn_id, tNFC_CONN_EVT event, tNFC_CONN *p_data)
{
    tRW_T1T_CB              *p_t1t      = &rw_cb.tcb.t1t;
    tRW_EVENT               rw_event    = RW_RAW_FRAME_EVT;
    BOOLEAN                 b_notify    = TRUE;
    tRW_DATA                evt_data;
    BT_HDR                  *p_pkt;
    UINT8                   *p;
    tT1T_CMD_RSP_INFO       *p_cmd_rsp_info     = (tT1T_CMD_RSP_INFO *) rw_cb.tcb.t1t.p_cmd_rsp_info;
#if (BT_TRACE_VERBOSE == TRUE)
    UINT8                   begin_state         = p_t1t->state;
#endif

    p_pkt = (BT_HDR *) (p_data->data.p_data);
    if (p_pkt == NULL)
        return;
    /* Assume the data is just the response byte sequence */
    p = (UINT8 *) (p_pkt + 1) + p_pkt->offset;

#if (BT_TRACE_VERBOSE == TRUE)
    RW_TRACE_DEBUG2 ("rw_t1t_data_cback (): state:%s (%d)", rw_t1t_get_state_name (p_t1t->state), p_t1t->state);
#else
    RW_TRACE_DEBUG1 ("rw_t1t_data_cback (): state=%d", p_t1t->state);
#endif

    evt_data.status = NFC_STATUS_OK;

    if(  (p_t1t->state == RW_T1T_STATE_IDLE)
       ||(!p_cmd_rsp_info)  )
    {
        /* If previous command was retransmitted and if response is pending to previous command retransmission,
         * check if lenght and ADD/ADD8/ADDS field matches the expected value of previous
         * retransmited command response. However, ignore ADD field if the command was RALL/RID
         */
        if (  (p_t1t->prev_cmd_rsp_info.pend_retx_rsp)
            &&(p_t1t->prev_cmd_rsp_info.rsp_len == p_pkt->len)
            &&((p_t1t->prev_cmd_rsp_info.op_code == T1T_CMD_RID) || (p_t1t->prev_cmd_rsp_info.op_code == T1T_CMD_RALL) || (p_t1t->prev_cmd_rsp_info.addr == *p))  )
        {
            /* Response to previous command retransmission */
            RW_TRACE_ERROR2 ("T1T Response to previous command in Idle state. command=0x%02x, Remaining max retx rsp:0x%02x ", p_t1t->prev_cmd_rsp_info.op_code, p_t1t->prev_cmd_rsp_info.pend_retx_rsp - 1);
            p_t1t->prev_cmd_rsp_info.pend_retx_rsp--;
            GKI_freebuf (p_pkt);
        }
        else
        {
            /* Raw frame event */
            evt_data.data.p_data = p_pkt;
            (*rw_cb.p_cback) (RW_T1T_RAW_FRAME_EVT, (tRW_DATA *) &evt_data);
        }
        return;
    }

#if (defined (RW_STATS_INCLUDED) && (RW_STATS_INCLUDED == TRUE))
    /* Update rx stats */
    rw_main_update_rx_stats (p_pkt->len);
#endif  /* RW_STATS_INCLUDED */


    if (  (p_pkt->len != p_cmd_rsp_info->rsp_len)
        ||((p_cmd_rsp_info->opcode != T1T_CMD_RALL) && (p_cmd_rsp_info->opcode != T1T_CMD_RID) && (*p != p_t1t->addr))  )

    {
        /* If previous command was retransmitted and if response is pending to previous command retransmission,
         * then check if lenght and ADD/ADD8/ADDS field matches the expected value of previous
         * retransmited command response. However, ignore ADD field if the command was RALL/RID
         */
        if (  (p_t1t->prev_cmd_rsp_info.pend_retx_rsp)
            &&(p_t1t->prev_cmd_rsp_info.rsp_len == p_pkt->len)
            &&((p_t1t->prev_cmd_rsp_info.op_code == T1T_CMD_RID) || (p_t1t->prev_cmd_rsp_info.op_code == T1T_CMD_RALL) || (p_t1t->prev_cmd_rsp_info.addr == *p))  )
        {
            RW_TRACE_ERROR2 ("T1T Response to previous command. command=0x%02x, Remaining max retx rsp:0x%02x", p_t1t->prev_cmd_rsp_info.op_code, p_t1t->prev_cmd_rsp_info.pend_retx_rsp - 1);
            p_t1t->prev_cmd_rsp_info.pend_retx_rsp--;
        }
        else
        {
            /* Stop timer as some response to current command is received */
            nfc_stop_quick_timer (&p_t1t->timer);
            /* Retrasmit the last sent command if retry-count < max retry */
#if (BT_TRACE_VERBOSE == TRUE)
            RW_TRACE_ERROR2 ("T1T Frame error. state=%s command (opcode) = 0x%02x", rw_t1t_get_state_name (p_t1t->state), p_cmd_rsp_info->opcode);
#else
            RW_TRACE_ERROR2 ("T1T Frame error. state=0x%02x command = 0x%02x ", p_t1t->state, p_cmd_rsp_info->opcode);
#endif
            rw_t1t_process_frame_error ();
        }
        GKI_freebuf (p_pkt);
        return;
    }

    /* Stop timer as response to current command is received */
    nfc_stop_quick_timer (&p_t1t->timer);

    RW_TRACE_EVENT2 ("RW RECV [%s]:0x%x RSP", t1t_info_to_str (p_cmd_rsp_info), p_cmd_rsp_info->opcode);

    /* If we did not receive response to all retransmitted previous command,
     * dont expect that as response have come for the current command itself.
     */
    if (p_t1t->prev_cmd_rsp_info.pend_retx_rsp)
        memset (&(p_t1t->prev_cmd_rsp_info), 0, sizeof (tRW_T1T_PREV_CMD_RSP_INFO));

    if (rw_cb.cur_retry)
    {
    /* If the current command was retransmitted to get this response, we might get
       response later to all or some of the retrasnmission of the current command
     */
        p_t1t->prev_cmd_rsp_info.addr          = ((p_cmd_rsp_info->opcode != T1T_CMD_RALL) && (p_cmd_rsp_info->opcode != T1T_CMD_RID))? p_t1t->addr:0;
        p_t1t->prev_cmd_rsp_info.rsp_len       = p_cmd_rsp_info->rsp_len;
        p_t1t->prev_cmd_rsp_info.op_code       = p_cmd_rsp_info->opcode;
        p_t1t->prev_cmd_rsp_info.pend_retx_rsp = (UINT8) rw_cb.cur_retry;
    }

    rw_cb.cur_retry = 0;

    if (p_cmd_rsp_info->opcode == T1T_CMD_RID)
    {
        rw_event = rw_t1t_handle_rid_rsp (p_pkt);
    }
    else
    {
        rw_event = rw_t1t_handle_rsp (p_cmd_rsp_info, &b_notify, p, &evt_data.status);
    }

    if (b_notify)
    {
        if(  (p_t1t->state != RW_T1T_STATE_READ)
           &&(p_t1t->state != RW_T1T_STATE_WRITE)  )
        {
            GKI_freebuf (p_pkt);
            evt_data.data.p_data = NULL;
        }
        else
        {
            evt_data.data.p_data = p_pkt;
        }
        rw_t1t_handle_op_complete ();
        (*rw_cb.p_cback) (rw_event, (tRW_DATA *) &evt_data);
    }
    else
        GKI_freebuf (p_pkt);

#if (BT_TRACE_VERBOSE == TRUE)
    if (begin_state != p_t1t->state)
    {
        RW_TRACE_DEBUG2 ("RW T1T state changed:<%s> -> <%s>",
                          rw_t1t_get_state_name (begin_state),
                          rw_t1t_get_state_name (p_t1t->state));
    }
#endif
}