Hulp gevraagd bij het ultieme badkamer vochtregeling script

Ik kom vanuit Domoticz en ben sinds een tijdje overgestapt naar Homey pro 2023.
Zo langzaam aan van alles aan het over verhuizen.
Zo ook mijn Aeotec multisensor 6 om het vochtgehalte te meten.

Hier had ik een heel mooi Lua script voor lopen en met alle eerlijkheid dat was knip en plakwerk hier en daar wat tweaken en liep als een zonnetje.
Zodanig goed dat ik heeeeel graag dit weer op dezelfde manier wil inregelen op mijn homey.

Dus met vele avonden en middagen gekletst te hebben met Chatgpt ben ik tot een javascript gekomen.
Maar ik krijg deze dus niet werken om dat het ons niet lukt om met de variabelen te werken.

Vandaar mijn hulpvraag nu hier.

Wie kan mij op gang helpen om dit script werkend te krijgen.
ter informatie zal ik als eerste het lua script hier plaatsen en dan daar op volgend mijn javascript tot zover ik en Chatgpt zijn gekomen.

ik waardeer de hulp!

Time_triggered LUA:

--[[


    This script controls the humidity in a typical bathroom setting by detecting
    relative rises in humidity in a short period.
    Of course it requires a humidity sensor and a binary switch controlling a fan/ventilator.
    (there is no provision for variable speed ventilators here!)

    How it works (assuming the default constants as defined below):

    Save the script as time triggered!!

    Every 5 minutes a reading is done. Every reading is stored together
    with the previous reading and is stored in two user variables (humidityTmin5 and humidityTmin10).
    So it has two reading over the past 10 minutes.
    It then takes the lowest of the two and compares it with the latest reading and
    calculates a delta.
    If the delta is 3 or higher (see constants) then the fan will be turned
    on, it calculates the target humidity and the 'humidity-decrease program' is started (fanFollowsProgram=1).
    From then on, every 5 minutes the current humidity is compared to the
    stored target humidity. Basically if that target is reached, the fan is turned off
    and the 'program' is ended.
    Of course, it is possible that the target is never reached (might start raining outside
    or whatever). Then there is a failsafe (FAN_MAX_TIME) after which the ventilator
    will be turned off.

    Also, it will detect if the ventilator is manually switched off during a program
    or when it is switched on before the program starts.

    Along the lines it prints to the log and sends notifications
    but of course you can turn that off by removing those lines.

--]]

commandArray = {}

-- adjust to your specific situation

-- devices
local FAN_NAME = 'Dummy Afzuiging Badkamer'    -- exact device name of the switch turning on/off the ventilator
local SENSOR_NAME = 'Vocht Badkamer'     -- exact device name of the humidity sensor

-- script constants
local SAMPLE_INTERVAL = 5                 -- time in minutes when a the script logic will happen
local FAN_DELTA_TRIGGER = 3               -- rise in humidity that will trigger the fan
local FAN_MAX_TIME = 15                   -- maximum amount of sample cycles the fan can be on, in case we never reach the target humidity
local TARGET_OFFSET = 5                   -- ventilator goes off if target+offset is reached (maybe it takes too long to reach the true target due to wet towels etc)
local LABEL = '- Humidity control - '

-- test / debug
local TEST_MODE = false                   -- when true TEST_MODE_HUMVAR is used instead of the real sensor
local TEST_MODE_HUMVAR = 'testHumidity'   -- fake humidity value, give it a test value in domoticz/uservars
local PRINT_MODE = true                   -- Any other value as false or nil will print output to log and send notifications

if PRINT_MODE then
    print(LABEL)
end

-- Function added to overcome compatibility problem between Lua version 5.2 an 5.3
local function toInteger(str)
    return math.floor(str)
end

-- get the global variables:
-- this script runs every minute, humCounter is used to create SAMPLE_INTERVAL periods
local current
local humCounter = toInteger(uservariables['humCounter'])
local humidityTmin5 = toInteger(uservariables['humidityTmin5'])                -- youngest reading
local humidityTmin10 = toInteger(uservariables['humidityTmin10'])              -- oldest reading
local targetFanOffHumidity = toInteger(uservariables['targetFanOffHumidity'])  -- target humidity
local fanMaxTimer = toInteger(uservariables['fanMaxTimer'])
local fanFollowsProgram = toInteger(uservariables['fanFollowsProgram'])        -- marker indicating that the decrease program is started

local target = 0 -- will hold the target humidity when the program starts

-- get the current humidity value
if (TEST_MODE) then
    current = toInteger(uservariables[TEST_MODE_HUMVAR])
else
    current = toInteger(otherdevices_humidity[SENSOR_NAME])
end

-- check if the sensor is on or has some weird reading
if (current == 0 or current == nil) then
    print(LABEL .. 'current is 0 or nil. Skipping this reading')
    return commandArray
end

if PRINT_MODE then
    print(LABEL .. 'Current humidity:' .. current)
    print(LABEL .. 'targetFanOffHumidity:' .. targetFanOffHumidity)
    print(LABEL .. 'humidityTmin5: ' .. humidityTmin5)
    print(LABEL .. 'humidityTmin10: ' .. humidityTmin10)
    print(LABEL .. 'fanMaxTimer: ' .. fanMaxTimer)
    print(LABEL .. 'humCounter:' .. humCounter)
    print(LABEL .. 'fanFollowsProgram:' .. fanFollowsProgram)
end

-- increase cycle counter
humCounter = humCounter + 1

