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

防火布

相关推荐
666HZ6662 小时前
微信小程序中scss、ts、wxml
微信小程序·小程序·scss
二十十十十十2 小时前
微信点餐小程序—美食物
微信·小程序
向明天乄3 小时前
在小程序中实现实时聊天:WebSocket最佳实践
websocket·网络协议·小程序
h185385922443 小时前
租车小程序电动车租赁小程序php方案
小程序
海的诗篇_3 小时前
前端开发面试题总结-原生小程序部分
前端·javascript·面试·小程序·vue·html
说私域3 小时前
基于开源AI智能客服、AI智能名片与S2B2C商城小程序的微商服务质量提升路径研究
人工智能·小程序·开源
牧杉-惊蛰3 小时前
uniapp微信小程序css中background-image失效问题
css·微信小程序·uni-app
拼图2098 小时前
微信小程序——skyline版本问题
微信小程序·小程序
mg66810 小时前
微信小程序入门实例_____打造你的专属单词速记小程序
微信小程序·小程序
程序员陆通10 小时前
Vibe Coding开发微信小程序实战案例
微信小程序·小程序·notepad++·ai编程