Trrying to turn a device off after a certain amount of time

Im trying to turn an item off after 2 mins, but what i have isnt working. Im pretty new to this so it my all be tottaly wrong

Item File

Switch ToiletLight “Light” [ “Switchable” ] {mqtt=">[broker:cmnd/sonoff-12/power:command:OFF:0],>[broker:cmnd/sonoff-12/power:command:ON:1]"}

Rules File

var Timer md1Timer = null
val int timeoutMinutes = 2

rule "ToiletLight received ON"
when
Item ToiletLight received command ON
then
if(md1Timer == null) {
md1Timer = createTimer(now.plusMinutes(timeoutMinutes ), [|
ToiletLight.sendCommand(OFF)
md1Timer = null
])
}
else {
md1Timer.reschedule(now.plusMinutes(timeoutMinutes )
}
end

There is a bracket missing at the end of the last but two line.

md1Timer.reschedule(now.plusMinutes(timeoutMinutes))
                                                  /\

Apart from that the rule seems ok to me.
Does the switch work at all if using through UI?
I don’t use mqtt, so I don’t know if the item definition is correct, though it seems correct either.

You wouldn’t need the italic part, but the main problem is a missing second ) after timeoutMinutes.
Also see this on NULL vs null.
Also, I vaguely recall that if comparing against null, you need to use !== (or ===) in latest software version, but I fail to find a reference. Usually the rule parser will complain about.

Either way, make sure you make use of proper tooling. Will make it a lot easier for you to write error-free rules.
Use the Eclipse Designer, or set proper debugging so you will get alerted by the parser in openhab.log (set debug level for org.openhab.model.script.rules and .engine logging).

check out the expire binding also

+1 The expire binding is simple to implement and just works

Examples of Expire Binding as a Timer:

I would wait for an error in the logs before I would blindly switch over to using !== and === verses != and == because the two are really two different operations and it is not entirely clear to me yet exactly when the rules parser complains about it.

== calls the .equals method but === does a Java identity equals. Thus if I had:

val string1 = "foo"
val string2 = "foo"
operator result comment
string1 == string2 true compares each letter in the two strings
string1 != string2 false comares each letter in the two strings
string1 === string2 false determines if both variables point to the same place in memory
string1 !== string2 true determines if both variables point to different places in memory

As you can see, in this case, == and === produce exactly opposite results.

The reason why string1 === string2 doesn’t work as expected is because string1 and string2 are not literally the same object and === only compares the memory address the variables point to.

Unfortunately, this is something built into the base language and not something I think we can get rid of in OH 2, but were I king for a day I would find a way to make == smarter and do away with === because it is only going to continue to cause major headaches going forward.

4 Likes

Guys, thanks for all your help, there is a lot of info there to process.

Regarding logs is there any easy way to view them

Yes the rule works OK in the UI

Ok, so the the missing ) was the answer to the initial timer problem, the light turns off after 2 mins which is great, however there are 2 further issues which I guess are linked.

  1. When the device turns off by the timer rule, the Switch icon on the UI still shows as on.
  2. When I turn the item on manually (Its a Sonoff Touch Switch) the rule does not turn it off after 2 mins

Items File
Switch ToiletLight “Light” [ “Switchable” ] {mqtt=">[broker:cmnd/sonoff-12/power:command:OFF:0],>[broker:cmnd/sonoff-12/power:command:ON:1]"}

Sure, they’re just files under /var/log/openhab2.
Then again, if you don’t know that, I guess you haven’t even looked at the beginner tutorial but somewhat jumped right into the middle. Start over with the basics at http://docs.openhab.org/tutorials/beginner/index.html.

It should, but there’s a number of situations where this does not or cannot work.
Could be because you use a Sonoff, that for sure is not the best switch in terms of SW (and HW), so a couple of issues are likely caused by that. Try to insert ToiletLight.postUpdate(OFF) after the sendCommand line.
Definitely not the best choice for a beginner to start with …

by “item” you mean the physical switch ? (as opposed to manually operating the virtual item in UI).
Well,first that would require the Sonoff to send a message (I guess it does that using MQTT? but don’t expect us to know …), and second you would need to configure openhab to accept input from MQTT channel and assign that to your switch item. That part is missing in your switch item definition above, the “>” will only generate output…search this forum for MQTT for examples on how to do that.

As I already said, definitely not the right device to start with for a beginner.

Markus
Thank you for your informative reply, I will digest your reply, with regards the “Logs” I have looked at the beginner tutorial, however I got stuck on the very start “open the finder,” it would be helpful if the guide explained what FINDER was and how to access it.

Regarding Sonoff, I have had a lot of success with them, I have 9 of them active at the moment, but only one Sonoff Touch. Please could you advise which devices you prefer as I am always open to suggestions.

regards
Steve

Hmm, I don’t know either. Possibly something simple like a file viewer program, but I haven’t heard that term before.
@ThomDietrich, would you mind to rework that page (or hand this task to whoever wrote it) ?
Btw, the final chapter (on persistence) also still needs to be written.

