gx
chenyc
5 天以前 747a86bb94006aaca721cfc0c0ce7061643a9ea6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
#!/usr/bin/env node
 
const fs = require('fs');
const path = require('path');
const net = require('net');
const {
  FRAME_LENGTH,
  JhmDecoder,
  additiveChecksum,
} = require('./decoder');
 
const DEFAULT_FRAMES_FILE = path.join(__dirname, '数据模拟.md');
const DEFAULT_INTERVAL_MS = 1000;
const DEFAULT_AL_MODEL_FILE = path.join(__dirname, 'alModel.json');
const BUILTIN_SCENARIOS = {
  jihua20260414: {
    name: '2026-04-14 真实业务抓包',
    description: '按历史抓包循环回放透析机固定帧数据。',
    framesFile: path.join(__dirname, 'jihua20260414.txt'),
    cycleLength: 17,
  },
};
 
// 模拟器支持三种方式:文件回放、单独血压、文件加血压混发。
function parseArgs(argv) {
  const options = {
    host: '127.0.0.1',
    port: 9000,
    intervalMs: DEFAULT_INTERVAL_MS,
    framesFile: DEFAULT_FRAMES_FILE,
    scenario: '',
    repeat: 0,
    localAddress: '',
    mode: 'file',
    includeBloodPressure: false,
    bpSystolic: 120,
    bpDiastolic: 80,
    bpPulse: 89,
    bpTime: '',
    bpIncludeTime: true,
  };
 
  for (let index = 2; index < argv.length; index += 1) {
    const arg = argv[index];
    const value = argv[index + 1];
 
    if (arg === '--host' && value) {
      options.host = value;
      index += 1;
    } else if (arg === '--port' && value) {
      options.port = Number(value);
      index += 1;
    } else if (arg === '--interval' && value) {
      options.intervalMs = Number(value);
      index += 1;
    } else if (arg === '--frames' && value) {
      options.framesFile = path.resolve(value);
      index += 1;
    } else if (arg === '--scenario' && value) {
      options.scenario = value.trim();
      index += 1;
    } else if (arg === '--repeat' && value) {
      options.repeat = Number(value);
      index += 1;
    } else if (arg === '--local-address' && value) {
      options.localAddress = value;
      index += 1;
    } else if (arg === '--mode' && value) {
      options.mode = value.trim().toLowerCase();
      index += 1;
    } else if (arg === '--with-blood-pressure' || arg === '--with-bp') {
      options.includeBloodPressure = true;
    } else if (arg === '--blood-pressure' || arg === '--bp') {
      options.mode = 'blood-pressure';
    } else if (arg === '--bp-systolic' && value) {
      options.bpSystolic = Number(value);
      index += 1;
    } else if (arg === '--bp-diastolic' && value) {
      options.bpDiastolic = Number(value);
      index += 1;
    } else if (arg === '--bp-pulse' && value) {
      options.bpPulse = Number(value);
      index += 1;
    } else if (arg === '--bp-time' && value) {
      options.bpTime = value.trim();
      index += 1;
    } else if (arg === '--bp-no-time') {
      options.bpIncludeTime = false;
    } else if (arg === '--help' || arg === '-h') {
      options.help = true;
    }
  }
 
  return options;
}
 
function printHelp() {
  console.log(`JHM TCP 模拟客户端
 
用法:
  node tcp-simulator.js --host 127.0.0.1 --port 9000
  node tcp-simulator.js --scenario jihua20260414 --host 127.0.0.1 --port 9000 --repeat 1
  node tcp-simulator.js --host 127.0.0.1 --port 9000 --with-bp
  node tcp-simulator.js --bp --host 127.0.0.1 --port 9000 --bp-systolic 120 --bp-diastolic 80 --bp-pulse 89
  node tcp-simulator.js --bp --host 127.0.0.1 --port 9000 --bp-time "2026-04-15 09:30"
 
参数:
  --host <ip>             目标 TCP 服务地址,默认 127.0.0.1
  --port <number>         目标 TCP 服务端口,默认 9000
  --interval <ms>         报文发送间隔,默认 1000ms
  --frames <path>         十六进制报文文件,默认 ./数据模拟.md
  --scenario <name>       内置场景:${Object.keys(BUILTIN_SCENARIOS).join(', ')}
  --repeat <number>       发送轮数,0 表示无限循环,默认 0
  --local-address <ip>    绑定本地 IP,用于模拟设备来源 IP
  --mode <file|blood-pressure>
  --with-blood-pressure, --with-bp
                          在每轮文件或场景回放后追加 1 条血压报文
  --blood-pressure, --bp  等同于 --mode blood-pressure
  --bp-systolic <n>       收缩压,默认 120
  --bp-diastolic <n>      舒张压,默认 80
  --bp-pulse <n>          脉搏,默认 89
  --bp-time "<text>"      自定义时间,格式 YYYY-MM-DD HH:mm,默认当前本地时间
  --bp-no-time            发送全 0 时间字节
  --help, -h              显示帮助
`);
}
 
