#include "config.h"
#include "wlan.h"
#include <Arduino.h>
#include <DHT.h>

#define DHTTYPE DHT22
#define DHTPIN 4
DHT dht(DHTPIN, DHTTYPE);

const int fc28_pin = A0;
const char *config_file_path = "/config.json";
Config *config;
WiFiClient wifi_client;
PubSubClient mqtt_client(wifi_client);

bool check_valid_value(float value) {
  return (!isnan(value) && value >= 0 && value <= 100);
}

void setup() {
  Serial.begin(9600);
  dht.begin();
  config = (Config *)malloc(sizeof(Config));
  if (!load_config_file(config_file_path, config))
    Serial.println("ERROR: The config file could not be loaded");
  connect_wlan(config);
}

void loop() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();
  int analog_val = analogRead(fc28_pin);
  int soil_percentage = map(analog_val, 0, 1023, 0, 100);
  float data[3] = {temperature, humidity, static_cast<float>(soil_percentage)};
  if (check_valid_value(temperature) && check_valid_value(humidity)) {
    mqtt_transfer(mqtt_client, config, data);
  }
  disconnect_mqtt(mqtt_client, config->topic);
  free(config);
  enter_deep_sleep(false, config->sleep_time);
}
