The Vera Community forums have moved!

Advanced => Programming => Scene Scripting => Topic started by: bennynations on September 06, 2010, 10:41:22 pm

Title: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 06, 2010, 10:41:22 pm
I have guests that love to leave the patio door open while sitting outside.  Is there some way trigger something that says if the door is open for so long...turn off the air????
Title: Re: If door is opened for 5 minutes...turn off air
Post by: raskell on September 07, 2010, 09:01:23 am
For starters, you can try having the door sensor in the armed state.  You can create an event when the armed sensor is tripped.   On the advanced tab set a 300 second delay (5 minutes).  The command tab action is turn HVAC off.  I have not done this before, but I believe you will also want to create an HVAC resume scene where every 15 minutes or so, turn the HVAC back on if the door sensor is closed.  It is obviously possible to shut off the HVAC immediately when the door opens, so try the delay and let us know how it works for you.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 07, 2010, 09:44:29 am
I understand that method, but I am looking for something that, once the sensor is triggered, monitor how long it is opened, if opened at 5 minutes, turn off the A/C.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 08, 2010, 12:30:40 pm
Does anyone have any ideas??
Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on September 08, 2010, 12:58:36 pm
So I haven't done this (and I am actually following this thread, hoping that someone who has will reply and confirm), but my strategy would be as follows.


Scene Event: Armed Sensor is tripped

Luup logic:
*Sleep for 5 minutes
* then check status of sensor.
    * If sensor is no longer tripped
              * end.
    * otherwise
              * continue to execute

Essentially what you would have here is the scene firing when the door is opened, but all the scene will do for 5 minutes is sit there watching the clock. Once the 5 minutes has expired, it'll manually (via luup code) check the status of the sensor again, and if it is still in a tripped state, then it'll execute the commands. In your case, it'd be to turn off the AC appliance control module (which is a very good idea btw). In my case, it'd be to send me an email saying you left the door open again.

I think this'll work, and the LUUP code would be pretty straightforward. I could write it up, but I'm sure someone has done it before.

Any comments from those that have done it?

Thanks

Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on September 08, 2010, 01:29:31 pm
I think this works. Here is my code:

Code: [Select]
os.execute("sleep 2")

if( luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",33)=="0" ) then
luup.log("Sensor Not Tripped, ending scene")
    return false
end


Note I have this set to sleep for only 2 seconds for testing, you'll want to change it to 300 for 5 minutes. The other thing you'll want to change is the device id (mine is 33) to match your Device.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 08, 2010, 03:28:37 pm
I am basically an end-user, so the code will be an interesting test for me.

Question

Can I test this remotely, or do I actually have to trigger the scene event??
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 08, 2010, 04:22:22 pm
I tried to get this to work, but I kept getting invalid scene.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on September 08, 2010, 04:46:32 pm
Bennynations,

What happens if you paste the code into the LUUP test window and hit go? This window can be found on UI2 in:

Devices -> Luup Plugins -> Test Luup code (Lua) - this last one is a button.

I'm not sure where this is in UI3 or 4, but I imagine it is easy to find.

You should be able to paste it in there and hit go to test, where you can absolutely test it remotely. Just remember you'll need to change the device ID (my example uses device 33) to the device number used by your sensor.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 08, 2010, 05:24:39 pm
I found the area and entered the code...it says bad device

I looked at my device and it says that urn:schemas-micasaverde-com:device:MotionSensor:1

My device is number 11

I entered the following:

os.execute("sleep 2")

if( luup.variable_get("urn:schemas-micasaverde-com:device:MotionSensor:1", "Tripped",11)=="0" ) then   
   luup.log("Sensor Not Tripped, ending scene")   
    return false
end

No luck
Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on September 08, 2010, 05:48:49 pm
Both of my door sensors (Both Hawkin HRDS1) also show up in their advanced properties as "urn:schemas-micasaverde-com:device:MotionSensor:1", but when I query the status I found I need to use urn:micasaverde-com:serviceId:SecuritySensor1.. I'm not exactly sure why that is.

I assume you tried my original snipit with just changing the device number as well, yes?

Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on September 08, 2010, 06:04:43 pm
Also, unless you aere on UI4 you don't need to put the device ID in the "Device Number" field next to the go button, just leave that blank since the device is specified in the code already. If I enter my device number in that field, I get the bad device error as well.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 08, 2010, 08:07:12 pm
I am on Vera2 and UI4.  I got it to work and then saved it in the scene.  Now that I run the scene remotely, I get "empty response."

At least it saved it properly, but I am not sure what to do now.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 08, 2010, 08:21:12 pm
Thanks so much for the help!!  Nice to learn more about this.

Everything is saved and appears to be working.  It is saved as a scene.  When I run the scene, it transmits and turns the air off. 

Is this correct??  If it is checking the status, the door is still closed.  Should it turn the AC off??
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Les F on September 08, 2010, 09:25:45 pm

Just one extra piece of logic  in case you didn't cover it. 

If door is opened for 5 minutes and air is already off don't do anything.

(you wouldn't want to turn the air on 15 minutes later if it was never on to start with)



Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 08, 2010, 09:36:30 pm
thanks for the advice, but I am lucky to just cut/paste advice.  LOL

Here is what is running now:

os.execute("sleep 5")

if( luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",11)=="0" ) then   
   luup.log("Sensor Not Tripped, ending scene")   
    return false
end

I am not concerned about turning the air back on.  The guest has been told that leaving the door open will turn the AC off.

Title: Re: If door is opened for 5 minutes...turn off air
Post by: reiserx on September 09, 2010, 02:46:15 am
I would have it set for 1 minute. It shouldn't take that long to get luggage inside. I may even make it 30 seconds. Let them suffer for being stupid and wasting energy. I had a tenant leave all the windows open with the air on too. When I saw it I just shut off  the air remotley from my phone. Then I found out they wern't even there all day. Grrrrr.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 09, 2010, 09:27:23 am
This is a balcony door.  The problem is that guests will go hang out on the balcony and leave the door open or they like the breeze from the Gulf and will just leave it open while inside the condo.  Either way, others owners seem to always complain it and I want to fix it before it happens to me.

I think the code that fall-line provided is working now that I know how to insert it. 

I still do not understand why running the scene remotely would actually turn the AC off since the patio door is closed.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Les F on September 09, 2010, 09:53:20 am

I am not an expert in when a plugin will work or how much it can really do... but there should be a 'rental / vacation home' plugin.   I guess there are too many differences in all of our places... motion sensors, door sensors,  (or info fed via alarm panel)... but this would be great for many people and perhaps even a selling point for MCV/Vera.  It could save a small fortune in utility costs for us rental owners. 

The person at my cabin this week has been playing the game of leaving the door open and the A/C on.   It's amazing what we didn't know in the past about guests and their habits. This is the first summer that I had vera online and it's an eye opener for sure.

 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: bennynations on September 09, 2010, 10:12:28 am
Good point Les! It would be beneficial. The current problem is that, while Vera is relatively easy to set-up, every individual will have something that they want "outside of the VERA box."  The Lua code is great for programmers, but it is not easily understood by the average Benny.  ;D


 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on September 14, 2010, 07:05:03 pm
@bennynations,

I tried my original code at home last night and got mixed results. After reviewing it more carefully, I think the logic is sound, but I made some poor choices in code when trying to write something off the cuff for you. With that in mind, I'd like to submit another attempt. This works much more reliably for me, and I believe it will for you as well. You can either use this to setup your scene to execute the commands as you already have them, or you can build the commands right into the code if you prefer. Here is the new code:
Code: [Select]

function checkdoorstatus()
  if( luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",38)=="0" ) then
luup.log("Sensor Not Tripped, ending scene")
   stilltripped = "0"
  else
luup.log("Sensor is still tripped!")
   stilltripped = "1"
  end
end

luup.call_timer("checkdoorstatus", 1, "5m", "", "")

if (stilltripped == "0") then
   return false
end

Note: This code uses the call_timer function to implement a cleaner/friendlier 5 minute delay (see the 5m designation in there). You can change "5m" to just "2" if you want to go back to a 2 second delay for testing.

If you want to build the command right into the code, just replace the last bit with something like this:
Code: [Select]
if (stilltripped == "1") then
   luup.call_action("urn:upnp-org:serviceId:SwitchPower1","SetTarget",{ newTargetValue="0" },37)
end    
This would turn off a switch with the device # 37 if the sensor is still tripped.

Title: Re: If door is opened for 5 minutes...turn off air
Post by: ravennevar on September 16, 2010, 10:54:15 pm
@bennynations:

Which device are you using to turn on/off your AC? I have a few 220-240v ACs that could benefit from such a device and would definitely be something worth adding to my Zwave network.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on September 27, 2010, 06:14:08 pm
I am also very interested in this application.  I wrote to micasaverde to see if their support would help me implement it.  They said that for $300, they would write a plug in that they would also make available for all vera users.  However have one of you already developed the plug in to do this?  If so, is this plug in currently located in the MIOS Market?  If it is, what is the name?  If the plug in is not located there, is there another way that I can obtain it?
Thanks
(As you can tell, I am a beginning user.)
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Les F on September 27, 2010, 06:30:20 pm

Don't they (MCV) get it?   Instead of charging someone $300 for this, it could be a STRONG selling point for rental owners.   Did MCV forget whats on the front page... "Cut your energy bill" .  This is something that everyday people as well as rental owners could use to actually cut their energy bill.

I have had other rental owners ask me how I am able to remotely set the thermostat etc... They think thats cool. (no pun intended).  However if I told them they could shut down A/C automatically on a door staying open they would probably be a lot more inclined to try it out for their own property.  (Yeah they are capable of dealing with the tech side of vera when she gets cranky)

Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on March 02, 2011, 01:43:16 pm
I have 2 trane thermostats and 6 Hawking HRDS1 sensors on windows and doors installed.  Is there anyone that can help me write and install a program to shut off the AC if the door or window is open for 5 min?  I saw that some code has been suggested but I am uncertain how to modify it and how to apply it.
I have a Vera2 and I think that I just updated the latest firmware although I am having to have someone power cycle it for me.
Thanks
Tom
Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on March 02, 2011, 02:51:36 pm
Hi aecchalet,

if you can let us know the device IDs for the door senors, as well as the thermostat, I bet we can come up with something useful for you.

You can find the device IDs by clicking the wrench icon, and clicking the Advanced Tab. The device ID will be listed at the top (e.g. Device #37).

Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on March 27, 2011, 01:14:04 pm
My functioning HRDS1 window/door sensor device#s are 9, 10, 12.  I have 3-4 more sensors that are not functioning properly yet but I am working on them! My trane thermostat device#s are 4, 16.
Thanks!!
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on April 04, 2011, 10:39:06 pm
Has anyone gotten the script to work? Can someone help me write a script for my installation?
Thanks
Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on April 05, 2011, 07:02:58 pm
Here is something you can try. This script is intended to be run periodically. It is a little more simplified than the original request, but this is probably the way I would accomplish what you are trying to do if it were me. Especially for a vacation home with needy guests, simple is always better.

Use this code in a scene that runs every N minutes (perhaps 5?). Each time it runs, it will check to see if ANY of the defined sensors are tripped. If so, it will turn the operating mode on ALL defined thermostats to OFF. Otherwise (if none of the sensors are tripped), it will turn the operating mode on ALL the defined thermostats to AUTO (auto switches between heat/cool as required by the set point).

Since this will run periodically, the amount of time from the window/door being opened until the A/C being turned off will vary (anywhere between 1 second and N minutes), but it accomplishes the shutoff and turn (back) on functionality all in one scene. When someone opens a door and leaves it open, the thermostat will be shut off on the next run of this scene. When they close the door (and no other sensors are tripped) the thermostat will go back to auto on the next pass.

I hope this helps you see how this can be accomplished. I would personally strongly recommend that you become familiar with the code and how to read and modify it however before implementing this in a home that you are renting to guests. You don't want to have goofy things happening to your paying customers.


Code: [Select]
-- user configurable values ------------------------------------------------------------
--
--

-- List of all of your Sensor Devices that you would like to be included in the checks.
sensors = {9, 10, 12}

-- List all thermostats that you would like controlled as a result
thermostats = {4, 16}


--
--
-- end of user configurable values -----------------------------------------------------



-- Assume that no sensors are tripped to begin the script.
anytripped = 0

-- Check each sensor defined above. If it is tripped, set the global tripped status.
for  k, v in pairs(sensors)
do

  if( luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",v)=="0" )  
  then
luup.log("Sensor "..v.." Not Tripped")

  else
luup.log("Sensor "..v.." is tripped!")
anytripped = 1
  end
end


-- Configure each thermostat defined above. If the global tripped status is set, turn the
-- thermostat OFF, otherwise, turn it to AUTO.

for  k, v in pairs(thermostats)
       do



if (anytripped == 1) then

       luup.log("Setting Mode on Thermostat "..v.." to OFF")
luup.variable_set("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "ModeStatus",  "Off", v)
else
       luup.log("Setting Mode on Thermostat "..v.." to AutoChangeOver")
luup.variable_set("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "ModeStatus",  "AutoChangeOver", v)
end
end




Good luck!
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Ap15e on April 06, 2011, 04:17:49 am
@fall-line

If the last sensor isn't tripped, anytripped is 0 - regardless of the state of the other sensors. Is this working as intended?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: fall-line on April 06, 2011, 11:54:27 am
@Ape15e right you are! Sorry, I had that in while testing and didn't remove it. Thanks for reviewing.

I've removed the offending line. The above script should now work as expected.


Title: Re: If door is opened for 5 minutes...turn off air
Post by: Grain on April 09, 2011, 09:10:01 am
Code: [Select]

function checkdoorstatus()
  if( luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",38)=="0" ) then
luup.log("Sensor Not Tripped, ending scene")
   stilltripped = "0"
  else
luup.log("Sensor is still tripped!")
   stilltripped = "1"
  end
end

luup.call_timer("checkdoorstatus", 1, "5m", "", "")

if (stilltripped == "0") then
   return false
end


If you want to build the command right into the code, just replace the last bit with something like this:
Code: [Select]
if (stilltripped == "1") then
   luup.call_action("urn:upnp-org:serviceId:SwitchPower1","SetTarget",{ newTargetValue="0" },37)
end    

thanks a lot for this code fall-line
it's great to start experimenting with this, it opens up a lot of possibilities of customisation for Vera!
Title: Re: If door is opened for 5 minutes...turn off air
Post by: JOD on April 09, 2011, 02:51:33 pm
@fall-line,

Just a thought.
Do you think this could be better implemented if instead of running the scene every N minutes, to where as you said:
Quote
Since this will run periodically, the amount of time from the window/door being opened until the A/C being turned off will vary (anywhere between 1 second and N minutes)
That the scene is run as an event of the D/W sensors and a countdown timer started that IF the door is left open for N minutes the scene is executed else end.
In my situation with kids, the exterior doors are opened and closed over and over, I wouldnt want the A/C units turning off & on each time the door was opened but only rather if the door was left open for N minutes.

JOD.

Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on May 20, 2011, 11:03:39 am
I haven't tried this script yet because I knew nothing about Lau code.  However, I found a good introduction to it and will soon start experimenting with a script like this.

One problem that I see with this script is that when the AC has been turned OFF by the resident, this script will actually turn the AC back ON if none of the sensors are tripped!  That is counter productive.  If I first look to see if the AC is OFF before running this script, how will I know if the AC is OFF because the resident turned it OFF or because the previous run of the script turned it OFF?

Maybe the previous idea was better.  That was when a door or window sensor is tripped for more than 5 min, turn AC OFF and leave it OFF until the resident turns it back on.  With this approach, I could first determine if the thermostat is OFF and if so, stop the script before it checks all of the sensors.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: JOD on May 20, 2011, 11:31:46 am
Here's something that is more in line to the original idea.

Scene that runs only if a security sensor has been tripped for a set period of time.

1. Create a new scene. In that scene:

2. Create a timer and set it to run every minute.

3. In the Luup Code section put the following code:

Code: [Select]
local deviceNo = 22
local period = 15
 
local SS_SID = "urn:micasaverde-com:serviceId:SecuritySensor1"
 
local armed = luup.variable_get(SS_SID, "Armed", deviceNo) or "0"
if armed == "1" then
    local tripped = luup.variable_get(SS_SID, "Tripped", deviceNo) or "0"
    if tripped == "0" then
        luup.variable_set(SS_SID, "TripPeriod", "0", deviceNo)
    else
        local tripPeriod = luup.variable_get(SS_SID, "TripPeriod", deviceNo) or 0
        tripPeriod = tonumber(tripPeriod)
        tripPeriod = tripPeriod + 1
        luup.variable_set(SS_SID, "TripPeriod", tripPeriod, deviceNo)
        if tripPeriod == period then
            return true
        end
    end
end
return false
deviceNo is the sensor's device number, which you can get by going into its Toolbox, in the Advanced tab.

period is the time (in minutes) the sensor has been tripped before running the scene.

Note: The sensor must be armed for this to work, but this can be easily changed

Code taken from here: http://wiki.micasaverde.com/index.php/Scripts_for_scenes

JOD.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: MNB on May 20, 2011, 01:57:19 pm
@JOD, thanxs for the LUA code. Question in the "Note: The sensor must be armed for this to work, but this can be easily changed" How? is via a scene or some other means?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: JOD on May 20, 2011, 03:07:54 pm
You’re asking the wrong person. All I did was find it and I’m quite sure this came from @mcvflorin and when someone says “this can be easily changed” it’s because they know how to change it.  :P
For the majority of us it's not easy AT ALL.
I’m not a coder and not using this code so would only be able to venture a guess.
This is what I would try. Hopefully someone chimes in with a legitimate “How To” to answer your question and points out my errors as I would hate to be a contributor of inaccurate garbage.

Remove this part?
Code: [Select]
local armed = luup.variable_get(SS_SID, "Armed", deviceNo) or "0"
if armed == "1" then
or change this.
Code: [Select]
if armed == "1" thento this for not armed.
Code: [Select]
if armed ~= "1" thenor
Code: [Select]
if armed == "0" thenPossibly changing this
Code: [Select]
(SS_SID, "Armed", deviceNo)To this for in Bypass
Code: [Select]
(SS_SID, "Bypass", deviceNo)
* Caveat. Don’t take any of the above as working examples.

JOD.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on August 12, 2011, 06:13:40 pm
I am not a programmer and it took a while to learn enough to give this a try.
I have multiple sensors (more than what is currently listed) that I want to see if tripped and if so to turn off AC.
Can some of you with more programming expertise look at this for any obvious mistakes?
I wanted to test it but in IU4, it requires a device# and rejected several that I tried??
Any advice would be appreciated. My renters are killing me leaving doors and windows open with AC on!
Thanks!
_______________________________________________________________
 -- Use this Luup code in a scene that runs every 5 minutes
-- Table of window/door Sensor Devices ID#
-- k is ID# and V is descriptor

WDSensorIDPair = {[25]="GRHall_W", [22]="GRFrnt_D", [23]="GRLanai_D", [28]="MastBR_D",
[21]="LFrtBR_D", [24]="LBkBR_D"}

-- Table of thermostats ID# with descriptor
thermostats = {[4]="GRThermostat", [20]="LHThermostat"}

-- Assume that no sensors are tripped to begin the script.
WDsensortripped = 0

-- Check if any sensor is tripped, if so set the global variable for tripped status.
function find_tripped_sensor()
  While WDsensortripped = 0 do
    for k,v in pairs(WDSensorIDPair)
    do
   if( luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",k)=="0" ) 
     then   
      luup.log("Sensor "..v.." Not Tripped")   
     else
      luup.log("Sensor "..v.." is tripped!")
      WDsensortripped = 1
     end
     end
  end
end

-- Wait 3 min to see if any door/window is still open
-- [[function: call_timer; parameters: function_name (string), type (number),
time (string), days (string), data (string)]]
luup.call_timer("find_tripped_sensor", 1, "5m", "", "")

-- [[If the global variable tripped status is =1, turn the thermostat OFF, else don't change setting
so as to avoid turning thermostats on that had been turned off to begin with!]]

if (WDsensortripped == "1") then
  for  k,v in pairs(thermostats)
  do
    if (WDsensortripped == 1) then
   luup.variable_set("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "ModeStatus",  "Off", k)
   luup.log("Setting Mode on Thermostat "..v.." to OFF")
    end
  end
end
Title: Re: If door is opened for 5 minutes...turn off air
Post by: MNB on August 16, 2011, 04:36:18 pm
@aecchalet did you perchance get anywhere with your code? Mike
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on August 16, 2011, 05:57:16 pm
I tried testing it in the mios developer's section but in UI4 that seems to want a device #. I tried several device numbers but it wouldn't accept them. Any suggestions for testing the code?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: oTi@ on August 16, 2011, 10:02:51 pm
[...] mios developer's section [...] seems to want a device #.
You can leave that field blank.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on August 17, 2011, 09:22:37 am
[...] mios developer's section [...] seems to want a device #.
You can leave that field blank.
You MUST leave that field blank!  ;D Otherwise it won't work. I remember that I removed that asterisk once, but probably I forgot to commit the changes.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: oTi@ on August 17, 2011, 01:51:23 pm
You MUST leave that field blank!  ;D Otherwise it won't work. I remember that I removed that asterisk once, but probably I forgot to commit the changes.
:) For completeness, the link to the prior discussion (http://forum.micasaverde.com/index.php?topic=6755.msg42883#msg42883).
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on August 25, 2011, 09:20:13 am
I tried running it in the MIOS Developers/Test Luup code and got "code failed" with no other indication of why it failed. Anyone have a clue?
Thanks
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on August 25, 2011, 10:34:55 am
Enable verbose logging and look in the logs for messages starting with 01.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Ap15e on August 25, 2011, 01:40:10 pm
Check the syntax (SciTE, ...):

Code: [Select]
  While WDsensortripped = 0 do

 '=' expected near 'WDsensortripped'

->

While (WDsensortripped == 0 ) do


time (string), days (string), data (string)]]
luup.call_timer("find_tripped_sensor", 1, "5m", "", "")

unexpected symbol near ','

so as to avoid turning thermostats on that had been turned off to begin with!]]

'=' expected near 'as'


Check the semantic:

Code: [Select]
if (WDsensortripped == "1") then
or
if (WDsensortripped == 1) then
?

Use an interval timer (http://wiki.micasaverde.com/index.php/Luup_Lua_extensions#function:_call_timer instead of while ... do.

Title: Re: If door is opened for 5 minutes...turn off air
Post by: myhomeserver on August 26, 2011, 11:49:35 am
I'd also like to do this and have tried different scripts in this thread and nothing works properly.   Im baffled on how hard this is.  I'd really like to get this working with one of my Aeon Labs D/W sensors and a Z-Wave Thermostat by Trane.  If the A/C is on, and the door is open for 5 min, set the Trane to OFF.  Im also not worried about turning it back on, the renter can do that.

Hopefully one of the code wizards can help us...
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on August 26, 2011, 04:28:32 pm
Ok Turning on verbose logging is simple but then examining the logs is NOT.
I found the following wiki page with an outdated link to download puTTY, a program that allows you to connect by SSH to your vera:
http://wiki.micasaverde.com/index.php/Logs
Here is a correct link to download puTTY:
http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html
I downloaded and ran puTTY.exe. I entered the IP address that appears when I get my cp.mios.com dashboard (with default port 22).  I pressed the open button and a blank window appears with the IP address that I had entered on the top margin.  However, when I try to type "cd /var/log/cmh" to get to the directory with logs, nothing happens. No characters that I type appear in this ssh window??
What am I doing wrong here?
Thus I was unable to view the logs.

Addendum: It appears that I can't connect to SSH remotely unless I had enabled SSH on my router in my home where vera is connected, which is a long way from my regular home.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on August 26, 2011, 04:35:43 pm
Here is my latest draft. I think that some of the syntax was incorrect and I modified it to resemble some vera scripts that I had found on the wiki.  Again I entered it into my Mios Developers/Test Luup code window and ran it.  Again I got "code failed".  Any other suggestions?
BTW I added a section (after the 3 min wait) which reset the global variable for a tripped sensor to "0" then queried the sensors for another tripped sensor. If one is still found, then the thermostats would be turned off.  It would be great if we could get this working!!

-- Use this Luup code in a scene that runs every 5 minutes
-- Table of window/door Sensor Devices ID#
-- k is ID# and V is descriptor

-- Begin user input variables

WDSensorIDPair = {[25]="GRHall_W", [22]="GRFrnt_D", [23]="GRLanai_D", [28]="MastBR_D",
[21]="LFrtBR_D", [24]="LBkBR_D"}

-- Table of thermostats ID# with descriptor
thermostats = {[4]="GRThermostat", [20]="LHThermostat"}

-- End user input variables

-- Assume that no sensors are tripped.
WDsensortripped == "0"

-- Check if any sensor is tripped, if so set the global variable for tripped status.
function find_tripped_sensor()
  While WDsensortripped == "0" do
    for k,v in pairs(WDSensorIDPair)
    do
   if(luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",k)=="0" ) 
     then   
      luup.log("Sensor "..v.." Not tripped.")   
     else
      luup.log("Sensor "..v.." IS TRIPPED!")
      WDsensortripped == "1"
     end
     end
  end
end

-- Wait 3 min
-- [[function: call_timer; parameters: function_name (string), type (number),
time (string), days (string), data (string)]]
luup.call_timer("find_tripped_sensor", 1, "3m", "", "")

-- Assume that no sensors are still tripped.
WDsensortripped == "0"

-- Check if any sensor is STILL tripped, if so set the global variable for tripped status.
function find_tripped_sensor()
  While WDsensortripped == "0" do
    for k,v in pairs(WDSensorIDPair)
    do
   if(luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",k)=="0" ) 
     then   
      luup.log("Sensor "..v.." not tripped.")   
     else
      luup.log("Sensor "..v.." IS TRIPPED!")
      WDsensortripped == "1"
     end
     end
  end
end

-- [[If the global variable tripped status is == "1", turn the thermostat OFF, else don't change setting
so as to avoid turning thermostats on that had been turned off to begin with!]]

if (WDsensortripped == "1") then
  for  k,v in pairs(thermostats)
  do
    if (WDsensortripped == "1") then
   luup.variable_set("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "ModeStatus",  "Off", k)
   luup.log("Setting Mode on Thermostat "..v.." to OFF")
    end
  end
end
Title: Re: If door is opened for 5 minutes...turn off air
Post by: oTi@ on August 26, 2011, 04:44:51 pm
[...] wiki page with an outdated link to download puTTY
Updated Wiki page is here (http://wiki.micasaverde.com/index.php/Logon_Vera_SSH).

Quote
[...]nothing happens. No characters that I type appear in this ssh window??
You should have gotten a login prompt. Double check the IP address? And is Vera on your LAN?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on August 26, 2011, 04:55:02 pm
I think that I should change my ID to Clueless!
Someone suggested using a function as a timer:
"function: call_timer
parameters: function_name (string), type (number), time (string), days (string), data (string)
returns: result (number)
The function 'function_name', which must be passed as a string, will be called when the timer is triggered, and will be passed the string 'data'. The function returns 0 if successful."
I read this but don't understand it. What exactly happens after the specified time expires?  It indicates to me that, after the specified time interval, this function passes the "data" to the specified function name.  Does that function run again? If the global variable was "1", wouldn't this go to the call_time function again and begin an endless loop?
What does, "The function returns 0 if successful" mean?
Thanks
Clueless
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on August 29, 2011, 05:54:21 am
What exactly happens after the specified time expires?
The call_timer function schedules function_name to run when the specified time expires, passing the data to it.

What does, "The function returns 0 if successful" mean?
If the call_timer function successfully schedules the function_name function to run, it returns 0.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: myhomeserver on September 07, 2011, 10:45:03 pm
aecchalet - did you ever get your code polished and working properly?  I'd really like to get mine working but every snippet of code I have won't work properly - and I only have one sliding door and one trane T-stat

Thanks for any help and code you can post..
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on September 08, 2011, 02:06:04 pm
Sorry to say but no.
I hope to work on it some more next week.
Any Luup programmer's efforts that figure out why it won't won would be greatly appreciated.
Thanks
Title: Re: If door is opened for 5 minutes...turn off air
Post by: myhomeserver on September 23, 2011, 10:16:53 am
Anyone?  I've tried this code and it's not working. I would like to have my A/C turn off (I have a schlage Z-Wave t-stat) when the aeon D/W sensor detects that the door has been open for more than 5 min.  How hard can this really be?

MCV, can you provide some code snippets for us to try?  This thread has gone on and on and nobody seems to get it to work....

Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on September 23, 2011, 11:12:10 am
Try one of the first scripts from here:
http://wiki.micasaverde.com/index.php/Scripts_for_scenes (http://wiki.micasaverde.com/index.php/Scripts_for_scenes)
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on September 27, 2011, 04:41:20 am
I modified and got the following script to run in the MIOS Developer's/Test Luup Code window successfully without syntax erros:
-- Create scene that runs every 5 minutes
-- Create Command in scene to "arm" each sensor
-- Table of window/door Sensor Devices ID#
-- k is ID# and V is descriptor

-- Begin user input variables

WDSensorIDPair = {[42]="UPHall_W", [31]="GRFrnt_D", [41]="GRLanai_D", [38]="UPLBckBR_W",
 [39]="UPRBckBR_W", [36]="MastBR_D", [32]="LFrtBR_D", [34]="LBkBR_D", [35]="LwHall_D",
[40]="LwHall_W"}

-- Table of thermostats ID# with descriptor
thermostats = {[4]="GRThermostat", [20]="LHThermostat"}

-- End user input variables

-- Assume that no sensors are tripped.
WDsensortripped = "0"

-- If any sensor is tripped, set the global variable for tripped status.
function find_tripped_sensor1()
  While (WDsensortripped == "0") do
    for k,v in pairs(WDSensorIDPair) do
   if(luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",k)=="0")  
     then   
      luup.log("Sensor "..v.." Not tripped.")   
     else
      luup.log("Sensor "..v.." IS TRIPPED!")
      WDsensortripped = "1"
     end
     end
  end
end

-- Wait 1 min
--[[function: call_timer; parameters: function_name (string), type (number),
time (string), days (string), data (string)]]
luup.call_timer("find_tripped_sensor2", 1, "1m", "", "")

-- Assume that no sensors are still tripped.
WDsensortripped = "0"

-- Check if any sensor is STILL tripped, if so set the global variable for tripped status.
function find_tripped_sensor2()
  While (WDsensortripped == "0") do
    for k,v in pairs(WDSensorIDPair)
    do
   if(luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",k)=="0" )  
     then   
      luup.log("Sensor "..v.." not tripped.")   
     else
      luup.log("Sensor "..v.." IS TRIPPED!")
      WDsensortripped = "1"
     end
     end
  end
end

--[[If the global variable tripped status is == "1", turn the thermostat OFF, else don't change setting
so as to avoid turning thermostats on that had been turned off to begin with!]]

if (WDsensortripped == "1") then
  for  k,v in pairs(thermostats)
  do
    if (WDsensortripped == "1") then
   luup.variable_set("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "ModeStatus",  "Off", k)
   luup.log("Setting Mode on Thermostat "..v.." to OFF")
    end
  end
end

However, when I created the scene and ran it, it didn't turn off the thermostat!
I am trying to do this remotely and am unable to view my logs.  Can anyone see any error in this script?

Thanks
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on September 29, 2011, 07:08:40 am
On this line while is written with capital W, so it is treated as a variable:
While (WDsensortripped == "0") do
Title: Re: If door is opened for 5 minutes...turn off air
Post by: myhomeserver on September 29, 2011, 11:53:30 am
I have two sensors and only one thermostat, but made the edits and also fixed the capital W as MCVFlorin pointed out.  I made a scene and put the edited code in the luup tab, saved it, then set my commands to arm both sensors.  I set a timer for every 5 min and saved

Turned on the T-Stat, ran the scene, waited a few min, then opened a door and waited another 15 min and nothing...It never turned off the T-Stat.

Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on October 11, 2011, 09:23:27 am
I modified @aecchalet's code. Here are the instructions:
1. Create a scene and set it to run every 5 minutes.
2. Add this code in that scene.
3. Modify the variables marked for user input.

Code: [Select]
-- Begin user input variables

local wdSensorIdPair = {
    [42]="UPHall_W", [31]="GRFrnt_D", [41]="GRLanai_D", [38]="UPLBckBR_W", [39]="UPRBckBR_W",
    [36]="MastBR_D", [32]="LFrtBR_D", [34]="LBkBR_D", [35]="LwHall_D", [40]="LwHall_W"
}

-- Table of thermostats ID# with descriptor
local thermostats = {[4]="GRThermostat", [20]="LHThermostat"}

-- End user input variables


-- Check if there are tripped sensors. If there are, then turn the thermostats off.
function checkForTrippedSensors()
    -- Assume that no sensors are still tripped.
    wdSensorTripped = false

    for k, v in pairs(wdSensorIdPair) do
        local tripped = luup.variable_get ("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped", k) or "0"
        if (tripped == "0") then
            luup.log("Sensor '" .. v .. "' is not tripped.")
        else
            luup.log("Sensor '" .. v .. "' IS TRIPPED!")
            wdSensorTripped = true
            break
        end
    end

    if (wdSensorTripped) then
        for k, v in pairs (thermostats) do
            luup.log ("Turning thermostat '" .. v .. "' OFF.")
            luup.call_action ("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "SetModeTarget",  {NewModeTarget = "Off"}, k)
        end
    end
end


-- Assume that no sensors are tripped.
local wdSensorTripped = false

-- If any sensor is tripped, set the global variable for tripped status.
for k, v in pairs (wdSensorIdPair) do
    local tripped = luup.variable_get ("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped", k) or "0"
    if (tripped == "0") then
        luup.log ("Sensor '" .. v .. "' is not tripped.")
    else
        luup.log ("Sensor '" .. v .. "' IS TRIPPED!")
        wdSensorTripped = true
        break
    end
end

-- If there was any tripped sensor, check again in 1 minute if there still are tripped sensors.
if (wdSensorTripped) then
    luup.call_delay ("checkForTrippedSensors", 60, "")
end
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on October 11, 2011, 12:52:07 pm
@MCVFlorin,
Thanks for the update.
However, this script looks like it checks for a tripped sensor and if one is found, then it immediately shuts off the thermostat without any wait.
We would like the 1 min delay to occur after a tripped sensor is detected then to check again for a tripped sensor. Only if a sensor is tripped on the second check do we want the thermostat to be turned off.
Can you reorganize the script to work that way?
I read the explanation of the Luup.call_delay function in the wiki but didn't understand it. Can you explain it?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on October 11, 2011, 01:20:58 pm
Actually it waits 60 seconds before it checks if there still are tripped sensors, and only then it turns off the thermostat.

The call_delay function runs the function given as the first parameter after the number of seconds given as the second parameter have passed. So it's like call_timer, only simpler, in that it handles only one type of timer, and the time is always specified in seconds.

And I'd like to know what exactly didn't you understand from the explanation. I'm asking this because you're not the first person to not understand the explanation, so this means that the explanation is not that good and needs reformulation.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on October 11, 2011, 02:35:36 pm
@MCVflorin
I am new to lua programming. The script appears to 1st check to see if there is a tripped sensor.  If one is found, a "break" occurs. I presume that the "break" causes it to do to the end of the 1st For Do loop and begin the segment that turns off the thermostat. If that is wrong, what happens after the "break".
Also, what happens after the luup.call_delay causes a pause?  What part of the script starts after the pause. Too bad the lines aren't numbered, it would be easier for me to understand the progression, ie where the script goes after the break and after the call_delay.
Thanks
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on October 11, 2011, 02:45:28 pm
@MCVflorin,
Here is the wiki definition:

function: call_delay parameters: function_name (string), seconds (number), data (string), thread (bool)

returns: result (number)

The function function_name (the first parameter), which must be passed as a string, will be called in seconds seconds (the second parameter), and will be passed the string data. The function returns 0 if successful

I understand that the function, the name of which must be entered as a string, will be "called" after the specified delay (seconds).  I am not sure what happens when you "call a function".  I would think that it means that the function, "checkForTrippedSensors", is run again but in this case that would seem to initiate an endless loop?
In this script the function is being passed "" or no data. What is the point of that?  Does that mean that the function will be "called" without passing it any data?
The function returns 0 if successful?? What does it mean for a function to return 0?  If what is successful?
As you can see, I am clueless!
Thanks for your patience.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on October 12, 2011, 04:19:37 am
Functions are run only if they're called, but they have to be declared first. The code runs sequentially:
1. Declare and define the variables.
2. Declare and define the checkForTrippedSensors function.
3. Go through all the sensors an check for the tripped ones. If one is found, exit the for loop.
4. If there was any tripped sensor, call the function checkForTrippedSensor in 60 seconds.
5. The script ends (with return nil if nothing else is returned) and the scene runs.
6. After 60 seconds the checkForTrippedSensor function runs.

Quote from: aecchalet
I would think that it means that the function, "checkForTrippedSensors", is run again but in this case that would seem to initiate an endless loop?
Because the function runs after all the other code, and because it is not called again at the end of the function, it only runs once.

Quote from: aecchalet
The function returns 0 if successful?? What does it mean for a function to return 0?  If what is successful?
The call_delay function returns the value 0 if it successfully scheduled the given function to run after the given number of seconds have passed.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on October 12, 2011, 12:13:41 pm
@MCVflorin
I understand now but it seems a little strange that the function is declared first but run last in the script and only if called!  I hope to test the script today.
Thanks
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on October 12, 2011, 05:18:45 pm
@MCVflorin - Thanks very much!!!!
It worked! I only tested it briefly but it seemed to work as designed!
The scene has a timer set to run every 5 min.  I added commands to the script to arm the door and window sensors that I want to monitor.  One would need to modified the script for the device# for the sensors that you want to monitor and for the thermostats that you want to shut off.
The next step would be to create a script to monitor the motion detectors during certain hours (i.e. 9 AM  to 9 PM).  If the motion detectors are not tripped for more than 30 min, I would also like to shut off the AC, presuming that no one is in the house. The down side of that second script would be that the AC would be shut off if the occupants were taking a nap. One could either make the period of inactivity longer (i.e. 60 min) before shutting off the AC or turn up the AC thermostat to say 78F. (My thermostats may not be zero'ed properly because we can tolerate settings below 72F there because it gets too cold. However, my renters tended to turn the thermostat down to 68F before I learned to limit the lowest setting to 75F.  My guess is that it was because they openned windows or doors if too cold!)
Title: Re: If door is opened for 5 minutes...turn off air
Post by: myhomeserver on October 13, 2011, 11:28:55 am
Thanks for the help here.  I have a client that has only one thermostat and one sensor.....I tried getting this working and it doesn't seem to work....would there be an issue with simply removing the other sensor and T-stats and leaving just one ID for each?   

Also, does the sensor need to be armed? 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on October 13, 2011, 11:39:46 am
The sensor does need to be armed.
If you only had one sensor, you wouldn't need the For loops.
I don't know how or if a For loop works if you only have one element in the table.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on October 13, 2011, 11:55:16 am
The code should work for any number of sensors and thermostats. For one sensor and one thermostat the code would look like this:

Code: [Select]
-- Begin user input variables

local wdSensorIdPair = { [42]="UPHall_W" }

-- Table of thermostats ID# with descriptor
local thermostats = { [4]="GRThermostat" }

-- End user input variables
Title: Re: If door is opened for 5 minutes...turn off air
Post by: myhomeserver on October 14, 2011, 01:09:37 pm
Thanks!  We have it working!

One problem is turning the T-Stat back on....Since this Vacation home is in a hot climate, we want to make sure that the thermostat is not off to too long. 

What should we do? Make another scene that simply turns on the thermostat and set a timer to perform that every 30 min?
I assume this will screw up and turn on the thermostat if the door turns it off, but in this case, it's more important to have it on than off.

Is there a way to have one scene disable another scene?  Sorry for all the questions, this thread has been very helpful in getting this stuff to work but now my goal is to make it bulletproof...

Title: Re: If door is opened for 5 minutes...turn off air
Post by: Minnies on October 14, 2011, 02:30:41 pm
Great that you have it working. Can you copy the luup code that you have that is working. I tried the one above and was unable to get it to work. I am not luup knowledgeable and do a copy and paste changing only the input numbers. I can use multiple doors in one config or use multiple configs to handle each of the possible doors (my preference) so I know which door triggered it.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: myhomeserver on October 14, 2011, 05:36:58 pm
Sure, here it is:

Code: [Select]
-- Begin user input variables

local wdSensorIdPair = {[10]="doorsensor1"}

-- Table of thermostats ID# with descriptor
local thermostats = {[9]="thermostat1"}

-- End user input variables


-- Check if there are tripped sensors. If there are, then turn the thermostats off.
function checkForTrippedSensors()
    -- Assume that no sensors are still tripped.
    wdSensorTripped = false

    for k, v in pairs(wdSensorIdPair) do
        local tripped = luup.variable_get ("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped", k) or "0"
        if (tripped == "0") then
            luup.log("Sensor '" .. v .. "' is not tripped.")
        else
            luup.log("Sensor '" .. v .. "' IS TRIPPED!")
            wdSensorTripped = true
            break
        end
    end

    if (wdSensorTripped) then
        for k, v in pairs (thermostats) do
            luup.log ("Turning thermostat '" .. v .. "' OFF.")
            luup.call_action ("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "SetModeTarget", {NewModeTarget = "Off"}, k)
        end
    end
end


-- Assume that no sensors are tripped.
local wdSensorTripped = false

-- If any sensor is tripped, set the global variable for tripped status.
for k, v in pairs (wdSensorIdPair) do
    local tripped = luup.variable_get ("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped", k) or "0"
    if (tripped == "0") then
        luup.log ("Sensor '" .. v .. "' is not tripped.")
    else
        luup.log ("Sensor '" .. v .. "' IS TRIPPED!")
        wdSensorTripped = true
        break
    end
end

-- If there was any tripped sensor, check again in 1 minute if there still are tripped sensors.
if (wdSensorTripped) then
    luup.call_delay ("checkForTrippedSensors", 60, "")
end



Make sure you use the Device Number in the DEVICE OPTIONS tab for your sensors and thermostat.   (See the screenshot attached)
Title: Re: questions on this script
Post by: aecchalet on December 09, 2011, 06:14:12 am
Thanks to many others but especially to MCVFlorin, my script to shut off the AC after a specified amount of time seems to be working fine.  It has already reduced my electric bill by about 40%! Can we add a block to also shut off the AC if the motion detectors have tripped after a set period (30 min) during the day (9 AM to 5 PM)?  I gave it a try, see my next post to this string.
What happens if one of my sensor's batteries dies, will the scrip continue as if it doesn't exist or will that cause the script to fail?
Should we add some Lua code at the begining to arm all of the sensors or simply do that with the scene's commands?

Title: Now, If no motion is detected, turn off air
Post by: aecchalet on December 09, 2011, 06:41:56 am
As many know, guests tend to leave AC run all day, even if they are gone all day.  In HI where electricity is $.386/kwh, that can be very costly.  I would like to also either extend this script or create another, which would turn off the AC if the motion detectors were not tripped for a given period (30 min) during the interval, 9 AM til 5 PM.  What do others think about that period of 30 min and the interval? Would 15 min be too short?  Should the interval be 9 AM til 9 PM?
The previous scene ran every 1 min, is that too frequent for this scene?  I am concerned about overloading Vera and limiting its ability to do other functions.
Can changing shadows (from clouds) trip these motion detectors?
I have pasted below, my first attempt at this but now realize that it doesn't handle two motion detectors appropriately.  Ideally, the lastTrip variable should be the shortest time period for either sensor but instead, this script makes it pertain only to the last motion detector sensor checked.  I suppose it should create a lastTrip variable for each sensor then compare and select the shortest of them.  Any ideas on simple code to do that?
_________________________________________________________
-- Create scene that runs every 5 minutes
-- Create Command in this scene to "arm" each W/D & MD sensor
-- k is Device ID# and V is device abbreviation in tables

-- Begin user input variables

-- Table of thermostats ID# with abbreviation
thermostats = {[4]="GRThermostat", [20]="LHThermostat"}

--Table of motion detectors ID# with abbreviation
MotionDetectIDPair = {[13]="GR_MD", [14]="LL_MD"}

-- End user input variables

--This portion makes the scene run only between startTime and endTime.
--[[The call string.sub(s,i,j) extracts a piece of the string s, from the i-th to
the j-th character inclusive.  This call can also be written s:sub(i,j). s:sub(-2)
gives the last 2 characters of a string, since the default for j is -1, which is
the last character in the string.]]
--find("%d+") finds the first sequence of digits

local startTime = "09:00"
local endTime   = "17:00"
local hour = tonumber( startTime:sub( startTime:find("%d+") ) )
local minute = tonumber(startTime:sub(-2))
 
if hour and minute then
    startTime = hour * 100 + minute
--creates number like 0900 without colon
else
    luup.log("ERROR: invalid start time")
    return false
end
 
hour = tonumber( endTime:sub( endTime:find("%d+") ) )
minute = tonumber(endTime:sub(-2))
 
if hour and minute then
    endTime = hour * 100 + minute
else
    luup.log("ERROR: invalid end time")
    return false
end
 
local currentTime = os.date("*t")
currentTime = currentTime.hour * 100 + currentTime.min
luup.log("startTime = " .. startTime .. "; currentTime = " .. currentTime .. "; endTime = " .. endTime)
 if startTime <= endTime then
    -- Both the start time and the end time are in the same day:
    -- if the current time is in the given interval, run the scene.
    if startTime <= currentTime and currentTime <= endTime then
        return true
    end
 end
return false

--Should period be a local or global variable?
local period = 30
local SS_SID = "urn:schemas-micasaverde-com:device:MotionSensor:1"

function find_time_MD_lasttripped()
   for k,v in pairs(MotionDetectIDPair)
   do
   local lastTrip = luup.variable_get(SS_SID, "LastTrip", k) or os.time()
   lastTrip = tonumber(lastTrip)
   if (os.difftime(os.time(), lastTrip) / 60) >= period then
       return true
   end
end
return false

--If between start and end time & time to last MD tripped > 30 min, AC turned off
for  k,v in pairs(thermostats)
  do
  luup.variable_set("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "ModeStatus",  "OFF", k)
  luup.variable_set("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "ModeTarget",  "OFF", k)
  luup.log("Setting Mode on Thermostat ".."#"..k.." "..v.." to OFF")
end
Title: Re: questions on this script
Post by: mcvflorin on December 09, 2011, 08:29:59 am
What happens if one of my sensor's batteries dies, will the scrip continue as if it doesn't exist or will that cause the script to fail?

If one of your sensor's batteries die it won't report the tripped status to Vera anymore, so the Tripped variable won't be updated. The script will run fine though.

If you want others to see this script you can create a thread on that board and I'll sticky it.

I updated the previous code to also turn off the AC if none of the motions sensors were tripped in the last 20 minutes. The recommended timer for the scene with this code is still 5 minutes.

Code: [Select]
-- Begin user input variables

-- Table of window and door sensors ID# with descriptor
local wdSensorIdPair = {
    [42]="UPHall_W", [31]="GRFrnt_D", [41]="GRLanai_D", [38]="UPLBckBR_W", [39]="UPRBckBR_W",
    [36]="MastBR_D", [32]="LFrtBR_D", [34]="LBkBR_D", [35]="LwHall_D", [40]="LwHall_W"
}

-- Table of motion sensors ID# with descriptor
local motionSensors = {
    [12]="HallSensor", [23]="KitchenSensor"
}

-- Table of thermostats ID# with descriptor
local thermostats = {[4]="GRThermostat", [20]="LHThermostat"}

-- End user input variables


-- Check if there are tripped sensors. If there are, then turn the thermostats off.
function checkForTrippedSensors()
    -- Assume that no sensors are still tripped.
    wdSensorTripped = false

    for k, v in pairs(wdSensorIdPair) do
        local tripped = luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped", k) or "0"
        if (tripped == "0") then
            luup.log("Sensor '" .. v .. "' is not tripped.")
        else
            luup.log("Sensor '" .. v .. "' IS TRIPPED!")
            wdSensorTripped = true
            break
        end
    end

    if (wdSensorTripped) then
        for k, v in pairs(thermostats) do
            luup.log("Turning thermostat '" .. v .. "' OFF.")
            luup.call_action("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "SetModeTarget", {NewModeTarget = "Off"}, k)
        end
    end
end

local now = os.date("*t")
-- If it's between 9 AM and 5 PM then check the motion sensors.
if (now.hour >= 9 and now.hour <= 17) then

    -- Assume that no motion sensor has been tripped in the last 20 minutes.
    local motionSensorTripped = false

    -- Check when was the last time each motion sensor was tripped.
    for k, v in pairs(motionSensors) do
        local lastTrip = luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "LastTrip", k)
        lastTrip = tonumber(lastTrip, 10) or os.time()
        if (((os.time() - lastTrip) / 60) < 1200) then
            motionSensorTripped = true
            break
        end
    end

    --  If no motion sensor has been tripped in the last 20 minutes (1200 seconds), then turn off the AC.
    if (not motionSensorTripped) then
        for k, v in pairs(thermostats) do
            luup.log("Turning thermostat '" .. v .. "' OFF.")
            luup.call_action("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "SetModeTarget", {NewModeTarget = "Off"}, k)
        end

        return -- AC has been turned off: don't check the door and window sensors anymore.
    end
end

-- Assume that no sensors are tripped.
local wdSensorTripped = false

-- If any sensor is tripped, set the global variable for tripped status.
for k, v in pairs(wdSensorIdPair) do
    local tripped = luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped", k) or "0"
    if (tripped == "0") then
        luup.log("Sensor '" .. v .. "' is not tripped.")
    else
        luup.log("Sensor '" .. v .. "' IS TRIPPED!")
        wdSensorTripped = true
        break
    end
end

-- If there was any tripped sensor, check again in 1 minute if there still are tripped sensors.
if (wdSensorTripped) then
    luup.call_delay("checkForTrippedSensors", 60, "")
end
Title: Re: questions on this script
Post by: oTi@ on December 09, 2011, 08:37:47 am
I updated the previous code to also turn off the AC if none of the motions sensors were tripped in the last 20 minutes.
Does it handle the case where the sensor is still tripped?
Title: Re: questions on this script
Post by: mcvflorin on December 09, 2011, 08:45:33 am
Does it handle the case where the sensor is still tripped?

AFAIK the LastTrip variable is updated every time the sensor reports it's tripped, and I trust it. :) If LastTrip says that the sensor has been tripped 20 minutes ago, then I believe it. In this case I don't care what Tripped says.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: oTi@ on December 09, 2011, 08:58:13 am
If I stay in the room for more than 20 minutes, in range of the motion sensor, wouldn't the LastTrip be more than 20 minutes ago? (Or leave the room / am out of range of the sensor, but return before the configured on-time/delay of the sensor.)
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on December 09, 2011, 09:42:15 am
Doesn't the motion sensor report it's tripped every on-time minutes? This is how I knew these worked, though I may be mistaken.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on December 09, 2011, 05:45:27 pm
@MCVFlorin
Thanks for the updated code!
However, 1st, I think the device name is incorrect for motion detectors, see substitute name below.
2ndly, this code will shut off AC if either motion detector hasn't tripped for the "period" length of time.  That won't work since all of the activity may be around one motion detector and not the other and in that case, I wouldn't want the AC shut off.  We need to be sure that the lastTrip for all motion detectors is > "period" length.
Obviously, I am a programming novice.  Do you think the following changes to the pertinent section of the code would work?
BTW I changed the "period" from 20 to 30 min and time from 9 AM to 7 PM.
________________________________
local now = os.date("*t")
-- If it's between 9 AM and 7 PM then check the motion sensors.
if (now.hour >= 9 and now.hour <= 19) then

    -- Assume that no motion sensor has been tripped in the last 30 minutes.
    local motionSensorTripped = false
    local mostrecentTrip = os.time()

    -- Get time that the last time each motion sensor was tripped.
    for k, v in pairs(motionSensors) do
        local lastTrip..k = luup.variable_get("urn:schemas-micasaverde-com:device:MotionSensor:1", "LastTrip", k)
        lastTrip..k = tonumber(lastTrip..k, 10) or os.time()
        If lastTrip..k < mostrecentTrip then mostrecentTrip = lastTrip..k
    end
    if (((os.time() - mostrecentTrip) / 60) < 1800) then
            motionSensorTripped = true
       break
    end
    end

    --  If no motion sensor has been tripped in the last 30 minutes (1800 seconds), then turn off the AC.
    if (not motionSensorTripped) then
        for k, v in pairs(thermostats) do
            luup.log("Turning thermostat '" .. v .. "' OFF.")
            luup.call_action("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "SetModeTarget", {NewModeTarget = "Off"}, k)
        end

        return -- AC has been turned off: don't check the door and window sensors anymore.
    end
end
Title: How many motion detectors needed when shutting off AC with inactivity?
Post by: aecchalet on December 09, 2011, 06:26:26 pm
Currently, I have a 2 story home with a motion detector in Great Room (living/dining area) and the hallway between 3 bedrooms on lower level.  However, I could easily foresee someone staying in a bedroom and watching TV or reading or using the bathroom and/or working in the kitchen for longer than the specified "period" and not tripping these two motion detectors.  If one is going to use this code to shut down AC when motion detectors are not tripped, the motion detectors should be located where persons may be spending significant time during the monitoring period.  In that case I should have motion detectors in each bedroom (4), the kitchen and great room.  The down side is more expense for motion detectors and batteries and more effort to keep batteries alive.  The upside is avoid AC use when guest are not home and avoiding annoying them when they are home.  In this home, guest are frequently not home during the hotest part of the day and return in the cooler evening.
Any thoughts or suggestions?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on December 12, 2011, 04:43:14 am
2ndly, this code will shut off AC if either motion detector hasn't tripped for the "period" length of time.

Actually the code shuts off the AC only if ALL the sensors have been inactive for x minutes or more.

First I assume that no motion sensor has been tripped in the last 20 minutes. Then I check when was the last time each motion sensor was tripped. If it was less than x minutes ago then I set the motionSensorTripped flag. If this flag is set, the AC won't be turned off.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: ArtemPCB on April 03, 2012, 01:17:49 am
OMG, the script works! Thank you very much to all of you who made it happened.
I have only one question. How to make it to turn to Auto again, after the door is closed. What should I add to the script, so when it runs the next time, it turn the thermostat to Auto. I think, that was the idea at the beginning of the thread.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on April 03, 2012, 05:23:51 am
@ArtemPCB
Simply create a scene that turns on the thermostat when the door is closed. No code required.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on April 03, 2012, 03:10:59 pm
Actually the code shuts off the AC only if ALL the sensors have been inactive for x minutes or more.

First I assume that no motion sensor has been tripped in the last 20 minutes. Then I check when was the last time each motion sensor was tripped. If it was less than x minutes ago then I set the motionSensorTripped flag. If this flag is set, the AC won't be turned off.

MCVFlorin
I hope that I am misunderstanding this message.  The goal of this program was to check the sensors and turn off the AC if the sensors indicated that any door or window (with sensor) has been open for the "period" length of time.  Is that what this program does?  You say above that the AC will only be shut off if all doors or windows are inactive.  By inactive do you mean tripped?  I presume that leaving a sensored door open causes it to be in the tripped mode.
PLEASE clarify.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: mcvflorin on April 04, 2012, 05:24:59 am
In that message I was referring to the code that does this:

I would like to also either extend this script or create another, which would turn off the AC if the motion detectors were not tripped for a given period (30 min) during the interval, 9 AM til 5 PM.

I didn't say anything about the door and window sensors, but only about the motion sensors.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on November 29, 2012, 12:47:16 am
I finally managed to get 5 motion detectors installed last week with the rest of the zwave system operating properly now.  I decided to try the new code that MCVFlorin helped us write that would also shut off the AC if no motion was detected in any of the 5 motion detectors for more than 20 min between 9 AM and 5 PM.
However, after I loaded the lua script and saved it and clicked the button to run now, I saw a message saying that there was an error in a Lua script.  I then replace the new script with the old script, saved it and ran it without any error message generated.  I will paste the new script below.  Does anyone see any errors?
Thanks
_______________________________________________________________________________________
-- Begin user input variables

-- Table of window and door sensors ID# with descriptor
local wdSensorIdPair = {
    [35]="LwHall_D", [38]="UpBed_W", [41]="GR_Lanai_D", [42]="UPHall_W", [49]="GRFrnt_D",
    [51]="LwHall_W", [60]="LwFrtBRDr", [61]="LwBkBR_D", [66]="LW_MastBR_D"
}

-- Table of motion sensors ID# with descriptor
local motionSensors = {
    [58]="GR_Foyer_MD", [59]="LH_MD", [63']="GR_TV_MD", [64]="Up_Mstr_BR_MD",
    [65]="Lw_Mstr_BR_MD"
}

-- Table of thermostats ID# with descriptor
local thermostats = {[4]="GRThermostat", [20]="LHThermostat"}

-- End user input variables


-- Check if there are tripped sensors. If there are, then turn the thermostats off.
function checkForTrippedSensors()
    -- Assume that no sensors are still tripped.
    local wdSensorTripped = false

    for k, v in pairs(wdSensorIdPair) do
        local tripped = luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped", k) or "0"
        if (tripped == "0") then
            luup.log("Sensor '" .. v .. "' is not tripped.")
        else
            luup.log("Sensor '" .. v .. "' IS TRIPPED!")
            wdSensorTripped = true
            break
        end
    end

    if (wdSensorTripped) then
        for k, v in pairs(thermostats) do
            luup.log("Turning thermostat '" .. v .. "' OFF.")
            luup.call_action("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "SetModeTarget", {NewModeTarget = "Off"}, k)
        end
    end
end

local now = os.date("*t")
-- If it's between 9 AM and 5 PM then check the motion sensors.
if (now.hour >= 9 and now.hour <= 17) then

    -- Assume that no motion sensor has been tripped in the last 20 minutes.
    local motionSensorTripped = false

    -- Check when was the last time each motion sensor was tripped.
    for k, v in pairs(motionSensors) do
        local lastTrip = luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "LastTrip", k)
        lastTrip = tonumber(lastTrip, 10) or os.time()
        if (((os.time() - lastTrip) / 60) < 1200) then
            motionSensorTripped = true
            break
        end
    end

    --  If no motion sensor has been tripped in the last 20 minutes (1200 seconds), then turn off the AC.
    if (not motionSensorTripped) then
        for k, v in pairs(thermostats) do
            luup.log("Turning thermostat '" .. v .. "' OFF.")
            luup.call_action("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "SetModeTarget", {NewModeTarget = "Off"}, k)
        end

        return -- AC has been turned off: don't check the door and window sensors anymore.
    end
end

-- Assume that no sensors are tripped.
local wdSensorTripped = false

-- If any sensor is tripped, set the global variable for tripped status.
for k, v in pairs(wdSensorIdPair) do
    local tripped = luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped", k) or "0"
    if (tripped == "0") then
        luup.log("Sensor '" .. v .. "' is not tripped.")
    else
        luup.log("Sensor '" .. v .. "' IS TRIPPED!")
        wdSensorTripped = true
        break
    end
end

-- If there was any tripped sensor, check again in 1 minute if there still are tripped sensors.
if (wdSensorTripped) then
    luup.call_delay("checkForTrippedSensors", 60, "")
end
Title: Re: If door is opened for 5 minutes...turn off air
Post by: futzle on November 29, 2012, 04:20:21 pm
Code: [Select]
/opt/local/bin/lua: stdin:11: unfinished string near '']="GR_TV_MD", [64]="Up_Mstr_BR_MD",'

It's the stray apostrophe near the 63.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on November 29, 2012, 04:32:48 pm
Thanks!
That got rid of the error message.  Now we will see if it runs okay.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on December 15, 2012, 05:15:22 pm
My electric bill have been running $650-750, down from my highest of $1150/mo.  That was before I implemented the additional Luup code to shut off the AC if none of the 5 motion detectors (2 bedrooms, 1 great room, 1 upper hall, 1 lower hall) trip for more than 20 minutes.  I hope that this will lower my electric bills even more now.  (I have also set my minimum temp to 74F.)

I had to implement this code when I was not staying at the house so can't be sure how it is working.   I have had 2 groups of guests there so far and neither has complained about the AC shutting off.

When I look at "My Alerts", I see that once or twice per day, both of my thermostats turn off at the same time.  That indicates that they are being shut off by my scene with the above code.  Is there some additional code that we can add to inform me why the thermostat was shut off, i.e. window/door sensor tripped > 1 min or no motion for > 20 min?

Also, is there a way to generate a report showing how much time my AC is on during a day? 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on December 15, 2012, 05:17:42 pm
BTW
It would be nice if someone could make a plugin for the market place with this luup code.  I am sure that many other rental home owners would like to implement this type of scene to save them money.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on December 15, 2012, 06:08:38 pm
Note: This and your current strategy will turn off the AC at 9:00 if people sleep in (no motion)
You could do this with the Program Logic Event Generator (PLEG) plugin and a scene that only turns off the thermostats.

For each Motion Sensor create a trigger for the PLEG using the Triggers tab.

Then in the PLEG Settings tab create a condition expression:
AutoOff = (Motion1; NOW > 30:00) and (Motion2; NOW > 30:00)  ...  and (MotionN;Now) > 30:00) and (09:00:00 < NOW < 17:00:00)

Then trigger your thermostat off scene when the PLEG device satisfies condition AutoOff

No LUUP code!

Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on December 17, 2012, 04:57:01 pm
I just learned that one can add luup code to send an alert to "Vera Alerts".
I modified the following section:

if (wdSensorTripped) then
        for k, v in pairs(thermostats) do
            luup.log("Turning thermostat '" .. v .. "' OFF.")
            luup.call_action("urn:upnp-org:serviceId:HVAC_UserOperatingMode1", "SetModeTarget", {NewModeTarget = "Off"}, k)
            luup.call_action("urn:richardgreen:serviceId:VeraAlert1", "SendAlert",
                  {Message = "Wind/Door Tripped AC Off {tone:1}", Recipients = "3vp209j1sjz"}, 67)
        end

It worked very well and told me that the AC was shut off because a window or door was open for more than 1 minute.  I was able to view my devices on the vera desktop and watched it work perfectly.  Unfortunately, I now have to remove that line of code because every 5 minutes when this scene is run, it again tries to turn off the AC and notifies me of such, if a door or window is still open.  At least it helped me confirm that that portion of the code works!
I also inserted the  same line of code in the loop that shuts off the AC if a motion detector hasn't been tripped for more than 20 min between 9 AM and 7 PM.  I will have to remove that extra line of code to avoid repetitive notices but it can help me to confirm that the luup program code is working.

Addendum
I added vera alert message to the luup code segment that turns off the AC if there is no motion for 20 min about 3 days ago.  Today was the first day that I started to receive the messages that the luup code was attempting to turn off my AC.  The house was occupied until yesterday afternoon.  I am surprised that it didn't start messaging me yesterday afternoon or earlier today until it finally started around 5 pm.  Can shadows from clouds trip ZIR000 motion detectors?  Without the vera alert messaging I couldn't tell if it was working because I can't read my logs remotely.  I had to remove the vera alert code because it was messaging me every 5 minutes!
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on December 17, 2012, 05:02:12 pm
RTS noted that my AC will shut off at 9 AM if someone is sleeping.  That is probably true though I have a motion sensor facing the bed in both master bedrooms.  In Hawaii, most guests are up very early because they are from West Coast or further East time zones so guests rarely sleep past 9 AM.
Thanks for the suggestion and thanks for your modifications to Vera Alerts!
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on December 17, 2012, 05:06:54 pm
I also learned about the DataMine plugin.  Once I get back to my vacation home and plug a USB drive into Vera, I hope to use that plugin to track/graph both of my thermostat's ON and OFF modes and average temperatures.  I will also try the google weather plugin to include outside temp for comparison purposes.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Radjin on December 22, 2012, 03:57:44 pm
I get "ERROR : Error in lua for scenes and events"  I pasted the code and changed the device numbers into the LUUP of several doors/window triggers i have set up in the GUI. Do I need to do anything to the lua below, beyond change the device ID if I paste it into each of the triggers luup events?

---------------------------
os.execute("sleep 300")

if( luup.variable_get("urn:micasaverde-com:serviceId:SecuritySensor1", "Tripped",33)=="0" ) then   
   luup.log("Sensor Not Tripped, ending scene")   
    return false
end
---------------------------


Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on December 23, 2012, 12:30:40 pm
Quote
os.execute("sleep 300")

This should NOT be called in your code. You are basically telling ALL of VERA to shut down for 5 minutes and do NOTHING!!!!!

It might be timing out and reporting this as an error.

Title: Re: If door is opened for 5 minutes...turn off air
Post by: Radjin on December 23, 2012, 02:08:39 pm
Thanks for the info. What should I use to get the results I need?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on December 23, 2012, 05:00:30 pm
What is the purpose of the SLEEP ?

There are options for delayed actions:

These all use safe mechanisms in Vera (luup.call_delay and luup.call_timer) to have an action completed at a later point in time.   
In general your lua code should execute in it's entirety in a few seconds ... for most plugins execution is usually a small fraction of a second.

Title: Re: If door is opened for 5 minutes...turn off air
Post by: Radjin on December 24, 2012, 12:20:46 am
It was simply to monitor a door or window and if it was left open for five minuets it would turn off the AC unit.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on December 24, 2012, 10:32:26 am
For Vera to work properly this has to be broken into two steps.

The plugins I have listed will do this for you.
If you call Sleep ... it causes ALL of VERA to sleep. It will not respond to any other inputs during that period ... If it's long enough it will restart it self ... because it's not responding.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Radjin on January 18, 2013, 11:47:21 am
Below are two code snippets I copied from the wiki that work like a charm if placed in two separate scenes. They each only look at one sensor and do not detect the status of the ac unit before firing to avoid turning on a unit that was manually turned off.

How would one combine them to:
* work within one scene
* Check the status of the ac unit and if off leave off
* check multiple sensors (doors & windows) closed or not tripped
* Return it to the mode it was in when the scene was triggered. (for those units without AUTO)

I can configure the scene with triggers for the doors/windows opening and closing, so triggers are not a problem.

I use the following two lines to check the status of a light to not run the scene if the light is already on manually. Will this work for the thermostat as well?

light = luup.variable_get("urn:upnp-org:serviceId:SwitchPower1","Status",3)
return (light == "1")

If so, I am not sure how to incorporate that into what I want to happen.
-----------------------------------------------------
-- Turn AC off when Doors/windows opened for 5 minuets

local SENSOR = 17    -- The door/window sensor device number
local THERMOSTAT = 3 -- The thermostat device number
local DELAY = 300    -- Seconds
 
local SES_SID = "urn:micasaverde-com:serviceId:SecuritySensor1"
local HVACO_SID = "urn:upnp-org:serviceId:HVAC_UserOperatingMode1"
 
luup.call_delay( "turnOffAc", DELAY)
 
-- Turn off the thermostat if the sensor has been tripped for at least 5 minutes.
function turnOffAc()
    local tripped = luup.variable_get( SES_SID, "Tripped", SENSOR) or "0"
    local lastTrip = luup.variable_get( SES_SID, "LastTrip", SENSOR) or os.time()
    if (tripped == "1" and (os.time() - lastTrip >= DELAY)) then
        local modeStatus = luup.variable_get( HVACO_SID, "ModeStatus", THERMOSTAT) or "Off"
        luup.variable_set( HVACO_SID, "LastModeStatus", modeStatus, THERMOSTAT)
        luup.call_action( HVACO_SID, "SetModeTarget", {NewModeTarget = "Off"}, THERMOSTAT)
    end
end

-------------------------------------------------

-- Turn on when doors/windows closed for 10 minuets

local SENSOR = 17    -- The door/window sensor device number
local THERMOSTAT = 3 -- The thermostat device number
local DELAY = 600    -- Seconds
 
local SES_SID = "urn:micasaverde-com:serviceId:SecuritySensor1"
local HVACO_SID = "urn:upnp-org:serviceId:HVAC_UserOperatingMode1"
 
luup.call_delay( "turnOnAc", DELAY)
 
-- Turn on the thermostat if the sensor hasn't been tripped in the past 10 minutes.
function turnOnAc()
    local tripped = luup.variable_get( SES_SID, "Tripped", DOOR_SENSOR) or "0"
    local lastTrip = luup.variable_get( SES_SID, "LastTrip", DOOR_SENSOR) or os.time()
    if (tripped == "0" and (os.time() - lastTrip >= DELAY)) then
        local lastModeStatus = luup.variable_get( HVACO_SID, "LastModeStatus", THERMOSTAT) or "Off"
        luup.call_action( HVACO_SID, "SetModeTarget", {NewModeTarget = lastModeStatus}, THERMOSTAT)
    end
end
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Fred S on April 08, 2013, 07:24:19 pm
Hey everybody. I'm trying to do the same thing... If door or windows are opened for 30 seconds ...turn off air but I'm not sure if I got the syntax right. What I have so far is a trigger to turn off the air and then a condition called DoHAVACAutoOff with the following syntax: (EntryDoorsOpen;NOW > 00:30) or  (KitchenWindowOpen;NOW > 00:30) or (GuestBedroomWindowOpen;NOW > 00:30) or (MasterBedroomWindowOpen;NOW > 00:30). What happens is that it triggers the event right away. Not after 30 seconds. Conversely I have condition to turn the AC back on when the doors are closed which works but I didn't know if I could combine them or not. The syntax to turn it on is DoHAVACAutoOn (EntryDoorsClosed;NOW > 00:10) or (KitchenWindowClosed;NOW > 00:10) or (GuestBedroomWindowClosed;NOW > 00:10) or
(MasterBedroomWindowClosed;NOW > 00:10)
Any help would be greatly appreciated. Thanks
Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on April 08, 2013, 08:28:03 pm
Yep when you do something like:

     (DoorOpen; Now > 00:30)

It will ALWAYS be true 30 seconds after the event happened ... Even if the door was  opened two weeks ago!

You want:
    (DoorOpen and (DoorOpen;Now > 00:30))

Also note the resolution of events is every minute using NOW as a trigger.
So there is not much difference from 00:10 or 00:30 or 1:00.

   
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Fred S on April 08, 2013, 10:23:09 pm
OK I think I get it. So basically it?s an expression within an expression. (I applied it BTW and it worked flawlessly... thank you.)

Could I apply that to another scenario I have? Essentially I?d like my front lights to turn on at night but only if my alarm is armed. I?m thinking I need to create a trigger for AlarmArmed as well as either a schedule for sunset or use the night or day plugin.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on April 08, 2013, 10:29:16 pm
You can use Day or Night.
You do not need a Schedule ...
You could do the following:

LightOn:     ALARM and (NOT (7:00:00; NOW; 19:00:00))

With Day or Night:

LigtOn:    ALARM and NIGHT
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Fred S on April 09, 2013, 10:06:48 pm
Hi Richard. OK so what I'm understanding is that LightOn:     ALARM and (NOT (7:00:00; NOW; 19:00:00)) would essentially be referencing an absolute value. Basically if the alarm is set between 7 pm and 7 am the lights would be on. the same with Day or night except day or night app would automatically adjust for sunrise and sunset.

I did the latter code LightOn:    ALARM and NIGHT but it didn't turn on via a schedule automatically however it did turn on and off when I armed and disarmed my alarm at night. I think I'm half way there. My scenario would be I set me alarm during the day so the lights would be off but nightfall comes before I disarm my alarm. I'd want the lights to turn on at night but only if my alarm was armed. I hope that makes sense. Thanks again for helping me with this fantastic app!!
Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on April 10, 2013, 08:18:20 am
That should work ... And you can test this all day or night ... Just toggle your Alarm and/or the Day Or Night switch.

Make sure you have setup your TimeZone AND Location properly in the Vera Setup tab. Otherwise it will not compute the Day and Night time properly.
 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Fred S on April 15, 2013, 09:42:10 pm
Hi Richard. I didn't want you to think I left you hanging there. I needed to apply what you wrote. I did finally get the (AlarmArmed and Night) expression to work. The problem was that I had two different triggers. (AlarmArmed and Night) which would turn my front lights on if it was armed and night. I also had a counter trigger and expression (AlarmDisarmed and Night) which would turn my front lights off. The problem so it would seem is that only the counter trigger was working so essentially my front light would turn off when night came. I'm not understanding why this would happen though as I was using two different triggers and expressions. The only common factor was "night."
Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on April 16, 2013, 08:52:02 am
EMAIL me your PLEG report.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Fred S on April 16, 2013, 07:16:01 pm
Richard, I emailed you the report as per your request. Please let me know if you have any questions and thanks.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Les F on April 22, 2013, 07:36:35 am

When you get the bugs out, please post the full setup, I can use this at my cabin... people always leaving the doors open and A/C on!
Title: Re: If door is opened for 5 minutes...turn off air
Post by: linkinx on April 24, 2013, 03:33:42 pm

When you get the bugs out, please post the full setup, I can use this at my cabin... people always leaving the doors open and A/C on!

I also would like this, I do not want the A/C shutoff just a notification of hey idiot someone probably left the door open... I seem to often not fully shut my (inside) garage door...
Title: Re: If door is opened for 5 minutes...turn off air
Post by: SOlivas on August 06, 2013, 02:33:09 am
Quote from: SOlivas
See at the end of this for a list of updates/fixed to this code

Ok, I got bored and wanted to try my hand at making the initial code that mcvflorin posted into a plugin, with a few additional features.  I know that there is a SmartVirtualThermostat Plugin already in the apps store (I have not tried it), and because of this, I will only post the code here (for now).  This plugin does not implement the later modification posted to accommodate motion sensors, but I may try this in a future version.

I call this plugin:  Window, Door, and Sensor Control HVAC (WDSC HVAC) plugin v1.0

I moved the files for this plugin here:

http://forum.micasaverde.com/index.php/topic,15982.msg121764.html#msg121764



This should make it easier to find, instead of having to dig several pages into this topic to find the code/files.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Les F on August 06, 2013, 06:27:18 am

Interesting...   I never got around to implementing anything in ref to this, but will play around this weekend.
Thanks for posting!
Title: Re: If door is opened for 5 minutes...turn off air
Post by: SOlivas on October 04, 2013, 01:52:35 am
I just posted an update that lets you use temperature sensors as well as door/window sensors to control your thermostat.

Title: Re: If door is opened for 5 minutes...turn off air
Post by: ryandidur on June 14, 2014, 06:43:01 pm
For Vera to work properly this has to be broken into two steps.

  • Detect Door or Window Opened ... Initiate Timer
  • When the timer expires do some additional work
The plugins I have listed will do this for you.
If you call Sleep ... it causes ALL of VERA to sleep. It will not respond to any other inputs during that period ... If it's long enough it will restart it self ... because it's not responding.

I would like to disable all three of my nest thermostats if any door or window is left open for more than 5 minutes. I can't figure out how to setup PLEG or PLET to do this. Are you able to provide details as to how I can set this up.

Thanks

Title: Re: If door is opened for 5 minutes...turn off air
Post by: SOlivas on July 05, 2014, 03:42:46 am
@ryandidur,
There is a plugin version of this that should do what you want - no coding with PLEG is needed.

Take a look at:

http://forum.micasaverde.com/index.php/topic,15982.msg121764.html#msg121764 (http://forum.micasaverde.com/index.php/topic,15982.msg121764.html#msg121764)

You can define multiple thermostats that you want to have controlled.

--

For PLEG, I would recommend you take a look at the information about this plugin elsewhere on this forum.  There are a lot of really good examples of how to do things with it. 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: klopfensteinj on April 25, 2016, 02:13:54 pm
Below are two code snippets I copied from the wiki that work like a charm if placed in two separate scenes. They each only look at one sensor and do not detect the status of the ac unit before firing to avoid turning on a unit that was manually turned off.

How would one combine them to:
* work within one scene
* Check the status of the ac unit and if off leave off
* check multiple sensors (doors & windows) closed or not tripped
* Return it to the mode it was in when the scene was triggered. (for those units without AUTO)

I can configure the scene with triggers for the doors/windows opening and closing, so triggers are not a problem.

I use the following two lines to check the status of a light to not run the scene if the light is already on manually. Will this work for the thermostat as well?

light = luup.variable_get("urn:upnp-org:serviceId:SwitchPower1","Status",3)
return (light == "1")

If so, I am not sure how to incorporate that into what I want to happen.
-----------------------------------------------------
-- Turn AC off when Doors/windows opened for 5 minuets

local SENSOR = 17    -- The door/window sensor device number
local THERMOSTAT = 3 -- The thermostat device number
local DELAY = 300    -- Seconds
 
local SES_SID = "urn:micasaverde-com:serviceId:SecuritySensor1"
local HVACO_SID = "urn:upnp-org:serviceId:HVAC_UserOperatingMode1"
 
luup.call_delay( "turnOffAc", DELAY)
 
-- Turn off the thermostat if the sensor has been tripped for at least 5 minutes.
function turnOffAc()
    local tripped = luup.variable_get( SES_SID, "Tripped", SENSOR) or "0"
    local lastTrip = luup.variable_get( SES_SID, "LastTrip", SENSOR) or os.time()
    if (tripped == "1" and (os.time() - lastTrip >= DELAY)) then
        local modeStatus = luup.variable_get( HVACO_SID, "ModeStatus", THERMOSTAT) or "Off"
        luup.variable_set( HVACO_SID, "LastModeStatus", modeStatus, THERMOSTAT)
        luup.call_action( HVACO_SID, "SetModeTarget", {NewModeTarget = "Off"}, THERMOSTAT)
    end
end

-------------------------------------------------

-- Turn on when doors/windows closed for 10 minuets

local SENSOR = 17    -- The door/window sensor device number
local THERMOSTAT = 3 -- The thermostat device number
local DELAY = 600    -- Seconds
 
local SES_SID = "urn:micasaverde-com:serviceId:SecuritySensor1"
local HVACO_SID = "urn:upnp-org:serviceId:HVAC_UserOperatingMode1"
 
luup.call_delay( "turnOnAc", DELAY)
 
-- Turn on the thermostat if the sensor hasn't been tripped in the past 10 minutes.
function turnOnAc()
    local tripped = luup.variable_get( SES_SID, "Tripped", DOOR_SENSOR) or "0"
    local lastTrip = luup.variable_get( SES_SID, "LastTrip", DOOR_SENSOR) or os.time()
    if (tripped == "0" and (os.time() - lastTrip >= DELAY)) then
        local lastModeStatus = luup.variable_get( HVACO_SID, "LastModeStatus", THERMOSTAT) or "Off"
        luup.call_action( HVACO_SID, "SetModeTarget", {NewModeTarget = lastModeStatus}, THERMOSTAT)
    end
end

I use this code and after figuring out my triggers to get the scene to turn back on it works great.  One question, I am using this with one sensor, is there a way to list a number of sensors in the code?  My alarm has a wireless sensor on each window and door and would to have this condition for more than one sensor w/o having a scene per sensor.
Thinking like local SENSOR = 17, 18, 19    -- The door/window sensor device number

Thanks

Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on September 15, 2016, 05:41:51 pm
I recently updated to Vera Plus from Vera 3 and undated the firmware to 1.7.2138.  I was speaking with Vera support about problems with getting my vera 3 online when I made this decision so they helped me with the transition.  They recommended that I not transfer my scenes and devices but recreate them.  This should make the system perform much more quickly. 
I decided to take Richard T. Schaffer's advice and try to do this with PLEG. (I had some trouble loading PLEG and PLC, which are the subject of another string.)
I would appreciate any comments on my first PLEG device, described below.

I created inputs using a trigger for each window and door sensor and each motion detector being tripped.
Here is the condition that I created, which would be positive when any sensored door or window was open for more than 60 seconds:
DoorWinOpen = ( tLFrBRWnOpen and ( tLFrBRWnOpen; Now > 00:60)) or ( tLHallWnOpen and ( tLHallWnOpen ; Now > 00:60)) or ( tLBkBRDrOpen and ( tLBkBRDrOpen; Now > 00:60)) or ( tLHallDrOpen and ( tLHallDrOpen; Now > 00:60)) or ( tLFrBRDrOpen and ( tLFrBRDrOpen; Now > 00:60)) or ( tLMstrBRDrOpen and ( tLMstrBRDrOpen; Now > 00:60)) or ( tULanaiDrOpen and ( tULanaiDrOpen; Now > 00:60)) or ( tUHallWnOpen; Now > 00:60)) or ( tUFrDrOpen and ( tUFrDrOpen; Now > 00:60)) or ( tUMstrBRWnOpen and ( tUMstrBRWnOpen; Now > 00:60))

Here is the condition that I created, which would be positive when it has been more than 30 minutes since any motion detector had tripped between the hours of 9 AM and 5 PM:
MDNotTrip = ( tLHallMDTrip; Now > 30:00) and ( tLMstrBRMDTrip; Now > 30:00) and ( tUGRMDTrip; Now > 30:00) and ( tUMstrBRMDTrip; Now > 30:00) and ( tUFoyMDTrip; Now > 30:00) and (09:00:00 < NOW < 17:00:00)

Then I created a logical action, which would be activated and change the SetModeTarget for each of of my 2 Trane thermostats to Off whenever the above conditions were true.  Do I need to make that "Off"? (I set options to repeat for these actions.)

The PLEG instructions say that I must restart Vera and reload browser for any newly created PLEG device to work properly.  Does that mean remotely reboot?
The instructions also say to click the Reload Luup button on the inputs, conditions or actions page.  My UI7 editor doesn't have a Reload Luup button on those pages but there is a Reload Lua button on editor options button drop down and a save changes button under the PLEG device.  I hit both of those.  Anything else that I need to do to save this?  Where is the backup button?
 
Do these conditions and logical actions look correct?

I need to test this PLEG device remotely, since I am 3000 mi away. I can set my thermostats on remotely and check remotely to see if they stay on so I don't need a dummy device to be acted upon.  Any suggestion on how I can test the conditions remotely?  I understand that I should make a dummy door/window sensor and trip it but don't know how to do either of these.  If I am supposed to use a virtualswitch and/or variablecontainer to do the test I don't understand how.

Thanks for any help!
 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on September 15, 2016, 10:44:01 pm
My guest just arrived so I have people triggering motion detectors.  The motion detection part of this script doesn't work properly.  I rebooted vera and refreshed the browser then armed the PLEG device.  At that point, no one had trigger a motion detector or opened a door or window but it kept shutting off my AC within a minute of me turning it on.  I know it was the PLEG device because it stopped shutting off the AC when I put in in bypass mode.  Because this happened so quickly (<= 1 min), can I presume that the problem is in the DoorWinOpen condition?  It was 4 pm there so the time interval was true.
Anyone see any obvious mistakes?
Thanks
Title: Re: If door is opened for 5 minutes...turn off air
Post by: RichardTSchaefer on September 16, 2016, 06:13:29 pm
I tend to ignore requests that do not include a STATUS report generated at the time of the problem to see both your logic and the state and sequence of Inputs and Conditions.
 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on September 03, 2017, 08:35:36 am
Richard, It has been a year since I wrote the PLEG program to control my AC.  I only visit my home 4 times a year and have had a variety of problems with sensors and locks but everything appears to be stable.  How do I generate a STATUS report?
Do I need to create a schedule in order for the PLEG programs to run all of the time?
I have wasted a lot of money on AC in the past year and would like to get these controls running.  Thanks for any assistance that you can give.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Don Phillips on September 03, 2017, 11:22:09 am
Try this:
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on September 04, 2017, 01:08:38 am
I made some changes to my devices then went to editor options/reload Lua.  Then I clicked on status report and nothing happened. 
Title: Re: If door is opened for 5 minutes...turn off air
Post by: Don Phillips on September 04, 2017, 09:46:16 am
Make sure pop ups are enabled.  You will get a new browser window with the status report.  You can then save/print it as a PDF and upload it here.  Here is a sample.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on April 25, 2018, 02:34:57 am
OK, with some help, I figured out how to view a status report and to reload Lua after making any changes (much faster than rebooting Vera). 
My triggers and condition seem to work fine but the problem is with the Logic Action.  I want to shut my AC off via my Trane TZ43 thermostats.  It appears that my only logical choices for Actions are Set Mode (OFF), Set Target (0) and Set Mode Target (OFF).  None of these choices turn off the cooling or change the Mode Status from CoolOn to Off.  How do I change the thermostat Variable Mode Status from CoolOn to Off, which is not in my list of actions under PLEG for that device?  Anyone familiar with controlling this thermostat via PLEG?
I then made a scene where I used my PLEG condition and then used this thermostat's UI to click on the OFF mode.  That works fine but I would prefer to do this with a PLEG Logic action.

I have a similar problem with a Logic Action for an outlet.  My only logical choice within PLEG is Set Target but that won't turn the outlet on.  I need a way to change the outlet variable Status from 0 to 1 but it doesn't appear in my list of available PLEG actions.  Any ideas for each of these devices?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on April 25, 2018, 10:54:33 am
I found a luup command from oTi@ that allows me to change Mode Status (runMode) to Off:
luup.call_action('urn:micasaverde-com:serviceId:ZWaveNetwork1','SendData',{Node='<nodeID>', Data='64 1 <runMode>'},0)
Where <nodeID> is the Z-Wave NodeID (Settings->ID / Advanced->altid), so not the Device#,  of the t-stat, and <runMode> is:
0: off
1: heating
2: cooling
3: auto
4: e-heat

I understand that I would enter it in the Lua field for my Logic Action.
Do I toggle on "save output as logic variable"?
Is there a specific name that I should give this logic variable?
I am not sure what to do with this now.  This is the action that I want to take when my condition is true.
How do I execute this action?
Do I leave everything below this step blank?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on April 28, 2018, 02:30:04 am
luup.call_action('urn:micasaverde-com:serviceId:ZWaveNetwork1','SendData',{Node='38', Data='64 1 <runMode>'},0)
I still haven't figured out how to get the above Luup call to change the value of the thermostat mode status to OFF by entering it in the Luu box of a logical action.
I found that another logic action option for my thermostat is "Send Data".  The first field is Node for which I entered 38 (identifies the particular thermostat device).  The next field is Value. Not surprisingly, 0 doesn't work probably because I didn't specify which variable I want to set at 0.  However, I wasn't given the option to enter '64 1 <runMode>' any where.  I tried entering '64 1 <runMode>, 0' in the Value field but that didn't work.  Is there a certain format that I can use to enter this data in the fields of a logic action under "Send Data"?
Essentially, I am trying to find a way to turn off my Trane thermostat within PLEG.  It appears that I want to change the ModeStatus to Off but that is not an option for my thermostat  in PLEG.  I can't find a way to enter the Luup.call_action above as a logical action.  Does anyone know if my Node='38', Data='64 1 <runMode>' variables are correct for the modestatus variable?
Title: Re: If door is opened for 5 minutes...turn off air
Post by: aecchalet on September 13, 2018, 02:17:54 am
I still haven't figured out why I can't shut off my AC at my thermostats with PLEG.  I created devices for each door & window sensor.  I created a condition to be true when any of the door or window sensors are open for more than 60 secs.  My problem is that I can't get my logical action to work properly.  I chose the desired condition then select both thermostats.  It appears that my only drop down logical choice is ModeTarget = Off.  When I test the logical action after saving it and clicking the run button, the status report indicates that the ModeTarget has been correctly changed to Off.  However, it doesn't shut off my AC.  When I open the thermostat device in UI7 of the AC unit that is running, go to advanced and then the variables tab, the ModeTarget is still set on CoolOn.  The same thing happens when I try to create a logical action to turn on the AC by changing the ModeTarget to CoolOn.  The status report will indicate that the ModeTarget is CoolOn but the AC will not turn on and the Variable field in the thermostat is still Off.
My work around has been to use that condition to trigger a scene.  When the condition is true, my scene will turn off the AC.   When it does so, the variable tab shows that the ModeTarget switches from CoolOn to Off.  I just can't get the PLEG logical action to do that!
I have attached my status report if anyone has any ideas.
Title: Re: If door is opened for 5 minutes...turn off air
Post by: pkaplan on March 12, 2019, 01:56:55 pm
This thread has been quiet for a long time now. But, I just started hacking away at the original request in the latest firmware (Shut off HVAC after 5 minutes of open sensors.)

Does anyone else still have an interest in this? If so, let me know and I can clean up and post my code if others are willing to test.