Ejemplo n.º 1
0
def init():
    conf = load_json(CONFIG_FILE)
    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)
        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity,
                               'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]
    return lights,api
Ejemplo n.º 2
0
    def __init__(self, ip, key):
        folder = os.path.dirname(os.path.abspath('.'))  # noqa
        sys.path.insert(0, os.path.normpath("%s/.." % folder))  # noqa

        conf = load_json(CONFIG_FILE)

        try:
            identity = conf[ip].get("identity")
            psk = conf[ip].get("key")
            api_factory = APIFactory(host=ip, psk_id=identity, psk=psk)
        except KeyError:
            identity = uuid.uuid4().hex
            api_factory = APIFactory(host=ip, psk_id=identity)

            try:
                psk = api_factory.generate_psk(key)
                print("Generated PSK: ", psk)

                conf[ip] = {"identity": identity, "key": psk}
                save_json(CONFIG_FILE, conf)
            except AttributeError:
                raise PytradfriError(
                    "Please provide the 'Security Code' on the "
                    "back of your Tradfri gateway using the "
                    "-K flag."
                )


        self.api = api_factory.request
        self.gateway = Gateway()
        self.updateDevices()
Ejemplo n.º 3
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)
    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    for bulb in lights:
        print(bulb.name)
        observe(api, bulb)
        #print("State: {}".format(bulb.light_control.lights[0].state))
        if args.state == "ON":
            if bulb.light_control.lights[0].state:
                print("The light is already ON")
                logging.warning(
                    'Could not turn on light %s, light was already ON' %
                    (bulb.name))
            else:
                print("The light is OFF, turning it ON")
                api(bulb.light_control.set_state(True))
                logging.info('Turning the light %s ON' % (bulb.name))
        elif args.state == "OFF":
            if not (bulb.light_control.lights[0].state):
                print("The light is already OFF")
                logging.warning(
                    'Could not turn off light %s, light was already OFF' %
                    (bulb.name))
            else:
                print("The light is ON, turning it OFF")
                api(bulb.light_control.set_state(False))
                logging.info('Turning the light %s OFF' % (bulb.name))
Ejemplo n.º 4
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = yield from api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity,
                               'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide your Key")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = yield from api(devices_command)
    devices = yield from api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    rgb = (0, 0, 102)

    # Convert RGB to XYZ using a D50 illuminant.
    xyz = convert_color(sRGBColor(rgb[0], rgb[1], rgb[2]), XYZColor,
                        observer='2', target_illuminant='d65')
    xy = int(xyz.xyz_x), int(xyz.xyz_y)

    #  Assuming lights[3] is a RGB bulb
    xy_command = lights[3].light_control.set_xy_color(xy[0], xy[1])
    yield from api(xy_command)

    #  Assuming lights[3] is a RGB bulb
    xy = lights[3].light_control.lights[0].xy_color

    #  Normalize Z
    Z = int(lights[3].light_control.lights[0].dimmer/254*65535)
    xyZ = xy+(Z,)
    rgb = convert_color(XYZColor(xyZ[0], xyZ[1], xyZ[2]), sRGBColor,
                        observer='2', target_illuminant='d65')
    rgb = (int(rgb.rgb_r), int(rgb.rgb_g), int(rgb.rgb_b))
    print(rgb)

    yield from asyncio.sleep(120)
Ejemplo n.º 5
0
async def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    if lights:
        light = lights[0]
    else:
        print("No lights found!")
        light = None

    def turnOnOff(bulb, state):
        lights[bulb].light_control.set_state(state)

    def setColor(bulb, color):
        lights[bulb].light_control.set_hex_color(color)

    turnOnOff(0, 1)

    await asyncio.sleep(30)

    await api_factory.shutdown()
