PubSubClient doesn't stay .connected()
Hi,
Thank you for your excellent WifiManager. I am having an issue with the pubsubclient where by it doesnt maintain it's connected state -
I have my code as so
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h>
WiFiClient wclient;
PubSubClient client(wclient, "my.mqtt.server", 1883);
void callback(const MQTT::Publish& pub) {
if (!pub.has_stream()) {
// Do stuff on publish
}
}
void setupWiFi() {
WiFiManager wifiManager;
wifiManager.setTimeout(300);
wifiManager.autoConnect("AHUB");
delay(3000);
}
void setup() {
Serial.begin(9600);
setupWiFi();
}
void loop() {
if (WiFi.status() == WL_CONNECTED) {
if (!client.connected()) {
Serial.println("not connected to MQTT broker, trying connection");
if (client.connect(MQTT::Connect("myhub")
.set_clean_session()
.set_will("status", "disconnected")
)) {
Serial.println("hub connected");
client.set_callback(callback);
client.subscribe("commands");
}
}
if (client.connected()) {
Serial.println("connected, looping"); // debug only
client.loop();
}
}
}
... unfotunately, once I have connected to my MQTT server, client.connected() is reset when client.loop() is called and so it keeps reconnected.
Any ideas?
I am using this PubSubClient as the callback methods are more advanced - https://github.com/Imroy/pubsubclient
Thanks
Your problems are with calls to the PubSubClient object.
They appear to be unrelated to WiFiManager.
hi @Jimbwlah , as @kentaylor mentioned (Thank you very much) this is more about the pubsubclient lib.
try to simplify everything like in the basic example they have https://github.com/knolleary/pubsubclient/blob/master/examples/mqtt_basic/mqtt_basic.ino
maybe it will help
thanks guys