/* Lab Trial Test 1
* Name: KOH XIANG LING
* Class: DEM1
* Date: 10 JAN 2025
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
const char* ssid = "Wokwi-GUEST"; // Given by Wokwi
const char* password = ""; // no password
const char* hostname = "broker.hivemq.com"; // MQTT broker address that we are connecting
int GLEDState = 1;
long GpreviousMillis = 0;
int Ginterval = 1000;
int RLEDState = 1;
long RpreviousMillis = 0;
int Rinterval = 2000;
//Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_koh1";
int PORTNUM = 1883;
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 setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void MQTTSubscribe()
{
// There is no topics to subscribe at this moment
client.subscribe("IoT/8096378B");
}
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];
}
if (topic == "IoT/8096378B")
{
Serial.print("Changing room LED to ");
if (messageTemp == "Off")
{
digitalWrite(19, HIGH);
Serial.print("Off");
}
else if (messageTemp == "On")
{
digitalWrite(19, LOW);
Serial.print("On");
}
}
}
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(18, OUTPUT);
pinMode(23, OUTPUT);
pinMode(19, OUTPUT);
setup_wifi();
setup_MQTT();
}
void loop()
{
// put your main code here, to run repeatedly:
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
long GcurrentMillis = millis();
if ( GcurrentMillis-GpreviousMillis >= Ginterval)
{
GpreviousMillis = GcurrentMillis;
if (GLEDState == LOW)
{
GLEDState = HIGH;
}
else
{
GLEDState = LOW;
}
digitalWrite(18, GLEDState);
}
long RcurrentMillis = millis();
if ( RcurrentMillis-RpreviousMillis >= Rinterval)
{
RpreviousMillis = RcurrentMillis;
if (RLEDState == LOW)
{
RLEDState = HIGH;
client.publish ("IoT/8096378B", "Off");
}
else
{
RLEDState = LOW;
client.publish ("IoT/8096378B", "On");
}
digitalWrite(23, RLEDState);
}
}