/*
 * BoardInit.c
 *
 *  Created on: Nov 7, 2025
 *      Author: tummalanr
 */





#include <inttypes.h>
#include "ti_drivers_open_close.h"
#include "ti_board_open_close.h"
#include "FreeRTOS.h"
#include "event_groups.h"

#include "AppGlobal.h"
#include "BoardInit.h"
#include "BoardInitExtern.h"

#include "ShmDataSyncExterns.h"
#include "CIPCoreExterns.h"




AppRET_T CheckRunningCoreId(void)
{
    CSL_ArmR5CPUInfo cpuInfo;

    /* Get Core ID Info */
    CSL_armR5GetCpuID(&cpuInfo);
    if( (cpuInfo.grpId != (uint32_t)CSL_ARM_R5_CLUSTER_GROUP_ID_1 ) || (cpuInfo.cpuID != CSL_ARM_R5_CPU_ID_0) ) /* R5SS1-0 */
    {
        #ifdef Debug_Verbose2
            DebugP_log("[CAN]Application Running On Wrong Core!!!\r\n");
        #endif

        //App_errorHandler(AppExecCore_Err);

        return AppExecCore_Err;
    }

    return AppRET_OK;
}

/*!
 *  <!-- Description: -->
 *
 *  \brief
 *  Creates main application Monitor_Events.
 *  Initialize  the Monitoring  events used in main App thread.
 *
 *  <!-- Parameters and return values: -->
 *  \param[in]  None.
 *  \return     None.
 */
void Init_AppMonitor_Events(void)
{
    //Create Events For Main App Monitor  Tasks
    xAppMonitorEventGroup = xEventGroupCreate();

    //Create Events For Checking App Status (LSS Complete/ CIP Sync Completed/SysConfig Updated) in Tasks
    xAppStatusEventGroup = xEventGroupCreate();

    xEventGroupClearBits( xAppStatusEventGroup, (const EventBits_t) ( AppStsEvntGrpLSSComplete_BIT
                                                                    | AppStsEvntGrpCIPSyncomplete_BIT
                                                                    | AppStsEvntGrpSysConfigUpd_BIT) );
    return;
}


/*!
 *  <!-- Description: -->
 *
 *  \brief
 *  Creates main application thread.
 *  Initialize GPIO's, CAN, Shared Memory And RPMessage for IPC
 *
 *  <!-- Parameters and return values: -->
 *  \param[in]  None.
 *  \return     AppRET_T.
 *              AppRET_OK   : On Success.
 *              Error Code  : On Failure.
 */
AppRET_T MBNBoard_Process_Init(void)
{
    AppRET_T sts;


    /*GPIOS from Group-1 Boards. GPIO_POS_DETECTION_OUT(B10)  GPIO_POS_DETECTION_IN(A11)*/
    /* Get address after translation translate*/
    mcugpioBaseAddr_posout = (uint32_t) AddrTranslateP_getLocalAddr(MCUGPIO0_21_POSDETOUT_BASE_ADDR);
    mcuposout_pinNum       = MCUGPIO0_21_POSDETOUT_PIN;
    mcugpioBaseAddr_posin  = (uint32_t) AddrTranslateP_getLocalAddr(MCUGPIO0_20_POSDETIN_BASE_ADDR);
    mcuposin_pinNum        = MCUGPIO0_20_POSDETIN_PIN;

    /*GPIO Direction selection*/
    GPIO_setDirMode(mcugpioBaseAddr_posout, MCUGPIO0_21_POSDETOUT_PIN, MCUGPIO0_21_POSDETOUT_DIR);
    GPIO_setDirMode(mcugpioBaseAddr_posin, MCUGPIO0_20_POSDETIN_PIN, MCUGPIO0_20_POSDETIN_DIR);

    /*Write GPIO-59(GPIO_POS_DETECTION_OUT) Low value*/
    GPIO_pinWriteLow(mcugpioBaseAddr_posout, mcuposout_pinNum);

    /*Init Shared Memory Data Process Tasks req / resp from different Applications(i.e CIP / LCD / Webserver etc).*/
    sts =  DataSync_ProcessInit();
    if(sts != AppRET_OK)
    {
        #ifdef Debug_Verbose2
            DebugP_log("SharedMemSyncInit Error!!!\r\n");
        #endif
        canmbnposterr |= MBN_CANCore_DataSynchInitErr;
        //App_errorHandler(sts);
        return sts;
    }
    #ifdef Debug_Verbose2
        DebugP_log("[[CAN]%s After DataSync_ProcessInit [%" PRId64 " ms]\r\n",__func__,(ClockP_getTimeUsec()/1000u));
    #endif

    /*Init CIP IPC Related Tasks.*/
    sts =  CIPDataSync_IPCProcessInit();
    if(sts != AppRET_OK)
    {
        #ifdef Debug_Verbose2
            DebugP_log("CIPDataSyncInit Error!!!\r\n");
        #endif
        canmbnposterr |= MBN_CANCore_CIPSynchInitErr;
        //App_errorHandler(sts);
        return sts;
    }
    #ifdef Debug_Verbose2
        DebugP_log("[[CAN]%s After CIPDataSync_IPCProcessInit [%" PRId64 " ms]\r\n",__func__,(ClockP_getTimeUsec()/1000u));
    #endif

    return AppRET_OK;
}

