/* ESP32 HTTP IoT Server Example for Wokwi.com
https://wokwi.com/projects/320964045035274834
To test, you need the Wokwi IoT Gateway, as explained here:
https://docs.wokwi.com/guides/esp32-wifi#the-private-gateway
Then start the simulation, and open http://localhost:9080
in another browser tab.
Note that the IoT Gateway requires a Wokwi Club subscription.
To purchase a Wokwi Club subscription, go to https://wokwi.com/club
*/
#include"WiFi.h"
#include <PubSubClient.h>
const char* mqttServer="broker.hivemq.com";
const char* ssid="Wokwi-Guest";
const char* password="";
int port=1883;
char clientid[50];
//#define SSID "Wokwi-Guest"
//#define PASSWORD ""
WiFiClient espClient;
PubSubClient client(espClient);
void setup(void) {
//put your setup code here,to run once:
Serial.begin(115200);
Serial.println("Hello,ESP32!");
Serial.print("Connecting to");
Serial.println(ssid);
wifiConnect();
client.setServer(mqttServer,port);
//client.setCallback(callback);
}
void loop(){
if(!client.connected())
{
mqttReconnect();
}
else
{
client.publish("esp32-pub","data received");
}
client.loop();
}
void wifiConnect()
{
WiFi.mode(WIFI_STA);
WiFi.begin(ssid,password);
while(WiFi.status()!=WL_CONNECTED)
{
delay(500);
Serial.println(",");
}
}
void mqttReconnect(){
while(!client.connected()){
Serial.print("Attempting MQTT connection...");
long r=random(1000);
sprintf(clientid,"fcs-clientid-%d",r);
if(client.connect(clientid)){
Serial.print(clientid);
Serial.println("connected");
}
else{
Serial.print("failed,rc=");
Serial.print(client.state());
Serial.println("try again in 5 seconds");
delay(5000);
}
}
}