How to get current device state during event handler?

Hi Guys,

Is it possible to get current state of a device during eventHandler?

example code:

def eventHandler(evt) {
    def battery = evt.device.currentState('battery')
    log.debug "get battery current state '${battery}'"
}

Yes, but not like that.

subscribe(battery1, “capability.battery”, batteryEventHandler)

batteryEventHandler(evt){
log.debug “${evt.displayName} ${evt.name} ${evt.value}”
}
These values would be current as they triggered the handler

1 Like

Yes, I know we can get battery value by using that.

but can we get Battery state during capability.contact?

example code

subscribe(contact, "capability.contact", eventHandler)

    def eventHandler(evt) {
        def battery = evt.device.currentState('battery')
        log.debug "get battery current state '${battery}'"

        def temperature = evt.device.currentState('temperature')
        log.debug "get temperature current state '${temperature}'"
    }

As you can see below, the device’s Battery current state is 63%.
Since we know which device trigger the event, so I supposed we should be able to get that device’s current state as well right?

I got it :smile:

evt.device.currentState(“battery”).stringValue

actually I’m almost there, only left .stringValue :blush:

1 Like

You can check if a device supports a given attribute using the hasAttribute() method.

Then you can get its string representation like you are, using the stringValue.

So you could do:

if (evt.device?.hasAttribute("battery")) {
   def currentBatteryAsString = evt.device.currentState("battery").stringValue
}

Fair warning, I haven’t tested that, but I think it should work. :slight_smile:

1 Like

Yeah, I was just thinking what if the value is null.
Thanks Jim :smile: