1937 lines
110 KiB
JavaScript
1937 lines
110 KiB
JavaScript
/* 独立主站字节测试:启动示例自己的Windows Net后端,仅连接127.0.0.1随机端口。
|
||
* Node内置模块即可运行,不安装包、不复用待测ASDU编码器,不更改系统时钟。
|
||
*/
|
||
/*
|
||
* 文件内导航(搜索方括号标记;Suite:Loopback):
|
||
* 公共Master负责真实TCP/APCI/ACK;业务辅助独立构造预期字节。常规回环和持续突发各启动独立示例进程。
|
||
* [COMMON/BASE] 公共基础:Node依赖与回环启动参数
|
||
* [COMMON/MASTER] 公共主站:TCP收发、APCI序号、START/STOP与逐帧ACK
|
||
* [COMMON/POINTS] 公共预期点表:遥控修改、后续总召读回共用;含总召请求模板
|
||
* [COMMAND/HELPERS] 遥控/遥调辅助:独立请求、选择执行与返回信息
|
||
* [CI/VECTORS] 计数量辅助:初值及QCC请求模板
|
||
* [CLOCK/HELPERS] 校时辅助:Type103请求及带时标命令时间工厂
|
||
* [CI/HELPERS] 计数量辅助:应答计数、冻结读取和确认检查
|
||
* [GI/HELPERS] 总召辅助:全站/分组请求及数据帧检查
|
||
* [LOOPBACK/STARTUP_REPLAY] 启动补发:Type70、真实全总召、STOP/START和未ACK缓存
|
||
* [CLI/CASES] 命令行用例:召唤期限、现场默认配置与显式覆盖
|
||
* [LOOPBACK/REGULAR] 常规回环:参数、读/校时、遥控、计数量、总召及重连
|
||
* [LOOPBACK/CLOCK_READ] Type103读时:模拟/系统时钟、全零请求、读写顺序与只读TEST
|
||
* [LOOPBACK/FLOAT_COUNTERS] 浮点累计量:206默认、207冻结时刻与37兼容模式
|
||
* [LOOPBACK/SPONTANEOUS] 持续突发回环:SOE时间、业务交错、读回及未ACK重发
|
||
* [LOOPBACK/FIELD_PROFILE] 现场默认回环:参数初值、门限变化、背景刷新与遥信稳定
|
||
* [ENTRY/RUN] 执行入口:各独立回环顺序执行,统一报告失败
|
||
* 公共辅助、业务专属辅助和用例按分区阅读;RUN/CASE标记用于细分执行组。
|
||
*/
|
||
|
||
/* ============================================================================
|
||
* [COMMON/BASE] 公共基础:Node依赖与回环启动参数
|
||
* ============================================================================ */
|
||
'use strict';
|
||
const assert = require('node:assert/strict');
|
||
const net = require('node:net');
|
||
const fs = require('node:fs');
|
||
const path = require('node:path');
|
||
const { spawn, spawnSync } = require('node:child_process');
|
||
const { once } = require('node:events');
|
||
const { setTimeout: delay } = require('node:timers/promises');
|
||
const executable = process.argv[2];
|
||
if (!executable) throw new Error('Usage: node slave_example_loopback_test.cjs <example.exe>');
|
||
|
||
/* ============================================================================
|
||
* [COMMON/MASTER] 公共主站:TCP收发、APCI序号、START/STOP与逐帧ACK
|
||
* ============================================================================ */
|
||
class Master {
|
||
constructor(socket) {
|
||
this.socket = socket;
|
||
// TCP的data回调可能含半帧或多帧;buffer保留未凑齐的尾部,frames只存完整APDU。
|
||
// waiters与frames分别容纳先发起的读取和先收到的帧,二者都按FIFO配对。
|
||
this.buffer = Buffer.alloc(0);
|
||
this.frames = [];
|
||
this.waiters = [];
|
||
this.ns = this.nr = 0;
|
||
socket.on('data', data => {
|
||
this.buffer = Buffer.concat([this.buffer, data]);
|
||
try {
|
||
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 frame = this.buffer.subarray(0, length);
|
||
this.buffer = this.buffer.subarray(length);
|
||
const waiter = this.waiters.shift();
|
||
if (waiter) { clearTimeout(waiter.timer); waiter.resolve(frame); }
|
||
else this.frames.push(frame);
|
||
}
|
||
} catch (error) { this.fail(error); socket.destroy(); }
|
||
});
|
||
socket.on('error', error => this.fail(error));
|
||
socket.on('close', () => this.fail(new Error('Connection closed')));
|
||
}
|
||
fail(error) {
|
||
// 一次连接故障拒绝全部挂起读取;后续next也能立即看到同一故障,不再等超时。
|
||
this.error = error;
|
||
for (const waiter of this.waiters.splice(0)) {
|
||
clearTimeout(waiter.timer);
|
||
waiter.reject(error);
|
||
}
|
||
}
|
||
next() {
|
||
// 这里只取原始APDU,不推进接收序号、不发送ACK;未确认重连用例刻意使用它。
|
||
if (this.frames.length) return Promise.resolve(this.frames.shift());
|
||
if (this.error) return Promise.reject(this.error);
|
||
return new Promise((resolve, reject) => {
|
||
const waiter = { resolve, reject };
|
||
// 1500ms是测试等待上限,不是被测端的t1/t2或业务期限。
|
||
waiter.timer = setTimeout(() => {
|
||
this.waiters.splice(this.waiters.indexOf(waiter), 1);
|
||
reject(new Error('Timed out waiting for an APDU'));
|
||
}, 1500);
|
||
this.waiters.push(waiter);
|
||
});
|
||
}
|
||
async control(code, expected) {
|
||
this.socket.write(Buffer.from([0x68, 4, code, 0, 0, 0]));
|
||
for (let i = 0; i < 8; i++) {
|
||
const frame = await this.next();
|
||
if (frame[2] === 1) continue; // 主站I帧的S确认允许穿插。
|
||
assert.deepEqual([...frame], [0x68, 4, expected, 0, 0, 0]);
|
||
return;
|
||
}
|
||
throw new Error('Missing U-frame confirmation');
|
||
}
|
||
frame(payload) {
|
||
// ns/nr以帧为单位保存,编码时左移一位;组帧即消耗ns,调用方须按组帧顺序发送。
|
||
const frame = Buffer.alloc(payload.length + 6);
|
||
frame[0] = 0x68;
|
||
frame[1] = payload.length + 4;
|
||
frame.writeUInt16LE(this.ns++ << 1, 2);
|
||
frame.writeUInt16LE(this.nr << 1, 4);
|
||
Buffer.from(payload).copy(frame, 6);
|
||
return frame;
|
||
}
|
||
async send(payload, fragmented = false) {
|
||
const frame = this.frame(payload);
|
||
if (fragmented) {
|
||
// 在APCI中间切开一次写入,检查接收器能跨多次TCP读取拼帧。
|
||
this.socket.write(frame.subarray(0, 3));
|
||
await delay(10);
|
||
this.socket.write(frame.subarray(3));
|
||
} else this.socket.write(frame);
|
||
}
|
||
async readASDU() {
|
||
// 过滤S帧,逐帧核对服务端N(S)并立即确认;不把TCP一次读取当作业务响应边界。
|
||
for (let i = 0; i < 8; i++) {
|
||
const frame = await this.next();
|
||
if (frame[2] === 1) continue;
|
||
assert.equal(frame[2] & 1, 0);
|
||
assert.equal(frame.readUInt16LE(2) >> 1, this.nr++);
|
||
// 持续突发可能在最新请求到达前已组帧,捎带的N(R)允许落后,但不能确认未发送请求。
|
||
if (this.asynchronous) assert((frame.readUInt16LE(4) >> 1) <= this.ns);
|
||
else assert.equal(frame.readUInt16LE(4) >> 1, this.ns);
|
||
const ack = Buffer.from([0x68, 4, 1, 0, 0, 0]);
|
||
ack.writeUInt16LE(this.nr << 1, 4);
|
||
this.socket.write(ack); // k=1,每帧ACK后服务才可继续发下一帧。
|
||
return frame.subarray(6);
|
||
}
|
||
throw new Error('Missing I frame');
|
||
}
|
||
async close() {
|
||
const closed = once(this.socket, 'close');
|
||
this.socket.end();
|
||
await closed;
|
||
}
|
||
}
|
||
|
||
/* ============================================================================
|
||
* [COMMON/POINTS] 公共预期点表:遥控修改、后续总召读回共用;含总召请求模板
|
||
* ============================================================================ */
|
||
const signals = [0, 1, 0, 1, 1, 0, 1, 0];
|
||
const doubleSignals = Array(8).fill(1);
|
||
const measures = [2300, 2310, 2290, 5000, -125, 0, 1234, 42];
|
||
const request = (oa, qoi = 20, ca = 7) => [100, 1, 0x86, oa, ca & 0xff, ca >> 8, 0, 0, 0, qoi];
|
||
/* ============================================================================
|
||
* [COMMAND/HELPERS] 遥控/遥调辅助:独立请求、选择执行与返回信息
|
||
* ============================================================================ */
|
||
// 构造单对象45/46命令原文:CA/IOA按小端编码,QU固定为3(示例支持的持续输出)。
|
||
// type/oa/ioa/state来自用例,select决定S/E;cot/ca默认激活原因6和示例站点7。
|
||
// 返回普通字节数组,也用于故意构造不支持类型的兜底请求,不在此执行业务校验。
|
||
const commandRequest = (type, oa, ioa, state, select, cot = 6, ca = 7) =>
|
||
[type, 1, cot, oa, ca & 0xff, ca >> 8, ioa & 0xff, (ioa >> 8) & 0xff, ioa >> 16,
|
||
state | 12 | (select ? 0x80 : 0)];
|
||
|
||
// 发送payload并断言紧随其后的应答;除COT/P/N外须回显原请求,TEST位也须保留。
|
||
// master负责链路收发及确认,cot/negative描述预期应答;Promise完成表示该帧已核对。
|
||
async function commandReply(master, payload, cot, negative = false) {
|
||
await master.send(payload);
|
||
const expected = [...payload]; expected[2] = (payload[2] & 0x80) | cot | (negative ? 0x40 : 0);
|
||
assert.deepEqual([...(await master.readASDU())], expected);
|
||
}
|
||
|
||
// 总召外单/双点必须带CP56;独立检查前缀、七字节时标和值域,不接受额外无时标副本。
|
||
function timedSignal(asdu, expected, invalid) {
|
||
assert(asdu, 'Missing timed signal response');
|
||
assert([30, 31].includes(expected[0]));
|
||
assert.equal(asdu.length, 17);
|
||
assert.deepEqual([...asdu.subarray(0, 10)], expected);
|
||
const tag = asdu.subarray(10);
|
||
if (invalid !== undefined) assert.equal(Boolean(tag[2] & 0x80), invalid);
|
||
assert(tag.readUInt16LE(0) < 60000 && (tag[2] & 63) < 60 && (tag[3] & 31) < 24);
|
||
assert((tag[4] & 31) >= 1 && (tag[4] & 31) <= 31);
|
||
assert((tag[5] & 15) >= 1 && (tag[5] & 15) <= 12 && (tag[6] & 127) <= 99);
|
||
}
|
||
|
||
// 验证真实TCP全流程;selectBeforeExecute区分SBO和直接点,monitorIoa为返回信息地址。
|
||
// 顺序逐帧读取:可选的选择ACT_CON、执行ACT_CON、COT=11返回信息、执行原文ACT_TERM。
|
||
// 链路窗口k=1,只有前一帧处理完才能推进下一帧,可暴露返回信息/终止抢先的问题。
|
||
async function commandExecute(master, type, oa, ioa, state, monitorIoa, timeTag = null, selectBeforeExecute = true) {
|
||
if (selectBeforeExecute) {
|
||
const selection = commandRequest(type, oa, ioa, state, true).concat(timeTag ? timeTag() : []);
|
||
await commandReply(master, selection, 7);
|
||
}
|
||
const execute = commandRequest(type, oa, ioa, state, false).concat(timeTag ? timeTag() : []);
|
||
await commandReply(master, execute, 7);
|
||
timedSignal(await master.readASDU(),
|
||
[type === 45 || type === 58 ? 30 : 31, 1, 11, oa, 7, 0, monitorIoa & 0xff, (monitorIoa >> 8) & 0xff, 0, state]);
|
||
const terminated = [...execute]; terminated[2] = 10;
|
||
assert.deepEqual([...(await master.readASDU())], terminated);
|
||
}
|
||
|
||
// 独立构造Type49/62的基础命令元素:有符号16位设定值及QOS,QL固定为0。
|
||
const scaledCommandRequest = (oa, ioa, value, select, type = 49) =>
|
||
[type, 1, 6, oa, 7, 0, ioa & 0xff, (ioa >> 8) & 0xff, ioa >> 16,
|
||
value & 0xff, (value >> 8) & 0xff, select ? 0x80 : 0];
|
||
|
||
// 返回信息固定按Type11独立解码预期:负设定值也须保留低16位,最后一字节为品质。
|
||
// timeTag是每次调用重新采样的工厂,避免选择、执行共用已经过时的CP56。
|
||
async function scaledCommandExecute(master, oa, ioa, value, monitorIoa, type = 49, timeTag = null, selectBeforeExecute = true) {
|
||
if (selectBeforeExecute) {
|
||
const selection = scaledCommandRequest(oa, ioa, value, true, type).concat(timeTag ? timeTag() : []);
|
||
await commandReply(master, selection, 7);
|
||
}
|
||
const execute = scaledCommandRequest(oa, ioa, value, false, type).concat(timeTag ? timeTag() : []);
|
||
await commandReply(master, execute, 7);
|
||
assert.deepEqual([...(await master.readASDU())],
|
||
[11, 1, 11, oa, 7, 0, monitorIoa & 0xff, (monitorIoa >> 8) & 0xff, 0,
|
||
value & 0xff, (value >> 8) & 0xff, 0]);
|
||
const terminated = [...execute]; terminated[2] = 10;
|
||
assert.deepEqual([...(await master.readASDU())], terminated);
|
||
}
|
||
// 升降仅QU=0;位置用有符号7位编码,带时标请求每次重新取时标。
|
||
async function stepCommandExecute(master, oa, ioa, state, monitorIoa, position, type = 47, timeTag = null, selected = true) {
|
||
const make = select => {
|
||
const bytes = commandRequest(type, oa, ioa, state, select);
|
||
bytes[9] &= ~12;
|
||
return bytes.concat(timeTag ? timeTag() : []);
|
||
};
|
||
if (selected) await commandReply(master, make(true), 7);
|
||
const execute = make(false);
|
||
await commandReply(master, execute, 7);
|
||
const monitor = [5, 1, 11, oa, 7, 0, monitorIoa & 0xff, monitorIoa >> 8, 0, position & 0x7f, 0];
|
||
assert.deepEqual([...(await master.readASDU())], monitor);
|
||
const terminated = [...execute]; terminated[2] = 10;
|
||
assert.deepEqual([...(await master.readASDU())], terminated);
|
||
await master.send([102, 1, 5, oa, 7, 0, monitorIoa & 0xff, monitorIoa >> 8, 0]);
|
||
monitor[2] = 5;
|
||
assert.deepEqual([...(await master.readASDU())], monitor);
|
||
}
|
||
|
||
// 位串没有QOS或S/E;线上4字节必须完整保留bit31,返回额外带好品质QDS。
|
||
const bitstringCommandRequest = (oa, ioa, value, type = 51) =>
|
||
[type, 1, 6, oa, 7, 0, ioa & 0xff, ioa >> 8, 0,
|
||
value & 0xff, (value >>> 8) & 0xff, (value >>> 16) & 0xff, value >>> 24];
|
||
|
||
async function bitstringCommandExecute(master, oa, ioa, value, monitorIoa, type = 51, timeTag = null) {
|
||
const execute = bitstringCommandRequest(oa, ioa, value, type).concat(timeTag ? timeTag() : []);
|
||
await commandReply(master, execute, 7);
|
||
const monitor = [7, 1, 11, oa, 7, 0, monitorIoa & 0xff, monitorIoa >> 8, 0, ...execute.slice(9, 13), 0];
|
||
assert.deepEqual([...(await master.readASDU())], monitor);
|
||
const terminated = [...execute]; terminated[2] = 10;
|
||
assert.deepEqual([...(await master.readASDU())], terminated);
|
||
await master.send([102, 1, 5, oa, 7, 0, monitorIoa & 0xff, monitorIoa >> 8, 0]);
|
||
monitor[2] = 5;
|
||
assert.deepEqual([...(await master.readASDU())], monitor);
|
||
}
|
||
/* ============================================================================
|
||
* [CI/VECTORS] 计数量辅助:初值及QCC请求模板
|
||
* ============================================================================ */
|
||
const initialCounters = [120000, 345600, 7890, 0, 1, 65535, 2147483647, 42];
|
||
const counterRequest = (oa, qcc = 5, cot = 6, test = false, ca = 7) =>
|
||
[101, 1, cot | (test ? 0x80 : 0), oa, ca & 0xff, ca >> 8, 0, 0, 0, qcc];
|
||
/* ============================================================================
|
||
* [CLOCK/HELPERS] 校时辅助:Type103请求及带时标命令时间工厂
|
||
* ============================================================================ */
|
||
const clockRequest = (oa, cot = 6, test = false, ca = 7) =>
|
||
[103, 1, cot | (test ? 0x80 : 0), oa, ca & 0xff, ca >> 8, 0, 0, 0, 0x39, 0x30, 34, 12, 28, 10, 26];
|
||
// 读时请求的7字节是全零占位,不是可解码的CP56日历;正常应答仍为COT5。
|
||
const clockReadRequest = (oa, test = false, ca = 7) =>
|
||
[103, 1, 5 | (test ? 0x80 : 0), oa, ca & 0xff, ca >> 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
|
||
|
||
function checkClockRead(asdu, request, invalid = false) {
|
||
assert.equal(asdu.length, 16);
|
||
assert.deepEqual([...asdu.subarray(0, 9)], [103, 1, request[2], request[3], 7, 0, 0, 0, 0]);
|
||
const tag = asdu.subarray(9), ms = tag.readUInt16LE(0);
|
||
const minute = tag[2] & 63, hour = tag[3] & 31, day = tag[4] & 31;
|
||
assert.equal(Boolean(tag[2] & 0x80), invalid);
|
||
assert.equal(tag[2] & 0x40, 0); assert.equal(tag[3] & 0xe0, 0);
|
||
assert.equal(tag[5] & 0xf0, 0); assert.equal(tag[6] & 0x80, 0);
|
||
assert(ms < 60000 && minute < 60 && hour < 24);
|
||
const local = new Date(Date.UTC(2000 + tag[6], tag[5] - 1, day, hour, minute,
|
||
Math.floor(ms / 1000), ms % 1000));
|
||
assert.equal(local.getUTCDate(), day); assert.equal(local.getUTCMonth() + 1, tag[5]);
|
||
assert.equal(local.getUTCFullYear(), 2000 + tag[6]);
|
||
assert.equal(tag[4] >> 5, local.getUTCDay() || 7); // 响应必须含星期1..7。
|
||
return local.getTime() - 8 * 60 * 60 * 1000;
|
||
}
|
||
|
||
// 主站独立计算UTC基准,逐次按单调经过时间生成UTC+8/无SU的CP56,选择与执行不复用旧时标。
|
||
function clockTagFactory(payload, baseNs) {
|
||
const tag = payload.slice(-7), milliseconds = tag[0] | (tag[1] << 8);
|
||
const utcMs = Date.UTC(2000 + tag[6], (tag[5] & 15) - 1, tag[4] & 31,
|
||
(tag[3] & 31) - 8 - ((tag[3] >> 7) & 1), tag[2] & 63,
|
||
Math.floor(milliseconds / 1000), milliseconds % 1000);
|
||
return (adjustMs = 0) => {
|
||
// adjustMs仅用于构造刻意过期的命令;测试不调整宿主系统时钟。
|
||
const elapsedMs = Number((process.hrtime.bigint() - baseNs) / 1000000n);
|
||
const local = new Date(utcMs + elapsedMs + adjustMs + 8 * 60 * 60 * 1000);
|
||
const minuteMs = local.getUTCSeconds() * 1000 + local.getUTCMilliseconds();
|
||
return [minuteMs & 0xff, minuteMs >> 8, local.getUTCMinutes(), local.getUTCHours(),
|
||
local.getUTCDate(), local.getUTCMonth() + 1, local.getUTCFullYear() - 2000];
|
||
};
|
||
}
|
||
/* ============================================================================
|
||
* [CI/HELPERS] 计数量辅助:应答计数、冻结读取和确认检查
|
||
* ============================================================================ */
|
||
let counterSubmitted = 0, counterCompleted = 0;
|
||
|
||
// 示例每批4个累计量,整站8点/分组4点;逐点核对IOA、32位值和BCR序列号。
|
||
// values/sequence由用例明确给出,故冻结、复位后的预期不依赖待测编码器或点表实现。
|
||
async function readCounters(master, oa, qcc = 5, values = initialCounters, sequence = 0) {
|
||
const group = qcc & 0x3f;
|
||
const first = group === 2 ? 4 : 0, end = group === 1 ? 4 : 8;
|
||
const count = 2 + (end - first) / 4;
|
||
for (let frame = 0; frame < count; frame++) {
|
||
const asdu = await master.readASDU();
|
||
if (frame === 0 || frame === count - 1) {
|
||
assert.deepEqual([...asdu], counterRequest(oa, qcc, frame === 0 ? 7 : 10));
|
||
} else {
|
||
assert.equal(asdu.length, 38);
|
||
assert.deepEqual([...asdu.subarray(0, 6)], [15, 4, group === 5 ? 37 : 37 + group, oa, 7, 0]);
|
||
for (let point = 0; point < 4; point++) {
|
||
const offset = 6 + 8 * point, index = first + 4 * (frame - 1) + point;
|
||
assert.equal(asdu.readUIntLE(offset, 3), 0x6401 + index);
|
||
assert.equal(asdu.readInt32LE(offset + 3), values[index]);
|
||
assert.equal(asdu[offset + 7], sequence);
|
||
}
|
||
}
|
||
}
|
||
counterSubmitted += count;
|
||
counterCompleted++;
|
||
}
|
||
|
||
async function counterRead(master, oa, qcc = 5, values = initialCounters, sequence = 0, ca = 7) {
|
||
await master.send(counterRequest(oa, qcc, 6, false, ca));
|
||
await readCounters(master, oa, qcc, values, sequence);
|
||
}
|
||
|
||
// 用于无数据的动作确认或校验拒绝:只消费一帧,肯定动作确认即计一次完成。
|
||
// 有数据的计数量读取走readCounters,避免错误等待不存在的ACT_TERM。
|
||
async function counterReply(master, payload, cot, negative = false) {
|
||
await master.send(payload);
|
||
const expected = [...payload]; expected[2] = (payload[2] & 0x80) | cot | (negative ? 0x40 : 0);
|
||
assert.deepEqual([...(await master.readASDU())], expected);
|
||
counterSubmitted++;
|
||
if (!negative) counterCompleted++;
|
||
}
|
||
/* ============================================================================
|
||
* [GI/HELPERS] 总召辅助:全站/分组请求及数据帧检查
|
||
* ============================================================================ */
|
||
async function totalCall(master, oa, fragmented = false, qoi = 20, ca = 7) {
|
||
await master.send(request(oa, qoi, ca), fragmented);
|
||
await readTotalCall(master, oa, qoi);
|
||
}
|
||
|
||
// busyRequests的否定回复可穿插在总召数据之间;它们不消耗本次总召的正应答帧序。
|
||
// 同一总召仍严格检查ACT_CON、各类数据、ACT_TERM,不能以“允许交错”为由放松内部顺序。
|
||
async function readTotalCall(master, oa, qoi = 20, busyRequests = []) {
|
||
const original = request(oa, qoi);
|
||
// 相同关联字段的重发仍回忙否定,但它不得先于原ACT_CON上线;不同键允许独立交错。
|
||
const sameKeyNegative = Buffer.from(original); sameKeyNegative[2] = 0xc7;
|
||
// 站总召依次返回单点、双点、遥测;遥信分组含前两类,遥测分组只含最后一类。
|
||
// 每类8点、每帧4点;数据用SQ=1仅带首IOA,首尾控制帧仍为SQ=0。
|
||
const types = qoi === 20 ? [1, 3, 11] : qoi === 21 ? [1, 3] : [11];
|
||
const count = 2 + types.length * 2;
|
||
const busyReplies = busyRequests.map(payload => {
|
||
const expected = [...payload]; expected[2] = 0xc7;
|
||
if (expected[4] === 0xff && expected[5] === 0xff) { expected[4] = 7; expected[5] = 0; }
|
||
return Buffer.from(expected);
|
||
});
|
||
for (let f = 0; f < count || busyReplies.length;) {
|
||
const asdu = await master.readASDU();
|
||
if ((asdu[2] & 0x40) !== 0) {
|
||
const index = busyReplies.findIndex(expected => expected.equals(asdu));
|
||
assert(index >= 0, `Unexpected negative reply: ${asdu.toString('hex')}`);
|
||
if (sameKeyNegative.equals(asdu)) assert(f > 0, 'Repeated GI rejection overtook the original ACT_CON');
|
||
busyReplies.splice(index, 1);
|
||
continue;
|
||
}
|
||
assert(f < count, 'Unexpected response after ACT_TERM');
|
||
if (f === 0 || f === count - 1) {
|
||
const expected = [...original];
|
||
expected[2] = f === 0 ? 0x87 : 0x8a;
|
||
assert.deepEqual([...asdu], expected);
|
||
} else {
|
||
const type = types[Math.floor((f - 1) / 2)];
|
||
const digital = type !== 11;
|
||
const values = type === 1 ? signals : type === 3 ? doubleSignals : measures;
|
||
const baseIoa = type === 1 ? 1001 : type === 3 ? 1101 : 0x4001;
|
||
const width = digital ? 1 : 3;
|
||
const first = ((f - 1) % 2) * 4;
|
||
assert.equal(asdu.length, 9 + width * 4);
|
||
assert.deepEqual([...asdu.subarray(0, 6)], [type, 0x84, 0x80 | qoi, oa, 7, 0]);
|
||
const firstIoa = asdu.readUIntLE(6, 3);
|
||
assert.equal(firstIoa, baseIoa + first);
|
||
for (let p = 0; p < 4; p++) {
|
||
const offset = 9 + p * width, index = firstIoa + p - baseIoa;
|
||
assert.equal(index, first + p);
|
||
if (digital) assert.equal(asdu[offset], values[index]);
|
||
else {
|
||
assert.equal(asdu.readInt16LE(offset), values[index]);
|
||
assert.equal(asdu[offset + 2], 0);
|
||
}
|
||
}
|
||
}
|
||
f++;
|
||
}
|
||
}
|
||
|
||
// 启动门禁只接受真实站总召;旧request()/totalCall()继续专门覆盖TEST,不能借其放行。
|
||
// 本辅助核对完整帧序/对象集合,点值允许离线采样推进;TEST和分组参数仅用于门禁反例。
|
||
async function startupInterrogation(master, oa, {
|
||
parameters = false, test = false, qoi = 20, doubleValues = [1, 1, 1, 1, 1, 1, 1, 1]
|
||
} = {}) {
|
||
const payload = [100, 1, test ? 0x86 : 6, oa, 7, 0, 0, 0, 0, qoi];
|
||
await master.send(payload);
|
||
const confirmation = [...payload]; confirmation[2] = test ? 0x87 : 7;
|
||
assert.deepEqual([...(await master.readASDU())], confirmation);
|
||
const types = qoi === 20 ? [1, 3, 11] : qoi === 21 ? [1, 3] : [11];
|
||
for (const type of types) for (let batch = 0; batch < 2; ++batch) {
|
||
const asdu = await master.readASDU(), width = type === 11 ? 3 : 1;
|
||
const base = (type === 1 ? 1001 : type === 3 ? 1101 : 0x4001) + batch * 4;
|
||
assert.deepEqual([...asdu.subarray(0, 6)], [type, 0x84, (test ? 0x80 : 0) | qoi, oa, 7, 0]);
|
||
assert.equal(asdu.length, 9 + width * 4);
|
||
const firstIoa = asdu.readUIntLE(6, 3);
|
||
assert.equal(firstIoa, base);
|
||
for (let point = 0; point < 4; ++point) {
|
||
const offset = 9 + width * point, ioa = firstIoa + point;
|
||
assert.equal(ioa, base + point);
|
||
// 本辅助允许短时离线采样改变数值,仍逐元素核对编码位置和有效品质。
|
||
if (type === 11) {
|
||
const initial = [2300, 2310, 2290, 5000, -125, 0, 1234, 42][ioa - 0x4001];
|
||
const value = asdu.readInt16LE(offset);
|
||
assert(value >= initial && value <= initial + 351);
|
||
assert.equal(asdu[offset + 2], 0);
|
||
} else if (type === 1) assert(asdu[offset] === 0 || asdu[offset] === 1);
|
||
else assert.equal(asdu[offset], doubleValues[ioa - 1101]);
|
||
}
|
||
}
|
||
if (parameters && qoi === 20) {
|
||
const addresses = new Set();
|
||
for (let index = 0; index < 32; ++index) {
|
||
const asdu = await master.readASDU(), ioa = asdu.readUIntLE(6, 3);
|
||
const group = Math.floor((ioa - 0x8601) / 0x10), point = (ioa - 0x8601) % 0x10;
|
||
assert(group >= 0 && group < 4 && point >= 0 && point < 8);
|
||
assert(!addresses.has(ioa), 'Duplicate parameter in startup interrogation'); addresses.add(ioa);
|
||
const type = group === 3 ? 112 : group === 0 && point >= 4 ? 110 : 111;
|
||
assert.deepEqual([...asdu.subarray(0, 6)], [type, 1, test ? 0x94 : 20, oa, 7, 0]);
|
||
assert.equal(asdu.length, type === 112 ? 14 : 12);
|
||
assert.equal(asdu[asdu.length - 1], [1, 3, 4, 2][group]);
|
||
}
|
||
}
|
||
const termination = [...payload]; termination[2] = test ? 0x8a : 10;
|
||
assert.deepEqual([...(await master.readASDU())], termination);
|
||
}
|
||
|
||
/* ============================================================================
|
||
* [CLI/CASES] 命令行用例:两种召唤整体期限参数
|
||
* ============================================================================ */
|
||
function totalTimeoutOptions() {
|
||
// 每项启动独立进程;非法参数必须在监听之前失败,防止解析错误仍开启服务。
|
||
for (const option of ['--gi-total-timeout', '--ci-total-timeout']) {
|
||
for (const values of [[], ['-1'], ['abc'], ['1x'], ['4294967296'], [''], [' 1']]) {
|
||
const result = spawnSync(executable, [option, ...values],
|
||
{ windowsHide: true, encoding: 'utf8', timeout: 5000 });
|
||
assert.ifError(result.error);
|
||
assert.equal(result.status, 1, `${option} ${values}: ${result.stderr}`);
|
||
assert(!result.stdout.includes('LISTEN '));
|
||
}
|
||
}
|
||
const cases = [
|
||
[[], 120000, 120000],
|
||
[['--gi-total-timeout', '2345', '--ci-total-timeout', '6789'], 2345, 6789],
|
||
[['--gi-total-timeout', '0'], 0, 120000],
|
||
[['--ci-total-timeout', '0'], 120000, 0],
|
||
[['--gi-total-timeout', '0', '--ci-total-timeout', '0'], 0, 0],
|
||
[['--gi-total-timeout', '4294967295', '--ci-total-timeout', '4294967295'], 4294967295, 4294967295]
|
||
];
|
||
for (const [options, gi, ci] of cases) {
|
||
// 端口0由系统分配,run-ms=1让合法配置短暂启动后自行退出,避免占用固定2404端口。
|
||
const result = spawnSync(executable, ['--port', '0', '--run-ms', '1', ...options],
|
||
{ windowsHide: true, encoding: 'utf8', timeout: 5000 });
|
||
assert.ifError(result.error);
|
||
assert.equal(result.status, 0, result.stderr);
|
||
assert.match(result.stdout, new RegExp(`^TIMEOUTS GI_TOTAL_MS=${gi} CI_TOTAL_MS=${ci}$`, 'm'));
|
||
assert.match(result.stdout, /^LISTEN 127\.0\.0\.1:\d+ CA=1$/m);
|
||
assert.equal(result.stderr.replace(/\r\n/g, '\n'),
|
||
(gi === 0 ? 'WARNING: GI total timeout disabled (--gi-total-timeout 0).\n' : '') +
|
||
(ci === 0 ? 'WARNING: CI total timeout disabled (--ci-total-timeout 0).\n' : ''));
|
||
}
|
||
console.log('Slave example timeout CLI: passed (defaults, independent overrides, explicit disable, invalid values, uint32 boundary)');
|
||
}
|
||
|
||
function fieldProfileOptions() {
|
||
for (const values of [[], ['invalid'], [''], ['FIELD']]) {
|
||
const result = spawnSync(executable, ['--simulation', ...values],
|
||
{ windowsHide: true, encoding: 'utf8', timeout: 5000 });
|
||
assert.ifError(result.error);
|
||
assert.equal(result.status, 1, result.stderr);
|
||
assert(!result.stdout.includes('LISTEN '));
|
||
}
|
||
const cases = [
|
||
[[], 1, 'field', 100, 0, 30000],
|
||
[['--no-parameter', '--simulation', 'stress', '--events', '10', '--cyclic-ms', '200', '--background-ms', '0'],
|
||
0, 'stress', 10, 200, 0],
|
||
[['--events', '0', '--background-ms', '300'], 1, 'field', 0, 0, 300],
|
||
[['--no-parameter', '--parameter'], 1, 'field', 100, 0, 30000],
|
||
[['--parameter', '--no-parameter'], 0, 'field', 100, 0, 30000]
|
||
];
|
||
for (const [options, parameter, simulation, sample, cyclic, background] of cases) {
|
||
const result = spawnSync(executable, ['--port', '0', '--run-ms', '1', ...options],
|
||
{ windowsHide: true, encoding: 'utf8', timeout: 5000 });
|
||
assert.ifError(result.error);
|
||
assert.equal(result.status, 0, result.stderr);
|
||
assert.equal(result.stderr, '');
|
||
assert.match(result.stdout, new RegExp(`^PROFILE PARAMETER=${parameter} SIMULATION=${simulation} SAMPLE_MS=${sample} CYCLIC_MS=${cyclic} BACKGROUND_MS=${background}$`, 'm'));
|
||
}
|
||
console.log('Slave example profile CLI: passed (field defaults, explicit timing overrides, parameter enable/disable, invalid simulation)');
|
||
}
|
||
|
||
/* ============================================================================
|
||
* [LOOPBACK/REGULAR] 常规回环:参数、读/校时、遥控、计数量、总召及重连
|
||
* ============================================================================ */
|
||
async function main() {
|
||
/* [CASE/CLI] 帮助和非法启动参数 */
|
||
const help = spawnSync(executable, ['--help'], { windowsHide: true, encoding: 'utf8' });
|
||
assert.ifError(help.error);
|
||
assert.equal(help.status, 0, help.stderr);
|
||
assert(help.stdout.includes('--run-ms'));
|
||
assert(help.stdout.includes('--clock simulated|system'));
|
||
assert(help.stdout.includes('--events milliseconds'));
|
||
assert(help.stdout.includes('--simulation field|stress'));
|
||
assert(help.stdout.includes('--no-parameter'));
|
||
assert(help.stdout.includes('--gi-total-timeout milliseconds'));
|
||
assert(help.stdout.includes('--ci-total-timeout milliseconds'));
|
||
assert(help.stdout.includes('--counter-type 15|37|206|207'));
|
||
assert(help.stdout.includes('120000/120000 ms'));
|
||
assert(help.stdout.includes('0x6001..0x6008'));
|
||
assert(help.stdout.includes('0x6011..0x6018'));
|
||
assert(help.stdout.includes('0x6031..0x6038'));
|
||
assert(help.stdout.includes('0x6021..0x6028'));
|
||
assert(help.stdout.includes('0x6041..0x6048'));
|
||
assert(help.stdout.includes('Type58/59/60/62/64'));
|
||
assert(help.stdout.includes('--command-extensions'));
|
||
assert(help.stdout.includes('60000'));
|
||
const invalid = spawnSync(executable, ['--ca', '0'], { windowsHide: true, encoding: 'utf8' });
|
||
assert.ifError(invalid.error);
|
||
assert.equal(invalid.status, 1);
|
||
const invalidClock = spawnSync(executable, ['--clock', 'invalid'], { windowsHide: true, encoding: 'utf8' });
|
||
assert.ifError(invalidClock.error);
|
||
assert.equal(invalidClock.status, 1);
|
||
totalTimeoutOptions();
|
||
fieldProfileOptions();
|
||
/* [CASE/START] 启动常规回环的独立子站进程 */
|
||
// CA故意取7,核对业务使用配置地址而非写死默认1;窗口1使每帧应答都依赖主站ACK。
|
||
const child = spawn(executable, ['--port', '0', '--ca', '7', '--window', '1', '--run-ms', '12000',
|
||
'--no-parameter', '--events', '0', '--background-ms', '0', '--counter-type', '15', '--command-extensions'],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '';
|
||
const sockets = [];
|
||
child.stdout.on('data', data => { output += data.toString(); });
|
||
child.stderr.on('data', data => { errors += data.toString(); });
|
||
const exit = once(child, 'exit');
|
||
const deadline = setTimeout(() => { child.kill(); }, 20000);
|
||
try {
|
||
// 从LISTEN日志取得系统分配的端口后才连接;不靠固定启动延时猜测服务是否就绪。
|
||
const port = await new Promise((resolve, reject) => {
|
||
const timer = setTimeout(() => reject(new Error(`No listening port: ${output} ${errors}`)), 2000);
|
||
child.once('error', error => { clearTimeout(timer); reject(error); });
|
||
child.stdout.on('data', () => {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { clearTimeout(timer); resolve(Number(match[1])); }
|
||
});
|
||
});
|
||
async function connect() {
|
||
const socket = net.connect({ host: '127.0.0.1', port });
|
||
sockets.push(socket);
|
||
const master = new Master(socket);
|
||
await once(socket, 'connect');
|
||
await master.control(7, 0x0b);
|
||
return master;
|
||
}
|
||
const master = await connect();
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
// 104的正常/TEST请求与坏图样逐字节检查,后续回复还能检测多余ACT_TERM。
|
||
await commandReply(master, [104, 1, 6, 0x48, 7, 0, 0, 0, 0, 0xaa, 0x55], 7);
|
||
await commandReply(master, [104, 1, 0x86, 0x49, 7, 0, 0, 0, 0, 0xaa, 0x55], 7);
|
||
await commandReply(master, [104, 1, 0x86, 0x4a, 7, 0, 0, 0, 0, 0x55, 0xaa], 7, true);
|
||
/* [CASE/READ_FALLBACK] Type102读取与Type106兜底交错 */
|
||
// 同批106与102按OA/类型匹配;跨业务先后不作保证,k=1仍逐帧确认。
|
||
const unsupportedBatch = [
|
||
[106, 1, 0x86, 0x18, 7, 0, 0, 0, 0, 0x39, 0x30],
|
||
[102, 1, 5, 0x19, 7, 0, 0xe9, 3, 0]
|
||
];
|
||
master.socket.write(Buffer.concat(unsupportedBatch.map(payload => master.frame(payload))));
|
||
const batchReplies = [await master.readASDU(), await master.readASDU()];
|
||
assert.equal(new Set(batchReplies.map(asdu => asdu[3])).size, 2);
|
||
const unsupportedExpected = [...unsupportedBatch[0]]; unsupportedExpected[2] = 0xec;
|
||
assert.deepEqual([...batchReplies.find(asdu => asdu[0] === 106 && asdu[3] === 0x18)], unsupportedExpected);
|
||
timedSignal(batchReplies.find(asdu => asdu[0] === 30 && asdu[3] === 0x19),
|
||
[30, 1, 5, 0x19, 7, 0, 0xe9, 3, 0, 0], true);
|
||
/* [CASE/CLOCK] Type103校时的肯定、否定及广播 */
|
||
// 默认模拟时钟:合法TEST只确认,错误COT及广播实际CA确认都保持请求时标原文。
|
||
// 在原有TEST帧叠加错误星期和GEN,验证真实TCP接收兼容且原文回显,不增加设时动作。
|
||
const clockTest = clockRequest(0x11, 6, true);
|
||
clockTest[11] |= 0x40; // 分钟bit6为RES1/GEN,不能当成保留位拒绝。
|
||
clockTest[13] |= 0x20; // 2026-10-28为周三,故意填写周一;实际日期保持合法。
|
||
for (const [payload, cot, negative] of [
|
||
[clockRequest(0x10), 7, false],
|
||
[clockTest, 7, false],
|
||
[clockRequest(0x12, 8), 45, true],
|
||
[clockRequest(0x13, 6, false, 65535), 7, false]
|
||
]) {
|
||
await master.send(payload);
|
||
const expected = [...payload];
|
||
expected[2] = (payload[2] & 0x80) | cot | (negative ? 0x40 : 0);
|
||
expected[4] = 7; expected[5] = 0;
|
||
assert.deepEqual([...(await master.readASDU())], expected);
|
||
}
|
||
/* [CASE/READ_CLOCK] Type102与校时同批,不约束跨业务先后 */
|
||
// 读与校时共用HIGH,按身份匹配而不规定跨业务先后。
|
||
const clockBatch = clockRequest(0x14);
|
||
const readBatch = [102, 1, 5, 0x15, 7, 0, 0xe9, 3, 0];
|
||
const clockBaseNs = process.hrtime.bigint();
|
||
master.socket.write(Buffer.concat([master.frame(clockBatch), master.frame(readBatch)]));
|
||
const clockReadReplies = [await master.readASDU(), await master.readASDU()];
|
||
timedSignal(clockReadReplies.find(asdu => asdu[0] === 30 && asdu[3] === 0x15),
|
||
[30, 1, 5, 0x15, 7, 0, 0xe9, 3, 0, 0], false);
|
||
const clockConfirmed = [...clockBatch]; clockConfirmed[2] = 7;
|
||
assert.deepEqual([...clockReadReplies.find(asdu => asdu[0] === 103 && asdu[3] === 0x14)], clockConfirmed);
|
||
const currentClockTag = clockTagFactory(clockBatch, clockBaseNs);
|
||
/* [CASE/COMMAND] 选择执行、遥调、撤销与带时标命令 */
|
||
// 每个有S/E的点均拒绝未选择执行;点的类型掩码独立于全局启用。
|
||
await commandReply(master, commandRequest(45, 0x80, 0x6008, 1, false), 7, true);
|
||
await commandReply(master, commandRequest(46, 0x81, 0x6018, 2, false), 7, true);
|
||
await commandReply(master, scaledCommandRequest(0x82, 0x6038, -888, false), 7, true);
|
||
await commandReply(master, commandRequest(45, 0x83, 0x6007, 0, false), 7, true);
|
||
await commandReply(master, commandRequest(46, 0x84, 0x6008, 2, false), 7, true);
|
||
await commandExecute(master, 45, 0x85, 0x6008, 1, 1008);
|
||
signals[7] = 1;
|
||
await commandExecute(master, 46, 0x86, 0x6018, 2, 1108);
|
||
doubleSignals[7] = 2;
|
||
await scaledCommandExecute(master, 0x87, 0x6038, -888, 0x4008);
|
||
measures[7] = -888;
|
||
// 同类型其余点保持SBO;k=1验证确认、返回信息和终止逐帧交接,后续总召必须读到新值。
|
||
await commandExecute(master, 45, 0x71, 0x6001, 1, 1001);
|
||
// 同步后续总召的预期值,验证遥控修改的是示例应用点表而非仅构造一次返回帧。
|
||
signals[0] = 1;
|
||
await commandExecute(master, 46, 0x72, 0x6013, 2, 1103);
|
||
// 站总召和遥信分组均须读回双点1103的新位置,其余双点仍为初值1。
|
||
doubleSignals[2] = 2;
|
||
// 设定值先验证应用限值拒绝,再走完整事务;后面的站总召和QOI=22必须读到新运行值。
|
||
await commandReply(master, scaledCommandRequest(0x79, 0x6031, 10001, true), 7, true);
|
||
await scaledCommandExecute(master, 0x7a, 0x6031, -1234, 0x4001);
|
||
measures[0] = -1234;
|
||
// 撤销故意使用不同状态值:匹配只要求类型/站点/IOA/OA,不比较命令状态。
|
||
await commandReply(master, commandRequest(45, 0x73, 0x6002, 0, true), 7);
|
||
// 未知命令地址须回47(含TEST),不能混成无匹配事务的9,也不能取消0x6002的选择。
|
||
// 1001虽是已注册遥信地址,仍不是命令点;已知点不支持的类型则保持业务否定9。
|
||
await commandReply(master, commandRequest(45, 0x73, 1001, 1, true, 8), 47, true);
|
||
await commandReply(master, commandRequest(45, 0x73, 0xffffff, 1, true, 0x88), 47, true);
|
||
await commandReply(master, commandRequest(46, 0x73, 0x6002, 1, true, 8), 9, true);
|
||
await commandReply(master, commandRequest(45, 0x73, 0x6002, 1, true, 8), 9);
|
||
// 同一已知地址再次撤销已无事务:回否定9,不能误报未知地址47。
|
||
await commandReply(master, commandRequest(45, 0x73, 0x6002, 1, true, 8), 9, true);
|
||
// 选择已撤销,该点配置为SBO,因此后续执行必须被否定。
|
||
await commandReply(master, commandRequest(45, 0x73, 0x6002, 0, false), 7, true);
|
||
// 公共地址错误由模块判定;遥信地址1001不在命令点表内,由库直接返回47。
|
||
await commandReply(master, commandRequest(46, 0x74, 0x6011, 1, true, 6, 65535), 46, true);
|
||
await commandReply(master, commandRequest(45, 0x75, 1001, 1, true), 47, true);
|
||
// TEST走完整SBO协议,但不能输出或消费真实选择;同OA的T0执行须独立否定。
|
||
const commandTest = commandRequest(45, 0x76, 0x6001, 0, true); commandTest[2] |= 0x80;
|
||
await commandReply(master, commandTest, 7);
|
||
await commandReply(master, commandRequest(45, 0x76, 0x6001, 0, false), 7, true);
|
||
const testExecute = commandRequest(45, 0x76, 0x6001, 0, false); testExecute[2] |= 0x80;
|
||
await commandReply(master, testExecute, 7);
|
||
const testTerm = [...testExecute]; testTerm[2] = 0x8a;
|
||
assert.deepEqual([...(await master.readASDU())], testTerm); // 无位置返回,随后GI仍读到真实值1。
|
||
// 库拒绝未支持QU/QL,示例另拒绝未实现的脉冲QU;后续GI点值不得改变。
|
||
for (const qu of [1, 2, 4, 9, 10, 11, 12, 13, 14, 15, 31]) {
|
||
const unsupported = commandRequest(45, 0x90 + qu, 0x6008, 0, false);
|
||
unsupported[9] = qu << 2;
|
||
await commandReply(master, unsupported, 7, true);
|
||
}
|
||
for (const ql of [1, 64, 127]) {
|
||
const unsupported = scaledCommandRequest(0xb0, 0x6038, 123, false);
|
||
unsupported[11] = ql;
|
||
await commandReply(master, unsupported, 7, true);
|
||
}
|
||
// 示例未启用归一化48;带时标命令确认和终止逐字节保留各自原CP56。
|
||
await commandReply(master, scaledCommandRequest(0x77, 0x6031, 123, false, 48), 44, true);
|
||
await commandExecute(master, 58, 0x78, 0x6002, 0, 1002, currentClockTag);
|
||
signals[1] = 0;
|
||
await commandExecute(master, 59, 0x7b, 0x6014, 2, 1104, currentClockTag);
|
||
doubleSignals[3] = 2;
|
||
await scaledCommandExecute(master, 0x7d, 0x6032, -4321, 0x4002, 62, currentClockTag);
|
||
measures[1] = -4321;
|
||
// 新增升降与位串:CA=7、k=1下验证普通/时标完整流程和Type102独立读回。
|
||
const unselectedStep = commandRequest(47, 0xc0, 0x6028, 2, false); unselectedStep[9] &= ~12;
|
||
await commandReply(master, unselectedStep, 7, true);
|
||
await commandReply(master, bitstringCommandRequest(0xc1, 0x6028, 1), 7, true);
|
||
await commandReply(master, bitstringCommandRequest(0xc2, 0x6049, 1), 47, true);
|
||
await stepCommandExecute(master, 0xc3, 0x6021, 1, 1201, -1);
|
||
await stepCommandExecute(master, 0xc4, 0x6028, 2, 1208, 1, 60, currentClockTag);
|
||
await bitstringCommandExecute(master, 0xc5, 0x6041, 0x80000001, 1301);
|
||
await bitstringCommandExecute(master, 0xc6, 0x6041, 0, 1301, 64, currentClockTag);
|
||
// 示例显式启用过期否定:完整回显58并返回COT49;非法日期及TEST+IV同样拒绝。
|
||
// 后续106和计数量流程检查无重复帧,STOP统计证明这些时标错误未执行应用动作。
|
||
const expiredCommand = commandRequest(58, 0x7e, 0x6003, 1, true).concat(currentClockTag(-60000));
|
||
await commandReply(master, expiredCommand, 49, true);
|
||
const malformedTag = currentClockTag(); malformedTag[5] = 0;
|
||
await commandReply(master, commandRequest(58, 0xc7, 0x6003, 1, true).concat(malformedTag), 49, true);
|
||
const invalidTag = currentClockTag(); invalidTag[2] |= 0x80;
|
||
await commandReply(master, commandRequest(58, 0xc8, 0x6003, 1, true, 0x86).concat(invalidTag), 49, true);
|
||
const follower = [106, 1, 6, 0x7f, 7, 0, 0, 0, 0, 0, 0];
|
||
master.socket.write(master.frame(follower));
|
||
const followerReply = [...follower]; followerReply[2] = 0x40 | 44;
|
||
assert.deepEqual([...(await master.readASDU())], followerReply);
|
||
/* [CASE/CI] Type101读取、冻结、复位及分组 */
|
||
await counterRead(master, 0x20);
|
||
await counterReply(master, counterRequest(0x21, 0x45), 7);
|
||
await counterRead(master, 0x22, 5, initialCounters, 1);
|
||
await counterRead(master, 0x23, 1, initialCounters, 1);
|
||
await counterRead(master, 0x24, 2, initialCounters, 1);
|
||
await counterReply(master, counterRequest(0x25, 3), 7, true);
|
||
await counterReply(master, counterRequest(0x26, 4), 7, true);
|
||
await counterReply(master, counterRequest(0x27, 5, 8), 45, true);
|
||
// TEST requests must not freeze or clear real counters.
|
||
await counterReply(master, counterRequest(0x28, 0x85, 6, true), 7);
|
||
await counterRead(master, 0x29, 5, initialCounters, 1, 65535);
|
||
await counterReply(master, counterRequest(0x2a, 0x85), 7);
|
||
await counterRead(master, 0x2b, 5, initialCounters, 2);
|
||
await counterReply(master, counterRequest(0x2c, 0x45), 7);
|
||
const zeroCounters = initialCounters.map(() => 0);
|
||
await counterRead(master, 0x2d, 5, zeroCounters, 3);
|
||
await counterReply(master, counterRequest(0x2e, 0xc5), 7);
|
||
await counterRead(master, 0x2f, 5, zeroCounters, 3);
|
||
/* [CASE/GI] Type100全站、分组、广播、忙及撤销 */
|
||
await totalCall(master, 0x5a, true);
|
||
await totalCall(master, 0x5b, false, 21);
|
||
await totalCall(master, 0x5c, false, 22);
|
||
// 广播请求的确认、数据和终止均按实际本站CA=7核对。
|
||
await totalCall(master, 0x5d, true, 20, 65535);
|
||
await totalCall(master, 0x5e, false, 21, 65535);
|
||
await totalCall(master, 0x5f, false, 22, 65535);
|
||
// 连续提交不同QOI:只执行第一个,后两个否定;结束后由主站重发才执行。
|
||
const burst = [[0x31, 22, 65535], [0x32, 20, 65535], [0x33, 21, 7]];
|
||
master.socket.write(Buffer.concat(burst.map(([oa, qoi, ca]) => master.frame(request(oa, qoi, ca)))));
|
||
await readTotalCall(master, 0x31, 22, burst.slice(1).map(([oa, qoi, ca]) => request(oa, qoi, ca)));
|
||
for (const [oa, qoi] of burst.slice(1)) await totalCall(master, oa, false, qoi);
|
||
// 同一TCP写入携带两条相同激活;分别验证定向/广播的实际CA关联,且仅执行一轮。
|
||
// 无论底层接收如何分批,同键忙否定都只能在原肯定确认后出现,不等待原轮次终止。
|
||
for (const ca of [7, 65535]) {
|
||
const repeated = request(0x34, 20, ca);
|
||
master.socket.write(Buffer.concat([master.frame(repeated), master.frame(repeated)]));
|
||
await readTotalCall(master, 0x34, 20, [repeated]);
|
||
}
|
||
for (const [index, value, cot] of [[4, 8, 46], [9, 37, 7], [9, 36, 7], [0, 200, 44]]) {
|
||
const invalidRequest = request(0x55);
|
||
invalidRequest[index] = value;
|
||
if (index === 9) { invalidRequest[4] = invalidRequest[5] = 0xff; }
|
||
await master.send(invalidRequest);
|
||
const expected = [...invalidRequest];
|
||
expected[2] = 0xc0 | cot;
|
||
if (index === 9) { expected[4] = 7; expected[5] = 0; }
|
||
assert.deepEqual([...(await master.readASDU())], expected);
|
||
}
|
||
// 同一接收批次的激活/撤销在驱动业务前按FIFO处理;随后重复撤销应否定确认。
|
||
const activation = request(0x4a, 21, 65535);
|
||
const deactivation = request(0x4a, 21); deactivation[2] = 0x88;
|
||
master.socket.write(Buffer.concat([master.frame(activation), master.frame(deactivation)]));
|
||
const deactCon = [...deactivation]; deactCon[2] = 0x89;
|
||
assert.deepEqual([...(await master.readASDU())], deactCon);
|
||
deactivation[4] = deactivation[5] = 0xff;
|
||
await master.send(deactivation);
|
||
deactCon[2] = 0xc9;
|
||
assert.deepEqual([...(await master.readASDU())], deactCon);
|
||
await master.control(0x13, 0x23);
|
||
await master.control(7, 0x0b);
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
/* [CASE/INTERROGATION] 两类召唤交错推进与重连 */
|
||
// k=1: both instances must make progress, preserving their own response order.
|
||
master.socket.write(Buffer.concat([master.frame(request(0x6b)), master.frame(counterRequest(0x60))]));
|
||
const generalFrames = [], counterFrames = [];
|
||
for (let index = 0; index < 12; index++) {
|
||
const asdu = await master.readASDU();
|
||
(asdu[0] === 101 || asdu[0] === 15 ? counterFrames : generalFrames).push(asdu);
|
||
}
|
||
assert.equal(generalFrames.length, 8);
|
||
assert.equal(counterFrames.length, 4);
|
||
await readTotalCall({ readASDU: async () => generalFrames.shift() }, 0x6b);
|
||
await readCounters({ readASDU: async () => counterFrames.shift() }, 0x60, 5, zeroCounters, 3);
|
||
await master.close();
|
||
const next = await connect();
|
||
assert.deepEqual([...(await next.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
await totalCall(next, 0x7c);
|
||
await next.close();
|
||
const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`);
|
||
// 线上的逐字节断言之外,再用退出统计核对动作次数,识别多执行或漏执行。
|
||
// Two Type102 replies now belong to Read, outside the original GI/fallback counters.
|
||
assert.match(output, /STOP submitted=99 gi_submitted=13 /);
|
||
assert.match(output, /deactivated=1 timeouts=0/);
|
||
assert.match(output, /negative_submitted=\d+ dropped_requests=0/);
|
||
assert.match(output, /^TIMEOUTS GI_TOTAL_MS=120000 CI_TOTAL_MS=120000$/m);
|
||
assert.match(output, new RegExp(`counter_submitted=${counterSubmitted} counter_completed=${counterCompleted}`));
|
||
assert.match(output, /clock_executed=3 clock_synchronized=3 clock_submitted=5/);
|
||
// 十三次真实执行加一次TEST协议完成;TEST不增加真实选择/执行或返回信息计数。
|
||
assert.match(output, /command_selected=12 command_executed=13 command_completed=14 command_submitted=\d+ command_returns=13 command_time_expired=1 command_time_rejected=2/);
|
||
assert.equal(errors, '');
|
||
console.log('Slave example loopback: passed (real TCP, SBO defaults and explicit bitstring extension, Type45/46/47/49/51/58/59/60/62/64 execute/return/termination, CP56 single/double feedback and reads, step and bitstring reads, scaled limits, fresh timestamps and COT49 expiry/date/TEST-IV rejection, command cancel/TEST/address/unsupported types, changed single/double/scaled GI values, batched 106+102 and 103+102, simulated clock, counters, k=1, STOP/START, reconnect, cleanup)');
|
||
} finally {
|
||
// 无论断言成功与否,只回收本用例创建的socket和子进程,不留占端口的后台示例。
|
||
clearTimeout(deadline);
|
||
for (const socket of sockets) socket.destroy();
|
||
if (child.exitCode === null) child.kill();
|
||
}
|
||
}
|
||
|
||
/* ============================================================================
|
||
* [LOOPBACK/CLOCK_READ] 一次取时形成固定响应,模拟设时与真实系统只读分别验收
|
||
* ============================================================================ */
|
||
async function clockReadLoopback() {
|
||
for (const mode of ['simulated', 'system']) {
|
||
const child = spawn(executable, ['--port', '0', '--ca', '7', '--window', '1', '--run-ms', '3500',
|
||
'--no-parameter', '--events', '0', '--background-ms', '0', '--clock', mode],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '', socket;
|
||
child.stdout.on('data', data => { output += data; });
|
||
child.stderr.on('data', data => { errors += data; });
|
||
const exit = once(child, 'exit'), deadline = setTimeout(() => child.kill(), 7500);
|
||
try {
|
||
let port;
|
||
for (let i = 0; i < 150; ++i) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; }
|
||
await delay(10);
|
||
}
|
||
assert(port, `${output}\n${errors}`);
|
||
socket = net.connect({ host: '127.0.0.1', port });
|
||
const master = new Master(socket);
|
||
await once(socket, 'connect'); await master.control(7, 0x0b);
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
const read = async (oa, test = false, ca = 7, invalid = false) => {
|
||
const request = clockReadRequest(oa, test, ca);
|
||
await master.send(request);
|
||
return checkClockRead(await master.readASDU(), request, invalid);
|
||
};
|
||
if (mode === 'simulated') {
|
||
// 没有校时基准时,普通/TEST读取均报告合法占位及IV,不偷偷初始化为宿主时间。
|
||
const placeholder = Date.UTC(1999, 11, 31, 16);
|
||
assert.equal(await read(0x30, false, 7, true), placeholder);
|
||
assert.equal(await read(0x31, true, 7, true), placeholder);
|
||
const firstSet = clockRequest(0x32);
|
||
await commandReply(master, firstSet, 7);
|
||
await delay(60);
|
||
const firstRead = await read(0x33);
|
||
const expectedBase = Date.UTC(2026, 9, 28, 4, 34, 12, 345);
|
||
assert(firstRead >= expectedBase + 40 && firstRead < expectedBase + 2000);
|
||
|
||
// 同一TCP批次READ->SET->READ:首个快照必须保留旧日期,后一个使用新日期。
|
||
const before = clockReadRequest(0x34), laterSet = clockRequest(0x35), after = clockReadRequest(0x36);
|
||
laterSet[13] = 29;
|
||
master.socket.write(Buffer.concat([before, laterSet, after].map(p => master.frame(p))));
|
||
const beforeTime = checkClockRead(await master.readASDU(), before);
|
||
const setResponse = [...laterSet]; setResponse[2] = 7;
|
||
assert.deepEqual([...(await master.readASDU())], setResponse);
|
||
const afterTime = checkClockRead(await master.readASDU(), after);
|
||
assert(beforeTime >= firstRead && beforeTime < expectedBase + 3000);
|
||
assert(afterTime >= expectedBase + 86400000 && afterTime < expectedBase + 86403000);
|
||
|
||
// TEST设时只回显;后续TEST读时仍读取29日,并且不增加真实设时次数。
|
||
const testSet = clockRequest(0x37, 6, true); testSet[13] = 30;
|
||
await commandReply(master, testSet, 7);
|
||
const testTime = await read(0x38, true);
|
||
assert(testTime >= afterTime && testTime < expectedBase + 86403000);
|
||
const broadcastTime = await read(0x39, false, 65535);
|
||
assert(broadcastTime >= afterTime && broadcastTime < expectedBase + 86403000);
|
||
|
||
const nonzero = clockReadRequest(0x3a); nonzero[15] = 1;
|
||
await commandReply(master, nonzero, 5, true);
|
||
const badIoa = clockReadRequest(0x3b); badIoa[6] = 1;
|
||
await commandReply(master, badIoa, 47, true);
|
||
await commandReply(master, clockReadRequest(0x3c, false, 8), 46, true);
|
||
} else {
|
||
// system模式只发读请求,检查真实时钟后端及UTC+8编码,不设置Windows系统时间。
|
||
for (const [oa, test, ca] of [[0x40, false, 7], [0x41, true, 7], [0x42, false, 65535]]) {
|
||
const before = Date.now(), sampled = await read(oa, test, ca), after = Date.now();
|
||
assert(sampled >= before - 1000 && sampled <= after + 1000);
|
||
}
|
||
}
|
||
await master.close();
|
||
const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`); assert.equal(errors, '');
|
||
const reads = mode === 'simulated' ? 7 : 3, sets = mode === 'simulated' ? 2 : 0;
|
||
assert.match(output, new RegExp(`CLOCK_READ executed=${reads} succeeded=${reads}`));
|
||
assert.match(output, new RegExp(`clock_executed=${sets} clock_synchronized=${sets} `));
|
||
} finally {
|
||
clearTimeout(deadline);
|
||
if (socket) socket.destroy();
|
||
if (child.exitCode === null) child.kill();
|
||
}
|
||
}
|
||
console.log('Clock read loopback: passed (103/COT5 zero placeholders, local CP56 weekday and IV, simulated elapsed time, ordered READ/SET, TEST isolation, broadcast, invalid request rejection, Windows read-only clock)');
|
||
}
|
||
|
||
/* ============================================================================
|
||
* [LOOPBACK/FLOAT_COUNTERS] 206读取当前值,207/37读取冻结值及原冻结时刻
|
||
* ============================================================================ */
|
||
async function floatCountersLoopback() {
|
||
for (const value of ['0', '13', '36', '208', 'invalid']) {
|
||
const result = spawnSync(executable, ['--counter-type', value], { windowsHide: true, encoding: 'utf8' });
|
||
assert.ifError(result.error);
|
||
assert.equal(result.status, 1, `--counter-type ${value} must be rejected`);
|
||
}
|
||
// 每种类型独立进程、独立统计。206故意不传选项,线上的TI同时验证新默认值。
|
||
for (const type of [206, 207, 37]) {
|
||
const args = ['--port', '0', '--ca', '7', '--window', '1', '--run-ms', '4500',
|
||
'--no-parameter', '--events', '0', '--background-ms', '0'];
|
||
if (type !== 206) args.push('--counter-type', String(type));
|
||
const child = spawn(executable, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '', socket;
|
||
child.stdout.on('data', data => { output += data; });
|
||
child.stderr.on('data', data => { errors += data; });
|
||
const exit = once(child, 'exit'), deadline = setTimeout(() => child.kill(), 8500);
|
||
let submitted = 0, completed = 0, oa = 0x30;
|
||
const floating = type !== 37, timed = type !== 206;
|
||
try {
|
||
let port;
|
||
for (let i = 0; i < 150; ++i) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; }
|
||
await delay(10);
|
||
}
|
||
assert(port, `${output}\n${errors}`);
|
||
socket = net.connect({ host: '127.0.0.1', port });
|
||
const master = new Master(socket);
|
||
await once(socket, 'connect'); await master.control(7, 0x0b);
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
const reply = async (qcc, test = false, negative = false) => {
|
||
await commandReply(master, counterRequest(oa++, qcc, 6, test), 7, negative);
|
||
submitted++;
|
||
if (!negative) completed++;
|
||
};
|
||
const read = async (values, sequence = 0, expectedTime = null, test = false, qcc = 5) => {
|
||
const originator = oa++, group = qcc & 0x3f;
|
||
const first = group === 2 ? 4 : 0, end = group === 1 ? 4 : 8;
|
||
const times = [];
|
||
await master.send(counterRequest(originator, qcc, 6, test));
|
||
assert.deepEqual([...(await master.readASDU())], counterRequest(originator, qcc, 7, test));
|
||
for (let begin = first; begin < end; begin += 4) {
|
||
const asdu = await master.readASDU(), payloadSize = timed ? 12 : 5;
|
||
assert.deepEqual([...asdu.subarray(0, 6)],
|
||
[type, floating ? 0x84 : 4, (group === 5 ? 37 : 37 + group) | (test ? 0x80 : 0), originator, 7, 0]);
|
||
assert.equal(asdu.length, floating ? 9 + 4 * payloadSize : 6 + 4 * (3 + payloadSize));
|
||
if (floating) assert.equal(asdu.readUIntLE(6, 3), 0x6401 + begin);
|
||
for (let point = 0; point < 4; ++point) {
|
||
const index = begin + point, offset = floating ? 9 + point * payloadSize : 6 + point * 15;
|
||
const valueOffset = floating ? offset : offset + 3;
|
||
if (floating) {
|
||
assert.equal(asdu.readFloatLE(valueOffset), Math.fround(values[index] / 1000));
|
||
assert.equal(asdu[valueOffset + 4], 0); // QDS有效,不把BCR序号混入品质。
|
||
} else {
|
||
assert.equal(asdu.readUIntLE(offset, 3), 0x6401 + index);
|
||
assert.equal(asdu.readInt32LE(valueOffset), values[index]);
|
||
assert.equal(asdu[valueOffset + 4], sequence);
|
||
}
|
||
if (timed) {
|
||
const tag = Buffer.from(asdu.subarray(valueOffset + 5, valueOffset + 12));
|
||
if (expectedTime) assert.deepEqual(tag, expectedTime[index]);
|
||
times[index] = tag;
|
||
}
|
||
}
|
||
}
|
||
assert.deepEqual([...(await master.readASDU())], counterRequest(originator, qcc, 10, test));
|
||
submitted += 2 + (end - first) / 4;
|
||
completed++;
|
||
return times;
|
||
};
|
||
const cp56Epoch = tag => Date.UTC(2000 + tag[6], (tag[5] & 15) - 1, tag[4] & 31,
|
||
(tag[3] & 31) - 8, tag[2] & 63, 0, tag[0] | (tag[1] << 8));
|
||
|
||
const initialTime = await read(initialCounters);
|
||
if (timed) for (const tag of initialTime) assert.equal(tag[2] & 0x80, 0x80);
|
||
if (floating) {
|
||
// 不支持的分组连同FRZ动作也必须否定,不能先清当前值再拒绝。
|
||
for (const group of [1, 2]) {
|
||
for (const freeze of [0, 1, 2, 3]) await reply((freeze << 6) | group, false, true);
|
||
}
|
||
await read(initialCounters, 0, timed ? initialTime : null);
|
||
}
|
||
const calibration = clockRequest(oa++), calibrationStart = process.hrtime.bigint();
|
||
await commandReply(master, calibration, 7);
|
||
const calibrationEnd = process.hrtime.bigint(), freezeStart = process.hrtime.bigint();
|
||
await reply(0x45); // FRZ=1:冻结但不复位。
|
||
const freezeEnd = process.hrtime.bigint();
|
||
await delay(200);
|
||
const frozenTime = await read(initialCounters, 1);
|
||
if (timed) {
|
||
const base = cp56Epoch(calibration.slice(-7));
|
||
const earliest = base + Number((freezeStart - calibrationEnd) / 1000000n) - 50;
|
||
const latest = base + Number((freezeEnd - calibrationStart) / 1000000n) + 50;
|
||
for (const tag of frozenTime) {
|
||
assert.equal(tag[2] & 0x80, 0);
|
||
assert.equal(tag[3] & 0x80, 0);
|
||
assert(cp56Epoch(tag) >= earliest && cp56Epoch(tag) <= latest, 'CP56 must describe freeze, not later read');
|
||
assert.deepEqual(tag, frozenTime[0]);
|
||
}
|
||
// 将模拟时钟推进一天,随后读取仍必须携带原冻结时间。
|
||
const laterClock = clockRequest(oa++); laterClock[13] = 29;
|
||
await commandReply(master, laterClock, 7);
|
||
await delay(150);
|
||
await read(initialCounters, 1, frozenTime, true);
|
||
}
|
||
if (type === 37) {
|
||
await read(initialCounters, 1, frozenTime, false, 1);
|
||
await read(initialCounters, 1, frozenTime, false, 2);
|
||
}
|
||
// TEST的FRZ=2/3都只能确认;值和冻结时间保持不变。
|
||
await reply(0x85, true); await reply(0xc5, true);
|
||
await read(initialCounters, 1, timed ? frozenTime : null, true);
|
||
await reply(0xc5); // FRZ=3:仅复位当前示值,冻结副本不能变。
|
||
const zero = Array(8).fill(0);
|
||
await read(type === 206 ? zero : initialCounters, 1, timed ? frozenTime : null);
|
||
await reply(0x85); // FRZ=2:冻结已复位的当前零值,207/37随之变为零。
|
||
const resetTime = await read(zero, 2);
|
||
if (timed) for (const tag of resetTime) {
|
||
assert.equal(tag[2] & 0x80, 0);
|
||
assert.equal(tag[4] & 31, 29);
|
||
assert.notDeepEqual(tag, frozenTime[0]);
|
||
}
|
||
await master.close();
|
||
const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`);
|
||
assert.equal(errors, '');
|
||
assert.match(output, new RegExp(`counter_submitted=${submitted} counter_completed=${completed}(?: |$)`));
|
||
assert.match(output, /dropped_requests=0/);
|
||
} finally {
|
||
clearTimeout(deadline);
|
||
if (socket) socket.destroy();
|
||
if (child.exitCode === null) child.kill();
|
||
}
|
||
}
|
||
console.log('Float counters loopback: passed (default 206 and optional 207/37, real TCP k=1, SQ1 batches, exact float32 values, COT7/37/10, group rejection before action, FRZ1/2/3, TEST isolation, current versus frozen values, original freeze timestamps)');
|
||
}
|
||
|
||
/* ============================================================================
|
||
* [LOOPBACK/SPONTANEOUS] 持续突发回环:SOE时间、业务交错、读回及未ACK重发
|
||
* ============================================================================ */
|
||
async function spontaneousLoopback() {
|
||
// 使用新进程重置点值;50ms持续采样、k=1和离线停顿制造积压,同时给严格低级遥测留出消化窗口。
|
||
const child = spawn(executable,
|
||
['--port', '0', '--ca', '7', '--window', '1', '--events', '50', '--run-ms', '6000',
|
||
'--simulation', 'stress', '--no-parameter', '--background-ms', '0'],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '';
|
||
const sockets = [];
|
||
child.stdout.on('data', data => { output += data.toString(); });
|
||
child.stderr.on('data', data => { errors += data.toString(); });
|
||
const exit = once(child, 'exit');
|
||
const deadline = setTimeout(() => child.kill(), 10000);
|
||
try {
|
||
const port = await new Promise((resolve, reject) => {
|
||
const timer = setTimeout(() => reject(new Error(`No event server: ${output} ${errors}`)), 2000);
|
||
child.once('error', error => { clearTimeout(timer); reject(error); });
|
||
child.stdout.on('data', () => {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { clearTimeout(timer); resolve(Number(match[1])); }
|
||
});
|
||
});
|
||
async function connectEvents() {
|
||
const socket = net.connect({ host: '127.0.0.1', port });
|
||
socket.setNoDelay(true); // k=1逐帧ACK及时发出,重连总召不额外堆积高频采样缓存。
|
||
sockets.push(socket);
|
||
const master = new Master(socket);
|
||
master.asynchronous = true; // Events can predate the latest master request.
|
||
await once(socket, 'connect');
|
||
await master.control(7, 0x0b);
|
||
return master;
|
||
}
|
||
const master = await connectEvents();
|
||
// 此处仅校验突发帧的共同不变式;时间有效性和业务交错由下面各阶段单独判断。
|
||
function event(asdu) {
|
||
assert.equal(asdu[2], 3);
|
||
assert.equal(asdu[1], 1);
|
||
assert.equal(asdu.readUInt16LE(4), 7);
|
||
const ioa = asdu.readUIntLE(6, 3);
|
||
assert([11, 30].includes(asdu[0]), 'Spontaneous single signals must only use Type30');
|
||
assert(ioa >= (asdu[0] === 11 ? 0x4001 : 1001) && ioa <= (asdu[0] === 11 ? 0x4008 : 1008));
|
||
}
|
||
// 每次START先初始化;真实全总召的TERM前不允许历史NORMAL插队。
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
await startupInterrogation(master, 0x20);
|
||
/* [CASE/EVENT_TIME] 持续突发:校时前IV及校时后有效SOE */
|
||
let before;
|
||
for (let index = 0; index < 10; index++) {
|
||
const asdu = await master.readASDU(); event(asdu);
|
||
if (asdu[0] === 30) { before = asdu; break; }
|
||
}
|
||
assert(before, 'Missing unsynchronized SOE');
|
||
assert.deepEqual([...before.subarray(10)], [0, 0, 0x80, 0, 0xc1, 1, 0]);
|
||
const calibration = clockRequest(0x21);
|
||
await master.send(calibration);
|
||
let confirmed = false, after;
|
||
// 校时为7级,遥信/SOE为4级、变化遥测为8级;必须找到校时后新生成的有效SOE才验证时间。
|
||
for (let index = 0; index < 20; index++) {
|
||
const asdu = await master.readASDU();
|
||
if (asdu[0] === 103) {
|
||
const expected = [...calibration]; expected[2] = 7;
|
||
assert.deepEqual([...asdu], expected); confirmed = true;
|
||
} else {
|
||
event(asdu);
|
||
// Confirming the clock does not rewrite cached timestamps; only a
|
||
// newly calibrated sample proves the application updated its time base.
|
||
if (confirmed && asdu[0] === 30 && (asdu[12] & 0x80) === 0) { after = asdu; break; }
|
||
}
|
||
}
|
||
assert(confirmed && after, 'Clock confirmation and calibrated SOE must both arrive');
|
||
assert.equal(after[12] & 0x80, 0);
|
||
assert.equal(after[13] & 0x80, 0);
|
||
const milliseconds = after.readUInt16LE(10);
|
||
const utc = Date.UTC(2000 + after[16], (after[15] & 15) - 1, after[14] & 31,
|
||
(after[13] & 31) - 8, after[12] & 63, Math.floor(milliseconds / 1000), milliseconds % 1000);
|
||
const baseUtc = Date.UTC(2026, 9, 28, 4, 34, 12, 345);
|
||
// 给真实调度留出时间窗口;精确期限边界在可控单调时钟的C测试中验证。
|
||
assert(utc >= baseUtc - 1000 && utc <= baseUtc + 5000, 'SOE must use calibrated event time');
|
||
/* [CASE/EVENT_GI] 持续突发:总召当前值与NORMAL积压互不门控 */
|
||
const generalRequest = request(0x22);
|
||
await master.send(generalRequest);
|
||
let began = false, terminated = false, dataFrames = 0;
|
||
for (let index = 0; index < 50; index++) {
|
||
const asdu = await master.readASDU();
|
||
const cause = asdu[2] & 63;
|
||
if (cause === 3) { event(asdu); continue; }
|
||
if (asdu[0] === 100) {
|
||
const expected = [...generalRequest]; expected[2] = cause === 10 ? 0x8a : 0x87;
|
||
assert.deepEqual([...asdu], expected);
|
||
if (cause === 10) { assert(began); terminated = true; break; }
|
||
assert(!began); began = true; continue;
|
||
}
|
||
assert(began && dataFrames < 6);
|
||
const type = [1, 1, 3, 3, 11, 11][dataFrames], width = type === 11 ? 3 : 1;
|
||
const count = asdu[1] & 0x7f, base = type === 1 ? 1001 : type === 3 ? 1101 : 0x4001;
|
||
assert.deepEqual([...asdu.subarray(0, 6)], [type, 0x84, 0x94, 0x22, 7, 0]);
|
||
assert.equal(asdu.length, 9 + count * width);
|
||
const firstIoa = asdu.readUIntLE(6, 3);
|
||
assert.equal(firstIoa, base + (dataFrames % 2) * 4);
|
||
// SQ=1只出现首IOA,后续地址按点序推导;每点载荷不再包含地址。
|
||
for (let point = 0; point < count; point++) {
|
||
const offset = 9 + point * width, ioa = firstIoa + point;
|
||
const value = type === 11 ? asdu.readInt16LE(offset) : asdu[offset];
|
||
// GI is a current-value read, independent of the NORMAL event backlog.
|
||
// Its value is not required to equal the most recently received event.
|
||
if (asdu[0] === 11) {
|
||
assert(ioa >= 0x4001 && ioa <= 0x4008 && value >= -10000 && value <= 10000);
|
||
assert.equal(asdu[offset + 2], 0);
|
||
} else if (asdu[0] === 3) {
|
||
assert(ioa >= 1101 && ioa <= 1108); assert.equal(value, 1);
|
||
} else {
|
||
assert.equal(asdu[0], 1); assert(ioa >= 1001 && ioa <= 1008 && (value === 0 || value === 1));
|
||
}
|
||
}
|
||
++dataFrames;
|
||
}
|
||
assert(terminated && dataFrames === 6);
|
||
/* [CASE/EVENT_COMMAND] 持续突发:遥控应答持续推进 */
|
||
// Keep consuming and checking spontaneous data while the command advances.
|
||
// Bounded reads fail if later events keep overtaking a queued response.
|
||
const responses = {
|
||
send: master.send.bind(master),
|
||
async readASDU() {
|
||
for (let index = 0; index < 128; ++index) {
|
||
const asdu = await master.readASDU();
|
||
if ((asdu[2] & 63) === 3) { event(asdu); continue; }
|
||
return asdu;
|
||
}
|
||
throw new Error('HIGH response starved by continuous spontaneous data');
|
||
}
|
||
};
|
||
await commandExecute(responses, 46, 0x23, 0x6018, 2, 1108);
|
||
/* [CASE/EVENT_READ] 持续突发:遥控后Type102读回及未知IOA */
|
||
// Read the same double point after command execution, during continuous events.
|
||
await responses.send([102, 1, 5, 0x24, 7, 0, 0x54, 4, 0]);
|
||
timedSignal(await responses.readASDU(), [31, 1, 5, 0x24, 7, 0, 0x54, 4, 0, 2], false);
|
||
await responses.send([102, 1, 5, 0x25, 7, 0, 0xff, 0xff, 0]);
|
||
assert.deepEqual([...(await responses.readASDU())], [102, 1, 0x6f, 0x25, 7, 0, 0xff, 0xff, 0]);
|
||
/* [CASE/EVENT_REPLAY] 持续突发:未ACK原文重连补发 */
|
||
// 不调用readASDU,否则其自动ACK会释放待重发记录;next仅取帧,随后主动断线。
|
||
// 不ACK的NORMAL保留原文。同等级仍按原入队顺序补发;更高等级的新事件允许先于它发送。
|
||
let retained;
|
||
for (let index = 0; index < 10; index++) {
|
||
const frame = await master.next();
|
||
if (frame[2] === 1) continue;
|
||
assert.equal(frame[2] & 1, 0);
|
||
assert.equal(frame.readUInt16LE(2) >> 1, master.nr++);
|
||
retained = Buffer.from(frame.subarray(6)); event(retained); break;
|
||
}
|
||
assert(retained);
|
||
await master.close();
|
||
// 离线继续采样:若保留的是8级遥测,新增4级遥信/SOE可以先补发,但不能跳过旧的同级原文。
|
||
await delay(250);
|
||
const reconnected = await connectEvents();
|
||
assert.deepEqual([...(await reconnected.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
await startupInterrogation(reconnected, 0x26, { doubleValues: [1, 1, 1, 1, 1, 1, 1, 2] });
|
||
const retainedPriority = retained[0] === 11 ? 8 : 4;
|
||
const replayDeadline = Date.now() + 2000;
|
||
let replayed = false;
|
||
for (let index = 0; index < 128; ++index) {
|
||
const asdu = await reconnected.readASDU(); event(asdu);
|
||
assert(Date.now() <= replayDeadline, 'Unacknowledged replay exceeded the two-second test window');
|
||
const priority = asdu[0] === 11 ? 8 : 4;
|
||
if (priority < retainedPriority) continue;
|
||
// 第一条同级或更低级帧必须就是未ACK原文;不能靠继续搜索掩盖丢帧、同级乱序或重新组帧。
|
||
assert.deepEqual(asdu, retained, 'First replay at the retained priority must preserve the unacknowledged ASDU');
|
||
replayed = true;
|
||
break;
|
||
}
|
||
assert(replayed, 'Unacknowledged event did not replay within the bounded higher-priority drain');
|
||
await reconnected.close();
|
||
const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`);
|
||
assert.match(output, /EVENTS event_published=[1-9]\d* event_asdus=[1-9]\d*/);
|
||
assert.match(output, /event_time_invalid=[1-9]\d*/);
|
||
assert.match(output, /event_accounting_errors=0 event_queue_dropped=0 event_queue_invalid=0/);
|
||
assert.equal(errors, '');
|
||
console.log('Slave spontaneous loopback: passed (50 ms COT3, pre-sync IV, clock/GI/command progress, current-value read and unknown IOA, exact unacknowledged replay with higher-priority offline events first)');
|
||
} finally {
|
||
clearTimeout(deadline);
|
||
for (const socket of sockets) socket.destroy();
|
||
if (child.exitCode === null) child.kill();
|
||
}
|
||
}
|
||
|
||
/* [LOOPBACK/STARTUP_REPLAY] 每个激活周期均先Type70,再真实全总召TERM,最后才允许补发。
|
||
* 独立进程在离线时积压NORMAL;k=1让每一帧进度受主站控制,IDLE另用满足reserve的窗口。
|
||
* 保留原APDU而不ACK后断线,逐字节核对缓存;ACK后的下一记录再重连,证明旧头确已释放。 */
|
||
async function startupReplayLoopback() {
|
||
const child = spawn(executable,
|
||
['--port', '0', '--ca', '7', '--window', '1', '--events', '100', '--run-ms', '8000',
|
||
'--simulation', 'stress', '--no-parameter', '--cyclic-ms', '0', '--background-ms', '0'],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '';
|
||
const sockets = [];
|
||
child.stdout.on('data', bytes => { output += bytes; });
|
||
child.stderr.on('data', bytes => { errors += bytes; });
|
||
const exit = once(child, 'exit'), deadline = setTimeout(() => child.kill(), 14000);
|
||
const initialization = [70, 1, 4, 0, 7, 0, 0, 0, 0, 0];
|
||
const acknowledge = master => {
|
||
const ack = Buffer.from([0x68, 4, 1, 0, 0, 0]); ack.writeUInt16LE(master.nr << 1, 4);
|
||
master.socket.write(ack);
|
||
};
|
||
const quiet = async master => {
|
||
await delay(100);
|
||
assert.ifError(master.error);
|
||
// 此时没有未ACK的I帧,NORMAL若泄漏就会完整到达;S确认可穿插。
|
||
assert(master.frames.every(frame => frame[2] === 1), 'I frame escaped before startup interrogation completed');
|
||
};
|
||
const retain = async master => {
|
||
for (let index = 0; index < 8; ++index) {
|
||
const frame = await master.next(); if (frame[2] === 1) continue;
|
||
assert.equal(frame[2] & 1, 0); assert.equal(frame.readUInt16LE(2) >> 1, master.nr++);
|
||
assert((frame.readUInt16LE(4) >> 1) <= master.ns);
|
||
const asdu = Buffer.from(frame.subarray(6));
|
||
assert.equal(asdu[2], 3); assert.equal(asdu.readUInt16LE(4), 7);
|
||
assert([11, 30].includes(asdu[0]), 'Replay must not reintroduce untimed single signals');
|
||
return asdu; // 不ACK,保留发送层的NORMAL头记录及线上原文。
|
||
}
|
||
throw new Error('Missing retained NORMAL event');
|
||
};
|
||
try {
|
||
let port;
|
||
for (let index = 0; index < 150; ++index) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; }
|
||
await delay(10);
|
||
}
|
||
assert(port, `${output}\n${errors}`);
|
||
const connect = async () => {
|
||
const socket = net.connect({ host: '127.0.0.1', port }); sockets.push(socket); socket.setNoDelay(true);
|
||
const master = new Master(socket); master.asynchronous = true;
|
||
await once(socket, 'connect'); await master.control(7, 0x0b);
|
||
assert.deepEqual([...(await master.readASDU())], initialization);
|
||
return master;
|
||
};
|
||
await delay(350); // 先离线采样,首个START已确实有历史NORMAL可发。
|
||
let master = await connect();
|
||
await quiet(master);
|
||
// 两种失败前置条件都完成正常协议流程,但不得解除门禁;每轮超过HIGH连续份额4帧。
|
||
await startupInterrogation(master, 0x61, { test: true }); await quiet(master);
|
||
await startupInterrogation(master, 0x62, { qoi: 21 }); await quiet(master);
|
||
await startupInterrogation(master, 0x63);
|
||
await retain(master);
|
||
|
||
// 已开放过的连接STOP/START必须重新闭锁。k=1持有一帧,STOP前不会另有已编号I帧。
|
||
// STOP_CON须等已预留I帧获ACK;同socket先写STOP_ACT再ACK,不能先await确认而死等。
|
||
// 这个ACK只释放旧缓存;新的START仍须先70及新的真实全总召。
|
||
const stopped = master.control(0x13, 0x23); acknowledge(master); await stopped; await quiet(master);
|
||
await master.control(7, 0x0b);
|
||
assert.deepEqual([...(await master.readASDU())], initialization); await quiet(master);
|
||
await startupInterrogation(master, 0x64);
|
||
const retained = await retain(master); await master.close();
|
||
|
||
await delay(150); // 断线继续采样,新增记录不得越过未确认的头记录。
|
||
master = await connect(); await quiet(master);
|
||
await startupInterrogation(master, 0x65);
|
||
assert.deepEqual(await master.readASDU(), retained); // 这次ACK释放旧头。
|
||
const nextRetained = await retain(master);
|
||
assert(!nextRetained.equals(retained), 'Fixture must expose two distinct consecutive cached events');
|
||
await master.close(); await delay(80);
|
||
master = await connect();
|
||
await startupInterrogation(master, 0x66);
|
||
assert.deepEqual(await master.readASDU(), nextRetained, 'ACKed cache head replayed or next unacknowledged event was lost');
|
||
await master.close();
|
||
const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`); assert.equal(errors, '');
|
||
assert.match(output, /event_accounting_errors=0 event_queue_dropped=0 event_queue_invalid=0/);
|
||
console.log('Startup replay loopback: passed (Type70 first, TEST/group exclusion, >4 HIGH frames before TERM, NORMAL gating, STOP/START rearm, unacknowledged replay, ACK release)');
|
||
} catch (error) {
|
||
console.error(`Startup replay diagnostics:\n${output}\n${errors}`); throw error;
|
||
} finally {
|
||
clearTimeout(deadline); for (const socket of sockets) socket.destroy();
|
||
if (child.exitCode === null) child.kill();
|
||
}
|
||
}
|
||
|
||
// 扫描reserve=2不允许k=1;单独用k=4让IDLE真实到期,且不由NORMAL积压掩盖IDLE泄漏。
|
||
async function startupIdleLoopback() {
|
||
const child = spawn(executable,
|
||
['--port', '0', '--ca', '7', '--window', '4', '--events', '0', '--run-ms', '2500',
|
||
'--no-parameter', '--cyclic-ms', '100', '--background-ms', '200'],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '', socket;
|
||
child.stdout.on('data', bytes => { output += bytes; }); child.stderr.on('data', bytes => { errors += bytes; });
|
||
const exit = once(child, 'exit'), deadline = setTimeout(() => child.kill(), 6000);
|
||
try {
|
||
let port;
|
||
for (let index = 0; index < 150; ++index) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; } await delay(10);
|
||
}
|
||
assert(port, `${output}\n${errors}`);
|
||
socket = net.connect({ host: '127.0.0.1', port }); socket.setNoDelay(true);
|
||
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, 0]);
|
||
await delay(350); assert.ifError(master.error);
|
||
assert(master.frames.every(frame => frame[2] === 1), 'Due IDLE snapshot escaped before startup GI');
|
||
await startupInterrogation(master, 0x67, { test: true });
|
||
await startupInterrogation(master, 0x68, { qoi: 21 });
|
||
await startupInterrogation(master, 0x69);
|
||
const seen = new Set();
|
||
for (let index = 0; index < 12 && seen.size < 2; ++index) {
|
||
const asdu = await master.readASDU(), cause = asdu[2];
|
||
assert.equal(asdu.readUInt16LE(4), 7); assert.equal(asdu[1], 8); assert.equal(asdu[3], 0);
|
||
assert((cause === 1 || cause === 2) && asdu[0] === 11);
|
||
seen.add(`${cause}/${asdu[0]}`);
|
||
}
|
||
assert.deepEqual([...seen].sort(), ['1/11', '2/11']);
|
||
await master.close(); const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`); assert.equal(errors, '');
|
||
console.log('Startup IDLE loopback: passed (due cyclic/background held until real full-GI TERM, then both measurement snapshots progress)');
|
||
} catch (error) {
|
||
console.error(`Startup IDLE diagnostics:\n${output}\n${errors}`); throw error;
|
||
} finally {
|
||
clearTimeout(deadline); if (socket) socket.destroy(); if (child.exitCode === null) child.kill();
|
||
}
|
||
}
|
||
|
||
/* [LOOPBACK/SYSTEM_COMMAND] 独立进程验证ACK门槛与原端口重启;精确30秒边界用可控时钟专项。 */
|
||
async function systemCommandLoopback() {
|
||
const child = spawn(executable, ['--port', '0', '--ca', '7', '--window', '1', '--run-ms', '4500',
|
||
'--no-parameter', '--events', '0', '--background-ms', '0'],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '';
|
||
const sockets = [];
|
||
child.stdout.on('data', data => { output += data.toString(); });
|
||
child.stderr.on('data', data => { errors += data.toString(); });
|
||
const exit = once(child, 'exit');
|
||
const deadline = setTimeout(() => child.kill(), 12000);
|
||
try {
|
||
let port;
|
||
for (let index = 0; index < 100; ++index) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; }
|
||
await delay(20);
|
||
}
|
||
assert(port, `${output} ${errors}`);
|
||
async function connect() {
|
||
const socket = net.connect({ host: '127.0.0.1', port }); sockets.push(socket);
|
||
const master = new Master(socket); await once(socket, 'connect');
|
||
await master.control(7, 0x0b); return master;
|
||
}
|
||
const master = await connect();
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
const test107 = [107, 1, 0x86, 0x41, 7, 0, 0, 0, 0, 0x34, 0x12].concat(clockRequest(0).slice(9));
|
||
// 107同样容忍非零错误星期和GEN;commandReply逐字节核对原时标,不能回成规范化副本。
|
||
test107[13] |= 0x40;
|
||
test107[15] |= 0x20;
|
||
await commandReply(master, test107, 7);
|
||
await commandReply(master, [105, 1, 0x86, 0x42, 7, 0, 0, 0, 0, 1], 7);
|
||
await commandReply(master, [105, 1, 6, 0x43, 7, 0, 0, 0, 0, 2], 7);
|
||
// 广播105的TEST及QRP2逐站使用具体CA回复,本例只有CA7。
|
||
await master.send([105, 1, 0x86, 0x46, 255, 255, 0, 0, 0, 2]);
|
||
assert.deepEqual([...(await master.readASDU())], [105, 1, 0x87, 0x46, 7, 0, 0, 0, 0, 2]);
|
||
await master.send([105, 1, 6, 0x47, 255, 255, 0, 0, 0, 2]);
|
||
assert.deepEqual([...(await master.readASDU())], [105, 1, 7, 0x47, 7, 0, 0, 0, 0, 2]);
|
||
const reset = [105, 1, 6, 0x44, 255, 255, 0, 0, 0, 1];
|
||
await master.send(reset);
|
||
let confirmation;
|
||
for (let i = 0; i < 8; ++i) {
|
||
const frame = await master.next(); if (frame[2] === 1) continue;
|
||
assert.equal(frame.readUInt16LE(2) >> 1, master.nr++);
|
||
confirmation = frame.subarray(6); break;
|
||
}
|
||
assert.deepEqual([...confirmation], [105, 1, 7, 0x44, 7, 0, 0, 0, 0, 1]);
|
||
await delay(150); // 已写出确认仍不能复位,必须等有效累计ACK。
|
||
assert(!master.socket.destroyed && !master.error);
|
||
const closed = once(master.socket, 'close');
|
||
const ack = Buffer.from([0x68, 4, 1, 0, 0, 0]); ack.writeUInt16LE(master.nr << 1, 4);
|
||
master.socket.write(ack); await closed; await delay(50);
|
||
const next = await connect();
|
||
assert.deepEqual([...(await next.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 2]);
|
||
await commandReply(next, [104, 1, 6, 0x4b, 7, 0, 0, 0, 0, 0xaa, 0x55], 7);
|
||
await next.send([102, 1, 5, 0x45, 7, 0, 0xe9, 3, 0]);
|
||
timedSignal(await next.readASDU(), [30, 1, 5, 0x45, 7, 0, 0xe9, 3, 0, 0]);
|
||
await next.close();
|
||
const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`); assert.equal(errors, '');
|
||
assert.match(output, /SYSTEM_COMMAND restarts=1 partial_failures=0/);
|
||
console.log('System command loopback: passed (104/107 echo, invalid 104 pattern echo, 70 COI0/2, unicast/broadcast TEST confirmation without reset, QRP2, broadcast QRP1, no reset before ACK, same-port protocol restart)');
|
||
} finally {
|
||
clearTimeout(deadline); for (const socket of sockets) socket.destroy();
|
||
if (child.exitCode === null) child.kill();
|
||
}
|
||
}
|
||
|
||
/* [LOOPBACK/RESET_EVENTS] 离线先积压无效时标SOE;校时后清除,后续只允许新有效SOE。
|
||
* 启动门禁保持旧帧未编号;清除后完成真实全总召,再核对旧IV副本没有随补发出现。
|
||
* 原有无时标副本仍应发送;新采样继续双报,不能把QRP=2误做成禁止未来SOE。 */
|
||
async function resetEventsLoopback() {
|
||
const child = spawn(executable,
|
||
['--port', '0', '--ca', '7', '--window', '1', '--events', '10', '--run-ms', '2500',
|
||
'--simulation', 'stress', '--no-parameter', '--background-ms', '0'],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '', socket;
|
||
child.stdout.on('data', data => { output += data.toString(); });
|
||
child.stderr.on('data', data => { errors += data.toString(); });
|
||
const exit = once(child, 'exit');
|
||
const deadline = setTimeout(() => child.kill(), 7000);
|
||
try {
|
||
let port;
|
||
for (let index = 0; index < 100; ++index) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; }
|
||
await delay(20);
|
||
}
|
||
assert(port, `${output} ${errors}`);
|
||
await delay(200); // 尚未START时就采集约20次变化,形成可清除的NORMAL积压。
|
||
socket = net.connect({ host: '127.0.0.1', port });
|
||
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, 0]);
|
||
const calibration = clockRequest(0x51);
|
||
await commandReply(master, calibration, 7);
|
||
await commandReply(master, [105, 1, 6, 0x52, 7, 0, 0, 0, 0, 2], 7);
|
||
await startupInterrogation(master, 0x53);
|
||
let plain = 0, timed = 0;
|
||
for (let index = 0; index < 64 && (plain < 4 || timed < 2); ++index) {
|
||
const asdu = await master.readASDU();
|
||
assert.equal(asdu[2], 3);
|
||
if (asdu[0] === 30) { assert.equal(asdu[12] & 0x80, 0, 'Cleared pre-sync SOE reappeared'); ++timed; }
|
||
else { assert.equal(asdu[0], 11); ++plain; }
|
||
}
|
||
assert(plain >= 4 && timed >= 2);
|
||
await master.close();
|
||
const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`); assert.equal(errors, '');
|
||
assert.match(output, /events_cleared=1 events_discarded=[1-9]\d*/);
|
||
console.log('Reset events loopback: passed (old CP56 removed, plain retained, new SOE continues)');
|
||
} finally {
|
||
clearTimeout(deadline); if (socket) socket.destroy();
|
||
if (child.exitCode === null) child.kill();
|
||
}
|
||
}
|
||
|
||
/* ============================================================================
|
||
* [LOOPBACK/PARAMETER] 标准参数与总召读回;周期启停不影响背景扫描
|
||
* ============================================================================ */
|
||
const parameterRequest = (type, ioa, value, qualifier, cause = 6, ca = 7) => {
|
||
const bytes = Buffer.alloc(type === 112 ? 14 : type === 113 ? 10 : 12);
|
||
bytes[0] = type; bytes[1] = 1; bytes[2] = cause; bytes[3] = 0x71;
|
||
bytes.writeUInt16LE(ca, 4); bytes.writeUIntLE(ioa, 6, 3);
|
||
if (type === 112) bytes.writeFloatLE(value, 9);
|
||
else if (type !== 113) bytes.writeInt16LE(value, 9);
|
||
bytes[bytes.length - 1] = qualifier;
|
||
return bytes;
|
||
};
|
||
|
||
async function parameterLoopback() {
|
||
const child = spawn(executable, ['--port', '0', '--ca', '7', '--run-ms', '6500',
|
||
'--parameter', '--events', '0', '--cyclic-ms', '200', '--background-ms', '300', '--sequence'],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '';
|
||
const sockets = [];
|
||
child.stdout.on('data', data => { output += data; }); child.stderr.on('data', data => { errors += data; });
|
||
const exit = once(child, 'exit'); const deadline = setTimeout(() => child.kill(), 12000);
|
||
try {
|
||
let port;
|
||
for (let i = 0; i < 100; ++i) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; } await delay(20);
|
||
}
|
||
assert(port, `${output}\n${errors}`);
|
||
const connect = async () => {
|
||
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); return master;
|
||
};
|
||
let master = await connect();
|
||
const until = async predicate => {
|
||
for (let i = 0; i < 256; ++i) { const asdu = await master.readASDU(); if (predicate(asdu)) return asdu; }
|
||
throw new Error('Missing parameter response');
|
||
};
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
await startupInterrogation(master, 0x70, { parameters: true });
|
||
const reply = async (requestBytes, cause, value) => {
|
||
await master.send(requestBytes);
|
||
const expected = Buffer.from(requestBytes); expected[2] = cause;
|
||
if (value !== undefined) {
|
||
if (expected[0] === 112) expected.writeFloatLE(value, 9); else expected.writeInt16LE(value, 9);
|
||
}
|
||
assert.deepEqual(await until(a => a[0] === requestBytes[0] && (a[2] & 0x3f) !== 20), expected);
|
||
};
|
||
await reply(parameterRequest(111, 0x8601, 200, 1), 7, 200);
|
||
await reply(parameterRequest(110, 0x8605, 16384, 1), 7, 16384);
|
||
await reply(parameterRequest(112, 0x8631, 1.5, 2), 7, 1.5);
|
||
await reply(parameterRequest(111, 0x8601, -1, 1), 0x47, 200);
|
||
await reply(parameterRequest(111, 0x8601, -1, 1, 0x86), 0x87, 200);
|
||
await reply(parameterRequest(110, 0x8605, -1, 1), 0x47, 16384);
|
||
for (const value of [-1, 61, Infinity, NaN]) await reply(parameterRequest(112, 0x8631, value, 2), 0x47, 1.5);
|
||
await reply(parameterRequest(111, 0x8611, 9000, 3), 7, 9000);
|
||
await reply(parameterRequest(111, 0x8621, 8000, 4), 0x47, 10000);
|
||
await reply(parameterRequest(111, 0x8621, 9500, 4), 7, 9500);
|
||
await reply(parameterRequest(113, 0, 0, 1), 0x47);
|
||
await reply(parameterRequest(113, 0x8601, 0, 2), 0x47);
|
||
await reply(parameterRequest(113, 9999, 0, 3), 0x6f);
|
||
const interrogation = async qoi => {
|
||
await master.send(request(0x72, qoi));
|
||
const parameters = new Map(); let began = false;
|
||
for (let i = 0; i < 256; ++i) {
|
||
const asdu = await master.readASDU();
|
||
if (asdu[0] === 100 && asdu[2] === 0x87) { began = true; continue; }
|
||
if (asdu[0] === 100 && asdu[2] === 0x8a) { assert(began); return parameters; }
|
||
if (asdu[0] < 110 || asdu[0] > 112) continue;
|
||
assert.equal(qoi, 20); assert.equal(asdu[1], 1); assert.equal(asdu[2], 0x94);
|
||
const ioa = asdu.readUIntLE(6, 3); assert(!parameters.has(ioa));
|
||
parameters.set(ioa, asdu);
|
||
}
|
||
throw new Error('Missing parameter interrogation termination');
|
||
};
|
||
const parameters = await interrogation(20); assert.equal(parameters.size, 32);
|
||
for (let group = 0; group < 4; ++group) for (let i = 0; i < 8; ++i) {
|
||
const asdu = parameters.get(0x8601 + 0x10 * group + i); assert(asdu);
|
||
assert.equal(asdu[0], group === 3 ? 112 : group === 0 && i >= 4 ? 110 : 111);
|
||
assert.equal(asdu[asdu.length - 1], [1, 3, 4, 2][group]);
|
||
}
|
||
assert.equal(parameters.get(0x8601).readInt16LE(9), 200);
|
||
assert.equal(parameters.get(0x8605).readInt16LE(9), 16384);
|
||
assert.equal(parameters.get(0x8631).readFloatLE(9), 1.5);
|
||
assert.equal(parameters.get(0x8611).readInt16LE(9), 9000);
|
||
assert.equal(parameters.get(0x8621).readInt16LE(9), 9500);
|
||
assert.equal((await interrogation(21)).size, 0); assert.equal((await interrogation(22)).size, 0);
|
||
// Real application wiring: the loaded range affects reads; a command is a raw
|
||
// input step, smoothing continues without --events, and tau=0 bypasses it.
|
||
const readMeasurement = async () => {
|
||
await master.send([102, 1, 5, 0x75, 7, 0, 0x01, 0x40, 0]);
|
||
return until(a => a[0] === 11 && a[2] === 5 && a[3] === 0x75);
|
||
};
|
||
let measurement = await readMeasurement();
|
||
assert.equal(measurement.readInt16LE(9), 2300); assert.equal(measurement[11], 1);
|
||
await reply(Buffer.from(scaledCommandRequest(0x74, 0x6031, 2500, true)), 7);
|
||
await reply(Buffer.from(scaledCommandRequest(0x74, 0x6031, 2500, false)), 7);
|
||
measurement = await until(a => a[0] === 11 && a[2] === 11);
|
||
assert.equal(measurement.readInt16LE(9), 2300); assert.equal(measurement[11], 1);
|
||
await until(a => a[0] === 49 && a[2] === 10);
|
||
await delay(150);
|
||
measurement = await readMeasurement();
|
||
assert(measurement.readInt16LE(9) > 2300 && measurement.readInt16LE(9) < 2500);
|
||
await reply(parameterRequest(112, 0x8631, 0, 2), 7, 0);
|
||
measurement = await until(a => a[0] === 11 && a[2] === 3);
|
||
assert.equal(measurement.readUIntLE(6, 3), 0x4001);
|
||
assert.equal(measurement.readInt16LE(9), 2500); assert.equal(measurement[11], 1);
|
||
// Restoring the range emits a quality transition even with zero value delta.
|
||
await reply(parameterRequest(111, 0x8611, -10000, 3), 7, -10000);
|
||
measurement = await until(a => a[0] === 11 && a[2] === 3);
|
||
assert.equal(measurement.readInt16LE(9), 2500); assert.equal(measurement[11], 0);
|
||
measurement = await readMeasurement();
|
||
assert.equal(measurement.readInt16LE(9), 2500); assert.equal(measurement[11], 0);
|
||
const ioas = asdu => {
|
||
const count = asdu[1] & 0x7f, sequence = (asdu[1] & 0x80) !== 0, result = [];
|
||
const width = asdu[0] === 11 ? 3 : 1;
|
||
for (let i = 0; i < count; ++i) result.push(sequence ? asdu.readUIntLE(6, 3) + i : asdu.readUIntLE(6 + i * (3 + width), 3));
|
||
return result;
|
||
};
|
||
await reply(parameterRequest(113, 0x4004, 0, 3, 8), 9);
|
||
await reply(parameterRequest(113, 0x4004, 0, 3, 0x86), 0x87); // TEST must not resume the point.
|
||
const settled = Date.now() + 400; let cyclic = 0, background = false, neighbor = false;
|
||
for (let i = 0; i < 128 && (cyclic < 4 || !background); ++i) {
|
||
const asdu = await master.readASDU(); if (Date.now() < settled) continue;
|
||
if (asdu[2] === 1) {
|
||
const addresses = ioas(asdu); assert(!addresses.includes(0x4004), 'Disabled point crossed an SQ segment');
|
||
if (addresses.includes(0x4003) || addresses.includes(0x4005)) neighbor = true;
|
||
++cyclic;
|
||
}
|
||
if (asdu[2] === 2 && asdu[0] === 11 && ioas(asdu).includes(0x4004)) background = true;
|
||
}
|
||
assert(cyclic >= 4 && background && neighbor);
|
||
await reply(parameterRequest(113, 0x4004, 0, 3), 7);
|
||
await until(a => a[0] === 11 && a[2] === 1 && ioas(a).includes(0x4004));
|
||
await reply(parameterRequest(113, 0x4004, 0, 3, 8), 9);
|
||
const closed = once(master.socket, 'close');
|
||
await master.send([105, 1, 6, 0x73, 7, 0, 0, 0, 0, 1]);
|
||
assert.equal((await until(a => a[0] === 105))[2], 7); await closed; await delay(50);
|
||
master = await connect();
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 2]);
|
||
await startupInterrogation(master, 0x70, { parameters: true });
|
||
const reset = await interrogation(20); assert.equal(reset.size, 32);
|
||
assert.equal(reset.get(0x8601).readInt16LE(9), 200); assert.equal(reset.get(0x8605).readInt16LE(9), 655);
|
||
assert.equal(reset.get(0x8631).readFloatLE(9), 0); assert.equal(reset.get(0x8611).readInt16LE(9), -10000);
|
||
assert.equal(reset.get(0x8621).readInt16LE(9), 10000);
|
||
await until(a => a[0] === 11 && a[2] === 1 && ioas(a).includes(0x4004));
|
||
await master.close(); const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`); assert.equal(errors, ''); assert.match(output, /PARAMETER accepted=/);
|
||
console.log('Parameter loopback: passed (three types, running-value confirmation, TEST, bounds, GI32, QPA3, smoothing, range quality, threshold, mixed SQ scans, reset)');
|
||
} finally { clearTimeout(deadline); for (const socket of sockets) socket.destroy(); if (child.exitCode === null) child.kill(); }
|
||
}
|
||
|
||
/* [LOOPBACK/FIELD_PROFILE] 独立进程验证默认现场模式;短背景场景只改背景周期。
|
||
* 普通点值允许采样推进,参数和线上报文仍按Type/IOA/COT独立核对。
|
||
* 每轮主动读0x4001保持短等待,同时观察其间的突发和背景帧,不依赖空闲读取超时证明静默。 */
|
||
async function fieldProfileLoopback(backgroundMs = 30000) {
|
||
const args = ['--port', '0', '--ca', '7', '--run-ms', '7000'];
|
||
if (backgroundMs !== 30000) args.push('--background-ms', String(backgroundMs));
|
||
const child = spawn(executable, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '', socket;
|
||
child.stdout.on('data', data => { output += data; });
|
||
child.stderr.on('data', data => { errors += data; });
|
||
const exit = once(child, 'exit');
|
||
const deadline = setTimeout(() => child.kill(), 11000);
|
||
const initialMeasurements = [2300, 2310, 2290, 5000, -125, 0, 1234, 42];
|
||
const initialSignals = [0, 1, 0, 1, 1, 0, 1, 0];
|
||
const changes = new Map(), stepped = new Set();
|
||
let backgroundMeasurements = 0, backgroundBeforeThreshold = false;
|
||
try {
|
||
let port;
|
||
for (let i = 0; i < 100; ++i) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; }
|
||
await delay(20);
|
||
}
|
||
assert(port, `${output}\n${errors}`);
|
||
assert.match(output, new RegExp(`^PROFILE PARAMETER=1 SIMULATION=field SAMPLE_MS=100 CYCLIC_MS=0 BACKGROUND_MS=${backgroundMs}$`, 'm'));
|
||
socket = net.connect({ host: '127.0.0.1', port });
|
||
const master = new Master(socket); master.asynchronous = true;
|
||
await once(socket, 'connect'); await master.control(7, 0x0b);
|
||
const snapshot = (asdu, sequence) => {
|
||
const type = asdu[0], count = asdu[1] & 0x7f, addresses = [];
|
||
assert([1, 3, 11].includes(type)); assert(count === 4 || count === 8);
|
||
assert.equal((asdu[1] & 0x80) !== 0, sequence);
|
||
const width = type === 11 ? 3 : 1, base = type === 1 ? 1001 : type === 3 ? 1101 : 0x4001;
|
||
assert.equal(asdu.length, sequence ? 9 + count * width : 6 + count * (3 + width));
|
||
const firstIoa = asdu.readUIntLE(6, 3);
|
||
for (let i = 0; i < count; ++i) {
|
||
const offset = sequence ? 9 + i * width : 9 + i * (3 + width);
|
||
const ioa = sequence ? firstIoa + i : asdu.readUIntLE(offset - 3, 3), index = ioa - base;
|
||
assert(index >= 0 && index < 8); addresses.push(ioa);
|
||
if (type === 11) {
|
||
const value = asdu.readInt16LE(offset);
|
||
assert(value >= initialMeasurements[index] && value <= initialMeasurements[index] + 351);
|
||
assert.equal(asdu[offset + 2], 0);
|
||
} else assert.equal(asdu[offset], type === 1 ? initialSignals[index] : 1);
|
||
}
|
||
return addresses;
|
||
};
|
||
const observe = asdu => {
|
||
assert.equal(asdu.readUInt16LE(4), 7);
|
||
const cause = asdu[2] & 63;
|
||
assert.notEqual(cause, 1, 'Default field profile emitted a cyclic frame');
|
||
if (cause === 4) {
|
||
assert.deepEqual([...asdu], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]); return true;
|
||
}
|
||
if (cause === 2) {
|
||
assert.notEqual(backgroundMs, 30000, 'Default background fired before its configured interval');
|
||
assert.deepEqual([...asdu.subarray(1, 6)], [8, 2, 0, 7, 0]);
|
||
snapshot(asdu, false);
|
||
if (asdu[0] === 11) ++backgroundMeasurements;
|
||
return true;
|
||
}
|
||
if (cause === 3) {
|
||
assert.deepEqual([...asdu.subarray(0, 6)], [11, 1, 3, 0, 7, 0], 'Field sampling must not toggle digital points');
|
||
assert.equal(asdu.length, 12); assert.equal(asdu[11], 0);
|
||
const ioa = asdu.readUIntLE(6, 3), value = asdu.readInt16LE(9), index = ioa - 0x4001;
|
||
assert(index >= 0 && index < 8);
|
||
if (!changes.has(ioa)) changes.set(ioa, []);
|
||
changes.get(ioa).push(value);
|
||
if (value === initialMeasurements[index] + 351) stepped.add(ioa);
|
||
if (ioa === 0x4001 && value === 2350) backgroundBeforeThreshold = backgroundMeasurements > 0;
|
||
return true;
|
||
}
|
||
return false;
|
||
};
|
||
const until = async predicate => {
|
||
for (let i = 0; i < 128; ++i) {
|
||
const asdu = await master.readASDU(), asynchronous = observe(asdu);
|
||
if (predicate(asdu)) return asdu;
|
||
assert(asynchronous, `Unexpected field response: ${asdu.toString('hex')}`);
|
||
}
|
||
throw new Error('Missing field profile response');
|
||
};
|
||
assert.deepEqual([...(await master.readASDU())], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]);
|
||
const gi = [100, 1, 6, 0x79, 7, 0, 0, 0, 0, 20];
|
||
await master.send(gi);
|
||
const confirmation = [...gi]; confirmation[2] = 7;
|
||
assert.deepEqual([...(await master.readASDU())], confirmation);
|
||
const parameters = new Map(), points = new Set();
|
||
let ended = false;
|
||
for (let i = 0; i < 128; ++i) {
|
||
const asdu = await master.readASDU();
|
||
if (asdu[0] === 100) {
|
||
const termination = [...gi]; termination[2] = 10;
|
||
assert.deepEqual([...asdu], termination); ended = true; break;
|
||
}
|
||
assert.equal(asdu[2], 20); assert.equal(asdu[3], 0x79);
|
||
if (asdu[0] >= 110 && asdu[0] <= 112) {
|
||
assert.equal(asdu[1], 1);
|
||
const ioa = asdu.readUIntLE(6, 3); assert(!parameters.has(ioa)); parameters.set(ioa, asdu);
|
||
} else {
|
||
assert.equal(asdu[1], 0x84);
|
||
for (const ioa of snapshot(asdu, true)) { assert(!points.has(ioa)); points.add(ioa); }
|
||
}
|
||
}
|
||
assert(ended); assert.equal(points.size, 24); assert.equal(parameters.size, 32);
|
||
for (let group = 0; group < 4; ++group) for (let i = 0; i < 8; ++i) {
|
||
const asdu = parameters.get(0x8601 + group * 0x10 + i); assert(asdu);
|
||
const type = group === 3 ? 112 : group === 0 && i >= 4 ? 110 : 111;
|
||
const value = group === 0 ? (i >= 4 ? 655 : 200) : group === 1 ? -10000 : group === 2 ? 10000 : 0;
|
||
assert.equal(asdu[0], type); assert.equal(asdu.length, type === 112 ? 14 : 12);
|
||
assert.equal(asdu[asdu.length - 1], [1, 3, 4, 2][group]);
|
||
assert.equal(type === 112 ? asdu.readFloatLE(9) : asdu.readInt16LE(9), value);
|
||
}
|
||
if (backgroundMs !== 30000) {
|
||
// A 50-unit threshold crosses during the slow ramp, while repeated background
|
||
// snapshots occur between changes. Background must not reset the COT3 baseline.
|
||
const load = parameterRequest(111, 0x8601, 50, 1, 6, 7); await master.send(load);
|
||
const expected = Buffer.from(load); expected[2] = 7;
|
||
assert.deepEqual(await until(a => a[0] === 111 && a.readUIntLE(6, 3) === 0x8601 && a[2] === 7), expected);
|
||
}
|
||
const stopAt = Date.now() + 6000;
|
||
while (stepped.size < 8 && Date.now() < stopAt) {
|
||
await master.send([102, 1, 5, 0x7a, 7, 0, 0x01, 0x40, 0]);
|
||
const read = await until(a => a[0] === 11 && a[2] === 5 && a[3] === 0x7a && a.readUIntLE(6, 3) === 0x4001);
|
||
assert.equal(read.length, 12); assert.equal(read[11], 0);
|
||
await delay(100);
|
||
}
|
||
assert.equal(stepped.size, 8, 'Missing threshold-triggered field load step');
|
||
for (let i = 0; i < 8; ++i) {
|
||
const expected = backgroundMs !== 30000 && i === 0 ? [2350, 2400, 2651] : [initialMeasurements[i] + 351];
|
||
assert.deepEqual(changes.get(0x4001 + i), expected);
|
||
}
|
||
if (backgroundMs !== 30000) {
|
||
assert(backgroundMeasurements >= 3); assert(backgroundBeforeThreshold, 'Background was not observed before ramp threshold crossing');
|
||
} else assert.equal(backgroundMeasurements, 0);
|
||
await master.close();
|
||
const [code] = await exit; assert.equal(code, 0, `${output}\n${errors}`); assert.equal(errors, '');
|
||
console.log(`Field profile loopback: passed (background=${backgroundMs}ms, GI32 defaults, no COT1/digital changes, threshold load step${backgroundMs !== 30000 ? ', background preserves change baseline' : ''})`);
|
||
} finally { clearTimeout(deadline); if (socket) socket.destroy(); if (child.exitCode === null) child.kill(); }
|
||
}
|
||
|
||
/* [LOOPBACK/FILE_SERVICE] Type210 真实 TCP:独立编码、连续写入和读回。
|
||
* 录波文件输出限于本目录.build;逐帧核对偏移、模和、CONT和宣告大小,并与磁盘文件比较。
|
||
* 连发12段不等待op10,覆盖示例保留BUSY事件的实际分派路径。 */
|
||
async function fileServiceLoopback() {
|
||
const artifactRoot = path.resolve(__dirname, '../.build');
|
||
fs.mkdirSync(artifactRoot, { recursive: true });
|
||
const recordingDirectory = fs.mkdtempSync(path.join(artifactRoot, 'recording-loopback-'));
|
||
const child = spawn(executable, ['--port', '0', '--ca', '7', '--run-ms', '12000',
|
||
'--recording-demo', recordingDirectory, '--events', '0', '--background-ms', '0', '--cyclic-ms', '0'],
|
||
{ windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||
let output = '', errors = '', socket;
|
||
child.stdout.on('data', b => { output += b; }); child.stderr.on('data', b => { errors += b; });
|
||
const exit = once(child, 'exit'), deadline = setTimeout(() => child.kill(), 16000);
|
||
const head = (op, cause) => Buffer.from([210, 1, cause, 0x41, 7, 0, 0, 0, 0, 2, op]);
|
||
const u32 = value => { const b = Buffer.alloc(4); b.writeUInt32LE(value); return b; };
|
||
const named = name => { const b = Buffer.from(name, 'ascii'); return Buffer.concat([Buffer.from([b.length]), b]); };
|
||
try {
|
||
let port;
|
||
for (let i = 0; i < 150; ++i) {
|
||
const match = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||
if (match) { port = Number(match[1]); break; } await delay(10);
|
||
}
|
||
assert(port, `${output}\n${errors}`);
|
||
socket = net.connect({ host: '127.0.0.1', port }); 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, 0]);
|
||
await startupInterrogation(master, 0x40, { parameters: true });
|
||
let faultReceived = false;
|
||
const receive = async op => {
|
||
let frame = await master.readASDU();
|
||
if (frame[0] === 42) {
|
||
assert.equal(faultReceived, false); assert.equal(frame[2], 3);
|
||
faultReceived = true;
|
||
frame = await master.readASDU();
|
||
}
|
||
assert(faultReceived, 'Fault event must arrive before the first file response');
|
||
assert.equal(frame[0], 210); assert.equal(frame[1], 1); assert.equal(frame[3], 0x41);
|
||
assert.equal(frame.readUInt16LE(4), 7); assert.equal(frame.readUIntLE(6, 3), 0);
|
||
assert.equal(frame[9], 2); assert.equal(frame[10], op); return frame;
|
||
};
|
||
const directory = async name => {
|
||
await master.send(Buffer.concat([head(1, 5), u32(name === 'COMTRADE' ? 6 : 0), named(name), Buffer.alloc(15)]));
|
||
const entries = [];
|
||
for (let frames = 0; frames < 10; ++frames) {
|
||
const frame = await receive(2); assert.equal(frame[2], 5); assert.equal(frame[11], 0);
|
||
assert(frame[17] > 0, 'A nonempty directory must not end with a zero-entry frame');
|
||
assert.equal(frame.readUInt32LE(12), 0); let cursor = 18;
|
||
for (let i = 0; i < frame[17]; ++i) {
|
||
const length = frame[cursor++], name = frame.subarray(cursor, cursor + length).toString('ascii'); cursor += length;
|
||
const attribute = frame[cursor++], size = frame.readUInt32LE(cursor); cursor += 4;
|
||
assert.equal(attribute, 0); assert(frame[cursor + 4] >= 1 && frame[cursor + 4] <= 31); cursor += 7;
|
||
entries.push({ name, size });
|
||
}
|
||
assert.equal(cursor, frame.length);
|
||
if (frame[16] === 0) return entries;
|
||
assert.equal(frame[16], 1);
|
||
}
|
||
throw new Error('Directory did not terminate');
|
||
};
|
||
const read = async name => {
|
||
await master.send(Buffer.concat([head(3, 6), named(name)])); const activation = await receive(4);
|
||
assert.equal(activation[2], 7); assert.equal(activation[11], 0);
|
||
const echoed = activation[12], idOffset = 13 + echoed;
|
||
assert.equal(activation.subarray(13, idOffset).toString('ascii'), name);
|
||
assert.equal(activation.readUInt32LE(idOffset), 0); const size = activation.readUInt32LE(idOffset + 4);
|
||
const chunks = []; let offset = 0;
|
||
for (let frames = 0; frames < 300; ++frames) {
|
||
const frame = await receive(5); assert.equal(frame[2], 5); assert.equal(frame.readUInt32LE(11), 0);
|
||
assert.equal(frame.readUInt32LE(15), offset);
|
||
const data = frame.subarray(20, -1); assert(data.length <= 228);
|
||
assert.equal(frame[frame.length - 1], data.reduce((sum, byte) => (sum + byte) & 255, 0));
|
||
chunks.push(data); offset += data.length;
|
||
if (frame[19] === 0) {
|
||
assert(data.length > 0, 'A nonempty file must not end with an empty data segment');
|
||
assert.equal(offset, size);
|
||
await master.send(Buffer.concat([head(6, 5), u32(0), frame.subarray(15, 19), Buffer.from([0])]));
|
||
return Buffer.concat(chunks);
|
||
}
|
||
assert.equal(frame[19], 1);
|
||
}
|
||
throw new Error('Read file did not terminate');
|
||
};
|
||
// Send the request immediately after startup GI, without waiting for Type42.
|
||
assert.deepEqual(await directory(''), [{ name: 'HISTORY/SOE/soe.msg', size: Buffer.byteLength('SOE example: breaker closed\n') }]);
|
||
const comtrade = await directory('COMTRADE'); assert.equal(comtrade.length, 2);
|
||
const downloaded = {};
|
||
for (const entry of comtrade) {
|
||
assert.match(entry.name, /^COMTRADE\/BAY01_0001_\d{8}_\d{6}_\d{3}\.(cfg|dat)$/);
|
||
const bytes = await read(entry.name); // Echo exactly the advertised directory-entry name.
|
||
assert.equal(bytes.length, entry.size);
|
||
assert.deepEqual(bytes, fs.readFileSync(path.join(recordingDirectory, entry.name)));
|
||
downloaded[path.extname(entry.name)] = bytes;
|
||
}
|
||
const cfg = downloaded['.cfg'], dat = downloaded['.dat'];
|
||
assert(cfg && dat); assert(cfg.every(byte => byte < 128));
|
||
assert(!cfg.toString('ascii').replaceAll('\r\n', '').includes('\n'));
|
||
const lines = cfg.toString('ascii').trimEnd().split('\r\n');
|
||
assert.equal(lines[0], 'SIMULATION,IEC104_DEMO,1999'); assert.equal(lines[1], '24,8A,16D');
|
||
assert.deepEqual(lines.slice(2, 10).map(line => line.split(',')[1]), ['Ua', 'Ub', 'Uc', 'U0', 'Ia', 'Ib', 'Ic', 'I0']);
|
||
assert.deepEqual(lines.slice(26, 29), ['50', '1', '4000,961']);
|
||
assert.deepEqual(lines.slice(31), ['BINARY', '1']);
|
||
const timestamp = value => {
|
||
const match = value.match(/^(\d{2})\/(\d{2})\/(\d{4}),(\d{2}):(\d{2}):(\d{2})\.(\d{6})$/);
|
||
assert(match);
|
||
const [, day, month, year, hour, minute, second, micros] = match.map(Number);
|
||
return Date.UTC(year, month - 1, day, hour, minute, second) * 1000 + micros;
|
||
};
|
||
assert.equal(timestamp(lines[30]) - timestamp(lines[29]), 80000);
|
||
assert.equal(dat.length, 961 * 26);
|
||
let beforeVoltage = 0, afterVoltage = 0, beforeCurrent = 0, afterCurrent = 0;
|
||
for (let sample = 0; sample < 961; ++sample) {
|
||
const pos = sample * 26;
|
||
assert.equal(dat.readUInt32LE(pos), sample + 1);
|
||
assert.equal(dat.readUInt32LE(pos + 4), sample * 250);
|
||
assert.equal(dat.readUInt16LE(pos + 24), (sample >= 320 ? 2 : 0) | (sample >= 360 ? 1 : 0));
|
||
const voltage = dat.readInt16LE(pos + 8), current = dat.readInt16LE(pos + 16);
|
||
if (sample >= 240 && sample < 320) { beforeVoltage += voltage ** 2; beforeCurrent += current ** 2; }
|
||
if (sample >= 320 && sample < 400) { afterVoltage += voltage ** 2; afterCurrent += current ** 2; }
|
||
}
|
||
assert(Math.abs(Math.sqrt(afterVoltage / beforeVoltage) - 0.5) < 0.001);
|
||
assert(Math.abs(Math.sqrt(afterCurrent / beforeCurrent) - 5) < 0.01);
|
||
assert.equal((await read('HISTORY/SOE/soe.msg')).toString('ascii'), 'SOE example: breaker closed\n');
|
||
const name = 'TEMP/transfer.bin', content = Buffer.alloc(12 * 228);
|
||
for (let i = 0; i < content.length; ++i) content[i] = (i * 31 + 7) & 255;
|
||
await master.send(Buffer.concat([head(7, 6), named(name), u32(17), u32(content.length)]));
|
||
const activation = await receive(8); assert.equal(activation[2], 7); assert.equal(activation[11], 0);
|
||
assert.equal(activation.readUInt32LE(13 + activation[12]), 0);
|
||
const burst = [];
|
||
for (let offset = 0; offset < content.length; offset += 228) {
|
||
const data = content.subarray(offset, offset + 228), sum = data.reduce((a, b) => (a + b) & 255, 0);
|
||
burst.push(master.frame(Buffer.concat([head(9, 5), u32(17), u32(offset),
|
||
Buffer.from([offset + data.length < content.length ? 1 : 0]), data, Buffer.from([sum])])));
|
||
}
|
||
socket.write(Buffer.concat(burst)); const final = await receive(10);
|
||
assert.deepEqual(final, Buffer.concat([head(10, 7), u32(0), u32(11 * 228), Buffer.from([0])]));
|
||
assert.deepEqual(await read(name), content);
|
||
for (const [target, size, code] of [['unsupported.bin', 1, 2], ['TEMP/large.bin', 4097, 3], ['upgrade.bin', 16, 2]]) {
|
||
await master.send(Buffer.concat([head(7, 6), named(target), u32(0), u32(size)]));
|
||
const failed = await receive(8); assert.equal(failed[2], 0x47); assert.equal(failed[11], code);
|
||
}
|
||
await master.close(); const [code] = await exit;
|
||
assert.equal(code, 0, `${output}\n${errors}`); assert.equal(errors, ''); assert.match(output, /FILE_SERVICE accepted=/);
|
||
console.log(`FileService loopback: passed (Type42 before download, full names/ID6/final confirmation, CFG/BINARY DAT parsed, disk equality, 12-segment burst). Artifacts: ${recordingDirectory}`);
|
||
} finally { clearTimeout(deadline); if (socket) socket.destroy(); if (child.exitCode === null) child.kill(); }
|
||
}
|
||
|
||
/* [ENTRY/RUN] Helpers are also used by the independent two-master loopback. */
|
||
module.exports = { Master, parameterRequest, fileServiceLoopback };
|
||
if (require.main === module) {
|
||
const run = process.argv[3] === '--file-service-only' ? fileServiceLoopback() :
|
||
process.argv[3] === '--spontaneous-only' ? spontaneousLoopback() :
|
||
process.argv[3] === '--startup-replay-only' ? startupReplayLoopback().then(startupIdleLoopback) :
|
||
process.argv[3] === '--system-command-only' ? systemCommandLoopback() :
|
||
process.argv[3] === '--clock-read-only' ? clockReadLoopback() :
|
||
process.argv[3] === '--float-counters-only' ? floatCountersLoopback() :
|
||
main().then(clockReadLoopback).then(floatCountersLoopback).then(startupReplayLoopback).then(startupIdleLoopback).then(spontaneousLoopback).then(systemCommandLoopback).then(resetEventsLoopback).then(parameterLoopback)
|
||
.then(() => fieldProfileLoopback()).then(() => fieldProfileLoopback(300)).then(fileServiceLoopback);
|
||
run
|
||
.catch(error => { console.error(error); process.exitCode = 1; });
|
||
}
|