/* DTU feature integration over real TCP. All mutable artifacts stay in .build. */ '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, parameterRequest } = 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 store = fs.mkdtempSync(path.join(root, '.build', 'dtu-features-')); const address = n => Buffer.from([n & 255, (n >> 8) & 255, (n >> 16) & 255]); const u32 = n => { const b = Buffer.alloc(4); b.writeUInt32LE(n); return b; }; const named = s => { const b = Buffer.from(s, 'ascii'); return Buffer.concat([Buffer.from([b.length]), b]); }; const request = (type, ioa, data = [], cot = 6) => Buffer.concat([Buffer.from([type, 1, cot, 0, 7, 0]), address(ioa), Buffer.from(data)]); const fileHead = (op, cot) => Buffer.from([210, 1, cot, 0, 7, 0, 0, 0, 0, 2, op]); const cp56 = (day, hour = 0, minute = 0, second = 0) => { const b = Buffer.from([0, 0, minute, hour, day, 1, 90]); b.writeUInt16LE(second * 1000); return b; }; const seen = []; const children = []; async function launch(extra = []) { const child = spawn(executable, ['--port', '0', '--ca', '7', '--events', '0', '--background-ms', '0', '--run-ms', '120000', ...extra], { cwd: root, windowsHide: true, 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.exit.catch(() => {}); state.timer = setTimeout(() => child.kill(), 125000); children.push(state); for (let attempt = 0; attempt < 1000; ++attempt) { 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); } throw Error(`DTU listener missing: ${state.output}\n${state.errors}`); } async function stop(state) { state.sockets.forEach(socket => socket.destroy()); if (state.child.exitCode === null) state.child.kill(); await state.exit; clearTimeout(state.timer); assert.equal(state.errors, ''); } async function connect(state, coi = 0) { let socket; for (let i = 0; i < 100; ++i) { socket = net.connect({ host: '127.0.0.1', port: state.port }); state.sockets.push(socket); try { await once(socket, 'connect'); break; } catch (e) { socket.destroy(); if (e.code !== 'ECONNREFUSED' || i === 99) throw e; await delay(20); } } const m = new Master(socket); m.asynchronous = true; await m.control(7, 11); assert.deepEqual(await m.readASDU(), Buffer.from([70, 1, 4, 0, 7, 0, 0, 0, 0, coi])); return m; } async function until(m, predicate) { const deadline = Date.now() + 10000; for (let i = 0; i < 4000; ++i) { const a = await m.readASDU(); assert.equal(a.readUInt16LE(4), 7); seen.push(a); if (predicate(a)) return a; assert(Date.now() < deadline, `Response timeout; recent frames ${seen.slice(-5).map(b => b.toString('hex')).join(' ')}`); } throw Error('Expected DTU response missing'); } async function reply(m, bytes, cot = 7) { await m.send(bytes); const a = await until(m, b => b[0] === bytes[0] && (b[2] & 63) !== 20); assert.equal(a[2], cot, `Type ${bytes[0]} response: ${a.toString('hex')}`); return a; } async function gi(m, qoi = 20) { await m.send(request(100, 0, [qoi])); const frames = []; let confirmed = false; for (let i = 0; i < 1000; ++i) { const a = await until(m, () => true); if (a[0] === 100 && a[2] === 7) { confirmed = true; continue; } if (a[0] === 100 && a[2] === 10) { assert(confirmed); return frames; } if (a[2] === qoi) frames.push(a); } throw Error('GI not terminated'); } async function read(m, ioa, type) { await m.send(request(102, ioa, [], 5)); return until(m, a => a[0] === type && a[2] === 5 && a.readUIntLE(6, 3) === ioa); } async function sbo(m, type, ioa, value, timed = false) { const payload = select => Buffer.concat([Buffer.from([value | ([47, 60].includes(type) ? 0 : 12) | (select ? 128 : 0)]), timed ? cp56(1) : Buffer.alloc(0)]); await reply(m, request(type, ioa, payload(true))); await reply(m, request(type, ioa, payload(false))); await until(m, a => a[0] === type && a[2] === 10); } async function sync(m, day, hour = 0, minute = 0, second = 0) { await reply(m, request(103, 0, cp56(day, hour, minute, second))); await delay(30); } async function directory(m, name) { await m.send(Buffer.concat([fileHead(1, 5), u32(42), named(name), Buffer.alloc(15)])); const entries = []; for (let page = 0; page < 100; ++page) { const a = await until(m, b => b[0] === 210 && b[10] === 2); assert.equal(a[2], 5); assert.equal(a[11], 0); assert.equal(a.readUInt32LE(12), 0); let p = 18; for (let i = 0; i < a[17]; ++i) { const n = a[p++], filename = a.subarray(p, p + n).toString('ascii'); p += n; assert.equal(a[p++], 0); const size = a.readUInt32LE(p); p += 11; entries.push({ name: filename, size }); } assert.equal(p, a.length); if (!a[16]) return entries; } throw Error('Directory pagination overflow'); } async function download(m, entry) { await m.send(Buffer.concat([fileHead(3, 6), named(entry.name)])); const active = await until(m, a => a[0] === 210 && a[10] === 4); assert.equal(active[2], 7); assert.equal(active[11], 0); const p = 13 + active[12]; assert.equal(active.subarray(13, p).toString(), entry.name); assert.equal(active.readUInt32LE(p + 4), entry.size); const chunks = []; let offset = 0; for (let segment = 0; segment < 10000; ++segment) { const a = await until(m, b => b[0] === 210 && b[10] === 5); assert.equal(a.readUInt32LE(15), offset); const bytes = a.subarray(20, -1); assert.equal(a.at(-1), bytes.reduce((sum, b) => (sum + b) & 255, 0)); chunks.push(bytes); offset += bytes.length; if (!a[19]) { assert.equal(offset, entry.size); await m.send(Buffer.concat([fileHead(6, 5), u32(0), a.subarray(15, 19), Buffer.from([0])])); return Buffer.concat(chunks); } } throw Error('File did not terminate'); } async function upload(m, name, bytes) { await m.send(Buffer.concat([fileHead(7, 6), named(name), u32(17), u32(bytes.length)])); const active = await until(m, a => a[0] === 210 && a[10] === 8); assert.equal(active[2], 7); assert.equal(active[11], 0); const burst = []; for (let offset = 0; offset < bytes.length; offset += 228) { const part = bytes.subarray(offset, offset + 228); burst.push(m.frame(Buffer.concat([fileHead(9, 5), u32(17), u32(offset), Buffer.from([offset + part.length < bytes.length ? 1 : 0]), part, Buffer.from([part.reduce((sum, b) => (sum + b) & 255, 0)])]))); } m.socket.write(Buffer.concat(burst)); const complete = await until(m, a => a[0] === 210 && a[10] === 10); assert.equal(complete[2], 7); assert.equal(complete[19], 0); } async function controlsAndScans() { const state = await launch(['--command-extensions', '--cyclic-ms', '100', '--background-ms', '150', '--sequence']); try { let m = await connect(state); await sync(m, 1); const all = await gi(m); assert.equal(all.filter(a => a[0] >= 110 && a[0] <= 112).reduce((n, a) => n + (a[1] & 127), 0), 120); const signals = await gi(m, 21); assert(signals.some(a => a[0] === 1)); const measurements = await gi(m, 22); assert(measurements.some(a => a[0] === 13)); for (const type of [110, 111, 112]) { const ioa = type === 110 ? 0x8605 : type === 111 ? 0x8601 : 0x8661; await reply(m, parameterRequest(type, ioa, type === 112 ? 0.5 : 200, type === 112 ? 2 : 1)); } await reply(m, parameterRequest(113, 0x4004, 0, 3, 8), 9); const causes = new Set(); while (causes.size < 2) { const a = await until(m, b => b[0] === 13 && [1, 2].includes(b[2])); causes.add(a[2]); if (a[2] === 1) { const first = a.readUIntLE(6, 3), count = a[1] & 127; if (a[1] & 128) assert(!(first <= 0x4004 && first + count > 0x4004)); } } await reply(m, parameterRequest(113, 0x4004, 0, 3)); await sbo(m, 47, 0x6101, 2); assert.equal((await read(m, 0x1201, 5))[9] & 127, 1); await reply(m, parameterRequest(112, 0x8661, 0, 2)); const setting = Buffer.alloc(3); setting.writeInt16LE(2500); setting[2] = 128; await reply(m, request(49, 0x6201, setting)); setting[2] = 0; await reply(m, request(49, 0x6201, setting)); await until(m, a => a[0] === 49 && a[2] === 10); assert.equal((await read(m, 0x4001, 13)).readFloatLE(9), 25); await reply(m, request(51, 0x6301, u32(0x80000001))); await until(m, a => a[0] === 51 && a[2] === 10); assert.equal((await read(m, 0x1301, 7)).readUInt32LE(9), 0x80000001); await sbo(m, 59, 0x6002, 1, true); assert.equal((await read(m, 0x1001, 31))[9] & 3, 1); await sbo(m, 58, 0x6001, 1, true); assert.equal((await read(m, 9, 30))[9] & 1, 1); await reply(m, request(104, 0, [0xaa, 0x55])); await reply(m, request(107, 0, Buffer.concat([Buffer.from([1, 0]), cp56(1)]))); await reply(m, request(105, 0, [2])); const closed = once(m.socket, 'close'); await reply(m, request(105, 0, [1])); await closed; m = await connect(state, 2); await gi(m); assert.equal((await read(m, 0x4001, 13)).readFloatLE(9), 24); await m.send(request(101, 0, [5])); for (;;) { const a = await until(m, b => b[0] === 101 || b[0] === 206); if (a[0] === 101 && a[2] === 10) break; if (a[0] === 206) { let p = 6; for (let i = 0; i < (a[1] & 127); ++i) { if (!i || !(a[1] & 128)) p += 3; assert.equal(a.readFloatLE(p), 0); p += 5; } } } await m.control(0x13, 0x23); await m.control(7, 11); await gi(m); await m.close(); console.log('DTU controls/scans: GI groups, 110-113, COT1/2, 47/49/51/58/59, 102, 104/107, 105, STOP/START passed.'); } finally { await stop(state); } } async function counters() { for (const type of [15, 37, 206, 207]) { const state = await launch(['--counter-type', String(type), '--no-parameter']); try { const m = await connect(state); await gi(m); for (const qcc of [5, 0x45, 0x85, 0xc5]) { if (qcc !== 5) { await reply(m, request(101, 0, [qcc])); } await m.send(request(101, 0, [5])); let count = 0; for (;;) { const a = await until(m, () => true); if (a[0] === 101 && a[2] === 10) break; if (a[0] === 101) { assert.equal(a[2], 7); continue; } assert.equal(a[0], type); count += a[1] & 127; } assert.equal(count, 8); } await m.close(); } finally { await stop(state); } } console.log('DTU counters: Type15/37/206/207 read, freeze, freeze-reset and reset passed.'); } async function floatingFreeze() { const state = await launch(['--events', '100', '--counter-type', '207', '--no-parameter']); try { const m = await connect(state); await sync(m, 1); await gi(m); const snapshot = async () => { await m.send(request(101, 0, [5])); const result = new Map(); let confirmed = false; for (;;) { const a = await until(m, b => b[0] === 101 || b[0] === 207); if (a[0] === 101) { if (a[2] === 7) { confirmed = true; continue; } assert.equal(a[2], 10); assert(confirmed); assert.equal(result.size, 8); return result; } assert(confirmed); assert.equal(a[2], 37); let p = 6, ioa; for (let i = 0; i < (a[1] & 127); ++i) { if (!i || !(a[1] & 128)) { ioa = a.readUIntLE(p, 3); p += 3; } else ioa++; assert(!result.has(ioa)); assert.equal(a[p + 4], 0); result.set(ioa, { value: a.readFloatLE(p), time: Buffer.from(a.subarray(p + 5, p + 12)) }); p += 12; } assert.equal(p, a.length); } }; await delay(1150); await reply(m, request(101, 0, [0x45])); const first = await snapshot(); assert(first.get(0x6401).value > 0 && first.get(0x6402).value > 0, 'Physical P/Q integration must survive conversion to the floating frozen snapshot'); await delay(1150); assert.deepEqual(await snapshot(), first, 'Type207 must retain both frozen values and original CP56 times'); await reply(m, request(101, 0, [0x85])); const second = await snapshot(); assert(second.get(0x6401).value > first.get(0x6401).value, 'FRZ2 must freeze accumulated growth before clearing current values'); assert.notDeepEqual(second.get(0x6401).time, first.get(0x6401).time); await reply(m, request(101, 0, [0xc5])); assert.deepEqual(await snapshot(), second, 'FRZ3 must clear current values without changing the frozen snapshot'); await reply(m, request(101, 0, [0x85])); const cleared = await snapshot(); assert(cleared.get(0x6401).value < second.get(0x6401).value * 0.5, 'A fresh FRZ2 after reset must publish the cleared current accumulator, not the previous frozen value'); await m.close(); console.log('DTU floating freeze: nonzero physical P/Q, Type207 retained values/timestamps and FRZ1/2/3 semantics passed.'); } finally { await stop(state); } } async function storage() { const config = path.join(store, 'config.ini'); const extra = ['--config', config, '--history', store, '--user-log', store, '--recording-demo', store, '--energy-freeze', store, '--energy-period-ms', '2000', '--no-parameter']; let state = await launch(extra); const saved = new Map(), payload = Buffer.from(Array.from({ length: 3001 }, (_, i) => (i * 19) & 255)); try { const m = await connect(state); await gi(m); await sync(m, 1); await sbo(m, 46, 0x6002, 1); await sbo(m, 46, 0x6002, 2); await upload(m, 'TEMP/dtu.bin', payload); const temporary = (await directory(m, 'TEMP')).find(e => e.name === 'TEMP/dtu.bin'); assert(temporary); assert.deepEqual(await download(m, temporary), payload); const recording = await directory(m, 'COMTRADE'); assert.equal(recording.length, 2); const files = new Map(); for (const entry of recording) { const bytes = await download(m, entry); files.set(path.extname(entry.name), bytes); assert.deepEqual(bytes, fs.readFileSync(path.join(store, entry.name))); } const cfg = files.get('.cfg').toString('ascii'), dat = files.get('.dat'); assert.match(cfg, /1999\r\n24,8A,16D\r\n/); assert.match(cfg, /4000,961\r\n/); assert.equal(dat.length, 961 * 26); for (let i = 0; i < 961; ++i) { assert.equal(dat.readUInt32LE(i * 26), i + 1); assert.equal(dat.readUInt32LE(i * 26 + 4), i * 250); } assert(seen.some(a => a[0] === 42 && a[2] === 3), 'Recording needs a Type42 report'); for (const [directoryName, ioa] of [['HISTORY/SOE', 0x11], ['HISTORY/CO', 0x6002]]) { const entries = await directory(m, directoryName); assert.equal(entries.length, 1); const xml = (await download(m, entries[0])).toString('utf8'); assert.match(xml, / e.name.endsWith('20900101.xml')); assert(entry, directoryName); const bytes = await download(m, entry); const xml = bytes.toString(); assert.match(xml, / e.name === 'TEMP/dtu.bin'); assert(temporary); assert.deepEqual(await download(m, temporary), payload); for (const [name, bytes] of saved) assert.deepEqual(await download(m, { name, size: bytes.length }), bytes); await m.close(); } finally { await stop(state); } console.log(`DTU storage: TEMP persistence, SOE/CO/ULOG/FIXPT/EXV/FRZ/FLOWREV, Type42 and COMTRADE passed. Artifacts: ${store}`); } async function upgradeRegression(script) { const child = spawn(process.execPath, [path.join(__dirname, script), executable], { cwd: root, windowsHide: true, stdio: 'inherit' }); const [code] = await once(child, 'close'); assert.equal(code, 0, script); } async function stress() { const state = await launch(['--simulation', 'stress', '--events', '5', '--no-parameter']); try { const m = await connect(state); await gi(m); const observed = new Set(), deadline = Date.now() + 1300; while (Date.now() < deadline) { const a = await until(m, b => b[2] === 3); observed.add(a[0]); } assert(observed.has(30) && observed.has(13)); await read(m, 0x401e, 13); await m.close(); console.log('DTU stress: full 59-SP/30-YC index rotation and spontaneous Type30/13 passed.'); } finally { await stop(state); } } async function main() { await controlsAndScans(); await counters(); await floatingFreeze(); await stress(); await storage(); await upgradeRegression('software_upgrade_loopback_test.cjs'); await upgradeRegression('firmware_update_loopback_test.cjs'); } main().catch(error => { console.error(error); for (const state of children) console.error(state.output, state.errors); process.exitCode = 1; }).finally(async () => { for (const state of children) { clearTimeout(state.timer); state.sockets.forEach(s => s.destroy()); if (state.child.exitCode === null) state.child.kill(); } });