if (humCounter >= SAMPLE_INTERVAL) then

    if (humidityTmin5 == 0) then
        -- initialization, assume this is the first time
        humidityTmin5 = current
        humidityTmin10 = current
    end

    humCounter = 0 -- reset the cycle counter

    -- pick the lowest history value to calculate the delta
    -- this also makes sure that two relative small deltas in the past 2*interval minutes are treated as one larger rise
    -- and therefore will still trigger the ventilator
    -- I don't want to use a longer interval instead because I want the ventilator to start as soon as possible
    -- (so rather after 5 minutes instead of after 15 minutes because the mirrors in the bathroom become kinda useless ;-)
    delta = current - math.min(humidityTmin10, humidityTmin5)

    if PRINT_MODE then
        print(LABEL .. 'Delta: ' .. delta)
    end

    -- pick the lowest history value
    target = math.min(humidityTmin10, humidityTmin5) + TARGET_OFFSET

    -- shift the previous measurements
    humidityTmin10 = humidityTmin5
    -- and store the current
    humidityTmin5 = current

    if (otherdevices[FAN_NAME]=='Off' or (otherdevices[FAN_NAME]=='On' and fanFollowsProgram==0)) then
        -- either the fan is off or it is on but the decrease program has not started
        -- in that latter case we start the program anyway. This could happen if someone turns on the ventilator
        -- manually because he/she is about to take a shower and doesn't like damp mirrors.
        -- I don't do this because the ventilator removes heat from the bathroom and I want this to happen
        -- as late as possible ;-)

        if (fanFollowsProgram == 1 and otherdevices[FAN_NAME]=='Off') then
            -- likely someone turned off the ventilator while the program was running
            fanFollowsProgram = 1
        end

        -- see if we have to turn it on
        if (delta >= FAN_DELTA_TRIGGER) then
            -- time to start the fan
            commandArray[FAN_NAME] = 'On'
            targetFanOffHumidity = target

            if (fanFollowsProgram == 1) then
                print('Ventilator was already on but we start the de-humidifying program')
            end

            fanFollowsProgram = 1

            -- set the safety stop
            fanMaxTimer = FAN_MAX_TIME

            if PRINT_MODE then
                print(LABEL .. 'Rise in humidity. Turning on the vents. Delta: ' .. delta)
                print(LABEL .. 'Target humidity for turning the ventilator: ' ..targetFanOffHumidity)
                commandArray['SendNotification'] = LABEL .. 'Ventilator is on#The ventilator was activated at humidity level ' .. current .. '#0'
            end
        end

    else
        if (fanMaxTimer > 0) then
            -- possible that someone started the ventilator manually
            fanMaxTimer = fanMaxTimer - 1
        end


        if (fanFollowsProgram == 1) then -- not manually started

            if (delta >= FAN_DELTA_TRIGGER) then
                -- ok, there is another FAN_DELTA_TRIGGER rise in humidity
                -- when this happen we reset the fanMaxTimer to a new count down
                -- because we have to ventilate a bit longer due to the extra humidity
                if PRINT_MODE then
                    print(LABEL .. 'Another large increase detected, resetting max timer. Delta: ' .. delta)
                end
                fanMaxTimer = FAN_MAX_TIME
            end

            -- first see if it can be turned off
            if (current <= targetFanOffHumidity or fanMaxTimer==0) then
                commandArray[FAN_NAME] = 'Off'

                msg = ''

                if (fanMaxTimer == 0 and current > targetFanOffHumidity) then
                    msg = 'Target not reached but safety time-out is triggered.'
                    if PRINT_MODE == true then
                    print(msg)
                    end
                else
                    msg = 'Target humidity reached'
                    if PRINT_MODE then
                        print(LABEL .. msg)
                    end
                end

                if PRINT_MODE then
                    print(LABEL .. 'Turning off the ventilator')
                    msg = msg .. '\nTurning off the ventilator'
                end

                targetFanOffHumidity = 0
                fanMaxTimer = 0
                fanFollowsProgram = 0
                -- reset history in this case.. we start all over
                -- Tmin10 is still in the 'ventilator=On'-zone
                humidityTmin10 = humidityTmin5
                 if PRINT_MODE == true then
                commandArray['SendNotification'] = 'Ventilator is off#' .. msg .. '#0'
                end

            else
                -- we haven't reached the target yet
                if PRINT_MODE then
                    print(LABEL .. 'Humidity delta: ' .. delta)
                end
            end
        end
    end

if PRINT_MODE then
    print(LABEL .. 'New values >>>>>>>>>>>')
    print(LABEL .. 'humidityTmin5: ' .. humidityTmin5)
    print(LABEL .. 'humidityTmin10: ' .. humidityTmin10)
    print(LABEL .. 'fanMaxTimer: ' .. fanMaxTimer)
    print(LABEL .. 'humCounter:' .. humCounter)
    print(LABEL .. 'fanFollowsProgram:' .. fanFollowsProgram)
    print(LABEL .. '------ target: ' .. targetFanOffHumidity)
end

end

-- save the globals
commandArray['Variable:humCounter'] = tostring(humCounter)
commandArray['Variable:humidityTmin10'] = tostring(humidityTmin10)
commandArray['Variable:humidityTmin5'] = tostring(humidityTmin5)
commandArray['Variable:targetFanOffHumidity'] = tostring(targetFanOffHumidity)
commandArray['Variable:fanMaxTimer'] = tostring(fanMaxTimer)
commandArray['Variable:fanFollowsProgram'] = tostring(fanFollowsProgram)

return commandArray

en dit is het javascript

// Define devices
const FAN_NAME = 'Ventilatie Badkamer Max';
const SENSOR_NAME = 'Multisensor 6';

// Script constants
const SAMPLE_INTERVAL = 5; // Time in minutes when the script logic will happen
const FAN_DELTA_TRIGGER = 3; // Rise in humidity that will trigger the fan
const FAN_MAX_TIME = 15; // Maximum amount of sample cycles the fan can be on if the target humidity is not reached
const TARGET_OFFSET = 5; // Ventilator goes off if target+offset is reached
const LABEL = '- Humidity control - ';

// Test/debug
const TEST_MODE = false; // When true, use a fixed test humidity value instead of the real sensor
const FIXED_TEST_HUMIDITY_VALUE = 25; // Fixed test value for humidity
const PRINT_MODE = true; // Set to true to print output to log and send notifications

// Function to convert a string to an integer
function toInteger(str) {
    return Math.floor(Number(str));
}

// Get all devices
const devices = Object.values(await Homey.devices.getDevices());

// Find the specified sensor by name
const sensor = devices.find(device => device.name === SENSOR_NAME);

// Get current humidity value
let current;

if (TEST_MODE) {
    current = toInteger(FIXED_TEST_HUMIDITY_VALUE);
} else {
    // Normal operation
    if (sensor && sensor.capabilitiesObj && sensor.capabilitiesObj.measure_humidity) {
        current = toInteger(sensor.capabilitiesObj.measure_humidity.value);
    } else {
        console.error(`Error: '${SENSOR_NAME}' device does not have a valid humidity capability.`);
        return;
    }
}

console.log(`${LABEL}Current Humidity: ${current}`);

// Increase cycle counter
let humCounter = global.get('humCounter') || 0;
let humidityTmin5 = global.get('humidityTmin5') || 0; // Youngest reading
let humidityTmin10 = global.get('humidityTmin10') || 0; // Oldest reading
let targetFanOffHumidity = global.get('targetFanOffHumidity') || 0; // Target humidity
let fanMaxTimer = global.get('fanMaxTimer') || 0;
let fanFollowsProgram = global.get('fanFollowsProgram') || 0; // Marker indicating that the decrease program is started

let target = 0; // Will hold the target humidity when the program starts

// Check if the sensor is on or has some weird reading
if (current === 0 || isNaN(current)) {
    console.log(`${LABEL}current is 0 or NaN. Skipping this reading`);
    return;
}

// Increase cycle counter
humCounter++;

