I'm trying to subscribe to an mqtt broker which uses SSL/TLS to authenticate clients. I use libmosquitto to do that.
I run this code to perform a subscription
#include <csignal>
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
#include <mosquitto.h>
#define WITH_AUTHENTICATION
#define MQTT_HOST "exmaple.com"
#define MQTT_PORT 8883
#define TARGET_USER "use"
#define TARGET_PW "password"
#define TARGET_TOPIC "/example-topic"
#define CERTIFICATE "/home/luca/TRIALS/tryMqttS/cert.pem"
using namespace std;
static int run = 1;
void signalHandler (int s) {
run = 0;
}
void messageCallback (struct mosquitto *mosq, void *obj, const struct mosquitto_message *message) {
bool match = 0;
cout << "got message " << (char *) message->payload << " from topic " << message->topic << endl;
}
int main(int argc, char *argv[])
{
uint8_t reconnect = true;
string clientID = "mosquitto_client_" + to_string (getpid());
struct mosquitto *mosq = nullptr;
int resCode = 0;
signal (SIGINT, signalHandler);
signal (SIGTERM, signalHandler);
mosquitto_lib_init ();
mosq = mosquitto_new (clientID.c_str(), true, 0);
if(mosq){
mosquitto_message_callback_set (mosq, messageCallback);
#ifdef WITH_AUTHENTICATION
cout << "Pw set result: " << mosquitto_strerror (mosquitto_username_pw_set (mosq, TARGET_USER, TARGET_PW)) << endl;
cout << "Tls insecure set result: " << mosquitto_strerror (mosquitto_tls_insecure_set (mosq, false)) << endl;
cout << "Tls opts set result: " << mosquitto_strerror (mosquitto_tls_opts_set (mosq, 1, NULL, NULL)) << endl;
cout << "Tls set result: " << mosquitto_strerror (mosquitto_tls_set (mosq, CERTIFICATE, nullptr, nullptr, nullptr, /*pw_cb * */ nullptr)) << endl;
#endif
cout << "Connection result: " << mosquitto_strerror (mosquitto_connect (mosq, MQTT_HOST, MQTT_PORT, 60)) << endl;
cout << "Subscription result: " << mosquitto_strerror (mosquitto_subscribe (mosq, NULL, TARGET_TOPIC, 0)) << endl;
while (run) {
resCode = mosquitto_loop (mosq, 20, 1);
if (resCode) {
cout << "ERROR: " << mosquitto_strerror (resCode) << " (" << resCode << ")\n";
sleep(1);
mosquitto_reconnect (mosq);
}
}
mosquitto_destroy (mosq);
}
mosquitto_lib_cleanup ();
return 0;
}
but the output is every time the same:
Connection result: 0
Subscription result: 0
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
ERROR: The connection was lost. (7)
Using an external tool (e.g. mqttfx) and using the same authentication credentials, the subscription is good and I can receive messages published on topic.
How can I perform the subscription correctly? Are there some missing settings?