Groovy: Get Device object by Name/Label

Given just the label of say a switch, how do I get the device object.
for example:

def devLbl = "Garage Switch"
def devObj = getDevice(devLbl )
devObj.on()

Are you trying to do this from a custom driver or a custom app?

You can only get a device reference if the device is a child of you (device or app) or if a specific list of device(s) was selected in a selector drop-down (app).

If it's a child of your app or driver, you can use getChildDevices() and then iterate over them as needed using accessors from the Device Object.

If it is from your app but not a direct child device, you can use the capability selector as shown in the Hubitat examples, like this one. Then you can use the Device Object methods as before.

2 Likes

You answered this as well as another question I had not even posted yet. I was trying to use childApp=getChildDevice(theChildID) in one app and it always returned a null. The same function worked fine in an other app (which created the device) Spent hours trying to figure this out until I read your post :blush:

1 Like