
/**
 ******************************************************************************
 *
 * @file        TH222x_12_BLE.c
 * @brief       This is to test TH222x SPI Flash C file.

 * @par         Project
 *              MG32
 * @version     V1.01
 * @date        2023/05/10
 * @author      Megawin Software Center
 * @copyright   Copyright (c) 2017 MegaWin Technology Co., Ltd.
 *              All rights reserved.
 *
 *******************************************************************************
 * @par Disclaimer
 * The Demo software is provided "AS IS" without any warranty, either
 * expressed or implied, including, but not limited to, the implied warranties
 * of merchantability and fitness for a particular purpose. The author will
 * not be liable for any special, incidental, consequential or indirect
 * damages due to loss of data or any other reason.
 * These statements agree with the world wide and local dictated laws about
 * authorship and violence against these laws.
 *******************************************************************************
 *******************************************************************************
 */

/* Includes ------------------------------------------------------------------*/

#include "MG32_URT_DRV.h"
#include "TH222x_Global.h"


#if BSP_12_BLE_MODULE == BSP_12_BLE_MODULE_HC06
#include "BSP_12_BLE_HC06.h"
#endif
#if BSP_12_BLE_MODULE == BSP_12_BLE_MODULE_HC42
#include "BSP_12_BLE_HC42.h"
#endif


/* Wizard menu ---------------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
//URT
#define tBLE_URTn          URT5
#define BLE_URT_IRQn       URT4x_IRQn

//Buffer control
#define BLE_BUF_MAX_SIZE   200

/* Private typedef -----------------------------------------------------------*/
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
uint8_t TH222x_BLE_UpdateFlag;
uint8_t TH222x_BLE_ONFlag;

static  uint8_t TH222x_BLE_RXTmp;
static  uint8_t TH222x_BLE_ActLEDCount;
static  uint8_t TH222x_BLE_ActLEDCountMax;

static  uint8_t TH222x_BLE_URTTxBuf[BLE_BUF_MAX_SIZE];
static  uint8_t TH222x_BLE_URTTXPosW;
static  uint8_t TH222x_BLE_URTTXtxLen;


/* Private function prototypes -----------------------------------------------*/
/* Exported variables --------------------------------------------------------*/
/* Exported functions --------------------------------------------------------*/
/* External variables --------------------------------------------------------*/

/**
 *******************************************************************************
 * @brief	 URT interrupt handler in TH222x BLE.
 * @details
 * @return
 * @note
 *******************************************************************************
 */
void TH222x_BLE_URTIRQHandler(void)
{

    if(tBLE_URTn->STA.MBIT.RXF)
    {
        TH222x_BLE_RXTmp = tBLE_URTn->RDAT.B[0];

        TH222x_BLE_WriteTxBuffer (&TH222x_BLE_RXTmp, 1);
    }
    if (tBLE_URTn->STA.MBIT.TCF)
    {
        if (TH222x_BLE_URTTXPosW < TH222x_BLE_URTTXtxLen)
        {
            tBLE_URTn->TDAT.B[0] = TH222x_BLE_URTTxBuf[TH222x_BLE_URTTXPosW++];
            return;
        }
        TH222x_BLE_URTTXPosW  = 0;
        TH222x_BLE_URTTXtxLen = 0;
        tBLE_URTn->STA.W       = URT_STA_TCF_mask_w;
    }
}

/**
 *******************************************************************************
 * @brief     BLE IRQ pin interrupt handle.
 * @details
 * @return
 * @note      ble has used, modify code must be careful
 *******************************************************************************
 */
#if BSP_12_BLE_MODULE == BSP_12_BLE_MODULE_MG126
void BLE_IRQHandler(void)
{
    #if BSP_12_BLE == 1
        #if BSP_2_ARGB == 1
            TH222x_BLE_ARGDelay = 3;
        #endif
        EXIC_ClearPxTriggerEventFlag(BLE_CSN_EXIC_PORT, BLE_CSN_EXIC_FLAG );        // Clear
        IWDT_RefreshCounter();
        ble_run(0);
    #endif
}
#endif
/**
 *******************************************************************************
 * @brief	 TH222x BLE parameter default initial.
 * @details
 * @return
 * @note
 *******************************************************************************
 */