Ejemplo n.º 6
0
async def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)
    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    # Create API devices -- from example
    api = api_factory.request
    gateway = Gateway()
    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)
    lights = [dev for dev in devices if dev.has_light_control]
    light = None
    # Find a bulb that can set color -- from example
    for dev in lights:
        if dev.light_control.can_set_color:
            light = dev
            break
    if not light:
        print("No color bulbs found")
        return

    # Get auth
    with open("tokens.json") as f:
        js = json.load(f)
        spotify_key = js['spotify']['auth']
        bpm_key = js['bpm']['api_key']

    # Check what procedure to run
    if args.cycle:
        await cycle(light, api)
    elif args.strobe:
        await strobe(light, api)
    elif args.brightness:
        await slider_brightness(light, api)
    print("Run ended.")
    return  # shutdown() throws an error so just exit
async def run() -> None:
    """Run."""
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = await APIFactory.init(host=args.host,
                                            psk_id=identity,
                                            psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = await APIFactory.init(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError as err:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.") from err

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)

    air_purifiers = [dev for dev in devices if dev.has_air_purifier_control]

    # Print all air purifiers
    print(air_purifiers)

    for air_purifier in air_purifiers:
        control = air_purifier.air_purifier_control
        assert control is not None
        print(control.air_purifiers[0].air_quality)
        # Set mode auto
        command = control.turn_on_auto_mode()
        await api(command)

    await api_factory.shutdown()
Ejemplo n.º 8
0
async def run():
    global makestate
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)
    sockets = [dev for dev in devices if dev.has_socket_control]
    for socket in sockets:
        # Print all sockets
        state = (socket.socket_control.sockets[0].state)
        print(socket.name, state, 'naar', makestate)
        state_command = socket.socket_control.set_state(makestate)
        await api(state_command)

    await asyncio.sleep(2)
    print('\n')
    await api_factory.shutdown()
Ejemplo n.º 9
0
def main():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    client = mqtt.Client(userdata={
        "api": api,
        "gateway": gateway,
        'topic': args.topic
    })
    client.username_pw_set(args.user, args.password)
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(args.mqtt_host, 1883, 60)

    client.loop_forever()
Ejemplo n.º 10
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    for light in lights:
        if light.light_control.lights[0].state:
            api(light.light_control.set_state(0))
        else:
            api(light.light_control.set_state(1))
Ejemplo n.º 11
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)

        except AttributeError:
            raise PytradfriError("Please provide your Key")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    light = lights[0]

    observe(api, light)

    # Example 1: checks state of the light (true=on)
    print(light.light_control.lights[0].state)

    # Example 2: get dimmer level of the light
    print(light.light_control.lights[0].dimmer)

    # Example 3: What is the name of the light
    print(light.name)

    # Example 4: Set the light level of the light
    dim_command = light.light_control.set_dimmer(254)
    api(dim_command)

    # Example 5: Change color of the light
    # f5faf6 = cold | f1e0b5 = normal | efd275 = warm
    color_command = light.light_control.set_hex_color('efd275')
    api(color_command)

    tasks_command = gateway.get_smart_tasks()
    tasks_commands = api(tasks_command)
    tasks = api(tasks_commands)

    # Example 6: Return the transition time (in minutes) for task#1
    if tasks:
        print(tasks[0].task_control.tasks[0].transition_time)

        # Example 7: Set the dimmer stop value to 30 for light#1 in task#1
        dim_command_2 = tasks[0].start_action.devices[0].item_controller\
            .set_dimmer(30)
        api(dim_command_2)

    print("Sleeping for 2 min to receive the rest of the observation events")
    print("Try altering the light (%s) in the app, and watch the events!" %
          light.name)
    time.sleep(120)
Ejemplo n.º 12
0
parser = argparse.ArgumentParser()
parser.add_argument('-H',
                    '--hostname',
                    dest='host',
                    required=True,
                    help='IP Address of your Tradfri gateway')
parser.add_argument('-K',
                    '--key',
                    dest='key',
                    required=False,
                    help='Key found on your Tradfri gateway')
args = parser.parse_args()

if Path(CONFIG_FILE).is_file() is False and args.key is None:
    raise PytradfriError("Please provide they key found on your "
                         "Tradfri gateway using the -K flag to this script.")


