[SOLVED] Contact to change a switch

I have contact0 simulating a push-button: evry time I click contact0 I have to change the status of switch0. (for example contact0 is a button that switch on and off a light).
I’ve used the following code:

rule “test contact”
Item Contact0 changed
if (Contact0.state == OPEN) {
if (MySwitch0.state == OFF) {
sendCommand(MySwitch0, ON)
if (MySwitch0.state == ON) {
sendCommand(MySwitch0, OFF)

I guess it can be improved. Does anyone have any suggestion ?
Thank you !

It is pretty simple code. You can reduce it a tad, and handle the case where MySwitch0 is Undefined:

rule "test contact"
    Item Contact0 changed to OPEN
    MySwitch0.sendCommand(if(MySwitch0.state != OFF) OFF else ON)


  • Since you only do something in the rule if Contact0 is OPEN, set the trigger so the rule only fires if the it is OPEN.
  • If MySwitch is ON or Undefined it will be turned OFF. If it is OFF it will be turned ON.
  • The if statement on one line like this is called a trinary operator and can be a useful way to reduce a lot of boilerplate code

Many thanks Rich !

Is it possible to find somewhere a manual describing for every item what are attributes and methods available ?

There is no one place.

  • Rules wiki page for a general outline
  • Actions wiki page for commands you can call in your rules
  • Xtend documention for a detailed description of the programming langauge, though be aware that the Rules programming language shares a common ancestor with Xtend but it is not exactly the same. Some of the things that work in Xtend will not work in openHAB (e.g. creation of classes)
  • the many examples on the wiki (bottom right) and on this forum
  • use Designer and learn the <ctrl>-<space> key combo which will show you a list of valid ways to complete what you have typed. For example, typing "MySwit<ctrl>-<space>" will bring up a list of all of your Items that start with “MySwit”. If you type in "MySwitch.<ctrl>-<space>" it will bring up a list of all the valid methods you can call on MySwitch.

Knowing a little about how Java works can help but it is not a requirement.