if (humCounter >= SAMPLE_INTERVAL) {
    if (humidityTmin5 === 0) {
        // Initialization, assume this is the first time
        humidityTmin5 = current;
        humidityTmin10 = current;
    }

    humCounter = 0; // Reset the cycle counter

    // Pick the lowest history value to calculate the delta
    const delta = current - Math.min(humidityTmin10, humidityTmin5);

    if (PRINT_MODE) {
        console.log(`${LABEL}Delta: ${delta}`);
    }

    // Pick the lowest history value
    target = Math.min(humidityTmin10, humidityTmin5) + TARGET_OFFSET;

    // Shift the previous measurements
    humidityTmin10 = humidityTmin5;
    // And store the current
    humidityTmin5 = current;

    const fanDevice = devices.find(device => device.name === FAN_NAME);
    const fanStatus = fanDevice && fanDevice.state;

    if (!fanStatus || (fanStatus === 'off' || (fanStatus === 'on' && fanFollowsProgram === 0))) {
        // Either the fan is off or it is on but the decrease program has not started
        // In the latter case, we start the program anyway. This could happen if someone turns on the ventilator
        // manually because he/she is about to take a shower and doesn't like damp mirrors.
        // I don't do this because the ventilator removes heat from the bathroom, and I want this to happen
        // as late as possible ;-)

        if (fanFollowsProgram === 1 && fanStatus === 'off') {
            // Likely someone turned off the ventilator while the program was running
            fanFollowsProgram = 1;
        }

        // See if we have to turn it on
        if (delta >= FAN_DELTA_TRIGGER) {
            // Time to start the fan
            Homey.devices.setCapabilityValue({ deviceId: FAN_NAME, capability: 'onoff', value: true });
            targetFanOffHumidity = target;

            if (fanFollowsProgram === 1) {
                console.log('Ventilator was already on, but we start the de-humidifying program');
            }

            fanFollowsProgram = 1;

            // Set the safety stop
            fanMaxTimer = FAN_MAX_TIME;

            if (PRINT_MODE) {
                console.log(`${LABEL}Rise in humidity. Turning on the vents. Delta: ${delta}`);
                console.log(`${LABEL}Target humidity for turning the ventilator: ${targetFanOffHumidity}`);
                // Homey.notifications.createNotification(`${LABEL}Ventilator is on`, `The ventilator was activated at humidity level ${current}`, '0');
            }
        }
    } else {
        if (fanMaxTimer > 0) {
            // Possible that someone started the ventilator manually
            fanMaxTimer--;
        }

        if (fanFollowsProgram === 1) { // Not manually started
            if (delta >= FAN_DELTA_TRIGGER) {
                // Ok, there is another FAN_DELTA_TRIGGER rise in humidity
                // When this happens, we reset the fanMaxTimer to a new countdown
                // because we have to ventilate a bit longer due to the extra humidity
                if (PRINT_MODE) {
                    console.log(`${LABEL}Another large increase detected, resetting max timer. Delta: ${delta}`);
                }
                fanMaxTimer = FAN_MAX_TIME;
            }

            if (fanMaxTimer === 0) {
                // End of the program
                // If someone manually set the ventilator to off, he/she probably doesn't want to follow the program.
                fanFollowsProgram = 0;
                Homey.devices.setCapabilityValue({ deviceId: FAN_NAME, capability: 'dim', value: 0 });

                if (PRINT_MODE) {
                    console.log(`${LABEL}Fan program has finished. Fan turned off.`);
                }
            }
        }
    }
} else {
    if (fanFollowsProgram === 1) {
        // Keep running, but show it's alive
        if (PRINT_MODE) {
            console.log(`${LABEL}Next program cycle. Target: ${targetFanOffHumidity}. Timer: ${fanMaxTimer}`);
        }
    }
}

// Store variables for the next cycle
global.set('humCounter', humCounter);
global.set('humidityTmin5', humidityTmin5);
global.set('humidityTmin10', humidityTmin10);
global.set('targetFanOffHumidity', targetFanOffHumidity);
global.set('fanMaxTimer', fanMaxTimer);
global.set('fanFollowsProgram', fanFollowsProgram);

Da’s ingewikkeld :grimacing:
Is onderstaande mss een alternatief? Hier wordt de absolute luchtvochtigheid met een formule berekend in een vrij simpele flow

Kun je omschrijven wat er niet lukt? Wat doe je, welke foutmelding, waar loop je vast?

ik ben ondertussen weer wel wat verder gekomen en zal weer een update van mijn script plaatsen.
waar we nu momenteel(zover ik weet) tegenaanlopen is dat als fanFollowsProgram: 0 (dus schakelaar uit) of fanFollowsProgram: 1 (schakelaar aan) dat deze de schakelaar const FAN_NAME = ‘Ventilatie Badkamer Max’ niet aan en uit kan schakelen.

en chatgpt komt er maar niet uit hoe dit device geschakeld moet worden.

geeft me steeds de vraag hoe setCapabilityValue functioneert.

// Define devices
const FAN_NAME = 'Ventilatie Badkamer Max';
const SENSOR_NAME = 'Multisensor 6';

// Script constants
const SAMPLE_INTERVAL = 5; // Time in minutes when the script logic will happen
const FAN_DELTA_TRIGGER = 3; // Rise in humidity that will trigger the fan
const FAN_MAX_TIME = 15; // Maximum amount of sample cycles the fan can be on if the target humidity is not reached
const TARGET_OFFSET = 5; // Ventilator goes off if target+offset is reached
const LABEL = '- Humidity control - ';

// Test/debug
const TEST_MODE = false; // When true, use a test humidity value instead of the real sensor
const TEST_HUMIDITY_VALUE = 100; // Set your desired test humidity value
const PRINT_MODE = true; // Set to true to print output to log and send notifications

// Function to convert a string to an integer
function toInteger(str) {
    return Math.floor(Number(str));
}

// Get all devices
const devices = await Homey.devices.getDevices();

// Find the specified sensor
const sensor = Object.values(devices).find(device => device.name === SENSOR_NAME);

// Find the specified fan
const fanDevice = Object.values(devices).find(device => device.name === FAN_NAME);

// Check if the sensor was found
if (sensor && sensor.capabilitiesObj) {
    console.log(`\n=== ${sensor.name} ===`);

    for (const capability of Object.values(sensor.capabilitiesObj)) {
        console.log(`${capability.title}: ${capability.value}`);
    }
} else {
    console.error(`Sensor '${SENSOR_NAME}' not found or does not have measurable values.`);
    return; // Stop execution if the sensor is not found
}

// Get current humidity value
let current;

if (TEST_MODE) {
    current = TEST_HUMIDITY_VALUE;
} else {
    if (sensor && sensor.capabilitiesObj) {
        if (sensor.capabilitiesObj.measure_humidity) {
            current = toInteger(sensor.capabilitiesObj.measure_humidity.value);
        } else {
            console.error(`Error: '${SENSOR_NAME}' device does not have a valid humidity capability.`);
            return;
        }
    } else {
        console.error(`Error: '${SENSOR_NAME}' device not found or does not have measurable values.`);
        return;
    }
}

console.log(`Current Humidity: ${current}`);

// Check if the sensor is on or has some weird reading
if (current === 0 || isNaN(current)) {
    console.log(`${LABEL}current is 0 or NaN. Skipping this reading`);
    return;
}

if (PRINT_MODE) {
    console.log(`${LABEL}Current humidity: ${current}`);
}

// Increase cycle counter
let humCounter = global.get('humCounter') || 0;
let humidityTmin5 = global.get('humidityTmin5') || 0; // Youngest reading
let humidityTmin10 = global.get('humidityTmin10') || 0; // Oldest reading
let targetFanOffHumidity = global.get('targetFanOffHumidity') || 0; // Target humidity
let fanMaxTimer = global.get('fanMaxTimer') || 0;
let fanFollowsProgram = global.get('fanFollowsProgram') || 0; // Marker indicating that the decrease program is started

let target = 0; // Will hold the target humidity when the program starts

// Check if the sensor is on or has some weird reading
if (current === 0 || isNaN(current)) {
    console.log(`${LABEL}current is 0 or NaN. Skipping this reading`);
    return;
}

// Increase cycle counter
humCounter++;

