当前位置:网站首页>Learn Taiji Maker - mqtt Chapter 2 (IV) esp8266 reserved message application
Learn Taiji Maker - mqtt Chapter 2 (IV) esp8266 reserved message application
2022-06-28 04:55:00 【xuechanba】
Video link :https://www.bilibili.com/video/BV1Ff4y1e7AB/?spm_id_from=autoNext&vd_source=b91967c499b23106586d7aa35af46413
The data link :http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-tuttorial/mqtt-tutorial/esp8266-retained-message/
Example 1 – Publish retention messages
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : publish_retained_msg The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20201014 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use PubSubClient Library usage ESP8266 towards MQTT The server publishes reserved information . This program is available at a_publish_ranye_url Based on the program . The key revision is publish Function added The third parameter , Used to set whether the published information is reserved (retained msg) ----------------------------------------------------------------------- This sample program is made by Taiji maker team 《 Zero basic introduction to the Internet of things 》 Sample program in . This tutorial is designed and produced by friends who are interested in the development of the Internet of things . For more information about this tutorial , Please refer to the following pages : http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-c/esp8266-nodemcu-web-client/http-request/ ***********************************************************************/
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
// Set up wifi Access information ( Please according to your WiFi Modify the information )
const char* ssid = "FAST_153C80";
const char* password = "123456798";
const char* mqttServer = "test.ranye-iot.net";
// As above MQTT The server cannot connect normally , Please go to the following page to find a solution
// http://www.taichi-maker.com/public-mqtt-broker/
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
void setup() {
Serial.begin(9600);
// Set up ESP8266 The working mode is wireless terminal mode
WiFi.mode(WIFI_STA);
// Connect WiFi
connectWifi();
// Set up MQTT Server and port number
mqttClient.setServer(mqttServer, 1883);
// Connect MQTT The server
connectMQTTServer();
if (mqttClient.connected()) {
// If the development board successfully connects to the server
pubRetMQTTmsg(); // Publish the information
}
}
void loop() {
mqttClient.loop(); // Keep your heart beating
}
void connectMQTTServer(){
// according to ESP8266 Of MAC Address generation client ID( Avoid contact with other ESP8266 The client of ID The nuptial )
String clientId = "esp8266-" + WiFi.macAddress();
// Connect MQTT The server
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);
}
}
// Publish the information
void pubRetMQTTmsg(){
// Create a publishing theme . The title of the topic is Taichi-Maker- The prefix , The device is added later MAC Address .
// This is done to ensure that different users MQTT When information is released ,ESP8266 Client names vary ,
String topicString = "Taichi-Maker-Ret-" + WiFi.macAddress();
char publishTopic[topicString.length() + 1];
strcpy(publishTopic, topicString.c_str());
// Create an upcoming retention message . The message is "Retained Msg".
String messageString = "Retained Msg";
char publishMsg[messageString.length() + 1];
strcpy(publishMsg, messageString.c_str());
// Realization ESP8266 Post to topic retained Information
// following publish The third parameter of the function is used to set the reserved information (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 Connect wifi
void connectWifi(){
WiFi.begin(ssid, password);
// wait for WiFi Connect , Output success information after successful connection
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi Connected!");
Serial.println("");
}
Let's verify the operation of the program .
First , Use the serial port monitor to see the output results .

next , We use MQTT.fx Software to subscribe to the news published by the development board . You can find , I received a message as soon as I subscribed .

below , Let's analyze the key content of this program .
// Publish the information
void pubRetMQTTmsg(){
// Create a publishing theme . The title of the topic is Taichi-Maker- The prefix , The device is added later MAC Address .
// This is done to ensure that different users MQTT When information is released ,ESP8266 Client names vary ,
String topicString = "Taichi-Maker-Ret-" + WiFi.macAddress();
char publishTopic[topicString.length() + 1];
strcpy(publishTopic, topicString.c_str());
// Create an upcoming retention message . The message is "Retained Msg".
String messageString = "Retained Msg";
char publishMsg[messageString.length() + 1];
strcpy(publishMsg, messageString.c_str());
// Realization ESP8266 Post to topic retained Information
// following publish The third parameter of the function is used to set the reserved information (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.");
}
}
Be careful ,publish Function number 3、 ... and Parameters (true Just tell the server , This message is reserved , This parameter defaults to false) It is used to set retention information (retained message) Of .
Example 2 – Modify the reserved message
Just change the content of the message to be published .
Example 3 – Delete reserved messages
Just set the above message content to be published as empty .
String messageString = "";
stay Serial port monitor end ,

stay MQTT.fx End ,

边栏推荐
- How to clean the nozzle of Epson l3153 printer
- 2022年G3锅炉水处理复训题库模拟考试平台操作
- Matlab exercises -- basic data processing
- [CSP-J2020] 优秀的拆分
- UI自动化测试框架搭建 —— 编写一个APP自动化
- How do I get the STW (pause) time of a GC (garbage collector)?
- [noip2002 popularization group] cross the river pawn
- 2022新版nft源码中国元宇宙数字藏品艺术品交易平台源码
- Mise en place d'un cadre d'essai d'automatisation de l'interface utilisateur - - rédaction d'une application d'automatisation
- Sword finger offer 47 Maximum gift value (DP)
猜你喜欢

机器人学DH参数及利用matlab符号运算推导

多线程实现 重写run(),怎么注入使用mapper文件操作数据库

Difference between curdate() and now()

Distributed transaction - Final consistency scheme based on message compensation (local message table, message queue)

TACo:一种关于文字识别的数据增强技术

Performance optimization and implementation of video codec

分享一个因子挖掘的利器:遗传规划

代码理解:IMPROVING CONVOLUTIONAL MODELS FOR HANDWRITTEN TEXT RECOGNITION

CUPTI error: CUPTI could not be loaded or symbol could not be found.

Code understanding: implementing volume models for hangwriten text recognition
随机推荐
控制器的功能和工作原理
如何从零设计一款牛逼的高并发架构(建议收藏)
2022年最新辽宁建筑八大员(标准员)考试试题及答案
If mysqlcdc sets multiple parallelism, will the incremental data repeat?
【牛客网刷题系列 之 Verilog快速入门】~ 四选一多路器
UI自動化測試框架搭建 —— 編寫一個APP自動化
Flexible IP network test tool -- x-launch
Principle and implementation of SSD for target detection
Idle interrupt cannot be cleared
June 27, 2022: give a 01 string with a length of N. now please find two intervals so that the number of 1 and the number of 0 in the two intervals are equal. The two intervals can intersect, but not c
机器人学DH参数及利用matlab符号运算推导
Feign通过自定义注解实现路径的转义
灵活的IP网络测试工具——— X-Launch
2022电力电缆判断题模拟考试平台操作
2022新版nft源码中国元宇宙数字藏品艺术品交易平台源码
2022烟花爆竹经营单位安全管理人员特种作业证考试题库及模拟考试
Learning Tai Chi Maker - mqtt Chapter II (VI) mqtt wills
Google Earth Engine(GEE)——全球洪水数据库 v1 (2000-2018年)
[early knowledge of activities] list of recent activities of livevideostack
信息学奥赛一本通 1360:奇怪的电梯(lift)