东丽网口版透析机 socket- server 通讯
chenyc
2026-01-01 ce98f732b9e4f32154d39454213e1abf3dc07f5b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// 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 };