当前位置:网站首页>Learning Tai Chi Maker - mqtt Chapter II (IX) test of this chapter
Learning Tai Chi Maker - mqtt Chapter II (IX) test of this chapter
2022-06-29 02:16:00 【xuechanba】
The program code is as follows ,
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : complete_connect The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20201024 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use PubSubClient Library connection MQTT All parameter options for the server ----------------------------------------------------------------------- Modify the record : 20201227 - Added user name and password content ( Replace the original NULL) ----------------------------------------------------------------------- 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);
const int subQoS = 1; // When the client subscribes to the topic QoS Level ( end 2020-10-07, Support only QoS = 1, I won't support it QoS = 2)
const bool cleanSession = false; // Clear session ( Such as QoS>0 Must be set to false)
const char* willTopic = "willTopic"; // Subject name of the will
const char* willMsg = "willMsg"; // Subject information of the will
const int willQos = 0; // will QoS
const int willRetain = false; // Testamentary reservation
const char* mqttUserName = "test-user"; // Server connection user name
const char* mqttPassword = "ranye-iot"; // Server connection password
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 the development board fails to connect to the server , Then try to connect to the server
if (!mqttClient.connected()) {
connectMQTTserver();
}
// Process information and heartbeat
mqttClient.loop();
}
// 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 = "client-" + WiFi.macAddress();
/* Connect MQTT The server boolean connect(const char* id, const char* user, const char* pass, const char* willTopic, uint8_t willQos, boolean willRetain, const char* willMessage, boolean cleanSession); If the device is offline, it can still make qos1 Work , be connect At the time of the cleanSession I need to set to false */
if (mqttClient.connect(clientId.c_str(), mqttUserName,
mqttPassword, willTopic,
willQos, willRetain, willMsg, cleanSession)) {
Serial.print("MQTT Server Connected. ClientId: ");
Serial.println(clientId);
Serial.print("MQTT Server: ");
Serial.println(mqttServer);
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 = "test-user/Pub-" + 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
// Please note that subscribe The second parameter number of the function is QoS Level . Here for QoS = 1
if(mqttClient.subscribe(subTopic, subQoS)){
Serial.print("Subscribed 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("");
}
After power on , The program output is as follows ,
then , operation MQTT.fx This software .
1、 Because this is the client (ESP8266 Development board ) It's subscribers , Instead of being the publisher as in the previous section , So in operation MQTT.fx This software is used to connect MQTT The user name and password do not need to be set for the server ( The specific reason is that the server does not have the permission to subscribe to users ).

When publishing messages through software , ESP8266 ( subscriber ) Received with 1 After the first message , Will light up LED The lamp , Other messages go out LED The lamp .

meanwhile , It will output information through the serial port monitor .

The above test also involves a problem of quality degradation ( Because when I released it, I used QoS = 0 released ).
below , Will be with QoS = 1 ( Attention should be paid to the QoS=1 Setting requirements for ) Test the news release ( It is consistent with the test method in the previous chapter , take ESP8266 After disconnecting the power supply , adopt MQTT.fx The software publishes messages to topics , After the ESP8266 Reconnect the power supply ).

ESP8266 After the development board restarts , You can receive messages immediately .

There is another problem , This program does not involve publishing or subscribing to wills ( because ESP8266 The development board is just a subscriber ), The variables related to the will here are only used as connection functions connect The parameter of .
边栏推荐
- SQL splits strings into tables
- The left toolbar of hbuilder is missing
- Smart world 2030
- 目标检测——ADAS实战
- 干货丨微服务架构是什么?有哪些优点和不足?
- Use kubernetes resource lock to complete your own ha application
- 如何成为一名高级数字 IC 设计工程师(6-6)数字 IC 验证篇:系统级仿真
- OculusRiftS与Unity.UI的交互(1)-总览
- [从零开始学习FPGA编程-49]:视野篇 - 芯片是如何被设计出来的?
- Finally got the byte offer. The 25-year-old inexperienced experience in software testing is written to you who are still confused
猜你喜欢

Live broadcast preview | can SQL also play industrial machine learning? Mlops meetup V3 takes you to the bottom!

如何成为一名高级数字 IC 设计工程师(4-3)脚本篇:C 语言实现的文件读写操作

To apply for a test engineer after years, the resume with high scores should be written like this
![[redis] get to know redis for the first time](/img/02/3c6a7f6ea8c563386a4cd458024728.png)
[redis] get to know redis for the first time

2022.02.15

Differences between web testing and app testing

How to become a senior digital IC Design Engineer (4-5) script: file comparison operation implemented by shell script
![[redis] sortedset type](/img/7f/f5f1aa603c8994b669d52a435fed7e.png)
[redis] sortedset type

Koa 快速入门

How to prevent virus
随机推荐
How to prevent virus
字符串替换
e.target与e.currentTarget的区别
Fundamentals of scala (3): operators and process control
HBuilder左侧工具栏不见了
直播预告|SQL也能玩转工业级机器学习?MLOps meetup V3带你一探究竟!
想请教一下,如何选择券商?现在网上开户安全么?
Is there any risk in opening an account for Dongfang fortune stock? Is it safe for Dongfang fortune to open an account
Why install an SSL certificate on a web site?
[从零开始学习FPGA编程-49]:视野篇 - 芯片是如何被设计出来的?
【Redis】List类型
【Redis】Key的层级结构
I have summarized some experiences from the whole process of R & D platform splitting
[learn FPGA programming from scratch -50]: Vision - how are chips made? The thirteen steps of chip manufacturing.
SAP ui5 beginner tutorial 22 - development and use of filter
Query any field of any table in JPA to the util method of entity class dto
Use code binding DataGridView control to display tables in program interface
为什么建议大家尽可能选择自研公司
CTFHub-Web-密码口令-默认口令
Troubleshooting of pyinstaller failed to pack pikepdf