ESP8266通过MQTT协议接入百度云天工物,乐鑫官网已经有现有的例程,首先
(1) 修改esp_mqtt_proj工程下的mqtt_config.h头文件里面的以下这些字段
#define MQTT_HOST "192.168.1.100"
#define MQTT_PORT 1883
#define MQTT_CLIENT_ID "Device_ID"
#define MQTT_USER "Device_Name"
#define MQTT_PASS "Device_Passwd"
#define STA_SSID "AP_SSID"
#define STA_PASS "AP_Passwd"
根据我们之前在百度云创建的项目设备的信息,修改为如下
#define MQTT_HOST "tefbct4.mqtt.iot.gz.baidubce.com"
#define MQTT_PORT 1883
#define MQTT_CLIENT_ID "Device_ID0x%x"
#define MQTT_USER "tefbct4/iot demo"
#define MQTT_PASS "F9rJ3FRHhfmQDR"
#define STA_SSID "AP_SSID" //这里自己填WIFI名称
#define STA_PASS "AP_Passwd" //这里自己填WIFI密码
(2) 在user_init函数进行相关的初始化
void user_init(void)
{
uart_init(BIT_RATE_115200, BIT_RATE_115200); // 串口波特率设为115200
os_delay_us(60000);
CFG_Load(); // 加载/更新系统参数
// 网络连接参数赋值:服务端域名、网络连接端口【1883】、安全类型【0:NO_TLS】
MQTT_InitConnection(&mqttClient, sysCfg.mqtt_host, sysCfg.mqtt_port, sysCfg.security);
//MQTT连接参数赋值、客户端标识符、MQTT用户名、MQTT密钥、保持连接时长、清除会话
MQTT_InitClient(&mqttClient, sysCfg.device_id, sysCfg.mqtt_user, sysCfg.mqtt_pass, sysCfg.mqtt_keepalive, 1);
// 设置遗嘱参数(如果云端没有对应的遗嘱主题,则MQTT连接会被拒绝)
//MQTT_InitLWT(&mqttClient, "Will", "ESP8266_offline", 0, 0);
// 设置MQTT相关函数
MQTT_OnConnected(&mqttClient, mqttConnectedCb); // 设置MQTT成功连接回调
MQTT_OnDisconnected(&mqttClient, mqttDisconnectedCb);//设置MQTT成功断开回调
MQTT_OnPublished(&mqttClient, mqttPublishedCb); // 设置MQTT成功发布回调
MQTT_OnData(&mqttClient, mqttDataCb)// 设置接收MQTT数据函数回调
// 连接WIFI:SSID
WIFI_Connect(sysCfg.sta_ssid, sysCfg.sta_pwd, wifiConnectCb);
INFO("\r\nSystem started ...\r\n");
}
(3) 在user_init函数中当ESP8266通过MQTT连接到百度云天工物时,会回调MQTT成功连接的函数,在回调函数中订阅我们之前在百度云创建的项目设备的主题(前面的策略),如下代码
void mqttConnectedCb(uint32_t *args)
{
MQTT_Client* client = (MQTT_Client*)args;// 获取mqttClient指针
INFO("MQTT: Connected\r\n");
//参数2:主题过滤器,参数3:Qos
MQTT_Subscribe(client, "LED CRTL", 0);// 订阅主题"LED CRTL",QoS=0
//参数2:主题名,参数3:发布消息的有效载荷,参数4:有效载荷长度,参数5:发布,Qos参数6:Retain
MQTT_Publish(client, "LED CRTL", "hello",strlen("hello"), 0, 0);
}
(4)接下来是一些MQTT的回调函数,这里只写出ESP8266接收到PUBLISH数据的处理:
void mqttDataCb(uint32_t *args, const char* topic, uint32_t topic_len, const char *data, uint32_t data_len)
{
char *topicBuf = (char*)os_zalloc(topic_len+1); // 申请【主题】空间
char *dataBuf = (char*)os_zalloc(data_len+1); // 申请【有效载荷】空间
MQTT_Client* client = (MQTT_Client*)args; // 获取MQTT_Client指针
os_memcpy(topicBuf, topic, topic_len);
topicBuf[topic_len] = 0;
os_memcpy(dataBuf, data, data_len);
dataBuf[data_len] = 0;
INFO("Receive topic: %s, data: %s \r\n", topicBuf, dataBuf);// 串口打印主题、有效载荷
INFO("Topic_len = %d, Data_len = %d\r\n", topic_len, data_len);//串口打印主题长度、有效载荷长度
if( os_strcmp(topicBuf,"LED CRTL") == 0 ) // 主题LED CRTL
{
if( os_strcmp(dataBuf,"LED_ON") == 0 ) // 有效载荷是"LED_ON"
{
//这里开灯的操作
}
else if( os_strcmp(dataBuf,"LED_OFF") == 0 ) // 有效载荷 == "LED_OFF"
{
//这里灭灯的操作
}
}
os_free(topicBuf); // 释放主题空间
os_free(dataBuf); // 释放有效载荷空间
}
(5) 可以用其他MQTT客户端对ESP8266进行远程控制了!!