/*!
 * @file        main.c
 *
 * @brief       Main program body
 *
 * @version     V1.0.0
 *
 * @date        2026-02-25
 *
 * @attention
 *
 *  Copyright (C) 2026 Geehy Semiconductor
 *
 *  You may not use this file except in compliance with the
 *  GEEHY COPYRIGHT NOTICE (Geehy Semiconductor Software License Agreement).
 *
 *  The program is only for reference, which is distributed in the hope
 *  that it will be useful and instructional for customers to develop
 *  their software. Unless required by applicable law or agreed to in
 *  writing, the program is distributed on an "AS IS" BASIS, WITHOUT
 *  ANY WARRANTY OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the Geehy Semiconductor Software License Agreement for the governing permissions
 *  and limitations under the License.
 */

/* Includes */
#include "stdio.h"
#include "inttypes.h"
#include "Board.h"
#include "user_can_config.h"

/** @addtogroup Examples
  @{
  */

/** @addtogroup CAN_Examples
  @{
  */

/** @addtogroup CAN_LoopBack
  @{
  */

/** @defgroup CAN_LoopBack_Macros Macros
  @{
  */

/* printf function configs to USART1*/
#define DEBUG_USART                    USART1

/**@} end of group CAN_LoopBack_Macros */

/** @defgroup CAN_LoopBack_Variables Variables
  @{
  */
static volatile uint8_t g_TxCompleteFlg = (uint8_t)FALSE;
static volatile uint8_t g_RxCompleteFlg = (uint8_t)FALSE;
static Can_TxFrameType g_TxFrame = {0U};
static Can_RxFrameType g_RxFrame = {0U};
static Can_RxFrameType g_RxFrameBuf = {0U};
static Can_HandleType g_CanHandle = {0U};
static Can_BufTransInfoType g_TxInfoBuf = {0U};
static Can_RxFifoTransInfoType g_RxInfoBuf = {0U};

static uint8_t g_sdu64[64] = {0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50,
                       0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60,
                       0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B, 0x6C, 0x6D, 0x6E, 0x6F, 0x70,
                       0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F, 0x80};

/**@} end of group Can_LoopBack_Variables */

/** @defgroup CAN_LoopBack_Functions Functions
  @{
  */
static void DealCanData(void);
static void Can_MainFunctionInit(void);
static void Delay(void);

int main(void)
{
    /* COM1 init*/
    Board_ComInit(COM1);

    printf("-------CAN loopback functional example-------\r\n\r\n");

    /* Arbitration field:1M 80%
     * Data field:4M 80% */
    Can_MainFunctionInit();

    while(1)
    {
        DealCanData();
    }
}

static void Can_IntCallback(CAN_T *ModulePtr, Can_HandleType *HandlePtr, Can_TransferStsType Status, 
                            uint32_t Result, uint8_t *InputParaPtr)
{
    switch (Status)
    {
        case CAN_FIFO0_RX_IDLE:
        {                   
            g_RxCompleteFlg = (uint8_t)TRUE;

            g_RxFrameBuf = g_RxFrame;
            g_RxInfoBuf.rxFramePtr = &g_RxFrame;
            Can_ReceiveFifoNonBlocking(ModulePtr, CAN_RX_FIFO0, &g_CanHandle, &g_RxInfoBuf);
        }
        break;

        case CAN_TX_IDLE:
        {
            g_TxCompleteFlg = (uint8_t)TRUE;
        }
        break;

        case CAN_FIFO0_RX_LOST:
        break;

        case CAN_FIFO1_RX_IDLE:
        break;
        
        case CAN_FIFO1_RX_LOST:
        break;

        /* Rx dedicate buffer successfully */
        case CAN_RX_IDLE:
        break;

        default:
            {
                /* do nothing */
            }
            break;
    }

    /* Avoid MISRA check warning */
    if(InputParaPtr != NULL)
    {
        *InputParaPtr = 0U;
    }
    else
    {
        /* do nothing */
    }
    /* Avoid MISRA check warning */
    if(HandlePtr != NULL)
    {
        HandlePtr->InputParaPtr = NULL;
    }
    else
    {
        /* do nothing */
    }
    (void)Result;
}

