Compare commits

...

6 Commits

Author SHA1 Message Date
znetsixe
b3f1fad74e final mods for first generic standardisation 2025-06-25 14:52:20 +02:00
znetsixe
57f6ec9cde fix for childregistration 2025-06-25 11:45:32 +02:00
znetsixe
0feff2e0fe updates for standaardisation 2025-06-25 10:43:15 +02:00
znetsixe
0f855a8d2f standaardisation of EVOLV eco 2025-06-24 10:48:40 +02:00
znetsixe
d05d521408 standaardisation of EVOLV eco 2025-06-23 13:23:51 +02:00
znetsixe
6f63415698 menu fixes with min lines of code and standard menus - WORKING- 2025-06-20 17:14:22 +02:00
6 changed files with 314 additions and 716 deletions

View File

@@ -1,357 +0,0 @@
{
"general": {
"name": {
"default": "Measurement Configuration",
"rules": {
"type": "string",
"description": "A human-readable name or label for this measurement configuration."
}
},
"id": {
"default": null,
"rules": {
"type": "string",
"nullable": true,
"description": "A unique identifier for this configuration. If not provided, defaults to null."
}
},
"unit": {
"default": "unitless",
"rules": {
"type": "string",
"description": "The unit of measurement for this configuration (e.g., 'meters', 'seconds', 'unitless')."
}
},
"logging": {
"logLevel": {
"default": "info",
"rules": {
"type": "enum",
"values": [
{
"value": "debug",
"description": "Log messages are printed for debugging purposes."
},
{
"value": "info",
"description": "Informational messages are printed."
},
{
"value": "warn",
"description": "Warning messages are printed."
},
{
"value": "error",
"description": "Error messages are printed."
}
]
}
},
"enabled": {
"default": true,
"rules": {
"type": "boolean",
"description": "Indicates whether logging is active. If true, log messages will be generated."
}
}
}
},
"functionality": {
"softwareType": {
"default": "measurement",
"rules": {
"type": "string",
"description": "Specified software type for this configuration."
}
},
"role": {
"default": "Sensor",
"rules": {
"type": "string",
"description": "Indicates the role this configuration plays (e.g., sensor, controller, etc.)."
}
}
},
"asset": {
"uuid": {
"default": null,
"rules": {
"type": "string",
"nullable": true,
"description": "Asset tag number which is a universally unique identifier for this asset. May be null if not assigned."
}
},
"tagCode":{
"default": null,
"rules": {
"type": "string",
"nullable": true,
"description": "Asset tag code which is a unique identifier for this asset. May be null if not assigned."
}
},
"geoLocation": {
"default": {
"x": 0,
"y": 0,
"z": 0
},
"rules": {
"type": "object",
"description": "An object representing the asset's physical coordinates or location.",
"schema": {
"x": {
"default": 0,
"rules": {
"type": "number",
"description": "X coordinate of the asset's location."
}
},
"y": {
"default": 0,
"rules": {
"type": "number",
"description": "Y coordinate of the asset's location."
}
},
"z": {
"default": 0,
"rules": {
"type": "number",
"description": "Z coordinate of the asset's location."
}
}
}
}
},
"supplier": {
"default": "Unknown",
"rules": {
"type": "string",
"description": "The supplier or manufacturer of the asset."
}
},
"type": {
"default": "sensor",
"rules": {
"type": "enum",
"values": [
{
"value": "sensor",
"description": "A device that detects or measures a physical property and responds to it (e.g. temperature sensor)."
}
]
}
},
"subType": {
"default": "pressure",
"rules": {
"type": "string",
"description": "A more specific classification within 'type'. For example, 'pressure' for a pressure sensor."
}
},
"model": {
"default": "Unknown",
"rules": {
"type": "string",
"description": "A user-defined or manufacturer-defined model identifier for the asset."
}
},
"accuracy": {
"default": null,
"rules": {
"type": "number",
"nullable": true,
"description": "The accuracy of the sensor, typically represented as a percentage or absolute value."
}
},
"repeatability": {
"default": null,
"rules": {
"type": "number",
"nullable": true,
"description": "The repeatability of the sensor, typically represented as a percentage or absolute value."
}
}
},
"scaling": {
"enabled": {
"default": false,
"rules": {
"type": "boolean",
"description": "Indicates whether input scaling is active. If true, input values will be scaled according to the parameters below."
}
},
"inputMin": {
"default": 0,
"rules": {
"type": "number",
"description": "The minimum expected input value before scaling."
}
},
"inputMax": {
"default": 1,
"rules": {
"type": "number",
"description": "The maximum expected input value before scaling."
}
},
"absMin": {
"default": 50,
"rules": {
"type": "number",
"description": "The absolute minimum value that can be read or displayed after scaling."
}
},
"absMax": {
"default": 100,
"rules": {
"type": "number",
"description": "The absolute maximum value that can be read or displayed after scaling."
}
},
"offset": {
"default": 0,
"rules": {
"type": "number",
"description": "A constant offset to apply to the scaled output (e.g., to calibrate zero-points)."
}
}
},
"smoothing": {
"smoothWindow": {
"default": 10,
"rules": {
"type": "number",
"min": 1,
"description": "Determines the size of the data window (number of samples) used for smoothing operations."
}
},
"smoothMethod": {
"default": "mean",
"rules": {
"type": "enum",
"values": [
{
"value": "none",
"description": "No smoothing is applied; raw data is passed through."
},
{
"value": "mean",
"description": "Calculates the simple arithmetic mean (average) of the data points in a window."
},
{
"value": "min",
"description": "Selects the smallest (minimum) value among the data points in a window."
},
{
"value": "max",
"description": "Selects the largest (maximum) value among the data points in a window."
},
{
"value": "sd",
"description": "Computes the standard deviation to measure the variation or spread of the data."
},
{
"value": "lowPass",
"description": "Filters out high-frequency components, allowing only lower frequencies to pass."
},
{
"value": "highPass",
"description": "Filters out low-frequency components, allowing only higher frequencies to pass."
},
{
"value": "weightedMovingAverage",
"description": "Applies varying weights to each data point in a window before averaging."
},
{
"value": "bandPass",
"description": "Filters the signal to allow only frequencies within a specific range to pass."
},
{
"value": "median",
"description": "Selects the median (middle) value in a window, minimizing the effect of outliers."
},
{
"value": "kalman",
"description": "Applies a Kalman filter to combine noisy measurements over time for more accurate estimates."
},
{
"value": "savitzkyGolay",
"description": "Uses a polynomial smoothing filter on a moving window, which can also provide derivative estimates."
}
]
}
}
},
"simulation": {
"enabled": {
"default": false,
"rules": {
"type": "boolean",
"description": "If true, the system operates in simulation mode, generating simulated values instead of using real inputs."
}
},
"safeCalibrationTime": {
"default": 100,
"rules": {
"type": "number",
"min": 100,
"description": "Time to wait before finalizing calibration in simulation mode (in milliseconds or appropriate unit)."
}
}
},
"interpolation": {
"percentMin": {
"default": 0,
"rules": {
"type": "number",
"min": 0,
"description": "Minimum percentage for interpolation or data scaling operations."
}
},
"percentMax": {
"default": 100,
"rules": {
"type": "number",
"max": 100,
"description": "Maximum percentage for interpolation or data scaling operations."
}
}
},
"outlierDetection": {
"enabled": {
"default": false,
"rules": {
"type": "boolean",
"description": "Indicates whether outlier detection is enabled. If true, outliers will be identified and handled according to the method specified."
}
},
"method": {
"default": "zScore",
"rules": {
"type": "enum",
"values": [
{
"value": "zScore",
"description": "Uses the Z-score method to identify outliers based on standard deviations from the mean."
},
{
"value": "iqr",
"description": "Uses the Interquartile Range (IQR) method to identify outliers based on the spread of the middle 50% of the data."
},
{
"value": "modifiedZScore",
"description": "Uses a modified Z-score method that is more robust to small sample sizes."
}
]
}
},
"threshold": {
"default": 3,
"rules": {
"type": "number",
"description": "The threshold value used by the selected outlier detection method. For example, a Z-score threshold of 3.0."
}
}
}
}

