当前位置:网站首页>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 .
边栏推荐
- Which brokerage is safer and more convenient to open an account for compass mobile stock?
- [C language] Fibonacci sequence and frog jumping steps (the most detailed elementary frog jumping steps)
- 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!
- How to use project Gantt chart to make project report
- What is stock online account opening? Is it safe to open an account online?
- 【学习笔记】子集和问题
- HBuilder左侧工具栏不见了
- RISC CPU design based on FPGA (4) 36 questions about the project and their answers
- [机缘参悟-33]:眼见不一定为实,大多数时候“眼见为虚”
猜你喜欢

Understand flex layout in an article

What is the Valentine's Day gift given by the operator to the product?

chrome浏览器关闭更新弹窗

Boost the digital economy and face the future office | the launch of the new version of spreadjsv15.0 is about to begin

Tiflash compiler oriented automatic vectorization acceleration

The left toolbar of hbuilder is missing

干货丨微服务架构是什么?有哪些优点和不足?

Use code binding DataGridView control to display tables in program interface
![[redis] sortedset type](/img/7f/f5f1aa603c8994b669d52a435fed7e.png)
[redis] sortedset type

瀑布型项目管理最常用的10个小工具,可以自由搭建使用
随机推荐
RISC CPU design based on FPGA (4) 36 questions about the project and their answers
Is it safe to contact the account manager online to open an account for stock speculation?
Which brokerage is safer and more convenient to open an account for compass mobile stock?
Digital IC design, FPGA design written examination questions, answers and analysis of autumn move (1) 2022 Ziguang zhanrui (Part 1)
【Redis】List类型
How to become a senior digital IC Design Engineer (6-4) digital IC Verification: test point decomposition
如何成为一名高级数字 IC 设计工程师(3-5)工具篇:SpyGlass 技术
Blog publishing test 1
基于 RISC-V SoC 的可配置 FFT 系统设计(1)引言
[C language] Fibonacci sequence and frog jumping steps (the most detailed elementary frog jumping steps)
How does flush open an account? Is it safe to open an account online?
Smart world 2030
Studies of relative costs for development in different languages
同花顺究竟是如何开户?现在网上开户安全么?
Who do you want to know when opening a stock account? Is it safe to open an account online now?
【Redis】数据介绍 & 通用命令 & String类型
Blog publishing test 3
Scala Foundation (3): Operators and Process Control
[redis] key hierarchy
What is the dry goods microservice architecture? What are the advantages and disadvantages?