need to further update measurement emit function

This commit is contained in:
Rene De ren
2025-10-03 15:37:08 +02:00
parent 44033da15d
commit d99561fa80
2 changed files with 89 additions and 86 deletions

View File

@@ -13,7 +13,7 @@ class ChildRegistrationUtils {
// Enhanced child setup // Enhanced child setup
child.parent = this.mainClass; child.parent = this.mainClass;
child.positionVsParent = positionVsParent; //child.positionVsParent = positionVsParent;
// Enhanced measurement container with rich context // Enhanced measurement container with rich context
if (child.measurements) { if (child.measurements) {
@@ -33,10 +33,10 @@ class ChildRegistrationUtils {
registeredAt: Date.now() registeredAt: Date.now()
}); });
// IMPORTANT: Only call parent registration - no automatic handling and if parent has this function then try to register this child this.logger.debug(`Child ${name} stored under type ${softwareType}`);
if (typeof this.mainClass.registerChild === 'function') { this.logger.debug(`Spitting out mainclass: ${this.mainClass.child} `);
this.mainClass.registerChild(child, softwareType); this.mainClass.registerChild(child, softwareType);
}
this.logger.info(`✅ Child ${name} registered successfully`); this.logger.info(`✅ Child ${name} registered successfully`);
} }

View File

