使用mosquitto库函数前,要先初始化,使用之后要清除:
int mosquitto_lib_init(void);
int mosquitto_lib_cleanup();
/*新建客户端*/
struct mosquitto *mosquitto_new(
const char *id,//用户自定义标识ID
bool clean_session,//断开后是否保留订阅信息
true/false void *userdata//回调参数
);
*释放客户端*/
void mosquitto_destroy(struct mosquitto *mosq);
参考接口函数:
订阅:
//订阅
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <mosquitto.h>
#include <time.h>
// 消息回调
void my_message_callback(struct mosquitto *mosq, void *obj, const \
struct mosquitto_message *msg)
{
time_t t;
struct tm *lt; printf("%d:topic(%s)->%s\n",__LINE__,(char *)msg->topic,\
(char *)msg->payload);
}
int main(int argc,char *argv[]){ struct mosquitto *m_hMqtt;
char *topic1 = "temp";
//初始化lib库函数
mosquitto_lib_init();
// 定义一个客户端名为subtest的发布端。客户端表示订阅端的唯一性
m_hMqtt = mosquitto_new("subdemo", true, "data");
//订阅回调 mosquitto_message_callback_set(m_hMqtt, my_message_callback);
//连接服务器(代理器)
mosquitto_connect(m_hMqtt, "49.232.150.163", 1883, 2);
//订阅消息
mosquitto_subscribe(m_hMqtt,NULL,topic1,1);
/* 阻塞等待 */
mosquitto_loop_start(m_hMqtt);
mosquitto_loop_stop(m_hMqtt, false);
mosquitto_destroy(m_hMqtt);
mosquitto_lib_cleanup();
return 0;
}
发布:
//发布
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
#include <mosquitto.h>
#include <time.h>
int main(int argc,char *argv[]){ struct mosquitto *m_hMqtt;
char *topic1 = "temp";
char *content = "27.5";
//初始化lib库函数
mosquitto_lib_init();
// 定义一个客户端名为subtest的发布端。客户端表示订阅端的唯一性
m_hMqtt = mosquitto_new("pubdemo", true, "data");
mosquitto_connect(m_hMqtt, "49.232.150.163",1883, 2);
mosquitto_publish(m_hMqtt,NULL,topic1,strlen(content)+1,content,1,true);
mosquitto_destroy(m_hMqtt);
mosquitto_lib_cleanup();
return 0;
}