SmartThings Community

Retain Variable Values between Event Handlers

The groovy excerpts below are all in the same SmartApp

I have a device handler where I set variables for the current value of a light and dimmer switch, like this:

def doorWindowOpenHandler(evt) {
log.debug “doorWindowOpenHandler called: $evt”

def theOriginalSwitchState = theSwitch.currentSwitch           // save original light switch state
log.debug "The Original Switch State: $theOriginalSwitchState"

def theOriginalDimmerLevel = theDimmerSwitch.currentLevel      // save original dimmer level
log.debug "The Original Dimmer Level: $theOriginalDimmerLevel"

All of the above works fine, I see the appropriate messages with the values in the logs.

However, in my door closed device handler:

def doorWindowClosedHandler(evt) { // wait x seconds, set lights back to previous state
log.debug “doorWindowClosedHandler called: $evt”

log.debug "Setting the Switch On/Off: $theOriginalSwitchState"
log.debug "Setting the dimmerSwitch Level to: $theOriginalDimmerLevel"

}

The above values come out in the logs as nul. How can I retain the values between the handlers?

You defined those variables within the doorWindowOpenHandler method so they can only be used within that method.

Use state.theOriginalSwitchState instead of defining it with “def”

Whenever you post code on the forum you should select it and then click the “</>” toolbar button so people can actually read it…

3 Likes

Spot on, thank you!

For other newbs out there, check out:
https://docs.smartthings.com/en/latest/smartapp-developers-guide/state.html