/* Lab Trial Test 1
* Name: Eunice Ocana Santamina
* Class: DEEC1(B)
* Date: 06/07/24
*/
#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
int LEDState = 1;
int LEDState2 = 1;
long previousMillis = 0;
long previousMillis2 = 0;
int interval = 1000;
int interval2 = 2000;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* hostname = "broker.hivemq.com";
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_2198663T"; // 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 setup()
{
pinMode(18,OUTPUT);
pinMode(19,OUTPUT);
pinMode(23,OUTPUT);
Serial.begin(9600);
delay(5000);
setup_wifi();
setup_MQTT();
}
void loop()
{
long currentMillis = millis();
if ( currentMillis - previousMillis >= interval)
{
previousMillis = currentMillis; // save the last time you blinked the LED
if (LEDState == LOW)
{
LEDState = HIGH;
}
else
{
LEDState = LOW;
}
}
if ( currentMillis - previousMillis2 >= interval2)
{
previousMillis2 = currentMillis; // save the last time you blinked the LED
if (LEDState2 == LOW)
{
LEDState2 = HIGH;
client.publish("IoT/10145291", "Off");
}
else
{
LEDState2 = LOW;
client.publish("IoT/10145291", "On");
}
}
digitalWrite(18, LEDState);
digitalWrite(23, LEDState2);
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
}
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 == "IoT/10145291")
{
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 MQTTSubscribe()
{
client.subscribe("IoT/10145291");
}
void setup_MQTT()
{
client.setServer(hostname, PORTNUM);
client.setCallback(callback);
}