基于Rt Thread的ETH应用(二)
1.Rt Thread设置
本期工程在 ETH应用(一)的基础上继续搭建
添加MQTT软件包 poho_mqtt
2.创建MQTT连接代码
代码比较少,程序如下
#include "my_mqtt.h"
//定义MQTT连接参数
#define mqtt_uri "tcp://192.168.101.7:1883"
#define ClientId "YANKE" // ClientId需要唯一
#define UserName "test01" // 用户名
#define PassWord "123456" // 用户名对应的密码
MQTTClient client;
//定义回调函数
void mqtt_connect_callback(MQTTClient *c)
{
rt_kprintf("connect success \n");
}
void mqtt_online_callback(MQTTClient *c)
{
rt_kprintf("mqtt online \n");
}
void mqtt_offline_callback(MQTTClient *c)
{
rt_kprintf("mqtt offline \n");
}
void MQTT_Entry(void *parameter)
{
//MQTT参数配置-连接参数
client.isconnected=0;
client.uri=mqtt_uri;
MQTTPacket_connectData condata=MQTTPacket_connectData_initializer; //连接参数配置
memcpy(&client.condata, &condata, sizeof(condata)); //参数初始化
client.condata.clientID.cstring=ClientId;
client.condata.username.cstring=UserName;
client.condata.cleansession=1; //退出后清除会话
client.condata.password.cstring=PassWord;
client.condata.keepAliveInterval=30;
client.buf_size = client.readbuf_size = 1024;
client.buf = rt_calloc(1, client.buf_size);
client.readbuf = rt_calloc(1, client.readbuf_size);
if (!(client.buf && client.readbuf))
{
rt_kprintf("no memory for MQTT client buffer!\r\n");
return ;
}
//设置回调函数
client.online_callback=mqtt_online_callback;
client.connect_callback=mqtt_connect_callback;
client.connect_callback=mqtt_offline_callback;
paho_mqtt_start(&client);
while(1){
paho_mqtt_publish(&client, QOS1, "/test", "i am rtt"); //最少一次
rt_thread_mdelay(1000);
}
}
#ifndef _MY_MQTT_H
#define _MY_MQTT_H
#include "paho_mqtt.h"
#include <rtthread.h>
#include <board.h>
#include <rtdevice.h>
#include "string.h"
void MQTT_Entry(void *parameter);
#endif
前提是已经创建了MQTT服务器,本文使用EMQX,自行搭建。
下期继续添加低功耗部分