I’m trying to get my first ‘hello world’ function working using an ESP-32 to post MQTT messages but seem to have hit a brick wall.
According to the serial monitor all of the arduino functions are succeeding (they return ‘true’) and I can see the client connecting to my Mosquitto broker in the log, but I can’t see any messages that the ESP-32 is posting in node-red. The callback function also isn’t getting triggered so the ESP-32 client doesn’t seem to be receiving anything. I have Shelly devices successfully working and can see their traffic in node-red and interact with them so seems everything is ok with my broker and the connection between node-red and Mosquitto. It must be something obvious I’m doing wrong but as an arduino newbie I can’t see where to go next.
I’ve been following the guide here - http://www.steves-internet-guide.com/using-arduino-pubsub-mqtt-client/) and have tried to adapt for wifi, and have also looked at the API documentation (https://pubsubclient.knolleary.net/api). Can anyone see where I’m going wrong? I’m running Hassio on a Raspberry pi. My code is below, thanks in advance for any help:
#include "WiFi.h"
#include "PubSubClient.h"
const char* ssid = "BTWholeHome-8GR";
const char* password = "My wifi password";
const char* mqtt_server = "192.168.0.21";
const char* mqtt_client_name="Weather station";
const char* mqtt_topic="Test";
const int mqtt_port=1883;
WiFiClient espClient;
PubSubClient mqttClient(espClient);
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
//connect to wifi network
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
//connect to mqtt broker
mqttClient.setServer(mqtt_server, mqtt_port);
mqttClient.setCallback(callback);
if (mqttClient.connect(mqtt_client_name)) {
Serial.println("Connected to MQTT broker");
}
else {
Serial.println("Connection failed");
}
if (mqttClient.subscribe(mqtt_topic)) {
//subscription was successful
Serial.print("Subscribed to ");
Serial.print(+mqtt_topic);
Serial.println();
}
}
void loop() {
while(true){
if (mqttClient.publish(mqtt_topic,"Test post")) {
Serial.println("Message posted");
}
else {
Serial.println("Message failed");
}
delay(1000);
mqttClient.loop();
}
}
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived [");
Serial.print(topic);
Serial.print("] ");
for (int i=0;i<length;i++) {
Serial.print((char)payload[i]);
}
Serial.println();
}