I’m working on my first SmartApp and I’m new to Groovy, so this is a neophyte question.
My app associates pairs of virtual switches with physical doors, and rather than create a separate event handler for each individual device, I have, generic handlers that figure out which door or switch is being handled and changes something in the associated door/switch. Here’s an example:
def onHandler(evt)
{
log.debug "Handler caught ON request from virtual Switch: $evt.device"
def map = [
(switch1 ? switch1.id : "") : door1,
(switch2 ? switch2.id : "") : door2,
(switch3 ? switch3.id : "") : door3,
(switch4 ? switch4.id : "") : door4,
]
def d = map.get(evt.device.id, null)
if (d)
{
log.debug "Opening door $d in response to switch ${evt.device}"
d.open()
}
}
I’d like to not need to create the map on each callback, but persist it in the app. Based on a recommendation on another thread, I tried putting it in state. That, unfortunately, quickly caused a crash. I can’t paste the exact error because Live Logging is broken for me right now. It was a rather vague and terse exception, and my guess is that I can’t put device references into state.
The docs say:
You can use state to store strings, numbers, lists, booleans, maps, etc
It’s the etc that I’m wondering about. It also mentions:
State is stored in JSON format; for most data types this works fine, but for more complex object types this may cause issues.
My guess is that may cause issues means might crash.
So, I can’t store devices into state. The obvious question is, what can I store? Presumably, any POD is fine, such as device IDs. But if I store device IDs, how do I retrieve a device from its ID? It seems like somewhere there should be a map of all devices by ID.
Am I missing something, or am I going about this wrong?