当前位置:网站首页>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 ,

边栏推荐
- Performance optimization and implementation of video codec
- 华为9年经验的软件测试总监工作感悟—写给还在迷茫的朋友
- What to do when MySQL changes the password and reports an error
- JS reverse massive star map sign signature
- [Matlab bp regression prediction] GA Optimized BP regression prediction (including comparison before optimization) [including source code 1901]
- Detailed reading of the thesis: implementing volume models for handowriting text recognition
- Sword finger offer 49 Ugly number (three finger needling technique)
- 2022年材料员-通用基础(材料员)操作证考试题库及答案
- If mysqlcdc sets multiple parallelism, will the incremental data repeat?
- 知识点滴 - 关于汉语学习的网络资源
猜你喜欢

Audio and video technology development weekly

【牛客网刷题系列 之 Verilog快速入门】~ 四选一多路器

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

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

华为9年经验的软件测试总监工作感悟—写给还在迷茫的朋友

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

控制器的功能和工作原理

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

【Matlab红绿灯识别】红绿灯识别【含GUI源码 1908期】

The second round of free public classes of the red team is coming ~ 8:00 tomorrow night!
随机推荐
Feign remote call fallback callback failed, no effect
2022新版nft源码中国元宇宙数字藏品艺术品交易平台源码
交流电和直流电的区别是什么?
RxSwift --(1)创建一个项目
Audio and video technology development weekly
UI自動化測試框架搭建 —— 編寫一個APP自動化
wordpress zibll子比主题6.4.1开心版 免授权
mysql修改密码报错需要怎么做
[csp-j2020] excellent splitting
The latest examination questions and answers for the eight members (standard members) of Liaoning architecture in 2022
!‘cat‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
[CSP-J2020] 优秀的拆分
求一个能判断表中数据,只填充不覆盖的sql
Notepad++ -- common plug-ins
Meta universe standard forum established
Play with double pointer
Notepad++ -- column editing mode -- Usage / instance
汇编常用指令
Necessary skills for test and development: actual combat of security test vulnerability shooting range
Pager when importing text files from MySQL