I'm using an ESP8266 that connects wifi and to MQTT server.
the code connects nicely to wifi and to MQTT, it publishes the topic but the callback function is not triggered when I publish the subscribed topic from elsewhere (I use MQTT Explorer for win)
here the code.. I think it is the simplest possible but maybe I miss something...
**
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
const char* ssid = "-------"; // Enter your WiFi name
const char* password = "--------------"; // Enter WiFi password
const char* mqttServer = "192.168.0.15";
const int mqttPort = 1883;
const char* mqttUser = "";
const char* mqttPassword = "";
WiFiClient espClient;
PubSubClient client(espClient);
void callback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message arrived in topic: ");
Serial.println(topic);
Serial.print("Message:");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println();
Serial.println("-----------------------");
}
void setup() {
Serial.begin(9600);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the WiFi network");
client.setServer(mqttServer, mqttPort);
client.setCallback(callback);
while (!client.connected()) {
Serial.println("Connecting to MQTT...");
if (client.connect("ESP8266Client", mqttUser, mqttPassword )) {
Serial.println("connected");
} else {
Serial.print("failed with state ");
Serial.print(client.state());
delay(2000);
}
client.publish("esp/test", "hello"); //Topic name
client.subscribe("esp/testb");
}
}
void loop() {
client.loop();
}**