/* Independent IEC104 master: Annex B energy files, current values and restart. * Artifacts remain below IEC60870-Slave/.build. No host clock is changed. */ '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 energy_freeze_loopback_test.cjs '); const project = path.resolve(__dirname, '..'); fs.mkdirSync(path.join(project, '.build'), { recursive: true }); const store = fs.mkdtempSync(path.join(project, '.build', 'energy-loopback-')); class Master { constructor(socket) { this.socket = socket; this.buffer = Buffer.alloc(0); this.frames = []; this.waiters = []; this.ns = 0; this.nr = 0; socket.on('data', bytes => { this.buffer = Buffer.concat([this.buffer, bytes]); try { while (this.buffer.length >= 2) { assert.equal(this.buffer[0], 0x68); const size = this.buffer[1] + 2; assert(size >= 6 && size <= 255); if (this.buffer.length < size) break; const frame = this.buffer.subarray(0, size); this.buffer = this.buffer.subarray(size); const waiter = this.waiters.shift(); if (waiter) { clearTimeout(waiter.timer); waiter.resolve(frame); } else this.frames.push(frame); } } catch (e) { this.fail(e); } }); socket.on('error', e => this.fail(e)); socket.on('close', () => this.fail(new Error('TCP closed'))); } fail(e) { this.error = e; for (const w of this.waiters.splice(0)) { clearTimeout(w.timer); w.reject(e); } } next() { if (this.frames.length) return Promise.resolve(this.frames.shift()); if (this.error) return Promise.reject(this.error); return new Promise((resolve, reject) => { const w = { resolve, reject }; w.timer = setTimeout(() => { this.waiters.splice(this.waiters.indexOf(w), 1); reject(new Error('TCP timeout')); }, 15000); this.waiters.push(w); }); } send(asdu) { const frame = Buffer.alloc(asdu.length + 6); frame[0] = 0x68; frame[1] = asdu.length + 4; frame.writeUInt16LE(this.ns++ << 1, 2); frame.writeUInt16LE(this.nr << 1, 4); Buffer.from(asdu).copy(frame, 6); this.socket.write(frame); } async read() { for (;;) { const frame = await this.next(); if (frame[2] === 1) continue; assert.equal(frame[2] & 1, 0); assert.equal(frame.readUInt16LE(2) >> 1, this.nr++); const ack = Buffer.from([0x68, 4, 1, 0, 0, 0]); ack.writeUInt16LE(this.nr << 1, 4); this.socket.write(ack); return frame.subarray(6); } } async receive(type, operation) { for (let i = 0; i < 100; ++i) { const a = await this.read(); if (a[0] !== type) { assert([1, 3, 11, 30, 31, 35, 70].includes(a[0])); continue; } if (operation !== undefined) assert.equal(a[10], operation); return a; } throw new Error('Expected ASDU absent'); } } const u32 = n => { const b = Buffer.alloc(4); b.writeUInt32LE(n); return b; }; const named = s => { const b = Buffer.from(s); return Buffer.concat([Buffer.from([b.length]), b]); }; const head = (op, cot) => Buffer.from([210, 1, cot, 0x41, 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; }; async function start() { const child = spawn(executable, ['--port', '0', '--ca', '7', '--run-ms', '180000', '--energy-freeze', store, '--energy-period-ms', '2000', '--events', '0', '--background-ms', '0', '--cyclic-ms', '0', '--no-parameter'], { cwd: project, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] }); let output = '', errors = ''; child.stdout.on('data', b => { output += b; }); child.stderr.on('data', b => { errors += b; }); const exited = once(child, 'exit'); const watchdog = setTimeout(() => child.kill(), 185000); let socket; try { let port; for (let i = 0; i < 1500; ++i) { const m = output.match(/LISTEN 127\.0\.0\.1:(\d+) CA=7/); if (m) { port = Number(m[1]); break; } if (child.exitCode !== null) break; await delay(10); } assert(port, `No listener\n${output}\n${errors}`); socket = net.connect({ host: '127.0.0.1', port }); const master = new Master(socket); await once(socket, 'connect'); socket.write(Buffer.from([0x68, 4, 7, 0, 0, 0])); assert.deepEqual([...(await master.next())], [0x68, 4, 11, 0, 0, 0]); assert.equal((await master.read())[0], 70); master.send([100, 1, 6, 0x40, 7, 0, 0, 0, 0, 20]); for (;;) { const a = await master.read(); if (a[0] === 100 && a[2] === 10) break; } return { master, async stop() { socket.destroy(); child.kill(); await exited; clearTimeout(watchdog); assert.equal(errors, '', errors); } }; } catch (e) { clearTimeout(watchdog); if (socket) socket.destroy(); child.kill(); await exited; e.message += `\n${output}\n${errors}`; throw e; } } async function setTime(m, day, hour = 0, minute = 0, second = 0) { m.send(Buffer.concat([Buffer.from([103, 1, 6, 0x40, 7, 0, 0, 0, 0]), cp56(day, hour, minute, second)])); assert.equal((await m.receive(103))[2], 7); await delay(30); } async function directory(m, name, range) { const filter = range ? Buffer.concat([Buffer.from([1]), ...range]) : Buffer.alloc(15); const began = performance.now(); m.send(Buffer.concat([head(1, 5), u32(42), named(name), filter])); const entries = []; for (let page = 0; page < 32; ++page) { const a = await m.receive(210, 2); 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(); p += n; assert.equal(a[p++], 0); const size = a.readUInt32LE(p); p += 4; const time = Buffer.from(a.subarray(p, p + 7)); p += 7; entries.push({ name: filename, size, time }); } assert.equal(p, a.length); if (!a[16]) { console.log(`DIRECTORY ${name} entries=${entries.length} elapsed_ms=${(performance.now() - began).toFixed(1)}`); return entries; } } throw new Error('Directory pagination overflow'); } async function download(m, entry) { m.send(Buffer.concat([head(3, 6), named(entry.name)])); const a = await m.receive(210, 4); assert.equal(a[11], 0); const p = 13 + a[12]; assert.equal(a.subarray(13, p).toString(), entry.name); assert.equal(a.readUInt32LE(p + 4), entry.size); const chunks = []; let offset = 0; for (let i = 0; i < 3000; ++i) { const b = await m.receive(210, 5); assert.equal(b.readUInt32LE(15), offset); const data = b.subarray(20, -1); assert.equal(b.at(-1), data.reduce((x, y) => (x + y) & 255, 0)); chunks.push(data); offset += data.length; if (!b[19]) { assert.equal(offset, entry.size); m.send(Buffer.concat([head(6, 5), u32(0), b.subarray(15, 19), Buffer.from([0])])); return Buffer.concat(chunks); } } throw new Error('File segment overflow'); } function parseXml(bytes) { // The independent .NET XML parser rejects malformed output; no third-party install. const p = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', '$ErrorActionPreference="Stop"; $x=New-Object System.Xml.XmlDocument; $x.LoadXml([Console]::In.ReadToEnd()); if($x.DocumentElement.Name -ne "DataFile"){exit 1}'], { input: bytes, windowsHide: true, encoding: 'utf8' }); assert.equal(p.status, 0, p.stderr); } async function counters(m, qcc = 5) { m.send([101, 1, 6, 0x40, 7, 0, 0, 0, 0, qcc]); const begin = await m.receive(101); if (qcc !== 5) { assert.equal(begin[2], 0x47); return; } assert.equal(begin[2], 7); const values = []; for (;;) { const a = await m.read(); if (a[0] === 101) { assert.equal(a[2], 10); break; } assert.equal(a[0], 206); assert.equal(a[2], 37); assert(a[1] & 128); const ioa = a.readUIntLE(6, 3); assert.equal(ioa, 0x6401 + values.length); for (let i = 0; i < (a[1] & 127); ++i) { const value = a.readFloatLE(9 + i * 5); assert(Number.isFinite(value) && value >= 0); assert.equal(a[13 + i * 5], 0); values.push(value); } } assert.equal(values.length, 8); return values; } async function run() { for (const extra of [['--counter-type', '207'], ['--energy-period-ms', '2001']]) { const p = spawnSync(executable, ['--energy-freeze', store, ...extra], { windowsHide: true, encoding: 'utf8' }); assert.notEqual(p.status, 0); } let first = await start(), frz; try { const m = first.master; for (const qcc of [1, 2, 3, 4, 0x45, 0x85, 0xc5]) await counters(m, qcc); await counters(m); for (let slot = 0; slot < 96; ++slot) await setTime(m, 1, Math.floor(slot / 4), (slot % 4) * 15); assert.equal((await directory(m, 'HISTORY/FRZ')).length, 0); await setTime(m, 2); await setTime(m, 2, 0, 0, 2); const entries = await directory(m, 'HISTORY/FRZ'); assert.equal(entries.length, 1); assert.equal(entries[0].name, 'HISTORY/FRZ/frz20900101.xml'); frz = await download(m, entries[0]); parseXml(frz); const text = frz.toString(); assert(text.includes('sectNum="96"')); assert.equal((text.match(/= 8 && num % 8 === 0); assert.equal((xml.match(//g)]; assert.equal(points.length, num); points.forEach((p, i) => assert.equal(Number(p[1]), 0x6419 + i % 8)); fs.writeFileSync(path.join(store, 'frz.xml'), frz); fs.writeFileSync(path.join(store, 'flowrev.xml'), bytes); } finally { await first.stop(); } first = await start(); try { // Startup wall clock is behind the persisted observation: sealed files still exist. const entries = await directory(first.master, 'HISTORY/FRZ'); assert.equal(entries.length, 1); assert.deepEqual(await download(first.master, entries[0]), frz); await counters(first.master); await delay(1100); const flow = await directory(first.master, 'HISTORY/FLOWREV'); parseXml(await download(first.master, flow[0])); } finally { await first.stop(); } console.log(`EnergyFreeze TCP, 97 records, FLOWREV, QCC, time filters and forced restart PASS: ${store}`); } run().catch(e => { console.error(e); process.exitCode = 1; });