东丽网口版透析机 socket- server 通讯
chenyc
2025-11-08 434f42a9b33927a64611c3f9a06c674a3ca6a013
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
const { info, warn, error } = require('./logger'); // 引入自定义的日志模块
const mqtt = require('mqtt');
 
const brokerUrl = 'mqtt-test.ihemodialysis.com';
const port = 62183;
 
const options = {
  host: brokerUrl,
  port: port,
  reconnectPeriod: 5000, // 自动重连间隔时间
};
 
let client = null;
let publishEnabled = false;
 
// 初始化客户端连接
function connect() {
  try {
    client = mqtt.connect(options);
 
    client.on('connect', () => {
      console.log('Connected to MQTT Broker');
      info(`成功完成连接到 MQTT Broker: ${brokerUrl}:${port}`);
      publishEnabled = true;
 
      // 可选:启动定时发布任务
      // startPeriodicPublish();
    });
 
    client.on('close', () => {
      console.log('MQTT connection closed, will reconnect...');
      publishEnabled = false;
      stopPeriodicPublish();
    });
 
    client.on('error', (err) => {
      console.error('MQTT Error:', err);
      error(`MQTT 错误: ${err.message}`);
    });
 
    client.on('reconnect', () => {
      console.log('MQTT client reconnecting...');
    });
  } catch (ex) {
    console.error('Error during connecting to MQTT Broker:', ex);
    error(`尝试连接 MQTT Broker 时发生错误: ${ex.message}`);
  }
}
 
let intervalId = null;
 
function startPeriodicPublish() {
  if (intervalId) return;
 
  intervalId = setInterval(() => {
    const topic = 'system/heartbeat';
    let message;
    try {
      message = JSON.stringify({
        timestamp: new Date().toISOString(),
        status: 'alive'
      });
    } catch (ex) {
      console.error('Failed to create heartbeat message:', ex);
      error('创建心跳消息失败');
      return;
    }
 
    publishMessage(topic, message);
  }, 5000); // 每5秒发一次心跳
}
 
function stopPeriodicPublish() {
  if (intervalId) {
    clearInterval(intervalId);
    intervalId = null;
  }
}
 
// 外部可调用的发布函数
function publishMessage(topic, message) {
  if (!client || !publishEnabled) {
    console.warn('MQTT client not connected. Message not sent:', message);
    warn('MQTT 客户端未连接。消息未发送');
    return;
  }
 
  console.log(`Publishing to ${topic}:`, message);
  try {
    client.publish(topic, message, { qos: 1 }, (err) => {
      if (err) {
        console.error('Failed to publish message:', err);
        error(`消息发布失败: ${err.message}`);
      }
    });
  } catch (ex) {
    console.error('Unexpected error while publishing message:', ex);
    error(`发布消息时发生意外错误: ${ex.message}`);
  }
}
 
// 初始化连接
connect();
 
// 暴出发布函数
module.exports = {
  publishMessage,
};