Files
STM32F4-Base/IEC60870-Slave/test/periodic_scan_loopback_test.cjs
T
STF bdcc8b6500
CI / L0 静态门禁 (pre-commit) (push) Failing after 7m46s
CI / L0.5 主机侧单测 (MSVC) (push) Successful in 21s
添加遥控、参数装载、文件传输等业务
2026-11-16 22:19:17 -08:00

307 lines
13 KiB
JavaScript

/* Independent TCP master for periodic snapshots. No ASDU encoder from the SUT.
* Usage: node test/periodic_scan_loopback_test.cjs example.exe [--soak-ms N] [--internal-checks]
* A soak is wall-clock time, not an accelerated fixture clock. */
'use strict';
const assert = require('node:assert/strict');
const net = require('node:net');
const {spawn, spawnSync} = require('node:child_process');
const {once} = require('node:events');
const {setTimeout: delay} = require('node:timers/promises');
const {performance} = require('node:perf_hooks');
const path = require('node:path');
const now = () => performance.now();
const expectedTypes = ['1/11','2/11'];
const diagnosticLimit = 65536;
const appendDiagnostic = (previous, bytes) => (previous + bytes.toString('utf8')).slice(-diagnosticLimit);
const exe = process.argv[2] && path.resolve(process.argv[2]);
if (!exe) throw Error('Usage: node periodic_scan_loopback_test.cjs example.exe [--soak-ms N] [--internal-checks]');
const options = process.argv.slice(3);
let soak = 0, internalChecks = false;
while (options.length) {
const option = options.shift();
if (option === '--soak-ms') soak = Number(options.shift());
else if (option === '--internal-checks') internalChecks = true;
else throw Error(`Unknown option: ${option}`);
}
assert(Number.isSafeInteger(soak) && soak >= 0 && soak <= 0xffffffff - 5000);
/* [COMMON/MASTER] 独立处理TCP粘包、I帧序号和累计ACK,逐对象解码SQ=0/1。
* 接收历史和诊断均有上限,长测不会把每一轮快照永久留在主站内存。 */
class Master {
constructor(socket, sequence, health, pause) {
this.socket = socket;
this.sequence = sequence;
this.health = health;
this.pause = pause;
this.buffer = Buffer.alloc(0);
this.ns = 0;
this.nr = 0;
this.frames = [];
this.controls = new Map(); // At most 256 control-code counters, independent of runtime.
this.error = null;
this.counts = new Map();
this.lastByType = new Map();
this.beginStartup();
socket.on('error', e => { this.error = e; });
socket.on('close', () => { if (!this.error) this.error = Error('TCP connection closed'); });
socket.on('data', bytes => {
try {
this.buffer = Buffer.concat([this.buffer, bytes]);
while (this.buffer.length >= 2) {
assert.equal(this.buffer[0], 0x68);
assert(this.buffer[1] >= 4 && this.buffer[1] <= 253);
const length = this.buffer[1] + 2;
if (this.buffer.length < length) break;
const f = this.buffer.subarray(0, length);
this.buffer = this.buffer.subarray(length);
if (!(f[2] & 1)) {
assert.equal(f.readUInt16LE(2) >> 1, this.nr);
this.nr = (this.nr + 1) & 0x7fff;
const ack = Buffer.from([0x68, 4, 1, 0, 0, 0]);
ack.writeUInt16LE(this.nr << 1, 4);
this.socket.write(ack);
this.check(f.subarray(6));
} else if (f[2] & 2) {
this.controls.set(f[2], (this.controls.get(f[2]) || 0) + 1);
if (f[2] === 0x43) this.socket.write(Buffer.from([0x68,4,0x83,0,0,0]));
}
}
} catch (e) { this.error = e; }
});
}
/* [SCAN/WIRE] 用固定点表预期值核对COT1/2帧,不调用待测库的编码或解析函数。 */
check(a) {
assert.equal(a.readUInt16LE(4), 1);
if (this.startupPhase === 'initialization') {
assert.deepEqual([...a], [70,1,4,0,1,0,0,0,0,0]);
this.startupPhase = 'interrogation';
return;
}
if (this.startupPhase === 'interrogation') {
assert(this.startupExpected.length > 0, 'I frame before real startup interrogation');
assert.deepEqual(a, this.startupExpected.shift());
// 同一个TCP数据块可紧随TERM携带快照;逐帧放行,不能等异步等待者恢复。
if (!this.startupExpected.length) this.startupPhase = 'ready';
return;
}
const type = a[0], cot = a[2] & 63;
assert(cot === 1 || cot === 2, 'Unexpected ASDU after startup');
assert.equal(a[2], cot);
assert.equal(a[3], 0);
assert.equal(!!(a[1] & 128), this.sequence);
assert.equal(a[1] & 127, 8);
assert.equal(type, 11, 'Periodic/background scans must not emit untimed digital signals');
const payload = type === 11 ? 3 : 1;
const start = type === 1 ? 1001 : type === 3 ? 1101 : 0x4001;
const values = type === 1 ? [0,1,0,1,1,0,1,0] :
type === 3 ? [1,1,1,1,1,1,1,1] : [2300,2310,2290,5000,-125,0,1234,42];
let offset = 6, base = 0;
for (let i = 0; i < 8; i++) {
let ioa;
if (!this.sequence || !i) {
ioa = a.readUIntLE(offset, 3); offset += 3; base = ioa;
} else ioa = base + i;
assert.equal(ioa, start + i);
if (type === 11) {
assert.equal(a.readInt16LE(offset), values[i]);
assert.equal(a[offset + 2], 0);
} else assert.equal(a[offset], values[i]);
offset += payload;
}
assert.equal(offset, a.length);
const key = `${cot}/${type}`;
this.counts.set(key, (this.counts.get(key) || 0) + 1);
this.frames.push({type, cot, at: now()});
// Bound master memory during 24-hour runs.
if (this.frames.length > 128) this.frames.splice(0, 64);
this.lastByType.set(key, now());
}
async waitFor(predicate, timeout = 3000) {
const end = now() + timeout;
while (!predicate()) {
this.health();
if (this.error) throw this.error;
assert(now() < end, 'TCP observation deadline exceeded');
await this.pause(10);
}
this.health();
if (this.error) throw this.error;
}
async control(code, response) {
const before = this.controls.get(response) || 0;
this.socket.write(Buffer.from([0x68,4,code,0,0,0]));
await this.waitFor(() => (this.controls.get(response) || 0) > before);
}
beginStartup() {
this.startupPhase = 'initialization';
this.startupExpected = [];
}
async startup() {
await this.waitFor(() => this.startupPhase === 'interrogation');
const request = Buffer.from([100,1,6,0x71,1,0,0,0,0,20]);
const confirmation = Buffer.from(request); confirmation[2] = 7;
this.startupExpected.push(confirmation);
// --sequence仅控制扫描;总召数据固定SQ=1、每批4点,且本夹具关闭参数。
// 仅写首IOA并紧排各点值/品质,整帧比较同时约束长度,不能只把SQ位置1。
for (const type of [1,3,11]) for (let batch = 0; batch < 2; ++batch) {
const width = type === 11 ? 3 : 1;
const start = type === 1 ? 1001 : type === 3 ? 1101 : 0x4001;
const values = type === 1 ? [0,1,0,1,1,0,1,0] :
type === 3 ? [1,1,1,1,1,1,1,1] : [2300,2310,2290,5000,-125,0,1234,42];
const asdu = Buffer.alloc(9 + 4 * width);
asdu.set([type,0x84,20,0x71,1,0]);
asdu.writeUIntLE(start + batch * 4, 6, 3);
for (let point = 0; point < 4; ++point) {
const index = batch * 4 + point, offset = 9 + point * width;
if (type === 11) {
asdu.writeInt16LE(values[index], offset);
asdu[offset + 2] = 0;
} else asdu[offset] = values[index];
}
this.startupExpected.push(asdu);
}
const termination = Buffer.from(request); termination[2] = 10;
this.startupExpected.push(termination);
const frame = Buffer.alloc(6 + request.length);
frame.set([0x68, 4 + request.length]);
frame.writeUInt16LE(this.ns << 1, 2); this.ns = (this.ns + 1) & 0x7fff;
frame.writeUInt16LE(this.nr << 1, 4); request.copy(frame, 6);
this.socket.write(frame);
await this.waitFor(() => this.startupPhase === 'ready');
}
async allTypes() {
await this.waitFor(() => expectedTypes.every(k => this.counts.has(k)));
}
}
/* [COMMON/CONNECT] 建立新TCP连接并等待START_CON;每次连接的序号由新Master从0开始。 */
async function connect(port, sequence, health, pause, signal) {
const socket = net.createConnection({host:'127.0.0.1',port});
const master = new Master(socket, sequence, health, pause);
const timer = setTimeout(() => socket.destroy(Error('TCP connect deadline exceeded')), 3000);
try {
await once(socket, 'connect', {signal});
health();
await master.control(7, 11);
await master.startup();
return master;
} catch (e) {
socket.destroy();
health();
throw e;
} finally { clearTimeout(timer); }
}
/* [SCAN/LIFECYCLE] 各SQ模式独立启动示例,依次检查快照、STOP/START和重连。
* duration只延长空闲链路观察;5秒停滞判据是本夹具的验收条件,不是库的送达保证。
* --internal-checks还要求观察器进程输出计数/定时器不变量PASS,普通示例没有该标记。 */
async function run(sequence, duration) {
const runMs = duration ? duration + 5000 : 5500;
const args = ['--port','0','--ca','1','--cyclic-ms','100','--background-ms','300',
'--no-parameter','--events','0','--run-ms',String(runMs)];
if (sequence) args.push('--sequence');
const childDeadline = now() + runMs;
const child = spawn(exe, args, {windowsHide:true, stdio:['ignore','pipe','pipe']});
const abort = new AbortController();
let stdout = '', stderr = '', childError, exitInfo, allowExit = false, stderrSeen = false;
const failChild = e => { childError = childError || e; abort.abort(childError); };
child.stdout.on('data', d => { stdout = appendDiagnostic(stdout, d); });
child.stderr.on('data', d => { stderrSeen = true; stderr = appendDiagnostic(stderr, d); });
child.stdout.on('error', failChild);
child.stderr.on('error', failChild);
child.on('error', failChild);
child.once('exit', (code, signal) => {
exitInfo = {code, signal};
if (!allowExit) failChild(Error(`Example exited before observations completed: code=${code}, signal=${signal}`));
});
// close follows drained stdio; exit alone can precede final diagnostic bytes.
const exited = new Promise(resolve => child.once('close', (code, signal) => resolve({code, signal})));
const health = () => { if (childError) throw childError; };
const pause = async ms => {
health();
try { await delay(ms, undefined, {signal: abort.signal}); }
catch (e) { health(); throw e; }
health();
};
const waitExit = async timeout => {
let timer;
try {
return await Promise.race([exited, new Promise((resolve, reject) => {
timer = setTimeout(() => reject(Error('Example exit deadline exceeded')), timeout);
})]);
} finally { clearTimeout(timer); }
};
let master;
try {
const end = now() + 5000;
let match;
while (!(match = stdout.match(/127\.0\.0\.1:(\d+)/))) {
health();
assert(now() < end, `No listening endpoint: ${stdout} ${stderr}`);
await pause(10);
}
master = await connect(Number(match[1]), sequence, health, pause, abort.signal);
await master.allTypes();
await master.control(0x13, 0x23);
// STOP_CON follows any pre-numbered current frame. Observe I sequence only;
// control/ack bytes are allowed and are never asserted to be zero.
const stoppedNr = master.nr;
await pause(400);
assert.equal(master.nr, stoppedNr, 'new I frame after STOP completion');
master.counts.clear();
master.beginStartup();
await master.control(7, 11);
await master.startup();
await master.allTypes();
master.socket.destroy();
await pause(80);
master = await connect(Number(match[1]), sequence, health, pause, abort.signal);
await master.allTypes(); // Sequence restarts at zero; all snapshots remain current.
const began = now();
let rounds = 0;
while (now() - began < duration) {
await pause(Math.min(1000, duration - (now() - began)));
if (master.error) throw master.error;
for (const key of expectedTypes) {
assert(now() - master.lastByType.get(key) < 5000, `snapshot stream ${key} stalled under an idle link`);
}
if (++rounds % 60 === 0) process.stdout.write(`Soak SQ=${+sequence}: ${Math.floor(now()-began)} ms\n`);
}
health();
const observedMs = Math.floor(now() - began);
allowExit = true;
master.socket.destroy();
const {code} = await waitExit(Math.max(1000, childDeadline - now() + 5000));
health();
assert.equal(code, 0, `${stdout}\n${stderr}`);
assert.equal(stderrSeen, false, stderr);
if (internalChecks) {
const marker = stdout.match(/PeriodicScan soak invariants: PASS checks=([1-9][0-9]*) polls=([1-9][0-9]*) max_zero_no_progress=([0-9]+) limit=([0-9]+)/);
assert(marker, 'Internal observer PASS marker missing from child output');
console.log(`SQ=${+sequence}: ${marker[0]}`);
}
console.log(`Periodic scan TCP SQ=${+sequence}: PASS, Type70/GI startup, COT1/2, IOA/value/quality, STOP/START, reconnect${duration ? `, monotonic elapsed soak ${observedMs} ms` : ''}`);
} catch (e) {
console.error(`Example diagnostics (last ${diagnosticLimit} characters per stream):\n${stdout}\n${stderr}`);
throw e;
} finally {
if (master) master.socket.destroy();
allowExit = true;
if (child.pid && !exitInfo) {
child.kill();
await waitExit(3000).catch(e => { console.error(e.message); });
}
}
}
/* [ENTRY/MAIN] 先验证非法CLI值,再跑SQ=0及SQ=1;长测时长仅施加于第一套,第二套仍做短回归。 */
async function main() {
for (const args of [['--cyclic-ms','99'],['--background-ms','-1'],['--cyclic-ms','4294967296']]) {
const p = spawnSync(exe,args,{windowsHide:true,timeout:3000,encoding:'utf8'});
assert.ifError(p.error); assert.notEqual(p.status,0);
}
await run(false, soak);
await run(true, 0);
}
main().catch(e => { console.error(e); process.exitCode = 1; });