function resolveScenario(options) {
  if (!options.scenario) {
    return { ...options, scenarioConfig: null };
  }
 
  const scenarioConfig = BUILTIN_SCENARIOS[options.scenario];
 
  if (!scenarioConfig) {
    throw new Error(`未知场景: ${options.scenario}`);
  }
 
  return {
    ...options,
    mode: 'file',
    framesFile: scenarioConfig.framesFile,
    scenarioConfig,
  };
}
 
function validateBloodPressureOptions(options) {
  for (const [name, value] of [
    ['bp-systolic', options.bpSystolic],
    ['bp-diastolic', options.bpDiastolic],
    ['bp-pulse', options.bpPulse],
  ]) {
    if (!Number.isInteger(value) || value < 0 || value > 0xFFFF) {
      throw new Error(`${name} 必须是 0 到 65535 之间的整数`);
    }
  }
 
  if (options.bpIncludeTime && options.bpTime) {
    parseBloodPressureTimeText(options.bpTime);
  }
}
 
function validateOptions(options) {
  if (!options.host) {
    throw new Error('必须指定 host');
  }
 
  if (!Number.isInteger(options.port) || options.port <= 0) {
    throw new Error('port 必须是正整数');
  }
 
  if (!Number.isInteger(options.intervalMs) || options.intervalMs <= 0) {
    throw new Error('interval 必须是大于 0 的毫秒整数');
  }
 
  if (!Number.isInteger(options.repeat) || options.repeat < 0) {
    throw new Error('repeat 必须是大于等于 0 的整数');
  }
 
  if (!['file', 'blood-pressure'].includes(options.mode)) {
    throw new Error(`不支持的模式: ${options.mode}`);
  }
 
  if (options.mode === 'file' && !fs.existsSync(options.framesFile)) {
    throw new Error(`未找到报文文件: ${options.framesFile}`);
  }
 
  if (options.mode === 'blood-pressure' || options.includeBloodPressure) {
    validateBloodPressureOptions(options);
  }
}
 
function bufferToHex(buffer) {
  return Array.from(buffer, (value) => value.toString(16).toUpperCase().padStart(2, '0')).join(' ');
}
 
function parseHexLine(line) {
  const normalized = line.replace(/0x/gi, ' ').replace(/[^a-fA-F0-9]/g, ' ');
  const hexPairs = normalized.split(/\s+/).filter(Boolean);
 
  if (hexPairs.length === 0) {
    return null;
  }
 
  return Buffer.from(hexPairs.map((pair) => {
    if (pair.length > 2) {
      throw new Error(`非法字节: ${pair}`);
    }
 
    return Number.parseInt(pair, 16);
  }));
}
 
function loadFramesByLines(content) {
  const lines = content.split(/\r?\n/);
  const frames = [];
  const framePattern = /^(?:0x)?[0-9a-fA-F]{2}(?:\s+(?:0x)?[0-9a-fA-F]{2})+$/;
 
  for (const line of lines) {
    const trimmed = line.trim();
 
    if (!trimmed || trimmed.startsWith('```') || trimmed.startsWith('#')) {
      continue;
    }
 
    if (!framePattern.test(trimmed)) {
      continue;
    }
 
    const frame = parseHexLine(trimmed);
 
    if (frame && frame.length > 0) {
      frames.push({ raw: trimmed, buffer: frame });
    }
  }
 
  return frames;
}
 
function loadFramesFromContinuousHex(content) {
  const bytes = (content.match(/[0-9a-fA-F]{2}/g) || []).map((pair) => Number.parseInt(pair, 16));
  const frames = [];
 
  for (let index = 0; index <= bytes.length - FRAME_LENGTH;) {
    if (bytes[index] === 0xEE && bytes[index + 1] === 0x55) {
      const buffer = Buffer.from(bytes.slice(index, index + FRAME_LENGTH));
      frames.push({ raw: bufferToHex(buffer), buffer });
      index += FRAME_LENGTH;
      continue;
    }
 
    index += 1;
  }
 
  return frames;
}
 
function loadFrames(framesFile) {
  const content = fs.readFileSync(framesFile, 'utf8');
  const lineFrames = loadFramesByLines(content);
 
  if (lineFrames.length > 0) {
    return {
      frames: lineFrames,
      mode: 'line',
    };
  }
 
  const continuousFrames = loadFramesFromContinuousHex(content);
 
  if (continuousFrames.length > 0) {
    return {
      frames: continuousFrames,
      mode: 'continuous',
    };
  }
 
  throw new Error('报文文件中没有找到可发送的十六进制报文');
}
 
function analyzeFrames(frames, scenarioConfig) {
  const decoder = new JhmDecoder({ alModelPath: DEFAULT_AL_MODEL_FILE });
  const analysis = {
    totalFrames: frames.length,
    publishableFrames: 0,
    unsupportedFrames: 0,
    snapshot: {},
    stateTransitions: [],
    fullCycles: 0,
    extraFrames: 0,
  };
  let lastState;
 
  for (let index = 0; index < frames.length; index += 1) {
    const results = decoder.push(frames[index].buffer);
 
    for (const result of results) {
      if (result.publish) {
        analysis.publishableFrames += 1;
 
        for (const [identifier, value] of Object.entries(result.metric || {})) {
          if (!(identifier in analysis.snapshot)) {
            analysis.snapshot[identifier] = value;
          }
        }
 
        if (Object.prototype.hasOwnProperty.call(result.metric || {}, 'o') && result.metric.o !== lastState) {
          analysis.stateTransitions.push({
            frameIndex: index + 1,
            value: result.metric.o,
          });
          lastState = result.metric.o;
        }
      }
 
      if (result.reason === 'unsupported-command') {
        analysis.unsupportedFrames += 1;
      }
    }
  }
 
  if (scenarioConfig && scenarioConfig.cycleLength) {
    analysis.fullCycles = Math.floor(frames.length / scenarioConfig.cycleLength);
    analysis.extraFrames = frames.length % scenarioConfig.cycleLength;
  }
 
  return analysis;
}
 
function formatSnapshot(snapshot) {
  const orderedKeys = ['F', 'A', 'sysj', 'C', 'B', 'L', 'D', 'H', 'o', 'J', 'U', 'G', 'Na', 'HCO3', 'N', 'O', 'P', 'M'];
 
  return orderedKeys
    .filter((key) => snapshot[key] !== undefined)
    .map((key) => `${key}=${snapshot[key]}`)
    .join(', ');
}
 
function parseBloodPressureTimeText(value) {
  const match = /^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/.exec(value);
 
  if (!match) {
    throw new Error(`--bp-time 格式不正确: ${value},应为 YYYY-MM-DD HH:mm`);
  }
 
  const [, year, month, day, hour, minute] = match;
 
  return [
    Number(year) % 100,
    Number(month),
    Number(day),
    Number(hour),
    Number(minute),
  ];
}
 
function getCurrentBloodPressureTimeBytes() {
  const now = new Date();
 
  return [
    now.getFullYear() % 100,
    now.getMonth() + 1,
    now.getDate(),
    now.getHours(),
    now.getMinutes(),
  ];
}
 
function buildBloodPressureFrame(options) {
  const timeBytes = options.bpIncludeTime
    ? (options.bpTime ? parseBloodPressureTimeText(options.bpTime) : getCurrentBloodPressureTimeBytes())
    : [0, 0, 0, 0, 0];
  const frameWithoutChecksum = Buffer.from([
    0xAA,
    0x55,
    0x0E,
    0xBA,
    (options.bpSystolic >> 8) & 0xFF,
    options.bpSystolic & 0xFF,
    options.bpDiastolic & 0xFF,
    options.bpPulse & 0xFF,
    ...timeBytes,
  ]);
  const checksumByte = additiveChecksum(frameWithoutChecksum);
  const buffer = Buffer.concat([frameWithoutChecksum, Buffer.from([checksumByte])]);
 
  return {
    raw: bufferToHex(buffer),
    buffer,
  };
}
 
function prepareSimulation(options) {
  if (options.mode === 'blood-pressure') {
    const frame = buildBloodPressureFrame(options);
    const analysis = analyzeFrames([frame], null);
 
    return {
      frames: [frame],
      analysis,
      loadMode: 'blood-pressure',
      scenarioConfig: null,
    };
  }
 
  const loadResult = loadFrames(options.framesFile);
  const frames = options.includeBloodPressure
    ? [...loadResult.frames, buildBloodPressureFrame(options)]
    : loadResult.frames;
  const analysis = analyzeFrames(frames, options.scenarioConfig);
 
  return {
    frames,
    analysis,
    loadMode: loadResult.mode,
    scenarioConfig: options.scenarioConfig,
  };
}
 
function startClient(options, prepared) {
  const socketOptions = {
    host: options.host,
    port: options.port,
  };
 
  if (options.localAddress) {
    socketOptions.localAddress = options.localAddress;
  }
 
  const socket = net.createConnection(socketOptions);
  let timer = null;
  let frameIndex = 0;
  let round = 0;
  let stopped = false;
 
  function stop(reason) {
    if (stopped) {
      return;
    }
 
    stopped = true;
 
    if (timer) {
      clearInterval(timer);
      timer = null;
    }
 
    if (!socket.destroyed) {
      socket.end();
      socket.destroy();
    }
 
    if (reason) {
      console.log(reason);
    }
  }
 
  function sendNextFrame() {
    const frame = prepared.frames[frameIndex];
    socket.write(frame.buffer);
    console.log(`[SIM] 已发送 round=${round + 1} frame=${frameIndex + 1} -> ${frame.raw}`);
 
    frameIndex += 1;
 
    if (frameIndex >= prepared.frames.length) {
      frameIndex = 0;
      round += 1;
 
      if (options.repeat > 0 && round >= options.repeat) {
        stop(`[SIM] 已完成 ${options.repeat} 轮发送`);
      }
    }
  }
 
  socket.on('connect', () => {
    console.log(`[SIM] 已连接到 ${options.host}:${options.port}`);
 
    if (options.localAddress) {
      console.log(`[SIM] 本地绑定地址 ${options.localAddress}`);
    }
 
    if (prepared.scenarioConfig) {
      console.log(`[SIM] 场景 ${options.scenario} -> ${prepared.scenarioConfig.name}`);
      console.log(`[SIM] 场景说明: ${prepared.scenarioConfig.description}`);
    } else if (options.mode === 'blood-pressure') {
      console.log(`[SIM] 当前模式为血压报文 systolic=${options.bpSystolic} diastolic=${options.bpDiastolic} pulse=${options.bpPulse}`);
      console.log(`[SIM] 血压时间 ${options.bpIncludeTime ? (options.bpTime || '当前本地时间') : '已禁用 / 发送全 0 字节'}`);
    } else {
      console.log(`[SIM] 已加载报文文件 ${path.basename(options.framesFile)}`);
    }
 
    if (options.mode === 'file' && options.includeBloodPressure) {
      console.log(`[SIM] 每轮追加血压报文 systolic=${options.bpSystolic} diastolic=${options.bpDiastolic} pulse=${options.bpPulse}`);
      console.log(`[SIM] 追加血压时间 ${options.bpIncludeTime ? (options.bpTime || '当前本地时间') : '已禁用 / 发送全 0 字节'}`);
    }
 
    console.log(`[SIM] 数据模式 ${prepared.loadMode} frames=${prepared.analysis.totalFrames} publishable=${prepared.analysis.publishableFrames} unsupported=${prepared.analysis.unsupportedFrames}`);
 
    if (prepared.analysis.fullCycles > 0 || prepared.analysis.extraFrames > 0) {
      console.log(`[SIM] 场景轮次统计 fullCycles=${prepared.analysis.fullCycles} extraFrames=${prepared.analysis.extraFrames}`);
    }
 
    if (prepared.analysis.stateTransitions.length > 0) {
      const transitionText = prepared.analysis.stateTransitions
        .map((item) => `frame#${item.frameIndex}:o=${item.value}`)
        .join(' -> ');
      console.log(`[SIM] 状态变化 ${transitionText}`);
    }
 
    if (Object.keys(prepared.analysis.snapshot).length > 0) {
      console.log(`[SIM] 指标快照 ${formatSnapshot(prepared.analysis.snapshot)}`);
    }
 
    sendNextFrame();
    timer = setInterval(sendNextFrame, options.intervalMs);
  });
 
  socket.on('error', (error) => {
    stop(`[SIM] 连接异常: ${error.message}`);
    process.exitCode = 1;
  });
 
  socket.on('close', () => {
    if (!stopped) {
      stop('[SIM] 连接已关闭');
    }
  });
 
  process.on('SIGINT', () => {
    stop('[SIM] 收到 SIGINT,停止发送');
    process.exit(0);
  });
 
  process.on('SIGTERM', () => {
    stop('[SIM] 收到 SIGTERM,停止发送');
    process.exit(0);
  });
}
 
function main() {
  const parsedOptions = parseArgs(process.argv);
 
  if (parsedOptions.help) {
    printHelp();
    return;
  }
 
  const options = resolveScenario(parsedOptions);
  validateOptions(options);
  const prepared = prepareSimulation(options);
  startClient(options, prepared);
}
 
if (require.main === module) {
  main();
}
 
module.exports = {
  BUILTIN_SCENARIOS,
  buildBloodPressureFrame,
  getCurrentBloodPressureTimeBytes,
  parseArgs,
  parseBloodPressureTimeText,
  prepareSimulation,
};