/*!
 * @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 "g32a10xx_gpio.h"
#include "g32a10xx_usart.h"
#include "g32a10xx_misc.h"
#include "g32a10xx_eint.h"
#include "lin.h"

/** @addtogroup Examples
  @{
*/

/** @addtogroup USART_Examples
  @{
*/

/** @addtogroup USART_LIN_autosync
  @{
*/

/** @defgroup USART_LIN_autosync_Macros Macros
  @{
*/

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

#define DATA_BUF_SIZE       (10)

/**@} end of group USART_LIN_autosync_Macros */

/** @defgroup USART_LIN_autosync_Variables Variables
  @{
*/

static const uint8_t g_sendBufConfig[3][8] =
{
    {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
    {0x11,0x12,0x13,0x14,0x15,0x16,0x17,0x18},
    {0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28}
};

/**@} end of group USART_LIN_autosync_Variables */

/** @defgroup USART_LIN_autosync_Functions Functions
  @{
*/

/* Usart_Delay */
void Usart_Delay(uint32_t count);
uint32_t SysTick_Init(uint32_t Ticks);
uint16_t Lin_GetCurrentSensorValue(void);
void SysTick_Stop(void);
/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 * @note
 */
int main(void)
{
    int i = 0;

    Board_ComInit(COM1);
    Lin_Init();

    printf("\r\nThis example provides a basic USARTx LIN autosync.\r\n");
    while (1)
    {
        Usart_Delay(1000);

        if((uint8_t)0 != g_SlaveReceivedOverFlag)
        {
            g_SlaveReceivedOverFlag = 0;
            printf("Slave mode received data: ");
            for(i = 0;i < 8; i++)
            {
                printf("0x%x ",g_ResponseBuf[i]);
            }
            printf("\r\n");
        }
        else
        {
            /* do nothing */
        }
    }
}

/*!
 * @brief       Lin Pid Received Notification.
 *
 * @param[in]     Pid: protect id
 * @param[in]     FrameIndex: Frame Index
 *
 * @retval      None.
 *
 */
void Lin_PidReceivedNotification(uint8_t Pid, uint8_t FrameIndex)
{
    (void)Pid;
    (void)FrameIndex;
}

/*!
 * @brief       Lin Get Current Sensor Value.
 *
 * @param       None.
 *
 * @retval      Zero.
 *
 */
uint16_t Lin_GetCurrentSensorValue(void)
{
    return 0;
}

void Lin_GetTxDataNotification(uint8_t FrameIdx, uint8_t* DataBufferPtr)
{
    uint16_t sensorVal = 0;
    uint8_t i = 0;
    /* 1. Basic logic: look up table and copy data */
    if(FrameIdx < (sizeof(g_sendBufConfig)/sizeof(g_sendBufConfig[0])))
    {
        for(i = 0u; i < 8u; i++)
        {
            DataBufferPtr[i] = g_sendBufConfig[FrameIdx][i];
        }
    }
    else
    {
        /* nothing */
    }
    /* 2. Extension logic: dynamic data override for specific IDs */
    /* Assume that the frame with FrameIdx equal to 2 is a sensor data frame */
    if (FrameIdx == 3u) 
    {
        sensorVal = Lin_GetCurrentSensorValue();
        /* Dynamically fill the low byte */
        DataBufferPtr[0] = (uint8_t)(sensorVal & 0xFFu);
        /* Dynamically fill the high byte */
        DataBufferPtr[1] = (uint8_t)((sensorVal >> 8u) & 0xFFu);
    }
    else
    {
        /* nothing */
    }
}

/**
 * @brief  Initializes the SysTick timer with a specified tick count.
 * @param  ticks: Number of clock cycles between two consecutive interrupts.
 *                For example, if the system clock is 64MHz, setting this to 64,000 will generate a 1ms interrupt period.
 *                Note: This is a 24-bit value (max 0xFFFFFF).
 * @retval initSts: 0: SysTick Init config success
 *                  1: SysTick Init config fail
 * @note   This function configures the SysTick using the standard CMSIS
 *         SysTick_Config() function. It also explicitly clears the NVIC
 *         pending bit to ensure the timer starts in a clean state, preventing
 *         any premature interrupts caused by residual flags or the
 *         configuration sequence itself.
 */
uint32_t SysTick_Init(uint32_t Ticks)
{
    uint32_t initSts = 0;
    /* Configure the SysTick timer using the standard CMSIS function */
    if (SysTick_Config(Ticks) == 0UL)
    {
        initSts = 0;
        /*
        * Immediately clear any pending interrupt flag that might have been
        * generated during the configuration process or left over from previous state.
        * This ensures the first interrupt occurs strictly after the specified period.
        */
        NVIC_ClearPendingIRQ(SysTick_IRQn);
    }
    else
    {
        initSts = 1;
    }
    return initSts;
}

/*!
 * @brief       Disables the SysTick timer and clears its interrupt.
 *
 * @param       None.
 *
 * @retval      None.
 *
 * @note        Stops the counter, disables the interrupt, and clears any
 *              remaining pending state in the NVIC.
 */
void SysTick_Stop(void)
{
    /* Disable counter and interrupt */
    SysTick->CTRL &= ~(SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk);

    /* Clear residual pending interrupt */
    NVIC_ClearPendingIRQ(SysTick_IRQn);
}

/*!
 * @brief       Usart_Delay
 *
 * @param       count:  delay count
 *
.
 * @retval      None
 *
 * @note
 */
void Usart_Delay(uint32_t count)
{
    volatile uint32_t delay = count;

    while (0u != delay)
    {
        delay = delay - 1u;
    }
}

#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) == (uint8_t)RESET)
    {
        /* 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)
    {
        /* nothing */
    }

    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 USART_LIN_autosync_Functions */
/**@} end of group USART_LIN_autosync */
/**@} end of group USART_Examples */
/**@} end of group Examples */
