1. 程式人生 > >esp8266用mqtt協議通訊

esp8266用mqtt協議通訊

之前用esp8266做的東西是通過tcp連線來和伺服器端通訊的,伺服器端需要自己管理所有的連線,每個連線要做心跳包,還要考慮通訊訊息的可靠性。偶然看到了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模組訂閱的主題傳送命令控制繼電器了。目前我已經可以通過天貓精靈和微信小程式控制我臥室的燈了。