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代码在文章的最上面,下载不了可私信我。

防火布

相关推荐
不如摸鱼去3 小时前
Trae 辅助下的 uni-app 跨端小程序工程化开发实践分享
微信小程序·小程序·uni-app·aigc·ai编程
意会6 小时前
微信闪照小程序实现
前端·css·微信小程序
小白_ysf9 小时前
uniapp 开发微信小程序,获取经纬度并且转化详细地址(单独封装版本)
微信小程序·uni-app
iOS阿玮12 小时前
三年期已满,你的产品不再更新将于90天后下架。
uni-app·app·apple
weixin_lynhgworld14 小时前
剧本杀小程序系统开发:构建剧本杀社交新生态
小程序
说私域14 小时前
基于定制开发开源 AI 智能名片 S2B2C 商城小程序的热点与人工下发策略研究
人工智能·小程序
weixin_lynhgworld14 小时前
陪诊小程序系统开发:让就医不再是一件难事
小程序
是一碗螺丝粉1 天前
拯救你的app/小程序审核!一套完美避开审核封禁的URL黑名单机制
前端·javascript·微信小程序
bug总结1 天前
深入理解 uni-app 的 uni.createSelectorQuery()
uni-app
weixin_lynhgworld1 天前
盲盒抽谷机小程序系统开发:从0到1的完整方法论
小程序