Files
STM32F4-Base/IEC60870-Slave/test/remote_parameter_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

233 lines
12 KiB
JavaScript

/* Independent wire expectations for the optional Type200..203 example.
* Usage: node test/remote_parameter_loopback_test.cjs .build/<name>/iec104_slave_example.exe
* Local TCP verifies application integration, not external-master interoperability. */
'use strict';
const assert = require('node:assert/strict');
const net = require('node:net');
const path = require('node:path');
const { spawn } = require('node:child_process');
const { once } = require('node:events');
const { setTimeout: delay } = require('node:timers/promises');
const { Master } = require('./slave_example_loopback_test.cjs');
const executable = path.resolve(process.argv[2]);
const build = path.resolve(__dirname, '..', '.build');
const relative = path.relative(build, executable);
assert(relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
const children = [], sockets = [];
const ioas = [0x8001, 0x8003, 0x8005, 0x8006, 0x8020, 0x8221, 0x8224];
const head = (type, count, cot = 6) => Buffer.from([type, count, cot, 0x72, 7, 0]);
const u16 = value => { const b = Buffer.alloc(2); b.writeUInt16LE(value); return b; };
const address = value => Buffer.from([value & 255, (value >> 8) & 255, (value >> 16) & 255]);
const element = (ioa, tag, value) => Buffer.concat([address(ioa), Buffer.from([tag, value.length]), value]);
const floating = value => { const b = Buffer.alloc(4); b.writeFloatLE(value); return b; };
const read = (sn, addresses = []) => Buffer.concat([head(202, addresses.length), u16(sn), ...addresses.map(address)]);
const preset = (sn, elements, more = false, test = false) => Buffer.concat([
head(203, elements.length, test ? 0x86 : 6), u16(sn), Buffer.from([more ? 0x81 : 0x80]), ...elements]);
const end = (sn, cancel = false, test = false) => Buffer.concat([
head(203, 0, (cancel ? 8 : 6) | (test ? 0x80 : 0)), u16(sn), Buffer.from([0])]);
function launch(enabled, runMs) {
const args = ['--port', '0', '--ca', '7', '--events', '0', '--background-ms', '0', '--run-ms', String(runMs)];
if (enabled) args.push('--remote-parameter');
const child = spawn(executable, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
const process = { child, output: '', errors: '', done: false };
child.stdout.on('data', b => { process.output += b; });
child.stderr.on('data', b => { process.errors += b; });
process.exit = once(child, 'close').then(([code, signal]) => { process.done = true; return { code, signal }; });
process.exit.catch(() => {});
process.timer = setTimeout(() => child.kill(), runMs + 5000);
children.push(process);
return process;
}
async function listener(process) {
const deadline = Date.now() + 2500;
while (!process.done && !/LISTEN 127\.0\.0\.1:(\d+) CA=7/.test(process.output) && Date.now() < deadline) await delay(10);
const match = process.output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
assert(match, `${process.output}\n${process.errors}`);
return Number(match[1]);
}
async function connect(port, coi = 0) {
const socket = net.connect({ host: '127.0.0.1', port });
sockets.push(socket);
const master = new Master(socket); master.asynchronous = true;
await once(socket, 'connect');
await master.control(7, 0x0b);
assert.deepEqual([...await master.readASDU()], [70, 1, 4, 0, 7, 0, 0, 0, 0, coi]);
return master;
}
async function response(master, request) {
await master.send(request);
return master.readASDU();
}
async function mirror(master, request, cot = 7, cancel = false) {
const expected = Buffer.from(request); expected[2] = cot | (request[2] & 0x80);
if (cancel) expected[8] = 0x40;
assert.deepEqual(await response(master, request), expected);
}
async function values(master, sn, addresses = [], test = false) {
const request = read(sn, addresses); if (test) request[2] |= 0x80;
await master.send(request);
const result = [];
for (let frames = 0; frames < 8; ++frames) {
const frame = await master.readASDU();
assert.deepEqual([...frame.subarray(0, 1)], [202]);
assert.equal(frame[2], test ? 0x87 : 7);
assert.deepEqual([...frame.subarray(3, 6)], [0x72, 7, 0]);
assert.equal(frame.readUInt16LE(6), sn);
assert.equal(frame[8] & ~1, 0);
let offset = 9;
for (let i = 0; i < frame[1]; ++i) {
assert(offset + 5 <= frame.length);
const ioa = frame.readUIntLE(offset, 3), tag = frame[offset + 3], length = frame[offset + 4];
assert(offset + 5 + length <= frame.length);
const raw = frame.subarray(offset + 5, offset + 5 + length);
const value = tag === 4 ? raw.toString('ascii') : tag === 45 ? raw.readUInt16LE() :
tag === 35 ? raw.readUInt32LE() : raw.readFloatLE();
result.push({ ioa, tag, value }); offset += 5 + length;
}
assert.equal(offset, frame.length);
if (frame[8] === 0) return result;
}
throw new Error('Read did not terminate');
}
async function area(master, expected) {
assert.deepEqual(await response(master, Buffer.concat([head(201, 1), address(0)])),
Buffer.from([201, 1, 7, 0x72, 7, 0, 0, 0, 0, expected, 0, 0, 0, 4, 0]));
}
async function finish(process) {
assert.deepEqual(await process.exit, { code: 0, signal: null }, `${process.output}\n${process.errors}`);
assert.equal(process.errors, '');
clearTimeout(process.timer);
}
async function exercise() {
const process = launch(true, 6500), port = await listener(process);
let master = await connect(port);
await area(master, 0);
for (const sn of [1, 4, 5]) {
await mirror(master, Buffer.concat([head(200, 1), address(0), u16(sn)]), sn === 5 ? 0x47 : 7);
}
await area(master, 4);
const initial = await values(master, 0);
assert.deepEqual(initial.map(x => x.ioa), ioas);
assert.deepEqual(initial.slice(0, 4).map(x => x.value), ['DTU\0', 'Example\0', '1\0', 0xCBF43926]);
assert.deepEqual((await values(master, 1)).map(x => x.ioa), [0x8221, 0x8224]);
// 202读取请求SN对应的已保存一套;当前选中4区时仍可逐区读取,读取不能隐式切区。
for (const [sn, expected] of [[0, [30, 1]], [1, [60, 2]], [2, [90, 3]], [3, [120, 4]], [4, [150, 5]]]) {
assert.deepEqual((await values(master, sn, [0x8221, 0x8224])).map(x => x.value), expected);
}
await area(master, 4);
await mirror(master, read(1, [0x8001]), 0x47);
await mirror(master, read(0, [0x9000]), 0x6f);
const first = preset(1, [element(0x8221, 45, u16(10))], true);
await mirror(master, first);
assert.equal((await values(master, 1, [0x8221]))[0].value, 60);
await mirror(master, end(1), 0x47); // incomplete batch cannot solidify
await mirror(master, Buffer.concat([head(200, 1), address(0), u16(0)]), 0x47);
await mirror(master, preset(1, [element(0x8224, 38, floating(2.5)), element(0x8221, 45, u16(11))]));
await mirror(master, end(1));
assert.deepEqual((await values(master, 1)).map(x => x.value), [11, 2.5]);
assert.deepEqual((await values(master, 1, [0x8221, 0x8221], true)).map(x => x.value), [11, 11]);
// 固化1区不会从4区自动切过去;显式200切入后才选用刚保存的11/2.5。
await area(master, 4);
assert.deepEqual((await values(master, 4)).map(x => x.value), [150, 5]);
await mirror(master, Buffer.concat([head(200, 1), address(0), u16(1)]));
await area(master, 1);
// 当前区固化直接更新当前配置,预置期间仍保持原值;未写的复归时间须保留11。
await mirror(master, preset(1, [element(0x8224, 38, floating(3.5))]));
assert.deepEqual((await values(master, 1)).map(x => x.value), [11, 2.5]);
await mirror(master, end(1));
assert.deepEqual((await values(master, 1)).map(x => x.value), [11, 3.5]);
assert.deepEqual((await values(master, 0, [0x8221, 0x8224])).map(x => x.value), [30, 1]);
// Read-only rejection discards candidates and erects the recovery boundary.
await mirror(master, preset(0, [element(0x8020, 38, floating(3)), element(0x8001, 4, Buffer.from('X\0'))]), 0x47);
await mirror(master, preset(0, [element(0x8020, 38, floating(4))]), 0x47);
await mirror(master, end(4, true), 9, true);
assert.equal((await values(master, 0, [0x8020]))[0].value, 0);
await mirror(master, preset(0, [element(0x8020, 38, floating(4))]));
await mirror(master, end(0));
assert.equal((await values(master, 0, [0x8020]))[0].value, 4);
await area(master, 1); // SN0公共死区固化不切区,但随后日志中的当前1区配置应使用公共值4。
// CANCEL carries SN2 while cleaning the original SN1 staging area only.
await mirror(master, preset(1, [element(0x8221, 45, u16(99))]));
await mirror(master, end(2, true), 9, true);
assert.equal((await values(master, 1, [0x8221]))[0].value, 11);
assert.equal((await values(master, 2, [0x8221]))[0].value, 90);
await mirror(master, preset(1, [element(0x8221, 45, u16(77))], false, true));
await mirror(master, end(1, false, true));
assert.equal((await values(master, 1, [0x8221]))[0].value, 11);
await mirror(master, Buffer.concat([head(200, 1, 0x86), address(0), u16(4)]));
await area(master, 1); // TEST切区也只能模拟,不能改变应用选中的一套。
await mirror(master, preset(1, [element(0x8221, 45, u16(66))], true));
const broken = preset(1, [element(0x8224, 38, floating(3))]).subarray(0, 13);
await mirror(master, broken, 0x47);
await mirror(master, end(1), 0x47);
await mirror(master, end(1, true), 9, true);
assert.deepEqual((await values(master, 1)).map(x => x.value), [11, 3.5]);
// STOP discards the unfinished batch but preserves published runtime values.
await mirror(master, preset(1, [element(0x8221, 45, u16(88))], true));
await master.control(0x13, 0x23);
await master.control(7, 0x0b);
// INIT_EVERY_START在同一TCP再次启动时也发送初始化结束;远程定值仍走HIGH。
assert.deepEqual([...await master.readASDU()], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
assert.equal((await values(master, 1, [0x8221]))[0].value, 11);
await area(master, 1);
const closed = once(master.socket, 'close');
await mirror(master, Buffer.from([105, 1, 6, 0x72, 7, 0, 0, 0, 0, 1]));
await closed; await delay(80);
master = await connect(port, 2);
await area(master, 0);
for (const [sn, expected] of [[0, [30, 1]], [1, [60, 2]], [2, [90, 3]], [3, [120, 4]], [4, [150, 5]]]) {
assert.deepEqual((await values(master, sn, [0x8221, 0x8224])).map(x => x.value), expected);
}
assert.deepEqual((await values(master, 0, [0x8005, 0x8006, 0x8020])).map(x => x.value), ['1\0', 0xCBF43926, 0]);
await mirror(master, preset(0, [element(0x8020, 38, floating(5))], true));
await master.close(); // disconnect must deliver one final DISCARD
await finish(process);
assert.match(process.output, /REMOTE_PARAMETER .*solidified=3 .*discards=3 .*recovery_required=0 faulted=0/);
// 完整退出后再检查stdout,避免TCP确认与管道分块的先后造成偶发失败。
// 这里独立核对应用真正选中的配置:预置、撤销、拒绝及TEST均不得增加一条变更记录。
assert.deepEqual(process.output.split(/\r?\n/).filter(line => line.startsWith('REMOTE_SETTINGS ')), [
'REMOTE_SETTINGS reason=init target_area=0 current_area=0 reset_seconds=30 x_time=1 deadband=0',
'REMOTE_SETTINGS reason=switch target_area=1 current_area=1 reset_seconds=60 x_time=2 deadband=0',
'REMOTE_SETTINGS reason=switch target_area=4 current_area=4 reset_seconds=150 x_time=5 deadband=0',
'REMOTE_SETTINGS reason=solidify target_area=1 current_area=4 reset_seconds=150 x_time=5 deadband=0',
'REMOTE_SETTINGS reason=switch target_area=1 current_area=1 reset_seconds=11 x_time=2.5 deadband=0',
'REMOTE_SETTINGS reason=solidify target_area=1 current_area=1 reset_seconds=11 x_time=3.5 deadband=0',
'REMOTE_SETTINGS reason=solidify target_area=0 current_area=1 reset_seconds=11 x_time=3.5 deadband=4',
'REMOTE_SETTINGS reason=reset target_area=0 current_area=0 reset_seconds=30 x_time=1 deadband=0',
'REMOTE_SETTINGS reason=exit target_area=0 current_area=0 reset_seconds=30 x_time=1 deadband=0'
]);
const disabled = launch(false, 1000);
const legacy = await connect(await listener(disabled));
await mirror(legacy, Buffer.concat([head(201, 1), address(0)]), 0x6c);
await legacy.close(); await finish(disabled);
assert(!disabled.output.includes('REMOTE_PARAMETER'));
assert(!disabled.output.includes('REMOTE_SETTINGS'));
}
exercise().then(() => console.log('Remote parameter example TCP loopback passed')).catch(error => {
console.error(error);
for (const child of children) console.error(child.output, child.errors);
process.exitCode = 1;
}).finally(async () => {
for (const socket of sockets) socket.destroy();
for (const child of children) { clearTimeout(child.timer); if (!child.done) child.child.kill(); }
await Promise.allSettled(children.map(child => child.exit));
});