void TH222x_BLEParameter_DeInit(void)
{
    TH222x_BLE_UpdateFlag     = 0;
    TH222x_BLE_ONFlag         = 0;

    TH222x_BLE_ActLEDCount    = 0;
    TH222x_BLE_ActLEDCountMax = 80;

    TH222x_BLE_URTTXPosW      = 0;
    TH222x_BLE_URTTXtxLen     = 0;
}
/**
 *******************************************************************************
 * @brief	 URT IT configure.
 * @details
 * @param[in]   URT_IT: (The device support which interrupt refer to the device spec , please)
 *  @arg\b      URT_IT_CALTMO : Baud rate calibration sync field receive time out.
 *  @arg\b      URT_IT_BKTMO  : Break receive time out.
 *  @arg\b      URT_IT_IDTMO  : Idle state time out.
 *  @arg\b      URT_IT_RXTMO  : Receive time out.
 *  @arg\b      URT_IT_TUDR   : URT SPI slave mode transmit underrun.
 *  @arg\b      URT_IT_TXE    : TX error detect.
 *  @arg\b      URT_IT_ROVR   : Receive overrun error.
 *  @arg\b      URT_IT_NCE    : Receive noised character error detect.
 *  @arg\b      URT_IT_FE     : Receive frame error detect.
 *  @arg\b      URT_IT_PE     : Receive parity error detect.
 *  @arg\b      URT_IT_CTS    : CTS change detect.
 *  @arg\b      URT_IT_IDL    : RX idle line detect.
 *  @arg\b      URT_IT_BK     : Break condition detect.
 *  @arg\b      URT_IT_CALC   : Auto baudrate calibration complete.
 *  @arg\b      URT_IT_TMO    : Timeout timer timeout.
 *  @arg\b      URT_IT_BRT    : Baud rate generator timer timeout.
 *  @arg\b      URT_IT_SADR   : Slave address matched.
 *  @arg\b      URT_IT_TX     : Transmit data register empty.
 *  @arg\b      URT_IT_RX     : Receive data register not empty.
 *  @arg\b      URT_IT_LS     : URT line status relationship interrupt.
 *  @arg\b      URT_IT_ERR    : URT error relationship interrupt.
 *  @arg\b      URT_IT_TC     : Transmission complete.(shadow buffer , data register , shift buffer empty)
 *  @arg\b      URT_IT_UG     : URT genernal event relationship interrupt.
 * @param[in]   URT_IT_State:
 * 	@arg\b      ENABLE : Enable interrupt of URT_IT.
 *  @arg\b      DISABLE: Disable interrupt of URT_IT.
 * @return
 * @note
 *******************************************************************************
 */
void TH222x_BLE_URTIT_Config(uint8_t BLE_URT_IT , FunctionalState BLE_URT_ITCmd)
{
    URT_IT_Config( tBLE_URTn , BLE_URT_IT , BLE_URT_ITCmd);
}
/**
 *******************************************************************************
 * @brief	 TH222x BLE initial.
 * @details
 * @return
 * @note
 *******************************************************************************
 */
void TH222x_BLE_Init(void)
{
    URT_BRG_TypeDef  URT_BRG;
    URT_Data_TypeDef DataDef;


    /*URT Module Initial*/
    //==============================================================
    //UART Initial ( Use URT1)
    // N-8-1 LSB Baud Rate = 9600
    //------------------------------------------------------
    //GPIO Initial
    //No output to PIN , internal loop TX->RX
    URT_LoopBackMode_Cmd( tBLE_URTn , ENABLE);
    //------------------------------------------------------
    //Set BaudRate
    URT_BRG.URT_InternalClockSource = URT_BDClock_PROC;
    URT_BRG.URT_BaudRateMode = URT_BDMode_Separated;
    URT_BRG.URT_PrescalerCounterReload = 9;
    URT_BRG.URT_BaudRateCounterReload  = 24;
    URT_BaudRateGenerator_Config(tBLE_URTn, &URT_BRG);
    URT_BaudRateGenerator_Cmd(tBLE_URTn, ENABLE);
    //------------------------------------------------------
    //TX/RX Clock
    URT_TXClockSource_Select(tBLE_URTn, URT_TXClock_Internal);
    URT_RXClockSource_Select(tBLE_URTn, URT_RXClock_Internal);
    URT_TXOverSamplingSampleNumber_Select(tBLE_URTn, 19);
    URT_RXOverSamplingSampleNumber_Select(tBLE_URTn, 19);
    URT_RXOverSamplingMode_Select(tBLE_URTn, URT_RXSMP_3TIME);
    URT_TX_Cmd(tBLE_URTn, ENABLE);
    URT_RX_Cmd(tBLE_URTn, ENABLE);

    //------------------------------------------------------
    //Set Data character config
    DataDef.URT_TX_DataLength  = URT_DataLength_8;
    DataDef.URT_RX_DataLength  = URT_DataLength_8;
    DataDef.URT_TX_DataOrder   = URT_DataTyped_LSB;
    DataDef.URT_RX_DataOrder   = URT_DataTyped_LSB;
    DataDef.URT_TX_Parity      = URT_Parity_No;
    DataDef.URT_RX_Parity      = URT_Parity_No;
    DataDef.URT_TX_StopBits    = URT_StopBits_1_0;
    DataDef.URT_RX_StopBits    = URT_StopBits_1_0;
    DataDef.URT_TX_DataInverse = DISABLE;
    DataDef.URT_RX_DataInverse = DISABLE;
    URT_DataCharacter_Config(tBLE_URTn, &DataDef);
    //------------------------------------------------------
    //Set Mode Select
    URT_Mode_Select(tBLE_URTn, URT_URT_mode);
    //------------------------------------------------------
    //Set DataLine Select
    URT_DataLine_Select(tBLE_URTn, URT_DataLine_2);

    //------------------------------------------------------
    //Set Data Control
    URT_RXShadowBufferThreshold_Select(tBLE_URTn, URT_RXTH_1BYTE);
    URT_IdlehandleMode_Select(tBLE_URTn, URT_IDLEMode_No);
    URT_TXGuardTime_Select(tBLE_URTn, 0);

    //------------------------------------------------------
    //Enable URT Interrupt
    URT_IT_Config(tBLE_URTn, URT_IT_RX | URT_IT_TC, ENABLE);
    URT_ITEA_Cmd(tBLE_URTn, ENABLE);
    NVIC_EnableIRQ(BLE_URT_IRQn);

    //------------------------------------------------------
    //Enable URT
    URT_Cmd(tBLE_URTn, ENABLE);
    
    BSP_BLE_Init();
}
/**
 *******************************************************************************
 * @brief	 TH222x BLE main function.
 * @details
 * @return
 * @note
 *******************************************************************************
 */
