chenyc
2025-12-09 545c24c6a711d71b65f3d4e8122fee3837fb1edc
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/**
 * 阿里云物联网客户端模块
 * 使用 alibabacloud-iot-device-sdk 实现设备接入和数据上传
 * 支持通过 API 动态获取设备三元组
 */
 
const { device } = require('alibabacloud-iot-device-sdk');
const axios = require('axios');
const Qs = require('qs');
const config = require('./config.json');
const appLogger = require('./loggerConfig');
 
// 获取阿里云配置
const aliyunConfig = config.aliyunIoT;
 
class AliyunIoTClient {
  constructor(deviceSerialNumber) {
    this.enabled = aliyunConfig.enabled;
    this.deviceSerialNumber = deviceSerialNumber;
    this.device = null;
    this.isConnected = false;
    this.deviceInfo = null;
    this.tripletInfo = null;
    
    if (!this.enabled) {
      return;
    }
  }
 
  /**
   * 通过 API 获取设备三元组
   * @returns {Promise<object>} 返回三元组信息 {deviceName, deviceSecret, productKey}
   */
  async fetchTripletFromAPI() {
    try {
      if (!aliyunConfig.apiConfig || !aliyunConfig.apiConfig.baseUrl) {
        appLogger.logWarn(`API 配置缺失,无法获取三元组`, {
          module: 'aliyun',
          device: this.deviceSerialNumber,
          hasApiConfig: !!aliyunConfig.apiConfig,
          hasBaseUrl: !!aliyunConfig.apiConfig?.baseUrl
        });
        console.warn(`⚠ API 配置不完整 [设备: ${this.deviceSerialNumber}]`);
        return null;
      }
 
      const apiConfig = aliyunConfig.apiConfig;
      const url = `${apiConfig.baseUrl}${apiConfig.secretUrl}`;
      const requestData = {
        isAutoRegister: 1,
        deviceName: this.deviceSerialNumber
      };
 
      // 记录 API 请求详情 - 使用 INFO 级别以确保记录
      appLogger.logInfo(`🔄 发起 API 请求获取三元组`, {
        module: 'aliyun',
        device: this.deviceSerialNumber,
        url: url,
        method: 'POST',
        params: requestData,
        timestamp: new Date().toISOString()
      });
 
      appLogger.logAliyunFetchingTriplet(this.deviceSerialNumber);
      console.log(`🔄 正在从 API 获取设备三元组 [设备: ${this.deviceSerialNumber}]...`);
      console.log(`   📡 请求地址: ${url}`);
      console.log(`   📤 请求参数: ${JSON.stringify(requestData)}`);
 
      const response = await axios({
        url: url,
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
        data: Qs.stringify(requestData),
        timeout: 10000
      });
 
      // 记录 API 响应详情
      appLogger.logInfo(`✓ API 请求成功,收到响应`, {
        module: 'aliyun',
        device: this.deviceSerialNumber,
        statusCode: response.status,
        statusText: response.statusText,
        dataLength: JSON.stringify(response.data).length,
        timestamp: new Date().toISOString()
      });
 
      console.log(`✓ API 请求成功 [状态码: ${response.status}]`);
      console.log(`   📥 响应数据大小: ${JSON.stringify(response.data).length} bytes`);
 
      if (response.data && response.data.data) {
        const tripletData = response.data.data;
        appLogger.logAliyunTripletFetched(this.deviceSerialNumber, {
          deviceName: tripletData.deviceName || this.deviceSerialNumber,
          deviceSecret: tripletData.deviceSecret,
          productKey: tripletData.productKey || aliyunConfig.productKey
        });
        
        // 记录成功的三元组获取
        appLogger.logInfo(`✓ 三元组获取成功`, {
          module: 'aliyun',
          device: this.deviceSerialNumber,
          deviceName: tripletData.deviceName || this.deviceSerialNumber,
          hasSecret: !!tripletData.deviceSecret,
          source: 'API',
          timestamp: new Date().toISOString()
        });
        
        console.log(`✓ 设备三元组获取成功 [设备: ${this.deviceSerialNumber}]`);
        console.log(`   ✔ 设备名称: ${tripletData.deviceName || this.deviceSerialNumber}`);
        console.log(`   ✔ 密钥已获取: ${!!tripletData.deviceSecret}`);
        
        return {
          deviceName: tripletData.deviceName || this.deviceSerialNumber,
          deviceSecret: tripletData.deviceSecret,
          productKey: tripletData.productKey || aliyunConfig.productKey
        };
      } else {
        console.error(`✗ API 返回数据格式错误:`, response.data);
        
        // 记录响应格式错误
        appLogger.logError(`✗ API 返回数据格式错误`, new Error('Invalid API response format'), {
          module: 'aliyun',
          device: this.deviceSerialNumber,
          statusCode: response.status,
          response: JSON.stringify(response.data),
          timestamp: new Date().toISOString()
        });
        
        appLogger.logAliyunTripletFetchError(this.deviceSerialNumber, new Error('Invalid API response format'));
        return null;
      }
    } catch (err) {
      console.error(`✗ 获取设备三元组失败 [${this.deviceSerialNumber}]: ${err.message}`);
      
      // 记录 API 请求错误详情 - 使用 ERROR 级别
      appLogger.logError(`✗ API 请求失败`, err, {
        module: 'aliyun',
        device: this.deviceSerialNumber,
        errorType: err.code || err.name,
        errorMessage: err.message,
        requestUrl: aliyunConfig.apiConfig?.baseUrl + aliyunConfig.apiConfig?.secretUrl,
        timeout: err.code === 'ECONNABORTED' ? '连接超时' : undefined,
        connectionRefused: err.code === 'ECONNREFUSED' ? '连接被拒绝' : undefined,
        timestamp: new Date().toISOString()
      });
      
      // 详细的错误日志输出
      console.error(`   ✗ 错误代码: ${err.code || err.name}`);
      console.error(`   ✗ 错误信息: ${err.message}`);
      if (err.response) {
        console.error(`   ✗ 响应状态: ${err.response.status}`);
        console.error(`   ✗ 响应数据: ${JSON.stringify(err.response.data)}`);
      }
      
      appLogger.logAliyunTripletFetchError(this.deviceSerialNumber, err);
      return null;
    }
  }
 
