Selaa lähdekoodia

提交设备详情与mqtt单例模式

wangming 1 kuukausi sitten
vanhempi
commit
a45f78f4d8
4 muutettua tiedostoa jossa 186 lisäystä ja 152 poistoa
  1. 124 92
      src/components/component/alarModel.vue
  2. 7 7
      src/main.js
  3. 31 49
      src/pagesA/deviceDetail/deviceDetail.vue
  4. 24 4
      src/utils/globalMqtt.js

+ 124 - 92
src/components/component/alarModel.vue

@@ -41,8 +41,8 @@
     </view>
 </template>
 <script>
+import MqttService from "../../utils/globalMqtt.js";
 import config from "../../data/config.js";
-import mqtt from "../../utils/mqtt";
 import {
     getSnTicket,
     authorize,
@@ -74,7 +74,6 @@ const getEnvVersionForVoip = (function () {
         return _map[envVersion];
     };
 })();
-
 export default {
     comments: {
         name: "alarModel",
@@ -637,114 +636,147 @@ export default {
             console.log("接收到消息:", topic, data);
         },
     },
-    // mounted() {
-    //     this.connectMQTTwo();
-    // },
-
-    // onShow() {
-    //     console.log("开始接受消息", "99999");
-    // },
     mounted() {
-        if (this.$mqttClient) {
-            console.log("开始接受mqtt消息111");
-            this.$mqttClient.on("message", (topic, message) => {
-                console.log(
-                    "接收到消息CMD11111:",
-                    JSON.parse(message.toString())
-                );
-                console.log(JSON.parse(message.toString()), "8870");
-                // 处理点位消息
+        // if (this.$mqttClient) {
+        //     console.log("开始接受mqtt消息111");
+        //     this.$mqttClient.on("message", (topic, message) => {
+        //         console.log(
+        //             "接收到消息CMD11111:",
+        //             JSON.parse(message.toString())
+        //         );
+        //         console.log(JSON.parse(message.toString()), "8870");
+        //         // 处理点位消息
+        //         let userId = uni.getStorageSync("userId");
+        //         const noticeMatch = /^\/mps\/wx_(.+)\/notice$/;
+        //         const match = topic.match(noticeMatch);
+        //         if (!match) return;
+        //         this.alarmModel = true;
+        //         const data = JSON.parse(message.toString());
+        //         this.clientId = data.clientId;
+        //         this.devName = data.devName;
+        //         this.sn = data.clientId;
+        //         this.eventListId = data.eventListId;
+        //         this.getVoipAuthor(this.clientId, userId);
+        //         console.log(data, topic, "接收到消息222:");
+        //         console.log(
+        //             "接收到消息:",
+        //             this.clientId,
+        //             this.devName,
+        //             this.sn,
+        //             this.eventListId,
+        //             data
+        //         );
+        //         const now = new Date();
+        //         const year = now.getFullYear();
+        //         const month = (now.getMonth() + 1).toString().padStart(2, "0");
+        //         const day = now.getDate().toString().padStart(2, "0");
+        //         const hours = now.getHours().toString().padStart(2, "0");
+        //         const minutes = now.getMinutes().toString().padStart(2, "0");
+        //         const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}`;
+        //         this.nowTime = formattedTime;
+        //         console.log("isWmpf:", isWmpf);
+        //         if (!isWmpf) {
+        //             console.log("isWmpf:", isWmpf);
+        //             this.getVoipDevices();
+        //         }
+        //         console.log("接收到消息:", topic, data);
+        //     });
+        // } else {
+        //     uni.$once("mqtt-ready", () => {
+        //         console.log("开始接受mqtt消息222");
+        //         this.$mqttClient.on("message", (topic, message) => {
+        //             console.log(
+        //                 "接收到消息CMD222:",
+        //                 JSON.parse(message.toString())
+        //             );
+        //             console.log(JSON.parse(message.toString()), "8870");
+        //             // 处理点位消息
+        //             let userId = uni.getStorageSync("userId");
+        //             const noticeMatch = /^\/mps\/wx_(.+)\/notice$/;
+        //             const match = topic.match(noticeMatch);
+        //             if (!match) return;
+        //             this.alarmModel = true;
+        //             const data = JSON.parse(message.toString());
+        //             this.clientId = data.clientId;
+        //             this.devName = data.devName;
+        //             this.sn = data.clientId;
+        //             this.eventListId = data.eventListId;
+        //             this.getVoipAuthor(this.clientId, userId);
+        //             console.log(data, topic, "接收到消息222:");
+        //             console.log(
+        //                 "接收到消息:",
+        //                 this.clientId,
+        //                 this.devName,
+        //                 this.sn,
+        //                 this.eventListId,
+        //                 data
+        //             );
+        //             const now = new Date();
+        //             const year = now.getFullYear();
+        //             const month = (now.getMonth() + 1)
+        //                 .toString()
+        //                 .padStart(2, "0");
+        //             const day = now.getDate().toString().padStart(2, "0");
+        //             const hours = now.getHours().toString().padStart(2, "0");
+        //             const minutes = now
+        //                 .getMinutes()
+        //                 .toString()
+        //                 .padStart(2, "0");
+        //             const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}`;
+        //             this.nowTime = formattedTime;
+        //             console.log("isWmpf:", isWmpf);
+        //             if (!isWmpf) {
+        //                 console.log("isWmpf:", isWmpf);
+        //                 this.getVoipDevices();
+        //             }
+        //             console.log("接收到消息:", topic, data);
+        //         });
+        //     });
+        // }
+
+        let userId = uni.getStorageSync("userId");
+        const topic = `/mps/wx_${userId}/notice`;
+        this.unsubscribeFn = MqttService.subscribe(
+            "CMD",
+            topic,
+            (topic, message) => {
+                const data = JSON.parse(message);
                 let userId = uni.getStorageSync("userId");
                 const noticeMatch = /^\/mps\/wx_(.+)\/notice$/;
                 const match = topic.match(noticeMatch);
                 if (!match) return;
+                // 更新页面数据
                 this.alarmModel = true;
-                const data = JSON.parse(message.toString());
                 this.clientId = data.clientId;
                 this.devName = data.devName;
                 this.sn = data.clientId;
                 this.eventListId = data.eventListId;
+                // VOIP 相关逻辑
                 this.getVoipAuthor(this.clientId, userId);
-                console.log(data, topic, "接收到消息222:");
-                console.log(
-                    "接收到消息:",
-                    this.clientId,
-                    this.devName,
-                    this.sn,
-                    this.eventListId,
-                    data
-                );
+                // 格式化时间
                 const now = new Date();
-                const year = now.getFullYear();
-                const month = (now.getMonth() + 1).toString().padStart(2, "0");
-                const day = now.getDate().toString().padStart(2, "0");
-                const hours = now.getHours().toString().padStart(2, "0");
-                const minutes = now.getMinutes().toString().padStart(2, "0");
-                const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}`;
-                this.nowTime = formattedTime;
-                console.log("isWmpf:", isWmpf);
+                this.nowTime = `${now.getFullYear()}-${String(
+                    now.getMonth() + 1
+                ).padStart(2, "0")}-${String(now.getDate()).padStart(
+                    2,
+                    "0"
+                )} ${String(now.getHours()).padStart(2, "0")}:${String(
+                    now.getMinutes()
+                ).padStart(2, "0")}`;
                 if (!isWmpf) {
-                    console.log("isWmpf:", isWmpf);
                     this.getVoipDevices();
                 }
-                console.log("接收到消息:", topic, data);
-            });
-        } else {
-            uni.$once("mqtt-ready", () => {
-                console.log("开始接受mqtt消息222");
-                this.$mqttClient.on("message", (topic, message) => {
-                    console.log(
-                        "接收到消息CMD222:",
-                        JSON.parse(message.toString())
-                    );
-                    console.log(JSON.parse(message.toString()), "8870");
-                    // 处理点位消息
-                    let userId = uni.getStorageSync("userId");
-                    const noticeMatch = /^\/mps\/wx_(.+)\/notice$/;
-                    const match = topic.match(noticeMatch);
-                    if (!match) return;
-                    this.alarmModel = true;
-                    const data = JSON.parse(message.toString());
-                    this.clientId = data.clientId;
-                    this.devName = data.devName;
-                    this.sn = data.clientId;
-                    this.eventListId = data.eventListId;
-                    this.getVoipAuthor(this.clientId, userId);
-                    console.log(data, topic, "接收到消息222:");
-                    console.log(
-                        "接收到消息:",
-                        this.clientId,
-                        this.devName,
-                        this.sn,
-                        this.eventListId,
-                        data
-                    );
-                    const now = new Date();
-                    const year = now.getFullYear();
-                    const month = (now.getMonth() + 1)
-                        .toString()
-                        .padStart(2, "0");
-                    const day = now.getDate().toString().padStart(2, "0");
-                    const hours = now.getHours().toString().padStart(2, "0");
-                    const minutes = now
-                        .getMinutes()
-                        .toString()
-                        .padStart(2, "0");
-                    const formattedTime = `${year}-${month}-${day} ${hours}:${minutes}`;
-                    this.nowTime = formattedTime;
-                    console.log("isWmpf:", isWmpf);
-                    if (!isWmpf) {
-                        console.log("isWmpf:", isWmpf);
-                        this.getVoipDevices();
-                    }
-                    console.log("接收到消息:", topic, data);
-                });
-            });
-        }
+                console.log("处理后的 CMD 数据:", data);
+            }
+        );
     },
 
     beforeDestroy() {
-        this.closemqtt();
+        if (this.unsubscribeCmd) {
+            this.unsubscribeCmd();
+            this.unsubscribeCmd = null;
+            console.log("CMD 订阅已取消");
+        }
     },
 };
 </script>

+ 7 - 7
src/main.js

@@ -33,13 +33,13 @@ Vue.prototype.$initMqtt = function () {
         });
 
     // 连接 DATA
-    MqttService.connectData(userId)
-        .then(client => {
-            console.log("DATA MQTT 初始化完成", client);
-        })
-        .catch(err => {
-            console.error("DATA MQTT 初始化失败", err);
-        });
+    // MqttService.connectData(userId)
+    //     .then(client => {
+    //         console.log("DATA MQTT 初始化完成", client);
+    //     })
+    //     .catch(err => {
+    //         console.error("DATA MQTT 初始化失败", err);
+    //     });
 }
 
 

+ 31 - 49
src/pagesA/deviceDetail/deviceDetail.vue

@@ -986,63 +986,45 @@ export default {
         this.clientId = clientId;
         console.log(this.clientId, "clientIDetail");
         this.clientId = clientId;
-        const bindMqtt = (mqttClientData) => {
-            if (!mqttClientData) {
-                console.error("MQTT 客户端未初始化");
-                return;
-            }
+        let userId = uni.getStorageSync("userId");
 
-            // 进入设备详情,先取消之前的订阅,避免重复
+        MqttService.connectData(userId).then((client) => {
             const topic = `/dev/${this.clientId}/tracker_targets`;
-            mqttClientData.unsubscribe(topic, (err) => {
-                if (err) {
-                    console.warn("取消订阅失败,可能之前没订阅过", err);
-                }
-                // 再订阅一次,确保立即生效
-                mqttClientData.subscribe(topic, (err) => {
-                    if (err) {
-                        console.error("DATA MQTT 订阅失败", err);
-                    } else {
-                        console.log(`DATA MQTT 订阅成功: ${topic}`);
+            // 使用 MqttService.subscribe 管理订阅
+            this.unsubscribeFn = MqttService.subscribe(
+                "DATA",
+                topic,
+                (message, msgTopic) => {
+                    console.log(`接收到 ${msgTopic} 消息:`, message);
+                    // 处理消息
+                    const dataMatch = msgTopic.match(
+                        /^\/dev\/(.+)\/tracker_targets$/
+                    );
+                    const cmdMatch = msgTopic.match(/^\/mps\/wx_(.+)\/notice$/);
+                    if (dataMatch && dataMatch[1] === this.clientId) {
+                        this.handleMessage(msgTopic, message, this.clientId);
+                    } else if (cmdMatch) {
+                        this.$refs.alarmModel.hanOtherMessage(
+                            msgTopic,
+                            message
+                        );
                     }
-                });
-            });
-            mqttClientData.removeAllListeners("message");
-            mqttClientData.on("message", (topic, message) => {
-                console.log("打印的点位", message.toString());
-
-                const dataMatch = topic.match(/^\/dev\/(.+)\/tracker_targets$/);
-                const cmdMatch = topic.match(/^\/mps\/wx_(.+)\/notice$/);
-
-                if (dataMatch && dataMatch[1] === this.clientId) {
-                    this.handleMessage(topic, message, this.clientId);
-                } else if (cmdMatch) {
-                    this.$refs.alarmModel.hanOtherMessage(topic, message);
                 }
-            });
-        };
-
-        if (this.$mqttClientData) {
-            bindMqtt(this.$mqttClientData);
-        } else {
-            uni.$once("mqttClientData-ready", (mqttClientData) => {
-                bindMqtt(mqttClientData);
-            });
-        }
+            );
+            if (this.unsubscribeFn) {
+                console.log(`✅ 已成功订阅主题: ${topic}`);
+            }
+        });
     },
     onUnload() {
         this.inactivityTimer = null;
         this.autoPlayinterval = null;
-        this.$mqttClientData.unsubscribe(
-            `/dev/${this.clientId}/tracker_targets`,
-            (err) => {
-                if (err) console.error("取消订阅失败", err);
-                else
-                    console.log(
-                        `取消订阅成功: /dev/${this.clientId}/tracker_targets`
-                    );
-            }
-        );
+        if (this.unsubscribeFn) {
+            this.unsubscribeFn();
+            this.unsubscribeFn = null;
+        }
+        // 关闭 DATA 连接
+        MqttService.disconnectData();
     },
     onHide() {
         this.showModle = false;

+ 24 - 4
src/utils/globalMqtt.js

@@ -30,10 +30,14 @@ class MqttService {
                 this.cmdConnected = true;
 
                 // 默认订阅 CMD 主题
-                this.subscribe('CMD', `/mps/wx_${userId}/notice`, (msg) => {
+                const topic = `/mps/wx_${userId}/notice`;
+                this.subscribe('CMD', topic, (msg) => {
                     console.log('CMD 消息:', msg);
                 });
 
+                // 打印订阅成功
+                console.log(`✅ CMD MQTT 主题已订阅成功: ${topic}`);
+
                 uni.$emit('mqtt-ready', this.cmdClient);
                 return client;
             });
@@ -132,19 +136,26 @@ class MqttService {
     }
 
     // 订阅
-    subscribe(clientType, topic, callback) {
+    subscribe(clientType, topic, callback, onSubscribeDone) {
         const connection = clientType === 'CMD' ? this.connections.get('CMD') : this.connections.get('DATA');
         if (!connection || !connection.connected) {
             console.warn(`${clientType} MQTT 未连接,无法 subscribe`);
+            if (onSubscribeDone) onSubscribeDone(new Error('未连接'));
             return;
         }
 
+        // 保存回调
         if (!connection.subscriptions.has(topic)) connection.subscriptions.set(topic, []);
         const callbacks = connection.subscriptions.get(topic);
         if (!callbacks.includes(callback)) callbacks.push(callback);
 
-        connection.client.subscribe(topic, err => {
-            if (err) console.error(`Subscribe error on ${clientType}:`, err);
+        // 执行订阅
+        connection.client.subscribe(topic, (err) => {
+            if (err) {
+                console.error(`Subscribe error on ${clientType}:`, err);
+            }
+            // 订阅完成回调
+            if (onSubscribeDone) onSubscribeDone(err);
         });
 
         // 返回取消订阅函数
@@ -175,6 +186,15 @@ class MqttService {
         this.connections.clear();
         console.log('所有 MQTT 连接已关闭');
     }
+    disconnectData() {
+        if (this.dataClient) {
+            this.dataClient.end(true);
+            this.dataClient = null;
+            this.dataConnected = false;
+            this.connections.delete("DATA");
+            console.log("DATA MQTT 连接已关闭");
+        }
+    }
 }
 
 // 单例导出