德朗6000透析机socket客户端程序通讯
gx
chenyc
2025-12-10 efa42a573642e7de5e3f0621034822c3238e80cb
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
 
const net = require('net');
const { info, warn, error } = require('./logger'); // 引入自定义的日志模块
const {calculateChecksum,funToModel,getFormattedDateTime,fetchServerList} =require('./jiexiData')
const iot = require('aliyun-iot-device-sdk');
const { publishMessage } = require('./mqttClient');
 
 
 
// 初始化阿里云物联网设备客户端
function createIotClient(config) {
    const client = iot.device({
        productKey: config.productKey,
        deviceName: config.deviceName,
        deviceSecret: config.deviceSecret,
        region: 'cn-shanghai' // 根据实际情况选择区域
    });
 
    client.on('connect', () => {
        // info(`阿里云物联网设备 ${config.deviceName} 已连接`);
    });
 
    client.on('error', (err) => {
        error(`阿里云物联网设备 ${config.deviceName} 连接发生错误: ${err.message}`);
    });
 
    return client;
}
function connectToServer(server, iotConfig) {
    let client;
    let sendInterval;
    const iotClient = createIotClient(iotConfig);
 
    function attemptConnect() {
        if (client) {
            client.destroy(); // 确保旧的Socket实例被销毁
        }
        client = new net.Socket();
        info(`${getFormattedDateTime()} 正在尝试连接到 ${server.host}:${server.port}`);
        client.connect(server.port, server.host, () => {
            info(`${getFormattedDateTime()} 已成功连接到 ${server.host}:${server.port}`);
 
            // 定时发送数据
            sendInterval = setInterval(() => {
                if (client.writable) {
                    client.write(Buffer.from([0xFF, 0x55, 0x00, 0x50, 0xEE, 0x42]));
                    info(`${getFormattedDateTime()} 向 ${server.host}:${server.port} 发送数据`);
                }
            }, server.interval);
        });
 
        client.on('data', (data) => {
            // 将接收到的 Buffer 数据转换为 16 进制字符串
            const hexData = data.toString('hex').toUpperCase();
            info(`${getFormattedDateTime()} 从 ${server.host}:${server.port} 接收到数据(16进制): ${hexData}`);
 
            // 将接收到的数据发送到阿里云物联网平台
            console.log(data)
             //计算校验码
            const jyma= calculateChecksum(data)
            console.log(jyma,data.length)
            // 将接收到的数据发送到阿里云物联网平台
            //数据头 67 89   长度86  做校验  贝朗的透析机
            if(data[0]==103&&data[1]===137&&data.length===86&&jyma===data[85]){
                try{
                    const mode=funToModel(data)
                    mode.n=iotConfig.deviceName,
                    mode.IPAddress=server.host,
                    iotClient.postProps(mode)
                    console.log('发送消息到matt')
                    onDeviceDataReceived(mode,iotConfig.deviceName);
                    
                }catch(error){
                    console.log('数据解析有误')
                }
            }else{
                console.log('无效的数据')
                console.log(data[0],data[1],data[85])
            }
        });
 
        client.on('close', (hadError) => {
            clearInterval(sendInterval); // 清除定时发送
            error(`${getFormattedDateTime()} 连接到 ${server.host}:${server.port} 已关闭。发生错误: ${hadError}`);
 
            // 无限次重连
            const delay = Math.pow(2, server.retryCount++) * 1000; // 指数退避
            error(`${getFormattedDateTime()} 将在 60 秒后重试连接...`);
            setTimeout(attemptConnect, 60000);
        });
 
        client.on('error', (err) => {
            error(`${getFormattedDateTime()} 与 ${server.host}:${server.port} 的连接发生错误: ${err.message}`);
            client.destroy(); // 确保发生错误时关闭连接,以便触发重连
        });
    }
 
    attemptConnect();
}
 
async function start() {
    try {
        // const res = await fetchServerList();
        // const servers=res?.data?.设备列表
        fetchServerList().then(res => {
            // const servers=[
                // {
                    // '设备IMEI号': 'C35AD053',
                    // '设备名称': 'TQS88-HDF',
                    // '阿里云物联网平台ProductKey': 'k08fz9VK3Q8',
                    // 'IP设置': '{"isEnabled":"1","ip":"127.0.0.1","port":"6000","work_mode":"client","interval":"30"}',
                    // '设备SIM号': '',
                    // '阿里云物联网信息': {
                    //   owner: true,
                    //   utcCreate: '2024-09-02T06:33:38.000Z',
                    //   gmtActive: '2024-09-19 11:10:26',
                    //   utcActive: '2024-09-19T03:10:26.617Z',
                    //   ipAddress: '123.146.28.7',
                    //   gmtOnline: '2024-09-20 10:14:19',
                    //   gmtCreate: '2024-09-02 14:33:38',
                    //   nodeType: 0,
                    //   productKey: 'k08fz9VK3Q8',
                    //   deviceName: 'C35AD053',
                    //   productName: 'DORA6000',
                    //   utcOnline: '2024-09-20T02:14:19.902Z',
                    //   deviceSecret: '7dd8aaabae652f10ff7ab4410eda05dd',
                    //   iotId: 'VCTmJy29VI1A62dfYlVsk08fz0',
                    //   region: 'cn-shanghai',
                    //   status: 'OFFLINE'
                    // },
                    // '设备编号': 'DEVICE1332405137464',
                    // '设备序列号': 'C35AD053',
                    // '设备医院编号': 'C35AD053',
                    // '阿里云物联网平台DeviceName': 'C35AD053',
                    // '阿里云物联网平台Secrect': '7dd8aaabae652f10ff7ab4410eda05dd'
                //   }
            // ]
            const servers=res.data.设备列表
            console.log('获取到客户设备信息')
            console.log(servers)
            servers.forEach(server => {
                if(server.阿里云物联网平台ProductKey==='k08fz9VK3Q8'){
                    const IP设置=JSON.parse(server.IP设置)
                    const ser={
                        host: IP设置.ip,
                        port: IP设置.port,
                        interval: IP设置.interval*1000,
                        retryCount: 0,
                        maxRetries: 5,
                        iotConfig: {
                            productKey: server.阿里云物联网平台ProductKey,
                            deviceName: server.阿里云物联网平台DeviceName,
                            deviceSecret: server.阿里云物联网平台Secrect
                        }
                    }
                    connectToServer(ser, ser.iotConfig);
                }
                
            });
        }).catch(error => {
            console.error('错误:', error);
        });
        
    } catch (err) {
        error('启动失败:', err.message);
    }
}
 
 
start();
 
 
// 模拟设备接收到的数据
async function onDeviceDataReceived(data,deviceName) {
  const topic = `touxiji/${deviceName}`;
  const payload = JSON.stringify({
    ...data,
    timestamp: new Date().toISOString()
  });
 
  publishMessage(topic, payload);
}