Well I use many ZWave devices as ‘generic’ switches, but there’s many many options, and they in turn are highly dependent on several factors (location, existing tech, your housing situation, knowledge, functionality, price, use cases, …), so one cannot answer that in a generic fashion.

I don’t think this is entirely correct.

Unless I am mistaken, the triple-euqal-operator (===) takes the type of the two operands into account, i.e. first it checks if the operands are of the same type, then - if they are - it checks if the “content” of the two operands matches.

The double-equal-operator (==) on the other hand may do an “implicit type conversion” (if needed) before matching only the contents of the two operands. As I understand it, this means that the string “123” will match the integer 123.

That I think is how it works in JavaScript. But the Xtend docs say:

In Xtend the equals operators (==,!=) are bound to Object.equals. … Java’s identity equals semantic is mapped to the tripple-equals operators === and !== in Xtend.

According to this and other articles identity equals in Java (i.e. Java’s ==) and based on my memory from coding in Java:

We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.

So, given the above, I think you are mistaken and === does not take the type of the two operands into account. It only looks at the memory address.

This is true in JavaScript and perhaps other languages (Python?). This is not true for Java and by extension Xtend. In Java you cannot compare “123” to the integer 123. With == it will always evaluate to false. To use .equals you would have to create your own new class and create a .equals(int) method that converts the int to a String or the opposite.

Yep, I can see now that I mixed it up a bit (or even a great bit). Thanks for clearing this up!

Good to have this sorted out (thanks). Just for completeness: the parser only requests to use !==/=== whenever the operand to compare to is NULL(or null?) - it does not tell you to use this when you intend to compare two objects of the same type.

When the device turns off by the timer rule, the Switch icon on the UI still shows as on.
When I turn the item on manually (Its a Sonoff Touch Switch) the rule does not turn it off after 2 mins

it seems your switch item des not get an update on its MQTT channel. I see 2x “>” but no “<”

If you want the actual state of the SOnOff to show up in the UI rather than the command you last sent it, you need to change your SOnOff so the state of the relay is used to update the UI when it changes.
I have copied the entry for one of my items on a SOnOff 4Ch running Tasmota below as an example.

Switch DiningLight (gMAPDB)	{mqtt=">[mosquitto:cmnd/loungeesp2/POWER1:command:*:default],<[mosquitto:stat/loungeesp2/POWER1:state:default]",autoupdate="false"}

With this setup the status update from the SOnOff is what changed the UI, autoupdate=“false” prevents the initial command from changing the item, and with this setup pressing the button on the SOnOff updates the UI too. I use variants of this with all my ESP based items as it gives me the best idea of what is actually going on, rather than what should be going on

Guys, thanks for all your help its really appreciated, however i still have my original problem. From reading some of the replies, I may not have explained the problem very well so I will try and give a better explanation, as I have done some more testing.

I’ve got the Sonoff touch switch, and because my kids are always leaving the toilet light on, I want it to turn off after a pre- determined number of minutes. I have a rule for this and it intermittently. i use the word intermittently loosely, what i should say is it works under certain conditions, which will be reviled below. I have listed the specific line from my ITEMS file below (Some of you may notice some changes I have made to it. Don’t worry that it says GarageLEDS, and not ToiletLight, The GareLEDS are closer for me to test than having to walking to the toilets lights every time to check them.

Switch GarageLEDS “Garage LEDs” [ “Switchable” ] {mqtt=">[broker:cmnd/sonoff-18/power:command:OFF:0],>[broker:cmnd/sonoff-18/power:command:ON:1],<[broker:stat/sonoff-18/power:state:default]"}

Scenario 1 - OPENHAB2 UI - WORKS
Switch on
Light turns off after 60 seconds

Scenario 2 - SONOFF UI (in Web Browser) - NOT WORKING
Switch Light On with “TOGGLE” button
Light never goes out (Until Toggle button pressed again)

Scenario 3 - SONOFF SWITCH - Doesn’t Work
Switch light on with Hardware Switch
Light turns on but never goes out until switch is pressed again

For all the above scenarios, I can see MQTT messages in MQTT.fx

For all 3 scenarios the messages that come back to MQTT.fx are identical

I get a stat/sonoff-18/RESULT which is [“POWER”:“OFF”] or ON and a stat/sonoff-18/POWER OFF or ON

I think I must be missing something really simple.

I also just notice that if I tell my Amazon Echo Dot to turn the lights on, they come on and then turn off after the required time set in the RULES, now i am really baffled

Steve

So your MQTT messages sent from Sonoff aren’t processed by OH, most likely because the MQTT binding does not forward them to the internal event bus. Check for events to arrive in /var/log/openhab2/events.log as the first step, though.
I’d double check the MQTT binding config next, ramp up logging (org.openhab.binding.mqtt), eventually restart the MQTT binding (bundle:restart in Karaf console) to see if there’s problems connecting to MQTT.fx
But since you also said it works with a different type of Sonos switch, it might be because it’s listening for a channel topic that doesn’t match what the Sonoff is sending to.

Switching via Echo works as that turns the OH item on just like when you use the UI.