当前位置:网站首页>Learn Tai Chi Maker - mqtt (IV) server connection operation
Learn Tai Chi Maker - mqtt (IV) server connection operation
2022-06-26 02:52:00 【xuechanba】
Tutorial links :http://www.taichi-maker.com/homepage/esp8266-nodemcu-iot/iot-tuttorial/mqtt-tutorial/client-connect-mqtt-server/
MQTT Server connection operation
PC client connection MQTT Server side
First , Let's learn how to use computer software to connect the client and server . We will install a free MQTT Client software – MQTTfx.
Registration code is required for the latest version of the official website , Otherwise it won't work , Directly install the... Provided by Taiji serial port 1.7.1 edition .
Watch the video during the operation .
If encryption is required during transmission , Just use TCP/TLS port :8883.
ESP8266 Connect MQTT Server side
ESP8266 Of Arduino There are multiple in the development environment MQTT library , We will use the most popular PubSubClient Library to implement MQTT Internet of things applications .
/********************************************************************** Project name /Project : Zero basic introduction to the Internet of things Program name /Program name : connect_mqtt_server The team /Team : Taiji maker team / Taichi-Maker (www.taichi-maker.com) author /Author : CYNO Shuo date /Date(YYYYMMDD) : 20201109 Purpose of procedure /Purpose : The purpose of this program is to demonstrate how to use PubSubClient Library usage ESP8266 Connect to MQTT The server . ----------------------------------------------------------------------- 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();
}
void loop() {
if (mqttClient.connected()) {
// If the development board successfully connects to the server
mqttClient.loop(); // Keep the client's heartbeat
} else {
// If the development board fails to connect to the server
connectMQTTServer(); // Then try to connect to the server
}
}
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);
}
}
// 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 operation results are as follows :
1、 Pay attention to... In the program
WiFi.status()
I said before , After the client sends a connection request to the server , After the server receives the request , Will return a packet CONNACK , This CONNACK The information in the packet is as follows ,
There are two , One is sessionPresent , One is returnCode . This returnCode It is in the program status The return value of the function .
2、 Pay attention to... In the program
void loop() {
if (mqttClient.connected()) {
// If the development board successfully connects to the server
mqttClient.loop(); // Keep the client's heartbeat
} else {
// If the development board fails to connect to the server
connectMQTTServer(); // Then try to connect to the server
}
}
mqttClient.loop(); Is to keep the client's heartbeat . This function should be called frequently ( Do not add delay function ).
3、 There may be doubts , It's the connection MQTT Server time
mqttClient.connect(clientId.c_str()
Send according to the above CONNECT message ,
In this message , Three parameters are required , But there is only one in the program , namely clientId , Why is that ?
In fact, the other two parameters have default values , namely cleanSession = true ,keepAlive = 15.
边栏推荐
- Camtasia 2022 nouvelle vidéo d'ordinateur d'enregistrement ultra - clair
- Cox regression model
- The programmer's eight-year salary change has made netizens envious: you pay me one year's salary per month
- [solution] cmake was unable to find a build program corresponding to "UNIX makefiles"
- 7 tips to change your life
- Deep understanding of distributed cache design
- High availability in Internet three highs (high concurrency, high performance and high availability)
- 版本管理工具使用
- Never criticize
- Camtasia 2022 new ultra clear recording computer video
猜你喜欢
Dynamic analysis and calculation of expression, flee is really sweet to use
Little p weekly Vol.10
Introduction to bloc: detailed explanation of cube
[机器翻译]—BLEU值的计算
Redis configuration and optimization of NoSQL
How did the thief unlock the password after the iPhone was stolen? After reading the long knowledge
【flask入门系列】flask处理请求和处理响应
财富自由技能:把自己产品化
How do I fix the iPhone green screen problem? Try these solutions
The programmer's eight-year salary change has made netizens envious: you pay me one year's salary per month
随机推荐
Use annotationdbi to convert gene names in R
请指教同花顺开户选选择哪家券商比较好?网上开户是否安全么?
Multi surveyor Gongshu Xiao sir_ The solution of using websocket error reporting under working directory
Redis configuration and optimization of NoSQL
Multi surveyor Gongshu campus Xiao sir_ Page error in Jenkins
解读Oracle
Share some remote office experience in Intranet operation | community essay solicitation
7 tips to change your life
MySQL doit maîtriser 4 langues!
组件与路由
Binary search
无法上网问题解决过程
How to open a stock account? Is it safe to open an account online?
DF reports an error stale file handle
Pie chart metamorphosis record, the liver has 3000 words, collection is to learn!
[机器翻译]—BLEU值的计算
Wechat launched a web version transmission assistant. Is it really easy to use?
Sloppy formula
力扣(LeetCode)176. 第二高的薪水(2022.06.25)
【系统架构】-如何评估软件架构