#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 value,statlampu,statpintu,mentah;
void setup()
{
Serial.begin(115200);
pinMode(ledg, OUTPUT);
pinMode(ledy, OUTPUT);
pinMode(ledr, OUTPUT);
pinMode(2, 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);
}
}
value = client.subscribe("sensor");
}
void callback(char* topic, byte* payload, unsigned int length)
{
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
String receivedMessage = "";
for (int i = 0; i < length; i++)
{
mentah = (char)payload[i];
receivedMessage += (char)payload[i];
}
int value = receivedMessage.toInt();
Serial.println(value);
if(value == 10)
{
for(int a = 0; a<=3; a++)
{
digitalWrite(2, 1);
delay(100);
digitalWrite(2, 0);
delay(100);
}
Serial.println("HADIR");
}
Serial.println("-----------------------");
}
void loop()
{
Serial.println(mentah);
delay(100);
client.loop();
}