Reading onoff property with Homeyscript

Hi,

I’m trying to create my first homeyscript. I do have experience in programming but not in JavaScript, and I can’t wrap my head around this, in my opinion, very simple problem.

I have this Hue light, and I want to make a script that switches the light on when it’s off, and vice versa.

The switching on/off part is working, but getting the current state is the problem.

This is what I have:

let LightID = '1d81d3cd-f3ec-4025-8210-4cb930004577';

var MyLight = await Homey.devices.getDevice({ id: LightID });

await MyLight.setCapabilityValue('onoff', true);

I tried to read the onoff property in different ways (I found browsing scripts on this forum), but all below are not working (“is not a function” error):

MyLight.CapabilitiesObj.onoff.value
MyLight.getCapabilityValue('onoff')
MyLight.state.onoff

If anybody can help me get on my way, I’d most appreciate it!

MyLight.capabilitiesObj.onoff.value

However, this is a lazily updated value, which means that you cannot change the state and retrieve it from the same script and expect the retrieved state to match the changed state. The other way around should work: retrieve it (for instance to check if it’s already on or off), then change it (using setCapabilityValue).

Thanks for the help, this is now working.

I did try something like this before but got an error. Maybe I got the error on some other part of the script.

I noticed the “lazy” part. Checking too soon after setting the value, indeed results in the wrong value.

So this is wat the script now looks like now (for future reference).

let LightID = '1d81d3cd-f3ec-4025-8210-4cb930004577';

var MyLight = await Homey.devices.getDevice({ id: LightID });

if (MyLight.capabilitiesObj.onoff.value) {
    await MyLight.setCapabilityValue('onoff', false);
} else {
    await MyLight.setCapabilityValue('onoff', true);
}
1 Like