#include "at32f403a_407.h"
#include "tim_delay.h"
#include "mux.h"


static bool tx_enable = false;


//
void mb_helper_tim_init(uint32_t baudrate)
{
    float foo;
    
    foo = 1.0/((float)baudrate / 11.0);
    foo *= 2000.0; // время в мс (длительность в два символа)
    
    crm_clocks_freq_type crm_clocks_freq_struct = {0};
    
    crm_clocks_freq_get(&crm_clocks_freq_struct);
    
    nvic_irq_disable(TMR6_GLOBAL_IRQn);
    
    crm_periph_clock_enable(CRM_TMR6_PERIPH_CLOCK, TRUE);

    tmr_base_init(TMR6, (uint32_t)(foo * 1000) - 1, (crm_clocks_freq_struct.ahb_freq / 1000000) - 1);
    tmr_cnt_dir_set(TMR6, TMR_COUNT_UP);
    
    NVIC_ClearPendingIRQ(TMR6_GLOBAL_IRQn);
    nvic_irq_enable(TMR6_GLOBAL_IRQn, 5, 0);
}


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


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


//
void mb_helper_set_tx_state(bool state)
{
    tx_enable = state;
}


//
void TMR6_GLOBAL_IRQHandler(void)
{
    if(tmr_flag_get(TMR6, TMR_OVF_FLAG) != RESET)
    {
        tmr_flag_clear(TMR6, TMR_OVF_FLAG);
        if (tx_enable) {
            usart_interrupt_enable(USART3, USART_TDBE_INT, TRUE);
            leds[TX_R].state = LED_ON;
        }
        else {
            gpio_bits_reset(GPIOD, GPIO_PINS_10);
            leds[TX_R].state = LED_OFF;
        }
        mb_helper_tim_disable();
    }
}

