代码还原
parent
be0492f952
commit
f48815d556
69
App.vue
69
App.vue
|
|
@ -1,48 +1,10 @@
|
|||
<script>
|
||||
import config from './config'
|
||||
import { getToken } from '@/utils/auth'
|
||||
import { initMQTT, disconnectMQTT, getMQTTStatus, getMQTTClient } from '@/utils/mqtt'; // 替换为你的mqtt工具层路径
|
||||
|
||||
export default {
|
||||
globalData: {
|
||||
mqttClient: null, // 全局MQTT客户端实例
|
||||
mqttConfig: { // MQTT全局配置(可根据环境切换)
|
||||
host: '1.94.254.176',
|
||||
port: 9001, // 小程序用wss端口(如EMQ X的8084)
|
||||
isSSL: false, // true=wss,false=ws
|
||||
username: 'admin',
|
||||
password: 'Admin#12345678',
|
||||
keepalive: 60,
|
||||
clean: true
|
||||
},
|
||||
mqttSubscribeList: [ // 全局基础订阅列表(所有页面都需要的主题)
|
||||
"dtu/864865085016294/up",
|
||||
"dtu/864536071808560/up",
|
||||
"dtu/864865085008135/up"
|
||||
// {topic: 'system/status', qos: 1}
|
||||
],
|
||||
},
|
||||
onLaunch() {
|
||||
onLaunch: function() {
|
||||
this.initApp()
|
||||
console.log('应用启动,初始化MQTT连接');
|
||||
this.initGlobalMQTT();
|
||||
},
|
||||
onShow() {
|
||||
console.log('应用切前台,检查MQTT连接');
|
||||
const { isConnected, isManualDisconnect } = getMQTTStatus();
|
||||
// 未连接且非手动断开 → 重新初始化连接
|
||||
if (!isConnected && !isManualDisconnect) {
|
||||
this.initGlobalMQTT();
|
||||
}
|
||||
console.info("mqtt:",isConnected,getMQTTStatus);
|
||||
},
|
||||
// 应用切后台时触发(最小化/锁屏/切换应用)
|
||||
onHide() {
|
||||
console.log('应用切后台,断开MQTT连接');
|
||||
// 手动断开连接(避免后台消耗资源)
|
||||
disconnectMQTT(() => {
|
||||
console.log('MQTT断开完成,应用进入后台');
|
||||
});
|
||||
},
|
||||
methods: {
|
||||
// 初始化应用
|
||||
|
|
@ -61,38 +23,11 @@
|
|||
if (!getToken()) {
|
||||
this.$tab.reLaunch('/pages/login')
|
||||
}
|
||||
},
|
||||
/**
|
||||
* 初始化全局MQTT连接(核心方法)
|
||||
*/
|
||||
initGlobalMQTT() {
|
||||
const {mqttConfig, mqttSubscribeList} = this.globalData;
|
||||
|
||||
// 调用MQTT工具层的初始化方法
|
||||
initMQTT(
|
||||
mqttConfig,
|
||||
mqttSubscribeList,
|
||||
// 连接成功回调
|
||||
(client) => {
|
||||
console.log('MQTT全局连接成功');
|
||||
this.globalData.mqttClient = getMQTTClient();
|
||||
},
|
||||
// 连接失败回调
|
||||
(err) => {
|
||||
console.error('MQTT全局连接失败:', err);
|
||||
// 可添加重试逻辑/用户提示
|
||||
uni.showToast({
|
||||
title: '设备通信异常',
|
||||
icon: 'none',
|
||||
duration: 3000
|
||||
});
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="scss">
|
||||
@import '@/static/scss/index.scss';
|
||||
@import '@/static/scss/index.scss'
|
||||
</style>
|
||||
|
|
|
|||
|
|
@ -284,6 +284,14 @@ export default {
|
|||
onUnload() {
|
||||
// 页面卸载时断开连接
|
||||
if (this.client && this.isConnected) {
|
||||
console.info("mqtt链接已关闭")
|
||||
this.client.end()
|
||||
}
|
||||
},
|
||||
onHide() {
|
||||
// 页面卸载时断开连接
|
||||
if (this.client && this.isConnected) {
|
||||
console.info("mqtt链接已关闭")
|
||||
this.client.end()
|
||||
}
|
||||
},
|
||||
|
|
|
|||
Loading…
Reference in New Issue