| | |
| | | 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() { |
| | |
| | | logger.info(`尝试重新发送 '${deviceInfo.lastSignal}' 给设备 ${deviceId}`); |
| | | this.sendKeepAliveToDevice(deviceId); // 如果设备状态是待确认,则重发上次的信号 |
| | | } |
| | | }, 5000); // 每2秒重试一次 |
| | | }, 10000); // 每2秒重试一次 |
| | | }catch(err){ |
| | | logger.error(`${deviceId}设备重试机制出错:${err}`) |
| | | } |
| | |
| | | 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('注册成功后第二次就发送数据到阿里云') |
| | |
| | | }); |
| | | // 监听设备连接状态变化 |
| | | 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); |
| | | }); |
| | | } |
| | | |
| | |
| | | if (deviceInfo.iotDevice) { |
| | | // 上报属性数据 |
| | | const props = deviceInfo.masData |
| | | |
| | | onDeviceDataReceived(deviceInfo.masData); // 调用函数处理接收到的数据 |
| | | deviceInfo.iotDevice.postProps(props, (res) => { |
| | | if (res.message==='success') { |
| | | logger.info(`${deviceId} 上报属性成功:`, res); |
| | |
| | | |
| | | } |
| | | } |
| | | // 接收到的数据 |
| | | 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); |
| | | |
| | | } |
| | | |
| | | } |
| | | |