瀏覽代碼

重新提交mqtt代码

wangming 1 月之前
父節點
當前提交
d66f79653f
共有 5 個文件被更改,包括 163 次插入115 次删除
  1. 25 0
      src/App.vue
  2. 114 114
      src/components/component/alarModel.vue
  3. 10 0
      src/main.js
  4. 4 1
      src/pagesA/loginNew/loginNew.vue
  5. 10 0
      src/pagesA/my/my.vue

+ 25 - 0
src/App.vue

@@ -71,5 +71,30 @@ export default {
             },
         });
     },
+    onHide() {
+        if (this.$mqttClient) {
+            this.$mqttClient.end(true);
+            this.$mqttClient = null;
+            console.log("MQTT 已关闭(onHide)");
+        }
+        if (this.$mqttClientData) {
+            this.$mqttClientData.end(true);
+            this.$mqttClientData = null;
+            console.log("MQTT Data 已关闭(onHide)");
+        }
+    },
+    onUnload() {
+        // 小程序卸载时也关闭
+        if (this.$mqttClient) {
+            this.$mqttClient.end(true);
+            this.$mqttClient = null;
+            console.log("MQTT 已关闭(onUnload)");
+        }
+        if (this.$mqttClientData) {
+            this.$mqttClientData.end(true);
+            this.$mqttClientData = null;
+            console.log("MQTT Data 已关闭(onUnload)");
+        }
+    },
 };
 </script>

+ 114 - 114
src/components/component/alarModel.vue

@@ -417,125 +417,125 @@ export default {
             }
         },
         // mqtt相关方法