if (humCounter >= SAMPLE_INTERVAL) {
    if (humidityTmin5 === 0) {
        // Initialization, assume this is the first time
        humidityTmin5 = current;
        humidityTmin10 = current;
    }

    humCounter = 0; // Reset the cycle counter

    // Pick the lowest history value to calculate the delta
    const delta = current - Math.min(humidityTmin10, humidityTmin5);

    if (PRINT_MODE) {
        console.log(`${LABEL}Delta: ${delta}`);
    }

    // Pick the lowest history value
    target = Math.min(humidityTmin10, humidityTmin5) + TARGET_OFFSET;

    // Shift the previous measurements
    humidityTmin10 = humidityTmin5;
    // And store the current
    humidityTmin5 = current;

    // Get the current fan state
    const fanState = fanDevice ? fanDevice.state : 'unknown';

    if (PRINT_MODE) {
        console.log(`${LABEL}Fan state: ${fanState}`);
    }

    if (fanDevice && (fanState === 'off' || (fanState === 'on' && fanFollowsProgram === 0))) {
        // Either the fan is off or it is on but the decrease program has not started
        // In the latter case, we start the program anyway. This could happen if someone turns on the ventilator
        // manually because he/she is about to take a shower and doesn't like damp mirrors.
        // I don't do this because the ventilator removes heat from the bathroom, and I want this to happen
        // as late as possible ;-)

        if (fanFollowsProgram === 1 && fanState === 'off') {
            // Likely someone turned off the ventilator while the program was running
            fanFollowsProgram = 1;
        }

        // See if we have to turn it on
        if (delta >= FAN_DELTA_TRIGGER) {
            // Time to start the fan
            log(`Turning '${FAN_NAME}' on...`);
            await Homey.devices.setCapabilityValue({ deviceId: FAN_NAME, capability: 'onoff' }, true)
                .then(() => log('OK'))
                .catch(error => log(`Error:`, error));

            targetFanOffHumidity = target;

            if (fanFollowsProgram === 1) {
                console.log('Ventilator was already on, but we start the de-humidifying program');
            }

            fanFollowsProgram = 1;

            // Set the safety stop
            fanMaxTimer = FAN_MAX_TIME;

            if (PRINT_MODE) {
                console.log(`${LABEL}Rise in humidity. Turning on the vents. Delta: ${delta}`);
                console.log(`${LABEL}Target humidity for turning the ventilator: ${targetFanOffHumidity}`);
            }
        }
    } else {
        if (fanMaxTimer > 0) {
            // Possible that someone started the ventilator manually
            fanMaxTimer--;
        }

        if (fanFollowsProgram === 1) { // Not manually started
            if (delta >= FAN_DELTA_TRIGGER) {
                // Ok, there is another FAN_DELTA_TRIGGER rise in humidity
                // When this happens, we reset the fanMaxTimer to a new countdown
                // because we have to ventilate a bit longer due to the extra humidity
                if (PRINT_MODE) {
                    console.log(`${LABEL}Another large increase detected, resetting max timer. Delta: ${delta}`);
                }
                fanMaxTimer = FAN_MAX_TIME;
            }

            // First see if it can be turned off
            if (current <= targetFanOffHumidity || fanMaxTimer === 0) {
                log(`Turning '${FAN_NAME}' off...`);
                await Homey.devices.setCapabilityValue({ deviceId: FAN_NAME, capability: 'onoff' }, false)
                    .then(() => log('OK'))
                    .catch(error => log(`Error:`, error));

                let msg = '';

                if (fanMaxTimer === 0 && current > targetFanOffHumidity) {
                    msg = 'Target not reached, but safety time-out is triggered.';
                    if (PRINT_MODE) {
                        console.log(msg);
                    }
                } else {
                    msg = 'Target humidity reached';
                    if (PRINT_MODE) {
                        console.log(`${LABEL}${msg}`);
                    }
                }

                if (PRINT_MODE) {
                    console.log(`${LABEL}Turning off the ventilator`);
                    console.log(`Ventilator is off: ${msg}`);
                }

                targetFanOffHumidity = 0;
                fanMaxTimer = 0;
                fanFollowsProgram = 0;
                // Reset history in this case, we start all over
                // Tmin10 is still in the 'ventilator=On'-zone
                humidityTmin10 = humidityTmin5;
            } else {
                // We haven't reached the target yet
                if (PRINT_MODE) {
                    console.log(`${LABEL}Humidity delta: ${delta}`);
                }
            }
        }
    }
}

if (PRINT_MODE) {
    console.log(`${LABEL}Current humidity: ${current}`);
    console.log(`${LABEL}targetFanOffHumidity: ${targetFanOffHumidity}`);
    console.log(`${LABEL}humidityTmin5: ${humidityTmin5}`);
    console.log(`${LABEL}humidityTmin10: ${humidityTmin10}`);
    console.log(`${LABEL}fanMaxTimer: ${fanMaxTimer}`);
    console.log(`${LABEL}humCounter: ${humCounter}`);
    console.log(`${LABEL}fanFollowsProgram: ${fanFollowsProgram}`);
    
    // Find the specified fan
    const fanDevice = Object.values(devices).find(device => device.name === FAN_NAME);

    // Check if the fan was found
    if (fanDevice && fanDevice.capabilitiesObj) {
        // Get the current fan state
        const fanState = fanDevice.capabilitiesObj.onoff.value ? 'on' : 'off';
        console.log(`${LABEL}Fan state: ${fanState}`);
    } else {
        console.error(`Fan '${FAN_NAME}' not found or does not have valid capabilities.`);
    }
}


// Get current values of global variables
let humCounterGlobal = global.get('humCounter') || 0;
let humidityTmin10Global = global.get('humidityTmin10') || 0;
let humidityTmin5Global = global.get('humidityTmin5') || 0;
let targetFanOffHumidityGlobal = global.get('targetFanOffHumidity') || 0;
let fanMaxTimerGlobal = global.get('fanMaxTimer') || 0;
let fanFollowsProgramGlobal = global.get('fanFollowsProgram') || 0;

// Initialize variables if they don't exist
humidityTmin10Global = humidityTmin10Global || 0;
humidityTmin5Global = current || 0;
targetFanOffHumidityGlobal = target + TARGET_OFFSET || 0;

// Save the updated values
global.set('humCounter', humCounterGlobal + 1);
global.set('humidityTmin10', humidityTmin10Global);
global.set('humidityTmin5', humidityTmin5Global);
global.set('targetFanOffHumidity', targetFanOffHumidityGlobal);
global.set('fanMaxTimer', fanMaxTimerGlobal || 0);
global.set('fanFollowsProgram', fanFollowsProgramGlobal || 0);

Ik denk dat je beter kunt beginnen met debuggen en proberen de fout te isoleren.
Ik zie alleen maar code, geen foutmeldingen, geen logging.

Test met een simpele normale flow of dat schakelen wel lukt. Dan weet je tenminste dat Homey die ventilator wél kan schakelen. Schrijf vervolgens een klein scriptje om daarmee dan die ventilator aan te zetten.

ja sorry dat was geen handige zet.

// Define devices
const FAN_NAME = 'Ventilatie Badkamer Max';
const SENSOR_NAME = 'Multisensor 6';
const targetDeviceName = 'Ventilatie Badkamer Max';

// Script constants
const SAMPLE_INTERVAL = 5; // Time in minutes when the script logic will happen
const FAN_DELTA_TRIGGER = 3; // Rise in humidity that will trigger the fan
const FAN_MAX_TIME = 15; // Maximum amount of sample cycles the fan can be on if the target humidity is not reached
const TARGET_OFFSET = 5; // Ventilator goes off if target+offset is reached
const LABEL = '- Humidity control - ';

// Test/debug
const TEST_MODE = false; // When true, use a test humidity value instead of the real sensor
const TEST_HUMIDITY_VALUE = 70; // Set your desired test humidity value
const PRINT_MODE = true; // Set to true to print output to log and send notifications

// Function to convert a string to an integer
function toInteger(str) {
    return Math.floor(Number(str));
}

// Get all devices
const devices = await Homey.devices.getDevices();

// Find the target device
const targetDevice = Object.values(devices).find(device => device.name === targetDeviceName);

// Check if the target device is found
if (targetDevice) {
    // Log the available capabilities for the target device
    console.log('Available capabilities:', Object.keys(targetDevice.capabilitiesObj));

    // Turn the device on by setting the capability `onoff` to `true`
    await targetDevice.setCapabilityValue('onoff', true)
        .then(() => console.log('OK'))
        .catch(error => console.error('Error:', error));
} else {
    console.error(`Device '${targetDeviceName}' not found.`);
}

// Find the specified sensor
const sensor = Object.values(devices).find(device => device.name === SENSOR_NAME);

