#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
char led_red = 23;
char led_yellow = 19;
char led_green = 18;
char led_red_state = LOW;
long led_red_previous_millis = 0;
int led_red_interval = 1000;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "maymaychia"; // yourStudentID must be unique
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 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 == "chia/Living_room/led_red")
{
Serial.print("Changing GREEN LED to ");
if (messageTemp == "Off")
{
digitalWrite(led_green, LOW);
Serial.print("Off");
}
else if (messageTemp == "On")
{
digitalWrite(led_green, HIGH);
Serial.print("On");
}
}
}
void MQTTSubscribe()
{
client.subscribe("chia/Living_room/led_red");
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}
void setup()
{
Serial.begin(9600);
delay(5000);
pinMode(led_red, OUTPUT);
pinMode(led_yellow, OUTPUT);
pinMode(led_green, OUTPUT);
setup_wifi();
setup_MQTT();
}
void loop()
{
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
long current_millis = millis();
if (current_millis - led_red_previous_millis >= led_red_interval)
{
led_red_previous_millis = current_millis;
if(led_red_state == LOW)
{
led_red_state =HIGH;
client.publish("chia/Living_room/led_red","On");
}
else
{
led_red_state = LOW;
client.publish("chia/Living_room/led_red","Off");
}
digitalWrite(led_red, led_red_state);
}
}