当前位置:网站首页>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 :
边栏推荐
- JVM的手术刀式剖析——一文带你窥探JVM的秘密
- [slam] orb-slam3 parsing - track () (3)
- LTE CSFB test analysis
- Microkernel structure understanding
- Take you to wechat applet development in 3 minutes
- Factors affecting user perception
- STC8H开发(十二): I2C驱动AT24C08,AT24C32系列EEPROM存储
- Facebook等大厂超十亿用户数据遭泄露,早该关注DID了
- 1. New project
- 20、 EEPROM memory (AT24C02) (similar to AD)
猜你喜欢

LTE CSFB test analysis

WPF效果第一百九十一篇之框选ListBox

C (XXIX) C listbox CheckedListBox Imagelist

Flask learning and project practice 8: introduction and use of cookies and sessions

多项目编程极简用例

Edcircles: a real time circle detector with a false detection control translation

【按键消抖】基于FPGA的按键消抖模块开发

JVM的手术刀式剖析——一文带你窥探JVM的秘密

Data analysis Seaborn visualization (for personal use)

JS Vanke banner rotation chart JS special effect
随机推荐
UDP reliable transport protocol (quic)
C mouse event and keyboard event of C (XXVIII)
Mapping between QoE and KQI
自动化测试怎么规范部署?
A brief introduction to symbols and link libraries in C language
C#(三十一)之自定义事件
判断当天是当月的第几周
Cf464e the classic problem [shortest path, chairman tree]
[introduction to Django] 11 web page associated MySQL single field table (add, modify, delete)
On Data Mining
cookie,session,Token 这些你都知道吗?
Cf603e pastoral oddities [CDQ divide and conquer, revocable and search set]
C language circular statement
【按键消抖】基于FPGA的按键消抖模块开发
Pointer written test questions ~ approaching Dachang
Factors affecting user perception
Custom event of C (31)
mysql关于自增长增长问题
C (thirty) C combobox listview TreeView
Blue Bridge Cup - Castle formula