// Find the specified fan
const fanDevice = Object.values(devices).find(device => device.name === FAN_NAME);

// Check if the sensor was found
if (sensor && sensor.capabilitiesObj) {
    console.log(`\n=== ${sensor.name} ===`);

    for (const capability of Object.values(sensor.capabilitiesObj)) {
        console.log(`${capability.title}: ${capability.value}`);
    }
} else {
    console.error(`Sensor '${SENSOR_NAME}' not found or does not have measurable values.`);
    return; // Stop execution if the sensor is not found
}

// Get current humidity value
let current;

if (TEST_MODE) {
    current = TEST_HUMIDITY_VALUE;
} else {
    if (sensor && sensor.capabilitiesObj) {
        if (sensor.capabilitiesObj.measure_humidity) {
            current = toInteger(sensor.capabilitiesObj.measure_humidity.value);
        } else {
            console.error(`Error: '${SENSOR_NAME}' device does not have a valid humidity capability.`);
            return;
        }
    } else {
        console.error(`Error: '${SENSOR_NAME}' device not found or does not have measurable values.`);
        return;
    }
}

console.log(`Current Humidity: ${current}`);

// Check if the sensor is on or has some weird reading
if (current === 0 || isNaN(current)) {
    console.log(`${LABEL}current is 0 or NaN. Skipping this reading`);
    return;
}

if (PRINT_MODE) {
    console.log(`${LABEL}Current humidity: ${current}`);
}

// Increase cycle counter
let humCounter = global.get('humCounter') || 0;
let humidityTmin5 = global.get('humidityTmin5') || 0; // Youngest reading
let humidityTmin10 = global.get('humidityTmin10') || 0; // Oldest reading
let targetFanOffHumidity = global.get('targetFanOffHumidity') || 0; // Target humidity
let fanMaxTimer = global.get('fanMaxTimer') || 0;
let fanFollowsProgram = global.get('fanFollowsProgram') || 0; // Marker indicating that the decrease program is started

let target = 0; // Will hold the target humidity when the program starts

// Check if the sensor is on or has some weird reading
if (current === 0 || isNaN(current)) {
    console.log(`${LABEL}current is 0 or NaN. Skipping this reading`);
    return;
}

// Increase cycle counter
humCounter++;

if (humCounter >= SAMPLE_INTERVAL) {
    if (humidityTmin5 === 0) {
        // Initialization, assume this is the first time
        humidityTmin5 = current;
        humidityTmin10 = current;
    }

    humCounter = 0; // Reset the cycle counter

    // Pick the lowest history value to calculate the delta
    const delta = current - Math.min(humidityTmin10, humidityTmin5);

    if (PRINT_MODE) {
        console.log(`${LABEL}Delta: ${delta}`);
    }

    // Pick the lowest history value
    target = Math.min(humidityTmin10, humidityTmin5) + TARGET_OFFSET;

    // Shift the previous measurements
    humidityTmin10 = humidityTmin5;
    // And store the current
    humidityTmin5 = current;

    // Get the current fan state
    const fanState = fanDevice ? fanDevice.state : 'unknown';

    if (PRINT_MODE) {
        console.log(`${LABEL}Fan state: ${fanState}`);
    }

    if (fanDevice && (fanState === 'off' || (fanState === 'on' && fanFollowsProgram === 0))) {
        // Either the fan is off or it is on but the decrease program has not started
        // In the latter case, we start the program anyway. This could happen if someone turns on the ventilator
        // manually because he/she is about to take a shower and doesn't like damp mirrors.
        // I don't do this because the ventilator removes heat from the bathroom, and I want this to happen
        // as late as possible ;-)

        if (fanFollowsProgram === 1 && fanState === 'off') {
            // Likely someone turned off the ventilator while the program was running
            fanFollowsProgram = 1;
        }

        // See if we have to turn it on
        if (delta >= FAN_DELTA_TRIGGER) {
            // Time to start the fan
            log(`Turning '${FAN_NAME}' on...`);
            
            const onoffCapability = fanDevice.capabilitiesObj.onoff;
            
            if (onoffCapability) {
                await onoffCapability.set(true)
                    .then(() => log('OK'))
                    .catch(error => log(`Error:`, error));
            } else {
                console.error(`Error: '${FAN_NAME}' device does not have a valid 'onoff' capability.`);
            }

            targetFanOffHumidity = target;

            if (fanFollowsProgram === 1) {
                console.log('Ventilator was already on, but we start the de-humidifying program');
            }

            fanFollowsProgram = 1;

            // Set the safety stop
            fanMaxTimer = FAN_MAX_TIME;

            if (PRINT_MODE) {
                console.log(`${LABEL}Rise in humidity. Turning on the vents. Delta: ${delta}`);
                console.log(`${LABEL}Target humidity for turning the ventilator: ${targetFanOffHumidity}`);
            }
        }
    } else {
        if (fanMaxTimer > 0) {
            // Possible that someone started the ventilator manually
            fanMaxTimer--;
        }

        if (fanFollowsProgram === 1) { // Not manually started
            if (delta >= FAN_DELTA_TRIGGER) {
                // Ok, there is another FAN_DELTA_TRIGGER rise in humidity
                // When this happens, we reset the fanMaxTimer to a new countdown
                // because we have to ventilate a bit longer due to the extra humidity
                if (PRINT_MODE) {
                    console.log(`${LABEL}Another large increase detected, resetting max timer. Delta: ${delta}`);
                }
                fanMaxTimer = FAN_MAX_TIME;
            }

            // First see if it can be turned off
            if (current <= targetFanOffHumidity || fanMaxTimer === 0) {
                log(`Turning '${FAN_NAME}' off...`);
                
                const onoffCapability = fanDevice.capabilitiesObj.onoff;
                
                if (onoffCapability) {
                    await onoffCapability.set(false)
                        .then(() => log('OK'))
                        .catch(error => log(`Error:`, error));
                } else {
                    console.error(`Error: '${FAN_NAME}' device does not have a valid 'onoff' capability.`);
                }

                let msg = '';

                if (fanMaxTimer === 0 && current > targetFanOffHumidity) {
                    msg = 'Target not reached, but safety time-out is triggered.';
                    if (PRINT_MODE) {
                        console.log(msg);
                    }
                } else {
                    msg = 'Target humidity reached';
                    if (PRINT_MODE) {
                        console.log(`${LABEL}${msg}`);
                    }
                }

                if (PRINT_MODE) {
                    console.log(`${LABEL}Turning off the ventilator`);
                    console.log(`Ventilator is off: ${msg}`);
                }

                targetFanOffHumidity = 0;
                fanMaxTimer = 0;
                fanFollowsProgram = 0;
                // Reset history in this case, we start all over
                // Tmin10 is still in the 'ventilator=On'-zone
                humidityTmin10 = humidityTmin5;
            } else {
                // We haven't reached the target yet
                if (PRINT_MODE) {
                    console.log(`${LABEL}Humidity delta: ${delta}`);
                }
            }
        }
    }
}

if (PRINT_MODE) {
    console.log(`${LABEL}Current humidity: ${current}`);
    console.log(`${LABEL}targetFanOffHumidity: ${targetFanOffHumidity}`);
    console.log(`${LABEL}humidityTmin5: ${humidityTmin5}`);
    console.log(`${LABEL}humidityTmin10: ${humidityTmin10}`);
    console.log(`${LABEL}fanMaxTimer: ${fanMaxTimer}`);
    console.log(`${LABEL}humCounter: ${humCounter}`);
    console.log(`${LABEL}fanFollowsProgram: ${fanFollowsProgram}`);
    
    // Find the specified fan
    const fanDevice = Object.values(devices).find(device => device.name === FAN_NAME);

    // Check if the fan was found
    if (fanDevice && fanDevice.capabilitiesObj) {
        // Get the current fan state
        const fanState = fanDevice.capabilitiesObj.onoff.value ? 'on' : 'off';
        console.log(`${LABEL}Fan state: ${fanState}`);
    } else {
        console.error(`Fan '${FAN_NAME}' not found or does not have valid capabilities.`);
    }
}


