/*********************************************************************************************************//**
 * @file    USART/HyperTerminal_TxRx_Interrupt/main.c
 * @version $Rev:: 4231         $
 * @date    $Date:: 2019-10-04 #$
 * @brief   Main program.
 *************************************************************************************************************
 * @attention
 *
 * Firmware Disclaimer Information
 *
 * 1. The customer hereby acknowledges and agrees that the program technical documentation, including the
 *    code, which is supplied by Holtek Semiconductor Inc., (hereinafter referred to as "HOLTEK") is the
 *    proprietary and confidential intellectual property of HOLTEK, and is protected by copyright law and
 *    other intellectual property laws.
 *
 * 2. The customer hereby acknowledges and agrees that the program technical documentation, including the
 *    code, is confidential information belonging to HOLTEK, and must not be disclosed to any third parties
 *    other than HOLTEK and the customer.
 *
 * 3. The program technical documentation, including the code, is provided "as is" and for customer reference
 *    only. After delivery by HOLTEK, the customer shall use the program technical documentation, including
 *    the code, at their own risk. HOLTEK disclaims any expressed, implied or statutory warranties, including
 *    the warranties of merchantability, satisfactory quality and fitness for a particular purpose.
 *
 * <h2><center>Copyright (C) Holtek Semiconductor Inc. All rights reserved</center></h2>
 ************************************************************************************************************/

/* Includes ------------------------------------------------------------------------------------------------*/
#include "ht32.h"
#include <string.h>

#include "main.h"
#include "gpio.h"
#include "gptm0.h"
#include "delay.h"
#include "Systick_For_Timeout.h"

/* USER CODE BEGIN Includes */
#include "bc45_cli.h"
#include "BC45_Board_Define.h"
#include "BC45_Board_ASIC_Category.h"
#include "BC45_Chip_Function.h"
#include "ISO14443A_Category.h"
#include "ISO15693_Category.h"
#include "ISO14443B_Category.h"
#include "BC45_Function.h"
/* USER CODE END Includes */

/** @addtogroup HT32_Series_Peripheral_Examples HT32 Peripheral Examples
  * @{
  */

/** @addtogroup USART_Examples USART
  * @{
  */

/** @addtogroup HyperTerminal_TxRx_Interrupt
  * @{
  */

/* Private function prototypes -----------------------------------------------------------------------------*/
void USART_Configuration(void);

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN 0 */
/*External variable*/
extern tBC45_WAKEUP_TIMER_PROPERTY Timer_WKUP;
extern tBC45_CD_TUNING Tunning_Thereshold;
/* USER CODE END 0 */



/**
  * @brief  This function is used to execute MCU to sleep mode.
  * @param	None
  * @retval None
  */
void GotoSleepMode(void)
{
	#if 0	
	/*Disable UART and SPI peripheral*/
	SPI1_DeInit();
	USART1_DeInit();

	/*Disable All peripheral */
	DisableAllPeripheral();
	#endif

	/*Init BC45 IRQ Pin is interrupt*/	
	EnableBC45_IRQ();

	/*Suspend Tick increment to prevent wakeup by Systick interrupt.
	Otherwise the Systick interrupt will wake up the device within 1ms*/
	SYSTICK_CounterCmd(SYSTICK_COUNTER_DISABLE);

	//debug pin
	//GPIO_SetOutBits(HT_GPIOA, GPIO_PIN_7);

	PWRCU_Sleep(PWRCU_SLEEP_ENTRY_WFI);

	//debug pin
	//GPIO_ClearOutBits(HT_GPIOA, GPIO_PIN_7);
	
	/* Resume Tick interrupt if disabled prior to sleep mode entry*/
	SYSTICK_CounterCmd(SYSTICK_COUNTER_ENABLE);

	DisableBC45_IRQ();
	
	#if 0
	/*Re-initial all peripheral for BC45*/
	InitUart_Pin();
	SPI1_Init();
	InitSPI_Pin();
	InitLED_GPIO_Pin();
	#endif
}

/**
  * @brief  This function is used to execute MCU to sleep mode.
  * @param	None
  * @retval None
  */
