Referencing devices as a list?

Hi,

I have the following problem: I have a list of switches that I need to iterate, this list is a subset of all the switches with the capability.switch that I have available. I have tried to define this list with:

def list = [switch1, switch2, ... ]

But the list is not accepted and I get a runtime error. I also tried declaring the list as a strings list:

def list = ["switch1", "switch2", ... ]

But I cannot reference this strings as devices. So, my questions are:

  • Is it possible to define a list of devices by their input device name?
  • Is it possible to obtain the reference to a device from the input device name as a string?

Thanks!

Could you give a few more details? Are you getting the Switches from an input() statement in SmartApp Preferences?

There is no way to fetch Devices based on their names. They need to be authorized explicitly by the user via Preferences pages (i.e., the input statements), which gives you handles to their object instances.

1 Like

Hi tgauchat,

Thank you for the question. As a more detailed explanation, in my apartment I have several areas, on each area I have a set of switches. On my app, for each area I have an input where I can select the switches involved for each area.

At certain point, in a callback function triggered by a sensor, I need to turn off the switches of all the areas except for one area. Therefore, I could hardcode this for each possible case but that implies a nightmare if I need to do a change on the future (e.g.: I get more sensors :stuck_out_tongue:). My “elegant” solution is to iterate on a list of areas and apply the on()/off() according to the input names.

I have been able to work out an array in the shape of def list = [switch1, switch2, ... ] where switchN correspond to the input name at the configuration, but to work it needs to be declared inside de function that is going to use it. If I declare it outside a function (parallel to the other functions) I get a runtime error (the array arrives as NULL inside the functions).

With this inside function array implementation, I have some level of better code maintenance because in case of a change I’ll need to update all the arrays in all the functions and that is better that the need of repairing all the hardcoded on()/off(); nevertheless, I imagine it should be more efficient ways of maintaining this code by declaring a Global array with my input labels that I can use on all my functions.

P.S.: I still do not understand why we are not provided a “getDeviceBy[some_attribute]” function. The only option is to implement a very inefficient method were you iterate over everything to find something that matches!!!

1 Like

SmartThings does not let you define your own variables in it’s “SmartApp Sandbox”.

You can use the provided global map: state[] … Look it up in the Developer Documentation. It has some quirks though.

2 Likes