/*!
 *  <!-- Description: -->
 *
 *  \brief
 *  Function implementing the BoardMain_initTask.
 *
 *  \details
 *  <br
 *  Calls Api's for MBN Board Peripheral's Initialization. Create's Application Monitor Events.
 *  Waits in Endless Loop For Application Close Event.
 *
 * @param args  : Not used
 * @retval      : AppRET_T.
 *              AppRET_OK   : On Success.
 *              Error Code  : On Failure.
 */
AppRET_T  BoardMain_init(void *args)
{
        AppRET_T sts = AppRET_OK;

        /* Open drivers to open the UART driver for console */
        Drivers_open();
        Board_driversOpen();

        //Create Appl Monitor events
        Init_AppMonitor_Events();

        //Check Core Id
        sts = CheckRunningCoreId();
        if(sts != AppRET_OK) {
            return sts;
        }

        //Init HW timer
        sts = App_Timer_Init();
        if( sts != AppRET_OK ) {
            //return sts;
        }

        //Init Board Pheripherals,Stack and Tasks
        sts = MBNBoard_Process_Init();
        if(sts != AppRET_OK) {
            return sts;
        }

        #ifdef Debug_Verbose2
            DebugP_log("[CAN]%s sts[%d]\r\n",__func__,sts);
        #endif

        return sts;
}


/*!
 *  <!-- Description: -->
 *
 *  \brief
 *  Function implementing the BoardMain_close.
 *
 *  \details
 *  <br
 *   Close all Board Drivers.
 *
 * @param args  : Not used
 * @retval      : None
 */

void  BoardMain_close(void *args)
{

    #ifdef Debug_Verbose
       DebugP_log("[CAN]%s\r\n",__func__);
    #endif

    Board_driversClose();
    Drivers_close();

    return;
}

/*later create oneshot*/

/*!
 *  @brief GPIO Position Trigger function.
 *  @param None
 *  @retval None
*/
void gpio_position_trigger(void)
{

    /*Write GPIO-59(CONFIG_GPIO1_59_POS_OUT_PIN) High value*/
    GPIO_pinWriteHigh(mcugpioBaseAddr_posout, mcuposout_pinNum);
}

/**
 *  @brief GPIO Position Read function.
 *  @param None
 *  @retval  GPIO pin Status.
*/
uint8_t gpio_position_read(void)
{
    uint8_t     sts = 0u;
    volatile    uint32_t posval = 0u;

    /*Read GPIO-58(GPIO_POS_DETECTION_IN) value*/
    posval = GPIO_pinRead(mcugpioBaseAddr_posin, mcuposin_pinNum);
    if(posval != 0u) {
        sts = 1u;
    }

    return sts;
}

