#include "rtc_battery.h"
#include "FreeRTOS.h"
#include "task.h"
#include <stdio.h>


#define ADV_FACTOR      0.000805

uint16_t bat_voltage;


//
void adc_battery_gpio_init(void)
{
    gpio_init_type gpio_initstructure;
        
    crm_periph_clock_enable(CRM_GPIOA_PERIPH_CLOCK, TRUE);
    crm_periph_clock_enable(CRM_GPIOC_PERIPH_CLOCK, TRUE);
 
    gpio_default_para_init(&gpio_initstructure);
    
    // VBAT RTC
    gpio_initstructure.gpio_mode           = GPIO_MODE_ANALOG;  
    gpio_initstructure.gpio_pins           = GPIO_PINS_4;
    gpio_init(GPIOA, &gpio_initstructure);
    
    // EN_MEAS_V_BAT
    gpio_initstructure.gpio_out_type       = GPIO_OUTPUT_PUSH_PULL;  
    gpio_initstructure.gpio_pull           = GPIO_PULL_NONE;  
    gpio_initstructure.gpio_mode           = GPIO_MODE_OUTPUT;  
    gpio_initstructure.gpio_drive_strength = GPIO_DRIVE_STRENGTH_STRONGER;
    gpio_initstructure.gpio_pins           = GPIO_PINS_6;
    gpio_init(GPIOC, &gpio_initstructure);
}


//
void adc_battery_init(void)
{
    adc_base_config_type adc_base_struct;
    
    adc_battery_gpio_init();
    
    crm_periph_clock_enable(CRM_ADC1_PERIPH_CLOCK, TRUE);
    crm_adc_clock_div_set(CRM_ADC_DIV_2);
    
    nvic_priority_group_config(NVIC_PRIORITY_GROUP_4);
    nvic_irq_enable(ADC1_2_IRQn, 5, 0);
        
    adc_combine_mode_select(ADC_INDEPENDENT_MODE);
    
    adc_base_default_para_init(&adc_base_struct);
    
    adc_base_struct.sequence_mode = TRUE;
    adc_base_struct.repeat_mode = FALSE;
    adc_base_struct.data_align = ADC_RIGHT_ALIGNMENT;
    adc_base_struct.ordinary_channel_length = 1;
    adc_base_config(ADC1, &adc_base_struct);
    
    adc_ordinary_channel_set(ADC1, ADC_CHANNEL_4,  1, ADC_SAMPLETIME_239_5);
    
    adc_ordinary_conversion_trigger_set(ADC1, ADC12_ORDINARY_TRIG_SOFTWARE, TRUE);
    
    adc_dma_mode_enable(ADC1, FALSE);
    adc_tempersensor_vintrv_enable(FALSE);
    
    adc_flag_clear(ADC1, ADC_CCE_FLAG);
    
    adc_interrupt_enable(ADC1, ADC_CCE_INT, TRUE);
    
    adc_enable(ADC1, TRUE);
    adc_calibration_init(ADC1);
    
    while(adc_calibration_init_status_get(ADC1));
    adc_calibration_start(ADC1);
    while(adc_calibration_status_get(ADC1));
}


//
void adc_battery_task(void *params)
{
    for (;;)
    {
        MEAS_VBAT_ENABLE;
        vTaskDelay(100);
        adc_ordinary_software_trigger_enable(ADC1, TRUE);
        vTaskDelay(360000);
    }
}


//
void ADC1_2_IRQHandler(void)
{
    adc_flag_clear(ADC1, ADC_CCE_FLAG);
    bat_voltage = (uint16_t)(adc_combine_ordinary_conversion_data_get()*ADV_FACTOR*1000.0);
    //printf("ADC: %f\r\n", bat_voltage);
    MEAS_VBAT_DISABLE;
}