| | |
| | | const message = buffer.substring(startIdx, endIdx).trim(); |
| | | buffer = buffer.substring(endIdx + 2); // 移除已处理部分(含 \r\n) |
| | | |
| | | logger.info(`${deviceId} 接收到完整消息: ${message}`); |
| | | logger.info(`${deviceId} 接收到完整消息: ${randomLetters(20)}${message}${randomLetters(20)}`); |
| | | this.handleData(deviceId, message); |
| | | } |
| | | }); |
| | |
| | | if (deviceInfo.status === 'pending' || deviceInfo.status === 'invalid') { |
| | | // 握手阶段:在 'K' 和 'K0000' 之间切换(你的原始逻辑) |
| | | deviceInfo.lastSignal = deviceInfo.lastSignal === 'K' ? 'K0000' : 'K'; |
| | | logger.info(`重试发送 '${deviceInfo.lastSignal}' 给设备 ${deviceId}`); |
| | | logger.info(`重试发送 '${randomLetters(10)}${deviceInfo.lastSignal==='K'?'a':'b'}${randomLetters(10)}' 给设备 ${deviceId}`); |
| | | this.sendKeepAliveToDevice(deviceId); |
| | | } |
| | | }, RETRY_INTERVAL_MS); |
| | |
| | | |
| | | try { |
| | | deviceInfo.socket.write(`${deviceInfo.lastSignal}\r\n`); |
| | | logger.info(`发送信号 '${deviceInfo.lastSignal}' 给设备 ${deviceId}`); |
| | | logger.info(`发送信号 '${randomLetters(10)}${deviceInfo.lastSignal==='K'?'a':'b'}${randomLetters(10)}' 给设备 ${deviceId}`); |
| | | } catch (err) { |
| | | logger.error(`发送信号失败 ${deviceId}:`, err.message); |
| | | this.removeDevice(deviceId); |
| | |
| | | throw new CustomError("获取三元组失败", err); |
| | | } |
| | | } |
| | | // 生成随机字母字符串 |
| | | function randomLetters(length) { |
| | | const chars = 'abcdefghijklmnopqrstuvwxyz'; |
| | | let result = ''; |
| | | for (let i = 0; i < length; i++) { |
| | | result += chars.charAt(Math.floor(Math.random() * chars.length)); |
| | | } |
| | | return result; |
| | | } |
| | | |
| | | |
| | | |
| | | // ========== 启动服务器 ========== |
| | | const manager = new DeviceManager(); // ✅ 单例! |