德朗6000透析机socket客户端程序通讯
chenyc
2025-02-21 d3973da8b1f1775a888a3a3fa90423a0e89b1425
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
 
const net = require('net');
const { info, warn, error } = require('./logger'); // 引入自定义的日志模块
const {calculateChecksum,funToModel,getFormattedDateTime} =require('./jiexiData')
const iot = require('aliyun-iot-device-sdk');
const path = require('path');
const fs = require('fs');
const axios = require('axios');
 
// 读取配置文件
// 使用 pkg 特定的方式访问打包进来的资产
const configPath = path.join(__dirname, 'config.json');
const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
 
info(`获取文件 ${configPath}地址,${JSON.stringify(config)}`);
async function fetchServerList() {
    try {
        const response = await axios({
            method: config.http.method,
            url: config.http.url,
            headers: config.http.headers,
            params: config.http.params
        });
        return response.data;
    } catch (err) {
        error(`获取服务器列表失败: ${err.message}`);
        throw err;
    }
}
 
// 初始化阿里云物联网设备客户端
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)
                    iotClient?.postProps(mode)
                }catch(error){
                    console.log('数据解析有误')
                }
            }else{
                console.log('无效的数据')
                console.log(data[0],data[1],data[85])
            }
        });
 
        client.on('close', (hadError) => {
            clearInterval(sendInterval); // 清除定时发送
            warn(`${getFormattedDateTime()} 连接到 ${server.host}:${server.port} 已关闭。发生错误: ${hadError}`);
 
            // 无限次重连
            const delay = Math.pow(2, server.retryCount++) * 1000; // 指数退避
            warn(`${getFormattedDateTime()} 将在 60 秒后重试连接...`);
            setTimeout(attemptConnect, 60000);
        });
 
        client.on('error', (err) => {
            error(`${getFormattedDateTime()} 与 ${server.host}:${server.port} 的连接发生错误: ${err.message}`);
            client.destroy(); // 确保发生错误时关闭连接,以便触发重连
        });
    }
 
    attemptConnect();
}
 
// function connectToServer(server, iotConfig) {
//     const client = new net.Socket();
//     let sendInterval;
//     const iotClient = createIotClient(iotConfig);
 
//     function attemptConnect() {
//         info(`正在尝试连接到 ${server.host}:${server.port}`);
//         client.connect(server.port, server.host, () => {
//             info(`已成功连接到 ${server.host}:${server.port}`);
//             server.retryCount = 0; // 重置重试次数
 
//             // 定时发送数据
//             sendInterval = setInterval(() => {
//                 if (client.writable) {
//                     client.write(Buffer.from([0xFF, 0x55, 0x00, 0x50, 0xEE, 0x42]));
//                     info(`向 ${server.host}:${server.port} 发送数据`);
//                 }
//             }, server.interval);
//         });
 
//         client.on('data', (data) => {
//             // 将接收到的 Buffer 数据转换为 16 进制字符串
//             const hexData = data.toString('hex').toUpperCase();
//             info(`从 ${server.host}:${server.port} 接收到数据:${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)
//                     iotClient?.postProps(mode)
//                 }catch(error){
//                     console.log('数据解析有误')
//                 }
//             }else{
//                 console.log('无效的数据')
//                 console.log(data[0],data[1],data[85])
//             }
 
//         });
 
//         client.on('close', (hadError) => {
//             warn(`连接到 ${server.host}:${server.port} 已关闭。发生错误: ${hadError}`);
//             clearInterval(sendInterval); // 清除定时发送
//             // 无限次重连
//             warn(`${getFormattedDateTime()} 将在 10 秒后重试连接...`);
//             setTimeout(attemptConnect, 10000);
//             // if (hadError && server.retryCount < server.maxRetries) {
//             //     server.retryCount++;
//             //     const delay = Math.pow(2, server.retryCount) * 1000; // 指数退避
//             //     warn(`将在 ${delay / 1000} 秒后重试连接...`);
//             //     setTimeout(attemptConnect, delay);
//             // } else if (server.retryCount >= server.maxRetries) {
//             //     error(`达到最大重试次数 (${server.maxRetries}) 对于 ${server.host}:${server.port}。不再尝试重连。`);
//             //     // 在这里可以加入通知机制,例如发送邮件或短信给管理员
//             // }
//         });
 
//         client.on('error', (err) => {
//             error(`与 ${server.host}:${server.port} 的连接发生错误: ${err.message}`);
//             client.destroy(); // 确保发生错误时关闭连接,以便触发重连
//         });
//     }
 
//     attemptConnect();
// }
 
async function start() {
    try {
        const res = await fetchServerList();
        const servers=res?.data?.设备列表
        // const servers=[
        //     {
        //         '设备IMEI号': 'C35AD053',
        //         '设备名称': 'TQS88-HDF',
        //         '阿里云物联网平台ProductKey': 'k08fz9VK3Q8',
        //         'IP设置': '{"isEnabled":"1","ip":"127.0.0.1","port":"60000","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'
        //       }
        // ]
        console.log('获取到客户设备信息')
        console.log(servers)
        servers.forEach(server => {
            console.log(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 (err) {
        error('启动失败:', err.message);
    }
}
 
 
start();