  /**
   * 获取设备三元组(优先从 API 获取,回退到配置文件)
   */
  async getTriplet() {
    // 首先尝试从 API 获取
    if (aliyunConfig.apiConfig && aliyunConfig.apiConfig.baseUrl) {
      appLogger.logInfo(`尝试从 API 获取三元组`, {
        module: 'aliyun',
        device: this.deviceSerialNumber,
        api: aliyunConfig.apiConfig.baseUrl + aliyunConfig.apiConfig.secretUrl
      });
      
      const triplet = await this.fetchTripletFromAPI();
      if (triplet) {
        return triplet;
      }
      
      appLogger.logWarn(`API 获取三元组失败,尝试本地配置`, {
        module: 'aliyun',
        device: this.deviceSerialNumber
      });
      console.warn(`⚠ API 获取失败,尝试从配置文件获取 [设备: ${this.deviceSerialNumber}]`);
    }
 
    // 回退到配置文件(如果有设备配置)
    if (aliyunConfig.devices && aliyunConfig.devices[this.deviceSerialNumber]) {
      this.deviceInfo = aliyunConfig.devices[this.deviceSerialNumber];
      
      appLogger.logInfo(`三元组获取成功`, {
        module: 'aliyun',
        device: this.deviceSerialNumber,
        deviceName: this.deviceInfo.deviceName,
        source: 'config'
      });
      
      return {
        deviceName: this.deviceInfo.deviceName,
        deviceSecret: this.deviceInfo.deviceSecret,
        productKey: aliyunConfig.productKey
      };
    }
 
    // 三元组获取完全失败
    appLogger.logError(`无法获取设备三元组`, new Error('Device not found'), {
      module: 'aliyun',
      device: this.deviceSerialNumber,
      apiEnabled: !!aliyunConfig.apiConfig?.baseUrl,
      hasLocalConfig: !!(aliyunConfig.devices && aliyunConfig.devices[this.deviceSerialNumber])
    });
    
    appLogger.logAliyunTripletFetchError(this.deviceSerialNumber, 'Device not found in config');
    console.warn(`⚠ 设备 ${this.deviceSerialNumber} 未在阿里云配置中注册,且无法从 API 获取`);
    return null;
  }
 
