/******************************************************************************
*@file  : app.c
*@brief : UART 7816M Demos 
******************************************************************************/
#include "app.h"
#include "hal_uart_7816m.h"

static uint8_t atr[32];

static uint8_t apdu[] = {0x00, 0x84, 0x00, 0x00, 0x08};

static UART_HandleTypeDef UART1_7816_Handle;


void printf_buff_byte(uint8_t* buff, uint32_t length)
{
	uint32_t i;

	for(i=0;i<length;i++)
	{
		printf("%.2x ",buff[i]);	
	}
	printf("\n");
}


void UART_7816M_ColdRST(UART_HandleTypeDef *huart)
{
    SET_BIT(huart->Instance->CR2, UART_CR2_CLKEN);   //Enable CLK out
    HAL_Delay(5);	
    UART_7816_RSTPIN_HIGH();
}

void UART_7816M_WarmRST(void)
{
	UART_7816_RSTPIN_HIGH();		
	HAL_Delay(1);
	UART_7816_RSTPIN_LOW();		
	HAL_Delay(10);              //At lest 2000*7816clk here is 10ms
	UART_7816_RSTPIN_HIGH();	
}

static void UART_7816M_Init(UART_HandleTypeDef *huart)
{
    huart->Instance = UART1;
    huart->Init.BaudRate = 10752;
    HAL_UART_7816M_Init(huart, 7, 1);
}

void Uart_7816M_Demo(void)
{
    uint8_t atr_len = 0;
    uint8_t status = HAL_OK;
    UART_HandleTypeDef *puart_7816_handle;

    puart_7816_handle = &UART1_7816_Handle;
    
    memset((uint8_t *)atr,0x00,sizeof(atr));

    printf("UART 7816M Demo\r\n\r\n");

    UART_7816M_Init(puart_7816_handle);
    
    printfS("Please insert the SmartCard and press the USR_PB button to continue......\r\n\r\n");
    
    while(GPIO_PIN_SET == BSP_PB_GetState());
	
    UART_7816M_ColdRST(puart_7816_handle);
    
    
    HAL_UART_7816M_Receive(puart_7816_handle, (uint8_t*)atr, 16, 9600);
    atr_len = puart_7816_handle->RxCount;
    
    printf("The ATR is: \r\n");
    printf_buff_byte((uint8_t*)atr,atr_len);


    HAL_Delay(1000);

    UART_7816M_WarmRST();
    HAL_UART_7816M_Receive(puart_7816_handle, (uint8_t*)atr, 16, 9600);
    atr_len = puart_7816_handle->RxCount;
    printf("The ATR after Warm RST is: \r\n");
    printf_buff_byte((uint8_t*)atr,atr_len);


    status = HAL_UART_7816M_Transmit(puart_7816_handle, apdu, 5);
    if(status == HAL_OK)
        printf("7816m send success.\n");
    else
        printf("7816m send failed. status = %d\n", status);

}

