Example #1
0
async def main():
    async with aiohttp.ClientSession() as session:
        api = pysmartthings.SmartThings(session, config.token)
        devices = await api.devices()
        for device in devices:
            print(device.name)
            await device.status.refresh()
            if (device.status.switch):
                resp = requests.post(url=config.light_url,
                                     json={"ids": config.light_ids})
Example #2
0
async def trigger_action():
    async with aiohttp.ClientSession() as session:
        api = pysmartthings.SmartThings(session, smart_things['access-token'])
        result = await api.scenes()
        assert result
        for scene in result:
            for requested_scene in actions['Action']['SmartThings']['PowerOn']:
                if scene.scene_id in requested_scene['SceneID']:
                    result = await scene.execute()
                    logging.info("executed scene: " + scene.name)
Example #3
0
async def turn_off_light():
    async with aiohttp.ClientSession() as session:
        try:
            api = pysmartthings.SmartThings(session, smart_things_token)
            devices = await api.devices(device_ids=config.device_ids)
            light = devices[0]
            result = await light.command("switch", "off")
            assert result
        except Exception as err:
            logging.warning("Unable to toggle light: " + err)
Example #4
0
async def print_devices():
    async with aiohttp.ClientSession() as session:
        api = pysmartthings.SmartThings(session, token)
        locations = await api.locations()
        for l in locations:
            if 'Olive' == l.name:
                print(l.location_id)

        devices = await api.devices()
        for d in devices:
            print(d.label)
Example #5
0
async def control(token):
    async with aiohttp.ClientSession() as session:
        api = pysmartthings.SmartThings(session,token)
        devices = await api.devices()
        for device in devices:
            if device.label == device_name:
                await device.status.refresh()
                state = device.status.values['switch']
                if state == 'on':
                    await device.command("main","switch","off")
                if state == 'off':
                    await device.command("main","switch","on")
Example #6
0
    async def _execute(self, device_id: str, capability: str, command,
                       component_id: str, args: Optional[list]):
        import pysmartthings

        async with aiohttp.ClientSession(timeout=self._timeout) as session:
            api = pysmartthings.SmartThings(session, self._access_token)
            device = await api.device(device_id)
            ret = await device.command(component_id=component_id,
                                       capability=capability,
                                       command=command,
                                       args=args)

        assert ret, 'The command {capability}={command} failed on device {device}'.format(
            capability=capability, command=command, device=device_id)
Example #7
0
async def main(api_token):
    global gauge_electricity, gauge_gas

    async with aiohttp.ClientSession() as session:
        api = pysmartthings.SmartThings(session, api_token)
        device = await get_device(api)
        if device is None:
            print("Can't find energy monitor device")
            return

        gas_reading = None
        electricity_reading = None

        print("Connected, running...")
        while True:
            with refresh_time.time():
                await device.status.refresh()

            new_electricity = device.status.values.get("energy")
            if valid_reading(new_electricity, electricity_reading):
                electricity_reading = new_electricity
            else:
                print(
                    f"Invalid electricity reading: {new_electricity} (previous:"
                    f" {electricity_reading})")

            new_gas = device.status.values.get("gasMeter")
            if valid_reading(new_gas, gas_reading):
                gas_reading = new_gas
            else:
                print(
                    f"Invalid gas reading: {new_gas} (previous: {gas_reading})"
                )

            if electricity_reading:
                if gauge_electricity is None:
                    gauge_electricity = Gauge("bulb_electricity_used_kwh",
                                              "Electricity meter reading")
                gauge_electricity.set(electricity_reading)

            if gas_reading:
                if gauge_gas is None:
                    gauge_gas = Gauge("bulb_gas_used_units",
                                      "Gas meter reading")
                gauge_gas.set(gas_reading)

            await asyncio.sleep(10)
Example #8
0
        async def _toggle() -> bool:
            async with aiohttp.ClientSession(timeout=self._timeout) as session:
                api = pysmartthings.SmartThings(session, self._access_token)
                dev = await api.device(device_id)
                assert 'switch' in dev.capabilities, 'The device {} has no switch capability'.format(
                    dev.label)

                await dev.status.refresh()
                state = 'off' if dev.status.switch else 'on'
                ret = await dev.command(component_id='main',
                                        capability='switch',
                                        command=state,
                                        args=args)

            assert ret, 'The command switch={state} failed on device {device}'.format(
                state=state, device=dev.label)
            return not dev.status.switch
Example #9
0
async def run():
    async with aiohttp.ClientSession() as session:
        api = pysmartthings.SmartThings(session, token)

        devices = await api.devices()
        device = devices[0]

        if sys.argv[1] == "--off":
            result = await device.switch_off()

        if sys.argv[1] == "--on":
            result = await device.switch_on()

        if sys.argv[1] == "--vol-up":
            result = await device.volume_up()

        if sys.argv[1] == "--vol-down":
            result = await device.volume_down()
Example #10
0
    async def _refresh_info(self):
        import pysmartthings

        async with aiohttp.ClientSession(timeout=self._timeout) as session:
            api = pysmartthings.SmartThings(session, self._access_token)
            tasks = [
                asyncio.ensure_future(self._refresh_locations(api)),
                asyncio.ensure_future(self._refresh_devices(api)),
            ]

            await asyncio.gather(*tasks)

            room_tasks = [
                asyncio.ensure_future(
                    self._refresh_rooms(api, location.location_id))
                for location in self._locations
            ]

            await asyncio.gather(*room_tasks)
