#include "misc.h"
#include "user_misc.h"
#include "button.h"
#include "ltc1867.h"
#include "modbus.h"
#include "filter.h"
#include "concentration.h"
#include "ltc2640.h"
#include "ms5611.h"
#include "adc.h"
#include "cali.h"
#include "debug.h"
#include "cli.h"
#include "calc.h"
#include "stm32f4xx_rcc.h"

uint32_t system_tick_cnt;

void system_tick_init(void)
{
    RCC_ClocksTypeDef rcc_clocks;

    system_tick_cnt = 0;
    RCC_GetClocksFreq(&rcc_clocks);
    SysTick_CLKSourceConfig(SysTick_CLKSource_HCLK);
    SysTick_Config(rcc_clocks.HCLK_Frequency / 1000);
}

void device_init(void)
{
    flag.filter = data_ltc1867.calc_flag;
    flag.concentration = flag.filter;
    flag.gas_fault = 0xFFFFFFFF;
}

void system_init(void)
{
    gas_id_init();
    concentration_init();
    cali_update_from_flash();
    led_init(LED1 | LED2);
    heat_init();
    button_init();
    ltc1867_init();
    modbus_init();
    filter_init();
    adc_init();
    cali_init();
    debug_init();
    cli_init();
    system_tick_init();
    device_init();
    ltc2640_init();
    ms5611_init();
    calc_quadratic_fit_init(CALC_POINTS);
    led_det_temperature_init();
}

int main(void)
{
    system_init();
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_4);
    SCB->VTOR = 0x08020000;
    __enable_irq();
    while (1) {
        modbus_loop();
        led_loop();
        filter_loop();
        concentration_loop();
        adc_loop();
        led_det_temperature_loop();
        led_sig_loop();
        cli_loop();
        ltc2640_loop();
        ms5611_loop();
        button_loop();
    }
    return 0;
}

void SysTick_Handler(void)
{
    system_tick_cnt++;
}
