#include <WiFi.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
#include "DHTesp.h"

const int DHT_PIN  = 15;            // BRYAN TEGAR SYACH
const int Potensio = 34;            // 2070231017 - A1 - IOT

DHTesp dhtSensor;

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "test.mosquitto.org";

WiFiClient espClient;
PubSubClient client(espClient);
long randNumber;
//StaticJsonDocument<256> doc;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }  

  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    String clientId = "mqtt-explorer-c9694758";
    clientId += String(random(0xffff), HEX);
    if (client.connect(clientId.c_str())) {
      Serial.println("Connected");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  pinMode(Potensio, INPUT);
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, 1883);
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}

void loop() {
  float Nilai = analogRead(Potensio);
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

    String temp = String(data.temperature, 2);
    //String datastr = String(data);
    Serial.print("Temperature: ");
    Serial.println(temp);
    client.publish("User1/Temp", temp.c_str());
    
    String hum = String(data.humidity, 1);
    //String datastr2 = String(data2);
    Serial.print("Humidity: ");
    Serial.println(hum);
    client.publish("User1/Hum", hum.c_str());
    
     
    String POTENSIO = String(Nilai, 1);
    //String datastr2 = String(data2);
    Serial.print("Potensio: ");
    Serial.println(Nilai);
    client.publish("User1/Poten", POTENSIO.c_str());

    StaticJsonDocument<256> doc;
    JsonArray datajson = doc.createNestedArray("datajson");
    datajson.add(temp);
    datajson.add(hum);
    datajson.add(POTENSIO);
    char out[128];
    int b =serializeJson(doc, out);
    boolean dataout= client.publish("User1/Data", out);
    
    Serial.println("Data Terkirim");
  delay(2000);
}