diff --git a/src/utils/mqtt.js b/src/utils/mqtt.js index 650ff6d..3fe442d 100644 --- a/src/utils/mqtt.js +++ b/src/utils/mqtt.js @@ -32,6 +32,12 @@ export const initMqtt = (clientId, topic, type, {username='sw_mqtt', password='1 const entry = { client, callback: null }; clients[type] = entry; + client.on('message', (topic, message) => { + if (entry.callback) { + entry.callback({ topic, message: JSON.parse(message.toString()) }); + } + }); + client.on("connect", () => { console.info("MQTT 连接成功_clientId:" + clientId); @@ -39,11 +45,6 @@ export const initMqtt = (clientId, topic, type, {username='sw_mqtt', password='1 if (err) { reject("订阅失败_clientId:" + clientId); } else { - if (entry.callback) { - client.on('message', (topic, message) => { - entry.callback({ topic, message: JSON.parse(message.toString()) }); - }); - } resolve("订阅成功_clientId:" + clientId); } }); @@ -59,11 +60,6 @@ export const callBackMqttMessage = (type, callback) => { const entry = clients[type]; if (entry) { entry.callback = callback; - if (entry.client) { - entry.client.on('message', (topic, message) => { - callback({ topic, message: JSON.parse(message.toString()) }); - }); - } } }; diff --git a/src/views/dataBoard/dataBoard.vue b/src/views/dataBoard/dataBoard.vue index cff6545..931df88 100644 --- a/src/views/dataBoard/dataBoard.vue +++ b/src/views/dataBoard/dataBoard.vue @@ -274,10 +274,16 @@ export default { }, methods: { initMqttConnect() { - const clientId = 'db-' + Math.random().toString(16).substring(2, 8); + let clientId = localStorage.getItem('dbDeviceId'); + if (!clientId) { + const bytes = new Uint8Array(8); + crypto.getRandomValues(bytes); + clientId = 'db-' + Array.from(bytes, b => b.toString(16).padStart(2, '0')).join(''); + localStorage.setItem('dbDeviceId', clientId); + } console.log(clientId); initMqtt(clientId, 'yx/device/rankingScreen/needUpdate', 'db', { - head: 'ws', + head: 'wss', username: process.env.VUE_APP_DB_MQTT_USERNAME, password: process.env.VUE_APP_DB_MQTT_PASSWORD }) @@ -286,7 +292,7 @@ export default { console.log('[MQTT] 收到消息:', data.topic, dayjs().format('YYYY-MM-DD HH:mm:ss'), data.message); if (data.topic === 'yx/device/rankingScreen/needUpdate') { const msg = data.message; - if (msg.type === 'RANKING_UPDATE') { + if (msg && msg.type === 'RANKING_UPDATE') { this.initData(''); } } diff --git a/src/views/led/led.vue b/src/views/led/led.vue index 0d1b86e..e2b6041 100644 --- a/src/views/led/led.vue +++ b/src/views/led/led.vue @@ -21,7 +21,7 @@