Page 1 of 1

if..then only runs once

Posted: Friday 24 March 2023 14:19
by ajseesink
Hi,

I guess this topic is posted several times, but I just can't find an answer.
I have the following LUA script created in the embedded Domoticz editor, with trigger type Device.

Door open/close status works.
At open, the doorOpenTime is set and the debug message is printed in de log.
At close, the doorOpenTime is set to nil and the debug message is printed in the log.

The second if then is used as debug.
The third if then should print the message in the log.

However, the second if then is called only once. I didn't expect that one. I expected it to be called every time when doorOpenTime is set.
This also means that the third if then behaves the same way. It never reaches the value of 120.

Can anyone explain what I'm doing wrong? And hopefully how to solve this one?


commandArray = {}

if (devicechanged['Kastdeur'] == 'On') then
doorOpenTime = os.time() -- get the current time
print('--->>> Deur: Deur is nu open')
elseif (devicechanged['Kastdeur'] == 'Off') then
doorOpenTime = nil -- reset the timer
print('--->>> Deur: Deur is nu dicht')
end

-- Print time as debug
if (doorOpenTime ~= nil ) then
print('doorOpenTime is: ' .. doorOpenTime)
end


-- check if the door has been open for more than 2 minutes
if (doorOpenTime ~= nil and os.difftime(os.time(), doorOpenTime) > 120) then
print('Door has been open for more than 2 minutes!')
end

return commandArray


Thanks ahead
Andre

Re: if..then only runs once

Posted: Friday 24 March 2023 14:28
by jvdz
You assume that doorOpenTime is a persistent variable, but it only lives during the execution of the script! Dzvents has the option to use persistent values.
On top of that: there needs to be a time trigger to test for duration of the last change. When you add the time trigger, you could add a test for the device being open and the time of the last change being longer than x number of seconds.