uniapp 微信小程序接入MQTT

MQTT安装

前期准备

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

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

  3. 目录/srv/mosquitto/config中新建配置文件mosquitto.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服务

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用户认证配置

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

输入上面的命令后还要输入两次密码就可以了
如果MQTT客户端连不上,重启一下MQTT服务

docker restart mqtt 

uniapp配置

NPM方式安装

npm i mqtt@4.1.0

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

MQTT连接示例

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记录一一订阅

onHide(() => {
  console.log("App onHide");
  client.end();
});

应用实例

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

wol远程电脑开机

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

防火布

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值