当前位置:网站首页>Esp32 (based on Arduino) connects the mqtt server of emqx to upload information and command control
Esp32 (based on Arduino) connects the mqtt server of emqx to upload information and command control
2022-07-06 03:53:00 【Haoyuehua】
Preface :
EMQX The open source version provides free local LAN mqtt The server , Many operations of the Internet of things can be realized by subscribing to the theme and publishing the information under the theme . What operation ? Such as dumping the sensor information collected by the device to the local database through subscription . The switch of the equipment is controlled by publishing .
The upload information and command control are based on a client built locally by me as the intermediate hub . The local client opens a web And provides interface access .
Upload information :
Because I have written a client subscription locally ESP32 The topic of the release information device/date,esp32 Each pair device/date Release a message , The client will dump it to mysql database .
Command control :
esp32 subscribe esp32/dev/# , Not exactly , there # It can be 1,2,3 representative esp32 The controller dev1,dev2,dev3( about esp32 disjunctive led The lamp , The motor , Buzzer, etc ). The control here is the most direct control , In order to achieve indirect control, such as Andrade ,web End control can send parameters through the interface to let the local client publish esp32/dev/# The information under the corresponding topic is controlled by ESP32.
problem :
1:esp32 Of json Send data and let the client receive .
Reference resources
Add library
#include <ArduinoJson.h>
What is sent is in the form of string json data
StaticJsonDocument<200> sensor_json;
sensor_json["sensor_val"] = hallRead();
sensor_json["sensor_val"] = cnt;
sensor_json["to"] = "starmelon";
String msg;
serializeJson(sensor_json, msg);
2:esp32 Can't connect emqx Of mqtt The server .
Because it is under the LAN ,emqx Under the mqtt The server has its LAN address , This LAN address is emqx Of the host ip Address , If you use a local LAN built by a router and use IP Automatic allocation , You need to change the server address every time , The same is true for connecting mobile phone hotspots .
Default domain name :"broker-cn.emqx.io" String format
The problem is coming. , When I use this default domain name as the server address ,esp32 You can really send messages to the set theme , But on my host poho( A monitoring software ) And the client did not receive the message .
Only when I return to my original state , Use LAN address 192.168.43.234,esp32 Can work normally ,poho And the client can also work normally .
Normal message reporting
Realization :
#include <WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>
#include <ArduinoJson.h>
StaticJsonDocument<200> sensor_json;
String realmsg="";
int LED=2;
// Set up wifi Access information ( Please according to your WiFi Modify the information )
const char* ssid = "realme";
const char* password = "12345678";
const char* mqttServer = "192.168.43.246";// This machine ip Address
// Published message field
typedef struct {
int msg1;
int msg2;
int msg3;
}msg;
int count=0;// Publish message interval
// 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/
//------------------ Global variable definition -----------------
msg mymsg={123,45,6};// Define the message structure
Ticker ticker;
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
//------------------ Global variable definition -----------------
void tickerCount(){//Ticker Callback function
count++;
// The test data
sensor_json["msg1"] = 12;
sensor_json["msg2"] =21;
sensor_json["msg3"] = 98;
serializeJson(sensor_json, realmsg);
}
void pubmsg( const String &topicString, const String &messageString){
char publishTopic[topicString.length() + 1];
strcpy(publishTopic, topicString.c_str());
char publishMsg[messageString.length() + 1];
strcpy(publishMsg, messageString.c_str());
// Realization ESP8266 Post information to the subject
if(mqttClient.publish(publishTopic, publishMsg)){
Serial.println("Publish Topic:");Serial.println(publishTopic);
Serial.println("Publish message:");Serial.println(publishMsg);
} else {
Serial.println("Message Publish Failed.");
}
}
void setup() {
pinMode(LED, OUTPUT); // Set up on the board LED Pin is output mode
digitalWrite(LED, LOW); // Turn it on and off the board LED
Serial.begin(9600); // Start serial communication
// Ticker Timing object
ticker.attach(2, tickerCount); // every 2s Call its callback function
// 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 (mqttClient.connected()) { // If the development board successfully connects to the server
if (count >= 2){
pubmsg("device/date",realmsg);
realmsg="";
count = 0;
}
mqttClient.loop(); // Process information and heartbeat
} else { // If the development board fails to connect to the server
connectMQTTserver(); // Then try to connect to the server
}
}
// 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 = "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);
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);
int temp=0;
while(*topic){
temp++;
topic++;
}
Serial.println(" Theme length :");
Serial.println(temp);
if(temp>11){
if((char)topic[11]=='1'){
if ((char)payload[0] == 'O' && (char)payload[1] == 'F') { // If you receive a message with “1” For the beginning
digitalWrite(LED, LOW); // Then light up LED.
} else {
digitalWrite(LED, HIGH); // Otherwise, it goes out LED.
}
}
}
}
// Subscribe to specific topics
void subscribeTopic(){
// Output whether the topic has been successfully subscribed through the serial port monitor 1 And the topics you subscribe to 1 name
if(mqttClient.subscribe("device/dev/#")){
Serial.println("Subscrib Topic:");
Serial.println("device/action");
} else {
Serial.print("Subscribe Fail...");
}
// Output whether the topic has been successfully subscribed through the serial port monitor 2 And the topics you subscribe to 2 name
}
// 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("");
}
effect :
stay poho The control information can be released on the control board LED The lamp .
Reference resources :
边栏推荐
- SAP ALV color code corresponding color (finishing)
- Recommended papers on remote sensing image super-resolution
- A brief introduction to symbols and link libraries in C language
- Plus d'un milliard d'utilisateurs de grandes entreprises comme Facebook ont été compromis, il est temps de se concentrer sur le did
- C#(二十九)之C#listBox checkedlistbox imagelist
- 使用JS完成一个LRU缓存
- Teach you to build your own simple BP neural network with pytoch (take iris data set as an example)
- Record the pit of NETCORE's memory surge
- How to modify field constraints (type, default, null, etc.) in a table
- Ethernet port &arm & MOS &push-pull open drain &up and down &high and low sides &time domain and frequency domain Fourier
猜你喜欢
JVM的手术刀式剖析——一文带你窥探JVM的秘密
C#(二十七)之C#窗体应用
Plus d'un milliard d'utilisateurs de grandes entreprises comme Facebook ont été compromis, il est temps de se concentrer sur le did
Facebook等大厂超十亿用户数据遭泄露,早该关注DID了
C language circular statement
C#(三十一)之自定义事件
1. New project
How do we make money in agriculture, rural areas and farmers? 100% for reference
在 .NET 6 中使用 Startup.cs 更简洁的方法
Brush questions in summer -day3
随机推荐
BUAA magpie nesting
In Net 6 CS more concise method
1、工程新建
【PSO】基于PSO粒子群优化的物料点货物运输成本最低值计算matlab仿真,包括运输费用、代理人转换费用、运输方式转化费用和时间惩罚费用
多项目编程极简用例
[slam] orb-slam3 parsing - track () (3)
【可调延时网络】基于FPGA的可调延时网络系统verilog开发
Custom event of C (31)
【FPGA教程案例11】基于vivado核的除法器设计与实现
P7735-[noi2021] heavy and heavy edges [tree chain dissection, line segment tree]
Maxay paper latex template description
Cubemx 移植正点原子LCD显示例程
On Data Mining
Record the pit of NETCORE's memory surge
Simple blog system
Align items and align content in flex layout
ESP32(基于Arduino)连接EMQX的Mqtt服务器上传信息与命令控制
【FPGA教程案例12】基于vivado核的复数乘法器设计与实现
Facebook and other large companies have leaked more than one billion user data, and it is time to pay attention to did
[prediction model] difference method model