/**
 * @file           : main.c
 * @brief          : Main program body
 *
 * @copyright Copyright 2023 Antaris, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <stdio.h>
#include "main.h"
#include "stm32f7xx_hal.h"
#include "stm32f7xx_hal_rcc.h"
#include "cmsis_os.h"
#include "osal_test.h"
#include "exo_osal.h"
#include "eps_ctrlr.h"
#include "eps.h"
#include "csp_if.h"
#include "exo_stack_example.h"
#include "mfcc_sample_app.h"
#include "schedular.h"
#include "exo_io_al_rtc_common.h"
#include "exo_io_al_sos_timer.h"
#include "comms_csw.h"
#include "xband_main.h"
#include "comms_uhf_main.h"
#include "csp_comms.h"
#include "adcs_csw.h"
#include "tc_tm_mngr.h"
#include "tc_tm_mngr_buffer.h"
#include "obc_main.h"
#include "sensor_driver_intf.h"
#include "exo_ahw_al_dt_common.h"
#include "log_thread.h"
#include "system_init_exit.h"
#include "exo_debug.h"
#include "logger.h"
#include "eps_ctrlr_init.h"
#include "otsu_shutdown.h"
#include "sdr_app_main.h"
#include "gps_app.h"
#ifdef LWIP_THROW_TEST
#include "csp_if_sludp.h"
#endif
#if defined(TEST_LAYER)
#include "utfw_test_main.h"
#endif

extern uint32_t start_time;
static uint32_t prev_time;
extern uint32_t total_time;
extern volatile uint8_t system_error;
uint32_t i =0;
uint32_t mcu_uptime ;

//#define SPI_TO_UART_ENB

#ifdef STM32F769xx
#ifdef SPI_TO_UART_ENB

extern os_sem_handle_ptr intr_semhandle;

void* gpio_j = GPIOJ;
void* gpio_a = GPIOA;
#endif
#endif

/** TBD: Complete stats collection */
#if 0
/** Maximum Number of stats entries */
#define MAX_STATS_ENTRIES 1

/** Maximum stat table length, currently we have 60 tasks, each task will consume 40Bytes
 *  so 40*60 = 2400, kept 3k for now
 *  */
 
#define MAX_STATS_LEN 1024*3

typedef struct task_stats
{
    uint32_t timestamp;
    uint8_t data[MAX_STATS_LEN];
}task_stats;


task_stats PLACE_IN_EXT_RAM_MEM stats_table[MAX_STATS_ENTRIES];
uint8_t stats_idx=0;
#endif

/**
 * @brief Application entry point.
 * @retval int
 */
void app_main(void)
{
	obc_main_init();
#if defined(TEST_LAYER)
        test_task_init();
#endif
	tc_tm_mngr_main();
        health_metric_buffer_main();
        CSP_Setup();
        comms_csw_init();
        comms_uhf_csw_init();
        sdr_app_init();
	
#ifdef SDR_XBAND_XLINK
	xband_init();
#endif

	eps_init();
	//sensors_init();
	adcs_csw_main();
#ifdef LWIP_THROW_TEST
	test_udp_socket();
#endif
	conops_sch_init();
	gps_init();
}

/**
 * @brief Function to add the stats to array
 */
/** TBD */
#if 0
void addTaskStats(void) {

    /** Buffer to store the stats , for 1 task 40Bytes required
     * Refer: https://www.freertos.org/a00021.html#vTaskGetRunTimeStats 
     * */
    stats_table[(stats_idx % MAX_STATS_ENTRIES)].timestamp = 0x00;

    /** Retrieve run-time stats  and store it in array */
    vTaskGetRunTimeStats((char*)&stats_table[(stats_idx++ % MAX_STATS_ENTRIES)].data);
}
#endif
/**
 * @brief Function to return the stats
 */
