(openwrt mqtt移植和使用)mt7628加入mqtt支持
1.mqtt开发过程
2 展示效果
拷贝细目文件mqtt_nossl 到packet/utils/ls 下面,如下图
1.mqtt开发过程
浪费了很多时间(4天时间)来开发这个功能,之前对openwrt不是很了解,
所以开始就直接上网搜索怎么在openwrt中加入mqtt,编写应用程序调用mqtt结
果网上的就没有找到一个正确参考的,而且走了不少弯路下面就把我开发的正确
的过程写出来给想要用的人参考
1
2
3
4
2 展示效果
运行mqtt_nossl 开发板收到的,和发送的
网页版mqtt发送和收到的
#需要编译的c代码,最后会附上完整的放在packet下面的项目,只需要拷贝到packet下面,配置好make menuconfig就可以了
#include "mqtt_nossl.h"
bool session = true;
void my_message_callback(struct mosquitto *mosq, void *userdata, const struct mosquitto_message *message)
{
if(message->payloadlen)
{
printf("%s %s", message->topic, message->payload);
}
else
{
printf("%s (null)\n", message->topic);
}
fflush(stdout);
}
void my_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
int i;
if(!result)
{
/* Subscribe to broker information topics on successful connect. */
mosquitto_subscribe(mosq, NULL, "topic/qos0", 2);
}
else
{
fprintf(stderr, "Connect failed\n");
}
}
void my_subscribe_callback(struct mosquitto *mosq, void *userdata, int mid, int qos_count, const int *granted_qos)
{
int i;
printf("Subscribed (mid: %d): %d", mid, granted_qos[0]);
for(i=1; i<qos_count; i++)
{
printf(", %d", granted_qos[i]);
}
printf("\n");
}
void my_log_callback(struct mosquitto *mosq, void *userdata, int level, const char *str)
{
/* Pring all log messages regardless of level. */
printf("log:%s\n", str);
}
int main()
{
char buff[MSG_MAX_SIZE];
struct mosquitto *mosq = NULL;
//libmosquitto 库初始化
mosquitto_lib_init();
//创建mosquitto客户端
mosq = mosquitto_new(NULL,session,NULL);
if(!mosq)
{
printf("create client failed..\n");
mosquitto_lib_cleanup();
return 1;
}
//设置回调函数,需要时可使用
mosquitto_log_callback_set(mosq, my_log_callback);
mosquitto_connect_callback_set(mosq, my_connect_callback);
mosquitto_message_callback_set(mosq, my_message_callback);
mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
//客户端连接服务器
if(mosquitto_connect(mosq, HOST, PORT, KEEP_ALIVE))
{
fprintf(stderr, "Unable to connect.\n");
return 1;
}
//循环处理网络消息
//mosquitto_loop_forever(mosq, -1, 1);
//开启一个线程,在线程里不停的调用 mosquitto_loop() 来处理网络信息
int loop = mosquitto_loop_start(mosq);
if(loop != MOSQ_ERR_SUCCESS)
{
printf("mosquitto loop error\n");
return 1;
}
while(fgets(buff, MSG_MAX_SIZE, stdin) != NULL)
{
/*发布消息*/
mosquitto_publish(mosq,NULL,"topic/qos1",strlen(buff)+1,buff,0,0);
memset(buff,0,sizeof(buff));
}
mosquitto_destroy(mosq);
mosquitto_lib_cleanup();
return 0;
}
拷贝细目文件mqtt_nossl 到packet/utils/ls 下面,如下图
mqtt_nossl 下载链接:( ),可能资料还在审核中,暂时下载不了
#在make menuconfig中选中mosquitto-nossl(network下面)
#在make menuconfig中选中mqtt_nossl(utilitues下面)
#make V=s后烧写到开发板
#开启远端mqtt,运行mqtt_nossl
---------------------
作者:liupeng08304