// Get current values of global variables
let humCounterGlobal = global.get('humCounter') || 0;
let humidityTmin10Global = global.get('humidityTmin10') || 0;
let humidityTmin5Global = global.get('humidityTmin5') || 0;
let targetFanOffHumidityGlobal = global.get('targetFanOffHumidity') || 0;
let fanMaxTimerGlobal = global.get('fanMaxTimer') || 0;
let fanFollowsProgramGlobal = global.get('fanFollowsProgram') || 0;

// Initialize variables if they don't exist
humidityTmin10Global = humidityTmin10Global || 0;
humidityTmin5Global = current || 0;
targetFanOffHumidityGlobal = target + TARGET_OFFSET || 0;

// Save the updated values
global.set('humCounter', humCounterGlobal + 1);
global.set('humidityTmin10', humidityTmin10Global);
global.set('humidityTmin5', humidityTmin5Global);
global.set('targetFanOffHumidity', targetFanOffHumidityGlobal);
global.set('fanMaxTimer', fanMaxTimerGlobal || 0);
global.set('fanFollowsProgram', fanFollowsProgramGlobal || 0);

geeft deze foutmelding

Available capabilities: [ 'onoff' ]
OK

=== Multisensor 6 ===
Ultraviolet: 0
Luchtvochtigheid: 50
Helderheid: 24
Temperatuur: 21.7
Sabotagealarm: false
Bewegingsalarm: false
Accuniveau: 100
Current Humidity: 50
- Humidity control - Current humidity: 50
- Humidity control - Delta: -18
- Humidity control - Fan state: undefined
Turning 'Ventilatie Badkamer Max' off...

———————————————————
❌ Script Error
⚠️ TypeError: onoffCapability.set is not a function
    at test 7.js:208:43
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async HomeyScriptApp.runScript (/app/app.js:495:22)
    at async Object.runScript (/app/api.js:30:22)

nu heb ik het al wel voor elkaar dat als ik de testmode aanzet en op 100 % vocht fake stuur, dat de ventilatie wel aangeschakeld word… nu nog uit…

Probeer eens daar waar je hem aanzet, juist uit te zetten. Dus true door false te vervangen.

Heb weer wat aanpassingen gemaakt en dit lijkt goed??
als ik test met een lage waarde schakelt hij mijn virtuele device (die uiteindelijk mij ventilatie schakelt) uit.
en met een hoge vochtwaarde schakelt hij dit device aan.

nu alleen testen in het echt.

zoals in het lua script aangegeven word moet het een time based script zijn.

begrijp ik dan goed dat ik een flow aanmaak met ALS “iedere minuut” Dan “start script”?
of zit ik dan totaal verkeerd?

en ik begrijp van je dat je er wel wat verstand van hebt… zou jij hier eens een plasje over willen doen.

alvast bedankt voor de genomen moeite!

20:39 22-11-23 laatste versie

// Define devices
const FAN_NAME = 'Ventilatie Badkamer Max';
const SENSOR_NAME = 'Multisensor 6';
const targetDeviceName = 'Ventilatie Badkamer Max';

// Script constants
const SAMPLE_INTERVAL = 5; // Time in minutes when the script logic will happen
const FAN_DELTA_TRIGGER = 3; // Rise in humidity that will trigger the fan
const FAN_MAX_TIME = 15; // Maximum amount of sample cycles the fan can be on if the target humidity is not reached
const TARGET_OFFSET = 5; // Ventilator goes off if target+offset is reached
const LABEL = '- Humidity control - ';

// Test/debug
const TEST_MODE = false; // When true, use a test humidity value instead of the real sensor
const TEST_HUMIDITY_VALUE = 100; // Set your desired test humidity value
const PRINT_MODE = true; // Set to true to print output to log and send notifications

// Function to convert a string to an integer
function toInteger(str) {
    return Math.floor(Number(str));
}

// Get all devices
const devices = await Homey.devices.getDevices();

// Find the target device
const targetDevice = Object.values(devices).find(device => device.name === targetDeviceName);

// Check if the target device is found
if (targetDevice) {
    // Log the available capabilities for the target device
    console.log('Available capabilities:', Object.keys(targetDevice.capabilitiesObj));

    // Turn the device on by setting the capability `onoff` to `true`
    await targetDevice.setCapabilityValue('onoff', true)
        .then(() => console.log('OK'))
        .catch(error => console.error('Error:', error));
} else {
    console.error(`Device '${targetDeviceName}' not found.`);
}

// Find the specified sensor
const sensor = Object.values(devices).find(device => device.name === SENSOR_NAME);

// Find the specified fan
const fanDevice = Object.values(devices).find(device => device.name === FAN_NAME);

// Check if the sensor was found
if (sensor && sensor.capabilitiesObj) {
    console.log(`\n=== ${sensor.name} ===`);

    for (const capability of Object.values(sensor.capabilitiesObj)) {
        console.log(`${capability.title}: ${capability.value}`);
    }
} else {
    console.error(`Sensor '${SENSOR_NAME}' not found or does not have measurable values.`);
    return; // Stop execution if the sensor is not found
}

// Get current humidity value
let current;

if (TEST_MODE) {
    current = TEST_HUMIDITY_VALUE;
} else {
    if (sensor && sensor.capabilitiesObj) {
        if (sensor.capabilitiesObj.measure_humidity) {
            current = toInteger(sensor.capabilitiesObj.measure_humidity.value);
        } else {
            console.error(`Error: '${SENSOR_NAME}' device does not have a valid humidity capability.`);
            return;
        }
    } else {
        console.error(`Error: '${SENSOR_NAME}' device not found or does not have measurable values.`);
        return;
    }
}

console.log(`Current Humidity: ${current}`);

// Check if the sensor is on or has some weird reading
if (current === 0 || isNaN(current)) {
    console.log(`${LABEL}current is 0 or NaN. Skipping this reading`);
    return;
}

if (PRINT_MODE) {
    console.log(`${LABEL}Current humidity: ${current}`);
}

// Increase cycle counter
let humCounter = global.get('humCounter') || 0;
let humidityTmin5 = global.get('humidityTmin5') || 0; // Youngest reading
let humidityTmin10 = global.get('humidityTmin10') || 0; // Oldest reading
let targetFanOffHumidity = global.get('targetFanOffHumidity') || 0; // Target humidity
let fanMaxTimer = global.get('fanMaxTimer') || 0;
let fanFollowsProgram = global.get('fanFollowsProgram') || 0; // Marker indicating that the decrease program is started

let target = 0; // Will hold the target humidity when the program starts

// Check if the sensor is on or has some weird reading
if (current === 0 || isNaN(current)) {
    console.log(`${LABEL}current is 0 or NaN. Skipping this reading`);
    return;
}

// Increase cycle counter
humCounter++;

