#include "uptime.h"
#include "rtc.h"
#include "io_utils.h"
#include "analog_input.h"
#include <stdio.h>


uint32_t uptime = 0;
uint32_t rtc_unix = 0;

//
void get_uptime(uint32_t *value)
{
    *value = uptime;
}


//
void uptime_init(void)
{
    crm_clocks_freq_type crm_clocks_freq_struct = {0};
    
    crm_periph_clock_enable(CRM_TMR10_PERIPH_CLOCK, TRUE);

    crm_clocks_freq_get(&crm_clocks_freq_struct);
    tmr_base_init(TMR10, 9999, (crm_clocks_freq_struct.ahb_freq / 10000) - 1);
    tmr_cnt_dir_set(TMR10, TMR_COUNT_UP);
        
    tmr_flag_clear(TMR10, TMR_OVF_FLAG);

    nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
    nvic_irq_enable(TMR1_OVF_TMR10_IRQn, 5, 0);
       
    tmr_counter_enable(TMR10, TRUE);
    
    tmr_interrupt_enable(TMR10, TMR_OVF_INT, TRUE);
}


void TMR1_OVF_TMR10_IRQHandler(void)
{
    if (tmr_flag_get(TMR10, TMR_OVF_FLAG) != RESET)
    {
        tmr_flag_clear(TMR10, TMR_OVF_FLAG);
        uptime++;
        rtc_unix = RTC_GetUnixTime();
        
#if defined (MDIO_88) || (MAO_4)
        save_mode_set_with_counter();
#endif        
        
#if defined (MAI_12)        
        ai_alarm_tim_handler();
#endif
    }
}

