Selaa lähdekoodia

提交mqtt优化

wangming 2 kuukautta sitten
vanhempi
commit
6869efe612

+ 146 - 11
src/components/component/alarModel.vue

@@ -78,6 +78,11 @@ export default {
     comments: {
         name: "alarModel",
     },
+    props: {
+        clientIdProp: {
+            default: null,
+        },
+    },
     data() {
         return {
             alarmModel: false,
@@ -103,6 +108,7 @@ export default {
             currentIndex: 0,
             voipFlag: "",
             mqttClientFlag: false,
+            inactivityTimer: "",
         };
     },
     computed: {},
@@ -416,7 +422,6 @@ export default {
             //     console.log("MQTT连接已存在,无需重新创建", this.mqttClientTwo);
             //     return;
             // }
-            // 清理之前的连接
             // if (this.mqttClientTwo) {
             //     try {
             //         this.mqttClientTwo.end();
@@ -428,12 +433,12 @@ export default {
             // }
 
             if (this.mqttClientFlag) {
-                return;
                 console.log("主题已订阅");
+                return;
             }
             const THRESHOLD = 2;
             const params = {
-                keepalive: 60,
+                keepalive: 6000,
                 clean: true,
                 connectTimeout: 30 * 1000,
                 clientId:
@@ -460,9 +465,13 @@ export default {
             if (!selectedService || selectedService == "aloneServe") {
                 if (__wxConfig.envVersion == "develop") {
                     client = mqtt.connect(
-                        "wxs://api.radar-power.asia:8084/mqtt",
+                        "wxs://radar-power.cn:8084/mqtt",
                         params
                     );
+                    // client = mqtt.connect(
+                    //     "wxs://radar-power.cn:8084/mqtt",
+                    //     params
+                    // );
                 }
                 if (__wxConfig.envVersion == "trial") {
                     client = mqtt.connect(
@@ -470,7 +479,6 @@ export default {
                         params
                     );
                 }
-                // client = mqtt.connect("wxs://radar-power.cn:8084/mqtt", params);
             }
             // 存储client引用以便后续操作
             this.mqttClientTwo = client;
@@ -487,6 +495,21 @@ export default {
                         );
                     }
                 });
+                console.log(this.clientIdProp);
+                if (this.clientIdProp !== null) {
+                    client.subscribe(
+                        `/dev/${this.clientIdProp}/dsp_data`,
+                        (err) => {
+                            if (err) {
+                                console.error("订阅clientId失败", err);
+                            } else {
+                                console.log(
+                                    `成功订阅设备主题: /dev/${this.clientIdProp}/dsp_data`
+                                );
+                            }
+                        }
+                    );
+                }
             });
             client.on("disconnect", () => {
                 console.log("MQTT不在连接");
@@ -503,6 +526,12 @@ export default {
             client.on("close", () => {});
 
             client.on("message", (topic, message) => {
+                console.log(JSON.parse(message.toString()), "8870");
+                // 处理点位消息
+                if (this.clientIdProp !== null) {
+                    this.handleMessage(topic, message, this.clientIdProp);
+                }
+
                 let userId = uni.getStorageSync("userId");
                 const noticeMatch = /^\/mps\/wx_(.+)\/notice$/;
                 const match = topic.match(noticeMatch);
@@ -597,18 +626,124 @@ export default {
                     }
                 });
         },
+
+        // 处理点位消息
+        handleMessage(topic, message, clientId) {
+            // 清除不活动定时器
+            clearTimeout(this.inactivityTimer);
+            this.inactivityTimer = setTimeout(() => {
+                this.targetPoints = {};
+                console.log("长时间没有点位,清除数据");
+            }, 1500);
+
+            // 验证topic格式
+            const match = topic.match(/^\/dev\/(.+)\/dsp_data$/);
+            if (!match || match[1] !== clientId) return;
+
+            try {
+                const data = JSON.parse(message.toString());
+                this.processTrackerData(data.tracker_targets);
+            } catch (e) {
+                console.error("MQTT消息解析失败", e);
+            }
+        },
+
+        processTrackerData(arr) {
+            if (Array.isArray(arr) && arr.length > 0 && Array.isArray(arr[0])) {
+                this.targetPoints = {};
+                const currentIds = new Set();
+                const newTargetPoints = {};
+                // 处理每个追踪目标
+                arr.forEach((item) => {
+                    if (!Array.isArray(item) || item.length < 4) return;
+
+                    const [x, y, z, id] = item;
+                    currentIds.add(id.toString());
+
+                    // 处理新点或更新现有点
+                    if (!this.targetPoints[id]) {
+                        newTargetPoints[id] = this.createNewTargetPoint(
+                            x,
+                            y,
+                            z,
+                            id
+                        );
+                    } else {
+                        newTargetPoints[id] = this.updateExistingTargetPoint(
+                            this.targetPoints[id],
+                            x,
+                            y,
+                            z,
+                            2
+                        );
+                    }
+                });
+
+                // 移除不存在的点
+                Object.keys(this.targetPoints).forEach((id) => {
+                    if (!currentIds.has(id)) {
+                        delete this.targetPoints[id];
+                    }
+                });
+
+                // 更新目标点
+                this.targetPoints = {
+                    ...this.targetPoints,
+                    ...newTargetPoints,
+                };
+                if (Array.isArray(this.targetPoints)) {
+                    this.targetPoints = this.targetPoints.filter(
+                        (item) => item !== null && item !== undefined
+                    );
+                }
+                console.log("当前目标点11111", this.targetPoints);
+                this.sendChange();
+            }
+        },
+        sendChange() {
+            this.$emit("sendChange", this.targetPoints);
+        },
+        // 创建新目标点
+        createNewTargetPoint(x, y, z, id) {
+            return {
+                x,
+                y,
+                z,
+                id,
+                displayX: x,
+                displayY: y,
+                lastX: x,
+                lastY: y,
+            };
+        },
+        // 更新现有目标点
+        updateExistingTargetPoint(existingPoint, x, y, z, THRESHOLD) {
+            const dx = x - existingPoint.lastX;
+            const dy = y - existingPoint.lastY;
+            const distance = Math.sqrt(dx * dx + dy * dy);
+
+            if (distance > THRESHOLD) {
+                return {
+                    ...existingPoint,
+                    x,
+                    y,
+                    z,
+                    lastX: x,
+                    lastY: y,
+                    displayX: x,
+                    displayY: y,
+                };
+            }
+
+            return existingPoint;
+        },
     },
     mounted() {
-        setTimeout(() => {
-            this.connectMQTTwo();
-            console.log("组件挂载,连接MQTT");
-        }, 1000);
+        this.connectMQTTwo();
     },
 
     beforeDestroy() {
-        // 在组件销毁前断开MQTT连接
         this.closemqtt();
-        console.log("组件销毁3333,断开MQTT连接");
     },
 };
 </script>

+ 3 - 2
src/components/js_sdk/index.js

@@ -5,7 +5,7 @@ http.setConfig(config => {
     if (__wxConfig.envVersion == 'develop') {
         let selectedService = uni.getStorageSync("sercviceChoice")
         if (!selectedService || selectedService == 'aloneServe') {
-            // config.baseUrl = "https://api.radar-power.asia:4443/portal-service-server/";
+            config.baseUrl = "https://api.radar-power.asia:4443/portal-service-server/";
         }
         config.baseUrl = "https://radar-power.cn/portal-service-server/";
     }
@@ -56,7 +56,8 @@ http.interceptor.response(response => {
                     uni.reLaunch({
                         url: "/pagesA/loginNew/loginNew"
                     })
-                } else {
+                }
+                if (res.cancel) {
                     uni.reLaunch({
                         url: "/pagesA/loginNew/loginNew"
                     })

+ 11 - 259
src/pagesA/deviceDetail/deviceDetail.vue

@@ -264,7 +264,11 @@
                 </view>
             </view>
         </view>
-        <alarModel v-if="isInitAlarm" />
+        <alarModel
+            v-if="isInitAlarm"
+            :clientIdProp="clientIdProp"
+            @sendChange="receptionChange"
+        />
     </view>
 </template>
 <script>
@@ -281,7 +285,6 @@ export default {
             startDate: "",
             endDate: "",
             softWare: "",
-            targetPoints: [],
             statusLight: 0,
             currentDate: new Date().getTime(),
             lnbAction: "action8",
@@ -321,6 +324,7 @@ export default {
             isConnecting: false,
             left: 0,
             top: 0,
+            clientIdProp: null,
         };
     },
     computed: {},
@@ -386,255 +390,6 @@ export default {
                 });
         },
 
-        connectMQTT(clientId, devId) {
-            // 配置常量
-            const CONFIG = {
-                THRESHOLD: 2,
-                RECONNECT_DELAY: 3000, // 重连延迟增加到3秒
-                INACTIVITY_TIMEOUT: 1500,
-                MQTT_PARAMS: {
-                    keepalive: 60,
-                    clean: true,
-                    connectTimeout: 30 * 1000,
-                    clientId:
-                        "wx_mqtt_" +
-                        Math.random().toString(16).substring(2, 10),
-                    username: "admin",
-                    password: "public",
-                    wsOptions: {
-                        WebSocket: function (url) {
-                            return wx.connectSocket({
-                                url: url,
-                                header: { "content-type": "application/json" },
-                                protocols: ["mqtt"],
-                            });
-                        },
-                    },
-                    rejectUnauthorized: false,
-                    reconnectPeriod: 0,
-                },
-            };
-
-            if (this.isConnecting) {
-                console.log("mqtt已经链接,请勿重复链接");
-                return;
-            }
-            // 清理之前的连接和定时器
-            this.cleanupMQTT();
-
-            // 获取服务选择
-            const selectedService = uni.getStorageSync("sercviceChoice");
-            const serverUrl = "wxs://radar-power.cn:8084/mqtt";
-
-            // 创建连接
-            this.mqttClient = mqtt.connect(serverUrl, CONFIG.MQTT_PARAMS);
-
-            // 连接成功事件
-            this.mqttClient.on("connect", () => {
-                console.log("MQTT连接成功");
-                this.handleConnectSuccess(clientId);
-            });
-
-            // 断开连接事件
-            this.mqttClient.on("disconnect", () => {
-                console.log("MQTT连接断开");
-            });
-
-            // 错误事件
-            this.mqttClient.on("error", (err) => {
-                console.error("MQTT连接错误", err);
-                this.handleReconnect(clientId, devId, CONFIG.RECONNECT_DELAY);
-            });
-
-            // 重连事件
-            this.mqttClient.on("reconnect", () => {
-                console.log("MQTT尝试重新连接");
-            });
-
-            // 关闭事件
-            this.mqttClient.on("close", () => {
-                console.log("MQTT连接已关闭");
-            });
-
-            // 消息事件
-            this.mqttClient.on("message", (topic, message) => {
-                this.handleMessage(topic, message, clientId, CONFIG);
-            });
-        },
-
-        // 处理连接成功
-        handleConnectSuccess(clientId) {
-            this.isConnecting = true;
-            this.mqttClient.subscribe(`/dev/${clientId}/dsp_data`, (err) => {
-                if (err) {
-                    console.error("订阅失败", err);
-                } else {
-                    console.log(`成功订阅设备主题: /dev/${clientId}/dsp_data`);
-                }
-            });
-        },
-
-        // 处理MQTT消息
-        handleMessage(topic, message, clientId, CONFIG) {
-            this.isConnecting = false;
-            // 清除不活动定时器
-            clearTimeout(this.inactivityTimer);
-            this.inactivityTimer = setTimeout(() => {
-                this.targetPoints = {};
-                console.log("长时间没有点位,清除数据");
-            }, CONFIG.INACTIVITY_TIMEOUT);
-
-            // 验证topic格式
-            const match = topic.match(/^\/dev\/(.+)\/dsp_data$/);
-            if (!match || match[1] !== clientId) return;
-
-            try {
-                const data = JSON.parse(message.toString());
-                this.processTrackerData(data.tracker_targets, CONFIG.THRESHOLD);
-            } catch (e) {
-                console.error("MQTT消息解析失败", e);
-            }
-        },
-
-        // 处理追踪器数据
-        processTrackerData(arr, THRESHOLD) {
-            if (!Array.isArray(arr) || arr.length === 0) {
-                this.targetPoints = {};
-                return;
-            }
-
-            const currentIds = new Set();
-            const newTargetPoints = {};
-
-            // 处理每个追踪目标
-            arr.forEach((item) => {
-                if (!Array.isArray(item) || item.length < 4) return;
-
-                const [x, y, z, id] = item;
-                currentIds.add(id.toString());
-
-                // 处理新点或更新现有点
-                if (!this.targetPoints[id]) {
-                    newTargetPoints[id] = this.createNewTargetPoint(
-                        x,
-                        y,
-                        z,
-                        id
-                    );
-                } else {
-                    newTargetPoints[id] = this.updateExistingTargetPoint(
-                        this.targetPoints[id],
-                        x,
-                        y,
-                        z,
-                        THRESHOLD
-                    );
-                }
-            });
-
-            // 移除不存在的点
-            Object.keys(this.targetPoints).forEach((id) => {
-                if (!currentIds.has(id)) {
-                    delete this.targetPoints[id];
-                }
-            });
-
-            // 更新目标点
-            this.targetPoints = { ...this.targetPoints, ...newTargetPoints };
-            this.cleanTargetPoints();
-
-            console.log("当前目标点", this.targetPoints);
-        },
-
-        // 创建新目标点
-        createNewTargetPoint(x, y, z, id) {
-            return {
-                x,
-                y,
-                z,
-                id,
-                displayX: x,
-                displayY: y,
-                lastX: x,
-                lastY: y,
-            };
-        },
-
-        // 更新现有目标点
-        updateExistingTargetPoint(existingPoint, x, y, z, THRESHOLD) {
-            const dx = x - existingPoint.lastX;
-            const dy = y - existingPoint.lastY;
-            const distance = Math.sqrt(dx * dx + dy * dy);
-
-            if (distance > THRESHOLD) {
-                return {
-                    ...existingPoint,
-                    x,
-                    y,
-                    z,
-                    lastX: x,
-                    lastY: y,
-                    displayX: x,
-                    displayY: y,
-                };
-            }
-
-            return existingPoint;
-        },
-
-        // 清理目标点数组
-        cleanTargetPoints() {
-            // 如果targetPoints是数组,过滤掉null/undefined
-            if (Array.isArray(this.targetPoints)) {
-                this.targetPoints = this.targetPoints.filter(
-                    (item) => item !== null && item !== undefined
-                );
-            }
-        },
-
-        // 处理重连
-        handleReconnect(clientId, devId, delay) {
-            this.isConnecting = false;
-            // 使用防抖避免频繁重连
-            if (this.reconnectTimer) {
-                clearTimeout(this.reconnectTimer);
-            }
-
-            this.reconnectTimer = setTimeout(() => {
-                const storedDevId = uni.getStorageSync("devIdDetail");
-                const storedClientId = uni.getStorageSync("clientIDetail");
-
-                if (storedClientId && storedDevId) {
-                    console.log("尝试重新连接MQTT...");
-                    this.connectMQTT(storedClientId, storedDevId);
-                }
-            }, delay);
-        },
-
-        // 清理MQTT资源
-        cleanupMQTT() {
-            // 清理定时器
-            if (this.inactivityTimer) {
-                clearTimeout(this.inactivityTimer);
-                this.inactivityTimer = null;
-            }
-
-            if (this.reconnectTimer) {
-                clearTimeout(this.reconnectTimer);
-                this.reconnectTimer = null;
-            }
-
-            // 断开旧连接
-            if (this.mqttClient) {
-                try {
-                    this.mqttClient.end();
-                    this.mqttClient = null;
-                } catch (e) {
-                    console.warn("断开旧连接时发生错误", e);
-                }
-            }
-        },
-
         parseDeviceItem(devItemStr) {
             try {
                 const devItem = JSON.parse(devItemStr);
@@ -882,18 +637,17 @@ export default {
                 now.getMonth() + 1
             }月${now.getDate().toString().padStart(2, "0")}日`;
         },
+        receptionChange(val) {
+            this.targetPoints = val;
+        },
     },
     onShow() {
-        let devIdDetail = uni.getStorageSync("devIdDetail");
-        let clientIDetail = uni.getStorageSync("clientIDetail");
-        this.connectMQTT(clientIDetail, devIdDetail);
-        console.log(devIdDetail, clientIDetail, 999999);
+        this.clientIdProp = uni.getStorageSync("clientIDetail");
+        this.isInitAlarm = true;
     },
     onLoad(options) {
         const devItem = this.parseDeviceItem(options.devItem);
         const { devId, clientId } = devItem;
-        this.isInitAlarm = true;
-        // this.connectMQTT(clientId, devId);
         this.getFrequency(devId);
         this.getdevInfo(devId);
         this.getdevRoomInfo(devId);
@@ -906,13 +660,11 @@ export default {
         this.isInitAlarm = false;
         this.inactivityTimer = null;
         this.autoPlayinterval = null;
-        this.cleanupMQTT();
     },
     onHide() {
         this.inactivityTimer = null;
         this.autoPlayinterval = null;
         this.isInitAlarm = false;
-        this.cleanupMQTT();
     },
 };
 </script>