Hi. I'm currently working on a small project using ESP32 and MQTT. I'm new to MQTT so i'm having a little trouble solving this small part. Been looking for solutions but unable to resolve it still.
#include <M5Stack.h>
#include <Wire.h>
#include <Ethernet.h>
#include <WiFi.h>
#include <PubSubClient.h>
const char* ssid = "";
const char* password= "";
WiFiClient wclient;
PubSubClient client(wclient);
long tsLastReport = 0;
//Setup MQTT Client
const char *ID = "MyM5Device";
const char* topic="esp32/button";
IPAddress mqtt_server = (192,168,0,191);
void setup() {
// put your setup code here, to run once:
M5.begin();
setup_wifi();
client.setServer(mqtt_server,1883);
delay(500);
mqtt_connect();
delay(500);
}
void setup_wifi(){
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED){
Serial.println("WIFI CONNECTED");
delay(500);
}
}
void mqtt_connect(){
if (client.connected()){
return;
}
else{
while(!client.connected()){
if(client.connect(ID)){
Serial.println("MQTT Connected");
client.publish("esp32/button","HI THERE");
}
else{
Serial.println("Attempt MQTT connection in another 5secs");
delay(500);
}
}
}
}
void loop() {
// put your main code here, to run repeatedly:
M5.update();
if (millis() - tsLastReport > 50000){
String payload ="";
// payload+="field1=";
// payload+=HR;
// payload+="&field2=";
// payload+=SpO2;
// payload+="field3=";
// payload+=HRV;
// payload+="&status=MQTTPUBLISH";
if(client.connect(ID)){
Serial.println("Connected for publishing");
}
if(client.publish(topic, (char*)payload.c_str())){
Serial.println("Publish ok");
}
}
tsLastReport = millis();
}
I've set up inbound rule on my firewall TCP port 1883 to allow connection.
I'm also using Node-Red to connect to the MQTT broker but its successful for that side but unable for my ESP32
I've set up my conf file but i'm a little unsure if i placed the listener 1883 and allow_anonymous true at that right place.
Please help me if i'm doing anything wrong. I just can't seem to find a solution