当前位置:网站首页>Learn Tai Chi Maker - mqtt (VIII) esp8266 subscribe to mqtt topic
Learn Tai Chi Maker - mqtt (VIII) esp8266 subscribe to mqtt topic
2022-06-27 02:14:00 【xuechanba】
The data link :http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-tuttorial/mqtt-tutorial/esp8266-subscribe-mqtt/

1、 Subscribe to a single topic
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : subscribe_ranye_url The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20200708 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use PubSubClient Library usage ESP8266 towards MQTT Server subscription information . ----------------------------------------------------------------------- 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() {
pinMode(LED_BUILTIN, OUTPUT); // Set up on the board LED Pin is output mode
digitalWrite(LED_BUILTIN, HIGH); // Turn it on and off the board LED
Serial.begin(9600); // Start serial communication
// 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);
// Set up MQTT Subscription callback function
mqttClient.setCallback(receiveCallback);
// Connect MQTT The server
connectMQTTserver();
}
void loop() {
if (mqttClient.connected()) {
// If the development board successfully connects to the server
mqttClient.loop(); // Process information and heartbeat
} else {
// If the development board fails to connect to the server
connectMQTTserver(); // Then try to connect to the server
}
}
// Connect MQTT Server and subscribe to information
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);
subscribeTopic(); // Subscribe to specific topics
} else {
Serial.print("MQTT Server Connect Failed. Client State:");
Serial.println(mqttClient.state());
delay(5000);
}
}
// Callback function after receiving information
void receiveCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message Received [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println("");
Serial.print("Message Length(Bytes) ");
Serial.println(length);
if ((char)payload[0] == '1') {
// If you receive a message with “1” For the beginning
digitalWrite(BUILTIN_LED, LOW); // Then light up LED.
Serial.println("LED ON");
} else {
digitalWrite(BUILTIN_LED, HIGH); // Otherwise, it goes out LED.
Serial.println("LED OFF");
}
}
// Subscribe to specific topics
void subscribeTopic(){
// Create a subscription topic . The title of the topic is Taichi-Maker-Sub The prefix , The device is added later MAC Address .
// This is to make sure that different devices use the same MQTT When the server tests the message subscription , The topic names you subscribe to are different
String topicString = "Taichi-Maker-Sub-" + WiFi.macAddress();
char subTopic[topicString.length() + 1];
strcpy(subTopic, topicString.c_str());
// The serial port monitor outputs whether the topic is successfully subscribed and the name of the subscription topic
if(mqttClient.subscribe(subTopic)){
Serial.println("Subscrib Topic:");
Serial.println(subTopic);
} else {
Serial.print("Subscribe Fail...");
}
}
// 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("");
}
The program runs as follows ,
Let's try again MQTT.fx This software provides Taichi-Maker-Sub-EC:FA:BC:40:6F:5B This topic publishes information , At the same time, observe the output of the serial port monitor .


