spidertyler2005

smartyThingy.py

Apr 30th, 2020
332
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.94 KB | None | 0 0
  1. #!usr/bin/python3
  2.  
  3. #A small Module that makes connecting to SmartThings easier for us
  4.  
  5. import aiohttp
  6. import asyncio
  7. import pysmartthings
  8.  
  9. #gets the api session using TOKEN
  10. async def getApi(TOKEN,SESSION):
  11.     api = None
  12.     api = pysmartthings.SmartThings(SESSION,TOKEN)
  13.     if not api == None:
  14.         return api
  15.  
  16. #gets All Locations
  17. async def getLocations(api):
  18.     locations = await api.locations()
  19.     return locations
  20.  
  21. #gets all the Devices
  22. async def getDevices(api):
  23.     devices = await api.devices()
  24.     return devices
  25.  
  26. #getsDeviceByName
  27. async def getDeviceByName(devices, name):
  28.     for device in devices:
  29.         dname = device.label
  30.         if dname != name:
  31.             continue
  32.         else:
  33.             print(dname)
  34.             return device
  35.        
  36.  
  37. #toggles the switch
  38. async def toggleSwitch(device):
  39.     await device.status.refresh()
  40.     status = device.status.switch
  41.     print(status)
  42.     if status:
  43.         result = await device.switch_off()
  44.         assert result == True
  45.     else:
  46.         result = await device.switch_on()
  47.         assert result == True
  48.  
  49. #Function only runs if __name__ == "__main__".
  50. #You must have the following code in all files using this module!
  51. async def run(loop):
  52.     api = await getApi(token,session)
  53.     locations = await getLocations(api)
  54.     devices = await getDevices(api)
  55.     closet = await getDeviceByName(devices,"Print Light")
  56.     print(f" \r\r\n\n{api} \n\r connected to SmartThings! \r\n {locations} \r\n Recieved all locations \r\n Receieved all Devices")
  57.     print("------------------------------------- \r\n")
  58.  
  59.     await toggleSwitch(closet)
  60.     await session.close() #have in all files!
  61.     return None
  62.  
  63. if __name__ == "__main__":
  64.     #have the following code in all files using this module
  65.     token = "TOKEN THAT HAS BEEN REMOVED FOR SECURITY"
  66.     session= aiohttp.ClientSession()
  67.     loop = asyncio.get_event_loop()
  68.     loop.run_until_complete(run(loop))
Add Comment
Please, Sign In to add comment