99 lines
2.9 KiB
Vue
99 lines
2.9 KiB
Vue
<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() {
|
||
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: {
|
||
// 初始化应用
|
||
initApp() {
|
||
// 初始化应用配置
|
||
this.initConfig()
|
||
// 检查用户登录状态
|
||
//#ifdef H5
|
||
this.checkLogin()
|
||
//#endif
|
||
},
|
||
initConfig() {
|
||
this.globalData.config = config
|
||
},
|
||
checkLogin() {
|
||
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';
|
||
</style>
|