Toggle lights with one button; how to query ON/OFF state

  • Platform information:
    • Hardware: Raspberry pi 3
    • OS: OpenHabian
    • Java Runtime Environment: 11
    • openHAB version: Openhabian 3.0.1
  • Issue of the topic:
    I am trying to create a rule that will let me toggle lights on or off when i press one button (The same button) The button is actually a tasmota device that has a keypad, and the lights are tasmotized 3stone rgb lights using hue emulation.

The keypad part works (when i press a button, i can see the event in openhab logs, and i can also trigger rules. The problem appears to be with the rule itself. I am using the following code:

var currentvalue;
currentvalue = itemRegistry.getItem('Bedsidelamp').getState();
if (currentvalue == "OFF") {
  events.sendCommand('Bedsidelamp', 'ON');
} else if (currentvalue == "ON") {
  events.sendCommand('Bedsidelamp', 'OFF');
}

After troubleshooting, i realized that getState() is returning a numeric value that appears not to be the ON/OFF state. For example, as i am writing this, the value shows as a card in the interface and it is set to 0.23

I have also tried to query one of the points of the equipment (_Color). I did this because the interface does show an on/off switch. So i modified the code to do run the following when the rule is triggered.

var currentvalue;
currentvalue = itemRegistry.getItem('Bedsidelamp_Color').getState();
logger.error(currentvalue)
brightness = currentvalue.getBrightness();
if (brightness == 0) {
  events.sendCommand('Bedsidelamp_Color', 'ON');
} else if (brightness > 0) {
  events.sendCommand('Bedsidelamp_Color', 'OFF');
}

However, it does not look to me like the brightness in the HSV object color necessarily corresponds to the ON/OFF state. And i could not find out what could.

The issue that i am facing is that the values returned do not appear to represent the on/off state. So what happens is, that i press the button once, and nothing happens (It appears that the rule sends an OFF command to a light that is already off), and then, the next time the command works. Almost like something (Maybe the itemregistry) looses state at some point. Before troubleshooting that further, i want to make sure that i am querying the correct states.

In summary. how can i query the ON/OFF state of a light bulb? I understand this might depend on the light bulb, but if it does, how can i find out how to query it in my specific light bulb?

I wanted to post some code about how the light bulb is created, but i didn’t find how in OH3. What i can say is, the light was automatically discovered by OH3, and it is an equipment of the semantic class “Lightbulb”.

Any help is appreciated.
Thanks!

  • Please post configurations (if applicable):
    • Items configuration related to the issue: The light has two Points, Color, and Color Temperature.

    • Sitemap configuration related to the issue

    • Rules code related to the issue

    • Services configuration related to the issue

  • If logs where generated please post these here using code fences:

This ignored prompt is important. What is the type of your Item?

Dimmer types and Color types never have a state ON or OFF, but you can ask the framework to work it out with .getStateAs(OnOffType)

Hello @rossko57:
Thanks for that. i did not mean to ignore stating the items. i just thought that the the item configuration was implied by stating the device, since OH3 auto-discovered the object.
I have updated the topic to include that information.

I guess what confuses me is the fact that dimmer and color types never have a stat ON or OFF. The interface can definetely figure out if the equipment is on or off, since it has a switch. I am just trying to replicate that behaviour with an external control.I imagine the state is derived from The HSB/HSV values of the item. but, how can i find out what combination of values is on, and what combination of values is off, so i can query it?

Thanks for your suggestion on using getStateAs(OnOffType). I will try it, can you point me to some documentation where i can learn of all the methods available?

Thanks again

A Dimmer has state 0-100, that’s all. It’s pretty self evident 0 brightness is “off” and all else is “on”, so you could test the state for zero or not if you wanted.
Or get the framework to do it for you with as

Color Items have HSB state, so you could isolate the brightness component in a similar way if you really wanted.

but I think the docs are being reorganised.

Hey @rossko57:
If you look at my code snippets above, you will see that i tried exactly those things. For some reason, i was not able to get the remote to work reliably, it resulted in the behaviour mentioned.
Additionally, i tried to get the value as an OnOffType with both:

currentvalue = itemRegistry.getItem(‘Bedsidelamp_Color’).getStateAs(OnOffType);
and
currentvalue = itemRegistry.getItem(‘Bedsidelamp’).getStateAs(OnOffType);

Both failed with:
20:30:15.076 [ERROR] [re.automation.internal.RuleEngineImpl] - Failed to execute rule ‘3fda737c18’: Fail to execute action: 2

and no more details about it.
Thanks

What’s ‘action 2’? We don’t know the structure of your rule. Use the 'code tab. We still don’t know the type of the Item involved.

Example of usage here

Hi again:
“Action 2” is the only action i have in the rule, action id 2. It is basically the code i posted previously.
the light has 2 points. one is a color type. The other one is a “Color temperature”, which i am assuming it is a dimmer type.

I looked at the posted example, and i managed to get my action working using getStateAs, with the following code:

var currentvalue;
var logger = Java.type('org.slf4j.LoggerFactory').getLogger('org.openhab.rule.' + ctx.ruleUID);
currentvalue = itemRegistry.getItem('Bedsidelamp_Color').getStateAs(OnOffType.class);
logger.error(currentvalue);
if (currentvalue == 'OFF') {
  events.sendCommand('Bedsidelamp_Color', 'ON');
} else if (currentvalue == 'ON') {
  events.sendCommand('Bedsidelamp_Color', 'OFF');
}

This code targets the color point of the lamp. I would have preferred to make it work targeting the lamp equipment itself instead of the point inside of it, however, i suspect i might have to change some metadata to do that. I think i need to learn more about how the equipment is represented, and how the values that equipment can hold are calculated.

In the mean time, i still have a strange behavior where after not using the remote for a while, the first time i press the button, the light does not turn on…i am going to have to investigate this further. Maybe an issue with the tasmota configuration (maybe the device going into sleep mode?) but i currently have no idea what the issue is.

Thanks

The keyword here is going to be Item. Items are the objects at the heart of openHAB, Items are the objects rules operate on, Items are the objects interacting with the UI, Items are the objects interacting with device-specific Things and channels.

‘Points’ and ‘Equipment’ are just presentation metadata attached to Items. ‘Equipment’ is really just a type of Item, a Group, that allows collections of Items to be formed.
You can probably tell I’m unconvinced of the usefulness of this metadata, and indeed you don’t have to use any of it in OH3. openHAB is flexible.

Two parts to that; does the button press make it to openHAB, does the device respond to instruction? Your logs will reveal, openhab.log and events.log

Hey @rossko57:
Thanks for all your help on this.

Regarding Items, that confuses me a little bit. I always thought that the real power was on leveraging the semantic model to abstract the different equipment you want to control.

For example, in this case, my lightbulb has a color item and a color item temperature. But at the same time, that is bundled into a “lightbulb” equipment. If i manage to make my llightbulb equipment turn on and off as i want to, then i can make groups of lights within the same room, and control them that way. And subsequently, i can assign those groups to locations and act upon that.

If i rely only on items to control my equipment, besides the semantic model, i need to start creating non semantic groups that contain things like the color items of my lights to be able to control groups of equipment.
It feels to me that defeats the point of having a semantic model. Going back to the same example of this lamp, the default widget for it is a label, that currently has a value of .23. That value is probably calculated from some kind of aggregation of the color temperature item and the color item inside of them. If i can understand how it is calculated, and even more, if i can change the value or calculation (which is why i think i need to understand more on equipment default behavior), i can act directly on the lamp semantic model, which makes a little bit more sense to me.

Regarding the “Strange behavior”, i am currently testing the new script, but i think i need more testing. In the last couple of tests, it seems to me that the button press reaches openhab (i am looking at the console logs), and the command to turn on the light reaches the lightbulb, but there is some delay (seconds )between the time i press the button and the time the light turns on. This does not happen always, which is what threw me off at first. It mostly happens when i have not used the light for a while (half a day or so). As mentioned before, that makes me suspect of an issue with the lamp maybe going to sleep mode or something, but that is a wild guess right now. Another possibility could be that the hue emulation on tasmota just takes a while to respond sometimes, which i can test by switching to control through mqtt (defeats the point of auto discovering these lights, but if it works better, i am all for it).

Thanks again!

Everything in this statement is correct except for the word “control”. The model is a way to abstract and organize your Items. But you still have to control them through the Point Items.

Correct. It is not expected that all your Items and Groups are a part of the semantic model. Right now the only things that the model is used for are:

  • defining the Overview Pages in MainUI
  • natural language interactions using HABot
  • there are a few new Actions that can be used in rules to query for semantic information about a given Item

It doesn’t change the nature of what a Group is or how Group Items work. It doesn’t change the nature of Item types. All that the semantic model does is provide a way to add a little bit more information about what the Items represent.

The model makes no changes to how things are controlled.

Given that, your LightBulb tagged Group Item is still just a Group Item. You can give it a type and you can sendCommand to it just like any other Group Item. However, when you send it a command, that command will go to all members of the Group. That is almost certainly not something you’d ever want to do with an Equipment because an Equipment’s entire reason for being is to group together all the different actuators and sensors for a device.

Correct, in which case either the individual Items should be left out of the model or your control Groups would be left out of the model.

Your expectations of what the semantic model does and what it’s for are not correct.

Let’s take an only slightly more complicated example. My front door. It has a bunch of sensors, a smart lock, and a camera all represented as part of the front door Equipment. If I send an ON command to the front door, what should happen? The lock unlock? But what about the camera? Maybe what I really intend is for the camera to take a still image. How can I control both the lock and the camera through the front door Equipment Group? What state should the Equipment Group show? The door’s open/closed state? The lock’s locked/unlocked state? The camera image?

The whole concept of Groups simply cannot handle that. And since the semantic model is entirely represented using Group membership and tags, there is no way for the semantic model to handle that either.

It’s hard to say what is being used for the calculation but it’s likely the average of all the members of the Group. But knowing that doesn’t help you because it doesn’t work two ways. If you send .23 as a command to the Equipment Group it’s not going to reverse the calculation and send the right brightness to the dimmer and the right color temp to the color temp Item. It’s just going to send .23 to both Items.

You simply are not going to be able to use the semantic model for control in this way.

1 Like

Ahh the semantic model is an excellent tool.

Is it 1 switch on tasmoata to 1 light tasmotised.

if so you can directly do this through tasmota rules and cut out the openHAB.

or using openHAB

If its multiple lights how do you want to define the current state of the lights. e.g. 5 lights total and if 3 lights are on when I press the button it will turn the lights blah.

What type of item is Bedsidelamp?

Can you create a switch item and link it to the same channel and turn the light on and off with that?

This new item can be used to turn the light on and off and determine state.

@rlkoshak
Everything in this statement is correct except for the word “control”. The model is a way to abstract and organize your Items. But you still have to control them through the Point Items.

Ok, noted, thanks for the clarification.

@rlkoshak
That is almost certainly not something you’d ever want to do with an Equipment because an Equipment’s entire reason for being is to group together all the different actuators and sensors for a device.

Understood. I agree with this, however, in my head it conflicts a little bit with the fact that you have semantic model objects that are meant to model equipment. I understand you will never want to send “On” or get the state of a coffee table, if the coffee table has a lamp and and a smart electric teapot in it. The status will likely not make any sense, and the command will likely have unintended consequences depending on if you just wanted to turn on the tea pot, turn on the lights or both. However, since you can model a light, i thought of trying to leverage that to control it too. Specially since the equipment model created for a lamp will let you issue commands to it. At this point, and as far as i can see, to only limitation to do this is having a better understanding on the default metadata assigned to the equipment semantic type, and how to change it if it does not behave properly.

@rlkoshak
Let’s take an only slightly more complicated example. My front door. It has a bunch of sensors, a smart lock, and a camera all represented as part of the front door Equipment. …

Yes, the door is a great example, i would think, like the coffee table above. I think my confusion comes from the fact that, when i think about equipment, i think about a physical item capable of responding to actions…So light bulbs, water heaters, blinds, etc. When Things like doors or coffee tables to me, are more akin to a functional group. So if i had to define them semantically, they would be something like a location that contains equipment (The sensors, actuators, etc), and then i would have a functional group (non semantic) that would control things on that location.

@rlkoshak
It’s hard to say what is being used for the calculation but it’s likely the average of all the members of the Group. But knowing that doesn’t help you because it doesn’t work two ways. If you send .23 as a command to the Equipment Group it’s not going to reverse the calculation and send the right brightness to the dimmer and the right color temp to the color temp Item. It’s just going to send .23 to both Items.

Got it. My thought process was something like: “a semantic equipment allows me to control it. it already has switches, dimmers, etc. It is not working as expected. However, if i can modify the metadata so the equipment actions are assigned to specific items inside the equipment, a wil be able to control the the behavior of the equipment by controlling the semantic object”. I have realized there are some limitations to this though. One of them is the fact that i cannot select all item types in the metadata section of the equipment, so i cannot direct its behavior to , for example, a color type (i think you opened a bug about this for me).

Anyway, the whole explanation of the semantic model has been extremely helpful. I will go back and reevaluate my deployment taking this into account.
Thanks!

Hi! Thanks for your help on this.

@denominator
Is it 1 switch on tasmoata to 1 light tasmotised.

if so you can directly do this through tasmota rules and cut out the openHAB.

or using openHAB

Both devices are tasmotized yes. Initially, i decided to go through openhab because i wanted to learn more about mqtt and rules. I am aware i could just use mqtt directly between the devices. However, i have more complex scenarios that not only involve tasmota devices, so i decided also to uniformize my automation rules in openhab

@denominator
If its multiple lights how do you want to define the current state of the lights. e.g. 5 lights total and if 3 lights are on when I press the button it will turn the lights blah.

For this example, i am just doing a simple test where 1 button on 1 tasmota toggles the light on 1 rgb lightbulb. I do have other rules set up where the toggle button just acts when either all lights are on, or all lights are off.

@denominator
What type of item is Bedsidelamp ?

It is a tasmotized 3stone rgb light. The sematic equipment contains 1 color item and 1 dimmer item for color temperature

@denominator
Can you create a switch item and link it to the same channel and turn the light on and off with that?

I have tried this and it works. i was just trying to keep channels associated to as little things as possible, i find that kind of thing difficult to track.

Additionally, while troubleshooting a number of things, i had to reboot my openhabian device…after that, i have had way less instances where a command delays or does not respond…i need to really look at moving the openhabian install to an external hard driver, and get some performance metrics for the device itself.

Thanks!

Keep in mind with the front door example that “Frontdoor” is an Equipment tag, not a location tag.

To help with thinking about it I think maybe an HVAC system might be a better example. I don’t think anyone would argue that an HVAC is not an Equipment. However, there are often multiple actuators:

  • temperature setpoint
  • mode (heating/AC/OFF)
  • separate control for the fan (if a forced air system)

And multiple sensors

  • humidity
  • current temperature
  • status of the system (e.g. heating ON)

These are all naturally a part of a single piece of equipment. But there really isn’t a way to control or understand what’s going on with it using just the parent HVAC Group Item.

However, when it comes to the UI the story changes a little bit. You can assign/configure custom widgets to the Equipment Group Item. That custom widget can in fact be a unified set of buttons and dials that allow for the representation and control of the Equipment in a unified whole. I don’t have my HVAC integrated with OH right now but the examples I put into the Getting Started Tutorial illustrate this.

For the list widgets (those widgets that appear on the cards in the Overview page) you can define a widget that merges multiple Items into one widget. In the tutorial I show that the sensor telling me whether the garage door is open or not is merged with the switch that lets me trigger the garage door opener. I’ve applied this widget to the Switch Item and excluded the Contact sensor Item from the model, though one could also set the visibility to false and keep it in the model.

But to address your light bulb with two controls, you could do something similar. Define a default list item widget and apply it to the Dimmer Item that allows control of both the Dimmer and the Color Temp. Then either hide or exclude the color temp Item from the model. One control and multiple Items.

There are further examples at Example Custom List Widgets.

For the non-automatically generated pages you can do something similar also. For example, in the tutorial I show a unified Chromecast widget. This widget unifies the display and controls from nearly a dozen different Items all associated with the same Chromecast. Once this custom widget is created, I can assign it as the default card widget to the Equipment Group that represents that one Chromecast. Now, on the Overview page or on any other layout page I can select “add from model”, select the parent Chromecast Equipment Group Item and it will drop that unified widget onto the page.

I bring this up because control, from a UI perspective, is indeed able to handle representing more than one Point Item in a single widget. And you can leverage the model, if only a little bit, to make it possible. But from rules and Persistence and Sitemaps and such, you’ll have to deal with each Point Item directly, not through the parent Equipment Group.

1 Like

:+1:

Rules and items don’t cost you extra money or time. You can write super complex rules and forget how they work. I do this sometimes and have to re-learn how they work. To do complex rules I use VSCode with the openHAB extension and text based rules.

For easy rules the UI is good. I use DSL rules

So you have a light you want to control by multiple means.
You have a light
You have a switch

You want the state of the light to change when you press a button.
The button gives openHAB and on or an off when you press the button.
The light can be controlled using a switch item on/off.

Lets create a new rule that toggles light when switch received a command

triggers:
  - id: "1"
    configuration:
      itemName: switch_1
    type: core.ItemCommandTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/vnd.openhab.dsl.rule
      script: |-
        if(BEDROOM_LIGHT.state == ON) {
            BEDROOM_LIGHT.sendCommand(OFF)
        } else {
          BEDROOM_LIGHT.sendCommand(ON)
        }
    type: script.ScriptAction

@rlkoshak
I bring this up because control, from a UI perspective, is indeed able to handle representing more than one Point Item in a single widget. And you can leverage the model, if only a little bit, to make it possible. But from rules and Persistence and Sitemaps and such, you’ll have to deal with each Point Item directly, not through the parent Equipment Group.

I think the distinction you made in this paragraph between the UI and rules, persistence and sitemaps really drives phone the idea. That and examples will certainly point me the right way.

Thanks for all the insight!

I need to get more into DSL rules. They look cleaner. i am currently using javascript, and the following is the script that i use:

triggers:

  - id: "1"
    configuration:
      thingUID: mqtt:broker:abcdef
      event: '{"MPR121A":{"Button7":1}}'
      channelUID: mqtt:broker:abcdef:iot_bedroom_rm2
    type: core.ChannelEventTrigger
conditions: []
actions:
  - inputs: {}
    id: "2"
    configuration:
      type: application/javascript
      script: >
        var currentvalue;
        currentvalue = itemRegistry.getItem('BedsidelampRicardo_Color').getStateAs(OnOffType.class);
        if (currentvalue == 'OFF') {
          events.sendCommand('BedsidelampRicardo_Color', 'ON');
        } else if (currentvalue == 'ON') {
          events.sendCommand('BedsidelampRicardo_Color', 'OFF');
        }
    type: script.ScriptAction

It works well, but i do like the way the DSL rule looks better