// Basic tests for the machineGroupControl commands registry. // Run with: node --test test/basic/commands.basic.test.js 'use strict'; const test = require('node:test'); const assert = require('node:assert/strict'); const { createRegistry } = require('generalFunctions'); const commands = require('../../src/commands'); // --- helpers --------------------------------------------------------------- function makeLogger() { const calls = { warn: [], error: [], info: [], debug: [] }; return { calls, warn: (m) => calls.warn.push(String(m)), error: (m) => calls.error.push(String(m)), info: (m) => calls.info.push(String(m)), debug: (m) => calls.debug.push(String(m)), }; } function makeSource({ name = 'mgc-1', handleInputResult = undefined, dt = { flow: { min: 0, max: 100 } }, // Initial mode for the fake. Defaults to optimalControl so gates pass for // the historical tests; per-test override via the returned `source.mode = …`. mode = 'optimalControl', // Override the gate decisions. Default-true matches the no-gating world // tests assumed before this change; negative-path tests pass functions that // return false for specific actions / sources. isValidActionForMode = () => true, isValidSourceForMode = () => true, } = {}) { const calls = { setMode: [], handleInput: [], registerChild: [], turnOffAllMachines: 0, gateAction: [], gateSource: [], }; const source = { logger: makeLogger(), config: { general: { name } }, mode, setMode: (m) => { calls.setMode.push(m); /* keep fake.mode unchanged unless test does it */ }, isValidActionForMode: (action, m) => { const ok = isValidActionForMode(action, m); calls.gateAction.push({ action, mode: m, ok }); if (!ok) source.logger.warn(`action '${action}' not allowed in mode '${m}'`); return ok; }, isValidSourceForMode: (src, m) => { const ok = isValidSourceForMode(src, m); calls.gateSource.push({ src, mode: m, ok }); if (!ok) source.logger.warn(`source '${src}' not allowed in mode '${m}'`); return ok; }, handleInput: async (src, demand) => { calls.handleInput.push({ src, demand }); if (handleInputResult instanceof Error) throw handleInputResult; return handleInputResult; }, // Used by set.demand handler when unit is %: needs dt.flow + interpolation. // With min=0, max=100, the linear interpolation is identity so a bare // numeric demand round-trips through handleInput unchanged. calcDynamicTotals: () => dt, interpolation: { interpolate_lin_single_point: (x, ix, iy, ox, oy) => { if (iy === ix) return ox; return ox + ((x - ix) * (oy - ox)) / (iy - ix); }, }, turnOffAllMachines: async () => { calls.turnOffAllMachines += 1; }, childRegistrationUtils: { registerChild: (childSource, position) => calls.registerChild.push({ childSource, position }), }, }; return { source, calls }; } function makeCtx({ child = null, logger = makeLogger(), sendSpy = null } = {}) { return { logger, RED: { nodes: { getNode: (id) => (child && child.id === id ? child : undefined) } }, node: {}, send: sendSpy || (() => {}), }; } function makeRegistry(logger) { return createRegistry(commands, { logger }); } // --- tests ----------------------------------------------------------------- test('canonical topics dispatch to their handlers', async () => { const { source, calls } = makeSource(); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.mode', payload: 'prioritycontrol' }, source, makeCtx()); assert.deepEqual(calls.setMode, ['prioritycontrol']); // bare-number demand → interpreted as % → interpolated against dt.flow. // Default test dt is {min:0,max:100} so % is identity. await reg.dispatch({ topic: 'set.demand', payload: '12.5' }, source, makeCtx()); assert.equal(calls.handleInput.length, 1); assert.deepEqual(calls.handleInput[0], { src: 'parent', demand: 12.5 }); }); test('set.demand with explicit flow unit converts to canonical m³/s', async () => { const { source, calls } = makeSource(); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.demand', payload: { value: 200, unit: 'm3/h' } }, source, makeCtx()); assert.equal(calls.handleInput.length, 1); // 200 m³/h = 0.0555... m³/s assert.ok(Math.abs(calls.handleInput[0].demand - 0.05555555555555556) < 1e-9, `expected ~0.0556 m³/s, got ${calls.handleInput[0].demand}`); }); test('set.demand negative value triggers turnOffAllMachines and bypasses handleInput', async () => { const { source, calls } = makeSource(); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.demand', payload: -1 }, source, makeCtx()); assert.equal(calls.turnOffAllMachines, 1); assert.equal(calls.handleInput.length, 0); }); test('child.register canonical resolves child via RED.nodes.getNode', async () => { const { source, calls } = makeSource(); const child = { id: 'child-1', source: { tag: 'child-domain' } }; const reg = makeRegistry(makeLogger()); await reg.dispatch( { topic: 'child.register', payload: 'child-1', positionVsParent: 'upstream' }, source, makeCtx({ child }) ); assert.equal(calls.registerChild.length, 1); assert.equal(calls.registerChild[0].childSource, child.source); assert.equal(calls.registerChild[0].position, 'upstream'); }); test('aliases dispatch to the same handler and log a one-time deprecation', async () => { const { source, calls } = makeSource(); const ctxLogger = makeLogger(); const reg = makeRegistry(ctxLogger); await reg.dispatch({ topic: 'setMode', payload: 'prioritycontrol' }, source, makeCtx({ logger: ctxLogger })); await reg.dispatch({ topic: 'setMode', payload: 'optimalcontrol' }, source, makeCtx({ logger: ctxLogger })); assert.deepEqual(calls.setMode, ['prioritycontrol', 'optimalcontrol']); let warns = ctxLogger.calls.warn.filter((m) => m.includes("'setMode' is deprecated")); assert.equal(warns.length, 1, 'setMode deprecation warning should log exactly once'); await reg.dispatch({ topic: 'Qd', payload: 5 }, source, makeCtx({ logger: ctxLogger })); warns = ctxLogger.calls.warn.filter((m) => m.includes("'Qd' is deprecated")); assert.equal(warns.length, 1); assert.equal(calls.handleInput.length, 1); const child = { id: 'child-x', source: { tag: 'child-domain' } }; await reg.dispatch( { topic: 'registerChild', payload: 'child-x', positionVsParent: 'atEquipment' }, source, makeCtx({ child, logger: ctxLogger }) ); warns = ctxLogger.calls.warn.filter((m) => m.includes("'registerChild' is deprecated")); assert.equal(warns.length, 1); assert.equal(calls.registerChild.length, 1); }); test('set.demand with non-numeric payload logs error and does not call handleInput', async () => { const { source, calls } = makeSource(); const ctxLogger = makeLogger(); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.demand', payload: 'oops' }, source, makeCtx({ logger: ctxLogger })); assert.equal(calls.handleInput.length, 0); assert.ok( ctxLogger.calls.error.some((m) => m.includes('set.demand') && m.includes('oops')), `expected error about invalid Qd, got: ${JSON.stringify(ctxLogger.calls.error)}` ); }); test('set.demand on success calls ctx.send with reply { topic: config.general.name, payload: "done" }', async () => { const { source, calls } = makeSource({ name: 'mgc-A' }); const sent = []; const ctx = makeCtx({ sendSpy: (m) => sent.push(m) }); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.demand', payload: 7.5 }, source, ctx); assert.equal(calls.handleInput.length, 1); assert.deepEqual(calls.handleInput[0], { src: 'parent', demand: 7.5 }); assert.equal(sent.length, 1); assert.equal(sent[0].topic, 'mgc-A'); assert.equal(sent[0].payload, 'done'); }); test('child.register with unknown child id logs warn and does not throw', async () => { const { source, calls } = makeSource(); const ctxLogger = makeLogger(); const reg = makeRegistry(makeLogger()); await assert.doesNotReject(() => reg.dispatch( { topic: 'child.register', payload: 'missing-id', positionVsParent: 'atEquipment' }, source, makeCtx({ logger: ctxLogger }) ) ); assert.equal(calls.registerChild.length, 0); assert.ok( ctxLogger.calls.warn.some((m) => m.includes('registerChild') && m.includes('missing-id')), `expected warn about missing child, got: ${JSON.stringify(ctxLogger.calls.warn)}` ); }); // --- mode gate tests ------------------------------------------------------- test('gate: set.demand in maintenance mode is dropped (action not allowed)', async () => { // Mirror schema: maintenance allows only statusCheck. The dispatch action // for a positive demand under optimalControl/priorityControl is // execOptimalCombination / execSequentialControl — neither in maintenance. const { source, calls } = makeSource({ mode: 'maintenance', isValidActionForMode: (action) => action === 'statusCheck', }); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.demand', payload: 50 }, source, makeCtx()); assert.equal(calls.handleInput.length, 0, 'handleInput must not be invoked'); assert.equal(calls.turnOffAllMachines, 0, 'turnOffAllMachines must not be invoked'); assert.ok( source.logger.calls.warn.some((m) => m.includes('not allowed')), `expected warn about action not allowed in maintenance, got: ${JSON.stringify(source.logger.calls.warn)}` ); }); test("gate: set.demand from msg.source 'physical' in maintenance is dropped (source not allowed)", async () => { // Maintenance accepts sources ['parent','GUI'] per schema. Physical/HMI is // rejected by the source gate even before we ask which action to perform. const { source, calls } = makeSource({ mode: 'maintenance', isValidActionForMode: () => true, // pretend action is allowed; source gate must still reject isValidSourceForMode: (src) => src === 'parent' || src === 'GUI', }); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.demand', payload: 50, source: 'physical' }, source, makeCtx()); assert.equal(calls.handleInput.length, 0); assert.equal(calls.turnOffAllMachines, 0); assert.ok( source.logger.calls.warn.some((m) => m.includes("'physical'") && m.includes('not allowed')), `expected warn about physical source not allowed, got: ${JSON.stringify(source.logger.calls.warn)}` ); }); test('gate: set.demand from msg.source GUI in optimalControl reaches handleInput', async () => { const { source, calls } = makeSource({ mode: 'optimalControl', isValidActionForMode: (action) => ['statusCheck', 'execOptimalCombination', 'balanceLoad', 'emergencyStop'].includes(action), isValidSourceForMode: (src) => ['parent', 'GUI', 'physical', 'API'].includes(src), }); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.demand', payload: 25, source: 'GUI' }, source, makeCtx()); assert.equal(calls.handleInput.length, 1); assert.deepEqual(calls.handleInput[0], { src: 'parent', demand: 25 }); // Sanity check on the gate plumbing: both gates were consulted with the // expected (action, source, mode) tuple. assert.ok(calls.gateAction.some((g) => g.action === 'execOptimalCombination' && g.mode === 'optimalControl' && g.ok)); assert.ok(calls.gateSource.some((g) => g.src === 'GUI' && g.mode === 'optimalControl' && g.ok)); }); test('gate: emergencyStop (negative demand) gated by mode → maintenance blocks the stop-all', async () => { // A negative demand is the operator stop-all signal. The schema declares // emergencyStop in optimalControl/priorityControl but NOT in maintenance, // so this should be rejected too — maintenance is "monitor only", which // includes "no dispatch decisions, even shutdowns". const { source, calls } = makeSource({ mode: 'maintenance', isValidActionForMode: (action) => action === 'statusCheck', }); const reg = makeRegistry(makeLogger()); await reg.dispatch({ topic: 'set.demand', payload: -1 }, source, makeCtx()); assert.equal(calls.turnOffAllMachines, 0, 'turnOff must be gated'); assert.ok( source.logger.calls.warn.some((m) => m.includes('emergencyStop') && m.includes('not allowed')), `expected warn about emergencyStop not allowed, got: ${JSON.stringify(source.logger.calls.warn)}` ); }); // --- mode-string normalisation (specificClass internals) -------------------- const { _normaliseMode, ALLOWED_MODES } = require('../../src/specificClass'); test('mode normalisation: camelCase pass-through, lowercase accepted, garbage rejected', () => { assert.equal(_normaliseMode('optimalControl'), 'optimalControl'); assert.equal(_normaliseMode('optimalcontrol'), 'optimalControl'); assert.equal(_normaliseMode('OPTIMALCONTROL'), 'optimalControl'); assert.equal(_normaliseMode('priorityControl'), 'priorityControl'); assert.equal(_normaliseMode('prioritycontrol'), 'priorityControl'); assert.equal(_normaliseMode('maintenance'), 'maintenance'); assert.equal(_normaliseMode('MAINTENANCE'), 'maintenance'); assert.equal(_normaliseMode('wat'), null); assert.equal(_normaliseMode(''), null); assert.equal(_normaliseMode(null), null); assert.equal(_normaliseMode(undefined), null); assert.deepEqual(ALLOWED_MODES, ['optimalControl', 'priorityControl', 'maintenance']); }); // --- schema-shape regression ----------------------------------------------- test('schema regression: allowedSources keys are camelCase for all three modes', () => { // Read the JSON directly — generalFunctions' package.json `exports` map // doesn't expose the configs subpath, and we don't want to add it just for // a test. Path is repo-relative from this test file. const fs = require('node:fs'); const path = require('node:path'); const schemaPath = path.resolve(__dirname, '../../../generalFunctions/src/configs/machineGroupControl.json'); const schema = JSON.parse(fs.readFileSync(schemaPath, 'utf8')); const allowedSourcesSchema = schema.mode.allowedSources.rules.schema; assert.ok(allowedSourcesSchema.optimalControl, 'optimalControl key must exist on allowedSources'); assert.ok(allowedSourcesSchema.priorityControl, 'priorityControl key must exist on allowedSources'); assert.ok(allowedSourcesSchema.maintenance, 'maintenance key must exist on allowedSources'); // Maintenance is monitor-only: parent + GUI permitted, physical/API rejected. const mDefaults = allowedSourcesSchema.maintenance.default; assert.ok(mDefaults.includes('parent'), `maintenance default should permit parent, got ${mDefaults}`); assert.ok(mDefaults.includes('GUI'), `maintenance default should permit GUI, got ${mDefaults}`); assert.ok(!mDefaults.includes('physical'), 'maintenance must NOT permit physical writes'); assert.ok(!mDefaults.includes('API'), 'maintenance must NOT permit API writes'); // Catch a regression to lowercase keys. assert.equal(allowedSourcesSchema.optimalcontrol, undefined, 'lowercase optimalcontrol key must NOT exist'); assert.equal(allowedSourcesSchema.prioritycontrol, undefined, 'lowercase prioritycontrol key must NOT exist'); });