添加遥控、参数装载、文件传输等业务
This commit is contained in:
@@ -0,0 +1,184 @@
|
||||
/* Type211/210真实TCP回环:启动生产Windows后端示例,独立构造ASDU和工程升级包。
|
||||
* 顺序:开关/拒绝路径 -> 多段文件上传 -> ACK后协议重建 -> 202版本与CRC读回 -> 再次升级。
|
||||
* 仅运行本目录.build内指定的示例;验证RAM模拟激活,不写设备Flash或替换宿主程序。 */
|
||||
'use strict';
|
||||
const assert = require('node:assert/strict');
|
||||
const net = require('node:net');
|
||||
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 { Master } = require('./slave_example_loopback_test.cjs');
|
||||
|
||||
const executable = path.resolve(process.argv[2]);
|
||||
const build = path.resolve(__dirname, '..', '.build');
|
||||
const relative = path.relative(build, executable);
|
||||
assert(relative !== '' && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
|
||||
const children = [], sockets = [];
|
||||
const u32 = value => { const bytes = Buffer.alloc(4); bytes.writeUInt32LE(value); return bytes; };
|
||||
const named = value => { const bytes = Buffer.from(value, 'ascii'); return Buffer.concat([Buffer.from([bytes.length]), bytes]); };
|
||||
const fileHead = (op, cot) => Buffer.from([210, 1, cot, 0x41, 7, 0, 0, 0, 0, 2, op]);
|
||||
const command = (operation, test = false) => Buffer.from([
|
||||
211, 0, (operation === 'cancel' ? 8 : 6) | (test ? 0x80 : 0), 0x62, 7, 0,
|
||||
0x56, 0x34, 0x12, operation === 'start' ? 0x95 : 0x15]);
|
||||
|
||||
/* 主站侧独立计算CRC并先核对已知向量,避免把终端自算值与自身比较当成整包校验。 */
|
||||
function crc32(bytes) {
|
||||
let crc = 0xffffffff;
|
||||
for (const byte of bytes) {
|
||||
crc ^= byte;
|
||||
for (let bit = 0; bit < 8; ++bit) crc = (crc >>> 1) ^ ((crc & 1) ? 0xedb88320 : 0);
|
||||
}
|
||||
return (crc ^ 0xffffffff) >>> 0;
|
||||
}
|
||||
assert.equal(crc32(Buffer.from('123456789')), 0xcbf43926);
|
||||
function packageBytes(version, payload) {
|
||||
return Buffer.concat([Buffer.from('I104'), u32(version), u32(payload.length), u32(crc32(payload)), payload]);
|
||||
}
|
||||
function launch(enabled, runMs) {
|
||||
const args = ['--port', '0', '--ca', '7', '--events', '0', '--background-ms', '0', '--run-ms', String(runMs),
|
||||
'--file-service', '--remote-parameter'];
|
||||
if (enabled) args.push('--software-upgrade');
|
||||
const child = spawn(executable, args, { windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
const item = { child, output: '', errors: '', done: false };
|
||||
child.stdout.on('data', bytes => { item.output += bytes; });
|
||||
child.stderr.on('data', bytes => { item.errors += bytes; });
|
||||
item.exit = once(child, 'close').then(([code, signal]) => { item.done = true; return { code, signal }; });
|
||||
item.exit.catch(() => {});
|
||||
item.timer = setTimeout(() => child.kill(), runMs + 5000); children.push(item); return item;
|
||||
}
|
||||
async function listener(item) {
|
||||
for (let i = 0; i < 250; ++i) {
|
||||
const match = item.output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/);
|
||||
if (match) return Number(match[1]);
|
||||
if (item.done) break;
|
||||
await delay(10);
|
||||
}
|
||||
throw new Error(`No listener: ${item.output}\n${item.errors}`);
|
||||
}
|
||||
/* 重建会短暂撤下监听,有限重试后核对Type70;初始化确认还须配合imageValues判成功。 */
|
||||
async function connect(port, coi = 0) {
|
||||
let socket;
|
||||
for (let attempt = 0; attempt < 30; ++attempt) {
|
||||
socket = net.connect({ host: '127.0.0.1', port }); sockets.push(socket);
|
||||
try { await once(socket, 'connect'); break; }
|
||||
catch (error) { socket.destroy(); if (attempt === 29) throw error; await delay(25); }
|
||||
}
|
||||
const master = new Master(socket); master.asynchronous = true;
|
||||
await master.control(7, 0x0b);
|
||||
assert.deepEqual(await master.readASDU(), Buffer.from([70, 1, 4, 0, 7, 0, 0, 0, 0, coi]));
|
||||
return master;
|
||||
}
|
||||
/* 确认须镜像除COT外的请求字段;Master.readASDU会发送累计S帧ACK。 */
|
||||
async function reply(master, request, cause) {
|
||||
const expected = Buffer.from(request); expected[2] = cause | (request[2] & 0x80);
|
||||
await master.send(request); assert.deepEqual(await master.readASDU(), expected);
|
||||
}
|
||||
async function fileResponse(master, op) {
|
||||
const frame = await master.readASDU();
|
||||
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;
|
||||
}
|
||||
async function activateFile(master, size, expected = 0, name = 'upgrade.bin') {
|
||||
await master.send(Buffer.concat([fileHead(7, 6), named(name), u32(17), u32(size)]));
|
||||
const response = await fileResponse(master, 8);
|
||||
assert.equal(response[2], expected === 0 ? 7 : 0x47); assert.equal(response[11], expected);
|
||||
}
|
||||
async function upload(master, bytes, success = true) {
|
||||
await activateFile(master, bytes.length);
|
||||
const burst = []; let offset = 0, lastOffset = 0;
|
||||
// 故意把16字节包头拆入前三段;每段校验有效,整包CRC仍可故意错误。
|
||||
for (const desired of [5, 7, ...Array(Math.ceil(bytes.length / 228) + 2).fill(228)]) {
|
||||
if (offset === bytes.length) break;
|
||||
const data = bytes.subarray(offset, Math.min(bytes.length, offset + desired));
|
||||
const sum = data.reduce((value, byte) => (value + byte) & 255, 0);
|
||||
burst.push(master.frame(Buffer.concat([fileHead(9, 5), u32(17), u32(offset),
|
||||
Buffer.from([offset + data.length < bytes.length ? 1 : 0]), data, Buffer.from([sum])])));
|
||||
lastOffset = offset; offset += data.length;
|
||||
}
|
||||
assert.equal(offset, bytes.length); master.socket.write(Buffer.concat(burst));
|
||||
const final = await fileResponse(master, 10);
|
||||
assert.deepEqual(final, Buffer.concat([fileHead(10, success ? 7 : 0x47), u32(0), u32(lastOffset), Buffer.from([success ? 0 : 1])]));
|
||||
}
|
||||
/* 202的0x8005为含NUL的十进制版本字符串,0x8006为负载CRC;同时核对两值发布时机。 */
|
||||
async function imageValues(master, version, crc) {
|
||||
await master.send(Buffer.from([202, 2, 6, 0x73, 7, 0, 0, 0, 5, 0x80, 0, 6, 0x80, 0]));
|
||||
const frame = await master.readASDU();
|
||||
const text = Buffer.from(`${version}\0`, 'ascii');
|
||||
assert.deepEqual(frame, Buffer.concat([Buffer.from([202, 2, 7, 0x73, 7, 0, 0, 0, 0,
|
||||
5, 0x80, 0, 4, text.length]), text, Buffer.from([6, 0x80, 0, 35, 4]), u32(crc)]));
|
||||
}
|
||||
async function finish(item) {
|
||||
assert.deepEqual(await item.exit, { code: 0, signal: null }, `${item.output}\n${item.errors}`);
|
||||
assert.equal(item.errors, ''); clearTimeout(item.timer);
|
||||
}
|
||||
|
||||
async function exercise() {
|
||||
// 运行开关有依赖,禁用211时由应用回44;两条路径不应创建升级会话。
|
||||
const invalid = spawnSync(executable, ['--software-upgrade', '--run-ms', '1'], { windowsHide: true, encoding: 'utf8' });
|
||||
assert.equal(invalid.error, undefined); assert.notEqual(invalid.status, 0);
|
||||
|
||||
const disabled = launch(false, 800), disabledMaster = await connect(await listener(disabled));
|
||||
await reply(disabledMaster, command('start'), 0x6c);
|
||||
await disabledMaster.close(); await finish(disabled);
|
||||
assert(!disabled.output.includes('SOFTWARE_UPGRADE'));
|
||||
|
||||
const item = launch(true, 8000), port = await listener(item);
|
||||
let master = await connect(port);
|
||||
await imageValues(master, 1, 0xcbf43926);
|
||||
await reply(master, command('end'), 0x47);
|
||||
await reply(master, command('cancel'), 9);
|
||||
await reply(master, command('cancel'), 9);
|
||||
await activateFile(master, 17, 1); // 保留升级目标没有匹配的真实OPEN会话,不能降级成普通写文件。
|
||||
await reply(master, command('start', true), 7);
|
||||
await reply(master, command('end', true), 7);
|
||||
await imageValues(master, 1, 0xcbf43926);
|
||||
|
||||
await reply(master, command('start'), 7);
|
||||
await activateFile(master, 16, 3);
|
||||
await activateFile(master, 65537, 3);
|
||||
// Type210段校验全部通过,损坏的期望整包CRC仍须使COMMIT及后续END失败。
|
||||
const corrupt = packageBytes(2, Buffer.from('incorrect checksum'));
|
||||
corrupt[12] ^= 0x01; await upload(master, corrupt, false);
|
||||
await reply(master, command('end'), 0x47);
|
||||
await imageValues(master, 1, 0xcbf43926);
|
||||
await reply(master, command('cancel'), 9);
|
||||
|
||||
await reply(master, command('start'), 7);
|
||||
const payload = Buffer.alloc(2800);
|
||||
for (let i = 0; i < payload.length; ++i) payload[i] = (i * 31 + 7) & 255;
|
||||
await upload(master, packageBytes(2, payload));
|
||||
await imageValues(master, 1, 0xcbf43926); // COMMIT完成只形成候选,不能提前发布当前运行映像。
|
||||
const closed = once(master.socket, 'close');
|
||||
await reply(master, command('end'), 7); // readASDU发出的ACK允许领取授权,随后等待旧连接关闭。
|
||||
await closed; assert(!item.done, 'Upgrade must rebuild the protocol, not end the host process');
|
||||
master = await connect(port, 2);
|
||||
await imageValues(master, 2, crc32(payload));
|
||||
|
||||
// 普通105复位只重建协议,必须保留已经成功激活的版本及CRC。
|
||||
const resetClosed = once(master.socket, 'close');
|
||||
await reply(master, Buffer.from([105, 1, 6, 0x74, 7, 0, 0, 0, 0, 1]), 7);
|
||||
await resetClosed; master = await connect(port, 2);
|
||||
await imageValues(master, 2, crc32(payload));
|
||||
|
||||
// 成功收尾必须释放设备owner;第二次最小包升级同时验证 owner 复用和17字节下界。
|
||||
await reply(master, command('start'), 7);
|
||||
const minimum = Buffer.from([0xa7]); await upload(master, packageBytes(3, minimum));
|
||||
const nextClosed = once(master.socket, 'close');
|
||||
await reply(master, command('end'), 7); await nextClosed;
|
||||
master = await connect(port, 2); await imageValues(master, 3, crc32(minimum));
|
||||
await reply(master, command('cancel'), 9); await master.close(); await finish(item);
|
||||
assert.match(item.output, /SOFTWARE_UPGRADE .*restarts_released=2/);
|
||||
assert.match(item.output, /SOFTWARE_UPGRADE .*version=3/);
|
||||
console.log('SoftwareUpgrade TCP loopback passed: Type210 upload, validation/rejection, ACK restart, Type202 identity, 105 preservation, owner reuse');
|
||||
}
|
||||
exercise().catch(error => {
|
||||
console.error(error);
|
||||
for (const item of children) console.error(item.output, item.errors);
|
||||
process.exitCode = 1;
|
||||
}).finally(async () => {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
for (const item of children) { clearTimeout(item.timer); if (!item.done) item.child.kill(); }
|
||||
await Promise.allSettled(children.map(item => item.exit));
|
||||
});
|
||||
Reference in New Issue
Block a user