void TH222x_BLE(void)
{
    #if BSP_12_BLE_MODULE == BSP_12_BLE_MODULE_MG126
        if(ble_run_interrupt_McuCanSleep())
        {
            // To do ......
        }
    #endif
    if( TH222x_BLE_UpdateFlag == 0)
    {
        return;
    }
    TH222x_BLE_UpdateFlag = 0;
    
    /*TH223x LED control*/
    if( TH222x_CTR.RLED_Lock == 1 || TH222x_CTR.GLED_Lock == 1 || TH222x_CTR.YLED_Lock == 1)
    {
        return;
    }
    if( TH222x_BLE_ActLEDCount < TH222x_BLE_ActLEDCountMax)
    {
        TH222x_BLE_ActLEDCount  = TH222x_BLE_ActLEDCount + 1;
        return;

    }
    TH222x_BLE_ActLEDCount  = 0;

    
    if(GetConnectedStatus()==0)
    {
        TH223x_LEDG_PIN   = TH223x_LED_OFF;
        TH223x_LEDR_PIN   = ~TH223x_LEDR_PIN;
        TH222x_BLE_ONFlag = 0;
    }
    else
    {
        TH223x_LEDR_PIN   = TH223x_LED_OFF;
        TH223x_LEDG_PIN   = ~TH223x_LEDG_PIN;
        TH222x_BLE_ONFlag = 1;
    }

}

/**
 *******************************************************************************
 * @brief	 TH222x BLE write TX buffer.
 * @details
 * @return
 * @note
 *******************************************************************************
 */
uint8_t TH222x_BLE_WriteTxBuffer(uint8_t* TH222xBLE_TXBuf, uint8_t TH222xBLE_TXLen)
{
    if( TH222x_BLE_ONFlag == 0)
    {
        return(TH222x_FAILURE);
    }
    BSP_BLE_WriteTxBuffer(TH222xBLE_TXBuf,TH222xBLE_TXLen);
    return(TH222x_SUCCESS);
}
/**
 *******************************************************************************
 * @brief	 TH222x BLE main function.
 * @details
 * @return
 * @note
 *******************************************************************************
 */
void BSP_BLE_ReadCallback(void)
{
    if( TH222x_BLE_URTTXtxLen !=0)
    {
        return;
    }
    #if BSP_12_BLE_MODULE == BSP_12_BLE_MODULE_HC06 || BSP_12_BLE_MODULE == BSP_12_BLE_MODULE_HC42
        TH222x_BLE_URTTXtxLen = BSP_BLE_ReadRxBuffer(&TH222x_BLE_URTTxBuf[0],BLE_BUF_MAX_SIZE);
    #endif
    #if BSP_12_BLE_MODULE == BSP_12_BLE_MODULE_MG126
        TH222x_BLE_URTTXtxLen = BSP_BLE_ReadRxBuffer(&TH222x_BLE_URTTxBuf[0]);
    #endif
    TH222x_BLE_URTTXPosW  = 0;
    BLE_RXF = 0;
    #if BSP_12_BLE_MODULE == BSP_12_BLE_MODULE_MG126
        BSP_BLE_ClearBleRxBuffer();
    #endif
    
    if( TH222x_BLE_URTTXtxLen==0)
    {
        return;
    }
    tBLE_URTn->TDAT.B[0] = TH222x_BLE_URTTxBuf[TH222x_BLE_URTTXPosW++];

}




