/* Independent DTU XML and wire regression. No external packages or target hardware. */ 'use strict'; const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const net = require('node:net'); const { spawn } = require('node:child_process'); const { once } = require('node:events'); const { setTimeout: delay } = require('node:timers/promises'); const { Master } = require('./slave_example_loopback_test.cjs'); const root = path.resolve(__dirname, '..'); const executable = path.resolve(process.argv[2]); const relative = path.relative(path.join(root, '.build'), executable); assert(relative && !relative.startsWith('..') && !path.isAbsolute(relative)); const source = path.join(root, fs.readdirSync(root).find(name => name.startsWith('DTU'))); const parameters = new Map(); const signals = [], measurements = [], commands = [], counters = []; let emptyFiles = 0, definitions = 0; function readXml(directory) { for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { const filename = path.join(directory, entry.name); if (entry.isDirectory()) { readXml(filename); continue; } if (!entry.name.endsWith('.xml')) continue; const xml = fs.readFileSync(filename, 'utf8'); if (!xml.length) { emptyFiles++; continue; } for (const match of xml.matchAll(/]+)>([^<]*)<\/Item>/g)) { const attrs = Object.fromEntries([...match[1].matchAll(/(\w+)="([^"]*)"/g)].map(m => [m[1], m[2]])); const addr = Number(attrs.addr), value = match[2].trim(); const pointFile = filename.includes('\u70b9\u8868\u53c2\u6570'); definitions++; if (pointFile) { const point = { source: addr, ioa: value ? parseInt(value, 16) : null }; if (entry.name.startsWith('01_')) signals.push(point); else if (entry.name.startsWith('02_')) measurements.push(point); else if (entry.name.startsWith('03_')) commands.push(point); else counters.push(point); } if (value) { assert(!parameters.has(addr), `Duplicate source parameter ${attrs.addr}`); const tag = pointFile ? 45 : { Boolean: 1, UInt: 35, UShort: 45, Float: 38 }[attrs.tag]; assert(tag, `Unexpected source type ${attrs.tag}`); parameters.set(addr, { tag, value: pointFile ? parseInt(value, 16) : Number(value) }); } } } } readXml(source); assert.equal(emptyFiles, 4); assert.equal(definitions, 430); assert.equal(parameters.size, 345); assert.equal(signals.filter(x => x.ioa !== null).length, 59); assert.equal(commands.filter(x => x.ioa !== null).length, 19); assert.equal(measurements.length, 30); assert.equal(counters.length, 4); const addr = value => Buffer.from([value & 255, (value >> 8) & 255, (value >> 16) & 255]); const u16 = value => { const b = Buffer.alloc(2); b.writeUInt16LE(value); return b; }; const head = (type, count = 1, cot = 6) => Buffer.from([type, count, cot, 0, 7, 0]); const request = (type, ioa, value = [], cot = 6) => Buffer.concat([head(type, 1, cot), addr(ioa), Buffer.from(value)]); const closeTo = (actual, expected, label) => assert(Math.abs(actual - expected) <= Math.max(1e-6, Math.abs(expected) * 1e-6), `${label}: ${actual} != ${expected}`); async function launch(events, runMs) { const child = spawn(executable, ['--port', '0', '--ca', '7', '--k', '1', '--events', String(events), '--run-ms', String(runMs)], { windowsHide: true, cwd: root, stdio: ['ignore', 'pipe', 'pipe'] }); const state = { child, output: '', errors: '', sockets: [] }; child.stdout.on('data', b => { state.output += b; }); child.stderr.on('data', b => { state.errors += b; }); state.exit = once(child, 'close'); state.timer = setTimeout(() => child.kill(), runMs + 5000); for (let i = 0; i < 300; ++i) { const found = state.output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/); if (found) { state.port = Number(found[1]); return state; } if (child.exitCode !== null) break; await delay(10); } cleanup(state); throw new Error(`No DTU listener: ${state.output}\n${state.errors}`); } function cleanup(state) { clearTimeout(state.timer); for (const socket of state.sockets) socket.destroy(); if (state.child.exitCode === null) state.child.kill(); } async function connect(state) { const socket = net.connect({ host: '127.0.0.1', port: state.port }); socket.on('data', b => { state.lastWire = b.toString('hex'); }); state.sockets.push(socket); const master = new Master(socket); master.asynchronous = true; await once(socket, 'connect'); await master.control(7, 0x0b); const init = await master.readASDU(); assert.equal(init[0], 70); assert.equal(init[2], 4); return master; } async function until(master, predicate) { for (let i = 0; i < 600; ++i) { const asdu = await master.readASDU(); assert.equal(asdu.readUInt16LE(4), 7); if (predicate(asdu)) return asdu; } throw new Error('Response did not arrive'); } function objects(asdu, size, decode) { const result = []; let offset = 6, ioa; for (let i = 0; i < (asdu[1] & 127); ++i) { if (!i || !(asdu[1] & 128)) { ioa = asdu.readUIntLE(offset, 3); offset += 3; } else ioa++; result.push([ioa, decode(asdu, offset)]); offset += size; } assert.equal(offset, asdu.length); return result; } async function gi(master) { await master.send(request(100, 0, [20])); const result = { signals: new Map(), measurements: new Map(), doubles: new Map(), steps: new Map(), bits: new Map(), parameters: new Map() }; for (let i = 0; i < 500; ++i) { const asdu = await master.readASDU(); if (asdu[0] === 100 && asdu[2] === 10) return result; if (asdu[0] === 100) { assert.equal(asdu[2], 7); continue; } if (asdu[2] !== 20) continue; const schema = { 1: ['signals', 1, (b, p) => b[p]], 3: ['doubles', 1, (b, p) => b[p]], 5: ['steps', 2, (b, p) => b[p] & 127], 7: ['bits', 5, (b, p) => b.readUInt32LE(p)], 13: ['measurements', 5, (b, p) => { assert.equal(b[p + 4], 0); return b.readFloatLE(p); }], 110: ['parameters', 3, (b, p) => b.readInt16LE(p)], 111: ['parameters', 3, (b, p) => b.readInt16LE(p)], 112: ['parameters', 5, (b, p) => b.readFloatLE(p)] }[asdu[0]]; assert(schema, `Unexpected DTU GI type ${asdu[0]}`); const entries = objects(asdu, schema[1], schema[2]); const target = result[schema[0]]; for (const [ioa, value] of entries) { assert(!target.has(ioa)); target.set(ioa, value); } } throw new Error('GI did not terminate'); } async function read(master, ioa, type) { await master.send(request(102, ioa, [], 5)); return until(master, asdu => asdu[0] === type && asdu[2] === 5 && asdu.readUIntLE(6, 3) === ioa); } async function readParameters(master, addresses = []) { await master.send(Buffer.concat([head(202, addresses.length), u16(0), ...addresses.map(addr)])); const result = new Map(); for (let i = 0; i < 100; ++i) { const b = await until(master, a => a[0] === 202); assert.equal(b[2], 7); assert.equal(b.readUInt16LE(6), 0); let offset = 9; for (let n = 0; n < b[1]; ++n) { const ioa = b.readUIntLE(offset, 3), tag = b[offset + 3], length = b[offset + 4]; offset += 5; const expectedLength = { 1: 1, 35: 4, 45: 2, 38: 4 }[tag]; assert.equal(length, expectedLength, `Parameter ${ioa.toString(16)} TLV`); const value = tag === 38 ? b.readFloatLE(offset) : b.readUIntLE(offset, length); assert(!result.has(ioa)); result.set(ioa, { tag, value }); offset += length; } assert.equal(offset, b.length); if (!(b[8] & 1)) return result; } throw new Error('Parameter read did not terminate'); } async function control(master, type, ioa, value) { for (const select of [true, false]) { await master.send(request(type, ioa, [value | 12 | (select ? 128 : 0)])); const ack = await until(master, b => b[0] === type && b.readUIntLE(6, 3) === ioa); assert.equal(ack[2], 7); if (!select) await until(master, b => b[0] === type && b[2] === 10); } } async function synchronize(master) { // Application clock only: 2026-01-01 00:00:00 local, valid CP56 without weekday. const sync = request(103, 0, [0, 0, 0, 0, 1, 1, 26]); await master.send(sync); const reply = await until(master, a => a[0] === 103); const expected = Buffer.from(sync); expected[2] = 7; assert.deepEqual(reply, expected); } async function readEnergy(master) { await master.send(request(101, 0, [5])); const energy = new Map(); let confirmed = false, terminated = false; for (let i = 0; i < 100; ++i) { const a = await master.readASDU(); if (a[0] === 101 && a[2] === 7) { confirmed = true; continue; } if (a[0] === 101 && a[2] === 10) { terminated = true; break; } if (a[0] === 206) { assert(confirmed, 'CI data before confirmation'); for (const [ioa, count] of objects(a, 5, (b, p) => b.readFloatLE(p))) { assert(!energy.has(ioa), 'Duplicate energy point'); energy.set(ioa, count); } } } assert(confirmed && terminated, 'CI must confirm and terminate'); assert.deepEqual([...energy.keys()], Array.from({ length: 8 }, (_, i) => 0x6401 + i)); return energy; } async function staticCase() { const state = await launch(0, 20000); try { let master = await connect(state); await synchronize(master); const points = await gi(master); assert.deepEqual([...points.signals.keys()].sort((a, b) => a - b), signals.filter(p => p.ioa !== null).map(p => p.ioa).sort((a, b) => a - b)); assert.deepEqual([...points.measurements.keys()], measurements.map((_, i) => 0x4001 + i)); assert.deepEqual([...points.doubles.keys()], Array.from({ length: 16 }, (_, i) => 0x1001 + i)); assert.equal((await read(master, 0x1201, 5))[9], 0); assert.equal((await read(master, 0x1301, 7)).readUInt32LE(9), 0); assert.equal(points.parameters.size, 120); for (const [sourceAddr, expected] of [[0x960a, 100], [0x9613, 100], [0x960d, 50], [0x9616, 50], [0x961f, 0.4], [0x9622, 0.4]]) { const ioa = 0x4001 + measurements.findIndex(p => p.source === sourceAddr); closeTo(points.measurements.get(ioa), expected, `GI ${ioa}`); closeTo((await read(master, ioa, 13)).readFloatLE(9), expected, `Read ${ioa}`); } const saved = await readParameters(master); assert.equal(saved.size, parameters.size); for (const [ioa, expected] of parameters) { assert(saved.has(ioa), `Missing source parameter ${ioa.toString(16)}`); assert.equal(saved.get(ioa).tag, expected.tag, `Parameter ${ioa.toString(16)} tag`); closeTo(saved.get(ioa).value, expected.value, `Parameter ${ioa.toString(16)}`); } await master.send(Buffer.concat([head(201), addr(0)])); const area = await until(master, a => a[0] === 201); assert.equal(area[2], 7); assert.deepEqual([...area.subarray(9)], [0, 0, 0, 0, 4, 0]); // An empty XML field is unknown, not a fabricated zero or a mapping-parameter IOA. await master.send(Buffer.concat([head(202), u16(0), addr(0x9601)])); assert.equal((await until(master, a => a[0] === 202))[2] & 0x40, 0x40); // Source diagnostics are a separate Read102 namespace; paused sampling is IV. assert.equal((await read(master, 0x9601, 13))[13] & 0x80, 0x80); await master.send(request(102, 0x961c, [], 5)); const unknownRead = await until(master, a => a[0] === 102); assert.equal(unknownRead[2] & 0x3f, 47); assert.equal(unknownRead[2] & 0x40, 0x40); // Point-map identities stay read-only; writable settings have a separate regression. await master.send(Buffer.concat([head(203), u16(0), Buffer.from([128]), addr(0x9806), Buffer.from([45, 2]), u16(0x6003)])); assert.equal((await until(master, a => a[0] === 203))[2] & 0x40, 0x40); assert.equal((await readParameters(master, [0x9806])).get(0x9806).value, 0x6002); assert.deepEqual([...(await readEnergy(master)).values()], Array(8).fill(0)); // A direct execute must fail; the same point succeeds after selection. await master.send(request(46, 0x6002, [1 | 12])); assert.equal((await until(master, a => a[0] === 46))[2] & 0x40, 0x40); await control(master, 46, 0x6002, 1); assert.equal((await read(master, 0x11, 30))[9], 0); assert.equal((await read(master, 0x28, 30))[9], 1); await control(master, 46, 0x6002, 2); assert.equal((await read(master, 0x11, 30))[9], 1); assert.equal((await read(master, 0x28, 30))[9], 0); await control(master, 45, 0x6001, 1); assert.equal((await read(master, 0x9, 30))[9], 1); await master.close(); master = await connect(state); assert.equal((await gi(master)).signals.get(0x11), 1); await master.close(); const [code] = await state.exit; assert.equal(code, 0, `${state.output}\n${state.errors}`); assert.equal(state.errors, ''); console.log('DTU: XML 430 definitions/345 values, 59 SP, 16 DP, 30 YC, 120 parameters, 8 energy, SBO and reconnect passed.'); } catch (error) { console.error(state.output, state.errors, 'last APDU', state.lastWire); throw error; } finally { cleanup(state); } } async function dynamicCase() { const state = await launch(100, 18000); try { const master = await connect(state); await synchronize(master); await gi(master); const alarms = new Map(); let faultCurrent = false; const end = Date.now() + 14000; while (Date.now() < end && alarms.size < 3) { // Polling also keeps a quiet channel active while waiting for timed simulation. await master.send(request(102, 0x4015, [], 5)); const a = await master.readASDU(); if (a[0] === 30 && a[2] === 3) { for (const [ioa, item] of objects(a, 8, (b, p) => ({ value: b[p], time: b.readUInt16LE(p + 1) + 60000 * (b[p + 3] & 63) + 3600000 * (b[p + 4] & 31) }))) { if (ioa >= 0x39 && ioa <= 0x3b && item.value === 1 && !alarms.has(ioa)) alarms.set(ioa, item.time); } } if (a[0] === 13) { for (const [ioa, value] of objects(a, 5, (b, p) => b.readFloatLE(p))) { if (ioa === 0x4015 && value > 1.2) faultCurrent = true; } } await delay(20); } assert.deepEqual([...alarms.keys()], [0x39, 0x3a, 0x3b]); // CP56 event times avoid conflating network backpressure with protection delays. const delta = (later, earlier) => (alarms.get(later) - alarms.get(earlier) + 86400000) % 86400000; assert(Math.abs(delta(0x3a, 0x39) - 500) <= 200, 'OC2 must follow OC1 by 0.5 s'); assert(Math.abs(delta(0x3b, 0x3a) - 1000) <= 200, 'OC3 must follow OC2 by 1 s'); assert(faultCurrent, 'Simulation must expose the overcurrent measurement'); assert.equal((await read(master, 0x11, 30))[9], 1, 'Exit disabled: alarm must not open breaker'); assert.equal((await read(master, 0x28, 30))[9], 0); const energy = await readEnergy(master); assert(energy.get(0x6401) > 0 && energy.get(0x6402) > 0, 'Forward active/reactive energy must accumulate'); await master.close(); const [code] = await state.exit; assert.equal(code, 0, `${state.output}\n${state.errors}`); assert.equal(state.errors, ''); console.log('DTU: timed three-stage overcurrent alarms without automatic trip passed.'); } catch (error) { console.error(state.output, state.errors); throw error; } finally { cleanup(state); } } staticCase().then(dynamicCase).catch(error => { console.error(error); process.exitCode = 1; });