MQTT over SSL 与 PAHO C

MQTT over SSL with PAHO C

我想弄清楚 paho 如何与 SSL 一起工作。 我已经使用 mosquitto 作为代理(默认 mosquitto.conf)测试了一个简单的酒吧(没有 SSL)并且一切正常。现在我修改了下面的代码(使用 ADDRESS 定义而不是 ADDRESSTEST)来测试 SSL。我使用了paho的“test”部分提供的认证。

#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <MQTTClient.h>


#define ADDRESS     "ssl://localhost:18885"
#define ADDRESSTEST     "tcp://localhost:1883"
#define CLIENTID    "ExampleClientPub"
#define TOPIC       "MQTTExamples"
#define PAYLOAD     "Hello World!"
#define QOS         1
#define TIMEOUT     10000L


int main() {

MQTTClient client;

MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer;;

MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;

MQTTClient_create(&client, ADDRESS, CLIENTID,
    MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);

conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;

conn_opts.ssl = &ssl_opts;
conn_opts.ssl->trustStore = "../../validpath/test-root-ca.crt";
conn_opts.ssl->keyStore = "../../validpath/client.pem";

conn_opts.serverURIcount = 0;
conn_opts.serverURIs = NULL;

if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
    printf("Failed to connect, return code %d\n", rc);
    exit(EXIT_FAILURE);
}

pubmsg.payload = PAYLOAD;
pubmsg.payloadlen = (int)strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;


MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
printf("Waiting for up to %d seconds for publication of %s\n"
        "on topic %s for client with ClientID: %s\n",
        (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
printf("Message with delivery token %d delivered\n", token);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);

return 0;
}

问题是,当我 运行 使用此配置的软件时, MQTTClient_connect return 我的代码 MQTTCLIENT_WRONG_MQTT_VERSION。本地主机中的 Mosquitto 运行s,我以这种方式修改了 mosquitto.conf:

# server authentication - no client authentication
listener 18885
cafile validpath/all-ca.crt
certfile validpath/server.crt
keyfile validpath/server.key
require_certificate false
#tls_version tlsv1

当您使用 -lpaho-mqtt3c 而不是 -lpaho-mqtt3cs(启用 SSL)进行编译时会出现此问题。现在它可以正常工作了!