async def print_devices():
    async with aiohttp.ClientSession() as session:
        print("Open session")
        api = pysmartthings.SmartThings(session, token)
        print("Opened session")
        devices = await api.devices()
        locations = await api.locations()
        print(len(locations))
        for device in devices:
            print("{}: {}".format(device.device_id, device.label))
            await device.status.refresh()
            print(device.status.values)
            print("")
            print("")
            print(device.status.switch)
            print("")
            print("")
            print(device.status.level)
            print("")
            print("")
Example #12
0
async def main():
    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)

        devices = await api.devices()
        print(len(devices))
        for device in devices:
            if device.device_id == "a7460f7e-52d0-45c6-bd9b-b0b54cba2983":
                print(device.name)
                print(device.label)
                print(device.capabilities)
                await device.status.refresh()
                print(device.status.values)
                print(device.status.switch)
                print(device.status.level)
Example #13
0
    async def _refresh_status(self, devices: List[str]) -> List[dict]:
        import pysmartthings

        device_ids = []
        missing_device_ids = set()

        def parse_device_id(device):
            device_id = None
            if device in self._devices_by_id:
                device_id = device
                device_ids.append(device_id)
            elif device in self._devices_by_name:
                device_id = self._devices_by_name[device].device_id
                device_ids.append(device_id)
            else:
                missing_device_ids.add(device)

            if device_id and device in missing_device_ids:
                missing_device_ids.remove(device)

        for dev in devices:
            parse_device_id(dev)

        # Fail if some devices haven't been found after refreshing
        assert not missing_device_ids, 'Could not find the following devices: {}'.format(
            list(missing_device_ids))

        async with aiohttp.ClientSession(timeout=self._timeout) as session:
            api = pysmartthings.SmartThings(session, self._access_token)
            status_tasks = [
                asyncio.ensure_future(self._get_device_status(api, device_id))
                for device_id in device_ids
            ]

            # noinspection PyTypeChecker
            return await asyncio.gather(*status_tasks)
Example #14
0
async def main(api_token):
    global gauge_electricity, gauge_gas, lastReadingElec, lastReadingGas
    global startOfDayElect, startOfDayGas, currentDayElect, currentDayGas

    async with aiohttp.ClientSession() as session:
        api = pysmartthings.SmartThings(session, api_token)
        device = await get_device(api)
        if device is None:
            print("Can't find energy monitor device")
            return

        gas_reading = None
        electricity_reading = None

        print("Connected, running...")
        while True:

            await device.status.refresh()
            #print(device.status.values)
            new_electricity = device.status.values.get("energy")
            if valid_reading(new_electricity, electricity_reading):
                electricity_reading = new_electricity
            else:
                print(
                    f"Invalid electricity reading: {new_electricity} (previous:"
                    f" {electricity_reading})")

            new_gas = device.status.values.get("gasMeter")
            if valid_reading(new_gas, gas_reading):
                gas_reading = new_gas
            else:
                print(
                    f"Invalid gas reading: {new_gas} (previous: {gas_reading})"
                )

            if electricity_reading:
                #print("electricity_reading: " + str(electricity_reading))

                # if we are a new day, then reset the daily
                curDay = datetime.datetime.now().date().day
                if curDay != currentDayElect:
                    startOfDayElect = electricity_reading
                    currentDayElect = curDay

                # calculate the daily usage
                daily_reading = electricity_reading - startOfDayElect

                client.publish("energy/electricity_daily",
                               round(daily_reading, 2))

                if lastReadingElec != None:

                    diff = electricity_reading - lastReadingElec
                    # we want to convert it to KWhours, this is a bit "fake"
                    # because its not really over an hour, it more a cause that if
                    # the increate happened over an hour, this is how much it would be.
                    client.publish("energy/electricity", int(diff * 1000 * 60))

                lastReadingElec = electricity_reading

            if gas_reading:
                #print("gas_reading: "+str(gas_reading))

                # if we are a new day, then reset the daily
                curDay = datetime.datetime.now().date().day
                if curDay != currentDayGas:
                    startOfDayGas = gas_reading
                    currentDayGas = curDay

                # calculate the daily usage
                daily_reading = gas_reading - startOfDayGas

                client.publish("energy/gas_daily", round(daily_reading, 2))

                if lastReadingGas != None:

                    diff = gas_reading - lastReadingGas

                    client.publish("energy/gas", int(diff * 1000 * 60))

                lastReadingGas = gas_reading

            dict_file = {}
            dict_file["lastReadingElec"] = lastReadingElec
            dict_file["lastReadingGas"] = lastReadingGas
            dict_file["measurementPeriod"] = measurementPeriod
            dict_file["startOfDayElect"] = startOfDayElect
            dict_file["currentDayElect"] = currentDayElect
            dict_file["startOfDayGas"] = startOfDayGas
            dict_file["currentDayGas"] = currentDayGas

            with open(saveFile, 'w') as file:
                documents = yaml.dump(dict_file, file)

            await asyncio.sleep(measurementPeriod * 60)