/* Real TCP regression for DTU settings and the shared atomic INI. * Usage: node test/dtu_settings_loopback_test.cjs .build//iec104_dtu_example.exe */ 'use strict'; const assert = require('node:assert/strict'); const fs = require('node:fs'); const net = require('node:net'); const path = require('node:path'); const { spawn } = require('node:child_process'); const { once } = require('node:events'); const { setTimeout: delay } = require('node:timers/promises'); const { Master } = require('./slave_example_loopback_test.cjs'); const root = path.resolve(__dirname, '..'); const build = path.join(root, '.build'); const executable = path.resolve(process.argv[2]); const relative = path.relative(build, executable); assert(relative && !relative.startsWith('..') && !path.isAbsolute(relative)); const directory = fs.mkdtempSync(path.join(build, 'dtu-settings-')); const config = path.join(directory, 'device.ini'); const children = [], sockets = []; const head = (type, count = 1, cot = 6) => Buffer.from([type, count, cot, 0x72, 7, 0]); const u16 = value => { const b = Buffer.alloc(2); b.writeUInt16LE(value); return b; }; const addr = value => Buffer.from([value & 255, value >> 8 & 255, value >> 16 & 255]); const f32 = value => { const b = Buffer.alloc(4); b.writeFloatLE(value); return b; }; const element = (ioa, tag, bytes) => Buffer.concat([addr(ioa), Buffer.from([tag, bytes.length]), bytes]); const floatElement = (ioa, value) => element(ioa, 38, f32(value)); const preset = (sn, entries, more = false, test = false) => Buffer.concat([ head(203, entries.length, test ? 0x86 : 6), u16(sn), Buffer.from([more ? 0x81 : 0x80]), ...entries]); const finish = (sn, cancel = false, test = false) => Buffer.concat([ head(203, 0, (cancel ? 8 : 6) | (test ? 0x80 : 0)), u16(sn), Buffer.from([0])]); const switchArea = (sn, test = false) => Buffer.concat([head(200, 1, test ? 0x86 : 6), addr(0), u16(sn)]); const read = (sn, addresses = []) => Buffer.concat([head(202, addresses.length), u16(sn), ...addresses.map(addr)]); const closeTo = (actual, expected) => assert(Math.abs(actual - expected) < 0.00001, `${actual} != ${expected}`); function launch(runMs = 6500) { const child = spawn(executable, ['--port', '0', '--ca', '7', '--events', '0', '--background-ms', '0', '--run-ms', String(runMs), '--config', config], { cwd: root, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); const state = { child, output: '', errors: '' }; child.stdout.on('data', data => { state.output += data; }); child.stderr.on('data', data => { state.errors += data; }); state.exit = once(child, 'close'); state.exit.catch(() => {}); state.timer = setTimeout(() => child.kill(), runMs + 5000); children.push(state); return state; } async function listener(state) { for (let attempt = 0; attempt < 300; ++attempt) { const match = state.output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/); if (match) return Number(match[1]); if (state.child.exitCode !== null) break; await delay(10); } throw new Error(`No listener: ${state.output}\n${state.errors}`); } async function connect(port) { 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); assert.deepEqual([...await master.readASDU()], [70, 1, 4, 0, 7, 0, 0, 0, 0, 0]); return master; } async function mirror(master, request, cot = 7, cancel = false) { const expected = Buffer.from(request); expected[2] = cot | (request[2] & 0x80); if (cancel) expected[8] = 0x40; await master.send(request); assert.deepEqual(await master.readASDU(), expected); } async function area(master, expected) { await master.send(Buffer.concat([head(201), addr(0)])); assert.deepEqual([...await master.readASDU()], [201, 1, 7, 0x72, 7, 0, 0, 0, 0, expected, 0, 0, 0, 4, 0]); } async function values(master, sn, addresses = []) { await master.send(read(sn, addresses)); const result = new Map(); for (let frames = 0; frames < 40; ++frames) { const frame = await master.readASDU(); assert.equal(frame[0], 202); assert.equal(frame[2], 7); assert.equal(frame.readUInt16LE(6), sn); assert.equal(frame[8] & ~1, 0); let offset = 9; for (let i = 0; i < frame[1]; ++i) { const ioa = frame.readUIntLE(offset, 3), tag = frame[offset + 3], length = frame[offset + 4]; const bytes = frame.subarray(offset + 5, offset + 5 + length); assert.equal(bytes.length, length); assert(!result.has(ioa), `Duplicate IOA ${ioa}`); const value = tag === 1 ? bytes[0] : tag === 45 ? bytes.readUInt16LE() : tag === 35 ? bytes.readUInt32LE() : bytes.readFloatLE(); result.set(ioa, { tag, value }); offset += 5 + length; } assert.equal(offset, frame.length); if (frame[8] === 0) return result; } throw new Error('Type202 did not terminate'); } async function value(master, sn, ioa) { return (await values(master, sn, [ioa])).get(ioa).value; } async function cancel(master, sn = 4) { await mirror(master, finish(sn, true), 9, true); } async function exercise() { const first = launch(), port = await listener(first); let master = await connect(port); await area(master, 0); assert.equal((await values(master, 0)).size, 345); for (const sn of [1, 2, 3, 4]) { const all = await values(master, sn); assert.equal(all.size, 88); assert([...all.keys()].every(ioa => ioa >= 0x8820 && ioa <= 0x88ff)); closeTo(all.get(0x8842).value, 1.2); } await mirror(master, read(1, [0x8020]), 0x47); // common values are SN0 only await mirror(master, read(0, [0x8001]), 0x47); // source XML contains no terminal name await mirror(master, switchArea(5), 0x47); // A multi-frame preset is invisible until complete SOLIDIFY; repeated IOA is last-wins. await mirror(master, preset(2, [floatElement(0x8842, 2.2)], true)); closeTo(await value(master, 2, 0x8842), 1.2); await mirror(master, finish(2), 0x47); await mirror(master, switchArea(2), 0x47); await mirror(master, preset(2, [floatElement(0x8842, 2.4), floatElement(0x8821, 8)])); await mirror(master, finish(2)); closeTo(await value(master, 2, 0x8842), 2.4); closeTo(await value(master, 0, 0x8842), 1.2); await area(master, 0); // saving a different area must not select it await mirror(master, switchArea(2)); await area(master, 2); await mirror(master, preset(0, [floatElement(0x8020, 0.05)])); await mirror(master, finish(0)); closeTo(await value(master, 0, 0x8020), 0.05); await area(master, 2); // Read-only mapping, wrong tag, unknown address, and a negative value reject the entire batch. for (const invalid of [element(0x9806, 45, u16(0x6003)), element(0x8842, 45, u16(2)), floatElement(0x7777, 2), floatElement(0x8842, -1)]) { await mirror(master, preset(2, [floatElement(0x8821, 55), invalid]), invalid.readUIntLE(0, 3) === 0x7777 ? 0x6f : 0x47); await mirror(master, finish(2), 0x47); await cancel(master); closeTo(await value(master, 2, 0x8821), 8); } await mirror(master, preset(2, [floatElement(0x8821, 66)])); await cancel(master, 1); // cancellation SN differs from the owner SN closeTo(await value(master, 2, 0x8821), 8); await mirror(master, preset(2, [floatElement(0x8821, 77)], false, true)); await mirror(master, finish(2, false, true)); await mirror(master, switchArea(4, true)); await area(master, 2); closeTo(await value(master, 2, 0x8821), 8); // Cross-field validation occurs over the complete candidate; failed solidification discards it. await mirror(master, preset(2, [floatElement(0x8834, 90)])); await mirror(master, finish(2), 0x47); await cancel(master); closeTo(await value(master, 2, 0x8834), 30); // A blocked destination must retain both the original file and the committed runtime value. await mirror(master, preset(2, [floatElement(0x8821, 99)])); const previous = fs.readFileSync(config); fs.renameSync(config, `${config}.saved`); fs.mkdirSync(config); await mirror(master, finish(2), 0x47); fs.rmdirSync(config); fs.renameSync(`${config}.saved`, config); assert.deepEqual(fs.readFileSync(config), previous); await cancel(master); closeTo(await value(master, 2, 0x8821), 8); await mirror(master, preset(2, [floatElement(0x8821, 88)], true)); await master.control(0x13, 0x23); await master.control(7, 0x0b); assert.equal((await master.readASDU())[0], 70); closeTo(await value(master, 2, 0x8821), 8); await mirror(master, preset(2, [floatElement(0x8821, 88)], true)); await master.close(); await delay(60); master = await connect(port); closeTo(await value(master, 2, 0x8821), 8); await mirror(master, preset(2, [floatElement(0x8821, 9)])); await mirror(master, finish(2)); await master.close(); assert.deepEqual(await first.exit, [0, null], `${first.output}\n${first.errors}`); clearTimeout(first.timer); assert.match(first.errors, /REMOTE_CONFIG save failed: io-error/); assert.match(first.output, /REMOTE_SETTINGS reason=solidify target_area=2 current_area=2 reset_seconds=9/); const saved = fs.readFileSync(config, 'utf8'); assert.equal([...saved.matchAll(/^\[parameter_/gm)].length, 120); assert.equal([...saved.matchAll(/^\[dtu_area_/gm)].length, 5); assert.match(saved, /\[dtu\]\ncurrent_area=2\n/); assert.match(saved, /\[temp\]\npresent=0/); assert(!fs.existsSync(`${config}.remote.ini`)); const second = launch(1600); master = await connect(await listener(second)); await area(master, 2); closeTo(await value(master, 2, 0x8821), 9); closeTo(await value(master, 2, 0x8842), 2.4); closeTo(await value(master, 0, 0x8842), 1.2); closeTo(await value(master, 0, 0x8020), 0.05); await master.close(); assert.deepEqual(await second.exit, [0, null], second.errors); clearTimeout(second.timer); assert.equal(second.errors, ''); // Duplicate entries cannot silently override the stored point value on restart. const broken = saved.replace('[dtu_area_2]\n', '[dtu_area_2]\n34849=99\n'); fs.writeFileSync(config, broken, 'utf8'); const rejected = launch(600); const [code] = await rejected.exit; clearTimeout(rejected.timer); assert.notEqual(code, 0); assert.match(rejected.errors, /CONFIG load failed: invalid/); assert.equal(fs.readFileSync(config, 'utf8'), broken); console.log('DTU settings TCP: passed (345/88 reads, five areas, staged atomic commit, cancel/TEST, ownership cleanup, validation, disk failure, shared INI and restart)'); } exercise().catch(error => { console.error(error); process.exitCode = 1; }).finally(() => { for (const socket of sockets) socket.destroy(); for (const state of children) { clearTimeout(state.timer); if (state.child.exitCode === null) state.child.kill(); } // Keep the uniquely named fixture under .build for review; no recursive deletion. });