【MQTT编程】消息Publish实践:Synchronous publication同步发布示例

旧城等待, 2022-11-11 14:41 116阅读 0赞

  编程框架

Using the client
Applications that use the client library typically use a similar structure:
1)Create a client object
2)Set the options to connect to an MQTT server
3)Set up callback functions if multi-threaded (asynchronous mode) operation is being used (see Asynchronous vs synchronous client applications).
4)Subscribe to any topics the client needs to receive
5)Repeat until finished:
Publish any messages the client needs to
Handle any incoming messages
6)Disconnect the client
7)Free any memory being used by the client

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <unistd.h>
  5. #include "MQTTClient.h"
  6. #define ADDRESS "tcp://192.168.1.101:1883"
  7. #define CLIENTID "ExampleClientPub"
  8. #define TOPIC "MQTT_Examples"
  9. #define PAYLOAD "Hello MQTT!"
  10. #define QOS 1
  11. #define TIMEOUT 10000L
  12. int main(int argc, char* argv[])
  13. {
  14. MQTTClient client;
  15. MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  16. MQTTClient_message pubmsg = MQTTClient_message_initializer;
  17. MQTTClient_deliveryToken token;
  18. int rc;
  19. MQTTClient_create(&client, ADDRESS, CLIENTID,
  20. MQTTCLIENT_PERSISTENCE_NONE, NULL);
  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(EXIT_FAILURE);
  27. }
  28. pubmsg.payload = PAYLOAD;
  29. pubmsg.payloadlen = strlen(PAYLOAD);
  30. pubmsg.qos = QOS;
  31. pubmsg.retained = 0;
  32. while (1)
  33. {
  34. MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
  35. printf("Waiting for up to %d seconds for publication of %s\n"
  36. "on topic %s for client with ClientID: %s\n",
  37. (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
  38. rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  39. printf("Message with delivery token %d delivered\n", token);
  40. sleep(1);
  41. }
  42. MQTTClient_disconnect(client, 10000);
  43. MQTTClient_destroy(&client);
  44. return rc;
  45. }

发表评论

表情:
评论列表 (有 0 条评论,116人围观)

还没有评论,来说两句吧...

相关阅读