简体   繁体   中英

Paho MQTT (C++) client fails to connect to Mosquitto

I've got C++ code using the Paho MQTTPacket Embedded C++ library to connect to an MQTT broker. When that broker is io.adafruit.com, it works perfectly fine. But when it's my own Mosquitto instance running on my Raspberry Pi, the connection fails. I've narrowed it down to this line in MQTTClient.h, in the MQTT::Client::connect method:

// this will be a blocking call, wait for the connack
if (waitfor(CONNACK, connect_timer) == CONNACK)

The app hangs here for about 30 seconds, and then gets a result other than CONNACK (specifically 0 rather than 2).

I have tried both protocol version 3 (ie 3.1) and 4 (ie 3.1.1); same result.

My Mosquitto instance has no authentication or passwords set up. I've tried turning on debug messages in the Mosquitto log, but they're not showing anything useful. I'm at a loss. Why might I be unable to connect to Mosquitto from my C++ Paho code?

EDIT: Here's the client code... again, this works fine with Adafruit, but when I point it to my Mosquitto at localhost, it hangs as described. (I've elided the username and password -- I am sending them, but I really don't think those are the issue, since with mosquitto_pub or mosquitto_sub on the command line, I can connect regardless of this, since mosquitto is configured to allow anonymous connections.)

const char* host = "127.0.0.1";
int port = 1883;
const char* clientId = "ZoomBridge";
const char* username = "...";
const char* password = "...";
MQTT::QoS subsqos = MQTT::QOS2;

ipstack = new IPStack();
client = new MQTT::Client<IPStack, Countdown, 30000>(*ipstack);

MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.willFlag = 1;
data.MQTTVersion = 3;
data.clientID.cstring = (char*)clientId;
data.username.cstring = (char*)username;
data.password.cstring = (char*)password;

data.keepAliveInterval = 20;
data.cleansession = 1;

int rc = ipstack->connect(host, port);
if (rc != MQTT::SUCCESS) {
    cout << "Failed [1] (result " << rc << ")" << endl;
    return rc;
}

rc = client->connect(data);
if (rc != MQTT::SUCCESS) {
    cout << "Failed [2] (result " << rc << ")" << endl;
    ipstack->disconnect();
    return rc;
}

As hashed out in the comments.

It looks like you are setting the flag to indicate you want to set a Last Will and Testament for the client ( data.willFlag = 1; ) but then not passing any topic or payload for the LWT.

If you don't need the LWT then set the flag to 0 (or remove the line settings flag) as it should default to disabled.

Also worth pointing out to clarity, this is all with the Paho Embedded C++ MQTTPacket client not the full blown Paho C++ client .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM