/**
|
* XML数据解析模块
|
* 负责XML数据的解析、状态转换检测
|
*/
|
|
const ParameterParser = require('./parser');
|
|
class FreseniusXMLParser {
|
constructor() {
|
this.buffer = '';
|
this.recordCount = 0;
|
this.lastTSPRGR = null; // 记录上一个 TSPRGR 值
|
this.prewashStartTime = null; // 预冲开始时间
|
this.treatmentStartTime = null; // 治疗开始时间
|
this.treatmentEndTime = null; // 治疗结束时间
|
this.events = []; // 事件日志
|
}
|
|
/**
|
* 解析数据流
|
* @param {Buffer} data - 接收到的数据
|
*/
|
parseData(data) {
|
this.buffer += data.toString();
|
const records = [];
|
|
const regex = /<Rec[^>]*>[\s\S]*?<\/Rec>/g;
|
let match;
|
|
while ((match = regex.exec(this.buffer)) !== null) {
|
records.push(this.analyzeRecord(match[0]));
|
}
|
|
const lastRecEnd = this.buffer.lastIndexOf('</Rec>');
|
if (lastRecEnd !== -1) {
|
this.buffer = this.buffer.substring(lastRecEnd + 6);
|
}
|
|
return records;
|
}
|
|
/**
|
* 分析单条记录
|
* @param {string} xmlStr - XML字符串
|
*/
|
analyzeRecord(xmlStr) {
|
this.recordCount++;
|
const params = ParameterParser.extractAllParameters(xmlStr);
|
const currentTSPRGR = params['TSPRGR'];
|
|
// 检查状态转换事件
|
const stateTransition = this.checkStateTransition(currentTSPRGR);
|
|
const record = {
|
recordNo: this.recordCount,
|
timestamp: new Date().toLocaleString('zh-CN'),
|
crc: ParameterParser.extractAttribute(xmlStr, 'CRC'),
|
version: ParameterParser.extractElement(xmlStr, 'Ver'),
|
dateTime: ParameterParser.extractElement(xmlStr, 'DtTm'),
|
type: ParameterParser.extractElement(xmlStr, 'Type'),
|
parameters: params,
|
keyData: ParameterParser.extractKeyData(xmlStr),
|
tsprgr: currentTSPRGR,
|
stateEvent: stateTransition
|
};
|
|
// 更新最后的 TSPRGR 值
|
if (currentTSPRGR) {
|
this.lastTSPRGR = currentTSPRGR;
|
}
|
|
return record;
|
}
|
|
/**
|
* 检查状态转换并生成事件
|
* @param {string} currentTSPRGR - 当前TSPRGR值
|
*/
|
checkStateTransition(currentTSPRGR) {
|
const now = new Date().toLocaleString('zh-CN');
|
let event = null;
|
|
if (!currentTSPRGR) return null;
|
|
// TSPRGR = 1: 预冲开始
|
if (currentTSPRGR === '1' && this.lastTSPRGR !== '1') {
|
this.prewashStartTime = now;
|
event = {
|
type: 'PREWASH_START',
|
description: '预冲开始',
|
time: now,
|
severity: 'info'
|
};
|
this.events.push(event);
|
}
|
|
// TSPRGR = 2: 治疗运行
|
if (currentTSPRGR === '2' && this.lastTSPRGR !== '2') {
|
this.treatmentStartTime = now;
|
event = {
|
type: 'TREATMENT_START',
|
description: '治疗开始 (参数采集已激活)',
|
time: now,
|
severity: 'info'
|
};
|
this.events.push(event);
|
}
|
|
// TSPRGR 从 2 到 3: 治疗结束
|
if (currentTSPRGR === '3' && this.lastTSPRGR === '2') {
|
this.treatmentEndTime = now;
|
event = {
|
type: 'TREATMENT_END',
|
description: '治疗结束',
|
time: now,
|
severity: 'warning'
|
};
|
this.events.push(event);
|
}
|
|
return event;
|
}
|
|
/**
|
* 获取事件日志
|
*/
|
getEvents() {
|
return this.events;
|
}
|
|
/**
|
* 获取记录计数
|
*/
|
getRecordCount() {
|
return this.recordCount;
|
}
|
}
|
|
module.exports = FreseniusXMLParser;
|