Device Driver: Running a method only once after each Hub reset or boot

I wish to set my measurement (temperature) Maximum and Minimum to the current value on each startup.
The runonce method requires a specific time so I want to use the below "if (!state.initialized)...

My question is:
Can I rely on the state.initialized variable which at this point is undefined, to be recognized as not being "true" ?

It doesn't cause a "save" error but I'll have rethink the remaining code if this is not the case.


def parse(String description){

    if (!state.initialized) runIn(125, resetMaxMin, [overwrite: true])   // <--------
    if (logEnable) "  Raw Description=  $description"

    if (description?.startsWith('read attr -')){        // in testing all messages are 'read attr -''

        def descMap = zigbee.parseDescriptionAsMap(description)
        if (logEnable) ("   descMap=  $descMap")

def resetMaxMin(){
	state.initialized = true
	schedule("0 58 23 1/1 * ? *", resetMaxMin)    // execute handlerMethod every day at 23:58.

	state.Max = SensorValue
	state.Min = SensorValue


The state map persists through reboots (and code saves, etc.), so I'm not sure if you have some way to "un-initialize" things on reboot that is not in your snippet above. If not, it won't cause errors, but I also don't see how the initialization/reset thing will "know" to run.

(This is assuming by "startup" you mean hub system startup/boot. I can't imagine that you're referring to sleep/wake cycles of your app or driver itself given that the entire purpose of state is to persist across these executions, but I suppose that's worth mentioning, too. :smiley: )

If my hunch is correct, you may be interested to know that initialize() will run at system start for any driver that has such a method and specifies capability "Initialize". So, perhaps you could reset values there and/or call runIn() from there to schedule whatever re-initialization later? But perhaps there is something I do not understand about your use case.



I wasn't sure Initialize ran automatically, since it had a tile on the device page. This will work great.


1 Like