if (humCounter >= SAMPLE_INTERVAL) {
    if (humidityTmin5 === 0) {
        // Initialization, assume this is the first time
        humidityTmin5 = current;
        humidityTmin10 = current;
    }

    humCounter = 0; // Reset the cycle counter

    // Pick the lowest history value to calculate the delta
    const delta = current - Math.min(humidityTmin10, humidityTmin5);

    if (PRINT_MODE) {
        console.log(`${LABEL}Delta: ${delta}`);
    }

    // Pick the lowest history value
    target = Math.min(humidityTmin10, humidityTmin5) + TARGET_OFFSET;

    // Shift the previous measurements
    humidityTmin10 = humidityTmin5;
    // And store the current
    humidityTmin5 = current;

    // Get the current fan state
    const fanState = fanDevice ? fanDevice.state : 'unknown';

    if (PRINT_MODE) {
        console.log(`${LABEL}Fan state: ${fanState}`);
    }

    if (fanDevice && (fanState === 'off' || (fanState === 'on' && fanFollowsProgram === 0))) {
        // Either the fan is off or it is on but the decrease program has not started
        // In the latter case, we start the program anyway. This could happen if someone turns on the ventilator
        // manually because he/she is about to take a shower and doesn't like damp mirrors.
        // I don't do this because the ventilator removes heat from the bathroom, and I want this to happen
        // as late as possible ;-)

        if (fanFollowsProgram === 1 && fanState === 'off') {
            // Likely someone turned off the ventilator while the program was running
            fanFollowsProgram = 1;
        }

        // See if we have to turn it on
        if (delta >= FAN_DELTA_TRIGGER) {
            // Time to start the fan
            log(`Turning '${FAN_NAME}' on...`);
            
            const onoffCapability = fanDevice.capabilitiesObj.onoff;
            
            if (onoffCapability) {
                await onoffCapability.set(true)
                    .then(() => log('OK'))
                    .catch(error => log(`Error:`, error));
            } else {
                console.error(`Error: '${FAN_NAME}' device does not have a valid 'onoff' capability.`);
            }

            targetFanOffHumidity = target;

            if (fanFollowsProgram === 1) {
                console.log('Ventilator was already on, but we start the de-humidifying program');
            }

            fanFollowsProgram = 1;

            // Set the safety stop
            fanMaxTimer = FAN_MAX_TIME;

            if (PRINT_MODE) {
                console.log(`${LABEL}Rise in humidity. Turning on the vents. Delta: ${delta}`);
                console.log(`${LABEL}Target humidity for turning the ventilator: ${targetFanOffHumidity}`);
            }
        }
    } else {
        if (fanMaxTimer > 0) {
            // Possible that someone started the ventilator manually
            fanMaxTimer--;
        }

        if (fanFollowsProgram === 1) { // Not manually started
            if (delta >= FAN_DELTA_TRIGGER) {
                // Ok, there is another FAN_DELTA_TRIGGER rise in humidity
                // When this happens, we reset the fanMaxTimer to a new countdown
                // because we have to ventilate a bit longer due to the extra humidity
                if (PRINT_MODE) {
                    console.log(`${LABEL}Another large increase detected, resetting max timer. Delta: ${delta}`);
                }
                fanMaxTimer = FAN_MAX_TIME;
            }

            // Check if the target device is found
            if (targetDevice) {
                // Log the available capabilities for the target device
                console.log('Available capabilities:', Object.keys(targetDevice.capabilitiesObj));
                
                // Turn the device off by setting the capability `onoff` to `false`
                await targetDevice.setCapabilityValue('onoff', false)
                .then(() => console.log('OK'))
                .catch(error => console.error('Error:', error));                                                 
                } else {
                    console.error(`Device '${targetDeviceName}' not found.`);
                }

                let msg = '';

                if (fanMaxTimer === 0 && current > targetFanOffHumidity) {
                    msg = 'Target not reached, but safety time-out is triggered.';
                    if (PRINT_MODE) {
                        console.log(msg);
                    }
                } else {
                    msg = 'Target humidity reached';
                    if (PRINT_MODE) {
                        console.log(`${LABEL}${msg}`);
                    }
                }

                if (PRINT_MODE) {
                    console.log(`${LABEL}Turning off the ventilator`);
                    console.log(`Ventilator is off: ${msg}`);
                }
                

                targetFanOffHumidity = 0;
                fanMaxTimer = 0;
                fanFollowsProgram = 0;
                // Reset history in this case, we start all over
                // Tmin10 is still in the 'ventilator=On'-zone
                humidityTmin10 = humidityTmin5;
            } else {
                // We haven't reached the target yet
                if (PRINT_MODE) {
                    console.log(`${LABEL}Humidity delta: ${delta}`);
                }
            }
        }
    }


if (PRINT_MODE) {
    console.log(`${LABEL}Current humidity: ${current}`);
    console.log(`${LABEL}targetFanOffHumidity: ${targetFanOffHumidity}`);
    console.log(`${LABEL}humidityTmin5: ${humidityTmin5}`);
    console.log(`${LABEL}humidityTmin10: ${humidityTmin10}`);
    console.log(`${LABEL}fanMaxTimer: ${fanMaxTimer}`);
    console.log(`${LABEL}humCounter: ${humCounter}`);
    console.log(`${LABEL}fanFollowsProgram: ${fanFollowsProgram}`);
    
    // Find the specified fan
    const fanDevice = Object.values(devices).find(device => device.name === FAN_NAME);

    // Check if the fan was found
    if (fanDevice && fanDevice.capabilitiesObj) {
        // Get the current fan state
        const fanState = fanDevice.capabilitiesObj.onoff.value ? 'on' : 'off';
        console.log(`${LABEL}Fan state: ${fanState}`);
    } else {
        console.error(`Fan '${FAN_NAME}' not found or does not have valid capabilities.`);
    }
}


// Get current values of global variables
let humCounterGlobal = global.get('humCounter') || 0;
let humidityTmin10Global = global.get('humidityTmin10') || 0;
let humidityTmin5Global = global.get('humidityTmin5') || 0;
let targetFanOffHumidityGlobal = global.get('targetFanOffHumidity') || 0;
let fanMaxTimerGlobal = global.get('fanMaxTimer') || 0;
let fanFollowsProgramGlobal = global.get('fanFollowsProgram') || 0;

// Initialize variables if they don't exist
humidityTmin10Global = humidityTmin10Global || 0;
humidityTmin5Global = current || 0;
targetFanOffHumidityGlobal = target + TARGET_OFFSET || 0;

// Save the updated values
global.set('humCounter', humCounterGlobal + 1);
global.set('humidityTmin10', humidityTmin10Global);
global.set('humidityTmin5', humidityTmin5Global);
global.set('targetFanOffHumidity', targetFanOffHumidityGlobal);
global.set('fanMaxTimer', fanMaxTimerGlobal || 0);
global.set('fanFollowsProgram', fanFollowsProgramGlobal || 0);

Wat ik me ook nog steeds afvraag is waarom de variabelen die ik aangemaakt heb niet wijzigen.
en dat het script wel andere waardes heeft en ik die weer nergens in homey naar voor kan halen?

maar dat terzijde

Dan belast je Homey onnodig vaak. Beter is een ALS met “als vochtigheid verandert is”. En dan onder AND een logica gebruiken waarop je test of de vochtigheid groter dan een zekere waarde is. En dan onder het THEN deel je script (neem ik aan). Dat laatste heb ik geen ervaring mee. Zal in de app HomeScript wel een kaartje voor zijn.

Om vanuit de code het regelalgoritme te halen vindt ik te veel moeite en gaat alleen maar vragen oproepen. Daar is het functioneel ontwerp cq use case voor, die je natuurlijk wel in je hoofd heb zitten. Maar als je script nu werkt is dat mooi!

