#include <WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* mqtt_server = "broker.hivemq.com";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

const char* suhu1_topic = "myskill/miot4/suhu1";
const char* suhu2_topic = "myskill/miot4/suhu2";
const char* humidity_topic = "myskill/miot4/humidity";

float temperature1 = 0.0;
float temperature2 = 0.0;
float humidity = 0.0;

void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
  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 callback(char* topic, byte* payload, unsigned int length) {
  // Handle incoming messages here
}

void reconnect() {
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    if (client.connect("ESP32Client")) {
      Serial.println("connected");
      client.subscribe(suhu1_topic);
      client.subscribe(suhu2_topic);
      client.subscribe(humidity_topic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      delay(5000);
    }
  }
}

void setup() {
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop() {
  if (!client.connected()) {
    reconnect();
  }
  client.loop();

  // Simulated sensor data
  temperature1 = random(20, 30);
  temperature2 = random(25, 35);
  humidity = random(40, 60);

  // Publish sensor data
  client.publish(suhu1_topic, String(temperature1).c_str());
  client.publish(suhu2_topic, String(temperature2).c_str());
  client.publish(humidity_topic, String(humidity).c_str());

  delay(5000); // Adjust delay as needed
}