#ifndef _MAIN_H
#define _MAIN_H


#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>

#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs.h"
#include "nvs_flash.h"
#include "esp_event_loop.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"
#include "freertos/event_groups.h"
#include "freertos/portmacro.h"
#include "freertos/portable.h"

#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"
#include "lwip/err.h"
#include "lwip/sys.h"

#include "soc/cpu.h"
#include "esp_attr.h"



#include "esp_log.h"
#include "mqtt_client.h"

#include "math.h"

#include "led.h"
#include "mpu.h"
#include "kalman.h"
#include "pwm.h"
#include "timer.h"

#define CONFIG_WIFI_SSID "Gothic"
#define CONFIG_WIFI_PASSWORD "darkness666"
#define CONFIG_BROKER_URL "mqtt://192.168.69.104:1883"

#define M_PI		3.14159265358979323846

static EventGroupHandle_t wifi_event_group;
static esp_mqtt_client_handle_t client;
const static int CONNECTED_BIT = BIT0;
static const char *TAG = "MQTT_EXAMPLE";

int num;
int i = 0;
char str_data[5], str_topic[11];
char flag_topic[11] = {'t','o','d','e','v','/','f','l','a','g','s'};
char ref_topic[9] = {'t','o','d','e','v','/','r','e','f'};

float error[2] = {0.0, 0.0};
float integral[2] = {0.0, 0.0}; 
float reference = 0;
float control_signal = 0.0;

float kp = 10;
float ki = 5;
float kd = 0.00006;
float bc_const = 0.012;

bool device_power_on = false;
bool control_algorithm_on = false;

xSemaphoreHandle control_semaphore = 0;
xSemaphoreHandle binary_flag_semaphore = 0;


static void wifi_init(void);
static esp_err_t mqtt_event_handler(esp_mqtt_event_handle_t event);
static void mqtt_app_start(void);

static void string2ref(char *string, int len, float *ref);

#endif