/*!
 * @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.
 */

/*
* MISRA-C:2012 compliance checks
*
*       main_c_MISRA_REF1
*          Breaks the required Rule 8.13 of MISRA 2012 guidelines,A pointer should point to a const-qualified 
*          type whenever possible
*
*       main_c_MISRA_REF2
*          Breaks the required Rule 17.11 C11 of MISRA 2012 guidelines,A function that never returns should be
*          declared with a _Noreturn function specifier*
*
*/

/* Includes */
#include "Board.h"
#include "g32a10xx.h"
#include "cmsis_os2.h"
#include  <math.h>
#include  <stdio.h>
#include  <stdlib.h>

/** @addtogroup Examples
  @{
  */

/** @addtogroup RTOS_Examples
  @{
  */

/** @addtogroup RTX
  * @{
  */

/** @defgroup RTX_Macros Macros
  * @{
  */

#define DATA_BUF_SIZE       (32U)

/**@} end of group RTX_Macros */


/** @defgroup RTX_Variables Variables
  * @{
  */

/* USART1 receive buffer */
static uint8_t rxDataBufUsart1[DATA_BUF_SIZE] = {0U};
/* USART1 transmit buffer */
static uint8_t txDataBufUsart1[DATA_BUF_SIZE] = {0U};

/* USART2 receive buffer */
static uint8_t rxDataBufUsart2[DATA_BUF_SIZE] = {0U};
/* USART2 transmit buffer */
static uint8_t txDataBufUsart2[DATA_BUF_SIZE] = {0U};

static const osThreadAttr_t THREADSTART_ATTR =
{
    .name = "osRtxStartThread",
    .attr_bits = osThreadDetached,
    .priority = osPriorityHigh4,
    .stack_size = 320,
};

static const osThreadAttr_t THREADLEDTOGGLE_ATTR =
{
    .name = "osRtxLedToggleThread",
    .attr_bits = osThreadDetached,
    .priority = osPriorityHigh2,
    .stack_size = 160,
};

static const osThreadAttr_t THREADUSART_ATTR =
{
    .name = "osRtxUsartThread",
    .attr_bits = osThreadDetached,
    .priority = osPriorityHigh1,
    .stack_size = 160,
};

/* Task handle */
/***  @warning main_c_MISRA_REF1 The object referenced by '%1s' is not modified through it, 
     so '%1s' could be declared with type '%2s' */
static osThreadId_t threadIdStart = NULL;
/***  @warning main_c_MISRA_REF1 The object referenced by '%1s' is not modified through it, 
     so '%1s' could be declared with type '%2s' */
static osThreadId_t threadIdTaskUsart = NULL;
/***  @warning main_c_MISRA_REF1 The object referenced by '%1s' is not modified through it, 
     so '%1s' could be declared with type '%2s' */
static osThreadId_t threadIdTaskLedToggle = NULL;

/**@} end of group RTX_Variables */

/** @defgroup RTX_Functions Functions
  * @{
  */

/* Delay */
static void Delay(uint32_t Count);

/* USART Init */
static void Usart_Init(void);

/* Buffer compare*/
static BOOL Buffer_Compare(const uint8_t* Buf1Ptr, const uint8_t* Buf2Ptr, uint8_t Size);

/* User create task */
static void Task_UserCreate(void);

static void User_TaskInit(void* ParametersPtr);

/* Led toggle task */
static void Task_LedToggle(void* ParametersPtr);

/* Usart test task */
static void Task_UsartTest(void* ParametersPtr);

/*!
 * @brief       Main program
 *
 * @param       None
 *
 * @retval      None
 *
 */
int main(void)
{
    /* Initialize the RTOS Kernel */
    osKernelInitialize();

    /* Create a thread and add it to Active Threads */
    threadIdStart = osThreadNew(&User_TaskInit, NULL, &THREADSTART_ATTR);
    if(threadIdStart == NULL)
    {
        /* Create a thread failed */
        while(1)
        {
            /* do nothing */
        }
    }
    else
    {
        /* nothing */
    }

    /* Start the RTOS Kernel scheduler */
    osKernelStart();

    while (1)
    {
        /* do nothing */
    }
}

