// mqttClient.js
|
const { info, warn, error } = require('./logger');
|
const mqtt = require('mqtt');
|
|
let client = null;
|
let publishEnabled = false;
|
let config = null;
|
|
function initMqtt(mqttConfig) {
|
if (!mqttConfig.enabled) {
|
info('MQTT 已禁用');
|
return;
|
}
|
|
config = mqttConfig;
|
const options = {
|
host: config.brokerUrl,
|
port: config.port,
|
reconnectPeriod: config.reconnectPeriod || 5000,
|
// 👇 添加认证
|
username: config.username,
|
password: config.password,
|
// 可选:设置 Client ID(避免重复)
|
clientId: 'fresenius_gateway_' + Math.random().toString(16).substr(2, 8),
|
};
|
|
try {
|
client = mqtt.connect(options);
|
client.on('connect', () => {
|
info(`✅ MQTT 连接成功: ${config.brokerUrl}:${config.port} (用户: ${config.username})`);
|
publishEnabled = true;
|
});
|
client.on('close', () => {
|
publishEnabled = false;
|
info('🔌 MQTT 连接断开');
|
});
|
client.on('error', (err) => {
|
error(`❌ MQTT 错误: ${err.message}`);
|
});
|
client.on('reconnect', () => {
|
info('🔄 MQTT 正在重连...');
|
});
|
} catch (ex) {
|
error(`💥 MQTT 初始化失败: ${ex.message}`);
|
}
|
}
|
|
function publishMessage(topic, message) {
|
if (!config?.enabled || !client || !publishEnabled) {
|
warn('MQTT 未启用或未连接,消息丢弃');
|
return;
|
}
|
client.publish(topic, message, { qos: 1 }, (err) => {
|
if (err) {
|
error(`📤 MQTT 发布失败 (${topic}): ${err.message}`);
|
} else {
|
info(`📤 MQTT 已发布到 ${topic}`);
|
}
|
});
|
}
|
|
module.exports = { initMqtt, publishMessage };
|