Any way to use persistent data from within Handlers?

From within a Smart App, you can store persistent data as “state.xxx”, and reuse it from one activation of the Smart App to the next.
I would like to do the same from within a custom Handler, recalling stored values from one activation of the Handler to the next.
But all my attempts using either state.xxx or settings.yyy have failed, each new activation of the Handller restarting from a null value.

Am I doing something wrong, or is it just plain impossible ?

You can declare a custom attribute and store arbitrary data there. You may have to convert your data to string (e.g. json) if you want to store structured data.

metadata {
    definition (name: ..... ) {
        attribute "myState", "string"
    }
}

// Save state
sendEvent(name:"myState", value:"My persistent state", displayed:false)

// Read state
def state = device.currentValue("myState")
1 Like

Thanks a lot, that was quick, I will try that :slight_smile:

state.xxx does work in device handlers, can you post example code showing how you tried to use it?

I tried :

> def parse(String description) {
>     state.parseCount = ++1
>     log.debug "Parsing... ; state.parseCount: ${state.parseCount}"
>     ...
> } 

but it always returned the same (2 ?!) value on consecutive commands :

06:14:37: debug Parsing... ; state.parseCount: 2
06:14:36: debug Parsing... ; state.parseCount: 2
06:14:11: debug Parsing... ; state.parseCount: 2
06:14:10: debug Parsing... ; state.parseCount: 2

What did I do wrong ?

Your code does what it’s supposed to do and not what you’ve intended to. I think you meant

state.parseCount += 1

You are right, what I meant was actually :

 state.parseCount++

Unfortunately, those two :

 state.parseCount += 1
 state.parseCount++

give the exact same result (= 2) as my initial (and faulty)

state.parseCount = ++1

BUT this one works ! :

state.parseCount = state.parseCount + 1

Don’t ask me why (Java is not my native language), but as long as it works…
Thanks to both of you :smile:

Now that I have found the persistent data, I have kind of the opposite problem : is there a way to detect from within a Handler that the Handler for the Device (the one owning state.xxx attributes) has just been updated ?
Something like a time stamp of the last Device’s handler update.

EDIT : found the solution ! :smile:
the updated() function does also work from within Handlers, as well as in Smart Apps !