/*!
 * @brief       Start task
 *
 * @param       ParametersPtr - passed into the task function as the function parameters
 *
 * @retval      None
 */
/***  @warning main_c_MISRA_REF2 This function doesn't return to the caller despite not 
     being declared as non-returning */
/***  @warning main_c_MISRA_REF1 The object referenced by '%1s' is not modified through it, 
     so '%1s' could be declared with type '%2s' */
static void User_TaskInit(void* ParametersPtr)
{
    const uint16_t usFrequency = 1;
    uint32_t tick;

    /* Configures LED */
    Board_LedInit(LED2);
    Board_LedInit(LED3);

    /* USART Initialization */
    Usart_Init();

    SystemCoreClockUpdate();
    SysTick_Config(SystemCoreClock / 1000U);

    /* User task create */
    Task_UserCreate();

    /* Get the RTOS kernel tick count */
    tick = osKernelGetTickCount();

    (void)ParametersPtr;

    while (1)
    {
        tick += usFrequency;
        osDelayUntil(tick);
    }
}

/*!
 * @brief       usart task
 *
 * @param       ParametersPtr - passed into the task function as the function parameters
 *
 * @retval      None
 */
/***  @warning main_c_MISRA_REF2 This function doesn't return to the caller despite not 
     being declared as non-returning */
/***  @warning main_c_MISRA_REF1 The object referenced by '%1s' is not modified through it, 
     so '%1s' could be declared with type '%2s' */
static void Task_UsartTest(void* ParametersPtr)
{
    BOOL state = TRUE;
    uint32_t timeout = 0U;
    uint32_t i = 0U;

    /* Init txDataBufUsart2 */
    for (i = 0U; i < DATA_BUF_SIZE; i++)
    {
        txDataBufUsart1[i] = (uint8_t)i;
        txDataBufUsart2[i] = (uint8_t)i;
    }

    while (1)
    {
        /** Send Data from USART1 to USART2 */
        timeout = 0U;
        for (i = 0U; i < DATA_BUF_SIZE; i++)
        {
            /* Wait until end of transmission */
            while (Usart_ReadStatusFlag(EVAL_COM1, USART_FLAG_TXBE) == (uint8_t)RESET)
            {
                osDelay(10);
                timeout++;
                if (timeout > 10U)
                {
                    break;
                }
                else
                {
                    /* nothing */
                }
            }

            Usart_TxData(EVAL_COM1, txDataBufUsart1[i]);

            /* Wait until end of reception */
            while (Usart_ReadStatusFlag(EVAL_COM2, USART_FLAG_RXBNE) == (uint8_t)RESET)
            {
                osDelay(10U);
                timeout++;
                if (timeout > 10U)
                {
                    break;
                }
                else
                {
                    /* nothing */
                }
            }

            rxDataBufUsart2[i] = (uint8_t)Usart_RxData(EVAL_COM2);
        }

        /* Verify data */
        state = Buffer_Compare(rxDataBufUsart2, txDataBufUsart1, DATA_BUF_SIZE);

        /* Data is ok then turn off LED3 */
        if (state == TRUE)
        {
            Board_LedOn(LED3);
        }
        else
        {
            Board_LedOff(LED3);
        }

        /* Task blocking time Delay */
        osDelay(1000U);

        timeout = 0U;
        /* Send Data from USART2 to USART1 */
        for (i = 0U; i < DATA_BUF_SIZE; i++)
        {
            /* Wait until end of transmission */
            while (Usart_ReadStatusFlag(EVAL_COM2, USART_FLAG_TXBE) == (uint8_t)RESET)
            {
                osDelay(10U);
                timeout++;
                if (timeout > 10U)
                {
                    break;
                }
                else
                {
                    /* nothing */
                }
            }

            Usart_TxData(EVAL_COM2, txDataBufUsart2[i]);

            /* Wait until end of reception */
            while (Usart_ReadStatusFlag(EVAL_COM1, USART_FLAG_RXBNE) == (uint8_t)RESET)
            {
                osDelay(10U);
                timeout++;
                if (timeout > 10U)
                {
                    break;
                }
                else
                {
                    /* nothing */
                }
            }

            rxDataBufUsart1[i] = (uint8_t)Usart_RxData(EVAL_COM1);
        }

        /* Verify data */
        state = Buffer_Compare(rxDataBufUsart1, txDataBufUsart2, DATA_BUF_SIZE);

        /* Data is ok then turn off LED3 */
        if (state == TRUE)
        {
            Board_LedOn(LED3);
        }
        else
        {
            Board_LedOff(LED3);
        }

        (void)ParametersPtr;
        /* Task blocking time Delay */
        osDelay(1000U);
    }
}