When LED ON when ,ESP8266 On board LED Also lit .
below , To explain the key points of the program .
// Set up MQTT Subscription callback function
mqttClient.setCallback(receiveCallback);
Here ESP8266 The function of the development board is to subscribe MQTT The theme , It is subscribing MQTT After the theme , Whenever you receive this topic message , He will call a callback function receiveCallback , To process the received information .
2、 Subscribe to specific topics
// The serial port monitor outputs whether the topic is successfully subscribed and the name of the subscription topic
if(mqttClient.subscribe(subTopic)){
Serial.println("Subscrib Topic:");
Serial.println(subTopic);
} else {
Serial.print("Subscribe Fail...");
}
mqttClient.subscribe(subTopic) Will try to subscribe to a topic , The theme is called “Taichi-Maker-Sub-” + WiFi.macAddress(),
If the subscription is successful, it will return 1 .
3、 Callback function after receiving information
void receiveCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message Received [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println("");
Serial.print("Message Length(Bytes) ");
Serial.println(length);
if ((char)payload[0] == '1') {
// If you receive a message with “1” For the beginning
digitalWrite(BUILTIN_LED, LOW); // Then light up LED.
Serial.println("LED ON");
} else {
digitalWrite(BUILTIN_LED, HIGH); // Otherwise, it goes out LED.
Serial.println("LED OFF");
}
}
Notice the three parameters , The three parameters are fixed format .
topic It's the theme name
payload Is the content of specific information , It's an array type
length Is the length of the specific information
2、 Subscribe to multiple topics
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : subscribe_multitopic_ranye_url The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20201125 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use PubSubClient Library usage ESP8266 towards MQTT The server subscribes to multiple topics ----------------------------------------------------------------------- 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() {
pinMode(LED_BUILTIN, OUTPUT); // Set up on the board LED Pin is output mode
digitalWrite(LED_BUILTIN, HIGH); // Turn it on and off the board LED
Serial.begin(9600); // Start serial communication
// 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);
mqttClient.setCallback(receiveCallback);
// Connect MQTT The server
connectMQTTserver();
}
void loop() {
if (mqttClient.connected()) {
// If the development board successfully connects to the server
mqttClient.loop(); // Process information and heartbeat
} else {
// If the development board fails to connect to the server
connectMQTTserver(); // Then try to connect to the server
}
}
// Connect MQTT Server and subscribe to information
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);
subscribeTopic(); // Subscribe to specific topics
} else {
Serial.print("MQTT Server Connect Failed. Client State:");
Serial.println(mqttClient.state());
delay(5000);
}
}
// Callback function after receiving information
void receiveCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message Received [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println("");
Serial.print("Message Length(Bytes) ");
Serial.println(length);
if ((char)payload[0] == '1') {
// If you receive a message with “1” For the beginning
digitalWrite(BUILTIN_LED, LOW); // Then light up LED.
} else {
digitalWrite(BUILTIN_LED, HIGH); // Otherwise, it goes out LED.
}
}
// Subscribe to specific topics
void subscribeTopic(){
// Create a subscription topic 1. The title of the topic is Taichi-Maker-Sub The prefix , The device is added later MAC Address .
// This is to make sure that different devices use the same MQTT When the server tests the message subscription , The topic names you subscribe to are different
String topicString = "Taichi-Maker-Sub-" + WiFi.macAddress();
char subTopic[topicString.length() + 1];
strcpy(subTopic, topicString.c_str());
// Create a subscription topic 2
String topicString2 = "Taichi-Maker-Sub2-" + WiFi.macAddress();
char subTopic2[topicString2.length() + 1];
strcpy(subTopic2, topicString2.c_str());
// Output whether the topic has been successfully subscribed through the serial port monitor 1 And the topics you subscribe to 1 name
if(mqttClient.subscribe(subTopic)){
Serial.println("Subscrib Topic:");
Serial.println(subTopic);
} else {
Serial.print("Subscribe Fail...");
}
// Output whether the topic has been successfully subscribed through the serial port monitor 2 And the topics you subscribe to 2 name
if(mqttClient.subscribe(subTopic2)){
Serial.println("Subscrib Topic:");
Serial.println(subTopic2);
} else {
Serial.print("Subscribe Fail...");
}
}
// 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("");
}
The running code is as follows ,
Let's try again MQTT.fx This software is directed to Taichi-Maker-Sub-EC:FA:BC:40:6F:5B and Taichi-Maker-Sub2-EC:FA:BC:40:6F:5B These two topics publish information , At the same time, observe the output of the serial port monitor .


