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

const char* mqttServer    = "intaluones.co.id";
const int mqttPort        = 1883;
const char* mqttUser      = "mahasiswa";
const char* mqttPassword  = "mahasiswa2024";

WiFiClient espClient;
PubSubClient client(espClient);

const int ledg    = 13;
const int ledy    = 12;
const int ledr    = 14;

int stattopic,statlampu,statpintu;
 
void setup() 
{
  Serial.begin(115200); 

  pinMode(ledg, OUTPUT); 
  pinMode(ledy, OUTPUT); 
  pinMode(ledr, OUTPUT);
 
  WiFi.begin("Wokwi-GUEST", "", 6);
 
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(500);
    Serial.println("Connecting to WiFi..");
  }
  Serial.println("Connected to the WiFi network");
 
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
 
  while (!client.connected()) 
  {
    Serial.println("Connecting to MQTT...");
 
    if (client.connect("ESP8266Client", mqttUser, mqttPassword )) 
    {
      Serial.println("connected");  
    } else
     {
      Serial.print("failed with state ");
      Serial.print(client.state());
      delay(2000);
    }
  }
  // client.publish("esp/test", "hello aku udin"); //Topic name
  stattopic = client.subscribe("sensor");
  //statpintu = client.subscribe("esp/Pintu");
}
 
void callback(char* topic, byte* payload, unsigned int length) 
{
  Serial.print("Message arrived in topic: ");
  Serial.println(topic);
 
  Serial.print("Message:");
  for (int i = 0; i < length; i++) 
  {
    stattopic = (char)payload[i];
    Serial.print((char)payload[i]);
  }
  Serial.println();
  Serial.println("-----------------------");
}
 
void loop() 
{
  //stattopic = client.subscribe("antarmuka/lampu");
  // Serial.println(stattopic);
  
  // if (stattopic == 49) 
  // {
  //   digitalWrite(ledg, 0);
  // }
  // if (stattopic == 50)
  // {
  //   digitalWrite(ledg, 1);
  // }

  // if (stattopic == 51) 
  // {
  //   digitalWrite(ledy, 0);
  // }
  // if (stattopic == 52)
  // {
  //   digitalWrite(ledy, 1);
  // }

  // if (stattopic == 53) 
  // {
  //   digitalWrite(ledr, 0);
  // }
  // if (stattopic == 54)
  // {
  //   digitalWrite(ledr, 1);
  // }
  int i;
  for(i = 0; i <= 10; i++)
  {
    client.publish("sensor", String(i).c_str(), true);
    Serial.println(i);
  }
  //client.publish("antarmuka5aa", "fitri");
  delay(500);
  client.loop(); 
}