想与服务器 test.mosquitto.org 建立连接,使用 MQTT paho 客户端和 ssl。我无法连接

时间:2021-07-22 06:47:07

标签: c ssl mqtt paho

这是我当前运行 idk 的代码,我犯了错误,得到错误 """"Failed to connect, return code -1"""" 任何帮助将不胜感激,我正在树莓派中运行它,提前致谢

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

#define ADDRESS "ssl://test.mosquitto.org:8884"

#define CLIENTID "c1"
#define TOPIC "ack"
#define PAYLOAD "Hello World"
#define QOS 1
#define TIMEOUT 10000L

void MQTTClient_global_init (   MQTTClient_init_options *   inits   );
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 = "client.crt";
  conn_opts.ssl->keyStore = "client.key";
  conn_opts.ssl->CApath = "mosquitto.org.crt";

  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;
}

输出: 连接失败,返回码-1

1 个答案:

答案 0 :(得分:0)

基于 the source for Paho,获得 -1 错误的最简单方法是忘记初始化库。

您需要在程序开始时调用 MQTTClient_global_init