#include <sys/param.h>
#include <freertos/FreeRTOS.h>
#include "freertos/task.h"
#include "esp_log.h"
#include "driver/gpio.h"

#include "temp_sensor.h"
#include "lm75a.h"

#define MAX_SENSORS 5
#define MEASURE_PERIOD 10000 // 10s
#define MEASURE_ERR_THRESHOLD 3

static const char *TAG = "temp_sensor";

static uint8_t sensor_count = 0;

static int16_t low_temp = 0;

static int high_temp = 0;

static uint8_t measure_err_count = 0;

static void temp_sensor_task_func(void *param)
{
    while (true)
    {
        high_temp = lm75a_read_temperature(0);

        vTaskDelay(pdMS_TO_TICKS(MEASURE_PERIOD));
    }
}

void temp_sensor_init(void)
{

    ESP_LOGW(TAG, "temp_sensor_init");

    lm75a_init();

    xTaskCreate(temp_sensor_task_func, "temp_sensor_task", 5 * 1024, NULL, 2, NULL);
}

uint8_t temp_sensor_get_count(void)
{
    return sensor_count;
}

int16_t temp_sensor_get_low(void)
{
    return low_temp;
}

int temp_sensor_get_high(void)
{
    return high_temp;
}

bool temp_sensor_is_error(void)
{
    return sensor_count == 0 || measure_err_count > MEASURE_ERR_THRESHOLD;
}