mqtt全局工具

master
lld 2025-12-30 20:31:47 +08:00
parent e5c243b74e
commit 15a5db4479
2 changed files with 45 additions and 50 deletions

18
App.vue
View File

@ -19,11 +19,10 @@
keepalive: 60, keepalive: 60,
clean: true clean: true
}, },
globalSubscribeTopic: [ // mqttSubscribeList: [ //
{topic: 'dtu/#', qos: 0}, {topic: 'dtu/#', qos: 0},
// {topic: 'system/status', qos: 1} // {topic: 'system/status', qos: 1}
], ],
mqttStatus: 'disconnected' // connected/disconnected/reconnecting
}, },
onLaunch() { onLaunch() {
this.initApp() this.initApp()
@ -33,18 +32,16 @@
onShow() { onShow() {
console.log('应用切前台检查MQTT连接'); console.log('应用切前台检查MQTT连接');
const { isConnected } = getMQTTStatus(); const { isConnected } = getMQTTStatus();
if (!isConnected && this.globalData.mqttStatus !== 'disconnected') { if (!isConnected) {
// this.initGlobalMQTT();
manualReconnect(this.globalData.mqttConfig);
this.globalData.mqttStatus = 'reconnecting';
} }
console.info("mqtt",isConnected,getMQTTStatus);
}, },
onHide() { onHide() {
console.log('应用切后台断开MQTT连接'); console.log('应用切后台断开MQTT连接');
// //
disconnectMQTT(); disconnectMQTT();
this.globalData.mqttStatus = 'disconnected';
this.globalData.mqttClient = null; this.globalData.mqttClient = null;
}, },
methods: { methods: {
@ -71,15 +68,16 @@
// + // +
const client = await initMQTT( const client = await initMQTT(
this.globalData.mqttConfig, this.globalData.mqttConfig,
this.globalData.globalSubscribeTopic this.globalData.mqttSubscribeList
); );
// //
this.globalData.mqttClient = client; this.globalData.mqttClient = client;
this.globalData.mqttStatus = 'connected'; //
uni.$emit('mqtt_client_ready', client);
console.log('全局MQTT初始化成功'); console.log('全局MQTT初始化成功');
} catch (err) { } catch (err) {
console.error('全局MQTT初始化失败', err); console.error('全局MQTT初始化失败', err);
this.globalData.mqttStatus = 'disconnected'; uni.$emit('mqtt_init_fail', err);
} }
} }
} }

View File

@ -18,6 +18,7 @@ let isManualDisconnect = false; // 是否主动断开(用于区分主动/被
* 初始化MQTT连接 * 初始化MQTT连接
* @param {Object} config - MQTT连接配置 * @param {Object} config - MQTT连接配置
* @param {Array} subs - 初始订阅列表格式[{ topic: 'topic1', qos: 0 }, { topic: 'topic2', qos: 1 }] * @param {Array} subs - 初始订阅列表格式[{ topic: 'topic1', qos: 0 }, { topic: 'topic2', qos: 1 }]
* // 初始化连接(移除事件监听,只返回客户端实例)
* @returns {Promise} 连接成功/失败的Promise * @returns {Promise} 连接成功/失败的Promise
*/ */
export function initMQTT(config, subs = []) { export function initMQTT(config, subs = []) {
@ -60,41 +61,31 @@ export function initMQTT(config, subs = []) {
// 7. 创建客户端并连接 // 7. 创建客户端并连接
client = mqtt.connect(connectUrl, mqttOptions); client = mqtt.connect(connectUrl, mqttOptions);
// 8. 监听连接成功 // 仅保留连接成功的基础逻辑(订阅列表),移除其他事件监听
client.on('connect', () => { client.on('connect', () => {
console.log('MQTT连接成功', connectUrl); console.log('MQTT连接成功', connectUrl);
currentReconnectTimes = 0; // 重置重连次数 currentReconnectTimes = 0;
// 9. 订阅初始主题 // 9. 订阅初始主题
subscribeTopics(subscribeList); subscribeTopics(subscribeList);
resolve(client); resolve(client); // 成功后返回客户端实例,让页面自定义监听
}); });
// 10. 监听连接错误 // 移除工具层的error/close/message监听 → 交给页面处理
client.on('error', (err) => { // 保留重连的核心逻辑通过单独的close监听仅用于重连不处理业务
console.error('MQTT连接错误', err);
client.end();
reject(err);
});
// 11. 监听连接断开(被动断开则触发重连)
client.on('close', () => { client.on('close', () => {
console.log('MQTT连接已断开'); console.log('MQTT连接已断开工具层');
const oldClient = client; // 暂存旧客户端,避免重连时被覆盖
client = null; client = null;
// 非主动断开 + 未达最大重连次数 → 触发重连
if (!isManualDisconnect && currentReconnectTimes < maxReconnectTimes) { if (!isManualDisconnect && currentReconnectTimes < maxReconnectTimes) {
reconnectMQTT(config); reconnectMQTT(config).then(newClient => {
} // 重连成功后,全局通知页面:客户端已更换,需重新绑定事件
uni.$emit('mqtt_reconnected', newClient);
}).catch(err => {
uni.$emit('mqtt_reconnect_fail', err);
}); });
}
// 12. 监听消息全局消息转发页面层通过uni.$on监听 // 通知页面:旧客户端已断开
client.on('message', (topic, message) => { uni.$emit('mqtt_closed', oldClient);
const msg = {
topic,
payload: message.toString(), // 转字符串原始是Buffer
timestamp: Date.now()
};
// 全局广播消息,页面层按需监听
uni.$emit('mqtt_message', msg);
}); });
} catch (err) { } catch (err) {
@ -104,6 +95,8 @@ export function initMQTT(config, subs = []) {
}); });
} }
// 其他方法subscribeTopics/unsubscribeTopics/publishMQTT/disconnectMQTT/reconnectMQTT/getMQTTStatus/manualReconnect
// 【完全不变】,直接复用之前的代码
/** /**
* 订阅主题支持单个/多个 * 订阅主题支持单个/多个
* @param {Array} topics - 订阅列表格式[{ topic: 'topic1', qos: 0 }, { topic: 'topic2', qos: 1 }] * @param {Array} topics - 订阅列表格式[{ topic: 'topic1', qos: 0 }, { topic: 'topic2', qos: 1 }]
@ -258,3 +251,7 @@ export function manualReconnect(config) {
currentReconnectTimes = 0; // 重置重连次数 currentReconnectTimes = 0; // 重置重连次数
reconnectMQTT(config); reconnectMQTT(config);
} }
export function getMQTTClientInstance() {
return client;
}