paho mqtt库使用记录

paho  MQTT库使用,主要分为同步和异步两种方式,暂不清楚两种有啥区别。总结,直接使用还是比较简单的。

1.  初始化

MQTTAsync_init();

2.  创建MQTT上下文

MQTTAsync_create(&pstClient, pcUrl, opts.clientid, 1, NULL);

3. 设置MQTT回调函数

MQTTAsync_setCallbacks(pstClient, pstClient, NULL, messageArrived, NULL);

4. 建立连接

MqttConnect(pstClient);

5. 发布消息

MQTTAsync_responseOptions PubRespOpts = MQTTAsync_responseOptions_initializer;

PubRespOpts.onSuccess = onPublish;
PubRespOpts.onFailure = onPublishFailure;
PubRespOpts.context = client;
rc = MQTTAsync_send(client, opts.topic, datalen, data, opts.qos, opts.retained, &PubRespOpts);

 

6. 订阅消息

MQTTAsync_responseOptions SubRespOpts = MQTTAsync_responseOptions_initializer;

SubRespOpts.onSuccess = onSubscribe;
SubRespOpts.onFailure = onSubscribeFailure;
SubRespOpts.context = client;
rc = MQTTAsync_subscribe(client, opts.topic, opts.qos, &SubRespOpts);

 

7. 怎么接收数据,用的回调函数,就是messageArrived

static int messageArrived(void *context, char *topicName, int topicLen, MQTTAsync_message *message)

posted @ 2021-09-15 18:14  429512065  阅读(654)  评论(0编辑  收藏  举报