def observe(api, device):
    def callback(updated_device):
        light = updated_device.light_control.lights[0]
        print("Received message for: %s" % light)

    def err_callback(err):
        print(err)

    def worker():
        api(device.observe(callback, err_callback, duration=120))

    threading.Thread(target=worker, daemon=True).start()
    print('Sleeping to start observation task')
Ejemplo n.º 13
0
async def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = await APIFactory.init(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = await APIFactory.init(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError(
                "Please provide the 'Security Code' on the "
                "back of your Tradfri gateway using the "
                "-K flag."
            )

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    if lights:
        light = lights[0]
    else:
        print("No lights found!")
        light = None

    def observe_callback(updated_device):
        light = updated_device.light_control.lights[0]
        print("Received message for: %s" % light)

    def observe_err_callback(err):
        print("observe error:", err)

    for light in lights:
        observe_command = light.observe(
            observe_callback, observe_err_callback, duration=120
        )
        # Start observation as a second task on the loop.
        asyncio.ensure_future(api(observe_command))
        # Yield to allow observing to start.
        await asyncio.sleep(0)

    if light:
        # Example 1: checks state of the light (true=on)
        print("Is on:", light.light_control.lights[0].state)

        # Example 2: get dimmer level of the light
        print("Dimmer:", light.light_control.lights[0].dimmer)

        # Example 3: What is the name of the light
        print("Name:", light.name)

        # Example 4: Set the light level of the light
        dim_command = light.light_control.set_dimmer(254)
        await api(dim_command)

        # Example 5: Change color of the light
        # f5faf6 = cold | f1e0b5 = normal | efd275 = warm
        color_command = light.light_control.set_hex_color("efd275")
        await api(color_command)

    # Get all blinds
    blinds = [dev for dev in devices if dev.has_blind_control]

    # Print all blinds
    print(blinds)

    if blinds:
        blind = blinds[0]
    else:
        print("No blinds found!")
        blind = None

    if blind:
        blind_command = blinds[0].blind_control.set_state(50)
        await api(blind_command)

    tasks_command = gateway.get_smart_tasks()
    tasks_commands = await api(tasks_command)
    tasks = await api(tasks_commands)

    # Example 6: Return the transition time (in minutes) for task#1
    if tasks:
        print(tasks[0].task_control.tasks[0].transition_time)

        # Example 7: Set the dimmer stop value to 30 for light#1 in task#1
        dim_command_2 = tasks[0].start_action.devices[0].item_controller.set_dimmer(30)
        await api(dim_command_2)

    print("Waiting for observation to end (2 mins)")
    print("Try altering any light in the app, and watch the events!")
    await asyncio.sleep(120)

    await api_factory.shutdown()
Ejemplo n.º 14
0
    "--key",
    dest="key",
    required=False,
    help="Security code found on your Tradfri gateway",
)
args = parser.parse_args()

if args.host not in load_json(CONFIG_FILE) and args.key is None:
    print(
        "Please provide the 'Security Code' on the back of your "
        "Tradfri gateway:",
        end=" ",
    )
    key = input().strip()
    if len(key) != 16:
        raise PytradfriError("Invalid 'Security Code' provided.")
    else:
        args.key = key

conf = load_json(CONFIG_FILE)

try:
    identity = conf[args.host].get("identity")
    psk = conf[args.host].get("key")
    api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
except KeyError:
    identity = uuid.uuid4().hex
    api_factory = APIFactory(host=args.host, psk_id=identity)

    try:
        psk = api_factory.generate_psk(args.key)
Ejemplo n.º 15
0
async def run(shutdown):
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    # end copy/pasted

    #
    # set and regularly renew the commissioning timeout, remove when done
    #
    async def keep_commissioning_alive(readiness):
        try:
            while True:
                await api(gateway.set_commissioning_timeout(60))
                if readiness is not None:
                    readiness()
                readiness = None
                await asyncio.sleep(45)
        finally:
            await api(gateway.set_commissioning_timeout(00))

    commissioning_ready = asyncio.Future()
    commissioning = asyncio.Task(
        keep_commissioning_alive(lambda: commissioning_ready.set_result(None)))

    #
    # monitor the device list and give instructions
    #

    last_devices = None

    def devices_updated(result):
        nonlocal last_devices

        if last_devices is None:
            print("Originally, %s device(s) are known" % len(result))
        else:
            for r in result:
                if r not in last_devices:
                    asyncio.Task(new_device(r))

        last_devices = result

    async def new_device(devno):
        nonlocal commissioning

        print("New device, fetching details...", end="", flush=True)

        device_command = gateway.get_device(devno)
        device = await api(device_command)

        print()

        print("  New device description: %s" % (device, ))

        if commissioning:
            if device.has_light_control:
                print("That was not in the expected sequence: This device was"
                      " a light and not a controller. You can still pair"
                      " another controller device.")
            else:
                print("Found a controller. You can now go ahead and add light"
                      " bulbs by pairing them to the switch as you would do"
                      " without a gateway. Press Ctrl-C when done.")
                commissioning.cancel()
                commissioning = None
                # if you wanted to implemente infinite-commissioning mode, you
                # should cancel or restart keep_commissioning_alive in a way
                # that resets the timeout, because the timeout will have gone
                # to 0 the moment the device was added.
        else:
            if not device.has_light_control:
                print("That was unexpected: A controller showed up even though"
                      " the gateway was not in pairing mode any more.")
            else:
                print("You can still add more light bulbs; press Ctrl-C when"
                      " done.")

    observe_devices = Command('get', [ROOT_DEVICES],
                              observe=True,
                              process_result=devices_updated)
    await api(observe_devices)
    await commissioning_ready

    print("Ready to start: Gateway is in commissioning mode.")
    print("Pressing the pairing button on a switch, dimmer or motion detector"
          " for 10s near the gateway until the gateway blinks fast. A few"
          " seconds later, it the new device shows up here. You may need to"
          " switch off light bulbs in the immediate vicinity (?).")

    #
    # run until the outer loop says not to any more
    #

    await api_factory.shutdown()
    await shutdown

    if commissioning is not None:
        print("Please allow for the commissioning mode to be disabled")
        commissioning.cancel()
Ejemplo n.º 16
0
async def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = await APIFactory.init(host=args.host,
                                            psk_id=identity,
                                            psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = await APIFactory.init(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    rgb = (0, 0, 102)

    # Convert RGB to XYZ using a D50 illuminant.
    xyz = convert_color(
        sRGBColor(rgb[0], rgb[1], rgb[2]),
        XYZColor,
        observer="2",
        target_illuminant="d65",
    )
    xy = int(xyz.xyz_x), int(xyz.xyz_y)

    light = None
    # Find a bulb that can set color
    for dev in lights:
        if dev.light_control.can_set_color:
            light = dev
            break

    if not light:
        print("No color bulbs found")
        return

    xy_command = light.light_control.set_xy_color(xy[0], xy[1])
    await api(xy_command)

    xy = light.light_control.lights[0].xy_color

    #  Normalize Z
    Z = int(light.light_control.lights[0].dimmer / 254 * 65535)
    xyZ = xy + (Z, )
    rgb = convert_color(
        XYZColor(xyZ[0], xyZ[1], xyZ[2]),
        sRGBColor,
        observer="2",
        target_illuminant="d65",
    )
    rgb = (int(rgb.rgb_r), int(rgb.rgb_g), int(rgb.rgb_b))
    print(rgb)

    await asyncio.sleep(120)

    await api_factory.shutdown()
Ejemplo n.º 17
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError(
                "Please provide the 'Security Code' on the "
                "back of your Tradfri gateway using the "
                "-K flag."
            )

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)
    try:
        print(devices)
    except:
        print("Could not retrieve devices")
        return


    lights = [dev for dev in devices if dev.has_light_control]

    print(lights)

    device_names = ["Bord", "Gulvlampe", "Stue", "Klædeskab", "Knagerække", "Dør", "Pendellamper"]

    lamps = {}

    for device in device_names:
        for light in lights:
            if device.lower() in light.name.lower():
                lamps[device] = light
    

    #print(lamps["Stue"].light_control.lights[0].state)
    #api(lamps["Stue"].light_control.set_state(True))
    #api(lamps["Stue"].light_control.set_dimmer(1))
    #api(lamps["Stue"].light_control.set_state(False))
    
    for dev in device_names:
        print(dev, end = '')
        state = lamps[dev].light_control.lights[0].state
        if state == False:
            print(':off ', end = '')
        else:
            print(':',round(lamps[dev].light_control.lights[0].dimmer/254*100, 2), '% ', sep = '', end = '') 
Ejemplo n.º 18
0
async def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)

    blinds = [dev for dev in devices if dev.has_blind_control]
    repeaters = [dev for dev in devices if dev.has_signal_repeater_control]

    # Print all sockets
    print("All blinds")
    print(blinds)

    print("All repeatersK")
    print(repeaters)

    # Sockets can be accessed by its index, so sockets[1] is the second blind
    if blinds:
        blind = blinds[0]
    else:
        print("No sockets found!")
        blind = None

    def observe_callback(updated_device):
        blind = updated_device.blind_control.blinds[0]
        print("Received message for: %s" % blind)

    def observe_err_callback(err):
        print('observe error:', err)

    for blind in blinds:
        observe_command = blind.observe(observe_callback,
                                        observe_err_callback,
                                        duration=120)
        # Start observation as a second task on the loop.
        asyncio.ensure_future(api(observe_command))
        # Yield to allow observing to start.
        await asyncio.sleep(0)

    if blind:
        # Example 1: What is the name of the blind
        print("Name:", blind.name)

        # Example 2: checks current battery level of blind
        print("Battery (%):", blind.device_info.battery_level)

        # Current level of the blind
        print("Battery (%):",
              blinds[0].blind_control.blinds[0].current_cover_position)

        # Example 3: Set blind to 50% open
        state_command = blinds[0].blind_control.set_state(50)
        await api(state_command)

    print("Waiting for observation to end (30 secs)")
    await asyncio.sleep(30)

    await api_factory.shutdown()
Ejemplo n.º 19
0
async def run() -> None:
    """Run process."""
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = await APIFactory.init(host=args.host,
                                            psk_id=identity,
                                            psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = await APIFactory.init(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError as err:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.") from err

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)

    sockets = [dev for dev in devices if dev.has_socket_control]

    # Print all sockets
    print(sockets)

    # Sockets can be accessed by its index, so sockets[1] is the second socket
    if sockets:
        socket = sockets[0]
    else:
        print("No sockets found!")
        socket = None

    def observe_callback(updated_device: ApiResource) -> None:
        assert isinstance(updated_device, Device)
        assert updated_device.socket_control is not None
        socket = updated_device.socket_control.sockets[0]
        print(f"Received message for: {socket}")

    def observe_err_callback(err: Exception) -> None:
        print("observe error:", err)

    for socket in sockets:
        observe_command = socket.observe(observe_callback,
                                         observe_err_callback,
                                         duration=120)
        # Start observation as a second task on the loop.
        asyncio.ensure_future(api(observe_command))
        # Yield to allow observing to start.
        await asyncio.sleep(0)

    if socket:
        assert socket.socket_control is not None
        # Example 1: checks state of the socket (true=on)
        print("Is on:", socket.socket_control.sockets[0].state)

        # Example 2: What is the name of the socket
        print("Name:", socket.name)

        # Example 3: Turn socket on
        state_command = socket.socket_control.set_state(True)
        await api(state_command)

    print("Waiting for observation to end (10 secs)")
    await asyncio.sleep(10)

    await api_factory.shutdown()
Ejemplo n.º 20
0
                    help='IP Address of your Tradfri gateway')
parser.add_argument('-K',
                    '--key',
                    dest='key',
                    required=False,
                    help='Security code found on your Tradfri gateway')
args = parser.parse_args()

if args.host not in load_json(CONFIG_FILE) and args.key is None:
    print(
        "Please provide the 'Security Code' on the back of your "
        "Tradfri gateway:",
        end=" ")
    key = input().strip()
    if len(key) != 16:
        raise PytradfriError("Invalid 'Security Code' provided.")
    else:
        args.key = key


def observe(api, device):
    def callback(updated_device):
        light = updated_device.light_control.lights[0]
        print("Received message for: %s" % light)

    def err_callback(err):
        print(err)

    def worker():
        api(device.observe(callback, err_callback, duration=120))
Ejemplo n.º 21
0
async def run() -> None:
    """Run."""
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = await APIFactory.init(host=args.host,
                                            psk_id=identity,
                                            psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = await APIFactory.init(host=args.host, psk_id=identity)

        try:
            psk = await api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError as err:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.") from err

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = await api(devices_command)
    devices = await api(devices_commands)

    blinds = [dev for dev in devices if dev.has_blind_control]
    repeaters = [dev for dev in devices if dev.has_signal_repeater_control]

    # Print all sockets
    print("All blinds")
    print(blinds)

    print("All repeaters")
    print(repeaters)

    # Blinds can be accessed by their index, so blinds[1] is the second blind
    if blinds:
        blind = blinds[0]
    else:
        print("No blinds found!")
        blind = None

    def observe_callback(updated_device: ApiResource) -> None:
        assert isinstance(updated_device, Device)
        assert updated_device.blind_control is not None
        blind = updated_device.blind_control.blinds[0]
        print(f"Received message for: {blind}")

    def observe_err_callback(err: Exception) -> None:
        print("observe error:", err)

    for blind in blinds:
        observe_command = blind.observe(observe_callback,
                                        observe_err_callback,
                                        duration=120)
        # Start observation as a second task on the loop.
        asyncio.create_task(api(observe_command))
        # Yield to allow observing to start.
        await asyncio.sleep(0)

    if blind:
        # Example 1: What is the name of the blind
        print("Name:", blind.name)

        # Example 2: checks current battery level of blind
        print("Battery (%):", blind.device_info.battery_level)

        blind_control = blind.blind_control
        assert blind_control is not None

        # Current level of the blind
        print("Battery (%):", blind_control.blinds[0].current_cover_position)

        # Example 3: Set blind to 50% open
        state_command = blind_control.set_state(50)
        await api(state_command)

    print("Waiting for observation to end (30 secs)")
    await asyncio.sleep(30)

    await api_factory.shutdown()
Ejemplo n.º 22
0
def save_dict(filename, d):
	json.dump(d, open(filename, 'w'))

def load_dict(filename):
	try:
		return json.load(open(filename, 'r'))
	except FileNotFoundError:
		return {}
	

CONFIG_FILE = '/home/vvdveen/tradfri_standalone_psk.conf'
POWER_STATUS_FILE = '/home/vvdveen/tradfri_power_status.conf'
IP = '10.0.0.109'

if IP not in load_json(CONFIG_FILE):
	raise PytradfriError("Lost Gateway")

conf = load_json(CONFIG_FILE)
try:
	identity = conf[IP].get('identity')
	psk = conf[IP].get('key')
	api_factory = APIFactory(host=IP, psk_id=identity, psk=psk)
except KeyError:
	raise PytradfriError("Lost Gateway")

api = api_factory.request

gateway = Gateway()

devices_command = gateway.get_devices()
devices_commands = api(devices_command)
Ejemplo n.º 23
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get("identity")
        psk = conf[args.host].get("key")
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print("Generated PSK: ", psk)

            conf[args.host] = {"identity": identity, "key": psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError(
                "Please provide the 'Security Code' on the "
                "back of your Tradfri gateway using the "
                "-K flag."
            )

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    if lights:
        light = lights[0]
    else:
        print("No lights found!")
        light = None

    if light:
        observe(api, light)

        # Example 1: checks state of the light (true=on)
        print("State: {}".format(light.light_control.lights[0].state))

        # Example 2: get dimmer level of the light
        print("Dimmer: {}".format(light.light_control.lights[0].dimmer))

        # Example 3: What is the name of the light
        print("Name: {}".format(light.name))

        # Example 4: Set the light level of the light
        dim_command = light.light_control.set_dimmer(254)
        api(dim_command)

        # Example 5: Change color of the light
        # f5faf6 = cold | f1e0b5 = normal | efd275 = warm
        color_command = light.light_control.set_color_temp(250)
        api(color_command)

    # Get all blinds
    blinds = [dev for dev in devices if dev.has_blind_control]

    # Print all blinds
    print(blinds)

    if blinds:
        blind = blinds[0]
    else:
        print("No blinds found!")
        blind = None

    if blind:
        blind_command = blinds[0].blind_control.set_state(50)
        api(blind_command)

    tasks_command = gateway.get_smart_tasks()
    tasks_commands = api(tasks_command)
    tasks = api(tasks_commands)

    # Example 6: Return the transition time (in minutes) for task#1
    if tasks:
        print(tasks[0].task_control.tasks[0].transition_time)

        # Example 7: Set the dimmer stop value to 30 for light#1 in task#1
        dim_command_2 = tasks[0].start_action.devices[0].item_controller.set_dimmer(30)
        api(dim_command_2)

    if light:
        print("Sleeping for 2 min to listen for more observation events")
        print(
            "Try altering the light (%s) in the app, and watch the events!" % light.name
        )
        time.sleep(120)
Ejemplo n.º 24
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    chromecasts = pychromecast.get_chromecasts()
    cast = next(cc for cc in chromecasts
                if cc.device.friendly_name == "Högtalare Kök")
    cast.wait()
    mc = cast.media_controller
    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    #    print(lights)

    #    for light in lights:
    #        observe(api,light)
    #        print("Name: {}".format(light.name) + " Index: {}".format(lights.index(light)))
    #    exit()

    # Lights can be accessed by its index, so lights[1] is the second light
    #    if lights:
    #        light = lights[0]
    #    else:
    #        print("No lights found!")
    #        light = None
    #
    #    if light:
    #        observe(api, light)

    # Example 1: checks state of the light (true=on)
    #        print("State: {}".format(light.light_control.lights[0].state))

    # Example 2: get dimmer level of the light
    #        print("Dimmer: {}".format(light.light_control.lights[0].dimmer))

    # Example 3: What is the name of the light
    #        print("Name: {}".format(light.name))

    # Example 4: Set the light level of the light
    #        dim_command = light.light_control.set_dimmer(254)
    #        api(dim_command)

    # Example 5: Change color of the light
    # f5faf6 = cold | f1e0b5 = normal | efd275 = warm
    #        color_command = light.light_control.set_color_temp(250)
    #        api(color_command)

    msleep = lambda x: time.sleep(x / 1000.0)

    porch = lights[int(halloween['porch']['id'])]
    #    observe(api,light)

    cmd_on = porch.light_control.set_dimmer(254)
    cmd_low = porch.light_control.set_dimmer(20)
    cmd_off = porch.light_control.set_dimmer(00)

    #  xy = light.light_control.lights[0].xy_color
    #print(xy)
    #  (25022, 24884) white
    #  (42926, 21299) red
    xy_white = porch.light_control.set_xy_color(25022, 24884)
    xy_red = porch.light_control.set_xy_color(42926, 21299)

    api(cmd_off)
    mc.play_media('http://172.22.16.7/sound/killer.mp3', 'audio/mpeg')
    mc.block_until_active()
    msleep(1000)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(200)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(200)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(100)
    api(cmd_low)
    msleep(20)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(100)
    api(cmd_on)
    msleep(20)
    api(cmd_low)
    msleep(100)
    api(cmd_on)
    msleep(100)
    api(cmd_off)
    time.sleep(2)
    api(xy_red)
    api(cmd_on)
Ejemplo n.º 25
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = yield from api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = yield from api(devices_command)
    devices = yield from api(devices_commands)

    sockets = [dev for dev in devices if dev.has_socket_control]

    # Print all sockets
    print(sockets)

    # Sockets can be accessed by its index, so sockets[1] is the second socket
    if sockets:
        socket = sockets[0]
    else:
        print("No sockets found!")
        socket = None

    def observe_callback(updated_device):
        socket = updated_device.socket_control.sockets[0]
        print("Received message for: %s" % socket)

    def observe_err_callback(err):
        print('observe error:', err)

    for socket in sockets:
        observe_command = socket.observe(observe_callback,
                                         observe_err_callback,
                                         duration=120)
        # Start observation as a second task on the loop.
        ensure_future(api(observe_command))
        # Yield to allow observing to start.
        yield from asyncio.sleep(0)

    if socket:
        # Example 1: checks state of the socket (true=on)
        print("Is on:", socket.socket_control.sockets[0].state)

        # Example 2: What is the name of the socket
        print("Name:", socket.name)

        # Example 3: Turn socket on
        state_command = socket.socket_control.set_state(True)
        yield from api(state_command)

    print("Waiting for observation to end (10 secs)")
    yield from asyncio.sleep(10)
Ejemplo n.º 26
0
                    help='IP Address of your Tradfri gateway')
parser.add_argument('-K',
                    '--key',
                    dest='key',
                    required=False,
                    help='Security code found on your Tradfri gateway')
args = parser.parse_args()

if args.host not in load_json(CONFIG_FILE) and args.key is None:
    print(
        "Please provide the 'Security Code' on the back of your "
        "Tradfri gateway:",
        end=" ")
    key = input().strip()
    if len(key) != 16:
        raise PytradfriError("'Security Code' has to be exactly" +
                             "16 characters long.")
    else:
        args.key = key

conf = load_json(CONFIG_FILE)

try:
    identity = conf[args.host].get('identity')
    psk = conf[args.host].get('key')
    api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
except KeyError:
    identity = uuid.uuid4().hex
    api_factory = APIFactory(host=args.host, psk_id=identity)

    try:
        psk = api_factory.generate_psk(args.key)
Ejemplo n.º 27
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[args.host].get('identity')
        psk = conf[args.host].get('key')
        api_factory = APIFactory(host=args.host, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=args.host, psk_id=identity)

        try:
            psk = api_factory.generate_psk(args.key)
            print('Generated PSK: ', psk)

            conf[args.host] = {'identity': identity, 'key': psk}
            save_json(CONFIG_FILE, conf)
        except AttributeError:
            raise PytradfriError("Please provide the 'Security Code' on the "
                                 "back of your Tradfri gateway using the "
                                 "-K flag.")

    api = api_factory.request

    gateway = Gateway()

    devices_command = gateway.get_devices()
    devices_commands = api(devices_command)
    devices = api(devices_commands)

    lights = [dev for dev in devices if dev.has_light_control]

    # Print all lights
    print(lights)

    # Lights can be accessed by its index, so lights[1] is the second light
    if lights:
        light = lights[0]
    else:
        print("No lights found!")
        light = None

    if light:
        light_command = [
            light.light_control.set_dimmer(0),
            light.light_control.set_dimmer(64),
            light.light_control.set_dimmer(128),
            light.light_control.set_dimmer(192),
            light.light_control.set_dimmer(254)
        ]
        dark_command = light.light_control.set_dimmer(0)
        api(dark_command)

        with PiCamera() as camera:
            # Configure camera
            camera.resolution = (1640, 922)  # Full Frame, 16:9 (Camera v2)
            camera.start_preview()

            # Do inference on VisionBonnet
            with CameraInference(face_detection.model()) as inference:
                for result in inference.run():
                    facecount = len(face_detection.get_faces(result))
                    if facecount >= 1:
                        if facecount > 4:
                            facecount = 4
                        print('I see you')
                        api(light_command[facecount])
                        time.sleep(5)
                        api(dark_command)