#include "at32f403a_407.h"
#include "FreeRTOS.h"
#include "task.h"
#include "port.h"
#include "mb.h"
#include "mbport.h"
#include "mux.h"
#include <stdbool.h>


static void prvvTIMERExpiredISR( void );



BOOL xMBPortTimersInit( USHORT usTim1Timerout50us )
{
    crm_clocks_freq_type crm_clocks_freq_struct = {0};
    
    crm_clocks_freq_get(&crm_clocks_freq_struct);
    
    nvic_irq_disable(TMR7_GLOBAL_IRQn);
    
    crm_periph_clock_enable(CRM_TMR7_PERIPH_CLOCK, TRUE);

    tmr_base_init(TMR7, (usTim1Timerout50us * 50) - 1, (crm_clocks_freq_struct.ahb_freq / 1000000) - 1);
    tmr_cnt_dir_set(TMR7, TMR_COUNT_UP);
    
    NVIC_ClearPendingIRQ(TMR7_GLOBAL_IRQn);
    nvic_irq_enable(TMR7_GLOBAL_IRQn, 5, 0);
  
    return TRUE;
}


/* Create an ISR which is called whenever the timer has expired. This function
 * must then call pxMBPortCBTimerExpired( ) to notify the protocol stack that
 * the timer has expired.
 */
static void prvvTIMERExpiredISR( void )
{
    ( void )pxMBPortCBTimerExpired(  );
}


//
void TMR7_GLOBAL_IRQHandler(void)
{
    if(tmr_flag_get(TMR7, TMR_OVF_FLAG) != RESET)
    {
      tmr_flag_clear(TMR7, TMR_OVF_FLAG);

      vMBPortSetWithinException(TRUE);
      prvvTIMERExpiredISR();
      leds[RX_G].state = LED_OFF;
      vMBPortSetWithinException(FALSE);
    }
}


//
void vMBPortTimerClose( void )
{
    tmr_interrupt_enable(TMR7, TMR_OVF_INT, FALSE);
    tmr_counter_enable(TMR7, FALSE);
}

//
void vMBPortTimersEnable()
{
    tmr_flag_clear(TMR7, TMR_OVF_FLAG);
    tmr_interrupt_enable(TMR7, TMR_OVF_INT, TRUE);
    tmr_counter_value_set(TMR7, 0);
    tmr_counter_enable(TMR7, TRUE);  
}

//
void vMBPortTimersDisable()
{
    tmr_flag_clear(TMR7, TMR_OVF_FLAG);
    tmr_interrupt_enable(TMR7, TMR_OVF_INT, FALSE);
    tmr_counter_value_set(TMR7, 0);
    tmr_counter_enable(TMR7, FALSE);
}

//
void vMBPortTimersDelay( USHORT usTimeOutMS )
{
    vTaskDelay( usTimeOutMS / portTICK_RATE_MS );
}
