Compare commits

..

1 Commits

Author SHA1 Message Date
Rene De Ren
ae46e0021c Refactor monster to current architecture 2026-03-12 16:43:29 +01:00
10 changed files with 835 additions and 1917 deletions

View File

@@ -1,4 +1,4 @@
const inputExample = const inputExample = // eslint-disable-line no-unused-vars
//tensor 1 //tensor 1
[ [
// 1 prediction per hour // 1 prediction per hour

File diff suppressed because one or more lines are too long

1
dependencies/monster/monster_class.js vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = require('../../src/specificClass');

File diff suppressed because one or more lines are too long

View File

@@ -1,182 +0,0 @@
module.exports = function (RED) {
function monster(config) {
// create node
RED.nodes.createNode(this, config);
// call this => node so whenver you want to call a node function type node and the function behind it
var node = this;
try{
// fetch monster object from monster.js
const Monster = require("./dependencies/monster/monster_class");
const OutputUtils = require("../generalFunctions/helper/outputUtils");
const mConfig={
general: {
name: config.name,
id: node.id,
unit: config.unit,
logging:{
logLevel: config.logLevel,
enabled: config.enableLog,
},
},
asset: {
supplier: config.supplier,
subType: config.subType,
model: config.model,
emptyWeightBucket: config.emptyWeightBucket,
},
constraints: {
minVolume: config.minVolume,
maxWeight: config.maxWeight,
samplingtime: config.samplingtime,
},
}
// make new monster on creation to work with.
const m = new Monster(mConfig);
// put m on node memory as source
node.source = m;
//load output utils
const output = new OutputUtils();
//internal vars
this.interval_id = null;
//updating node state
function updateNodeStatus() {
try{
const bucketVol = m.bucketVol;
const maxVolume = m.maxVolume;
const state = m.running;
const mode = "AI" ; //m.mode;
let status;
switch (state) {
case false:
status = { fill: "red", shape: "dot", text: `${mode}: OFF` };
break;
case true:
status = { fill: "green", shape: "dot", text: `${mode}: ON => ${bucketVol} | ${maxVolume}` };
break;
}
return status;
} catch (error) {
node.error("Error in updateNodeStatus: " + error);
return { fill: "red", shape: "ring", text: "Status Error" };
}
}
function tick(){
try{
// load status node
const status = updateNodeStatus();
// kick time based function in node
m.tick();
//show node status
node.status(status);
} catch (error) {
node.error("Error in tick function: " + error);
node.status({ fill: "red", shape: "ring", text: "Tick Error" });
}
}
// register child on first output this timeout is needed because of node - red stuff
setTimeout(
() => {
/*---execute code on first start----*/
let msgs = [];
msgs[2] = { topic : "registerChild" , payload: node.id, positionVsParent: "upstream" };
msgs[3] = { topic : "registerChild" , payload: node.id, positionVsParent: "downstream" };
//send msg
this.send(msgs);
},
100
);
//declare refresh interval internal node
setTimeout(
() => {
/*---execute code on first start----*/
this.interval_id = setInterval(function(){ tick() },1000)
},
1000
);
node.on('input', function (msg,send,done) {
try{
switch(msg.topic) {
case 'registerChild':
const childId = msg.payload;
const childObj = RED.nodes.getNode(childId);
m.childRegistrationUtils.registerChild(childObj.source ,msg.positionVsParent);
break;
case 'setMode':
m.setMode(msg.payload);
break;
case 'start':
m.i_start = true;
break;
}
} catch (error) {
node.error("Error in input function: " + error);
node.status({ fill: "red", shape: "ring", text: "Input Error" });
}
if(msg.topic == "i_flow"){
monster.q = parseFloat(msg.payload);
}
if(msg.topic == "i_start"){
monster.i_start = true;
}
if(msg.topic == "model_prediction"){
let var1 = msg.payload.dagvoorheen;
let var2 = msg.payload.dagnadien;
monster.get_model_prediction(var1, var2);
}
if(msg.topic == "aquon_monsternametijden"){
monster.monsternametijden = msg.payload;
}
if(msg.topic == "rain_data"){
monster.rain_data = msg.payload;
}
//register child classes
if(msg.topic == "registerChild"){
let child = msg.payload;
monster.registerChild(child);
}
done();
});
// tidy up any async code here - shutdown connections and so on.
node.on('close', function() {
clearTimeout(this.interval_id);
});
} catch (error) {
node.error("Error in monster function: " + error);
node.status({ fill: "red", shape: "ring", text: "Monster Error" });
}
}
RED.nodes.registerType("monster", monster);
};

View File

@@ -1,13 +1,20 @@
<!-- Load the dynamic menu & config endpoints --> <script type="module">
<script src="/monster/menu.js"></script> import * as menuUtils from "/generalFunctions/helper/menuUtils.js";
<script src="/monster/configData.js"></script>
RED.nodes.registerType('monster', {
category: 'wbd typical',
color: '#4f8582',
<script>
RED.nodes.registerType("monster", {
category: "EVOLV",
color: "#4f8582",
defaults: { defaults: {
// Define default properties
name: { value: "", required: true },
processOutputFormat: { value: "process" },
dbaseOutputFormat: { value: "influxdb" },
enableLog: { value: false },
logLevel: { value: "error" },
// Define specific properties // Define specific properties
samplingtime: { value: 0 }, samplingtime: { value: 0 },
minvolume: { value: 5 }, minvolume: { value: 5 },
@@ -16,128 +23,269 @@
aquon_sample_name: { value: "" }, aquon_sample_name: { value: "" },
//define asset properties //define asset properties
uuid: { value: "" },
supplier: { value: "" }, supplier: { value: "" },
category: { value: "" }, subType: { value: "" },
assetType: { value: "" },
model: { value: "" }, model: { value: "" },
unit: { value: "" }, unit: { value: "" },
//logger properties
enableLog: { value: false },
logLevel: { value: "error" },
//physicalAspect
positionVsParent: { value: "" },
positionIcon: { value: "" },
hasDistance: { value: false },
distance: { value: 0 },
distanceUnit: { value: "m" },
distanceDescription: { value: "" }
}, },
inputs: 1,
outputs: 3,
inputLabels: ["Input"],
outputLabels: ["process", "dbase", "parent"],
icon: "font-awesome/fa-tachometer",
label: function () { inputs: 1,
return this.positionIcon + " " + this.category.slice(0, -1) || "Monster"; outputs: 4,
inputLabels: ["Measurement Input"],
outputLabels: ["process", "dbase", "upstreamParent", "downstreamParent"],
icon: "font-awesome/fa-exchange",
// Define label function
label: function() {
return this.name || "Monsternamekast";
}, },
oneditprepare: function() { oneditprepare: function() {
// wait for the menu scripts to load const node = this;
const waitForMenuData = () => {
if (window.EVOLV?.nodes?.monster?.initEditor) {
window.EVOLV.nodes.monster.initEditor(this);
} else {
setTimeout(waitForMenuData, 50);
}
};
waitForMenuData();
// your existing projectsettings & asset dropdown logic can remain here // Define UI html elements
document.getElementById("node-input-samplingtime"); const elements = {
document.getElementById("node-input-minvolume"); // Basic fields
document.getElementById("node-input-maxweight"); name: document.getElementById("node-input-name"),
document.getElementById("node-input-emptyWeightBucket"); // specific fields
document.getElementById("node-input-aquon_sample_name"); samplingtime: document.getElementById("node-input-samplingtime"),
minvolume: document.getElementById("node-input-minvolume"),
maxweight: document.getElementById("node-input-maxweight"),
emptyWeightBucket: document.getElementById("node-input-emptyWeightBucket"),
aquon_sample_name: document.getElementById("node-input-aquon_sample_name"),
// Logging fields
logCheckbox: document.getElementById("node-input-enableLog"),
logLevelSelect: document.getElementById("node-input-logLevel"),
rowLogLevel: document.getElementById("row-logLevel"),
// Asset fields
supplier: document.getElementById("node-input-supplier"),
subType: document.getElementById("node-input-subType"),
model: document.getElementById("node-input-model"),
unit: document.getElementById("node-input-unit"),
};
//this needs to live somewhere and for now we add it to every node file for simplicity
const projecSettingstURL = "http://localhost:1880/generalFunctions/settings/projectSettings.json";
try{
// Fetch project settings
menuUtils.fetchProjectData(projecSettingstURL)
.then((projectSettings) => {
//assign to node vars
node.configUrls = projectSettings.configUrls;
const { cloudConfigURL, localConfigURL } = menuUtils.getSpecificConfigUrl("monster",node.configUrls.cloud.taggcodeAPI);
node.configUrls.cloud.config = cloudConfigURL; // first call
node.configUrls.local.config = localConfigURL; // backup call
node.locationId = projectSettings.locationId;
node.uuid = projectSettings.uuid;
// Gets the ID of the active workspace (Flow)
const activeFlowId = RED.workspaces.active(); //fetches active flow id
node.processId = activeFlowId;
// UI elements across all nodes
menuUtils.fetchAndPopulateDropdowns(node.configUrls, elements, node); // function for all assets
menuUtils.initBasicToggles(elements);
})
}catch(e){
console.log("Error fetching project settings", e);
}
}, },
oneditsave: function() { oneditsave: function() {
const node = this; const node = this;
// save asset fields console.log(`------------ Saving changes to node ------------`);
if (window.EVOLV?.nodes?.monster?.assetMenu?.saveEditor) { console.log(`${node.uuid}`);
window.EVOLV.nodes.monster.assetMenu.saveEditor(this);
} // Save basic properties
// save logger fields [ "name", "supplier", "subType", "model" ,"unit" ].forEach(
if (window.EVOLV?.nodes?.monster?.loggerMenu?.saveEditor) { (field) => (node[field] = document.getElementById(`node-input-${field}`).value || "")
window.EVOLV.nodes.monster.loggerMenu.saveEditor(this); );
}
// save position field // Save numeric and boolean properties
if (window.EVOLV?.nodes?.monster?.positionMenu?.saveEditor) { ["enableLog"].forEach(
window.EVOLV.nodes.monster.positionMenu.saveEditor(this); (field) => (node[field] = document.getElementById(`node-input-${field}`).checked)
);
["samplingtime","minvolume","maxweight","emptyWeightBucket","aquon_sample_name"].forEach(
(field) => (node[field] = parseFloat(document.getElementById(`node-input-${field}`).value) || 0)
);
node.logLevel = document.getElementById("node-input-logLevel").value || "info";
// Validation checks
if (node.scaling && (isNaN(node.i_min) || isNaN(node.i_max))) {
RED.notify("Scaling enabled, but input range is incomplete!", "error");
} }
["samplingtime", "minvolume", "maxweight", "emptyWeightBucket"].forEach((field) => { if (!node.unit) {
const element = document.getElementById(`node-input-${field}`); RED.notify("Unit selection is required.", "error");
const value = parseFloat(element?.value) || 0; }
console.log(`----------------> Saving ${field}: ${value}`);
node[field] = value;
});
["aquon_sample_name"].forEach((field) => { if (node.subType && !node.unit) {
const element = document.getElementById(`node-input-${field}`); RED.notify("Unit must be set when specifying a subtype.", "error");
const value = element?.value || ""; }
console.log(`----------------> Saving ${field}: ${value}`);
node[field] = value; console.log("stored node modelData", node.modelMetadata);
console.log("------------ Changes saved to measurement node preparing to save to API ------------");
try{
// Fetch project settings
menuUtils.apiCall(node,node.configUrls)
.then((response) => {
//save response to node information
node.assetId = response.asset_id;
node.assetTagCode = response.asset_tag_number;
})
.catch((error) => {
console.log("Error during API call", error);
}); });
}catch(e){
console.log("Error saving assetID and tagnumber", e);
}
} }
});
});
</script> </script>
<!-- Main UI Template --> <!-- Main UI -->
<script type="text/html" data-template-name="monster"> <script type="text/html" data-template-name="monster">
<!-- speficic input --> <!-------------------------------------------INPUT NAME / TYPE ----------------------------------------------->
<div class="form-row"> <!-- Node Name -->
<label for="node-input-samplingtime"><i class="fa fa-clock-o"></i> Sampling time (h)</label> <div class="form-row">
<input type="number" id="node-input-samplingtime" style="width:60%;" /> <label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
</div> <input type="text" id="node-input-name" placeholder="Measurement Name">
<div class="form-row">
<label for="node-input-minvolume"><i class="fa fa-clock-o"></i> Min volume (L)</label>
<input type="number" id="node-input-minvolume" style="width:60%;" />
</div>
<div class="form-row">
<label for="node-input-maxweight"><i class="fa fa-clock-o"></i> Max weight (kg)</label>
<input type="number" id="node-input-maxweight" style="width:60%;" />
</div>
<div class="form-row">
<label for="node-input-emptyWeightBucket"><i class="fa fa-clock-o"></i> Empty weight of bucket (kg)</label>
<input type="number" id="node-input-emptyWeightBucket" style="width:60%;" />
</div>
<div class="form-row">
<label for="node-input-aquon_sample_name"><i class="fa fa-clock-o"></i> Aquon sample name</label>
<input type="text" id="node-input-aquon_sample_name" style="width:60%;" />
</div> </div>
<!-- Asset fields injected here --> <!-- Sampling Time -->
<div id="asset-fields-placeholder"></div> <div class="form-row">
<label for="node-input-samplingtime"><i class="fa fa-clock-o"></i> Sampling Time (hours)</label>
<input type="number" id="node-input-samplingtime" placeholder="Enter sampling time in hours" min="0" required>
</div>
<!-- Logger fields injected here --> <!-- Minimum Volume -->
<div id="logger-fields-placeholder"></div> <div class="form-row">
<label for="node-input-minvolume"><i class="fa fa-tint"></i> Minimum Volume (liters)</label>
<input type="number" id="node-input-minvolume" placeholder="Enter minimum volume in liters" min="0" required>
</div>
<!-- Position fields injected here --> <!-- Maximum Weight -->
<div id="position-fields-placeholder"></div> <div class="form-row">
<label for="node-input-maxweight"><i class="fa fa-balance-scale"></i> Maximum Weight (kg)</label>
<input type="number" id="node-input-maxweight" placeholder="Enter maximum weight in kg" min="0" required>
</div>
<!-- Empty Bucket Weight -->
<div class="form-row">
<label for="node-input-emptyWeightBucket"><i class="fa fa-bucket"></i> Empty Bucket Weight (kg)</label>
<input type="number" id="node-input-emptyWeightBucket" placeholder="Enter empty bucket weight in kg" min="0" required>
</div>
<!-- Aquon Sample Name -->
<div class="form-row">
<label for="node-input-aquon_sample_name"><i class="fa fa-flask"></i> Aquon Sample Name</label>
<input type="text" id="node-input-aquon_sample_name" placeholder="Enter Aquon sample name">
</div>
<!-- Optional Extended Fields: supplier, type, subType, model -->
<hr />
<div class="form-row">
<label for="node-input-supplier"
><i class="fa fa-industry"></i> Supplier</label>
<select id="node-input-supplier" style="width:60%;">
<option value="">(optional)</option>
</select>
</div>
<div class="form-row">
<label for="node-input-subType"
><i class="fa fa-puzzle-piece"></i> SubType</label>
<select id="node-input-subType" style="width:60%;">
<option value="">(optional)</option>
</select>
</div>
<div class="form-row">
<label for="node-input-model"><i class="fa fa-wrench"></i> Model</label>
<select id="node-input-model" style="width:60%;">
<option value="">(optional)</option>
</select>
</div>
<div class="form-row">
<label for="node-input-unit"><i class="fa fa-balance-scale"></i> Unit</label>
<select id="node-input-unit" style="width:60%;"></select>
</div>
<hr />
<h3>Output Formats</h3>
<div class="form-row">
<label for="node-input-processOutputFormat"><i class="fa fa-random"></i> Process Output</label>
<select id="node-input-processOutputFormat" style="width:60%;">
<option value="process">process</option>
<option value="json">json</option>
<option value="csv">csv</option>
</select>
</div>
<div class="form-row">
<label for="node-input-dbaseOutputFormat"><i class="fa fa-database"></i> Database Output</label>
<select id="node-input-dbaseOutputFormat" style="width:60%;">
<option value="influxdb">influxdb</option>
<option value="json">json</option>
<option value="csv">csv</option>
</select>
</div>
<hr />
<!-- loglevel checkbox -->
<div class="form-row">
<label for="node-input-enableLog"
><i class="fa fa-cog"></i> Enable Log</label>
<input
type="checkbox"
id="node-input-enableLog"
style="width:20px; vertical-align:baseline;"
/>
<span>Enable logging</span>
</div>
<div class="form-row" id="row-logLevel">
<label for="node-input-logLevel"><i class="fa fa-cog"></i> Log Level</label>
<select id="node-input-logLevel" style="width:60%;">
<option value="info">Info</option>
<option value="debug">Debug</option>
<option value="warn">Warn</option>
<option value="error">Error</option>
</select>
</div>
</script> </script>
<script type="text/html" data-help-name="monster"> <script type="text/html" data-help-name="monster">
<p><b>Monster node</b>: Configure a monster asset.</p> <p><b>Monster Node</b>: Configures and manages monster measurement data.</p>
<ul> <p>Use this node to configure and manage monster measurement data. The node can be configured to handle various measurement parameters and asset properties.</p>
<li><b>Supplier:</b> Select a supplier to populate machine options.</li>
</ul> <li><b>SubType:</b> Select a subtype if applicable to further categorize the asset.</li>
<li><b>Model:</b> Define the specific model for more granular asset configuration.</li>
<li><b>Unit:</b> Assign a unit to standardize measurements or operations.</li>
<li><b>Sampling Time:</b> Define the sampling time in hours for measurements.</li>
<li><b>Minimum Volume:</b> Specify the minimum volume in liters.</li>
<li><b>Maximum Weight:</b> Specify the maximum weight in kilograms.</li>
<li><b>Empty Bucket Weight:</b> Define the weight of the empty bucket in kilograms.</li>
<li><b>Aquon Sample Name:</b> Provide the name for the Aquon sample.</li>
<li><b>Enable Log:</b> Enable or disable logging for this node.</li>
<li><b>Log Level:</b> Select the log level (Info, Debug, Warn, Error) for logging messages.</li>
</script> </script>

View File

@@ -1,35 +1,9 @@
const nameOfNode = 'monster'; const nameOfNode = 'monster';
const nodeClass = require('./src/nodeClass.js'); const nodeClass = require('./src/nodeClass.js');
const { MenuManager, configManager } = require('generalFunctions');
module.exports = function(RED) { module.exports = function(RED) {
// 1) Register the node type and delegate to your class
RED.nodes.registerType(nameOfNode, function(config) { RED.nodes.registerType(nameOfNode, function(config) {
RED.nodes.createNode(this, config); RED.nodes.createNode(this, config);
this.nodeClass = new nodeClass(config, RED, this, nameOfNode); this.nodeClass = new nodeClass(config, RED, this, nameOfNode);
}); });
// 2) Setup the dynamic menu & config endpoints
const menuMgr = new MenuManager();
const cfgMgr = new configManager();
// Serve /monster/menu.js
RED.httpAdmin.get(`/${nameOfNode}/menu.js`, (req, res) => {
try {
const script = menuMgr.createEndpoint(nameOfNode, ['logger','position']);
res.type('application/javascript').send(script);
} catch (err) {
res.status(500).send(`// Error generating menu: ${err.message}`);
}
});
// Serve /monster/configData.js
RED.httpAdmin.get(`/${nameOfNode}/configData.js`, (req, res) => {
try {
const script = cfgMgr.createEndpoint(nameOfNode);
res.type('application/javascript').send(script);
} catch (err) {
res.status(500).send(`// Error generating configData: ${err.message}`);
}
});
}; };

View File

@@ -1,34 +1,15 @@
/** const { outputUtils, configManager, POSITIONS } = require('generalFunctions');
* node class.js const Specific = require('./specificClass');
*
* Encapsulates all node logic in a reusable class. In future updates we can split this into multiple generic classes and use the config to specifiy which ones to use.
* This allows us to keep the Node-RED node clean and focused on wiring up the UI and event handlers.
*/
const { outputUtils, configManager } = require('generalFunctions');
const Specific = require("./specificClass");
class nodeClass { class nodeClass {
/**
* Create a Node.
* @param {object} uiConfig - Node-RED node configuration.
* @param {object} RED - Node-RED runtime API.
*/
constructor(uiConfig, RED, nodeInstance, nameOfNode) { constructor(uiConfig, RED, nodeInstance, nameOfNode) {
this.node = nodeInstance;
this.RED = RED;
this.name = nameOfNode;
this.source = null;
// Preserve RED reference for HTTP endpoints if needed this._loadConfig(uiConfig);
this.node = nodeInstance; // This is the Node-RED node instance, we can use this to send messages and update status this._setupSpecificClass();
this.RED = RED; // This is the Node-RED runtime API, we can use this to create endpoints if needed
this.name = nameOfNode; // This is the name of the node, it should match the file name and the node type in Node-RED
this.source = null; // Will hold the specific class instance
this.config = null; // Will hold the merged configuration
// Load default & UI config
this._loadConfig(uiConfig,this.node);
// Instantiate core class
this._setupSpecificClass(uiConfig);
// Wire up event and lifecycle handlers
this._bindEvents(); this._bindEvents();
this._registerChild(); this._registerChild();
this._startTickLoop(); this._startTickLoop();
@@ -36,118 +17,79 @@ class nodeClass {
this._attachCloseHandler(); this._attachCloseHandler();
} }
/** _loadConfig(uiConfig) {
* Load and merge default config with user-defined settings. const cfgMgr = new configManager();
* @param {object} uiConfig - Raw config from Node-RED UI.
*/
_loadConfig(uiConfig,node) {
// Merge UI config over defaults this.config = cfgMgr.buildConfig(this.name, uiConfig, this.node.id, {
this.config = { constraints: {
general: { samplingtime: Number(uiConfig.samplingtime) || 0,
id: node.id, // node.id is for the child registration process minVolume: Number(uiConfig.minvolume ?? uiConfig.minVolume) || 5,
unit: uiConfig.unit, // add converter options later to convert to default units (need like a model that defines this which units we are going to use and then conver to those standards) maxWeight: Number(uiConfig.maxweight ?? uiConfig.maxWeight) || 23,
logging: {
enabled: uiConfig.enableLog,
logLevel: uiConfig.logLevel
}
}, },
asset: { });
uuid: uiConfig.assetUuid, //need to add this later to the asset model
tagCode: uiConfig.assetTagCode, //need to add this later to the asset model this.config.functionality = {
supplier: uiConfig.supplier, ...this.config.functionality,
category: uiConfig.category, //add later to define as the software type role: 'samplingCabinet',
type: uiConfig.assetType, aquonSampleName: uiConfig.aquon_sample_name || undefined,
model: uiConfig.model, };
unit: uiConfig.unit
}, this.config.asset = {
functionality: { uuid: uiConfig.uuid || null,
positionVsParent: uiConfig.positionVsParent supplier: uiConfig.supplier || 'Unknown',
} type: 'sensor',
subType: uiConfig.subType || 'pressure',
model: uiConfig.model || 'Unknown',
emptyWeightBucket: Number(uiConfig.emptyWeightBucket) || 3,
}; };
// Utility for formatting outputs
this._output = new outputUtils(); this._output = new outputUtils();
} }
/** _setupSpecificClass() {
* Instantiate the core Measurement logic and store as source. this.source = new Specific(this.config);
*/ this.node.source = this.source;
_setupSpecificClass(uiConfig) {
const monsterConfig = this.config;
this.source = new Specific(monsterConfig);
//store in node
this.node.source = this.source; // Store the source in the node instance for easy access
} }
/** _bindEvents() {}
* Bind events to Node-RED status updates. Using internal emitter. --> REMOVE LATER WE NEED ONLY COMPLETE CHILDS AND THEN CHECK FOR UPDATES
*/
_bindEvents() {
}
_updateNodeStatus() { _updateNodeStatus() {
const m = this.source; try {
try{ const stateText = this.source.running
const bucketVol = m.bucketVol; ? `${this.source.currentMode}: ON => ${this.source.bucketVol} | ${this.source.maxVolume}`
const maxVolume = m.maxVolume; : `${this.source.currentMode}: OFF`;
const state = m.running;
const mode = "AI" ; //m.mode;
let status; return {
fill: this.source.running ? 'green' : 'red',
switch (state) { shape: 'dot',
case false: text: stateText,
status = { fill: "red", shape: "dot", text: `${mode}: OFF` }; };
break;
case true:
status = { fill: "green", shape: "dot", text: `${mode}: ON => ${bucketVol} | ${maxVolume}` };
break;
}
return status;
} catch (error) { } catch (error) {
node.error("Error in updateNodeStatus: " + error); this.node.error(`Error in updateNodeStatus: ${error.message}`);
return { fill: "red", shape: "ring", text: "Status Error" }; return { fill: 'red', shape: 'ring', text: 'Status Error' };
} }
} }
/**
* Register this node as a child upstream and downstream.
* Delayed to avoid Node-RED startup race conditions.
*/
_registerChild() { _registerChild() {
setTimeout(() => { setTimeout(() => {
this.node.send([ this.node.send([
null, null,
null, null,
{ topic: 'registerChild', payload: this.config.general.id, positionVsParent: this.config?.functionality?.positionVsParent || 'atEquipment' }, { topic: 'registerChild', payload: this.node.id, positionVsParent: POSITIONS.UPSTREAM },
{ topic: 'registerChild', payload: this.node.id, positionVsParent: POSITIONS.DOWNSTREAM },
]); ]);
}, 100); }, 100);
} }
/**
* Start the periodic tick loop.
*/
_startTickLoop() { _startTickLoop() {
setTimeout(() => { setTimeout(() => {
this._tickInterval = setInterval(() => this._tick(), 1000); this._tickInterval = setInterval(() => this._tick(), 1000);
// Update node status on nodered screen every second ( this is not the best way to do this, but it works for now)
this._statusInterval = setInterval(() => { this._statusInterval = setInterval(() => {
const status = this._updateNodeStatus(); this.node.status(this._updateNodeStatus());
this.node.status(status);
}, 1000); }, 1000);
}, 1000); }, 1000);
} }
/**
* Execute a single tick: update measurement, format and send outputs.
*/
_tick() { _tick() {
this.source.tick(); this.source.tick();
@@ -155,59 +97,53 @@ try{
const processMsg = this._output.formatMsg(raw, this.config, 'process'); const processMsg = this._output.formatMsg(raw, this.config, 'process');
const influxMsg = this._output.formatMsg(raw, this.config, 'influxdb'); const influxMsg = this._output.formatMsg(raw, this.config, 'influxdb');
// Send only updated outputs on ports 0 & 1 this.node.send([processMsg, influxMsg, null, null]);
this.node.send([processMsg, influxMsg]);
} }
/**
* Attach the node's input handler, routing control messages to the class.
*/
_attachInputHandler() { _attachInputHandler() {
this.node.on('input', (msg, send, done) => { this.node.on('input', (msg, _send, done) => {
/* Update to complete event based node by putting the tick function after an input event */ try {
const m = this.source; switch (msg.topic) {
switch(msg.topic) { case 'registerChild': {
case 'registerChild':
// Register this node as a child of the parent node
const childId = msg.payload; const childId = msg.payload;
const childObj = this.RED.nodes.getNode(childId); const childObj = this.RED.nodes.getNode(childId);
m.childRegistrationUtils.registerChild(childObj.source ,msg.positionVsParent); if (childObj?.source) {
break; this.source.childRegistrationUtils.registerChild(childObj.source, msg.positionVsParent);
case 'setMode': }
m.setMode(msg.payload);
break;
case 'execSequence':
const { source, action, parameter } = msg.payload;
m.handleInput(source, action, parameter);
break;
case 'execMovement':
const { source: mvSource, action: mvAction, setpoint } = msg.payload;
m.handleInput(mvSource, mvAction, Number(setpoint));
break;
case 'flowMovement':
const { source: fmSource, action: fmAction, setpoint: fmSetpoint } = msg.payload;
m.handleInput(fmSource, fmAction, Number(fmSetpoint));
break;
case 'emergencystop':
const { source: esSource, action: esAction } = msg.payload;
m.handleInput(esSource, esAction);
break;
case 'showWorkingCurves':
m.showWorkingCurves();
send({ topic : "Showing curve" , payload: m.showWorkingCurves() });
break;
case 'CoG':
m.showCoG();
send({ topic : "Showing CoG" , payload: m.showCoG() });
break; break;
} }
case 'setMode':
this.source.setMode(msg.payload);
break;
case 'start':
case 'i_start':
this.source.i_start = true;
break;
case 'i_flow':
this.source.q = Number(msg.payload) || 0;
break;
case 'aquon_monsternametijden':
this.source.monsternametijden = msg.payload;
break;
case 'rain_data':
this.source.rain_data = msg.payload;
break;
case 'model_prediction':
this.source.setModelPrediction(msg.payload);
break;
default:
this.source.logger.warn(`Unknown topic: ${msg.topic}`);
break;
}
} catch (error) {
this.node.error(`Error in input function: ${error.message}`);
this.node.status({ fill: 'red', shape: 'ring', text: 'Input Error' });
}
done();
}); });
} }
/**
* Clean up timers and intervals when Node-RED stops the node.
*/
_attachCloseHandler() { _attachCloseHandler() {
this.node.on('close', (done) => { this.node.on('close', (done) => {
clearInterval(this._tickInterval); clearInterval(this._tickInterval);

393
src/specificClass.js Normal file
View File

@@ -0,0 +1,393 @@
const EventEmitter = require('events');
const { logger, configUtils, convert, childRegistrationUtils } = require('generalFunctions');
const defaultConfig = require('../dependencies/monster/monsterConfig.json');
class Monster {
constructor(config = {}) {
const loggingEnabled = config.general?.logging?.enabled ?? true;
const logLevel = config.general?.logging?.logLevel ?? 'info';
this.emitter = new EventEmitter();
this.configUtils = new configUtils(defaultConfig, loggingEnabled, logLevel);
this.config = this.configUtils.initConfig(config);
this.logger = new logger(loggingEnabled, logLevel, this.config.general.name);
this.childRegistrationUtils = new childRegistrationUtils(this);
this.convert = convert;
this.output = {};
this.child = {};
this.currentMode = 'AI';
this.externalPrediction = null;
this.aquonSampleName = this.config.functionality?.aquonSampleName || '112100';
this._monsternametijden = {};
this._rain_data = {};
this.aggregatedOutput = {};
this.sumRain = 0;
this.avgRain = 0;
this.daysPerYear = 0;
this.pulse = false;
this.bucketVol = 0;
this.sumPuls = 0;
this.predFlow = 0;
this.bucketWeight = 0;
this.q = 0;
this.i_start = false;
this.sampling_time = Number(this.config.constraints?.samplingtime) || 0;
this.emptyWeightBucket = Number(this.config.asset?.emptyWeightBucket) || 0;
this.temp_pulse = 0;
this.volume_pulse = 0.05;
this.minVolume = Number(this.config.constraints?.minVolume) || 0;
this.maxVolume = 0;
this.maxWeight = Number(this.config.constraints?.maxWeight) || 0;
this.cap_volume = 55;
this.targetVolume = 0;
this.minPuls = 0;
this.maxPuls = 0;
this.absMaxPuls = 0;
this.targetPuls = 0;
this.m3PerPuls = 0;
this.predM3PerSec = 0;
this.m3PerTick = 0;
this.m3Total = 0;
this.running = false;
this.qLineRaw = {};
this.minSeen = {};
this.maxSeen = {};
this.qLineRefined = {};
this.calcTimeShiftDry = 0;
this.calcTimeShiftWet = 0;
this.calcCapacitySewer = 0;
this.minDryHours = 0;
this.minWetHours = 0;
this.resolution = 0;
this.tmpTotQ = 0;
this.predFactor = 0.7;
this.start_time = Date.now();
this.stop_time = Date.now();
this.flowTime = 0;
this.timePassed = 0;
this.timeLeft = 0;
this.currHour = new Date().getHours();
this.nextDate = new Date(new Date().setFullYear(new Date().getFullYear() + 1)).getTime();
this.setMode(this.currentMode);
this.set_boundries_and_targets();
this.regNextDate(this.monsternametijden);
this._syncOutput();
}
set monsternametijden(value) {
if (!value || typeof value !== 'object' || Object.keys(value).length === 0) {
return;
}
const firstEntry = Array.isArray(value) ? value[0] : Object.values(value)[0];
if (
firstEntry &&
typeof firstEntry.SAMPLE_NAME !== 'undefined' &&
typeof firstEntry.DESCRIPTION !== 'undefined' &&
typeof firstEntry.SAMPLED_DATE !== 'undefined' &&
typeof firstEntry.START_DATE !== 'undefined' &&
typeof firstEntry.END_DATE !== 'undefined'
) {
this._monsternametijden = value;
this.regNextDate(value);
this._syncOutput();
}
}
get monsternametijden() {
return this._monsternametijden;
}
set rain_data(value) {
this._rain_data = value;
if (value && this.running === false) {
this.updatePredRain(value);
this._syncOutput();
}
}
get rain_data() {
return this._rain_data;
}
set bucketVol(val) {
this._bucketVol = Number(val) || 0;
this.output.bucketVol = this._bucketVol;
this.bucketWeight = this._bucketVol + this.emptyWeightBucket;
}
get bucketVol() {
return this._bucketVol;
}
set minVolume(val) {
const safeValue = Number(val) === 0 ? 1 : Number(val) || 0;
this._minVolume = safeValue;
this.output.minVolume = safeValue;
}
get minVolume() {
return this._minVolume;
}
set q(val) {
const parsed = Number(val) || 0;
this._q = parsed;
this.output.q = parsed;
this.output.qm3sec = this.convert(parsed).from('m3/h').to('m3/s');
}
get q() {
return this._q;
}
setMode(mode) {
this.currentMode = mode || 'AI';
this.output.mode = this.currentMode;
}
setModelPrediction(value) {
const parsed = Number(value);
if (!Number.isFinite(parsed) || parsed < 0) {
this.logger.warn(`Ignoring invalid model prediction: ${value}`);
return;
}
this.externalPrediction = parsed;
this.predFlow = parsed;
this.output.predFlow = parsed;
}
set_boundries_and_targets() {
this.maxVolume = Math.max(0, this.maxWeight - this.emptyWeightBucket);
this.minPuls = Math.round(this.minVolume / this.volume_pulse);
this.maxPuls = Math.round(this.maxVolume / this.volume_pulse);
this.absMaxPuls = Math.round(this.cap_volume / this.volume_pulse);
if (this.minVolume > 0 && this.maxVolume > 0) {
this.targetVolume = this.minVolume * Math.sqrt(this.maxVolume / this.minVolume);
this.targetPuls = Math.round(this.targetVolume / this.volume_pulse);
} else {
this.targetVolume = 0;
this.targetPuls = 0;
}
}
updateArchiveRain(_val) {}
updatePredRain(value) {
if (!value || typeof value !== 'object') {
return this.aggregatedOutput;
}
const totalProb = {};
let numberOfLocations = 0;
this.aggregatedOutput = {};
Object.entries(value).forEach(([locationKey, location]) => {
if (!location?.hourly?.time) {
return;
}
numberOfLocations++;
this.aggregatedOutput[locationKey] = {
tag: {
latitude: location.latitude,
longitude: location.longitude,
},
precipationRaw: {},
precipationProb: {},
};
Object.entries(location.hourly.time).forEach(([key, time]) => {
const currTimestamp = new Date(time).getTime();
const precipitation = Number(location.hourly.precipitation?.[key]) || 0;
let probability = Number(location.hourly.precipitation_probability?.[key]);
if (!Number.isFinite(probability)) {
probability = 100;
}
if (probability > 0) {
probability /= 100;
}
totalProb[currTimestamp] = (totalProb[currTimestamp] || 0) + (precipitation * probability);
this.aggregatedOutput[locationKey].precipationRaw[key] = { val: precipitation, time: currTimestamp };
this.aggregatedOutput[locationKey].precipationProb[key] = { val: probability, time: currTimestamp };
});
});
this.sumRain = Object.values(totalProb).reduce((sum, current) => sum + current, 0);
this.avgRain = numberOfLocations > 0 ? this.sumRain / numberOfLocations : 0;
return this.aggregatedOutput;
}
get_model_prediction() {
if (Number.isFinite(this.externalPrediction)) {
this.predFlow = this.externalPrediction;
} else if (!Number.isFinite(this.predFlow)) {
this.predFlow = 0;
}
this.output.predFlow = this.predFlow;
return this.predFlow;
}
sampling_program() {
if ((this.i_start || Date.now() >= this.nextDate) && !this.running) {
this.running = true;
this.temp_pulse = 0;
this.pulse = false;
this.bucketVol = 0;
this.sumPuls = 0;
this.m3Total = 0;
this.timePassed = 0;
this.timeLeft = 0;
this.predM3PerSec = 0;
const prediction = this.get_model_prediction();
this.m3PerPuls = prediction > 0 && this.targetPuls > 0 ? Math.max(Math.round(prediction / this.targetPuls), 1) : 0;
this.predM3PerSec = this.sampling_time > 0 ? prediction / this.sampling_time / 60 / 60 : 0;
this.start_time = Date.now();
this.stop_time = Date.now() + (this.sampling_time * 60 * 60 * 1000);
this.regNextDate(this.monsternametijden);
this.i_start = false;
}
if (this.running && this.stop_time > Date.now()) {
this.timePassed = Math.round((Date.now() - this.start_time) / 1000);
this.timeLeft = Math.round((this.stop_time - Date.now()) / 1000);
if (this.m3PerPuls > 0) {
const update = this.m3PerTick / this.m3PerPuls;
this.temp_pulse += update;
}
this.m3Total += this.m3PerTick;
if (this.temp_pulse >= 1 && this.sumPuls < this.absMaxPuls) {
this.temp_pulse -= 1;
this.pulse = true;
this.sumPuls++;
this.bucketVol = Math.round(this.sumPuls * this.volume_pulse * 100) / 100;
} else if (this.pulse) {
this.pulse = false;
}
} else if (this.running) {
this.m3PerPuls = 0;
this.temp_pulse = 0;
this.pulse = false;
this.bucketVol = 0;
this.sumPuls = 0;
this.timePassed = 0;
this.timeLeft = 0;
this.predFlow = Number.isFinite(this.externalPrediction) ? this.externalPrediction : 0;
this.predM3PerSec = 0;
this.m3Total = 0;
this.running = false;
}
}
flowCalc() {
const timePassed = this.flowTime > 0 ? (Date.now() - this.flowTime) / 1000 : 0;
this.m3PerTick = this.q / 60 / 60 * timePassed;
this.flowTime = Date.now();
}
tick() {
this.flowCalc();
this.sampling_program();
this.logQoverTime();
this._syncOutput();
}
regNextDate(monsternametijden) {
let nextDate = new Date(new Date().setFullYear(new Date().getFullYear() + 1)).getTime();
let daysRemaining = 0;
if (monsternametijden && typeof monsternametijden === 'object') {
Object.entries(monsternametijden).forEach(([_key, line]) => {
if (!line || line.START_DATE === 'NULL') {
return;
}
const currentDate = new Date(line.START_DATE);
const currentTimestamp = currentDate.getTime();
if (line.SAMPLE_NAME === this.aquonSampleName && currentTimestamp > Date.now()) {
if (currentTimestamp < nextDate) {
nextDate = currentTimestamp;
}
if (new Date().getFullYear() === currentDate.getFullYear()) {
daysRemaining++;
}
}
});
}
this.daysPerYear = daysRemaining;
this.nextDate = nextDate;
}
logQoverTime() {
const currentHour = new Date().getHours();
if (this.currHour !== currentHour) {
this.qLineRaw[this.currHour] = this.tmpTotQ;
this.tmpTotQ = 0;
this.currHour = currentHour;
} else {
this.tmpTotQ += this.q;
}
}
createMinMaxSeen() {
this.minSeen = {};
this.maxSeen = {};
for (let hour = 1; hour < this.sampling_time; hour++) {
this.minSeen[hour] = null;
this.maxSeen[hour] = null;
}
}
_syncOutput() {
this.output = {
...this.output,
pulse: this.pulse,
bucketVol: this.bucketVol,
sumPuls: this.sumPuls,
predFlow: this.predFlow,
predM3PerSec: this.predM3PerSec,
bucketWeight: this.bucketWeight,
m3PerTick: this.m3PerTick,
m3Total: this.m3Total,
running: this.running,
timePassed: this.timePassed,
timeLeft: this.timeLeft,
daysPerYear: this.daysPerYear,
nextDate: this.nextDate,
avgRain: this.avgRain,
sumRain: this.sumRain,
mode: this.currentMode,
};
}
getOutput() {
this._syncOutput();
return { ...this.output };
}
}
module.exports = Monster;

View File

@@ -0,0 +1,95 @@
const Monster = require('../src/specificClass');
describe('monster specificClass', () => {
function createMonster(overrides = {}) {
return new Monster({
general: {
name: 'Monster Test',
unit: 'm3/h',
logging: {
enabled: false,
logLevel: 'error',
},
},
asset: {
emptyWeightBucket: 3,
},
constraints: {
samplingtime: 1,
minVolume: 5,
maxWeight: 23,
},
functionality: {
aquonSampleName: '112100',
},
...overrides,
});
}
test('aggregates rain data and exposes output state', () => {
const monster = createMonster();
monster.rain_data = [
{
latitude: 51.7,
longitude: 4.81,
hourly: {
time: ['2026-03-12T00:00', '2026-03-12T01:00'],
precipitation: [1, 3],
precipitation_probability: [100, 50],
},
},
{
latitude: 51.8,
longitude: 4.91,
hourly: {
time: ['2026-03-12T00:00', '2026-03-12T01:00'],
precipitation: [2, 2],
precipitation_probability: [100, 100],
},
},
];
const output = monster.getOutput();
expect(monster.sumRain).toBe(6.5);
expect(monster.avgRain).toBe(3.25);
expect(output.sumRain).toBe(6.5);
expect(output.avgRain).toBe(3.25);
});
test('supports external prediction input and starts sampling safely', () => {
const monster = createMonster();
monster.setModelPrediction(120);
monster.q = 3600;
monster.i_start = true;
monster.flowTime = Date.now() - 1000;
monster.tick();
const output = monster.getOutput();
expect(output.running).toBe(true);
expect(output.predFlow).toBe(120);
expect(output.predM3PerSec).toBeCloseTo(120 / 3600, 6);
});
test('calculates the next AQUON date from monsternametijden input', () => {
const monster = createMonster();
const nextMonth = new Date();
nextMonth.setMonth(nextMonth.getMonth() + 1);
monster.monsternametijden = [
{
SAMPLE_NAME: '112100',
DESCRIPTION: 'future sample',
SAMPLED_DATE: null,
START_DATE: nextMonth.toISOString(),
END_DATE: nextMonth.toISOString(),
},
];
expect(monster.daysPerYear).toBeGreaterThanOrEqual(0);
expect(monster.nextDate).toBeGreaterThan(Date.now());
});
});