东丽网口版透析机 socket- server 通讯
chenyc
2025-08-06 b0c04fb404892e7b14f6f82ba8153bea3db9b097
index.js
@@ -4,6 +4,7 @@
const aliyunIot = require('aliyun-iot-device-sdk');
const { getAliyunDeviceSecret } = require('./api');
const toModel = require('./Strholp');
const { publishMessage } = require('./mqttClient');
// 定义 DeviceManager 类来管理设备连接
class DeviceManager extends EventEmitter {
    constructor() {
@@ -77,7 +78,7 @@
                    logger.info(`尝试重新发送 '${deviceInfo.lastSignal}' 给设备 ${deviceId}`);
                    this.sendKeepAliveToDevice(deviceId);  // 如果设备状态是待确认,则重发上次的信号
                }
            }, 5000);  // 每2秒重试一次
            }, 10000);  // 每2秒重试一次
        }catch(err){
            logger.error(`${deviceId}设备重试机制出错:${err}`)
        }
@@ -137,7 +138,7 @@
                this.stopRetryMechanism(deviceId);  // 停止重试机制
                // 根据上次发送的信号启动相应的定时发送机制
                this.startKeepAlive(deviceId, deviceInfo.lastSignal);  // 启动定时发送 'K0000' 的机制
                logger.info(`${deviceId}启动定时发送 'K' 的机制60秒一次`);
                logger.info(`${deviceId}启动定时发送 ${deviceInfo.lastSignal} 的机制60秒一次`);
                this.registerDevice(deviceId)
            }else{
                logger.info('注册成功后第二次就发送数据到阿里云')
@@ -173,11 +174,11 @@
                    });
                    // 监听设备连接状态变化
                    deviceInfo.iotDevice.on('connect', () => {
                        logger.info(`${deviceId} 连接到阿里云IoT平台成功`);
                        // logger.info(`${deviceId} 连接到阿里云IoT平台成功`);
                    });
                
                    deviceInfo.iotDevice.on('error', (err) => {
                        logger.info(`${deviceId} 设备连接错误:`, err);
                        logger.info(`${deviceId} 设备连接到阿里云IoT平台错误:`, err);
                    });
                }
                
@@ -194,6 +195,8 @@
            if (deviceInfo.iotDevice) {
              // 上报属性数据
              const props = deviceInfo.masData
              onDeviceDataReceived(deviceInfo.masData); // 调用函数处理接收到的数据
              deviceInfo.iotDevice.postProps(props, (res) => {
                if (res.message==='success') {
                    logger.info(`${deviceId} 上报属性成功:`, res);
@@ -269,3 +272,21 @@
        
    }
}
// 接收到的数据
const  onDeviceDataReceived=(data)=> {
    const topic = `touxiji/${data.n}`;
    const payload = JSON.stringify({
      ...data,
      timestamp: new Date().toISOString()
    });
    try {
        logger.info(`发布消息到主题 ${topic}: ${payload}`);
        publishMessage(topic, payload);
    } catch (error) {
        logger.error(`发布消息到主题 ${topic} 失败:`, error);
        throw new CustomError("发布消息失败", error);
     }
  }