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。

要在微信小程序中连接到MQTT服务器并控制ESP8266 LED灯,需要进行以下几个步骤: 1. 搭建MQTT服务器 可以选择自己搭建一台MQTT服务器,或者使用第三方的MQTT服务器提供商,例如EMQ X, HiveMQ等。在这里我们以EMQ X为例,按照官方文档进行安装和配置。 2. 在小程序中引入MQTT.js 使用MQTT.js库实现MQTT服务器的连接和数据通信。可以通过npm或者直接下载在项目中使用。 3. 连接MQTT服务器 使用MQTT.js库提供的mqtt.connect()方法连接到MQTT服务器,需要指定MQTT服务器的IP地址和端口号。例如: ```javascript var mqtt = require('mqtt') var client = mqtt.connect('mqtt://localhost:1883') ``` 4. 发布消息 使用MQTT.js库提供的client.publish()方法向MQTT服务器发布消息。例如: ```javascript client.publish('topic', 'hello world') ``` 在这里,‘topic’是消息的主题,‘hello world’是消息的内容。 5. 订阅主题 使用MQTT.js库提供的client.subscribe()方法订阅MQTT服务器上的特定主题。例如: ```javascript client.subscribe('topic') ``` 6. 接收消息 使用MQTT.js库提供的client.on()方法监听MQTT服务器发送过来的消息。例如: ```javascript client.on('message', function (topic, message) { // message is Buffer console.log(message.toString()) client.end() }) ``` 7. 控制ESP8266 LED灯 在ESP8266上运行一个MQTT客户端程序,订阅特定的主题,可以接收来自MQTT服务器发布的消息。根据接收到的消息控制LED灯的开关状态。例如: ```c++ #include <PubSubClient.h> #include <WiFiClient.h> const char* ssid = "your_SSID"; const char* password = "your_PASSWORD"; const char* mqtt_server = "mqtt_server_IP_address"; const char* clientID = "ESP8266Client"; const char* topic = "led"; int led = 2; WiFiClient espClient; PubSubClient client(espClient); void setup() { pinMode(led, OUTPUT); Serial.begin(115200); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(1000); Serial.println("Connecting to WiFi..."); } Serial.println("Connected to WiFi"); client.setServer(mqtt_server, 1883); client.setCallback(callback); while (!client.connected()) { Serial.println("Connecting to MQTT Broker..."); if (client.connect(clientID)) { Serial.println("Connected to MQTT Broker"); client.subscribe(topic); } else { Serial.print("MQTT connection failed with state "); Serial.println(client.state()); delay(2000); } } } void callback(char* topic, byte* payload, unsigned int length) { Serial.print("Message arrived ["); Serial.print(topic); Serial.print("] "); for (int i = 0; i < length; i++) { Serial.print((char)payload[i]); } Serial.println(); if ((char)payload[0] == '1') { digitalWrite(led, HIGH); } else if ((char)payload[0] == '0') { digitalWrite(led, LOW); } } void loop() { if (!client.connected()) { reconnect(); } client.loop(); } void reconnect() { while (!client.connected()) { Serial.println("Connecting to MQTT Broker..."); if (client.connect(clientID)) { Serial.println("Connected to MQTT Broker"); client.subscribe(topic); } else { Serial.print("MQTT connection failed with state "); Serial.println(client.state()); delay(2000); } } } ``` 在上面的代码中,订阅了一个名为‘led’的主题,当接收到‘1’时,将LED灯打开;当接收到‘0’时,将LED灯关闭。 8. 在小程序中控制LED灯 在小程序使用MQTT.js库实现向MQTT服务器发布消息,控制ESP8266 LED灯的开关状态。例如: ```javascript // 打开LED灯 client.publish('led', '1') // 关闭LED灯 client.publish('led', '0') ``` 以上就是在微信小程序中连接MQTT服务器实现控制ESP8266 LED灯的全部步骤。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值