MQTT C 客户端库

Eclipse Paho CMQTT C Client Library - 图1 (opens new window)Eclipse Paho Embedded CMQTT C Client Library - 图2 (opens new window) 均为 Eclipse Paho 项目下的 C 语言客户端库(MQTT C Client),均为使用 ANSI C 编写的功能齐全的 MQTT 客户端。

Eclipse Paho Embedded C 可以在桌面操作系统上使用,但主要针对 mbedMQTT C Client Library - 图3 (opens new window)ArduinoMQTT C Client Library - 图4 (opens new window)FreeRTOSMQTT C Client Library - 图5 (opens new window) 等嵌入式环境。

该客户端有同步/异步两种 API ,分别以 MQTTClient 和 MQTTAsync 开头:

  • 同步 API 旨在更简单,更有用,某些调用将阻塞直到操作完成为止,使用编程上更加容易;
  • 异步 API 中只有一个调用块 API-waitForCompletion ,通过回调进行结果通知,更适用于非主线程的环境。

Paho C 使用示例

MQTT C 语言相关两个客户端库的比较、下载、使用方式等详细说明请移步至项目主页查看,本示例包含 C 语言的 Paho C 连接 EMQX Broker,并进行消息收发完整代码:

  1. #include "stdio.h"
  2. #include "stdlib.h"
  3. #include "string.h"
  4. #include "MQTTClient.h"
  5. #define ADDRESS "tcp://broker.emqx.io:1883"
  6. #define CLIENTID "emqx_test"
  7. #define TOPIC "testtopic/1"
  8. #define PAYLOAD "Hello World!"
  9. #define QOS 1
  10. #define TIMEOUT 10000L
  11. int main(int argc, char* argv[])
  12. {
  13. MQTTClient client;
  14. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  15. MQTTClient_message pubmsg = MQTTClient_message_initializer;
  16. MQTTClient_deliveryToken token;
  17. int rc;
  18. MQTTClient_create(&client, ADDRESS, CLIENTID,
  19. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  20. // MQTT 连接参数
  21. conn_opts.keepAliveInterval = 20;
  22. conn_opts.cleansession = 1;
  23. if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  24. {
  25. printf("Failed to connect, return code %d\n", rc);
  26. exit(-1);
  27. }
  28. // 发布消息
  29. pubmsg.payload = PAYLOAD;
  30. pubmsg.payloadlen = strlen(PAYLOAD);
  31. pubmsg.qos = QOS;
  32. pubmsg.retained = 0;
  33. MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
  34. printf("Waiting for up to %d seconds for publication of %s\n"
  35. "on topic %s for client with ClientID: %s\n",
  36. (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
  37. rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  38. printf("Message with delivery token %d delivered\n", token);
  39. // 断开连接
  40. MQTTClient_disconnect(client, 10000);
  41. MQTTClient_destroy(&client);
  42. return rc;
  43. }

Paho C MQTT 5.0 支持

目前 Paho C 已经完整支持 MQTT 5.0。