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

防火布

相关推荐
毕设源码-邱学长4 小时前
【开题答辩全过程】以 基于微信小程序的宠物领养系统为例,包含答辩的问题和答案
微信小程序·小程序·宠物
canglingyue5 小时前
微信小程序日历事件添加实现
微信小程序·小程序
毕设源码-邱学长9 小时前
【开题答辩全过程】以 基于微信小程序校园综合服务平台的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
Thetimezipsby9 小时前
基于Taro4打造的一款最新版微信小程序、H5的多端开发简单模板
前端·javascript·微信小程序·typescript·html5·taro
從南走到北9 小时前
JAVA同城打车小程序APP打车顺风车滴滴车跑腿源码微信小程序打车源码
java·开发语言·微信·微信小程序·小程序
猫七先生11 小时前
微信小程序一键登录可行性方案
前端·微信小程序
canglingyue12 小时前
微信小程序截屏与录屏功能详解
微信小程序·小程序
微三云-轩13 小时前
区块链系统:解决549 亿元积分商城是否违法的问题
大数据·小程序·重构·区块链·生活
D1555408805816 小时前
电竞护航小程序成品搭建三角洲行动护航小程序开发俱乐部点单小程序成品游戏派单小程序定制
游戏·小程序
说私域1 天前
兴趣电商内容数据洞察未来市场走向研究——基于开源AI智能名片链动2+1模式S2B2C商城小程序的实践
人工智能·小程序