static void Can_MainFunctionInit(void)
{
    Can_FilterConfigType rxFilter = {0U};
    Can_StdFilterEleConfigType stdFilter = {0U};
    Can_RxFifoConfigType rxFifo0 = {0};
    Can_TxBufConfigType txBuffer = {0U};

    Gpio_ConfigType GPIO_InitStructure = {0U};

    Rcm_ConfigCanClk(RCM_CANCLK_PLLCLK);
    Rcm_EnableApb1PeriphClock(RCM_APB1_PERIPH_CAN);
    Rcm_EnableAhbPeriphClock(RCM_AHB_PERIPH_GPIOB);
    
    Gpio_ConfigPinAF(CANTX_GPIO_PORT, CANTX_PIN_SOURCE, CANTX_AF);
    Gpio_ConfigPinAF(CANRX_GPIO_PORT, CANRX_PIN_SOURCE, CANRX_AF);
    
    GPIO_InitStructure.mode = GPIO_MODE_AF;
    GPIO_InitStructure.pupd = GPIO_PUPD_PD;
    GPIO_InitStructure.outtype = GPIO_OUT_TYPE_PP;
    GPIO_InitStructure.pin = (uint16_t)CANTX_PIN; 
    Gpio_Config(CANTX_GPIO_PORT, &GPIO_InitStructure);
    GPIO_InitStructure.pin = (uint16_t)CANRX_PIN; 
    Gpio_Config(CANRX_GPIO_PORT, &GPIO_InitStructure);

    Can_Init(EXAMPLE_MCAN, &g_canConfig);

    /* Create MCAN handle structure and set call back function */
    Can_CreateHandle(EXAMPLE_MCAN, &g_CanHandle, &Can_IntCallback, NULL);

   /* Set Message RAM base address and clear to avoid ECC error */
    memset((uint32_t *)CAN_SRAM_BASE, 0, MSG_RAM_SIZE);

    /* STD filter config. */
    rxFilter.address  = STD_FILTER_OFS;
    rxFilter.idFormat = CAN_FRAME_STD_ID;
    rxFilter.listSize = 1U;
    rxFilter.nmFrame  = CAN_REJECT;
    rxFilter.remFrame = CAN_REJECT_REMOTE_FRAME;
    Can_SetFilterConfig(EXAMPLE_MCAN, &rxFilter);

    stdFilter.sfec = (uint8_t)CAN_FILTER_STORE_IN_FIFO0;
    /* Classic filter mode, only filter matching ID. */
    stdFilter.sft   = (uint8_t)CAN_FILTER_RANGE_MODE;
    stdFilter.sfid1 = 0x730U;
    stdFilter.sfid2 = 0x737U;
    Can_SetStdFilterEle(&rxFilter, &stdFilter, 0);

    /* RX fifo0 config. */
    rxFifo0.address       = RX_FIFO0_OFS;
    rxFifo0.elementSize   = 1U;
    rxFifo0.watermark     = 0;
    rxFifo0.opmode        = CAN_RX_FIFO_BLOCK_OPERATION;
    rxFifo0.datafieldSize = CAN_DATA_SIZE_64;
    Can_SetRxFifo0Config(EXAMPLE_MCAN, &rxFifo0);

    /* TX buffer config. */
    memset(&txBuffer, 0, sizeof(txBuffer));
    txBuffer.address       = TX_BUFFER_OFS;
    txBuffer.dedicatedSize = 1U;
    txBuffer.fifoQueCnt    = 0;
    txBuffer.datafieldSize = CAN_DATA_SIZE_64;

    Can_SetTxBufConfig(EXAMPLE_MCAN, &txBuffer);

    /* Finish software initialization and enter normal mode, synchronizes to
       CAN bus, ready for communication */
    Can_EnterNorMode(EXAMPLE_MCAN);

    /* the MCAN engine can't auto to get rx payload size, we need set it. */
    g_RxInfoBuf.rxFramePtr = &g_RxFrame;
    Can_ReceiveFifoNonBlocking(EXAMPLE_MCAN, CAN_RX_FIFO0, &g_CanHandle, &g_RxInfoBuf);

    g_TxFrame.Can_TxFrameHead0.xtd  = (uint8_t)FALSE;
    g_TxFrame.Can_TxFrameHead0.rtr  = (uint8_t)CAN_DATA_FRAME;
    g_TxFrame.Can_TxFrameHead1.fdf  = (uint8_t)TRUE;
    g_TxFrame.Can_TxFrameHead1.brs  = (uint8_t)FALSE;
    g_TxFrame.Can_TxFrameHead0.id   = (uint32_t)0x733U << CAN_FRAME_STD_ID_SHIFT;;
    g_TxFrame.data = g_sdu64;
    g_TxFrame.dataSize = CAN_DATASIZE;
    g_TxFrame.Can_TxFrameHead1.dlc = 0x0F;

    g_TxInfoBuf.txFramePtr = &g_TxFrame;
    g_TxInfoBuf.bufferIdx = CAN_TX_BUF_ID_0;
    Can_SendNonBlocking(EXAMPLE_MCAN, &g_CanHandle, &g_TxInfoBuf);

}

