#include <WiFi.h>
#include <esp_wifi.h>
#include "DHTesp.h"
#include "ThingsBoard.h"

const int LDR = 34;
const int DHT_PIN = 15;
const float GAMMA = 0.7;
const float RL10 = 50;

DHTesp dhtSensor;

#define CURRENT_FIRMWARE_TITLE    "Suriota01"
#define CURRENT_FIRMWARE_VERSION  "1.0.0"

#define WIFI_SSID           "Wokwi-GUEST"
#define WIFI_PASSWORD       ""

#define TOKEN               "zSssq76nKKHROanIqdED"
// #define TOKEN               "fEqBFKuyDmuKYFk5nSQd"
// #define TOKEN               "RN8tWFXoyIbJGwwJtdnU"

#define THINGSBOARD_SERVER  "thingsboard.cloud"
#define SERIAL_DEBUG_BAUD   115200

WiFiClient espClient;
ThingsBoard tb(espClient);

int status = WL_IDLE_STATUS;

uint8_t newMACAddress[] = {0x30, 0xAE, 0xA5, 0x07, 0x0C, 0x69};
// uint8_t newMACAddress[] = {0x31, 0xAD, 0xA6, 0x08, 0x0E, 0x61};
// uint8_t newMACAddress[] = {0x32, 0xAF, 0xA7, 0x09, 0x0T, 0x65};

void InitWiFi()
{
  Serial.println("Connecting to Suriota WIFI");
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("Connected to AP");
}

void reconnect() {
  status = WiFi.status();
  if ( status != WL_CONNECTED) {
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    while (WiFi.status() != WL_CONNECTED) {
      delay(500);
      Serial.print(".");
    }
    Serial.println("Connected to AP");
  }
}

void setup() {
  Serial.begin(SERIAL_DEBUG_BAUD);
  Serial.println();
  InitWiFi();
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  Serial.print("[OLD] ESP32 Board MAC Address:  ");
  Serial.println(WiFi.macAddress());

  esp_wifi_set_mac(WIFI_IF_STA, &newMACAddress[0]);
  
  Serial.print("[NEW] ESP32 Board MAC Address:  ");
  Serial.println(WiFi.macAddress());
}

void loop() {
  delay(1000);

  if (WiFi.status() != WL_CONNECTED) {
    reconnect();
  }

  if (!tb.connected()) {
    Serial.print("Connecting to: ");
    Serial.print(THINGSBOARD_SERVER);
    Serial.print(" with token ");
    Serial.println(TOKEN);
    if (!tb.connect(THINGSBOARD_SERVER, TOKEN)) {
      Serial.println("Failed to connect");
      return;
    }
  }

  Serial.println("Sending data...");

  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  int analogValue = analogRead(LDR);
  float voltage = analogValue / 1024. * 5;
  float resistance = 2000 * voltage / (1 - voltage / 5);
  float lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

  tb.sendTelemetryFloat("Temperature01", data.temperature);
  tb.sendTelemetryFloat("Humidity01", data.humidity);
  tb.sendTelemetryFloat("Lux01", lux);

  Serial.print(data.temperature);
  Serial.print(",");
  Serial.print(data.humidity);
  Serial.print(",");
  Serial.println(lux);

  tb.loop();
}