void obc_get_cpu_load(obc_pck_data *tm_data_info) 
{
    /** To store all the tasks stats */
    TaskStatus_t *pxTaskStatusArray;

    /** Variable to store the number of tasks */
    UBaseType_t uxArraySize;

    /** Variable to store total time */
    uint32_t ulTotalTime;

    /** variable to store the idle tasks percentage */
    uint32_t idleTaskPercentage;
    
    /** Variable to store the cpu utilization */
    float cpuUtilization;
    int i;

    /** Get the number of tasks */
    uxArraySize = uxTaskGetNumberOfTasks();
    
    /** Allocate memory for all the tasks , since RTOS will fill for all tasks */
    pxTaskStatusArray = (TaskStatus_t*)os_malloc( uxTaskGetNumberOfTasks() * sizeof( TaskStatus_t ) );

    /** Memory allocation succeeded */
    if( pxTaskStatusArray != NULL )
    {
        /** - Get the task details */
        uxArraySize = uxTaskGetSystemState( pxTaskStatusArray, uxArraySize, &ulTotalTime);

        /** - Iterate through the list of task and get the IDLE task index */
        for (i = 0; i < uxArraySize; i++) 
        {
            if (strcmp(pxTaskStatusArray[i].pcTaskName, "IDLE") == 0) 
            {
                break;
            }
        }

        /** - For percentage calculations. */      
        ulTotalTime /= 100UL;

        /** - Avoid divide by zero errors. */
        if( ulTotalTime > 0UL )
        {
            /**  - calculate the idle task's percentage */
            idleTaskPercentage = pxTaskStatusArray[i].ulRunTimeCounter / ulTotalTime;

            /**  - Got valid percentage */
            if( idleTaskPercentage > 0UL )
            {
                /** - Calculate CPU utilization by subtracting the idle task percentage from 100% */
                cpuUtilization = 100 - idleTaskPercentage;
            }
            else
            {
                return;
            }
        }
    }
    else
    {
        /** - Malloc failed */
        return;
    }
    /** - Free the allocated memory for stats */
    if(pxTaskStatusArray)
    {
        os_free(pxTaskStatusArray);
    }
    /** If TM data pointer present */
    if(tm_data_info)
    {
        /** - Allocate memory for cpu utilization to store */
        tm_data_info->rx_data = (uint8_t*)os_malloc(sizeof(float));

        /** - Got the memory to fill the cpu utilization informations */
        if(tm_data_info->rx_data)
        {
            /** - clearing out the memory */
            os_memset(tm_data_info->rx_data, 0, sizeof(float));

            /** - Store the CPU utilization in TM data */
            os_memcpy(tm_data_info->rx_data, (char*)&cpuUtilization, sizeof(float));

            /** - Update the data length */
            tm_data_info->rx_data_len = sizeof(float);
        }
        else
        {
            /** Malloc error no memory in heap */
            return;
        }
    }
    else
    {
        // No TM data
        return;
    }

}

/**
 * @brief Application hook to idle task
 */
void vApplicationIdleHook(void)
{
	if(total_time==0xFFFFFFFF)
	{
		total_time = (HAL_GetTick()-start_time);
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wformat"
		DEBUG_CPRINT(("Thread init total time taken : %d ms\n",total_time));

#pragma GCC diagnostic pop
	}
	if(system_error==0)
	{
		exo_wdt_refresh();
	}
if((HAL_GetTick()- prev_time )>= 1000)
{
	prev_time = HAL_GetTick();
	poll_rtc();

}
mcu_uptime = xTaskGetTickCount();
#ifdef DBG_PRNT_EN
	wakeup_print();
#endif

	rtc_print_time();
#ifdef COREBOARD
	if(i++ > 10000000)
	{
		printf_metrix_sts();
		i=0;
	}
#endif
}

#if 0
/**
 * @brief GPIO external interrupt callback.
 */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
#ifdef COREBOARD
	if(GPIO_Pin == GPIO_PIN_6)
#else
#ifdef STM32F769xx
		if(GPIO_Pin == GPIO_PIN_8)
#endif
#endif
		{
			eps_alert_cb();
		}

		if(GPIO_Pin == GPIO_PIN_4)
		{
#ifdef SPI_TO_UART_ENB
#ifdef STM32F769xx
			os_sem_give(intr_semhandle);
#endif
#endif
		}

		else if(GPIO_Pin == GPIO_PIN_7)
		{
			obc_mcp98243_temp_sns_cb();    //core temp  sensor
		}
		else if(GPIO_Pin == GPIO_PIN_8)
		{
			gpio_8_cb();
		}
		else if(GPIO_Pin == GPIO_PIN_0)
		{
			ps_ina230_pwr_sns_cb();      // PAYLOAD_PCB_curr_SEN_ALERT
		}
		else if(GPIO_Pin == GPIO_PIN_2)
		{
			ps_mcp98243_temp_sns_cb();      //Payload_TEM_SEN_INT
		}
		else if(GPIO_Pin == GPIO_PIN_3)
		{
			edge_gpx_intr_cb();
		}
}
#endif
/**
 * @brief RTC alarm event callback.
 */
void HAL_RTCEx_AlarmBEventCallback(RTC_HandleTypeDef *hrtc)
{
	/* Prevent unused argument(s) compilation warning */
	shtdwn_rtc_time_expired_cb();
	/* NOTE : This function Should not be modified, when the callback is needed,
           the HAL_RTC_AlarmBEventCallback could be implemented in the user file
	 */
}


