Determining Switch Status in Device Handler

I am struggling with a syntax problem.

I have a device handler that is a Virtual Switch. It looks like this:

	tiles {
	standardTile("theSwitch", "device.switch", width: 2, height: 2, canChangeIcon: false) {
		state "on", label: 'On', action: "switch.off", icon: "st.Lighting.light13", backgroundColor: "#00AA00"
		state "off", label: 'Off', action: "switch.on", icon: "st.Lighting.light13", backgroundColor: "#AAAAAA"
	}
	standardTile("OnButton", "device.button", width: 1, height: 1, canChangeIcon: false) {
		state "pushed", label: 'On', action: "switch.on", icon: "st.Kids.kid10"
	}
	standardTile("OffButton", "device.button", width: 1, height: 1, canChangeIcon: false) {
		state "pushed", label: 'Off', action: "switch.off", icon: "st.Kids.kid10"
	}
	main "Switch"
	details(["Switch","OnButton","OffButton"])
    
}

}

Now, I’d like to be able to act conditionally inside the Device Handler on the current value of theSwitch, its ON or OFF status. There seem to be several ways to get its status in the documentation, but when I try to use them, I get this error every time:

java.lang.NullPointerException: Cannot invoke method currentValue() on null object @line 64 (stateOn)

Here’s one example of how I’ve tried to just get the value:

def stateOn() {
   def currentState = theSwitch.currentValue("switch")`
 }

I’ve also tried several alternate syntaxes from the documentation such as

def currentState = theSwitch.switchState

and the variant using latestValue.

But in all cases I get the nullObject error.

I think it’s just a syntax problem… or… ???

To get the attribute values from within the handler you have to use:

device.currentValue("switch")

2 Likes

You’re my best friend for the rest of the day.

1 Like