当前位置:网站首页>Esp8266 connect onenet (old mqtt mode)
Esp8266 connect onenet (old mqtt mode)
2022-07-06 12:19:00 【XlinliY. Zhang】
One 、 Why use the old version MQTT
1、 Simple
Use ESP8266 + Arduino The way of development , Only minimal code is needed , You can achieve cloud .
MQTT stay ESP8266 There are ready-made libraries on , We just need to create devices on the platform , Input parameters in the program .
2、 two-way
In contrast to HTTP One way connection of ,MQTT It's two-way , There is no need for the device to request the server to send data , Greatly simplifies the process .
Two 、 How to achieve MQTT Access
1、 Register device
Directly above
The first step, of course, is to log in to your account ( No direct registration + Real name authentication is enough , Free )
And then go to the console
Then start adding product devices
Using the old console
Add products before adding devices
Finished adding products , Then click the product just added to enter product management , Then start adding devices
equipment ID by CLIENTID The authentication information is USERPASSWORD product ID by USERNAME
To this step , The device has been added , Data flow can be ignored , After the device uploads data, the system will automatically add data nodes .
2、 burn ESP8266 Code
About Arduino IDE How to burn ESP8266, There are many tutorials online , This step will not be repeated , Go straight to the code
const char *Device_ID = "*******"; // equipment ID
const char *Product_ID = "*******"; // product ID
const char *Api_KEY = "*******"; // Authentication information
const char *WiFi_SSID = "*******"; //WiFi name
const char *WiFi_Password = "***********"; //WiFi password
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
float Current = 0;
uint8_t Upload_Package[100];
uint32_t Last_Updata_Time = 0;
WiFiClient espClient;
PubSubClient client(espClient);
void WiFi_Init(void);
void MQTT_Init(void);
void MQTT_Reconnection(void);
void MQTT_Callback(char *MQTT_Topic, uint8_t *MQTT_Payload, uint16_t MQTT_Payload_Len);
void setup()
{
Serial.begin(115200);
WiFi_Init();
MQTT_Init();
}
void loop()
{
if (!client.connected())
MQTT_Reconnection();
if (millis() - Last_Updata_Time >= 3000)
{
Last_Updata_Time = millis();
float ADC_Value = analogRead(A0);
Current = (ADC_Value - 512) * 0.033783784;
Serial.print("Current: ");
Serial.print(Current);
Serial.println(" A\r\n");
memset(Upload_Package, 0, 100);
String Json_Buffer = ",;Current,";
Json_Buffer += String(Current);
Json_Buffer += ";";
Upload_Package[0] = 5;
Upload_Package[1] = highByte(Json_Buffer.length());
Upload_Package[2] = lowByte(Json_Buffer.length());
for (int i = 0; i < Json_Buffer.length(); i++)
Upload_Package[i + 3] = Json_Buffer.c_str()[i];
client.publish("$dp", Upload_Package, Json_Buffer.length() + 3);
}
client.loop();
}
void WiFi_Init(void)
{
Serial.print("\r\n\r\nConnecting to ");
Serial.print(WiFi_SSID);
WiFi.mode(WIFI_STA);
WiFi.begin(WiFi_SSID, WiFi_Password);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.print("\r\nWiFi Connected.\r\nIP address: ");
Serial.println(WiFi.localIP());
}
void MQTT_Init(void)
{
client.setServer("183.230.40.39", 6002);
client.setCallback(MQTT_Callback);
}
void MQTT_Callback(char *MQTT_Topic, uint8_t *MQTT_Payload, uint16_t MQTT_Payload_Len)
{
Serial.printf("Topic: %s[%d]:\r\n", MQTT_Topic, MQTT_Payload_Len);
for (uint16_t i = 0; i < MQTT_Payload_Len; i++)
{
Serial.print(MQTT_Payload[i] < 0x10 ? " 0x0" : " 0x");
Serial.print(MQTT_Payload[i]);
}
Serial.println();
}
void MQTT_Reconnection(void)
{
while (!client.connected())
{
Serial.println("MQTT Reconnection.");
if (client.connect(Device_ID, Product_ID, Api_KEY))
Serial.println("MQTT Connected");
else
{
Serial.print("Connect Failed, Error Code = ");
Serial.print(client.state());
Serial.println(", Try again in 5 seconds.");
delay(5000);
}
}
}
This example will A0 The analog value read by the port is uploaded to onenet, And after receiving onenet When sending information, print it on the serial port
3、 ... and 、 The program on
1、 Networking related
// First of all WiFi Parameters
const char *WiFi_SSID = "*******"; //WiFi name
const char *WiFi_Password = "***********"; //WiFi password
// Secondly, we should have WiFi Driver library
#include <ESP8266WiFi.h>
// Declare the function
void WiFi_Init(void);
void setup()//setup Only once , Just put it in the Internet
{
// The serial port should be initialized , Easy to view the process
Serial.begin(115200);
// Start WiFi initialization
WiFi_Init();
}
void loop()
{
}
void WiFi_Init(void)
{
// Print the prompt
Serial.print("\r\n\r\nConnecting to ");
Serial.print(WiFi_SSID);
//STA Pattern , Pass in wifi Parameters
WiFi.mode(WIFI_STA);
WiFi.begin(WiFi_SSID, WiFi_Password);
// Loop to WiFi Connect
while (WiFi.status() != WL_CONNECTED)
{
// Print regularly ............ Tell you I didn't crash
delay(500);
Serial.print(".");
}
// Print prompt and local IP Address
Serial.print("\r\nWiFi Connected.\r\nIP address: ");
Serial.println(WiFi.localIP());
}
2、 Cloud related
// First of all, there must be parameters
const char *Device_ID = "711583270"; // equipment ID
const char *Product_ID = "421451"; // product ID
const char *Api_KEY = "20210425"; // Authentication information
// Provide socket agreement (MQTT be based on TCP)
#include <ESP8266WiFi.h>
// Provide MQTT agreement
#include <PubSubClient.h>
// Create objects
WiFiClient espClient;
PubSubClient client(espClient);
// Declare the function
void MQTT_Init(void);
void MQTT_Reconnection(void);
void setup()
{
Serial.begin(115200);
MQTT_Init();// initialization MQTT
}
void loop()//loop Equivalent to other microcontrollers while(1)
{
// Judge MQTT Is it connected , Reconnect if not
if (!client.connected())
MQTT_Reconnection();
//MQTT function
client.loop();
}
void MQTT_Init(void)
{
client.setServer("183.230.40.39", 6002);// Setup server IP Address and port
client.setCallback(MQTT_Callback); // Set the callback function that receives the information
}
//MQTT Reconnection function
void MQTT_Reconnection(void)
{
while (!client.connected())// Loop to MQTT Connected
{
Serial.println("MQTT Reconnection.");
if (client.connect(Device_ID, Product_ID, Api_KEY))// call MQTT Connect , Pass in the corresponding parameter , return 1 The connection is successful
Serial.println("MQTT Connected");
else// Otherwise, print an error message
{
Serial.print("Connect Failed, Error Code = ");
Serial.print(client.state());
Serial.println(", Try again in 5 seconds.");
delay(5000);
}
}
}
3、 Sending and receiving data
// Initializing MQTT When , We have set the callback function
client.setCallback(MQTT_Callback);
// therefore , When you receive a message , Will call this function , The meanings of the passed in parameters are as follows
//MQTT_Topic The subject of the received message
//MQTT_Payload The content of the received message
//MQTT_Payload_Len The length of the content of the received message
void MQTT_Callback(char *MQTT_Topic, uint8_t *MQTT_Payload, uint16_t MQTT_Payload_Len)
{
// Only printing is done here , There are no other processing operations
Serial.printf("Topic: %s[%d]:\r\n", MQTT_Topic, MQTT_Payload_Len);
for (uint16_t i = 0; i < MQTT_Payload_Len; i++)
{
Serial.print(MQTT_Payload[i] < 0x10 ? " 0x0" : " 0x");
Serial.print(MQTT_Payload[i]);
}
Serial.println();
}
// To upload data , Then use the publish function to publish
//$dp ONENT Upload data fixed theme
//Upload_Package Uploaded data array
//Json_Buffer.length() + 3 Length of uploaded data , Because contain 0, Use cannot use strlen Calculate the length
client.publish("$dp", Upload_Package, Json_Buffer.length() + 3);
4、 Upload protocol
Upload_Package[0] In upload format , See ONENET file , Here is 5
The data sample :,; Data name , Data values ;
Upload_Package[1] * 256 + Upload_Package[2] by 3~ The length of the end of the data
Four 、 summary
1、 A few things to pay attention to
ONENET The upload data format of is a little special , front 3 Bytes are in fixed format , Then comes the real data
ONENET The port number of is 6002 Not traditional 1883
Format 5 Even characters don't need double quotes ( differ JSON)
2、 shortcoming
ONENET The time of issuing data is different from that of updating data , Sometimes data is distributed , Control has not been refreshed
The fault is described as follows :
Press the button , He changed ON, It changed again after a while OFF, Until the device uploads ON Data will become ON
边栏推荐
- ESP学习问题记录
- MySQL takes up too much memory solution
- inline详细讲解【C语言】
- arduino获取数组的长度
- 关于Gateway中使用@Controller的问题
- 小天才电话手表 Z3工作原理
- Esp8266 uses Arduino to connect Alibaba cloud Internet of things
- Mp3mini playback module Arduino < dfrobotdfplayermini H> function explanation
- .elf .map .list .hex文件
- arduino UNO R3的寄存器写法(1)-----引脚电平状态变化
猜你喜欢
Working principle of genius telephone watch Z3
arduino JSON数据信息解析
arduino UNO R3的寄存器写法(1)-----引脚电平状态变化
Feature of sklearn_ extraction. text. CountVectorizer / TfidVectorizer
[esp32 learning-2] esp32 address mapping
Arduino JSON data information parsing
高通&MTK&麒麟 手机平台USB3.0方案对比
NRF24L01故障排查
MP3mini播放模块arduino<DFRobotDFPlayerMini.h>函数详解
高通&MTK&麒麟 手機平臺USB3.0方案對比
随机推荐
荣耀Magic 3Pro 充电架构分析
RT thread API reference manual
Whistle+switchyomega configure web proxy
Characteristics, task status and startup of UCOS III
The first simple case of GNN: Cora classification
如何给Arduino项目添加音乐播放功能
ESP学习问题记录
Kconfig Kbuild
arduino获取数组的长度
E-commerce data analysis -- salary prediction (linear regression)
arduino UNO R3的寄存器写法(1)-----引脚电平状态变化
VSCode基础配置
There are three iPhone se 2022 models in the Eurasian Economic Commission database
VIM command line notes
Imgcat usage experience
MySQL takes up too much memory solution
js 变量作用域和函数的学习笔记
arduino JSON数据信息解析
高通&MTK&麒麟 手机平台USB3.0方案对比
JS object and event learning notes