当前位置:网站首页>学习太极创客 — MQTT 第二章(四)ESP8266 保留消息应用
学习太极创客 — MQTT 第二章(四)ESP8266 保留消息应用
2022-06-28 04:24:00 【xuechanba】
示例1 – 发布保留消息
/********************************************************************** 项目名称/Project : 零基础入门学用物联网 程序名称/Program name : publish_retained_msg 团队/Team : 太极创客团队 / Taichi-Maker (www.taichi-maker.com) 作者/Author : CYNO朔 日期/Date(YYYYMMDD) : 20201014 程序目的/Purpose : 本程序旨在演示如何使用PubSubClient库使用ESP8266向MQTT服务器发布保留信息。 此程序在a_publish_ranye_url程序基础上修改。重点修改内容是publish函数添加了 第三个参数,用于设置发布信息是否是保留信息(retained msg) ----------------------------------------------------------------------- 本示例程序为太极创客团队制作的《零基础入门学用物联网》中示例程序。 该教程为对物联网开发感兴趣的朋友所设计和制作。如需了解更多该教程的信息,请参考以下网页: http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-nodemcu-web-client/http-request/ ***********************************************************************/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// 设置wifi接入信息(请根据您的WiFi信息进行修改)
const char* ssid = "FAST_153C80";
const char* password = "123456798";
const char* mqttServer = "test.ranye-iot.net";
// 如以上MQTT服务器无法正常连接,请前往以下页面寻找解决方案
// http://www.taichi-maker.com/public-mqtt-broker/
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
void setup() {
Serial.begin(9600);
//设置ESP8266工作模式为无线终端模式
WiFi.mode(WIFI_STA);
// 连接WiFi
connectWifi();
// 设置MQTT服务器和端口号
mqttClient.setServer(mqttServer, 1883);
// 连接MQTT服务器
connectMQTTServer();
if (mqttClient.connected()) {
// 如果开发板成功连接服务器
pubRetMQTTmsg(); // 发布信息
}
}
void loop() {
mqttClient.loop(); // 保持心跳
}
void connectMQTTServer(){
// 根据ESP8266的MAC地址生成客户端ID(避免与其它ESP8266的客户端ID重名)
String clientId = "esp8266-" + WiFi.macAddress();
// 连接MQTT服务器
if (mqttClient.connect(clientId.c_str())) {
Serial.println("MQTT Server Connected.");
Serial.println("Server Address: ");
Serial.println(mqttServer);
Serial.println("ClientId:");
Serial.println(clientId);
} else {
Serial.print("MQTT Server Connect Failed. Client State:");
Serial.println(mqttClient.state());
delay(3000);
}
}
// 发布信息
void pubRetMQTTmsg(){
// 建立发布主题。主题名称以Taichi-Maker-为前缀,后面添加设备的MAC地址。
// 这么做是为确保不同用户进行MQTT信息发布时,ESP8266客户端名称各不相同,
String topicString = "Taichi-Maker-Ret-" + WiFi.macAddress();
char publishTopic[topicString.length() + 1];
strcpy(publishTopic, topicString.c_str());
// 建立即将发布的保留消息。消息内容为"Retained Msg"。
String messageString = "Retained Msg";
char publishMsg[messageString.length() + 1];
strcpy(publishMsg, messageString.c_str());
// 实现ESP8266向主题发布retained信息
// 以下publish函数第三个参数用于设置保留信息(retained message)
if(mqttClient.publish(publishTopic, publishMsg, true)){
Serial.println("Publish Topic:");Serial.println(publishTopic);
Serial.println("Publish Retained message:");Serial.println(publishMsg);
} else {
Serial.println("Message Publish Failed.");
}
}
// ESP8266连接wifi
void connectWifi(){
WiFi.begin(ssid, password);
//等待WiFi连接,成功连接后输出成功信息
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected!");
Serial.println("");
}
下面来验证下程序的运行情况。
首先,使用串口监视器来看下输出结果。

接着,我们使用 MQTT.fx 软件来订阅开发板所发布的消息。可以发现,刚一订阅就马上收到了一个消息。

