#include <WiFi.h>
#include <WiFiClient.h>
#include <PubSubClient.h>
//#define Green_LED 18
//#define Yellow_LED 19
//#define Red_LED 23
int ledPin = 18; //the number of the LED pin
int ledState = LOW; //ledState used to set the LED
long previousMillis = 0; //will store last time LED
int interval = 1000;
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
//Initializes the espClient
WiFiClient espClient;
PubSubClient client(espClient);
const char* espClientName = "esp32Client_yourInitial";
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
}
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 == " ")
{
// There is no topic and messages to process at this moment
}
}
void setup()
{
// put your setup code here, to run once:
Serial.begin(115200);
pinMode(ledPin, OUTPUT);
setup_wifi();
setup_MQTT();
}
void loop()
{
// put your main code here, to run repeatedly:
if ( !client.connected() )
{
connectMQTT();
}
client.loop();
}