/*!
 * @brief       Led toggle task
 *
 * @param       ParametersPtr - passed into the task function as the function parameters
 *
 * @retval      None
 */
/***  @warning main_c_MISRA_REF2 This function doesn't return to the caller despite not 
     being declared as non-returning */
/***  @warning main_c_MISRA_REF1 The object referenced by '%1s' is not modified through it, 
     so '%1s' could be declared with type '%2s' */
static void Task_LedToggle(void* ParametersPtr)
{
    const uint16_t usFrequency = 200U;
    uint32_t tick;

    /* Get the RTOS kernel tick count */
    tick = osKernelGetTickCount();

    while (1)
    {
        /* Toggle LED2 */
        Board_LedToggle(LED2);

        /* Wait until specified time. */
        tick += usFrequency;

        (void)ParametersPtr;
        osDelayUntil(tick);
    }
}

/*!
 * @brief       User task create
 *
 * @param       None
 *
 * @retval      None
 */
static void Task_UserCreate(void)
{
    threadIdTaskLedToggle = osThreadNew(&Task_LedToggle, NULL, &THREADLEDTOGGLE_ATTR);
    if(threadIdTaskLedToggle == NULL)
    {
        /* Create a thread failed */
        while(1)
        {
            /* do nothing */
        }
    }
    else
    {
        /* nothing */
    }
    
    threadIdTaskUsart = osThreadNew(&Task_UsartTest, NULL, &THREADUSART_ATTR);
    if(threadIdTaskUsart == NULL)
    {
        /* Create a thread failed */
        while(1)
        {
            /* do nothing */
        }
    }
    else
    {
        /* nothing */
    }
}

/*!
 * @brief       Compares two buffers
 *
 * @param       Buf1Ptr:    First buffer to be compared
 *
 * @param       Buf2Ptr:    Second buffer to be compared
 *
 * @param       Size:    Buffer size
 *
 * @retval      Return SET if buf1 = buf2. If not then return RESET
 */
static BOOL Buffer_Compare(const uint8_t* Buf1Ptr, const uint8_t* Buf2Ptr, uint8_t Size)
{
    uint32_t i;
    BOOL retVal = TRUE;

    for (i = 0U; i < Size; i++)
    {
        if (Buf1Ptr[i] != Buf2Ptr[i])
        {
            retVal = FALSE;
            break;
        }
        else
        {
            /* do nothing */
        }
    }

    return retVal;
}

/*!
 * @brief       USARTS Initialization
 *
 * @param       None
 *
 * @retval      None
 */
static void Usart_Init(void)
{
    Board_ComInit(COM1);
    Board_ComInit(COM2);

    Delay(0x7FFFU);

    /* Disable USARTx RXBNE interrput */
    Usart_DisableInterrupt(USART1, USART_INT_RXBNEIE);
    Usart_DisableInterrupt(USART2, USART_INT_RXBNEIE);

    Usart_ClearStatusFlag(USART1, USART_FLAG_RXBNE);
    Usart_ClearStatusFlag(USART2, USART_FLAG_RXBNE);
}

/*!
 * @brief       Delay
 *
 * @param       Count:  delay count
 *
 * @retval      None
 */
static void Delay(uint32_t Count)
{
    volatile uint32_t delay = Count;

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

/**@} end of group RTX_Functions */
/**@} end of group RTX */
/**@} end of group RTOS_Examples */
/**@} end of group Examples */