void GotoStopMode(void)
{
	#if 0
	/*Disable UART and SPI peripheral*/
	SPI1_DeInit();
	USART1_DeInit();

	/*Disable All peripheral */
	DisableAllPeripheral();
	#endif

	/*Enable BC45 IRQ Pin is interrupt*/	
	EnableBC45_IRQ();

	/*Suspend Tick increment to prevent wakeup by Systick interrupt.
	Otherwise the Systick interrupt will wake up the device within 1ms*/
	SYSTICK_CounterCmd(SYSTICK_COUNTER_DISABLE);

	//debug pin
	//GPIO_SetOutBits(HT_GPIOA, GPIO_PIN_7);
	
	//PWRCU_DeepSleep2(PWRCU_SLEEP_ENTRY_WFI);
  PWRCU_DeepSleep1(PWRCU_SLEEP_ENTRY_WFE);
	
	//debug pin
	//GPIO_ClearOutBits(HT_GPIOA, GPIO_PIN_7);

	/* Resume Tick interrupt if disabled prior to sleep mode entry*/
	SYSTICK_CounterCmd(SYSTICK_COUNTER_ENABLE);

	DisableBC45_IRQ();

	#if 0
	/*Re-initial all peripheral for BC45*/
	InitUart_Pin();
	SPI1_Init();
	InitSPI_Pin();
	InitLED_GPIO_Pin();
  #endif
}


void GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
  if(GPIO_Pin == BC45_IRQ_Pin)
  {
		/*Reset IRQ variable*/
    waittingIRQ = 0;
  }
  else
  {
    //Do nothing
  }
}


/*********************************************************************************************************//**
  * @brief  Configure the system clocks.
  * @retval None
  ***********************************************************************************************************/
void CKCU_Configuration(void)
{
#if 1
  CKCU_PeripClockConfig_TypeDef CKCUClock = {{ 0 }};
  CKCUClock.Bit.EXTI       = 1;
  CKCUClock.Bit.SPI1       = 1;
  CKCUClock.Bit.PA         = 1;
  CKCUClock.Bit.PB         = 1;
  CKCUClock.Bit.AFIO       = 1;
  COM1_CLK(CKCUClock)      = 1;
  CKCU_PeripClockConfig(CKCUClock, ENABLE);
#endif
}


/*********************************************************************************************************//**
  * @brief  Main program.
  * @retval None
  * @details Main program as following
  *  - Enable peripheral clock of AFIO, COM1.
  *  - Config AFIO mode as COM1_Rx, COM1_Tx function.
  *  - USART0, USART1 configuration:
  *     - BaudRate = 115200 baud
  *     - Word Length = 8 Bits
  *     - One Stop Bit
  *     - None parity bit
  *  - COM1 Rx character and move to URRxBuf, then copy to URTxBuf.
  ***********************************************************************************************************/
