uniapp 微信小程序接入MQTT

MQTT安装

前期准备

  1. 由于微信小程序需要wss,所以要有域名SSL证书

  2. 新建目录/srv/mosquitto/config/srv/mosquitto/config/cert

  3. 目录/srv/mosquitto/config中新建配置文件mosquitto.conf,文件内容

    conf 复制代码
    persistence true
    persistence_location /mosquitto/data
    log_dest file /mosquitto/log/mosquitto.log
    listener 1883
    listener 9001
    protocol websockets
    certfile /mosquitto/config/cert/mqtt.xxx.com_public.crt
    keyfile /mosquitto/config/cert/mqtt.xxx.com.key
    cafile /mosquitto/config/cert/mqtt.xxx.com_chain.crt
    allow_anonymous false
    password_file /mosquitto/config/pwfile.conf

    最后一行 /mosquitto/config/pwfile.conf ,是用户认证配置,后面会说到

  4. 目录/srv/mosquitto/config/cert中的证书文件对应上面的配置文件内容

    • mqtt.xxx.com_public.crt
    • mqtt.xxx.com.key
    • mqtt.xxx.com_chain.crt

docker命令部署MQTT服务

sh 复制代码
docker run -d --name eclipse-mosquitto -p 1883:1883 -p 9001:9001 -v /srv/mosquitto/config/:/mosquitto/config/ -v /srv/mosquitto/data:/mosquitto/data -v /srv/mosquitto/log:/mosquitto/log eclipse-mosquitto

MQTT用户认证配置

sh 复制代码
docker exec -it mqtt /bin/sh
mosquitto_passwd /mosquitto/config/pwfile.conf {用户名}

输入上面的命令后还要输入两次密码就可以了

如果MQTT客户端连不上,重启一下MQTT服务

sh 复制代码
docker restart mqtt 

uniapp配置

NPM方式安装

sh 复制代码
npm i mqtt@4.1.0

安装指定版本4.1.0,目前【2024-07-09】最新版本有问题

MQTT连接示例

js 复制代码
import mqtt from 'mqtt/dist/mqtt'

const client = mqtt.connect("wxs://mqtt.xxx.com", {
    port: '9001',
    username: '用户名',
    password: '密码',
    reconnectPeriod: 1000
});
this.client = client
client.on('connect', () => {
    console.log('connect')
});
// 自动重连
client.on('reconnect', (msg) => {
    console.log('reconnect', msg)
});
// 错误
client.on('error', () => {
    console.log('error')
});
// 断开
client.on('end', () => {
    console.log('end')
});
// 掉线
client.on('offline', (msg) => {
    console.log('offline', msg)
});
// 收到消息        
client.on('message', (topic, message) => {
    // 把arrayBuffer转成字符串
    let encodedString = String.fromCharCode.apply(null, new Uint8Array(message));
})

熄屏断连问题

目前我的解决方案是

App.vue文件中onHide时断开连接,onShow时重新初始化client。

订阅时topic记录下来,client.on('connect')时遍历topic记录一一订阅

js 复制代码
onHide(() => {
  console.log("App onHide");
  client.end();
});

应用实例

我写了个小程序,目前实现了一个功能

wol远程电脑开机

微信小程序通过MQTT给ESP8266发送命令,ESP8266收到命令后发送WOL魔术包实现电脑开机,还可以用ESP8266直接连接电脑开机引脚开机。ESP8266代码在文章的最上面,下载不了可私信我。

防火布

相关推荐
耶啵奶膘6 小时前
uniapp+firstUI——上传视频组件fui-upload-video
前端·javascript·uni-app
racerun7 小时前
小程序导航设置更多内容的实现方法
小程序
说私域7 小时前
基于开源AI智能名片链动2+1模式S2B2C商城小程序的超级文化符号构建路径研究
人工智能·小程序·开源
mg6687 小时前
微信小程序入门实例_____快速搭建一个快递查询小程序
微信小程序·小程序
程序员柳8 小时前
基于微信小程序的校园二手交易平台、微信小程序校园二手商城源代码+数据库+使用说明,layui+微信小程序+Spring Boot
数据库·微信小程序·layui
Jyywww12111 小时前
微信小程序学习笔记
笔记·学习·微信小程序
The_era_achievs_hero12 小时前
微信小程序41~50
微信小程序·小程序
耶啵奶膘19 小时前
uniapp——地图路线绘制map
uni-app
shadouqi19 小时前
uniapp实现图片预览,懒加载,下拉刷新等
uni-app