Binary file not shown.

View File

@@ -1,17 +1,15 @@
<script src="measurement/resources/menuUtils.js"></script>
<script src="/measurement/menu.js"></script> <!-- Load the menu script for dynamic dropdowns -->
<script src="/measurement/configData.js"></script> <!-- Load the config script for node information -->
<script>
RED.nodes.registerType("measurement", {
category: "digital twin",
color: "#e4a363",
defaults: {
// Define default properties
name: { value: "", required: true },
enableLog: { value: false },
logLevel: { value: "error" },
name: { value: "", required: true }, // use asset category as name
// Define specific properties
scaling: { value: false },
@@ -21,120 +19,112 @@
o_min: { value: 0, required: true },
o_max: { value: 1, required: true },
simulator: { value: false },
unit: { value: "unit", required: true },
smooth_method: { value: "" },
count: { value: "10", required: true },
//define asset properties
uuid: { value: "" },
supplier: { value: "" },
subType: { value: "" },
category: { value: "" },
assetType: { value: "" },
model: { value: "" },
unit: { value: "" },
//logger properties
enableLog: { value: false },
logLevel: { value: "error" },
//physicalAspect
positionVsParent: { value: "" },
},
inputs: 1,
outputs: 4,
outputs: 3,
inputLabels: ["Measurement Input"],
outputLabels: ["process", "dbase", "upstreamParent", "downstreamParent"],
outputLabels: ["process", "dbase", "parent"],
icon: "font-awesome/fa-tachometer",
label: function () {
return this.name || "Measurement";
},
oneditprepare: function() {
const waitForMenuData = () => {
if (window.EVOLV?.nodes?.measurement?.initEditor) {
window.EVOLV.nodes.measurement.initEditor(this);
} else {
setTimeout(waitForMenuData, 50);
}
};
// Wait for the menu data to be ready before initializing the editor
waitForMenuData();
const node = this;
// THIS IS NODE SPECIFIC --------------- Initialize the dropdowns and other specific UI elements -------------- this should be derived from the config in the future (make config based menu)
// Populate smoothing methods dropdown
const smoothMethodSelect = document.getElementById('node-input-smooth_method');
const options = window.EVOLV?.nodes?.measurement?.config?.smoothing?.smoothMethod?.rules?.values || [];
// Use the namespaced version instead of global
const menuUtils = window.EVOLV.nodes.measurement.utils.menuUtils;
const helpers = window.EVOLV.nodes.measurement.utils.helpers;
//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";
// Clear existing options
smoothMethodSelect.innerHTML = '';
// Define UI html elements
const elements = {
// Basic fields
name: document.getElementById("node-input-name"),
// specific fields
scalingCheckbox: document.getElementById("node-input-scaling"),
rowInputMin: document.getElementById("row-input-i_min"),
rowInputMax: document.getElementById("row-input-i_max"),
smoothMethod: document.getElementById("node-input-smooth_method"),
count: document.getElementById("node-input-count"),
iOffset: document.getElementById("node-input-i_offset"),
oMin: document.getElementById("node-input-o_min"),
oMax: document.getElementById("node-input-o_max"),
// 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"),
};
// Add empty option
const emptyOption = document.createElement('option');
emptyOption.value = '';
emptyOption.textContent = 'Select method...';
smoothMethodSelect.appendChild(emptyOption);
// Add smoothing method options
options.forEach(option => {
const optionElement = document.createElement('option');
optionElement.value = option.value;
optionElement.textContent = option.value;
optionElement.title = option.description; // Add tooltip with full description
smoothMethodSelect.appendChild(optionElement);
});
// Set current value if it exists
if (this.smooth_method) {
smoothMethodSelect.value = this.smooth_method;
}
try{
// --- Scale rows toggle ---
const chk = document.getElementById('node-input-scaling');
const rowMin = document.getElementById('row-input-i_min');
const rowMax = document.getElementById('row-input-i_max');
// Fetch project settings
menuUtils.fetchProjectData(projecSettingstURL)
.then((projectSettings) => {
//assign to node vars
node.configUrls = projectSettings.configUrls;
const { cloudConfigURL, localConfigURL } = menuUtils.getSpecificConfigUrl("measurement",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 = 1;//activeFlowId;
// UI elements specific for node
menuUtils.initMeasurementToggles(elements);
menuUtils.populateSmoothingMethods(node.configUrls, elements, node);
// 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);
function toggleScalingRows() {
const show = chk.checked;
rowMin.style.display = show ? 'block' : 'none';
rowMax.style.display = show ? 'block' : 'none';
}
if(node.d){
//this means node is disabled
console.log("Current status of node is disabled");
}
},
// wire and initialize
chk.addEventListener('change', toggleScalingRows);
toggleScalingRows();
//------------------- END OF CUSTOM config UI ELEMENTS ------------------- //
},
oneditsave: function () {
const node = this;
console.log(`------------ Saving changes to node ------------`);
console.log(`${node.uuid}`);
// Validate asset properties using the asset menu
if (window.EVOLV?.nodes?.measurement?.assetMenu?.saveEditor) {
success = window.EVOLV.nodes.measurement.assetMenu.saveEditor(this);
}
// Validate logger properties using the logger menu
if (window.EVOLV?.nodes?.measurement?.loggerMenu?.saveEditor) {
success = window.EVOLV.nodes.measurement.loggerMenu.saveEditor(node);
}
// Save basic properties
["name", "supplier", "subType", "model", "unit", "smooth_method"].forEach(
["smooth_method"].forEach(
(field) => (node[field] = document.getElementById(`node-input-${field}`).value || "")
);
// Save numeric and boolean properties
["scaling", "enableLog", "simulator"].forEach(
["scaling", "simulator"].forEach(
(field) => (node[field] = document.getElementById(`node-input-${field}`).checked)
);
@@ -142,41 +132,11 @@
(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");
}
if (!node.unit) {
RED.notify("Unit selection is required.", "error");
}
if (node.subType && !node.unit) {
RED.notify("Unit must be set when specifying a subtype.", "error");
}
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.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>
@@ -185,47 +145,28 @@
<script type="text/html" data-template-name="measurement">
<!-- Node Name -->
<div class="form-row">
<label for="node-input-name"><i class="fa fa-tag"></i> Name</label>
<input
type="text"
id="node-input-name"
placeholder="Measurement Name"
style="width:70%;"
/>
</div>
<!-- Scaling Checkbox -->
<div class="form-row">
<label for="node-input-scaling"
><i class="fa fa-compress"></i> Scaling</label
>
<input
type="checkbox"
id="node-input-scaling"
style="width:20px; vertical-align:baseline;"
/>
><i class="fa fa-compress"></i> Scaling</label>
<input type="checkbox" id="node-input-scaling" style="width:20px; vertical-align:baseline;"/>
<span>Enable input scaling?</span>
</div>
<!-- Source Min/Max (only if scaling is true) -->
<div class="form-row" id="row-input-i_min">
<label for="node-input-i_min"
><i class="fa fa-arrow-down"></i> Source Min</label>
<label for="node-input-i_min"><i class="fa fa-arrow-down"></i> Source Min</label>
<input type="number" id="node-input-i_min" placeholder="0" />
</div>
<div class="form-row" id="row-input-i_max">
<label for="node-input-i_max"
><i class="fa fa-arrow-up"></i> Source Max</label>
<label for="node-input-i_max"><i class="fa fa-arrow-up"></i> Source Max</label>
<input type="number" id="node-input-i_max" placeholder="3000" />
</div>
<!-- Offset -->
<div class="form-row">
<label for="node-input-i_offset"
><i class="fa fa-adjust"></i> Input Offset</label>
<label for="node-input-i_offset"><i class="fa fa-adjust"></i> Input Offset</label>
<input type="number" id="node-input-i_offset" placeholder="0" />
</div>
@@ -241,87 +182,34 @@
<!-- Simulator Checkbox -->
<div class="form-row">
<label for="node-input-simulator"
><i class="fa fa-cog"></i> Simulator</label>
<input
type="checkbox"
id="node-input-simulator"
style="width:20px; vertical-align:baseline;"
/>
<label for="node-input-simulator"><i class="fa fa-cog"></i> Simulator</label>
<input type="checkbox" id="node-input-simulator" style="width:20px; vertical-align:baseline;"/>
<span>Activate internal simulation?</span>
</div>
<!-- Smoothing Method -->
<div class="form-row">
<label for="node-input-smooth_method"
><i class="fa fa-line-chart"></i> Smoothing</label>
<label for="node-input-smooth_method"><i class="fa fa-line-chart"></i> Smoothing</label>
<select id="node-input-smooth_method" style="width:60%;">
<!-- Filled dynamically from measurementConfig.json or fallback -->
</select>
</div>
<!-- Smoothing Window -->
<div class="form-row">
<label for="node-input-count">Window</label>
<input
type="number"
id="node-input-count"
placeholder="10"
style="width:60px;"
/>
<input type="number" id="node-input-count" placeholder="10" style="width:60px;"/>
<div class="form-tips">Number of samples for smoothing</div>
</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 />
<!-- Optional Extended Fields: supplier, cat, type, model, unit -->
<!-- Asset fields will be injected here -->
<div id="asset-fields-placeholder"></div>
<!-- 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 id="logger-fields-placeholder"></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>
<!-- Position fields will be injected here -->
<div id="position-fields-placeholder"></div>
</script>

View File

@@ -1,159 +1,50 @@
console.log('Loading measurement.js module...');
// load helper modules from the generalFunctions folder
const { outputUtils } = require('generalFunctions');
//internal node-red node dependencies this is the class that will handle the measurement
const Measurement = require("./dependencies/measurement/measurement");
const { menuUtils } = require('generalFunctions');
console.log('All dependencies loaded successfully');
console.log(menuUtils);
/**
* Thin wrapper that registers a node with Node-RED and exposes HTTP endpoints. and loads EVOLV in a standard way
*/
module.exports = function (RED) {
function measurement(config) {
//create node
const nameOfNode = 'measurement'; // this is the name of the node, it should match the file name and the node type in Node-RED
const nodeClass = require('./src/nodeClass.js'); // this is the specific node class
const { MenuManager, configManager } = require('generalFunctions');
// This is the main entry point for the Node-RED node, it will register the node and setup the endpoints
module.exports = function(RED) {
// Register the node type
RED.nodes.registerType(nameOfNode, function(config) {
// Initialize the Node-RED node first
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{
//load user defined config in the node-red UI
const mConfig={
general: {
name: config.name,
id: node.id,
unit: config.unit,
logging:{
logLevel: config.logLevel,
enabled: config.enableLog,
},
},
asset: {
tagCode: config.assetTagCode,
supplier: config.supplier,
subType: config.subType,
model: config.model,
},
scaling:{
enabled: config.scaling,
inputMin: config.i_min,
inputMax: config.i_max,
absMin: config.o_min,
absMax: config.o_max,
offset: config.i_offset
},
smoothing: {
smoothWindow: config.count,
smoothMethod: config.smooth_method,
},
simulation: {
enabled: config.simulator,
},
}
// Then create your custom class and attach it
this.nodeClass = new nodeClass(config, RED, this);
});
//make new measurement on creation to work with.
const m = new Measurement(mConfig);
// Setup admin UIs
const menuMgr = new MenuManager(); //this will handle the menu endpoints so we can load them dynamically
const cfgMgr = new configManager(); // this will handle the config endpoints so we can load them dynamically
// put m on node memory as source
node.source = m;
console.log(`Loading endpoint for ${nameOfNode} menu...`);
//load output utils
const output = new outputUtils();
function updateNodeStatus(val) {
//display status
node.status({ fill: "green", shape: "dot", text: val + " " + mConfig.general.unit });
}
//Update status only on event change
m.emitter.on('mAbs', (val) => {
updateNodeStatus(val);
});
//never ending functions
function tick(){
//kick class ticks for time move
m.tick();
//get output
const classOutput = m.getOutput();
const dbOutput = output.formatMsg(classOutput, m.config, "influxdb");
const pOutput = output.formatMsg(classOutput, m.config, "process");
//only send output on values that changed
let msgs = [];
msgs[0] = pOutput;
msgs[1] = dbOutput;
node.send(msgs);
}
// 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.intervalId = setInterval(function(){ tick() },1000)
},
1000
);
//-------------------------------------------------------------------->>what to do on input
node.on("input", function (msg,send,done) {
if(msg.topic == "simulator" ){
m.toggleSimulation();
}
if(msg.topic == "outlierDetection" ){
m.toggleOutlierDetection();
}
if(msg.topic == "calibrate" ){
m.calibrate();
}
if(msg.topic == "measurement" && typeof msg.payload == "number"){
//feed input into the measurement node and calculate output
m.inputValue = parseFloat(msg.payload);
}
done();
});
// tidy up any async code here - shutdown connections and so on.
node.on('close', function(done) {
if (node.intervalId) clearTimeout(node.intervalId);
if (node.tickInterval) clearInterval(node.tickInterval);
if (done) done();
});
}catch(e){
console.log(e);
// Register the different menu's for the measurement node (in the future we could automate this further by refering to the config)
RED.httpAdmin.get('/measurement/menu.js', (req, res) => {
try {
const script = menuMgr.createEndpoint(nameOfNode, ['asset','logger','position']);
res.type('application/javascript').send(script);
} catch (err) {
res.status(500).send(`// Error generating menu: ${err.message}`);
}
}
});
RED.nodes.registerType("measurement", measurement);
console.log(`Loading endpoint for ${nameOfNode} config...`);
// Create a new instance of MenuUtils for use in the html browser
let menuUtil = new menuUtils();
// Create the endpoint with one line!
menuUtil.createMenuUtilsEndpoint(RED, 'measurement', menuUtils);
// Endpoint to get the configuration data for the specific node
RED.httpAdmin.get(`/measurement/configData.js`, (req, res) => {
try {
const script = cfgMgr.createEndpoint(nameOfNode);
// Send the configuration data as JSON response
res.type('application/javascript').send(script);
} catch (err) {
res.status(500).send(`// Error generating configData: ${err.message}`);
}
});
console.log(`Measurement node '${nameOfNode}' registered.`);
};

175
src/nodeClass.js Normal file
View File

@@ -0,0 +1,175 @@
/**
* measurement.class.js
*
* 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 Measurement = require("./specificClass");
/**
* Class representing a Measurement Node-RED node.
*/
class MeasurementNode {
/**
* Create a MeasurementNode.
* @param {object} uiConfig - Node-RED node configuration.
* @param {object} RED - Node-RED runtime API.
*/
constructor(uiConfig, RED, nodeInstance) {
// Preserve RED reference for HTTP endpoints if needed
this.node = nodeInstance;
this.RED = RED;
// Load default & UI config
this._loadConfig(uiConfig,this.node);
// Instantiate core Measurement class
this._setupMeasurementClass();
// Wire up event and lifecycle handlers
this._bindEvents();
this._registerChild();
this._startTickLoop();
this._attachInputHandler();
this._attachCloseHandler();
}
/**
* Load and merge default config with user-defined settings.
* @param {object} uiConfig - Raw config from Node-RED UI.
*/
_loadConfig(uiConfig,node) {
const cfgMgr = new configManager();
this.defaultConfig = cfgMgr.getConfig("measurement");
console.log( uiConfig.positionVsParent);
// Merge UI config over defaults
this.config = {
general: {
name: uiConfig.name,
id: node.id, // node.id is for the child registration process
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)
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
supplier: uiConfig.supplier,
category: uiConfig.category, //add later to define as the software type
type: uiConfig.assetType,
model: uiConfig.model,
unit: uiConfig.unit
},
scaling: {
enabled: uiConfig.scaling,
inputMin: uiConfig.i_min,
inputMax: uiConfig.i_max,
absMin: uiConfig.o_min,
absMax: uiConfig.o_max,
offset: uiConfig.i_offset
},
smoothing: {
smoothWindow: uiConfig.count,
smoothMethod: uiConfig.smooth_method
},
simulation: {
enabled: uiConfig.simulator
},
functionality: {
positionVsParent: uiConfig.positionVsParent || 'atEquipment', // Default to 'atEquipment' if not specified
}
};
// Utility for formatting outputs
this._output = new outputUtils();
}
/**
* Instantiate the core Measurement logic and store as source.
*/
_setupMeasurementClass() {
this.source = new Measurement(this.config);
}
/**
* Bind Measurement events to Node-RED status updates. Using internal emitter. --> REMOVE LATER WE NEED ONLY COMPLETE CHILDS AND THEN CHECK FOR UPDATES
*/
_bindEvents() {
this.source.emitter.on('mAbs', (val) => {
this.node.status({ fill: 'green', shape: 'dot', text: `${val} ${this.config.general.unit}` });
});
}
/**
* Register this node as a child upstream and downstream.
* Delayed to avoid Node-RED startup race conditions.
*/
_registerChild() {
setTimeout(() => {
this.node.send([
null,
null,
{ topic: 'registerChild', payload: this.config.general.id, positionVsParent: this.config?.functionality?.positionVsParent || 'atEquipment' },
]);
}, 100);
}
/**
* Start the periodic tick loop to drive the Measurement class.
*/
_startTickLoop() {
setTimeout(() => {
this._tickInterval = setInterval(() => this._tick(), 1000);
}, 1000);
}
/**
* Execute a single tick: update measurement, format and send outputs.
*/
_tick() {
this.source.tick();
const raw = this.source.getOutput();
const processMsg = this._output.formatMsg(raw, this.config, 'process');
const influxMsg = this._output.formatMsg(raw, this.config, 'influxdb');
// Send only updated outputs on ports 0 & 1
this.node.send([processMsg, influxMsg]);
}
/**
* Attach the node's input handler, routing control messages to the Measurement class.
*/
_attachInputHandler() {
this.node.on('input', (msg, send, done) => {
switch (msg.topic) {
case 'simulator': this.source.toggleSimulation(); break;
case 'outlierDetection': this.source.toggleOutlierDetection(); break;
case 'calibrate': this.source.calibrate(); break;
case 'measurement':
if (typeof msg.payload === 'number') {
this.source.inputValue = parseFloat(msg.payload);
}
break;
}
done();
});
}
/**
* Clean up timers and intervals when Node-RED stops the node.
*/
_attachCloseHandler() {
this.node.on('close', (done) => {
clearInterval(this._tickInterval);
done();
});
}
}
module.exports = MeasurementNode;

View File

@@ -39,14 +39,15 @@
*/
const EventEmitter = require('events');
const {logger,configUtils} = require('generalFunctions');
const defaultConfig = require('./measurementConfig.json');
const {logger,configUtils,configManager} = require('generalFunctions');
class Measurement {
constructor(config={}) {
this.emitter = new EventEmitter(); // Own EventEmitter
this.configUtils = new configUtils(defaultConfig);
this.configManager = new configManager();
this.defaultConfig = this.configManager.getConfig('measurement');
this.configUtils = new configUtils(this.defaultConfig);
this.config = this.configUtils.initConfig(config);
// Init after config is set