当前位置:网站首页>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 :
边栏推荐
- [meisai] meisai thesis reference template
- Indicator system of KQI and KPI
- cookie,session,Token 这些你都知道吗?
- AcWing 243. A simple integer problem 2 (tree array interval modification interval query)
- No qualifying bean of type ‘......‘ available
- Svg drag point crop image JS effect
- 2.1 rtthread pin device details
- SAP ALV color code corresponding color (finishing)
- 【FPGA教程案例11】基于vivado核的除法器设计与实现
- Suggestions for new engineer team members
猜你喜欢
How to standardize the deployment of automated testing?
Exchange bottles (graph theory + thinking)
Image super resolution using deep revolutionary networks (srcnn) interpretation and Implementation
Alibaba testers use UI automated testing to achieve element positioning
KS008基于SSM的新闻发布系统
Pointer for in-depth analysis (problem solution)
WPF效果第一百九十一篇之框选ListBox
Cf464e the classic problem [shortest path, chairman tree]
JS Vanke banner rotation chart JS special effect
Overview of super-resolution reconstruction of remote sensing images
随机推荐
【FPGA教程案例12】基于vivado核的复数乘法器设计与实现
WPF效果第一百九十一篇之框选ListBox
Oracle ORA error message
[American competition] mathematical terms
Blue style mall website footer code
简述C语言中的符号和链接库
Containerization Foundation
WPF effect Article 191 box selection listbox
Serial port-rs232-rs485-ttl
[slam] lidar camera external parameter calibration (Hong Kong University marslab) does not need a QR code calibration board
1. New project
多项目编程极简用例
Ks003 mall system based on JSP and Servlet
Flask learning and project practice 8: introduction and use of cookies and sessions
Schnuka: what is visual positioning system and how to position it
【PSO】基于PSO粒子群优化的物料点货物运输成本最低值计算matlab仿真,包括运输费用、代理人转换费用、运输方式转化费用和时间惩罚费用
Take you to wechat applet development in 3 minutes
Record the pit of NETCORE's memory surge
2.2 STM32 GPIO操作
【按键消抖】基于FPGA的按键消抖模块开发