  /**
   * 连接到阿里云 IoT
   */
  async connect() {
    if (!this.enabled) {
      return Promise.resolve();
    }
 
    return new Promise(async (resolve, reject) => {
      try {
        // 获取三元组信息
        appLogger.logInfo(`开始获取设备三元组`, {
          module: 'aliyun',
          device: this.deviceSerialNumber,
          timestamp: new Date().toISOString()
        });
        
        const triplet = await this.getTriplet();
        if (!triplet || !triplet.deviceSecret) {
          appLogger.logError(`三元组验证失败`, new Error('Invalid triplet'), {
            module: 'aliyun',
            device: this.deviceSerialNumber,
            hasTriplet: !!triplet,
            hasSecret: !!(triplet && triplet.deviceSecret)
          });
          
          console.error(`✗ 无法获取有效的设备三元组 [${this.deviceSerialNumber}]`);
          reject(new Error('Invalid triplet information'));
          return;
        }
 
        const productKey = triplet.productKey || aliyunConfig.productKey;
        const regionId = aliyunConfig.regionId;
        const deviceName = triplet.deviceName;
        const deviceSecret = triplet.deviceSecret;
 
        // 记录即将创建的设备实例
        appLogger.logInfo(`准备创建阿里云设备实例`, {
          module: 'aliyun',
          device: this.deviceSerialNumber,
          deviceName: deviceName,
          productKey: productKey,
          regionId: regionId
        });
 
        // 构建设备配置
        const options = {
          productKey: productKey,
          deviceName: deviceName,
          deviceSecret: deviceSecret,
          regionId: regionId,
          keepalive: 60
        };
 
        console.log(`🔗 创建阿里云设备实例 [${deviceName}]...`);
 
        // 创建设备实例
        this.device = device(options);
 
        // 设置连接超时
        const connectTimeout = setTimeout(() => {
          appLogger.logError(`阿里云连接超时`, new Error('Connection timeout'), {
            module: 'aliyun',
            device: this.deviceSerialNumber,
            timeout: 15000,
            deviceName: deviceName
          });
          
          console.error(`✗ 阿里云 IoT 连接超时 [设备: ${this.deviceSerialNumber}]`);
          reject(new Error('Connection timeout'));
        }, 15000);
 
        // 监听连接事件
        this.device.on('connect', () => {
          clearTimeout(connectTimeout);
          this.isConnected = true;
          this.tripletInfo = triplet;
          
          appLogger.logInfo(`阿里云连接建立成功`, {
            module: 'aliyun',
            device: this.deviceSerialNumber,
            deviceName: deviceName,
            timestamp: new Date().toISOString()
          });
          
          appLogger.logAliyunConnected(this.deviceSerialNumber, deviceName);
          console.log(`✓ 阿里云 IoT 连接成功 [设备: ${this.deviceSerialNumber}] [${deviceName}]`);
          
          // 订阅主题
          this.subscribe();
          resolve();
        });
 
        // 监听错误事件
        this.device.on('error', (err) => {
          clearTimeout(connectTimeout);
          appLogger.logError(`阿里云连接错误`, err, {
            module: 'aliyun',
            device: this.deviceSerialNumber,
            deviceName: deviceName,
            errorType: err.code || err.name
          });
          
          appLogger.logAliyunConnectionError(this.deviceSerialNumber, err);
          console.error(`✗ 阿里云 IoT 错误 [设备: ${this.deviceSerialNumber}]:`, err.message);
          this.isConnected = false;
          if (!this.isConnected) {
            reject(err);
          }
        });
 
        // 监听离线事件
        this.device.on('offline', () => {
          this.isConnected = false;
          appLogger.logAliyunOffline(this.deviceSerialNumber);
          console.warn(`⚠ 阿里云 IoT 离线 [设备: ${this.deviceSerialNumber}]`);
        });
 
        // 监听重连事件
        this.device.on('reconnect', () => {
          appLogger.logInfo(`阿里云 IoT 重新连接中 [设备: ${this.deviceSerialNumber}]`, { module: 'aliyun', device: this.deviceSerialNumber });
          console.log(`⟳ 阿里云 IoT 重新连接中 [设备: ${this.deviceSerialNumber}]`);
        });
 
      } catch (err) {
        appLogger.logError(`创建设备实例失败`, err, { device: this.deviceSerialNumber });
        console.error(`创建设备实例失败:`, err);
        reject(err);
      }
    });
  }
 
  /**
   * 订阅主题
   */
  subscribe() {
    if (!this.enabled || !this.device) return;
 
    // 订阅属性设置命令
    this.device.subscribe('/a1/{productKey}/{deviceName}/thing/service/property/set');
 
    // 监听消息
    this.device.on('message', (topic, payload) => {
      console.log(`\n📩 收到阿里云下行消息 [${topic}]:`, payload);
    });
  }
 
