pythonsmartthings

How to get all locations connected to a SmartThings account using Python?


How to get the name of all location you have connected to your SmartThings account using Python with the pysmartthings libary?

I tryed this code from the documentation to the libary :

import aiohttp
import pysmartthings

token = 'PERSONAL_ACCESS_TOKEN'

async with aiohttp.ClientSession() as session:
    api = pysmartthings.SmartThings(session, token)
    locations = await api.locations()
    print(len(locations))

    location = locations[0]
    print(location.name)
    print(location.location_id)

but i got this error : SyntaxError: 'async with' outside async function then i tryed a code from youtube :

import aiohttp
import pysmartthings

token = 'PERSONAL_ACCESS_TOKEN'

async def get_locations():
    try:
        async with aiohttp.ClientSession() as session:
            api = pysmartthings.SmartThings(session, token)
            locations = await api.locations()
            for location in locations:
                print(location.name)
                print(location.location_id)
    except Exception as e:
        print("An error occurred:", e)

but got no output.


Solution

  • There are a few things missing.. With code snippet 2: The one is that you have defined a function and don't call it.. Try adding some simple 'print statements' to help find out what is happening. You can read up on the 'asyncio' at https://superfastpython.com/asyncio-coroutine-was-never-awaited/

    Remember functionality is limited by the operations permitted by the token