当前位置:网站首页>学习太极创客 — 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 端,
边栏推荐
- Precautions for using C language global variables (global variables in C and H files, static global variables)
- 论文详读:IMPROVING CONVOLUTIONAL MODELS FOR HANDWRITTEN TEXT RECOGNITION
- Analysis of distributed transaction solution Seata golang
- ?位置怎么写才能输出true
- To quickly download JDK, in addition to the official Oracle download, is there a download address for the latest version available in China
- 求一个能判断表中数据,只填充不覆盖的sql
- 27 years, Microsoft IE is over!
- Matlab exercises -- basic data processing
- 【Proteus仿真】定时器1外部计数中断
- LeetCode 88:合并两个有序数组
猜你喜欢
UI自動化測試框架搭建 —— 編寫一個APP自動化
[NOIP2002 普及组] 过河卒
Ppt production tips
2022年G3锅炉水处理复训题库模拟考试平台操作
Taco: a data enhancement technique for character recognition
Analysis of distributed transaction solution Seata golang
Multi thread implementation rewrites run (), how to inject and use mapper file to operate database
[CSP-J2020] 优秀的拆分
浅析搭建视频监控汇聚平台的必要性及场景应用
Severe tire damage: the first rock band in the world to broadcast live on the Internet
随机推荐
Distributed transaction - Final consistency scheme based on message compensation (local message table, message queue)
Unity delegate
Sword finger offer 47 Maximum gift value (DP)
Sword finger offer 49 Ugly number (three finger needling technique)
[early knowledge of activities] list of recent activities of livevideostack
Notepad++ -- column editing mode -- Usage / instance
Sword finger offer 53 - I. find the number I in the sorted array (improved bisection)
Multithreading and high concurrency V: detailed explanation of wait queue, executor and thread pool (key)
Light collector, Yunnan Baiyao!
Difference between curdate() and now()
One article explains in detail | those things about growth
Multithreading and high concurrency six: source code analysis of thread pool
Generate QR code in wechat applet
控制器的功能和工作原理
JS reverse massive star map sign signature
Play with double pointer
【Proteus仿真】定时器1外部计数中断
Mask's miserable and inspirational childhood, who is introverted by campus violence
How can we speed up the chunksplitter when CDC extracts MySQL data in full?
[Matlab bp regression prediction] GA Optimized BP regression prediction (including comparison before optimization) [including source code 1901]