esp8266用mqtt协议通讯

以前用esp8266作的东西是经过tcp链接来和服务器端通讯的,服务器端须要本身管理全部的链接,每一个链接要作心跳包,还要考虑通讯消息的可靠性。偶然看到了mqtt协议,发现能够拿来用。html

MQTT协议介绍git

ESP8266能够用的MQTT客户端github

安装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的,你们能够根据我的状况选择。我这边用的 activemqweb

  1. 下载activemq
    官方地址apache

  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模块订阅的主题发送命令控制继电器了。目前我已经能够经过天猫精灵和微信小程序控制我卧室的灯了。websocket

相关文章
相关标签/搜索