#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "stanleyyeo9165"; // yourStudentID must be unique
int PORTNUM = 1883;
int ledPin = 23;
int ledPin2 = 18;
long previousMillis = 0;
long interval = 1000;
int state = 0;
long previousMillis2 = 0;
long interval2 = 500;
int state2 = 0;
long previousMillisY = 0;
long intervalY = 500;
long previousMillisA = 0;
long intervalA = 500;
void setup_wifi()
{
WiFi.begin(ssid, password);
while(WiFi.status() != WL_CONNECTED )
{
delay(1000);
Serial.print(".");
}
Serial.println();
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("Given IP by the router to ESP32 is ");
Serial.println(WiFi.localIP());
}
void connectMQTT()
{
while(!client.connected() )
{
Serial.println("Connecting to MQTT ...");
if (client.connect(espClientName) ) //, mqttUser, mqttPassword) )
{
Serial.println("Connected");
MQTTSubscribe();
}
else
{
Serial.print("Failed with state ");
Serial.print(client.state() );
delay(2000);
}
}
}
void callback(String topic, byte* payload, unsigned int length)
{
String messageTemp;
Serial.print("Message received in topic: ");
Serial.print(topic);
Serial.print(" length is: ");
Serial.println(length);
Serial.print("Data received from broker: ");
for (int i = 0; i<length; i++)
{
Serial.print( (char)payload[i] );
messageTemp += (char)payload[i];
}
/// Handle your topics and payload here
// Example
if (topic == "LT51G/9024973R/LED")
{
Serial.print("Changing room LED to ");
if (messageTemp == "Off")
{
digitalWrite(18, HIGH);
Serial.print("Off");
}
else if (messageTemp == "On")
{
digitalWrite(18, LOW);
Serial.print("On");
}
}
}
void MQTTSubscribe()
{
// Subsccribe to your topics here
client.subscribe("LT51G/9024973R/LED");
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void setup()
{
Serial.begin(115200);
Serial.println("Hello, ESP32!");
pinMode(23, OUTPUT);
pinMode(18, OUTPUT);
setup_wifi();
setup_MQTT();
}
void loop()
{
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
//client.publish("LT51G/9024973R/LED","On");
//delay(1000);
//client.publish("LT51G/9024973R/LED","OFF");
//delay(1000);
long currentMillis = millis();
if (currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis;
if (digitalRead(ledPin) == HIGH)
{
digitalWrite(ledPin, LOW);
}
else
{
digitalWrite(ledPin, HIGH);
}
}
long currentMillis2 = millis();
if (currentMillis2 - previousMillis2 >= interval2)
{
previousMillis2 = currentMillis2;
if (state2 == 0)
{
state2 = 1;
client.publish("LT51G/9024973R/LED/yourLT/LED","on");
}
else
{state2 = 0;
client.publish("LT51G/9024973R/LED/yourLT/LED","off");
}
}
}