#include "at32f403a_407.h"
#include "soft_test.h"
#include "FreeRTOS.h"
#include "task.h"
#include "digital_input.h"
#include "mux.h"
#include <stdio.h>
#include <math.h>

float sin_signal;
int sin_input = 0;



//
void test_tim_init(void)
{
    crm_clocks_freq_type crm_clocks_freq_struct = {0};
    
    crm_periph_clock_enable(CRM_TMR3_PERIPH_CLOCK, TRUE);

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

    nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
    nvic_irq_enable(TMR3_GLOBAL_IRQn, 5, 0);
       
    tmr_counter_enable(TMR3, TRUE);
    
    tmr_interrupt_enable(TMR3, TMR_OVF_INT, TRUE);
    
    test_sin_input();
    sin_signal = 10*(sin(0.0174533*sin_input) + 1);
}


//
void test_sin_input(void)
{
    sin_input++;
    
    if (sin_input == 361)
        sin_input = 0;
}


void TMR3_GLOBAL_IRQHandler(void)
{
    if (tmr_flag_get(TMR3, TMR_OVF_FLAG) != RESET)
    {
        tmr_flag_clear(TMR3, TMR_OVF_FLAG);
        
        test_sin_input();
        sin_signal = 10*(sin(0.0174533*sin_input) + 1);
        //printf("%i, %f\r\n", sin_input, sin_signal);
    }
}


//
float test_get_signal(void)
{
    return sin_signal;
}


// Генерация тестовых сигналов
void test_signal_task(void *argument)
{
    for (;;)
    {
        vTaskDelay(1000);
        printf("Test signal task\r\n");
    }
}


//
void test_hw_task(void *argument)
{
    for (;;)
    {
#if 0      
        vTaskDelay(1000);
              
        printf("\r\n");
        for (uint8_t i = 0; i < 8; i++)
        {
            printf("Channel: %u, state = %u\r\n", i + 1, di_get(i));
        }
#endif
        
#if 1      
        vTaskDelay(100);
        mux_led_blink();
#endif
        //adc_test();
    }
}



//
void test_gpio(void *params)
{
    (void)params;
    
    for (;;)
    {
        vTaskDelay(100);
        
        //printf("%" PRId64 " \r\n", rtc_get_ms());

        //en_crnt_alrm_in(0x02);
        
        //io_test();
        //out_test();
        //load_test();
        
        //printf("HW rev: %u\r\n", cm_gpio_get_rev());
        //printf("Save mode: %u\r\n", save_mode_get());
    }
}