东丽网口版透析机 socket- server 通讯
chenyc
22 小时以前 55c8181bbe4c198f9bda5520ea0d8ba148933f9e
index.js
@@ -9,9 +9,13 @@
const appPath = process.pkg ? path.dirname(process.execPath) : __dirname;
const mqttConfigPath = path.join(appPath, 'mqtt.json');
const aliyunConfigPath = path.join(appPath, 'aliyun.json');
const httpConfigPath = path.join(appPath, 'httpConfig.json');
const homeConfigPath = path.join(appPath, 'homeConfig.json');
const mqttConfig = JSON.parse(fs.readFileSync(mqttConfigPath, 'utf8'));
const aliyunConfig=JSON.parse(fs.readFileSync(aliyunConfigPath, 'utf8'))
const aliyunConfig = JSON.parse(fs.readFileSync(aliyunConfigPath, 'utf8'));
const httpConfig = JSON.parse(fs.readFileSync(httpConfigPath, 'utf8'));
const homeConfig = JSON.parse(fs.readFileSync(homeConfigPath, 'utf8'));
console.log(aliyunConfig)
@@ -26,6 +30,8 @@
const aliyunIot = require('aliyun-iot-device-sdk');
const { getAliyunDeviceSecret } = require('./api');
const toModel = require('./Strholp');
const dataCache = require('./dataCache');
const HttpServer = require('./httpServer');
// 初始化 MQTT(独立于阿里云)
initMqtt(mqttConfig);
@@ -40,7 +46,7 @@
// ========== 常量配置 ==========
const MAX_BUFFER_SIZE = 500;      // 缓冲区最大长度
const RETRY_INTERVAL_MS = 10000;  // 重试间隔 10s
const RETRY_INTERVAL_MS = 30000;  // 重试间隔 30s
const KEEP_ALIVE_INTERVAL_MS = 60000; // 保活间隔 60s
const DEVICE_TIMEOUT_MS = 120000; // 设备无响应超时 2分钟
@@ -63,7 +69,12 @@
    }
    handleDevice(socket) {
        const deviceId = socket.remoteAddress + ':' + socket.remotePort;
        // 处理 IPv6 映射 IPv4 地址 (::ffff:127.0.0.1 -> 127.0.0.1)
        let remoteAddress = socket.remoteAddress;
        if (remoteAddress.startsWith('::ffff:')) {
            remoteAddress = remoteAddress.slice(7); // 移除 ::ffff: 前缀
        }
        const deviceId = remoteAddress + ':' + socket.remotePort;
        logger.info(`建立新连接: ${deviceId}`);
        const deviceInfo = {
@@ -109,7 +120,7 @@
                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);
            }
        });
@@ -134,7 +145,7 @@
            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);
@@ -173,7 +184,7 @@
        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);
@@ -186,9 +197,15 @@
        deviceInfo.lastAck = Date.now();
        try {
            const masData = toModel(message);
            const ipAddress = deviceId
            const masData = toModel(message, ipAddress);
            deviceInfo.iotDeviceNo = masData.n;
            deviceInfo.masData = masData;
            // ✅【新增】缓存数据到内存(按设备序号)
            dataCache.setDeviceData(masData.n, masData);
            // ✅【核心改动】收到数据立即发 MQTT(不管阿里云)
            if (mqttConfig.enabled) {
                const topic = `${mqttConfig.defaultTopicPrefix}/${masData.n}`;
@@ -301,6 +318,17 @@
        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(); // ✅ 单例!
@@ -317,7 +345,12 @@
    manager.handleDevice(socket);
});
const PORT = process.env.PORT || 10961;
const PORT =  homeConfig.socketPort || 10961;
server.listen(PORT, () => {
    logger.info(`Socket 服务已启动,监听超级端口: ${PORT}`);
});
});
// ========== 启动 HTTP 服务 ==========
const HTTP_PORT = process.env.HTTP_PORT || httpConfig.port || 8080;
const httpServer = new HttpServer(HTTP_PORT, httpConfig);
httpServer.start();