1.下载依赖
npm install mqttimport * as mqtt from "mqtt/dist/mqtt.min" 我是用的uniapp vue3 vite这里尝试了很多方式,都导入不进去后来我就采用的本地引入方式, 把mqtt.min.js下载到本地然后在index.html 中导入<script src="./MEQX/mqtt.js" type="text/javascript">
2.在EMQX后台创建一个JWT认证方式
并设置Secret,Payload根据子级需求设置,注意Expected Value不能大写全部小写
3.生成token
1.在线工具
通过在线网址生成 https://jwt.io/
PAYLOAD:DATA的值是需要和代码对应的,如果不需要就的话就填写{"password":""}
VERIFY SIGNATURE的Secret一定要记得填写
生成好后将这个值填写到password后
const options = {clientId,username,password: "生成的值"
}client = mqtt.connect(`${MQTT_IP}`, options)
2.通过jose包生成
下载jose npm i jose
payload参数根据自己需求
import { SignJWT } from 'jose'
//emqxsecret就是后台的Secret
const secret = new TextEncoder().encode('emqxsecret')
export async function createJWT(username, clientId) {const payload = {username,clientId,}
const jwt = await new SignJWT(payload).setProtectedHeader({ alg: 'HS256' }).setIssuedAt().setExpirationTime('2h').sign(secret)
console.log(`Encoded JWT: ${jwt}`)return jwt
}
4.最后进行连接和其他操作
import { userStore } from '@/store/user.js'
import { createJWT } from './jose.js'
const MQTT_IP = 'ws://192.168.31.20:8083/mqtt'
let client = null
const subscription = {topic: `topic`,qos: 1,
}
async function MEQXConnect(roomid = 1) {
subscription.topic = `topic${roomid}`
const userPinia = userStore()//传给mqtt.connect要是字符串是数字的不行,我传的数字失败了const clientId = String(userPinia.userInfo.id)
const username = String(userPinia.userInfo.nickName)
const token = await createJWT(username, clientId)
const options = {clientId,username,password: token}
client = mqtt.connect(`${MQTT_IP}`, options)
client.on('connect', () => {console.log('MEQX连接成功----------');doSubscribe()})
client.on('error', () => {console.log('MEQX连接失败------------');})
client.on('reconnect', () => {console.log('MEQX重新连接----------');})
client.on('end', () => {console.log('MEQX重新断开------------');})
client.on('close', () => {console.log('MEQX重新关闭------------');})
client.on('offline', () => {console.log('MEQX客户端下线------------');})
client.on("message", (topic, message) => {console.log(`MEQX received message: ${message} from topic: ${topic}`);})
//订阅const doSubscribe = () => {client.subscribe(subscription.topic, subscription.qos,(error, granted) => {if (error) {console.log("subscribe error:", error)return}console.log("subscribe successfully:", granted)})}
}
//取消订阅
export const doUnSubscribe = () => {client.unsubscribe(subscription.topic, subscription.qos, (error) => {if (error) {console.log("unsubscribe error:", error)return;}console.log(`unsubscribed topic: ${subscription.topic}`)})
}
export default MEQXConnect
参考地址