void ScanUID_LowPwr(void);
int main(void)
{
  /* USER CODE BEGIN 1 */
	uint8_t CMDLineBuffer[HTK_UART_BUFFER_SIZE];
	uint8_t CMDLineLen = 0;
	uint8_t count;
  /* USER CODE END 1 */

  /* Enable peripheral clock of AFIO, COM1                                                                  */  
  /* COM1 configuration                                                                                     */
  CKCU_Configuration();               /* System Related configuration                                       */
  USART_Configuration();
  GPTM0_Configuration();
  GPTM0_CH2_SetOnduty(50);
    
  GPIO_Init();
  SPI1_Init();             			  		/* SPI INT Related configuration                                      */

  
	Systick_1ms_Init();
		
  /*Initialize command line buffer*/
  htk_UART_Init(HT_UART1, CMDLineBuffer);
  /*Register SPIx, NCS pin and port*/
  htk_SPI_Init(HT_SPI1, SPI_SEL, SPI_SEL_PIN);
	
	//crystal
	memset(&nfca0,0,sizeof(nfc_config_t));
	memset(&nfcb0,0,sizeof(nfc_config_t));
	memset(&nfca1,0,sizeof(nfc_config_t));
	memset(&nfcb1,0,sizeof(nfc_config_t));
	//
	
  /* Configuration of tag type communication */	
  BC45_Configuration(CONFIG_14443A);
  tag_type = ISO14443A_TagType;

  /* Configure CD threshold to default*/
  Tunning_Thereshold.CD_Threshold_I_L = 0xD6;
  Tunning_Thereshold.CD_Threshold_I_H = 0xE0;
  Tunning_Thereshold.CD_Threshold_Q_L = 0xF5;
  Tunning_Thereshold.CD_Threshold_Q_H = 0xFF;

  CD_ADC_Tuning(Tunning_Thereshold);

  /*
   * Configure Wake up timer period to default
   * which is 500 ms. (reload is 0x10, prescaler is 0x09)
   * */
  Timer_WKUP.Timer_COUNTER = 0x0A;
  Timer_WKUP.Timer_PRESCALER = 0x09;
  Timer_WKUP.Timer_RELOAD = 0x10;

  TimerWKUP_INIT(Timer_WKUP);

  htk_UART_Transmit((uint8_t*)"HT32F2241 with BC45 CLI Start (Ver 2.0.0.0)\r\n", 35);
  LED_RED_OFF();
  LED_GREEN_OFF();

  /*Blue LED signaling after initialed BC45 reader*/
  for(count = 0; count < 3; count++)
  {
	  LED_RED_ON();
	  Delay(100);
	  LED_RED_OFF();
	  Delay(100);
  }
	GPTM0_CH2_SetOnduty(0);


  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		#if 0
    BC45_Configuration(CONFIG_14443A);
    ScanUID_ISO14443ATagType();
    BC45_Configuration(CONFIG_14443B);
    ScanUID_ISO14443BTagType();
    BC45_Configuration(CONFIG_15693);
    ScanUID_ISO15693TagType();
		#endif
		
		
		
	  /*Waiting for any command line*/
		//if(bc45__commandPrompt(CMDLineBuffer, &CMDLineLen,
		//	(uint8_t *)"\r\nHTK CLI> ", 11) > 0)
		if(bc45__commandPrompt(CMDLineBuffer, &CMDLineLen,
			(uint8_t *)"", 0) > 0)
		{
			// Convert to lower case
			customToLower(CMDLineBuffer, CMDLineLen);
			// Flush RxFIFO
			htk_ringBufferFlush(&rxFIFO);
			// Process shell command
			bc45__shellProcess(CMDLineBuffer);
			
			
		}
		if(runningLoop==1)
		{
			ScanUID_LowPwr();
		}
  /* USER CODE END WHILE */

  /* USER CODE BEGIN 3 */

  }
  /* USER CODE END 3 */


}

/*************************************************************************************************************
  * @brief  Configure the USART
  * @retval None
  ***********************************************************************************************************/
void USART_Configuration(void)
{
  USART_InitTypeDef USART_InitStructure;

  AFIO_GPxConfig(COM1_TX_GPIO_ID, COM1_TX_AFIO_PIN, AFIO_FUN_USART_UART);
  AFIO_GPxConfig(COM1_RX_GPIO_ID, COM1_RX_AFIO_PIN, AFIO_FUN_USART_UART);

  /* COM1 configured as follow:
        - BaudRate = 115200 baud
        - Word Length = 8 Bits
        - One Stop Bit
        - None parity bit
  */
  USART_InitStructure.USART_BaudRate = 115200;
  USART_InitStructure.USART_WordLength = USART_WORDLENGTH_8B;
  USART_InitStructure.USART_StopBits = USART_STOPBITS_1;
  USART_InitStructure.USART_Parity = USART_PARITY_NO;
  USART_InitStructure.USART_Mode = USART_MODE_NORMAL;
  USART_Init(COM1_PORT, &USART_InitStructure);

	#if 1
  /* Configure USART0 & USART1 interrupt                                                                    */
  NVIC_EnableIRQ(COM1_IRQn);

  /* Seting COM1_PORT interrupt-flag                                                                        */
  USART_IntConfig(COM1_PORT, USART_INT_RXDR, ENABLE);

  /* Enable COM1_PORT                                                                                       */
  USART_TxCmd(COM1_PORT, ENABLE);
  USART_RxCmd(COM1_PORT, ENABLE);
	#endif
}

#if (HT32_LIB_DEBUG == 1)
/*********************************************************************************************************//**
  * @brief  Report both the error name of the source file and the source line number.
  * @param  filename: pointer to the source file name.
  * @param  uline: error line source number.
  * @retval None
  ***********************************************************************************************************/
void assert_error(u8* filename, u32 uline)
{
  /*
     This function is called by IP library that the invalid parameters has been passed to the library API.
     Debug message can be added here.
     Example: printf("Parameter Error: file %s on line %d\r\n", filename, uline);
  */

  while (1)
  {
  }
}
#endif


/**
  * @}
  */

/**
  * @}
  */

/**
  * @}
  */