static void DealCanData(void)
{
    uint8_t cnt = 0U;

    Delay();

    if((uint8_t)TRUE == g_RxCompleteFlg)
    {
        g_RxCompleteFlg = (uint8_t)FALSE;

        g_TxFrame.Can_TxFrameHead0.xtd  = g_RxFrameBuf.Can_RxFrameHead0.xtd;
        g_TxFrame.Can_TxFrameHead0.rtr  = (uint8_t)CAN_DATA_FRAME;
        g_TxFrame.Can_TxFrameHead1.fdf  = g_RxFrameBuf.Can_RxFrameHead1.fdf;
        g_TxFrame.Can_TxFrameHead1.brs  = g_RxFrameBuf.Can_RxFrameHead1.brs;
        g_TxFrame.Can_TxFrameHead0.id   = g_RxFrameBuf.Can_RxFrameHead0.id;
        g_TxFrame.data = g_RxFrameBuf.data;
        g_TxFrame.dataSize = g_CanGblFdDlcConvDb[g_RxFrameBuf.Can_RxFrameHead1.dlc];
        g_TxFrame.Can_TxFrameHead1.dlc = g_RxFrameBuf.Can_RxFrameHead1.dlc;

        printf("Received Frame ID: 0x%x\r\n", g_RxFrameBuf.Can_RxFrameHead0.id >> CAN_FRAME_STD_ID_SHIFT);
        printf("Received Frame DATA: ");

        while (cnt < g_CanGblFdDlcConvDb[g_RxFrameBuf.Can_RxFrameHead1.dlc])
        {
            printf("0x%x ", g_RxFrameBuf.data[cnt]);
            cnt++;
        }
        
        printf("\r\n\r\n");

        g_TxInfoBuf.txFramePtr = &g_TxFrame;
        g_TxInfoBuf.bufferIdx = CAN_TX_BUF_ID_0;
        if(CAN_API_SUCCESS == Can_SendNonBlocking(EXAMPLE_MCAN, &g_CanHandle, &g_TxInfoBuf))
        {
            memset(g_RxFrameBuf.data, 0, CAN_DATASIZE);
        }
        else
        {
            /* do nothing */
        }
    }
    else
    {
        /* do nothing */
    }
}


/*!
 * @brief       Delay
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
static void Delay(void)
{
    volatile uint32_t delay = (uint32_t)0x8FFFFF;

    while (delay > (uint32_t)0)
    {
        delay -= (uint32_t)1;
    }
}

#if defined (__CC_ARM) || defined (__ICCARM__) || (defined(__ARMCC_VERSION) && (__ARMCC_VERSION >= 6010050))

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @param       *f:  pointer to a FILE that can recording all information
*              needed to control a stream
*
* @retval      The characters that need to be send.
*
* @note
*/
int fputc(int ch, FILE* f)
{
    /* send a byte of data to the serial port */
    Usart_TxData(DEBUG_USART, (uint8_t)ch);

    /* wait for the data to be send  */
    while (Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == 0U)
    {
        /* do nothing */
    }

    return (ch);
}

#elif defined (__GNUC__)

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       ch:  The characters that need to be send.
*
* @retval      The characters that need to be send.
*
* @note
*/
int __io_putchar(int ch)
{
    /* send a byte of data to the serial port */
    Usart_TxData(DEBUG_USART, ch);

    /* wait for the data to be send  */
    while (Usart_ReadStatusFlag(DEBUG_USART, USART_FLAG_TXBE) == RESET);

    return ch;
}

/*!
* @brief       Redirect C Library function printf to serial port.
*              After Redirection, you can use printf function.
*
* @param       file:  Meaningless in this function.
*
* @param       *ptr:  Buffer pointer for data to be sent.
*
* @param       len:  Length of data to be sent.
*
* @retval      The characters that need to be send.
*
* @note
*/
int _write(int file, char* ptr, int len)
{
    int i;
    for (i = 0; i < len; i++)
    {
        __io_putchar(*ptr++);
    }

    return len;
}

#else
#pragma message("Not supported compiler type")
#endif

/**@} end of group CAN_LoopBack_Functions */
/**@} end of group CAN_LoopBack */
/**@} end of group CAN_Examples */
/**@} end of group Examples */
