Jelajahi Sumber

提交mqtt优化代码

wangming 1 bulan lalu
induk
melakukan
92fe75075c
6 mengubah file dengan 168 tambahan dan 165 penghapusan
  1. 4 12
      src/App.vue
  2. 7 13
      src/main.js
  3. 0 17
      src/pages/home/home.vue
  4. 1 1
      src/pagesA/loginNew/loginNew.vue
  5. 3 10
      src/pagesA/my/my.vue
  6. 153 112
      src/utils/globalMqtt.js

+ 4 - 12
src/App.vue

@@ -6,7 +6,9 @@ import { isWmpf } from "./const";
 import { updatePushToken } from "./api/index";
 import { config } from "./data/index";
 
-// 引入voip插件
+import MqttService from "./utils/globalMqtt";
+
+// 引入voip
 const wmpfVoip = requirePlugin("wmpf-voip").default;
 
 // voip事件监听
@@ -73,17 +75,7 @@ export default {
         });
     },
     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)");
-        }
+        MqttService.disconnectAll();
     },
 };
 </script>

+ 7 - 13
src/main.js

@@ -1,9 +1,7 @@
 import Vue from 'vue'
 import App from './App'
 import './uni.promisify.adaptor'
-import {
-    createMqttClient, createMqttData
-} from "./utils/globalMqtt";
+import MqttService from "./utils/globalMqtt";
 
 import {
     http
@@ -19,17 +17,13 @@ Vue.prototype.$http = http;
 
 // 全局方法:初始化 MQTT(登录成功时调用)
 Vue.prototype.$initMqtt = function () {
-    if (!uni.getStorageSync("userId")) {
-        console.warn("MQTT 初始化失败:缺少 userId");
-        return;
+    const userId = uni.getStorageSync("userId")
+    if (!userId) {
+        console.warn("MQTT 初始化失败:缺少 userId")
+        return
     }
-    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 已初始化")
+    MqttService.connectCmd(userId)
+    MqttService.connectData(userId)
 }
 
 

+ 0 - 17
src/pages/home/home.vue

@@ -554,23 +554,6 @@ export default {
     height: 28rpx;
 }
 
-.bottom button {
-    all: unset;
-    margin: 0;
-    padding: 0;
-    border: none;
-    background: none;
-    font: inherit;
-    text-align: inherit;
-    line-height: normal;
-    outline: none;
-    box-shadow: none;
-    -webkit-appearance: none;
-    margin-left: 6rpx;
-    color: #a1aab4;
-    font-size: 28rpx;
-}
-
 .bot_version {
     opacity: 0.4;
     position: absolute;

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

@@ -111,7 +111,7 @@ export default {
                         uni.setStorageSync("userId", res.data.data.userId);
 
                         this.$initMqtt();
-                        console.log("✅ 登录成功后 MQTT 已重连");
+                        console.log("✅ 登录成功后 MQTT 开始登录连接");
 
                         uni.reLaunch({
                             url: "/pages/home/home",

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

@@ -55,6 +55,8 @@
 </template>
 
 <script>
+import MqttService from "../../utils/globalMqtt";
+
 export default {
     data() {
         return {
@@ -81,16 +83,7 @@ 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)");
-                        }
+                        MqttService.disconnectAll();
                         uni.clearStorageSync();
                         uni.reLaunch({
                             url: "/pagesA/loginNew/loginNew",

+ 153 - 112
src/utils/globalMqtt.js

@@ -1,123 +1,164 @@
-import mqtt from './mqtt';
+// mqttService.js
+import mqtt from './mqtt'
 
-let mqttClientCmd = null;   // 全局 CMD MQTT
-let mqttClientData = null;  // 全局 DATA MQTT
+class MqttService {
+    constructor() {
+        if (!MqttService.instance) {
+            this.cmdClient = null
+            this.dataClient = null
+            this.cmdConnected = false
+            this.dataConnected = false
+            MqttService.instance = this
+        }
+        return MqttService.instance
+    }
+
+    // 连接 CMD
+    connectCmd(userId) {
+        if (this.cmdConnected && this.cmdClient) {
+            console.log("CMD MQTT 已连接,复用现有实例")
+            return this.cmdClient
+        }
+        console.log("CMD MQTT 连接中...")
+        const params = {
+            clientId: "xcx_mqtt_cmd1_" + userId + "_" + Math.random().toString(16).substring(2, 8),
+            username: "lnradar",
+            password: "lnradar",
+            wsOptions: {
+                WebSocket: function (url) {
+                    return wx.connectSocket({
+                        url,
+                        header: { "content-type": "application/json" },
+                        protocols: ["mqtt"],
+                    })
+                },
+            },
+        }
+
+        this.cmdClient = mqtt.connect("wxs://cmd.radar-power.cn/mqtt/", params)
+
+        this.cmdClient.on("connect", () => {
+            this.cmdConnected = true
+            console.log("CMD MQTT 连接成功")
+            uni.$emit("mqtt-ready", mqttClient)
+            this.cmdClient.subscribe(`/mps/wx_${userId}/notice`, (err) => {
+                if (err) {
+                    console.error("CMD 订阅失败", err)
+                } else {
+                    console.log(`成功订阅设备主题: /mps/wx_${userId}/notice`)
+                }
+            })
+        })
+
+        this.cmdClient.on("message", (topic, message) => {
+            console.log("CMD 接收到消息:", topic, JSON.parse(message.toString()))
+        })
 
-let mqttCmdConnected = false;
-let mqttDataConnected = false;
-let reconnectTimer = null; // 重连定时器
+        this.cmdClient.on("error", (err) => {
+            this.cmdConnected = false
+            console.error("CMD MQTT 连接错误:", err)
+        })
 
-export function createMqttClient() {
-    if (mqttCmdConnected) {
-        console.log("CMD MQTT 已连接");
-        return mqttClientCmd;
+        this.cmdClient.on("disconnect", () => {
+            this.cmdConnected = false
+            console.log("CMD MQTT 断开")
+        })
+
+        return this.cmdClient
     }
-    const params = {
-        // keepalive: 60,
-        // clean: false,
-        // connectTimeout: 30 * 1000,
-        clientId:
-            "xcx_mqtt_cmd1" +
-            uni.getStorageSync("userId") +
-            Math.random().toString(16).substring(2, 8),
-        username: "lnradar",
-        password: "lnradar",
-        wsOptions: {
+
+    // 连接 DATA
+    connectData(userId) {
+        if (this.dataConnected && this.dataClient) {
+            console.log("DATA MQTT 已连接,复用现有实例")
+            return this.dataClient
+        }
+
+        const params = {
+            clientId: "xcx_mqtt_data1_" + userId + "_" + Date.now(),
+            username: "lnradar",
+            password: "lnradar",
             WebSocket: function (url) {
                 return wx.connectSocket({
-                    url: url,
-                    header: {
-                        "content-type": "application/json",
-                    },
+                    url,
+                    header: { "content-type": "application/json" },
                     protocols: ["mqtt"],
-                });
+                })
             },
-        },
-    };
-    let client = "";
-
-    client = mqtt.connect("wxs://cmd.radar-power.cn/mqtt/", params);
-    client.on("connect", () => {
-        mqttCmdConnected = true;
-        console.log("MQTTCMD连接成功");
-        const 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("message", (topic, message) => {
-        console.log("topic", topic, message);
-        console.log("接收到消息:", JSON.parse(message.toString()));
-        const noticeMatch = /^\/mps\/wx_(.+)\/notice$/;
-        const match = topic.match(noticeMatch);
-        if (!match) return;
-    });
-    client.on("error", (err) => {
-        mqttCmdConnected = false;
-        console.error("MQTTCMD连接错误:", err);
-    });
-
-    client.on("disconnect", () => {
-        mqttCmdConnected = false;
-        console.log("MQTT断开连接");
-    });
-    return client;
-}
+        }
+
+        this.dataClient = mqtt.connect("wxs://data.radar-power.cn/mqtt/", params)
+
+        this.dataClient.on("connect", () => {
+            this.dataConnected = true
+            uni.$emit("mqttData-ready", mqttClientData)
+            console.log("DATA MQTT 连接成功")
+        })
 
-// 创建data连接
-export function createMqttData() {
-    if (!uni.getStorageSync("userId")) {
-        console.warn("DATA MQTT 创建失败:缺少 userId");
-        return null;
+        this.dataClient.on("message", (topic, message) => {
+            console.log("DATA 接收到消息:", topic, JSON.parse(message.toString()))
+        })
+
+        this.dataClient.on("error", (err) => {
+            this.dataConnected = false
+            console.error("DATA MQTT 连接错误:", err)
+        })
+
+        this.dataClient.on("disconnect", () => {
+            this.dataConnected = false
+            console.log("DATA MQTT 断开")
+        })
+
+        // 给 DATA 加一个关闭方法
+        this.dataClient.close = (force = true) => {
+            this.dataClient.end(force, () => {
+                this.dataConnected = false
+                this.dataClient = null
+                console.log("DATA MQTT 已关闭")
+            })
+        }
+
+        return this.dataClient
     }
 
-    if (mqttDataConnected) return mqttClientData;
-
-    const params = {
-        // keepalive: 15,
-        // clean: false,
-        // connectTimeout: 1500,
-        // reconnectPeriod: 2000
-        clientId: "xcx_mqtt_data1_" + uni.getStorageSync("userId") + "_" + Date.now(),
-        username: "lnradar",
-        password: "lnradar",
-        WebSocket: function (url) {
-            return wx.connectSocket({
-                url: url,
-                header: {
-                    "content-type": "application/json",
-                },
-                protocols: ["mqtt"],
-            });
-        },
-    };
-
-    mqttClientData = mqtt.connect("wxs://data.radar-power.cn/mqtt/", params);
-
-    mqttClientData.on("connect", () => {
-        console.log("DATA MQTT 连接成功Global页面打印");
-        mqttDataConnected = true;
-        // uni.$emit("mqttData-ready", mqttClientData)
-    });
-
-    mqttClientData.on("message", (topic, message) => {
-        console.log("topic", topic, message);
-        console.log("接收到消息:", JSON.parse(message.toString()));
-
-    });
-
-    mqttClientData.on("error", (err) => { mqttDataConnected = false; console.error("MQTTDATA连接错误:", err); });
-    mqttClientData.on("disconnect", () => { mqttDataConnected = false; console.log("DATA MQTT 断开"); });
-    mqttClientData.close = function (force = true) {
-        mqttClientData.end(force, () => {
-            mqttDataConnected = false;
-            console.log("DATA MQTT 已关闭");
-        });
-    };
-
-    return mqttClientData;
-}
+    // 发布
+    publish(clientType, topic, message) {
+        const client = clientType === "CMD" ? this.cmdClient : this.dataClient
+        if (client) {
+            client.publish(topic, message)
+        } else {
+            console.warn(`${clientType} MQTT 未连接,无法 publish`)
+        }
+    }
+
+    // 订阅
+    subscribe(clientType, topic) {
+        const client = clientType === "CMD" ? this.cmdClient : this.dataClient
+        if (client) {
+            client.subscribe(topic)
+        } else {
+            console.warn(`${clientType} MQTT 未连接,无法 subscribe`)
+        }
+    }
+
+    // 断开所有连接
+    disconnectAll() {
+        if (this.cmdClient) {
+            this.cmdClient.end(true)
+            this.cmdClient = null
+            this.cmdConnected = false
+            console.log("CMD MQTT 已关闭")
+        }
+        if (this.dataClient) {
+            this.dataClient.end(true)
+            this.dataClient = null
+            this.dataConnected = false
+            console.log("DATA MQTT 已关闭")
+        }
+    }
+}
+
+const instance = new MqttService()
+// Object.freeze(instance)
+
+export default instance