1
This commit is contained in:
@@ -1,8 +1,30 @@
|
||||
const MqttSyncClient = require('./mqttClient');
|
||||
const Framework = require('../../../framework/node-core-framework');
|
||||
const logs = require('../logProxy');
|
||||
const appConfig = require('../../../config/config.js');
|
||||
// action.js 已合并到 mqttDispatcher.js,不再需要单独引入
|
||||
|
||||
function buildMqttManagerConfig() {
|
||||
const mqttCfg = appConfig.mqtt || {};
|
||||
const brokerUrl = (mqttCfg.brokerUrl && String(mqttCfg.brokerUrl).trim())
|
||||
? mqttCfg.brokerUrl.trim()
|
||||
: `mqtt://${mqttCfg.host || '192.144.167.231'}:${mqttCfg.port != null ? mqttCfg.port : 1883}`;
|
||||
const options = {
|
||||
clientId: mqttCfg.clientId || `mqtt_server_${Math.random().toString(16).substr(2, 8)}`,
|
||||
clean: mqttCfg.clean !== false,
|
||||
connectTimeout: mqttCfg.connectTimeout != null ? mqttCfg.connectTimeout : 5000,
|
||||
reconnectPeriod: mqttCfg.reconnectPeriod != null ? mqttCfg.reconnectPeriod : 5000,
|
||||
keepalive: mqttCfg.keepalive != null ? mqttCfg.keepalive : 60
|
||||
};
|
||||
if (mqttCfg.username) {
|
||||
options.username = mqttCfg.username;
|
||||
}
|
||||
if (mqttCfg.password) {
|
||||
options.password = mqttCfg.password;
|
||||
}
|
||||
return { brokerUrl, options };
|
||||
}
|
||||
|
||||
/**
|
||||
* MQTT管理器 - 单例模式
|
||||
* 负责管理MQTT连接,确保全局只有一个MQTT客户端实例
|
||||
@@ -11,16 +33,7 @@ class MqttManager {
|
||||
constructor() {
|
||||
this.client = null;
|
||||
this.isInitialized = false;
|
||||
this.config = {
|
||||
brokerUrl: 'mqtt://192.144.167.231:1883', // MQTT Broker地址
|
||||
options: {
|
||||
clientId: `mqtt_server_${Math.random().toString(16).substr(2, 8)}`,
|
||||
clean: true,
|
||||
connectTimeout: 5000,
|
||||
reconnectPeriod: 5000, // 自动重连间隔
|
||||
keepalive: 10
|
||||
}
|
||||
};
|
||||
this.config = buildMqttManagerConfig();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -30,8 +43,16 @@ class MqttManager {
|
||||
*/
|
||||
async getInstance(config = {}) {
|
||||
if (this.client && this.isInitialized) {
|
||||
console.log('[MQTT管理器] 返回已存在的MQTT客户端实例');
|
||||
return this.client;
|
||||
const brokerOk = typeof this.client.isBrokerConnected === 'function'
|
||||
? this.client.isBrokerConnected()
|
||||
: this.client.isConnected;
|
||||
if (!brokerOk) {
|
||||
console.warn('[MQTT管理器] 单例已初始化但 Broker 未连接,重置并重建');
|
||||
await this.reset();
|
||||
} else {
|
||||
console.log('[MQTT管理器] 返回已存在的MQTT客户端实例');
|
||||
return this.client;
|
||||
}
|
||||
}
|
||||
|
||||
// 合并配置
|
||||
@@ -91,7 +112,13 @@ class MqttManager {
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isReady() {
|
||||
return this.isInitialized && this.client && this.client.isConnected;
|
||||
if (!this.isInitialized || !this.client) {
|
||||
return false;
|
||||
}
|
||||
if (typeof this.client.isBrokerConnected === 'function') {
|
||||
return this.client.isBrokerConnected();
|
||||
}
|
||||
return !!this.client.isConnected;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user