提交 1afdbf74 authored 作者: 詹银鑫's avatar 詹银鑫

mqtt引入和配置

上级 82eeffbe
差异被折叠。
......@@ -14,6 +14,7 @@
"delaunator": "^5.0.0",
"echarts": "^5.5.0",
"gsap": "^3.12.2",
"mqtt": "^5.11.0",
"normalize.css": "^8.0.1",
"point-in-polygon": "^1.1.0",
"three": "0.161.0",
......
import mqtt from 'mqtt'
// MQTT 配置
const options = {
clean: true,
connectTimeout: 4000,
clientId: 'vue3-client-' + Math.random().toString(16).substr(2, 8),
username: 'your_username', // 如果需要认证
password: 'your_password'
}
// MQTT 代理地址(示例使用公共测试服务器)
const brokerUrl = 'ws://test.mosquitto.org:8080/mqtt'
class MQTTClient {
constructor() {
this.client = null
}
connect() {
this.client = mqtt.connect(brokerUrl, options)
// 连接成功
this.client.on('connect', () => {
console.log('MQTT Connected')
this.subscribe('your/topic')
})
// 错误处理
this.client.on('error', (error) => {
console.error('MQTT Error:', error)
})
}
subscribe(topic) {
this.client.subscribe(topic, { qos: 0 }, (err) => {
if (!err) console.log(`Subscribed to ${topic}`)
})
}
// 接收消息处理
onMessage(callback) {
this.client.on('message', (topic, message) => {
callback(topic, message.toString())
})
}
// 发送消息
publish(topic, message) {
this.client.publish(topic, message, { qos: 0 })
}
disconnect() {
this.client?.end()
}
}
export const mqttClient = new MQTTClient()
\ No newline at end of file
......@@ -146,6 +146,9 @@ import emitter from "@/utils/emitter"
import gsap from "gsap"
import autofit from "autofit.js"
// mqtt通信组件
import { mqttClient } from "@/utils/mqttClient"
const assets = shallowRef(null)
const mapSceneRef = ref(null)
const state = reactive({
......@@ -171,7 +174,39 @@ const state = reactive({
},
],
})
const messages = ref([])
const inputMessage = ref('')
// 初始化连接
const connect = () => {
mqttClient.connect()
mqttClient.onMessage((topic, message) => {
messages.value.push(`[${topic}]: ${message}`)
// 如果是 JSON 数据:
// const data = JSON.parse(message)
// 处理数据...
})
}
// 发送消息
const sendMessage = () => {
if (inputMessage.value.trim()) {
mqttClient.publish('your/topic', inputMessage.value)
inputMessage.value = ''
}
}
// 断开连接
const disconnect = () => {
mqttClient.disconnect()
messages.value = []
}
onMounted(() => {
// 连接mqtt
connect()
// 监听地图播放完成,执行事件
emitter.$on("mapPlayComplete", handleMapPlayComplete)
// 自动适配
......@@ -193,6 +228,8 @@ onMounted(() => {
})
onBeforeUnmount(() => {
emitter.$off("mapPlayComplete", handleMapPlayComplete)
// 断开mqtt连接
disconnect()
})
// 初始化加载资源
function initAssets(onLoadCallback) {
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论