#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif

#include "ThingsBoard.h"

#define CURRENT_VIRMWARE_TITLE   "TEST"
#define CURRENT_VIRMWARE_VERSION "1.0.0"

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

#define TOKEN                 "6tKKTUEYD5GP1F0VBKdH" //BUXREKA ACC
#define THINGSBOARD_SERVER    "demo.thingsboard.io"

#define SERIAL_DEBUG_BAUD 115200

WiFiClient espClient;
ThingsBoard tb(espClient);

int status = WL_IDLE_STATUS;

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

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

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  pinMode(34, INPUT);
  pinMode(16, OUTPUT);
  pinMode(17, OUTPUT);
  pinMode(18, OUTPUT);
  pinMode(19, OUTPUT);

  InitWiFi();
}

void loop() {

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

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

// if (digitalRead(34)==0){
//   digitalWrite(16, LOW);
//   digitalWrite(17, LOW);
//   digitalWrite(18, LOW);
//   digitalWrite(19, LOW);
// } else {
//   digitalWrite(16, HIGH);
//   delay(1000);
//   digitalWrite(17, HIGH);
//   delay(1000);
//   digitalWrite(18, HIGH);
//   delay(1000);
//   digitalWrite(19, HIGH); 
// //  delay(1000);
//   delay(10000);
// }

 // Serial.println("Sending Data...");
  // tb.sendTelemetryFloat("PV_Volts", pv_volts);
  // tb.sendTelemetryFloat("PV_Amps", pv_amps);
  // tb.sendTelemetryFloat("POWER", pv_power);
tb.loop();
// tb.loop();
}