-        connectMQTTwo() {
-            if (this.mqttClientFlag) {
-                console.log("主题已订阅");
-                return;
-            }
-            const THRESHOLD = 2;
-            const params = {
-                keepalive: 6000,
-                clean: true,
-                connectTimeout: 30 * 1000,
-                clientId:
-                    "xcx_mqtt_cmd1" +
-                    uni.getStorageSync("userId") +
-                    Math.random().toString(16).substring(2, 8),
-                username: "lnradar",
-                password: "lnradar",
-                // 微信小程序特定配置
-                wsOptions: {
-                    WebSocket: function (url) {
-                        return wx.connectSocket({
-                            url: url,
-                            header: {
-                                "content-type": "application/json",
-                            },
-                            protocols: ["mqtt"],
-                        });
-                    },
-                },
-                reconnectPeriod: 0,
-                rejectUnauthorized: false, // 仅开发环境使用,生产环境应设为true或移除
-            };
-            let client = "";
-            let selectedService = uni.getStorageSync("sercviceChoice");
-            if (!selectedService || selectedService == "aloneServe") {
-                if (__wxConfig.envVersion == "develop") {
-                    client = mqtt.connect(
-                        "wxs://cmd.radar-power.cn/mqtt/",
-                        params
-                    );
-                }
-                if (__wxConfig.envVersion == "trial") {
-                    client = mqtt.connect(
-                        "wxs://cmd.radar-power.cn/mqtt/",
-                        params
-                    );
-                }
-            }
-            // 存储client引用以便后续操作
-            this.mqttClientTwo = client;
-            client.on("connect", () => {
-                console.log("MQTT连接成功");
-                this.mqttClientFlag = true;
-                let userId = uni.getStorageSync("userId");
-                client.subscribe(`/mps/wx_${userId}/notice`, (err) => {
-                    if (err) {
-                        console.error("订阅失败", err);
-                    } else {
-                        console.log(
-                            `成功订阅设备主题: /mps/wx_${userId}/notice`
-                        );
-                    }
-                });
-            });
-            client.on("disconnect", () => {
-                console.log("MQTT不在连接");
-            });
-            client.on("error", (err) => {
-                this.mqttClientFlag = false;
-                setTimeout(() => {
-                    this.connectMQTTwo();
-                }, 1000);
-            });
+        // connectMQTTwo() {
+        //     if (this.mqttClientFlag) {
+        //         console.log("主题已订阅");
+        //         return;
+        //     }
+        //     const THRESHOLD = 2;
+        //     const params = {
+        //         keepalive: 6000,
+        //         clean: true,
+        //         connectTimeout: 30 * 1000,
+        //         clientId:
+        //             "xcx_mqtt_cmd1" +
+        //             uni.getStorageSync("userId") +
+        //             Math.random().toString(16).substring(2, 8),
+        //         username: "lnradar",
+        //         password: "lnradar",
+        //         // 微信小程序特定配置
+        //         wsOptions: {
+        //             WebSocket: function (url) {
+        //                 return wx.connectSocket({
+        //                     url: url,
+        //                     header: {
+        //                         "content-type": "application/json",
+        //                     },
+        //                     protocols: ["mqtt"],
+        //                 });
+        //             },
+        //         },
+        //         reconnectPeriod: 0,
+        //         rejectUnauthorized: false, // 仅开发环境使用,生产环境应设为true或移除
+        //     };
+        //     let client = "";
+        //     let selectedService = uni.getStorageSync("sercviceChoice");
+        //     if (!selectedService || selectedService == "aloneServe") {
+        //         if (__wxConfig.envVersion == "develop") {
+        //             client = mqtt.connect(
+        //                 "wxs://cmd.radar-power.cn/mqtt/",
+        //                 params
+        //             );
+        //         }
+        //         if (__wxConfig.envVersion == "trial") {
+        //             client = mqtt.connect(
+        //                 "wxs://cmd.radar-power.cn/mqtt/",
+        //                 params
+        //             );
+        //         }
+        //     }
+        //     // 存储client引用以便后续操作
+        //     this.mqttClientTwo = client;
+        //     client.on("connect", () => {
+        //         console.log("MQTT连接成功");
+        //         this.mqttClientFlag = true;
+        //         let userId = uni.getStorageSync("userId");
+        //         client.subscribe(`/mps/wx_${userId}/notice`, (err) => {
+        //             if (err) {
+        //                 console.error("订阅失败", err);
+        //             } else {
+        //                 console.log(
+        //                     `成功订阅设备主题: /mps/wx_${userId}/notice`
+        //                 );
+        //             }
+        //         });
+        //     });
+        //     client.on("disconnect", () => {
+        //         console.log("MQTT不在连接");
+        //     });
+        //     client.on("error", (err) => {
+        //         this.mqttClientFlag = false;
+        //         setTimeout(() => {
+        //             this.connectMQTTwo();
+        //         }, 1000);
+        //     });
 
-            client.on("reconnect", () => {});
+        //     client.on("reconnect", () => {});
 
-            client.on("close", () => {});
+        //     client.on("close", () => {});
 
-            client.on("message", (topic, message) => {
-                console.log(JSON.parse(message.toString()), "8870");
-                // 处理点位消息
-                let userId = uni.getStorageSync("userId");
+        //     client.on("message", (topic, message) => {
+        //         console.log(JSON.parse(message.toString()), "8870");
+        //         // 处理点位消息
+        //         let userId = uni.getStorageSync("userId");
 
-                console.log("topic777777", userId);
+        //         console.log("topic777777", 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);
-            });
-        },
+        //         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);
+        //     });
+        // },
 
         hanledList(type) {
             this.$http

+ 10 - 0
src/main.js

@@ -38,6 +38,16 @@ waitForUserId((userId) => {
     uni.$emit("mqtt-ready", mqttClient);
     uni.$emit("mqttData-ready", mqttClientData);
 });
+// 全局方法:初始化 MQTT(登录成功时调用)
+Vue.prototype.$initMqtt = function () {
+    const mqttClient = createMqttClient()
+    Vue.prototype.$mqttClient = mqttClient
+    const mqttClientData = createMqttData()
+    Vue.prototype.$mqttClientData = mqttClientData
+    uni.$emit("mqtt-ready", mqttClient)
+    uni.$emit("mqttData-ready", mqttClientData)
+    console.log("✅ MQTT 已初始化")
+}
 
 
 // 挂载处理时间的方法

+ 4 - 1
src/pagesA/loginNew/loginNew.vue

@@ -39,7 +39,6 @@
 </template>
 <script>
 export default {
-    name: "my",
     data() {
         return {
             checked: false,
@@ -110,6 +109,10 @@ export default {
                             res.data.data.tokenValue
                         );
                         uni.setStorageSync("userId", res.data.data.userId);
+
+                        this.$initMqtt();
+                        console.log("✅ 登录成功后 MQTT 已重连");
+
                         uni.reLaunch({
                             url: "/pages/home/home",
                         });

+ 10 - 0
src/pagesA/my/my.vue

@@ -81,6 +81,16 @@ export default {
                 content: "是否确认退出登录?",
                 success: function (res) {
                     if (res.confirm) {
+                        if (this.$mqttClient) {
+                            this.$mqttClient.end(true);
+                            this.$mqttClient = null;
+                            console.log("MQTT 已关闭(onHide)");
+                        }
+                        if (this.$mqttClientData) {
+                            this.$mqttClientData.end(true);
+                            this.$mqttClientData = null;
+                            console.log("MQTT Data 已关闭(onHide)");
+                        }
                         uni.clearStorageSync();
                         uni.reLaunch({
                             url: "/pagesA/loginNew/loginNew",