Hoe en waar zie je dat de variabelen niet wijzigen? In Homey heb je variabelen, die je aanmaakt onder variabelen, en tags. Deze laatste zie ik als objectkenmerken. Misschien dat de variabelen in je script tags zijn van HomeyScript? Dan bestaan ze alleen zolang de flow uitgevoerd wordt. Je kunt ze met een bericht naar de tijdslijn loggen.

ik moet wel op “tijd” triggeren want dat activeert ook de maximum instelbare looptijd.

ik ja ik heb het script gestart met een flow. dat werkt

image
dit zijn de variabelen die ik heb aan gemaakt in homey.
en deze zijn nog nooit anders dan 0 geweest.

terwijl dit in mijn logconsole komt
=== Multisensor 6 ===

Ultraviolet: 0

Luchtvochtigheid: 60

Helderheid: 4

Temperatuur: 23.2

Sabotagealarm: false

Bewegingsalarm: false

Accuniveau: 100

Current Humidity: 60

  • Humidity control - Current humidity: 60

  • Humidity control - Delta: -1

  • Humidity control - Fan state: undefined

  • Humidity control - Current humidity: 60

  • Humidity control - targetFanOffHumidity: 71

  • Humidity control - humidityTmin5: 60

  • Humidity control - humidityTmin10: 61

  • Humidity control - fanMaxTimer: 15

  • Humidity control - humCounter: 0

  • Humidity control - fanFollowsProgram: 1

  • Humidity control - Fan state: on

——————————————————— :white_check_mark: Script Success

:leftwards_arrow_with_hook: Returned: undefined

dus die waarde van mijn log console zou ik graag geupdate zien in mijn homey variabelen.
zo kan ik ook beter monitoren wat er op de achtergrond gebeurd in het javascript.
maar ik heb echt geen idee hoe dat moet.

en wat betreft het script homey zegt dat alles werkt maar in tegendeel.
er zit nog iets fout in fanmaxtimer.
als ik heb goed heb begrepen dan zou er een teller moeten lopen dat als iedere 5 minuten het script getriggerd word er een variable optelt dus na 15 min zou deze dan op 3 moeten staan bijv.

als dan de vochtigheid niet gehaald is door bijv natte handdoeken in de badkamer. dan schakelt hij toch de ventilator weer uit. soort failsafe.

maar dit brengt mij weer naar die variabelen. ik denk dat dit niet goed weggeschreven word.

dit word de volgende stap om te onderzoeken.

mochten er meer mensen zijn die dit lezen en kennis hebben van homey script en van javascript icm variabelen dan is alle hulp ook welkom.

Een script variabele is een ander ding dan een flow variabele. Wil je de waarden kunnen volgen, dan zul je sowieso ze op diverse plaatsen in je code moeten loggen. Al zou je ze kopiëren naar de flow variabele, heb je daar altijd alleen maar de laatste waarde staan na afloop van je script.

Een script variabele bestaat alleen tijdens het uitvoeren van de script. Zo te zien, wil je dat de variabelen blijven bestaan tussen de verschillende run’s van een script. Dan moet je ze dus telkens naar een persistent store opslaan. Een bestand, en kan in dit geval misschien ook in een flow variabele.

Je gebruikt 2 ventilatoren die het zelfde zijn. Je zoekt de ventilator dan ook twee keer op.
FAN_NAME = ‘Ventilatie Badkamer Max’;
targetDeviceName = ‘Ventilatie Badkamer Max’;

Wat heb je verandert dat de ventilator nu wel uit gaat?
En hoe zie je dat de ventilator met de hand is aangezet, en niet met je script?
Je zit erg op code niveau, terwijl de grote lijnen, de structuur ontbreekt. Met welke schakelaar zet iemand het licht aan en uit, welke vochtsensor, en waarmee schakel je de ventilator aan en uit. Bij welke vochtigheid aan, bij welke uit? Welke apps gebruik je daarvoor. Kennelijk stuur je op delta vochtigheid en niet op absolute waarden. Maar uit je code begrijp ik je berekening niet, maar ik weet ook niet wat je wilt bereiken met die berekening.

Als je code omzet van het ene naar het andere systeem, heb je natuurlijk altijd kans dat het qua manier van werken er niet goed in past.
Waarom maak je geen simpele normale flow? Dan zie je gelijk de kracht en manier van denken in Homey. En hoe je vochtigheidsberekening daar ingepast kan worden.

WHEN vochtigheid is verandert
AND vochtigheid > 50
THEN start ventilator
ELSE stop ventilator

Vervolgens stop je er nog wat voorwaarden in om te voorkomen dat de ventilator gestart wordt als die al draait, gestopt wordt als die al stil staat.

Ik krijg een beetje het idee dat je de LUA script niet zelf geschreven hebt.

dat klopt dt lua script heb ik ooit eens in een verleden op het domoticz forum opgepikt.
maar gezien ik nu van domoticz naar homey ga wil ik dit op dezelfde manier inregelen omdat dit fout en naadloos werkte.

en de rest wat ik hier in het homey forum is een stuk beperkter. dus probeer ik mijn oude lua aan de gang te krijgen

Volgens mij is dit forum bedoeld voor mensen die hun eigen systeem bedenken, ontwerpen en implementeren, daarbij af en toe wat vragen hebben en willen leren.
Dat mis ik een beetje bij jou. Dan is voor mij de lol er wel een beetje af. Dan kun je beter op zoek gaan naar iemand die het allemaal voor je regelt.

jammer.
wil hier ook niet off topic gaan maar volgens mij is een forum voor iedereen die het op zijn eigen manier wil doen, ontwerpen, bouwen/verbouwen of zelfs simpelweg kopiëren.

maar dat je me niet wil helpen dat begrijp ik aan je reactie.
jammer… maar dat zal me niet doen opgeven.

ik had alleen maar een hulpvraag gesteld of iemand met me mee kon kijken en zoals ik al in de eerste hulpvraag vermeld had…

Hier had ik een heel mooi Lua script voor lopen en met alle eerlijkheid dat was knip en plakwerk hier en daar wat tweaken en liep als een zonnetje.

maar toch bedankt voor je genomen moeite! :pray:

Ik heb het anders aangepakt, wellicht heb je er wat aan, met advanced flows, overigens.
Ik heb 2 badkamers en een toilet.
Als het toilet actief wordt, gaat de afzuiging aan en 5 minuten na inactief weer uit TENZIJ de fan ook aanstaat omdat het vochtig is in een van de badkamers.
De vochtigheid van de badkamers meet ik door zowel in als buiten beide badkamers de vochtigheid te meten. Als die buiten / binnen een door mij bepaald vochtigheid%. valt, gaat de ventilator aan of uit (en ook hier: alleen uit als er op de andere plekken ook geen vocht / aanwezigheid toilet is.

Vind ik een stuk eenvoudiger, te meer ik geen kaas van java heb gegeten. Ik zou zelf ook geen aansturing willen hebben die ik niet helemaal begrijp (but that’s me).

De ventilator (Ducobox) draait altijd op de standby stand, en als toilet actief is of een van de badkamers vochtig, dan vol vermogen.
Wordt geschakeld met een inbouw kika schakelaar.

Hopelijk kan je er wat mee, in ieder geval veel succes!

Dank je voor het meedenken!
Ziet er zeker goed uit en met 2 badkamers alweer een stukje gecompliceerder.

Maar zoals je hebt gelezen geef ik niet snel op.
Dus momenteel heb ik de hele werking in een advanced flow gebouwd. Het was wel even werk maar het draait nu in een testfase en so far so good.
Mocht ik er naar tevredenheid mee zijn zal ik hem wel posten, kijken of een extern oog er nog foutjes in ziet zitten… :wink:
of evt verbeteringen of aanvullingen die me aanspreken!