esp8266用mqtt協議通信


之前用esp8266做的東西是通過tcp連接來和服務器端通信的,服務器端需要自己管理所有的連接,每個連接要做心跳包,還要考慮通信消息的可靠性。偶然看到了mqtt協議,發現可以拿來用。

MQTT協議介紹

ESP8266可以用的MQTT客戶端

安裝MQTT客戶端

  1. 下載客戶端連接
  2. 把下載好文件解壓縮到 arduinoide安裝目錄的libraries文件夾下,重啟IDE

燒制程序到ESP8266

//注意我這邊用的是esp12e模塊,淘寶16塊左右,所以有16引腳,esp8266也可以燒制以下程序

#include <ESP8266WiFi.h>
#include <PubSubClient.h>

// Update these with values suitable for your network.

const char* ssid = "........";
const char* password = "........";
const char* mqttServer = ".....";
const int mqttPort = 9999;
const char* mqttUserName = "...";
const char* mqttPassword = "...";
const char* lightTopic = "...";
const char* willTopic = "...";
const char* onlineTopic = "..."; 
const char* clientId = "...";

WiFiClient espClient;
PubSubClient client(espClient);

int lightPin = 16;

void setup_wifi() {

  delay(10);
  // We start by connecting to a WiFi network
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }  
  Serial.println("");
  Serial.println("WiFi connected");
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
}

void callback(char* topic, byte* payload, unsigned int length) {
  Serial.println(topic);
  String command = "";
  for (int i = 0; i < length; i++) {
    command += (char)payload[i];
  }
  Serial.println(command);
  handlePayload(String(topic), command); 
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    //詳細參數說明請查看文檔
    if (client.connect(clientId,mqttUserName,mqttPassword,willTopic,1,0,clientId)) {
      Serial.println("connected");
      client.publish(onlineTopic, clientId);
      client.subscribe(lightTopic, 1);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}

void setup() {
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  setup_wifi();
  client.setServer(mqttServer, mqttPort);
  client.setCallback(callback);
}

void loop() {

  if (!client.connected()) {
    reconnect();
  }
  client.loop();
}

//處理命令
String handlePayload(String topic, String payload) {
  if (String(lightTopic).equals(topic)) {
    //light command
    if (String("lightOn").equals(payload)) {
      digitalWrite(lightPin, HIGH);
    } else if (String("lightOff").equals(payload)) {
      digitalWrite(lightPin, LOW);
    } 
  }
}

安裝MQTT服務器

服務器列表 中的服務器都是可以支持mqtt的,大家可以根據個人情況選擇。我這邊用的 activemq

  1. 下載activemq
    官方地址

  2. 解壓縮,然后進入bin目錄 運行以下命令啟動

activemq.bat start

3.打開examples\mqtt\websocket目錄下的index.html
可以進行測試
這里寫圖片描述

4.配置端口和用戶名密碼
打開config/activemq.xml文件


<!-- 找到一下內容,即是配置不同協議端口 -->
        <transportConnectors>
            <!-- DOS protection, limit concurrent connections to 1000 and frame size to 100MB -->
            <transportConnector name="openwire" uri="tcp://0.0.0.0:61616?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="amqp" uri="amqp://0.0.0.0:5672?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="stomp" uri="stomp://0.0.0.0:61613?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="mqtt" uri="mqtt://0.0.0.0:1883?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
            <transportConnector name="ws" uri="ws://0.0.0.0:61614?maximumConnections=1000&amp;wireFormat.maxFrameSize=104857600"/>
        </transportConnectors>

<!-- 在broker節點的最后添加 -->
<plugins>
            <simpleAuthenticationPlugin>
                <users>
                    <authenticationUser username="admin" password="admin" groups="users,admins"/>
                    <authenticationUser username="user" password="password" groups="users"/>     
                </users>
            </simpleAuthenticationPlugin>
        </plugins>

測試

給esp12e模塊的16引腳接個繼電器,通電,就可以通過向esp12e模塊訂閱的主題發送命令控制繼電器了。目前我已經可以通過天貓精靈和微信小程序控制我卧室的燈了。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM