if..then only runs once

Moderator: leecollings

Post Reply
ajseesink
Posts: 9
Joined: Monday 24 December 2018 11:29
Target OS: -
Domoticz version:
Contact:

if..then only runs once

Post 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
User avatar
jvdz
Posts: 2333
Joined: Tuesday 30 December 2014 19:25
Target OS: Raspberry Pi / ODroid
Domoticz version: 4.107
Location: Netherlands
Contact:

Re: if..then only runs once

Post 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.
New Garbage collection scripts: https://github.com/jvanderzande/GarbageCalendar
Post Reply

Who is online

Users browsing this forum: No registered users and 1 guest