/*
*************************************************************
 *@Copyright (C), 2016-2020 smartlinkMicro. Co., Ltd.  All rights reserved.
 *@Filename:
 *@Complier:
 *@Target OS:   NONE
 *@Target HW:   SL2x23
 *@Author:      htyi
 *@Version :    V1.0.0
 *@Date:        2017.8
 *@Description:
 *@History:
 *@    <author>     <time>     <version >   <desc>
*************************************************************
*/
#include <string.h>
#include <stdint.h>
#include "emv_if.h"
#include "sl2x23.h"

#ifdef USE_STDPERIPH_DRIVER
#include "utilities.h"
#include "spi.h"
#endif

volatile uint8_t irq_flag_io;
void delay_1ms(uint32_t delay_time){
    #ifdef USE_STDPERIPH_DRIVER
    delay_ms(delay_time);
    #else
    #endif
}

void write_reg(uint8_t addr, uint8_t RegValue) {
    #if defined IIC_Mode
    i2c_write_word(SL2x23_DEV_ADDRESS << 1, addr, RegValue);
    #elif defined UART_Mode
    addr = addr & 0x3f;      //code the first byte
    uart1_wrreg(addr, RegValue);
    #else
    addr = ((addr & 0x3f) << 1) & 0x7F;     //code the first byte
    #ifdef USE_STDPERIPH_DRIVER
    DEV_WriteSR(addr, RegValue);
    #else
    //接口函数
    #endif
    #endif
}

uint8_t read_reg(uint8_t addr) {
    #if defined IIC_Mode
    uint8_t reg_value;
    i2c_read_word(SL2x23_DEV_ADDRESS << 1, addr, &reg_value);
    return reg_value;
    #elif defined UART_Mode
    addr = (addr & 0x3f) | 0x80;    //code the first byte
    uart1_rdreg(addr);
    #else
    addr = ((addr & 0x3f) << 1) | 0x80;     //code the first byte
    #ifdef USE_STDPERIPH_DRIVER
    return DEV_ReadSR(addr);
    #endif
    //接口函数
    #endif
}

void spi_wr_test(void) {
    int ok = 0;
    uint8_t err = 0;
    int i = 0;
    uint8_t ret = 0xff;
    pcd_reset();//lpcd模式，下直接更新固件。不发reset，spi测试不成功
    delay_1ms(1);
    for(i = 0; i < 100; i++) {
        write_reg(0x09, i);
        ret = read_reg(0x09);
        if(i != ret) {
            err++;
            printf("i = 0x%x,errnum = 0x%x, data=0x%x\r\n", i, err, ret);
        } else {
            ok++;
        }
    }
    if(ok == 100) {
        printf("spi test pass! chip id = 0x%x\r\n",read_reg(0x37));
    } else {
        printf("spi test fail!\r\n");
    }
    
}
