#include <string.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdlib.h>

#include <main.h>
#include <usart.h>
#include <adc.h>
#include <spi.h>

#include <PontCoopScheduler.h>

#include <show.h>
#include <loopCtrl.h>
#include <mbusComm.h>
#include <logger.h>
#include <frontend.h>
#include <eeprom.h>
#include <wizHelper.h>
#include <mqttComm.h>
#include <cmdHandler.h>
#include <oled.h>
#include <config.h>


void my_setup_1() {
    schInit();
    logInit();
    showInit();
}

void my_errorHandler() {
    show(LED_RED, ON);
}


void my_setup_2() {
    show(LED_RED, OFF);
    show(LED_GREEN, BLINK);
    logMsg("Application starting");

    oledInit();
    oledClearAllScreens();
    oledSetActiveScreen(OLED_SCREEN0);
    oledPrint(OLED_SCREEN0, "App starting");

    eepromInit();
    oledPrint(OLED_SCREEN0, "eeprom init");
    
    configInit();
    oledPrint(OLED_SCREEN0, "config init");

    wizInit();
    oledPrint(OLED_SCREEN0, "network init");

    mqttCommInit();
    oledPrint(OLED_SCREEN0, "mqtt init");
    cmdHandlerInit();
    oledPrint(OLED_SCREEN0, "cmdhandler init");

    frontendInit();
    oledPrint(OLED_SCREEN0, "frontend init");

    mbusCommInit();
    oledPrint(OLED_SCREEN0, "Meterbus init");
    oledPrint(OLED_SCREEN0, "App running");
}

void my_loop() {
    // show(DEBUG_2, TOGGLE);

    schExec();

#ifndef LOGGER_OUTPUT_BY_INTERRUPT
    logExec();
#endif //LOGGER_OUTPUT_BY_INTERRUPT

    mbusCommExec();
}

void SYSTICK_Callback() {
    schUpdate();
}

void HAL_GPIO_EXTI_Callback(uint16_t pin) {
    if (pin == Loop_Status_Pin) {
        loopStatusCallback();
    }
}

void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef* hadc) {
    if (hadc == &frontendAdc) {
        frontendAdcCallback(hadc);   
    }
}

void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart) {
#ifdef LOGGER_OUTPUT_BY_INTERRUPT   
    if (huart == &debugUart) {
        debugTxCpltCallback(huart);
    }
#endif //LOGGER_OUTPUT_BY_INTERRUPT    
}

void HAL_SPI_TxCpltCallback(SPI_HandleTypeDef *hspi) {
    if (hspi == &eepromSpi) {
        eepromSpiTxCpltCallback(hspi);
    }
}
