当前位置:网站首页>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 .
边栏推荐
- Necessary technologies for chip manufacturers (1) Introduction
- Live broadcast preview | can SQL also play industrial machine learning? Mlops meetup V3 takes you to the bottom!
- How to become a senior digital IC Design Engineer (5-1) theory: clock technology, reset Technology
- How to become a senior digital IC Design Engineer (6-7) digital IC Verification: debug skills
- [learn FPGA programming from scratch -50]: Vision - how are chips made? The thirteen steps of chip manufacturing.
- Flex application: realize two rows and five columns of data, self-adaptive
- How does flush open an account? Is it safe to open an account online now?
- [redis] list type
- Scala 基础 (三):运算符和流程控制
- 字符串替换
猜你喜欢
Fundamentals of scala (3): operators and process control

SAP ui5 beginner tutorial 22 - development and use of filter

三角函数计算
![[MySQL practice of high concurrency, high performance and high availability of massive data -9] - transaction concurrency control solutions lbcc and mvcc](/img/62/77c2274db4f92ad1d88901e149251c.jpg)
[MySQL practice of high concurrency, high performance and high availability of massive data -9] - transaction concurrency control solutions lbcc and mvcc

Chrome browser close update Popup

项目研发,有哪些好用的免费脑图工具软件

HBuilder左侧工具栏不见了

How to become a senior digital IC Design Engineer (4-2) script: file read / write operation realized by Verilog HDL code

【Redis】Key的层级结构

To apply for a test engineer after years, the resume with high scores should be written like this
随机推荐
字符串长度
Google Borg论文
【网络通信学习笔记】Socket.IO的搭建和部署
The left toolbar of hbuilder is missing
How to become a senior digital IC Design Engineer (6-4) digital IC Verification: test point decomposition
B1009 irony
Zhongyi technology resumed the review status of the gem IPO, and xuxiaofei no longer acted as a practicing lawyer
The 10 most commonly used gadgets for waterfall project management can be built and used freely
Blog publishing test 3
[redis] get to know redis for the first time
基于 FPGA 的 RISC CPU 设计(4)关于项目的 36 个问题及其答案
Is there any risk in opening an account for Dongfang fortune stock? Is it safe for Dongfang fortune to open an account
OpenResty 使用介绍
微信运动自动点赞
Studies of relative costs for development in different languages
为什么要在网站上安装SSL证书?
How does flush open an account? Is it safe to open an account online?
11-Go基础:接口
Wechat campaign auto like
Tiflash compiler oriented automatic vectorization acceleration