下面,我们再来分析下这段程序的重点内容。
// 发布信息
void pubRetMQTTmsg(){
// 建立发布主题。主题名称以Taichi-Maker-为前缀,后面添加设备的MAC地址。
// 这么做是为确保不同用户进行MQTT信息发布时,ESP8266客户端名称各不相同,
String topicString = "Taichi-Maker-Ret-" + WiFi.macAddress();
char publishTopic[topicString.length() + 1];
strcpy(publishTopic, topicString.c_str());
// 建立即将发布的保留消息。消息内容为"Retained Msg"。
String messageString = "Retained Msg";
char publishMsg[messageString.length() + 1];
strcpy(publishMsg, messageString.c_str());
// 实现ESP8266向主题发布retained信息
// 以下publish函数第三个参数用于设置保留信息(retained message)
if(mqttClient.publish(publishTopic, publishMsg, true)){
Serial.println("Publish Topic:");Serial.println(publishTopic);
Serial.println("Publish Retained message:");Serial.println(publishMsg);
} else {
Serial.println("Message Publish Failed.");
}
}
注意,publish 函数第 三 个参数(true正是告诉服务端,这则消息为保留消息,该参数默认为 false)正是用于设置保留信息(retained message) 的。
示例2 – 修改保留消息
只需要将上述要发布的消息内容更改即可。
示例3 – 删除保留消息
只需要将上述要发布的消息内容设置为空即可。
String messageString = "";
在 串口监视器端,

在 MQTT.fx 端,

边栏推荐
- Has anyone ever used CDC to synchronize to MySQL with a deadlock?
- 为什么大厂不让使用undefined
- Pager when importing text files from MySQL
- Multithreading and high concurrency IV: varhandle, strong weak virtual reference and ThreadLocal
- Recommended by Alibaba P8, Fiddler packet capturing tool (I)
- 恭喜我自己,公众号粉丝破万
- Unity delegate
- Flinkcdc collects Oracle, and the Oracle database is CDB's
- 别卷!如何高质量地复现一篇论文?
- JS逆向之巨量星图sign签名
猜你喜欢

native关键字的作用

Light collector, Yunnan Baiyao!

Project practice! Teach you JMeter performance test hand in hand

Severe tire damage: the first rock band in the world to broadcast live on the Internet

Congratulations to myself, official account has more than ten thousand fans

别卷!如何高质量地复现一篇论文?

2022年G3锅炉水处理复训题库模拟考试平台操作

2022-06-27:给出一个长度为n的01串,现在请你找到两个区间, 使得这两个区间中,1的个数相等,0的个数也相等, 这两个区间可以相交,但是不可以完全重叠,即两个区间的左右端点不可以完全一样。

UI自動化測試框架搭建 —— 編寫一個APP自動化

Meta universe standard forum established
随机推荐
Notepad++ -- common plug-ins
Bitlock recovery occurs in win 10, and the blue screen error code is 0x1600007e
求一个能判断表中数据,只填充不覆盖的sql
Is it better for a novice to open a securities account? Is it safe to open a stock account
大促场景下,如何做好网关高可用防护
【Matlab BP回归预测】GA优化BP回归预测(含优化前的对比)【含源码 1901期】
MySQL gets the current date of the year
If mysqlcdc sets multiple parallelism, will the incremental data repeat?
The SQL of filincdc always reports this error when there are multiple tables. How can I solve it
Audio and video technology development weekly
100+数据科学面试问题和答案总结 - 机器学习和深度学习
Difference between curdate() and now()
[applet] solution document using font awesome Font Icon (picture and text)
How to clean the nozzle of Epson l3153 printer
Sword finger offer 47 Maximum gift value (DP)
华为9年经验的软件测试总监工作感悟—写给还在迷茫的朋友
Has anyone ever used CDC to synchronize to MySQL with a deadlock?
短视频平台开发,点击链接、图片自动跳转到新的页面
Multithreading and high concurrency IV: varhandle, strong weak virtual reference and ThreadLocal
Is it true that qiniu business school gives away securities accounts? Is it safe to open an account