arduino-libraries / ArduinoMqttClient

ArduinoMqttClient Library for Arduino
GNU Lesser General Public License v2.1
186 stars 73 forks source link

mqttClient.connected() always 0 despite being connected #93

Open Andreasjkoch opened 11 months ago

Andreasjkoch commented 11 months ago

Hi.

I am using the "ArduinoMqttClient" library (version 0.1.7) to connect to an MQTT broker. However, I have encountered an issue where the mqttClient.connected() function always returns 0, even when the connection to the MQTT broker is active and data is being sent.

Environment:

Code:

#include "wifi.h"
#include "mqtt.h"

WiFiClient wifiClient;
MqttClient mqttClient(wifiClient);

const long interval = 15000;
unsigned long previousMillis = 0;

void setup() {
    Serial.begin(9600);
    while (!Serial)

    connectWifiClient();
    connectMqttClient(mqttClient);
    postHomeassistantDiscoveryObjects(mqttClient);
}

void loop() {
    Serial.println(mqttClient.connected()); // This always returns 0, despite generateTestData() that actually does send data, so the connection clearly works
    mqttClient.poll();
    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval) {
        previousMillis = currentMillis;
        generateTestData(mqttClient);
    }
    checkWifiConnection(); 
}
Andreasjkoch commented 11 months ago

Okay so I attempted to go ahead and move the clientConnected() function from private to the public space in the "MqttClient.h" file from the library instead, and that functions works just fine...

richardsstafford commented 11 months ago

@Andreasjkoch did that solve the problem for you? I'm seeing a similar issue using Arduino Portenta H7 board in Arduino Portenta Machine Control device, connecting to Azure IOT Hub. mqttClient.connected() always returns 0

Andreasjkoch commented 11 months ago

@Andreasjkoch did that solve the problem for you?

Yes it did. For some reason the public function just doesn't work. So just move the line defining clientConnected() in MqttClient.h so that it is inside of public