This is probably an easy question, sorry, I’m new to Groovy.
I have a list of switches that I want to turn on and off, but ONLY if they’re not already on. My code currently supports just ONE switch, and has just ONE state (for that switch). For example, my state could be set to:
state.myState = "ready"
This works great. I was wondering if there was a way to dynamically include a GUID of a switch in the state, so when an event come in, it would look something like this:
state.$evt.GUID.myState = "ready"
I realize this is probably incorrect syntax, but it illustrates that I want to not count the switches, or enumerate them, but rather just include a unique ID in the State object. This way, all my switches would simply work by just adding info from the event itself directly in the state variable reference.
Would something like this be possible in Groovy? Hope that made sense
mySwitches.each {
if(it.currentSwitch != "on") { do whatever it is you want to do}
}
There is no need to keep anything in a state variable. If you have some deeper issue going on, please describe in more detail. It is possible to create a name for an input algorithmically, and later in your code retrieve it algorithmically, but I’m not sure that’s what you’re talking about.
Thanks Bruce. I do need state variables as I turn on the switch for 5 minutes, then back off. If it was already “on” due to another 5 minute interval, it should extend the period another 5 minutes. If the user turns the switch off and back on manually, the switch now cancels the timer and stays on. Anyway, that’s besides the point. Trust me, I need the state variables.
I’m updating my app “Smart Light Timer,…” which was published a long time ago.
P.S. I know I could obviously loop through my switches in the INI, create a key/value map based on each ID, and look up the state object from that map each time. So I can certainly code all this.
My question really is if it’s possible to add the state, somewhat like my pseudo code above, to a dynamically named object. That way, it makes my code super clean, I don’t have to do lookups, and life is good…
If by that you mean a dynamically made up name for a state variable, I don’t think so. I’m not aware of any ability to create dynamic state variable names. It is possible to create dynamic (at install time) device and input variable names, and recall them later using a dynamic method.
So you can get creative with that in mind. Note that I’m not able to test that with the actual state object object right now, but that works for maps (which is basically what state is).
But, if you do something like you posted:
That’s actually going to traverse the map structure, assuming that evt has a GUID property, which in turn has a myState property, etc.
My advice is to start super simple, get it working, then try and get fancy/cute later. Also, when it comes to Groovy, I find the Groovy console, or even the Web Groovy Console to be handy for trying out Groovy things quickly.