MQTT通讯-使用EMQX将ESP8266与微信小程序通讯

概念

MQTT

MQTT(Message Queuing Telemetry Transport)是一种基于发布/订阅范式的“轻量级”消息协议,由IBM发布。MQTT可以在TCP/IP协议族上工作,并且是为硬件性能低下的远程设备以及网络状况糟糕的情况下而设计的发布/订阅型消息协议。因此,MQTT协议适用于硬件性能低下的远程设备以及网络状况不佳的环境中,如机器与机器(M2M)通信和物联网(IoT)等领域。
在这里插入图片描述
关于MQTT还有很多其他的概念例如订阅发布机制、消息服务等级、心跳机制等,在阅读文章之前请先了解相关的知识,推荐学习地址

ESP8266

乐鑫ESP8266是一款内置WiFi功能的单片机,它具有高性能的无线SOC特性,能够为移动设备和物联网应用提供无线连接功能。
ESP8266的特点如下:
封装尺寸小,超低功耗,支持多种电源模式。
带有高性能的UART-WiFi透传模块,能够直接连接至其他基于微控制器的设备。
支持STA/AP/STA+AP三种工作模式,可以作为无线接入点或者客户端使用。
内置TCP/IP协议栈,支持多路TCP Client连接,无需添加任何匹配电路。
支持三种天线接口形式:板载PCB天线、IPEX接口和邮票孔接口。
可广泛应用于智能电网、智能交通、智能家具、手持设备、工业控制等领域。
需要注意的是,虽然我提供的信息尽可能准确,但产品可能在不断更新和变化,建议查阅乐鑫官方网站获取最新和最准确的信息。
在这里插入图片描述

搭建自己的MQTT服务器

本文使用的是EMQX 官网地址
购买自己的服务器后使用下面代码部署

curl -s https://assets.emqx.com/scripts/install-emqx-rpm.sh | sudo bash
sudo yum install emqx -y
sudo systemctl start emqx

在这里插入图片描述

安装完成之后 打开后台http://你的IP地址/#/login?to=/websocket 初始账户admin密码是public。
在这里插入图片描述

烧录ESP8266代码

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

// WiFi
const char *ssid = "mousse"; // Enter your WiFi name
const char *password = "qweqweqwe";  // Enter WiFi password

// MQTT Broker
const char *mqtt_broker = "broker.emqx.io";
const char *topic = "esp8266/test";
const char *mqtt_username = "emqx";
const char *mqtt_password = "public";
const int mqtt_port = 1883;

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
    
    
    // Set software serial baud to 115200;
    Serial.begin(115200);
    // connecting to a WiFi network
    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
    
    
        delay(500);
        Serial.println("Connecting to WiFi..");
    }
    Serial.println("Connected to the WiFi network");
    //connecting to a mqtt broker
    client.setServer(mqtt_broker, mqtt_port);
    client.setCallback(callback);
    while (!client.connected()) {
    
    
        String client_id = "esp8266-client-";
        client_id += String(WiFi.macAddress());
        Serial.printf("The client %s connects to the public mqtt broker\n", client_id.c_str());
        if (client.connect(client_id.c_str(), mqtt_username, mqtt_password)) {
    
    
            Serial.println("Public emqx mqtt broker connected");
        } else {
    
    
            Serial.print("failed with state ");
            Serial.print(client.state());
            delay(2000);
        }
    }
    // publish and subscribe
    client.publish(topic, "hello emqx");
    client.subscribe(topic);
}

void callback(char *topic, byte *payload, unsigned int length) {
    
    
    Serial.print("Message arrived in topic: ");
    Serial.println(topic);
    Serial.print("Message:");
    for (int i = 0; i < length; i++) {
    
    
        Serial.print((char) payload[i]);
    }
    Serial.println();
    Serial.println("-----------------------");
}

void loop() {
    
    
    client.loop();
}

将上面的信息改成自己的
注意添加PubSubClient库

微信小程序开发

官方接入教程
创建微信小程序的项目,并添加库文件,本文使用的是MQTT.js,同时针对不用的客户端都有相关的SDK,这里微信小程序使用JavaScript语言所以使用本库。
在这里插入图片描述
在这里插入图片描述
EMQX要求微信小程序支持通过 WebSocket 进行即时通信,EMQX 的 MQTT Over WebSocket 能够完全兼容使用在微信小程序上。
提示
由于微信小程序的规范限制,EMQX 使用微信小程序接入时需要注意以下几点:
必须使用已经通过域名备案 (opens new window)的域名接入
域名需要在小程序管理后台 (opens new window)域名/IP 白名单中(开发 -> 开发设置 -> 服务器域名 -> socket 合法域名)
仅支持 WebSocket/TLS 协议,需要为域名分配受信任 CA 颁发的证书
由于微信小程序 BUG,安卓真机必须使用 TLS/443 端口,否则会连接失败(即连接地址不能带端口)

下载并导入 mqtt.mini.js
在这里插入图片描述
在微信小程序onLoad声明周期中测试。

	 onLoad(options) {
    
    
    try {
    
    
      console.log("开始链接");
      const clientId = new Date().getTime();//mqtt的连接ID
      app.globalData.client = mqtt.connect(`wxs://${
      
      host}/mqtt`, {
    
    
          username,
          password,
          reconnectPeriod,
          connectTimeout,
          clientId,
      });
    } catch (error) {
    
    
        console.log("mqtt.connect error", error);
    }
    if (app.globalData.client) {
    
    
      app.globalData.client.subscribe("test")
    }

    app.globalData.client.on("message", (topic, payload) => {
    
    
      console.log(`收到消息 - Topic: ${
      
      topic},Payload: ${
      
      payload}`)
      // app.globalData.currMsg = JSON.parse(payload);
      // console.log(typeof payload)
    });
  }

这里已经收到遗嘱消息
在这里插入图片描述
订阅、发布、消息回调更多API请查询MQTT.js。

猜你喜欢

转载自blog.csdn.net/Systemmax20/article/details/132651442