当前位置:网站首页>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

Arduino-ESP32 Medium Json Construction and analysis _ Xingshuiguagua's blog -CSDN Blog _arduino esp32 json

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 :

Zero basic introduction to the Internet of things – MQTT The basic chapter – Catalog – Taiji maker (taichi-maker.com)

原网站

版权声明
本文为[Haoyuehua]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060346142898.html