Hi all,
I’m pretty raw at code but had a function node running which reads two sensors, outputs the current temp from the lowest of the two, then if it is lower than the lowest it updates it and likewise the highest if higher.
It worked well but having some spare time i thought i’d feed it through chatgpt and see what it did.
The result was way beyond me and sadly only outputs the current temp and zero for min and max now - no values.
Its all educational so i’m trying to learn why it fails - any ideas???
// Get raw states
let t1 = global.get('homeassistant.homeAssistant.states["sensor.motion_1_temperature"]')?.state;
let t2 = global.get('homeassistant.homeAssistant.states["sensor.motion_7_temperature"]')?.state;
// Convert safely
let temp_1 = Number(t1);
let temp_2 = Number(t2);
// Handle invalid sensor values
temp_1 = isNaN(temp_1) ? null : temp_1;
temp_2 = isNaN(temp_2) ? null : temp_2;
// Get stored min/max
let min_temp = Number(global.get('homeassistant.homeAssistant.states["sensor.hue_min"]')?.state);
let max_temp = Number(global.get('homeassistant.homeAssistant.states["sensor.hue_max"]')?.state);
min_temp = isNaN(min_temp) ? null : min_temp;
max_temp = isNaN(max_temp) ? null : max_temp;
// Determine current temp (lowest valid sensor)
let current_temp;
if (temp_1 !== null && temp_2 !== null) {
current_temp = Math.min(temp_1, temp_2);
} else if (temp_1 !== null) {
current_temp = temp_1;
} else if (temp_2 !== null) {
current_temp = temp_2;
} else {
current_temp = 0; // fallback if both sensors fail
}
// Update min
if (min_temp === null || current_temp < min_temp) {
min_temp = current_temp;
}
// Update max
if (max_temp === null || current_temp > max_temp) {
max_temp = current_temp;
}
// Outputs
return [
{ payload: current_temp },
{ payload: min_temp },
{ payload: max_temp }
];