@@ -7,7 +7,7 @@ class MeasurementContainer {
this.emitter = new EventEmitter(); this.emitter = new EventEmitter();
this.measurements = {}; this.measurements = {};
this.windowSize = options.windowSize || 10; // Default window size this.windowSize = options.windowSize || 10; // Default window size
// For chaining context // For chaining context
this._currentType = null; this._currentType = null;
this._currentVariant = null; this._currentVariant = null;
@@ -24,11 +24,11 @@ class MeasurementContainer {
length: 'm', length: 'm',
...options.defaultUnits // Allow override ...options.defaultUnits // Allow override
}; };
// Auto-conversion settings // Auto-conversion settings
this.autoConvert = options.autoConvert !== false; // Default to true this.autoConvert = options.autoConvert !== false; // Default to true
this.preferredUnits = options.preferredUnits || {}; // Per-measurement overrides this.preferredUnits = options.preferredUnits || {}; // Per-measurement overrides
// For chaining context // For chaining context
this._currentType = null; this._currentType = null;
this._currentVariant = null; this._currentVariant = null;
@@ -39,23 +39,23 @@ class MeasurementContainer {
this.childId = null; this.childId = null;
this.childName = null; this.childName = null;
this.parentRef = null; this.parentRef = null;
} }
// NEW: Methods to set child context // NEW: Methods to set child context
setChildId(childId) { setChildId(childId) {
this.childId = childId; this.childId = childId;
return this; return this;
} }
setChildName(childName) { setChildName(childName) {
this.childName = childName; this.childName = childName;
return this; return this;
} }
setParentRef(parent) { setParentRef(parent) {
this.parentRef = parent; this.parentRef = parent;
return this; return this;
} }
// New method to set preferred units // New method to set preferred units
@@ -66,9 +66,9 @@ class MeasurementContainer {
// Get the target unit for a measurement type // Get the target unit for a measurement type
_getTargetUnit(measurementType) { _getTargetUnit(measurementType) {
return this.preferredUnits[measurementType] || return this.preferredUnits[measurementType] ||
this.defaultUnits[measurementType] || this.defaultUnits[measurementType] ||
null; null;
} }
// Chainable methods // Chainable methods
@@ -99,71 +99,72 @@ class MeasurementContainer {
} }
this._currentPosition = positionValue; this._currentPosition = positionValue;
return this; return this;
} }
// ENHANCED: Update your existing value method // ENHANCED: Update your existing value method
value(val, timestamp = Date.now(), sourceUnit = null) { value(val, timestamp = Date.now(), sourceUnit = null) {
if (!this._ensureChainIsValid()) return this; if (!this._ensureChainIsValid()) return this;
const measurement = this._getOrCreateMeasurement();
const targetUnit = this._getTargetUnit(this._currentType);
let convertedValue = val;
let finalUnit = sourceUnit || targetUnit;
// Auto-convert if enabled and units are specified const measurement = this._getOrCreateMeasurement();
if (this.autoConvert && sourceUnit && targetUnit && sourceUnit !== targetUnit) { const targetUnit = this._getTargetUnit(this._currentType);
try {
convertedValue = convertModule(val).from(sourceUnit).to(targetUnit); let convertedValue = val;
finalUnit = targetUnit; let finalUnit = sourceUnit || targetUnit;
if (this.logger) { // Auto-convert if enabled and units are specified
this.logger.debug(`Auto-converted ${val} ${sourceUnit} to ${convertedValue} ${targetUnit}`); if (this.autoConvert && sourceUnit && targetUnit && sourceUnit !== targetUnit) {
} try {
} catch (error) { convertedValue = convertModule(val).from(sourceUnit).to(targetUnit);
if (this.logger) { finalUnit = targetUnit;
this.logger.warn(`Auto-conversion failed from ${sourceUnit} to ${targetUnit}: ${error.message}`);
} if (this.logger) {
convertedValue = val; this.logger.debug(`Auto-converted ${val} ${sourceUnit} to ${convertedValue} ${targetUnit}`);
finalUnit = sourceUnit;
} }
} catch (error) {
if (this.logger) {
this.logger.warn(`Auto-conversion failed from ${sourceUnit} to ${targetUnit}: ${error.message}`);
}
convertedValue = val;
finalUnit = sourceUnit;
} }
}
measurement.setValue(convertedValue, timestamp); measurement.setValue(convertedValue, timestamp);
if (finalUnit && !measurement.unit) {
measurement.setUnit(finalUnit);
}
// ENHANCED: Emit event with rich context if (finalUnit && !measurement.unit) {
const eventData = { measurement.setUnit(finalUnit);
value: convertedValue, }
originalValue: val,
unit: finalUnit,
sourceUnit: sourceUnit,
timestamp,
position: this._currentPosition,
variant: this._currentVariant,
type: this._currentType,
// NEW: Enhanced context
childId: this.childId,
childName: this.childName,
parentRef: this.parentRef
};
// Emit the exact event your parent expects // ENHANCED: Emit event with rich context
this.emitter.emit(`${this._currentType}.${this._currentVariant}.${this._currentPosition}`, eventData); const eventData = {
//console.log(`Emitted event: ${this._currentType}.${this._currentVariant}.${this._currentPosition}`, eventData); value: convertedValue,
originalValue: val,
unit: finalUnit,
sourceUnit: sourceUnit,
timestamp,
position: this._currentPosition,
variant: this._currentVariant,
type: this._currentType,
// NEW: Enhanced context
childId: this.childId,
childName: this.childName,
parentRef: this.parentRef
};
return this; // Emit the exact event your parent expects
this.emitter.emit(`${this._currentType}.${this._currentVariant}.${this._convertPositionNum2Str(this._currentPosition)}`, eventData);
this.emitter.emit(`${this._currentType}.${this._currentVariant}.${this._currentPosition}`, eventData);
console.log(`Emitted event: ${this._currentType}.${this._currentVariant}.${this._currentPosition}`, eventData);
return this;
} }
unit(unitName) { unit(unitName) {
if (!this._ensureChainIsValid()) return this; if (!this._ensureChainIsValid()) return this;
const measurement = this._getOrCreateMeasurement(); const measurement = this._getOrCreateMeasurement();
measurement.setUnit(unitName); measurement.setUnit(unitName);
this._unit = unitName; this._unit = unitName;
@@ -179,7 +180,7 @@ class MeasurementContainer {
getCurrentValue(requestedUnit = null) { getCurrentValue(requestedUnit = null) {
const measurement = this.get(); const measurement = this.get();
if (!measurement) return null; if (!measurement) return null;
const value = measurement.getCurrentValue(); const value = measurement.getCurrentValue();
if (value === null) return null; if (value === null) return null;
@@ -206,7 +207,7 @@ class MeasurementContainer {
getAverage(requestedUnit = null) { getAverage(requestedUnit = null) {
const measurement = this.get(); const measurement = this.get();
if (!measurement) return null; if (!measurement) return null;
const avgValue = measurement.getAverage(); const avgValue = measurement.getAverage();
if (avgValue === null) return null; if (avgValue === null) return null;
@@ -246,31 +247,31 @@ class MeasurementContainer {
if (!this._currentType || !this._currentVariant) { if (!this._currentType || !this._currentVariant) {
throw new Error('Type and variant must be specified for difference calculation'); throw new Error('Type and variant must be specified for difference calculation');
} }
const savedPosition = this._currentPosition; const savedPosition = this._currentPosition;
// Get upstream and downstream measurements // Get upstream and downstream measurements
const positions = this.getPositions(); const positions = this.getPositions();
this._currentPosition = Math.min(...positions); this._currentPosition = Math.min(...positions);
const upstream = this.get(); const upstream = this.get();
this._currentPosition = Math.max(...positions); this._currentPosition = Math.max(...positions);
const downstream = this.get(); const downstream = this.get();
this._currentPosition = savedPosition; this._currentPosition = savedPosition;
if (!upstream || !downstream || upstream.values.length === 0 || downstream.values.length === 0) { if (!upstream || !downstream || upstream.values.length === 0 || downstream.values.length === 0) {
return null; return null;
} }
// Get target unit for conversion // Get target unit for conversion
const targetUnit = requestedUnit || upstream.unit || downstream.unit; const targetUnit = requestedUnit || upstream.unit || downstream.unit;
// Get values in the same unit // Get values in the same unit
const upstreamValue = this._convertValueToUnit(upstream.getCurrentValue(), upstream.unit, targetUnit); const upstreamValue = this._convertValueToUnit(upstream.getCurrentValue(), upstream.unit, targetUnit);
const downstreamValue = this._convertValueToUnit(downstream.getCurrentValue(), downstream.unit, targetUnit); const downstreamValue = this._convertValueToUnit(downstream.getCurrentValue(), downstream.unit, targetUnit);
const upstreamAvg = this._convertValueToUnit(upstream.getAverage(), upstream.unit, targetUnit); const upstreamAvg = this._convertValueToUnit(upstream.getAverage(), upstream.unit, targetUnit);
const downstreamAvg = this._convertValueToUnit(downstream.getAverage(), downstream.unit, targetUnit); const downstreamAvg = this._convertValueToUnit(downstream.getAverage(), downstream.unit, targetUnit);
@@ -297,13 +298,13 @@ class MeasurementContainer {
if (!this.measurements[this._currentType]) { if (!this.measurements[this._currentType]) {
this.measurements[this._currentType] = {}; this.measurements[this._currentType] = {};
} }
if (!this.measurements[this._currentType][this._currentVariant]) { if (!this.measurements[this._currentType][this._currentVariant]) {
this.measurements[this._currentType][this._currentVariant] = {}; this.measurements[this._currentType][this._currentVariant] = {};
} }
if (!this.measurements[this._currentType][this._currentVariant][this._currentPosition]) { if (!this.measurements[this._currentType][this._currentVariant][this._currentPosition]) {
this.measurements[this._currentType][this._currentVariant][this._currentPosition] = this.measurements[this._currentType][this._currentVariant][this._currentPosition] =
new MeasurementBuilder() new MeasurementBuilder()
.setType(this._currentType) .setType(this._currentType)
.setVariant(this._currentVariant) .setVariant(this._currentVariant)
@@ -311,7 +312,7 @@ class MeasurementContainer {
.setWindowSize(this.windowSize) .setWindowSize(this.windowSize)
.build(); .build();
} }
return this.measurements[this._currentType][this._currentVariant][this._currentPosition]; return this.measurements[this._currentType][this._currentVariant][this._currentPosition];
} }
@@ -324,7 +325,7 @@ class MeasurementContainer {
if (!this._currentType) { if (!this._currentType) {
throw new Error('Type must be specified before listing variants'); throw new Error('Type must be specified before listing variants');
} }
return this.measurements[this._currentType] ? return this.measurements[this._currentType] ?
Object.keys(this.measurements[this._currentType]) : []; Object.keys(this.measurements[this._currentType]) : [];
} }
@@ -332,9 +333,9 @@ class MeasurementContainer {
if (!this._currentType || !this._currentVariant) { if (!this._currentType || !this._currentVariant) {
throw new Error('Type and variant must be specified before listing positions'); throw new Error('Type and variant must be specified before listing positions');
} }
if (!this.measurements[this._currentType] || if (!this.measurements[this._currentType] ||
!this.measurements[this._currentType][this._currentVariant]) { !this.measurements[this._currentType][this._currentVariant]) {
return []; return [];
} }
@@ -407,7 +408,7 @@ class MeasurementContainer {
const best = convertModule(currentValue) const best = convertModule(currentValue)
.from(measurement.unit) .from(measurement.unit)
.toBest({ exclude: excludeUnits }); .toBest({ exclude: excludeUnits });
return best; return best;
} catch (error) { } catch (error) {
if (this.logger) { if (this.logger) {
@@ -418,14 +419,16 @@ class MeasurementContainer {
} }
_convertPositionStr2Num(positionString) { _convertPositionStr2Num(positionString) {
switch(positionString) {
switch (positionString) {
case "atEquipment": case "atEquipment":
return 0; return 0;
case "upstream": case "upstream":
return Number.POSITIVE_INFINITY; return Number.POSITIVE_INFINITY;
case "downstream": case "downstream":
return Number.NEGATIVE_INFINITY; return Number.NEGATIVE_INFINITY;
default: default:
if (this.logger) { if (this.logger) {
this.logger.error(`Invalid positionVsParent provided: ${positionString}`); this.logger.error(`Invalid positionVsParent provided: ${positionString}`);