  /**
   * 发布医疗数据属性
   * @param {object} keyData - 关键数据对象
   */
  publishProperties(keyData) {
    if (!this.enabled || !this.isConnected || !this.device) {
      if (this.enabled && !this.isConnected) {
        console.warn(`⚠ 设备 ${this.deviceSerialNumber} 未连接到阿里云 IoT`);
      }
      return;
    }
 
    // 构建属性数据
    const properties = {
      // 基本信息
      deviceModel: keyData.deviceModel,
      softwareVersion: keyData.softwareVersion,
      
      // 超滤参数
      ultraFiltrateTarget: parseFloat(keyData.ultraFiltrateTarget) || 0,
      ultraFiltrateTotal: parseFloat(keyData.ultraFiltrateTotal) || 0,
      ultrafiltrateRateSet: parseFloat(keyData.ultrafiltrateRateSet) || 0,
      
      // 透析液参数
      dialysisFluidFlow: parseFloat(keyData.dialysisFluidFlow) || 0,
      dialysisFluidActual: parseFloat(keyData.dialysisFluidActual) || 0,
      dialysisFluidTemp: parseFloat(keyData.dialysisFluidTemp) || 0,
      sodiumConc: parseFloat(keyData.sodiumConc) || 0,
      conductivity: parseFloat(keyData.conductivity) || 0,
      
      // 血液/血流参数
      bloodFlow: parseFloat(keyData.bloodFlow) || 0,
      effectiveBloodFlow: parseFloat(keyData.effectiveBloodFlow) || 0,
      dialysisBloodVolume: parseFloat(keyData.dialysisBloodVolume) || 0,
      returnedBloodVolume: parseFloat(keyData.returnedBloodVolume) || 0,
      plasmaNA: parseFloat(keyData.plasmaNA) || 0,
      clearanceRate: parseFloat(keyData.clearanceRate) || 0,
      
      // 质量指标
      instantKT: parseFloat(keyData.instantKT) || 0,
      ktvTarget: parseFloat(keyData.ktvTarget) || 0,
      
      // 电解质参数
      bicarbonate: parseFloat(keyData.bicarbonate) || 0,
      
      // 压力参数
      arterialPressure: parseFloat(keyData.arterialPressure) || 0,
      venousPressure: parseFloat(keyData.venousPressure) || 0,
      transmembranePressure: parseFloat(keyData.transmembranePressure) || 0,
      
      // 膜型参数
      dialysisMode: keyData.dialysisMode,
      
      // 状态参数
      runStatus: keyData.runStatus,
      alarmStatus: keyData.alarmStatus,
      treatmentDuration: parseFloat(keyData.treatmentDuration) || 0,
      
      // 置换参数
      replacementFluidTarget: parseFloat(keyData.replacementFluidTarget) || 0,
      replacementRate: parseFloat(keyData.replacementRate) || 0,
      replacementVolume: parseFloat(keyData.replacementVolume) || 0
    };
 
    try {
      const propertyStr = JSON.stringify(properties);
      appLogger.logAliyunPublishing(this.deviceSerialNumber, 'properties', propertyStr.length);
      this.device.postProperty(properties, (err, data) => {
        if (err) {
          appLogger.logAliyunPublishError(this.deviceSerialNumber, 'properties', err);
          console.error(`发布属性失败 [${this.deviceSerialNumber}]:`, err.message);
        }
      });
    } catch (err) {
      appLogger.logError(`发布属性异常`, err, { device: this.deviceSerialNumber, module: 'aliyun' });
      console.error(`发布属性异常:`, err.message);
    }
  }
 
  /**
   * 发布事件
   * @param {object} event - 事件对象
   */
  publishEvent(event) {
    if (!this.enabled || !this.isConnected || !this.device) {
      return;
    }
 
    const eventData = {
      eventType: event.type,
      description: event.description,
      severity: event.severity,
      timestamp: Date.now()
    };
 
    try {
      const eventStr = JSON.stringify(eventData);
      appLogger.logAliyunPublishing(this.deviceSerialNumber, 'event', eventStr.length);
      // 发布自定义事件
      this.device.postEvent('alert', eventData, (err, data) => {
        if (err) {
          appLogger.logAliyunPublishError(this.deviceSerialNumber, 'event', err);
          console.error(`发布事件失败:`, err.message);
        } else {
          appLogger.logInfo(`事件发布成功`, { module: 'aliyun', device: this.deviceSerialNumber, eventType: event.type, description: event.description });
          console.log(`✓ 事件发布成功 [${this.deviceSerialNumber}] - ${event.description}`);
        }
      });
    } catch (err) {
      appLogger.logError(`发布事件异常`, err, { device: this.deviceSerialNumber, module: 'aliyun' });
      console.error(`发布事件异常:`, err.message);
    }
  }
 
  /**
   * 断开连接
   */
  disconnect() {
    if (!this.enabled || !this.device) return;
    
    try {
      this.device.disconnect();
      this.isConnected = false;
      console.log(`✓ 阿里云 IoT 连接已关闭 [设备: ${this.deviceSerialNumber}]`);
    } catch (err) {
      console.error(`断开连接失败:`, err.message);
    }
  }
 
  /**
   * 获取连接状态
   */
  getConnectionStatus() {
    return {
      deviceSerialNumber: this.deviceSerialNumber,
      aliyunEnabled: this.enabled,
      isConnected: this.isConnected,
      deviceName: this.tripletInfo?.deviceName
    };
  }
}
 
module.exports = AliyunIoTClient;