No matter which topic you post on , As long as the first character of the message is 1 , Then light up the onboard LED .
3、 Subscribe to topics using single level wildcards
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : subscribe_single_level_wildcard_ranye The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20200813 Purpose of procedure /Purpose : The purpose of this procedure is to demonstrate ESP8266 Unipolar wildcard when subscribing to information + application . ----------------------------------------------------------------------- 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 = "taichi-maker";
const char* password = "12345678";
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() {
pinMode(LED_BUILTIN, OUTPUT); // Set up on the board LED Pin is output mode
digitalWrite(LED_BUILTIN, HIGH); // Turn it on and off the board LED
Serial.begin(9600); // Start serial communication
// 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);
mqttClient.setCallback(receiveCallback);
// Connect MQTT The server
connectMQTTserver();
}
void loop() {
if (mqttClient.connected()) {
// If the development board successfully connects to the server
mqttClient.loop(); // Process information and heartbeat
} else {
// If the development board fails to connect to the server
connectMQTTserver(); // Then try to connect to the server
}
}
// Connect MQTT Server and subscribe to information
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);
subscribeTopic(); // Subscribe to specific topics
} else {
Serial.print("MQTT Server Connect Failed. Client State:");
Serial.println(mqttClient.state());
delay(5000);
}
}
// Callback function after receiving information
void receiveCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message Received [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println("");
Serial.print("Message Length(Bytes) ");
Serial.println(length);
if ((char)payload[0] == '1') {
// If you receive a message with “1” For the beginning
digitalWrite(BUILTIN_LED, LOW); // Then light up LED.
} else {
digitalWrite(BUILTIN_LED, HIGH); // Otherwise, it goes out LED.
}
}
// Subscribe to specific topics
void subscribeTopic(){
// Create a subscription topic . The title of the topic is Taichi-Maker-Sub The prefix , The device is added later MAC Address .
// This is to make sure that different devices use the same MQTT When the server tests the message subscription , The topic names you subscribe to are different
String topicString = "Taichi-Maker-Sub-" + WiFi.macAddress()+"/+/data";
char subTopic[topicString.length() + 1];
strcpy(subTopic, topicString.c_str());
// The serial port monitor outputs whether the topic is successfully subscribed and the name of the subscription topic
if(mqttClient.subscribe(subTopic)){
Serial.println("Subscrib Topic:");
Serial.println(subTopic);
} else {
Serial.print("Subscribe Fail...");
}
}
// 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("");
}
It is similar to the first program .
4、 Use multi-level wildcards to subscribe to topics
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : subscribe_multi_level_wildcard_ranye The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20200813 Purpose of procedure /Purpose : The purpose of this procedure is to demonstrate ESP8266 Multipole wildcard when subscribing to information # application . ----------------------------------------------------------------------- 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 = "taichi-maker";
const char* password = "12345678";
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() {
pinMode(LED_BUILTIN, OUTPUT); // Set up on the board LED Pin is output mode
digitalWrite(LED_BUILTIN, HIGH); // Turn it on and off the board LED
Serial.begin(9600); // Start serial communication
// 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);
mqttClient.setCallback(receiveCallback);
// Connect MQTT The server
connectMQTTserver();
}
void loop() {
if (mqttClient.connected()) {
// If the development board successfully connects to the server
mqttClient.loop(); // Process information and heartbeat
} else {
// If the development board fails to connect to the server
connectMQTTserver(); // Then try to connect to the server
}
}
// Connect MQTT Server and subscribe to information
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);
subscribeTopic(); // Subscribe to specific topics
} else {
Serial.print("MQTT Server Connect Failed. Client State:");
Serial.println(mqttClient.state());
delay(5000);
}
}
// Callback function after receiving information
void receiveCallback(char* topic, byte* payload, unsigned int length) {
Serial.print("Message Received [");
Serial.print(topic);
Serial.print("] ");
for (int i = 0; i < length; i++) {
Serial.print((char)payload[i]);
}
Serial.println("");
Serial.print("Message Length(Bytes) ");
Serial.println(length);
if ((char)payload[0] == '1') {
// If you receive a message with “1” For the beginning
digitalWrite(BUILTIN_LED, LOW); // Then light up LED.
} else {
digitalWrite(BUILTIN_LED, HIGH); // Otherwise, it goes out LED.
}
}
// Subscribe to specific topics
void subscribeTopic(){
// Create a subscription topic . The title of the topic is Taichi-Maker-Sub The prefix , The device is added later MAC Address .
// This is to make sure that different devices use the same MQTT When the server tests the message subscription , The topic names you subscribe to are different
String topicString = "Taichi-Maker-Sub-" + WiFi.macAddress()+"/sensor/#";
char subTopic[topicString.length() + 1];
strcpy(subTopic, topicString.c_str());
// The serial port monitor outputs whether the topic is successfully subscribed and the name of the subscription topic
if(mqttClient.subscribe(subTopic)){
Serial.println("Subscrib Topic:");
Serial.println(subTopic);
} else {
Serial.print("Subscribe Fail...");
}
}
// 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("");
}
It is similar to the first program .
边栏推荐
- dat. gui. JS star circle track animation JS special effect
- H5 liquid animation JS special effect code
- Oracle/PLSQL: HexToRaw Function
- h5液体动画js特效代码
- 消费者追捧iPhone,在于它的性价比超越国产手机
- Oracle/PLSQL: HexToRaw Function
- Sample development of WiFi IOT Hongmeng development kit
- d的appendTo包装
- Oracle/PLSQL: Replace Function
- Flink Learning 2: Application Scenarios
猜你喜欢

学习太极创客 — MQTT(七)MQTT 主题进阶

h5液体动画js特效代码

Flink学习3:数据处理模式(流批处理)

lottie.js创意开关按钮动物头像

Hot discussion: what are you doing for a meaningless job with a monthly salary of 18000?

CVPR2022 | PointDistiller:面向高效紧凑3D检测的结构化知识蒸馏

Consumers pursue the iPhone because its cost performance exceeds that of domestic mobile phones

“所有专业都在劝退”,对大学生最友好的竟然是它?

Is the division of each capability domain of Dama, dcmm and other data management frameworks reasonable? Is there internal logic?

Flink learning 1: Introduction
随机推荐
How does the C # TCP server limit the number of connections to the same IP?
Enterprise digital transformation: informatization and digitalization
Would rather go to 996 than stay at home! 24 years old, unemployed for 7 months, worse than work, no work
Reading a book in idea is too much!
pytorch_grad_cam——pytorch下的模型特征(Class Activation Mapping, CAM)可视化库
Google began to roll itself, AI architecture pathways was blessed, and 20billion generation models were launched
Memcached foundation 9
Shell script series (1) getting started
Memcached basics 11
mmdetection 用yolox训练自己的coco数据集
WiFi-IoT 鸿蒙开发套件样例开发
memcached基础12
dat. gui. JS star circle track animation JS special effect
memcached基础11
Memcached basics 13
Oracle/PLSQL: Length Function
paddlepaddle 20 指数移动平均(ExponentialMovingAverage,EMA)的实现与使用(支持静态图与动态图)
Shell脚本系列篇(1) 入门
pytorch 23 hook的使用与介绍 及基于hook实现即插即用的DropBlock
Is the division of each capability domain of Dama, dcmm and other data management frameworks reasonable? Is there internal logic?