Hulp gevraagd bij het ultieme badkamer vochtregeling script

Astrapowerrr
Mon, 20 Nov 2023 19:56:40 +0000
Vragen & hulp

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);

26 posts - 7 participants