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

412 lines
21 KiB
JavaScript

/* Real TCP acceptance for DTU inputs and configuration effects.
* Usage: node test/dtu_process_loopback_test.cjs .build/<name>/iec104_dtu_example.exe
* Fixtures stay under this repository's .build; no target hardware is used. */
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
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 root = path.resolve(__dirname, '..');
const build = path.join(root, '.build');
assert(process.argv[2], 'Pass the built DTU executable');
const executable = path.resolve(process.argv[2]);
const relative = path.relative(build, executable);
assert(relative && !relative.startsWith('..') && !path.isAbsolute(relative));
const fixture = fs.mkdtempSync(path.join(build, 'dtu-process-'));
const config = path.join(fixture, 'device.ini');
const inputFile = path.join(fixture, 'inputs.txt');
const recordings = path.join(fixture, 'recordings');
fs.mkdirSync(recordings);
const children = [];
const sourceValues = new Map([
[0x9601, 24], [0x960a, 100], [0x9613, 100], [0x9618, 7.5],
[0x961f, 0.1], [0x9620, 0.1], [0x9621, 0.1],
[0x9622, 0.1], [0x9623, 0.1], [0x9624, 0.1], [0x9625, 0.005],
[0x9627, 10], [0x9628, 4], [0x9141, 0], [0x915e, 1],
[0xb001, 0], [0xb002, 0], [0xb003, 0], [0xb004, 0], [0xb005, 0]
]);
let phase = 'initialization';
const head = (type, count = 1, cot = 6) => Buffer.from([type, count, cot, 0x72, 7, 0]);
const addr = value => Buffer.from([value & 255, value >> 8 & 255, value >> 16 & 255]);
const u16 = value => { const b = Buffer.alloc(2); b.writeUInt16LE(value); return b; };
const u32 = value => { const b = Buffer.alloc(4); b.writeUInt32LE(value); return b; };
const f32 = value => { const b = Buffer.alloc(4); b.writeFloatLE(value); return b; };
const request = (type, ioa, bytes = [], cot = 6) => Buffer.concat([head(type, 1, cot), addr(ioa), Buffer.from(bytes)]);
const element = (ioa, tag, bytes) => Buffer.concat([addr(ioa), Buffer.from([tag, bytes.length]), bytes]);
const float = (ioa, value) => element(ioa, 38, f32(value));
const ushort = (ioa, value) => element(ioa, 45, u16(value));
const boolean = (ioa, value) => element(ioa, 1, Buffer.from([Number(value)]));
const preset = (entries, more = false, test = false) => Buffer.concat([
head(203, entries.length, test ? 0x86 : 6), u16(0), Buffer.from([more ? 0x81 : 0x80]), ...entries]);
const finish = (cancel = false, test = false) => Buffer.concat([
head(203, 0, (cancel ? 8 : 6) | (test ? 0x80 : 0)), u16(0), Buffer.from([0])]);
const near = (actual, expected, label, tolerance = 0.0001) =>
assert(Math.abs(actual - expected) <= Math.max(tolerance, Math.abs(expected) * 0.00001), `${label}: ${actual} != ${expected}`);
function inputs(changes = []) {
for (const [source, value] of changes) sourceValues.set(source, value);
const text = [...sourceValues].map(([source, value]) => `${source.toString(16).toUpperCase()}=${value}`).join('\n') + '\n';
fs.writeFileSync(`${inputFile}.next`, text, 'ascii');
fs.renameSync(`${inputFile}.next`, inputFile);
}
async function launch(events = 20, configuration = config) {
const child = spawn(executable, ['--port', '0', '--ca', '7', '--events', String(events), '--background-ms', '0',
'--run-ms', '120000', '--config', configuration, '--dtu-input', inputFile, '--dtu-recording', recordings],
{ cwd: root, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
const state = { child, output: '', errors: '', sockets: [] };
child.stdout.on('data', data => { state.output += data; });
child.stderr.on('data', data => { state.errors += data; });
state.exit = once(child, 'close'); state.exit.catch(() => {});
state.timer = setTimeout(() => child.kill(), 125000);
children.push(state);
for (let attempt = 0; attempt < 1000; ++attempt) {
const match = state.output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
if (match) { state.port = Number(match[1]); return state; }
if (child.exitCode !== null) break;
await delay(10);
}
throw Error(`No listener: ${state.output}\n${state.errors}`);
}
async function stop(state) {
for (const socket of state.sockets) socket.destroy();
if (state.child.exitCode === null) state.child.kill();
await state.exit; clearTimeout(state.timer);
assert.equal(state.errors, '', state.output);
}
async function until(master, predicate) {
const recent = [];
const deadline = Date.now() + 10000;
for (let i = 0; i < 4000 && Date.now() < deadline; ++i) {
const asdu = await master.readASDU();
assert.equal(asdu.readUInt16LE(4), 7);
recent.push(asdu.toString('hex')); if (recent.length > 6) recent.shift();
if (predicate(asdu)) return asdu;
}
throw Error(`No matching response during ${phase}: ${recent.join(' ')}`);
}
async function mirror(master, bytes, cot = 7, cancel = false) {
const expected = Buffer.from(bytes); expected[2] = cot | (bytes[2] & 0x80);
if (cancel) expected[8] = 0x40;
await master.send(bytes);
const response = await until(master, b => b[0] === bytes[0]);
assert.deepEqual(response, expected, `Parameter response during ${phase}`);
}
async function commit(master, entries) {
for (let index = 0; index < entries.length; index += 20) {
await mirror(master, preset(entries.slice(index, index + 20), index + 20 < entries.length));
}
await mirror(master, finish());
}
async function connect(state) {
const socket = net.connect({ host: '127.0.0.1', port: state.port });
state.sockets.push(socket);
const master = new Master(socket); master.asynchronous = true;
await once(socket, 'connect'); await master.control(7, 11);
const initialization = await master.readASDU();
assert.equal(initialization[0], 70); assert.equal(initialization[2], 4);
await mirror(master, request(103, 0, [0, 0, 0, 0, 1, 1, 26]));
await master.send(request(100, 0, [20]));
let confirmed = false;
for (let frame = 0; frame < 500; ++frame) {
const asdu = await until(master, () => true);
if (asdu[0] === 100 && asdu[2] === 7) confirmed = true;
if (asdu[0] === 100 && asdu[2] === 10) { assert(confirmed); return master; }
}
throw Error('Startup general interrogation did not finish');
}
async function read(master, ioa, type) {
await master.send(request(102, ioa, [], 5));
const asdu = await until(master, b => (b[0] === type && b[2] === 5 && b.readUIntLE(6, 3) === ioa) ||
(b[0] === 102 && b.readUIntLE(6, 3) === ioa));
assert.equal(asdu[0], type, `Read 0x${ioa.toString(16)} rejected: ${asdu.toString('hex')}`);
return type === 13 ? asdu.readFloatLE(9) : asdu[9] & (type === 31 ? 3 : 1);
}
async function poll(master, ioa, type, expected, timeout = 3000) {
const deadline = Date.now() + timeout;
let actual;
do {
actual = await read(master, ioa, type);
if (Math.abs(actual - expected) < 0.0001) return actual;
await delay(20);
} while (Date.now() < deadline);
assert.fail(`Read 0x${ioa.toString(16)} during ${phase}: ${actual}, expected ${expected}`);
}
async function remain(master, ioa, type, expected, duration) {
const deadline = Date.now() + duration;
do {
assert.equal(await read(master, ioa, type), expected, `${phase}: unexpected state transition`);
await delay(20);
} while (Date.now() < deadline);
}
async function command(master, type, ioa, value, feedback = null) {
await mirror(master, request(type, ioa, [value | 12 | 128]));
await master.send(request(type, ioa, [value | 12]));
let confirmed = false, returned = feedback === null;
for (let i = 0; i < 200; ++i) {
const a = await until(master, () => true);
if (feedback !== null && a[0] === feedback.type && a[2] === 11 && a.readUIntLE(6, 3) === feedback.ioa) {
assert.equal(a[9] & 1, feedback.value, 'COT11 must use the same inversion as Read');
returned = true;
}
if (a[0] !== type || a.readUIntLE(6, 3) !== ioa) continue;
assert.equal(a[2] & 0x40, 0, `Command rejected during ${phase}: ${a.toString('hex')}`);
if (a[2] === 7) confirmed = true;
if (a[2] === 10) { assert(confirmed && returned, 'command confirmation/return information missing'); return; }
}
throw Error('Command did not terminate');
}
async function counter(master) {
await master.send(request(101, 0, [5]));
const values = new Map(); let confirmed = false;
for (let frame = 0; frame < 200; ++frame) {
const a = await until(master, b => b[0] === 101 || b[0] === 206);
if (a[0] === 101) {
if (a[2] === 7) { confirmed = true; continue; }
assert.equal(a[2], 10); assert(confirmed); assert.equal(values.size, 8); return values;
}
assert(confirmed); assert.equal(a[2], 37);
let p = 6, ioa;
for (let i = 0; i < (a[1] & 127); ++i) {
if (i === 0 || !(a[1] & 128)) { ioa = a.readUIntLE(p, 3); p += 3; } else ioa++;
assert(!values.has(ioa)); values.set(ioa, a.readFloatLE(p)); p += 5;
}
assert.equal(p, a.length);
}
throw Error('Counter interrogation did not finish');
}
const named = value => { const b = Buffer.from(value, 'ascii'); return Buffer.concat([Buffer.from([b.length]), b]); };
const fileHead = (op, cot) => Buffer.from([210, 1, cot, 0, 7, 0, 0, 0, 0, 2, op]);
async function directory(master) {
await master.send(Buffer.concat([fileHead(1, 5), u32(42), named('COMTRADE'), Buffer.alloc(15)]));
const entries = [];
for (let page = 0; page < 100; ++page) {
const a = await until(master, b => b[0] === 210 && b[10] === 2);
assert.equal(a[2], 5); assert.equal(a[11], 0);
let p = 18;
for (let i = 0; i < a[17]; ++i) {
const length = a[p++], name = a.subarray(p, p + length).toString('ascii'); p += length;
assert.equal(a[p++], 0); const size = a.readUInt32LE(p); p += 11;
entries.push({ name, size });
}
assert.equal(p, a.length); if (!a[16]) return entries;
}
throw Error('Recording directory did not finish');
}
async function download(master, entry) {
await master.send(Buffer.concat([fileHead(3, 6), named(entry.name)]));
const active = await until(master, b => b[0] === 210 && b[10] === 4);
assert.equal(active[2], 7); assert.equal(active[11], 0);
const p = 13 + active[12]; assert.equal(active.readUInt32LE(p + 4), entry.size);
const chunks = []; let offset = 0;
for (let segment = 0; segment < 10000; ++segment) {
const a = await until(master, b => b[0] === 210 && b[10] === 5);
assert.equal(a.readUInt32LE(15), offset);
const bytes = a.subarray(20, -1);
assert.equal(a.at(-1), bytes.reduce((sum, b) => (sum + b) & 255, 0));
chunks.push(bytes); offset += bytes.length;
if (!a[19]) {
assert.equal(offset, entry.size);
await master.send(Buffer.concat([fileHead(6, 5), u32(0), a.subarray(15, 19), Buffer.from([0])]));
return Buffer.concat(chunks);
}
}
throw Error('Recording download did not finish');
}
async function measurementEffects(master) {
phase = 'diagnostic inputs';
near(await poll(master, 0x9601, 13, 24), 24, 'battery input');
near(await read(master, 0x9618, 13), 7.5, 'unmapped longitude source');
for (let source = 0x9601; source <= 0x962c; ++source) {
if (source >= 0x961c && source <= 0x961e) continue;
assert(Number.isFinite(await read(master, source, 13)), `Source ${source.toString(16)}`);
}
for (let source = 0x9141; source <= 0x919d; ++source) assert([0, 1].includes(await read(master, source, 30)));
phase = 'multiplier and inversion commit';
await commit(master, [float(0xa2c1, 2), float(0xa2d8, 3), float(0xa2e7, 2),
ushort(0x9e01, 1), ushort(0x9e1e, 1)]);
await poll(master, 0x9601, 13, 48); near(await read(master, 0x9618, 13), 22.5, 'unmapped multiplier');
await poll(master, 0x9141, 30, 1); await poll(master, 0x915e, 30, 0);
await poll(master, 0x0007, 30, 1); await poll(master, 0x0003, 30, 0);
phase = 'cancel and TEST leave runtime unchanged';
await mirror(master, preset([float(0xa2c1, 9), ushort(0x9e01, 0)]));
near(await read(master, 0x9601, 13), 48, 'preset invisible');
await mirror(master, finish(true), 9, true);
await mirror(master, preset([float(0xa2c1, 9), ushort(0x9e01, 0)], false, true));
await mirror(master, finish(false, true));
near(await read(master, 0x9601, 13), 48, 'cancel/TEST multiplier');
assert.equal(await read(master, 0x9141, 30), 1);
phase = 'transformer ratios and power polarity';
await commit(master, [float(0x8024, 10), float(0x8025, 100), float(0x8026, 2),
float(0x8040, 200), float(0x8041, 5), float(0x8042, 3),
float(0x8043, 20), float(0x8044, 1), float(0x8045, 4),
float(0x8054, 2), float(0x8055, 4), boolean(0x8056, true)]);
await poll(master, 0x960a, 13, 200); await poll(master, 0x9622, 13, 0.3);
near(await read(master, 0x9625, 13), 0.02, 'residual transformer');
await poll(master, 0x9627, 13, -240); await poll(master, 0x9628, 13, -48);
phase = 'energy factor changes physical integration';
await delay(150);
const before = await counter(master), started = Date.now();
await delay(800);
const after = await counter(master), elapsed = Date.now() - started;
const actual = after.get(0x6403) - before.get(0x6403);
const expected = 240 * 4 * elapsed / 3600000000;
assert(actual > expected * 0.65 && actual < expected * 1.35, `8055 integration: ${actual} vs ${expected}`);
console.log('DTU process TCP: diagnostic 41/93 sources, calibration/inversion, cancel/TEST, ratios, power and energy passed');
}
async function protectionEffects(master) {
phase = 'protection and output pulse setup';
await commit(master, [float(0x802c, 0.4), float(0x802d, 0.4), boolean(0x8863, true),
boolean(0x8868, true), ushort(0x8864, 1), float(0x8865, 0.7), float(0x886f, 0.1),
float(0x8870, 0.1), ushort(0x887e, 0), boolean(0x804c, false), boolean(0x804d, false),
boolean(0x804e, false), boolean(0x804f, false)]);
for (const stage of [0, 1, 2, 3]) {
phase = stage < 3 ? `phase OC${stage + 1} trips and recloses` : 'zero-current OC trips and recloses';
const settings = [boolean(0x8841, false), boolean(0x8845, false), boolean(0x8849, false), boolean(0x884d, false), boolean(0x8851, false)];
const base = stage < 3 ? 0x8840 + 4 * stage : 0x884c;
settings.push(boolean(base + 1, true), float(base + 2, 0.5), float(base + 3, 0.06));
await commit(master, settings);
await poll(master, 0x1001, 31, 2);
inputs([[stage < 3 ? 0x9622 : 0x9625, 0.8]]);
await poll(master, 0x1001, 31, 1);
assert.equal(await read(master, 0xb100, 30), 1, 'trip pulse must energize');
await poll(master, 0x9176 + stage, 30, 1); // Digital debounce may follow the physical breaker transition.
inputs([[stage < 3 ? 0x9622 : 0x9625, stage < 3 ? 0.1 : 0.005]]);
await poll(master, 0x1001, 31, 2, 4000);
assert.equal(await read(master, 0xb100, 30), 1, 'close pulse must energize');
await delay(450); assert.equal(await read(master, 0xb100, 30), 0, 'pulse must release');
await delay(150); // Healthy-group reset starts after the 400 ms output pulse has released.
}
phase = 'recording disabled despite a qualifying source transition';
await commit(master, [boolean(0x884d, false), boolean(0x804e, false), float(0x8051, 0.2)]);
assert.equal((await directory(master)).length, 0, 'triggered recorder must not publish a startup demo');
inputs([[0x9625, 0.5]]);
await poll(master, 0x9625, 13, 2);
await delay(200);
assert.equal((await directory(master)).length, 0, 'disabled recording must ignore a qualifying transition');
inputs([[0x9625, 0.005]]); await poll(master, 0x9625, 13, 0.02);
phase = 'recording generated by source change after enable';
await commit(master, [boolean(0x804e, true)]);
inputs([[0x9625, 0.5]]);
let entries = [];
for (let attempt = 0; attempt < 80; ++attempt) {
entries = await directory(master);
if (entries.some(e => /\.cfg$/i.test(e.name)) && entries.some(e => /\.dat$/i.test(e.name))) break;
await delay(50);
}
const cfg = entries.find(e => /\.cfg$/i.test(e.name)), dat = entries.find(e => /\.dat$/i.test(e.name));
assert(cfg && dat, 'source transition must create COMTRADE pair');
assert(dat.size > 1000 && cfg.size > 100);
const cfgBytes = await download(master, cfg), datBytes = await download(master, dat);
assert.match(cfgBytes.toString('ascii'), /1999/);
assert.equal(datBytes.length, dat.size);
assert(datBytes.some(byte => byte !== 0), 'recorded data must contain samples');
inputs([[0x9625, 0.005]]);
await commit(master, [boolean(0x804e, false)]);
console.log('DTU process TCP: OC1/2/3/zero trips, physical DP change, reclose, pulses and triggered COMTRADE download passed');
}
async function recloseInterlocks(master) {
await commit(master, [boolean(0x8841, true), boolean(0x8845, false), boolean(0x8849, false),
boolean(0x884d, false), boolean(0x8851, false), float(0x8842, 0.5), float(0x8843, 0.06),
boolean(0x8863, true), ushort(0x8864, 1), float(0x8865, 0.7), float(0x886f, 0.1)]);
inputs([[0x9162, 0], [0x9163, 0], [0x9622, 0.1]]);
for (const source of [0x9162, 0x9163]) {
phase = source === 0x9162 ? 'earth switch blocks due automatic reclose' : 'spring uncharged blocks due automatic reclose';
await poll(master, 0x1001, 31, 2); await delay(200);
inputs([[source, 1], [0x9622, 0.8]]);
await poll(master, 0x1001, 31, 1); await poll(master, source, 30, 1);
inputs([[0x9622, 0.1]]);
await remain(master, 0x1001, 31, 1, 1000);
inputs([[source, 0]]);
await poll(master, 0x1001, 31, 2);
await delay(600); // Pulse release plus the configured 100 ms healthy-group reset.
}
phase = 'manual open cancels pending automatic reclose';
await commit(master, [float(0x8865, 1.2)]);
inputs([[0x9622, 0.8]]); await poll(master, 0x1001, 31, 1);
inputs([[0x9622, 0.1]]);
await poll(master, 0xb100, 30, 0); // Manual command respects the active output pulse.
await command(master, 46, 0x6002, 1);
await remain(master, 0x1001, 31, 1, 1500);
await command(master, 45, 0x6012, 1); // Explicit reset releases the cancelled group's reclose lock.
await poll(master, 0x9174, 30, 0);
await command(master, 46, 0x6002, 2);
await poll(master, 0x1001, 31, 2);
console.log('DTU process TCP: earth/spring contacts block reclose until released; manual open cancels reclose passed');
}
async function noSampleInversion() {
phase = 'events=0 inverted indication preserves actual control permission';
const state = await launch(0, path.join(fixture, 'no-sample.ini'));
const master = await connect(state);
assert.equal(await read(master, 0x914f, 30), 1);
await command(master, 45, 0x6012, 1);
assert.equal(await read(master, 0x914f, 30), 1, 'fault reset must preserve live voltage indication while sampling is paused');
await commit(master, [ushort(0x9e4a, 1)]);
await poll(master, 0x26, 30, 0); // Actual soft plate starts enabled, indicated value is inverted.
await command(master, 45, 0x6013, 0, { type: 30, ioa: 0x26, value: 1 });
await poll(master, 0x26, 30, 1);
await master.send(request(46, 0x6002, [1 | 12 | 128]));
const rejected = await until(master, b => b[0] === 46 && b.readUIntLE(6, 3) === 0x6002);
assert.equal(rejected[2] & 0x40, 0x40, 'inverted indication=1 must not bypass disabled actual soft plate');
assert.equal(await read(master, 0x1001, 31), 2, 'rejected command must not move breaker');
await command(master, 45, 0x6013, 1, { type: 30, ioa: 0x26, value: 0 });
await poll(master, 0x26, 30, 0);
await command(master, 46, 0x6002, 1);
assert.equal(await read(master, 0x1001, 31), 1, 'actual enabled soft plate permits command despite inverted indication=0');
await master.close(); await stop(state);
console.log('DTU process TCP: events=0 inversion agrees in COT11/Read, soft-plate permission uses raw state passed');
}
async function main() {
inputs();
const first = await launch();
const master = await connect(first);
await measurementEffects(master);
await protectionEffects(master);
await recloseInterlocks(master);
assert(fs.existsSync(config), 'committed settings must create the configured INI');
await master.close(); await stop(first);
phase = 'persisted runtime effects after process restart';
const second = await launch(), restored = await connect(second);
await poll(restored, 0x9601, 13, 48); await poll(restored, 0x9141, 30, 1);
await poll(restored, 0x9618, 13, 22.5); await poll(restored, 0x960a, 13, 200);
await poll(restored, 0x9622, 13, 0.3); await poll(restored, 0x9627, 13, -240);
await restored.close(); await stop(second);
console.log(`DTU process TCP: runtime effects survive restart. Artifacts: ${fixture}`);
await noSampleInversion();
}
main().catch(error => {
console.error(`DTU process failure during ${phase}:`, error);
for (const state of children) console.error(state.output, state.errors);
console.error(`Artifacts: ${fixture}`);
process.exitCode = 1;
}).finally(() => {
for (const state of children) {
clearTimeout(state.timer);
for (const socket of state.sockets) socket.destroy();
if (state.child.exitCode === null) state.child.kill();
}
});