maximvelichko / pyvera

A python library to control devices via the Vera hub
GNU General Public License v2.0
26 stars 30 forks source link

How to find switch by name? #83

Closed 172pilot closed 6 years ago

172pilot commented 6 years ago

Sorry - This isn't a problem with pyvera necessarily, but I haven't found any code examples or detailed docs to help me figure this out.. (my Python Newbie status is showing)..

The short version is that I need to find a device (switch for this example) by name, because I dont trust that devices[4] for example, would always return the same device, especially if I add/delete devices from my Vera.

So - using the example code on this site, I do:

controller = pyvera.VeraController("http://192.168.1.185:3480/") devices = controller.get_devices('On/Off Switch') devices and I get:

devices [VeraSwitch (id=6 category=On/Off Switch name=Kitchen Lights), VeraSwitch (id=31 category=On/Off Switch name=Porch light), VeraSwitch (id=64 category=On/Off Switch name=Pool pump), VeraSwitch (id=173 category=On/Off Switch name=Turtle Filter), VeraSwitch (id=174 category=On/Off Switch name=Christmas Lights)]

devices[1] is the Porch light, but I dont want to hardcode that in my python code because if I ever deleted kitchen lights, then the porch light would presumably become devices[0]..

In Powershell, I'd do something like: $dev=$Devices | where {$_.name -eq "Porch Light"} to return just the object in the list that I could then use the .is_switched_on() and other functions, but I can't figure out the python equivalent. I've tried to read substrings, etc.. but everything is giving me an error that seems to be related to the "VeraSwitch" type not being compatible with the string routines..

Where am I going wrong? Does someone have some simple example code or let me know where I'm going wrong? Even better - Is there a good forum for users of pyvera? I feel like this is NOT the place for such discussions, but I dont know where else to go.

Thanks in advance!! Steve

pavoni commented 6 years ago

Take a look at list comprehensions in python. The devices returned are python objects - so it's the attributes you want to look at (eg name). So you'll want something like

>>> mirror = [d for d in devices if d.name == "Bathroom mirror"][0]
>>> mirror
VeraSwitch (id=64 category=On/Off Switch name=Bathroom mirror)

pyvera isn't really documented - but you can see the VeraObject code here https://github.com/pavoni/pyvera/blob/d539f91f16f5d891f2fe8d53c45701c137907d40/pyvera/__init__.py#L262 which should give you some idea about the methods and atrributes.

172pilot commented 6 years ago

Thank you so much - That works great, and I think I understand the code.. I have more questions, but it's better served by a python forum than pyvera now that I know the terminology to use.

Thanks for putting up with my generic python support question!!