Device Array in Custom App

I have a custom app. A preference is set for multiple devices. If several devices are selected they are put into an array. I know, or it appears so, that the device position in the array doesn't follow any particular order.

Question, will the array position always remain constant as long as I don't change any entries in the preference?

Also, can a state variable be an array? ie state.item[...].

Yes, it will remain the same.

Yes, state objects can be of any type. You will need to "initialize" it so that it's clearly an array, like this:

state.myArray = []

Then you can use List operations on it (List is Groovy name for array), such as adding to it, indexing an element, etc.

You can put a Map in state also, with the same need to initialize, like this:

state.myMap = [:]

While the above is certainly true (look who answered!), the fact that you're asking about order makes me nervous. :slight_smile: Is there a reason you need to rely on that? If you need to match something for a device up with itself somehow, even if the collection changes, I'd use the device ID (or maybe something else that makes senses for your application).

So I defined it as : state.motion=

Then I have a routine to initial it as follows:
def motionReset(evt) {
sensor?.each {
state.motion[it] = false
}
}

But that gives me an error. I was under the impression that the 'it' was a array position, but apparently not???

I was monitoring some motion detectors to make sure they are seeing some activity, mainly cause some of them don't report battery correctly. I currently just create a separte routine to monitor each one. But everytime I add one I have to create a new routine. Was just trying to make it easier by storing a state, true or false, and then once every few days do a check. Thought it would be easier to iterate thru them rather than create a new routine every time.

In this case, the .each is giving you a device, and you can't use a device as an array index. What you could do is something like this:

int i = 0
sensor.each {
    state.motion[i] = false
    i++
}

Note that you don't need the protecting ? when using .each, as .each won't blow up on null, just does nothing.

1 Like

Got it working. Thanks.