Пример #1
0
def run(args):
    # Assign configuration variables.
    id=-1
    level=-1
    args.pop(0)
    ip=args.pop(0)
    if args:
        id = int(args.pop(0))
    if args:
        level=int(args.pop(0))

    conf=load_json(CONFFILE)
    if not conf:
        print("Could not load {}:".format(CONFFILE))
        print("pre-shared-key (generated by gateway device) needed: see example_sync.py")
        return

    identity=conf[ip].get('identity')
    psk=conf[ip].get('key')
    api = APIFactory(host=ip,psk_id=identity,psk=psk).request
    gateway = Gateway()

    devices = api(api(gateway.get_devices()))
    lights = [Switchable(api,gateway,dev) for dev in devices if dev.has_light_control or dev.has_socket_control]

    if id<0:
        # Print all lights
        for l in lights:
            print(l.reprline())
        return

    ids = [l.id for l in lights]
    if not id in ids:
        print("id not found ({} lights)".format(len(lights)))
        return

    i=ids.index(id);
    light=lights[i]

    prelevel=light.leveltext
    light.set_level(level)
    light.update()
    print("{} -> {}".format(prelevel,light.leveltext))
Пример #2
0
def connect():
	print("connect")
	global conf
	global api_factory	
	global lights
	global groups
	global api
	try:
		identity = conf[ip_host].get('identity')
		psk = conf[ip_host].get('key')
		api_factory = APIFactory(host=ip_host, psk_id=identity, psk=psk)
	except KeyError:
		identity = uuid.uuid4().hex
		api_factory = APIFactory(host=ip_host, psk_id=identity)

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

			conf[ip_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()

	#get all devices
	devices_command = gateway.get_devices()
	devices_commands = api(devices_command)
	devices = api(devices_commands)
	# create list of available bulbs
	lamps = [dev for dev in devices if dev.has_light_control]

	# get all available groups
	groups_command = gateway.get_groups()
	groups_commands = api(groups_command)
	groupc = api(groups_commands)
	groups = [dev for dev in groupc]
	
	lights = [dev for dev in devices if dev.has_light_control]
Пример #3
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    api_factory = APIFactory(sys.argv[1])
    with open('gateway_psk.txt', 'a+') as file:
        file.seek(0)
        psk = file.read()
        if psk:
            api_factory.psk = psk.strip()
        else:
            psk = yield from api_factory.generate_psk(sys.argv[2])
            print('Generated PSK: ', psk)
            file.write(psk)
    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]

    # Print all lights
    print(lights)

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

    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.
        ensure_future(api(observe_command))
        # Yield to allow observing to start.
        yield from asyncio.sleep(0)

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

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

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

    # Example 4: Set the light level of light 0
    dim_command = light.light_control.set_dimmer(255)
    yield from api(dim_command)

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

    tasks_command = gateway.get_smart_tasks()
    tasks_commands = yield from api(tasks_command)
    tasks = yield from 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)
        yield from api(dim_command_2)

    print("Waiting for observation to end (2 mins)")
    print("Try altering any light in the app, and watch the events!")
    yield from asyncio.sleep(120)
Пример #4
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()
Пример #5
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]

    # Print all lights
    print(lights)

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

    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.
        ensure_future(api(observe_command))
        # Yield to allow observing to start.
        yield from asyncio.sleep(0)

    # 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)
    yield from 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')
    yield from api(color_command)

    tasks_command = gateway.get_smart_tasks()
    tasks_commands = yield from api(tasks_command)
    tasks = yield from 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)
        yield from api(dim_command_2)

    print("Waiting for observation to end (2 mins)")
    print("Try altering any light in the app, and watch the events!")
    yield from asyncio.sleep(120)
Пример #6
0
async def async_setup_entry(
    hass: HomeAssistant,
    entry: ConfigEntry,
) -> bool:
    """Create a gateway."""
    tradfri_data: dict[str, Any] = {}
    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = tradfri_data
    listeners = tradfri_data[LISTENERS] = []

    factory = await APIFactory.init(
        entry.data[CONF_HOST],
        psk_id=entry.data[CONF_IDENTITY],
        psk=entry.data[CONF_KEY],
    )
    tradfri_data[FACTORY] = factory  # Used for async_unload_entry

    async def on_hass_stop(event: Event) -> None:
        """Close connection when hass stops."""
        await factory.shutdown()

    # Setup listeners
    listeners.append(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop))

    api = factory.request
    gateway = Gateway()
    groups: list[Group] = []

    try:
        gateway_info = await api(gateway.get_gateway_info(),
                                 timeout=TIMEOUT_API)
        devices_commands: Command = await api(gateway.get_devices(),
                                              timeout=TIMEOUT_API)
        devices: list[Device] = await api(devices_commands,
                                          timeout=TIMEOUT_API)

        if entry.data[CONF_IMPORT_GROUPS]:
            # Note: we should update this page when deprecating:
            # https://www.home-assistant.io/integrations/tradfri/
            _LOGGER.warning(
                "Importing of Tradfri groups has been deprecated due to stability issues "
                "and will be removed in Home Assistant core 2022.4")
            # No need to load groups if the user hasn't requested it
            groups_commands: Command = await api(gateway.get_groups(),
                                                 timeout=TIMEOUT_API)
            groups = await api(groups_commands, timeout=TIMEOUT_API)

    except RequestError as exc:
        await factory.shutdown()
        raise ConfigEntryNotReady from exc

    dev_reg = await hass.helpers.device_registry.async_get_registry()
    dev_reg.async_get_or_create(
        config_entry_id=entry.entry_id,
        connections=set(),
        identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])},
        manufacturer=ATTR_TRADFRI_MANUFACTURER,
        name=ATTR_TRADFRI_GATEWAY,
        # They just have 1 gateway model. Type is not exposed yet.
        model=ATTR_TRADFRI_GATEWAY_MODEL,
        sw_version=gateway_info.firmware_version,
    )

    remove_stale_devices(hass, entry, devices)

    # Setup the device coordinators
    coordinator_data = {
        CONF_GATEWAY_ID: gateway,
        KEY_API: api,
        COORDINATOR_LIST: [],
        GROUPS_LIST: [],
    }

    for device in devices:
        coordinator = TradfriDeviceDataUpdateCoordinator(hass=hass,
                                                         api=api,
                                                         device=device)
        await coordinator.async_config_entry_first_refresh()

        entry.async_on_unload(
            async_dispatcher_connect(hass, SIGNAL_GW,
                                     coordinator.set_hub_available))
        coordinator_data[COORDINATOR_LIST].append(coordinator)

    for group in groups:
        group_coordinator = TradfriGroupDataUpdateCoordinator(hass=hass,
                                                              api=api,
                                                              group=group)
        await group_coordinator.async_config_entry_first_refresh()
        entry.async_on_unload(
            async_dispatcher_connect(hass, SIGNAL_GW,
                                     group_coordinator.set_hub_available))
        coordinator_data[GROUPS_LIST].append(group_coordinator)

    tradfri_data[COORDINATOR] = coordinator_data

    async def async_keep_alive(now: datetime) -> None:
        if hass.is_stopping:
            return

        gw_status = True
        try:
            await api(gateway.get_gateway_info())
        except RequestError:
            _LOGGER.error("Keep-alive failed")
            gw_status = False

        async_dispatcher_send(hass, SIGNAL_GW, gw_status)

    listeners.append(
        async_track_time_interval(hass, async_keep_alive,
                                  timedelta(seconds=60)))

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Пример #7
0
def get_sockets():
    api = get_api()
    gateway = Gateway()

    devices = api(api(gateway.get_devices()))
    return [dev for dev in devices if dev.has_socket_control]
Пример #8
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Create a gateway."""
    # host, identity, key, allow_tradfri_groups
    tradfri_data: dict[str, Any] = {}
    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = tradfri_data
    listeners = tradfri_data[LISTENERS] = []

    factory = await APIFactory.init(
        entry.data[CONF_HOST],
        psk_id=entry.data[CONF_IDENTITY],
        psk=entry.data[CONF_KEY],
    )

    async def on_hass_stop(event: Event) -> None:
        """Close connection when hass stops."""
        await factory.shutdown()

    listeners.append(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, on_hass_stop))

    api = factory.request
    gateway = Gateway()

    try:
        gateway_info = await api(gateway.get_gateway_info())
        devices_commands = await api(gateway.get_devices())
        devices = await api(devices_commands)
        groups_commands = await api(gateway.get_groups())
        groups = await api(groups_commands)
    except RequestError as err:
        await factory.shutdown()
        raise ConfigEntryNotReady from err

    tradfri_data[KEY_API] = api
    tradfri_data[FACTORY] = factory
    tradfri_data[DEVICES] = devices
    tradfri_data[GROUPS] = groups

    dev_reg = await hass.helpers.device_registry.async_get_registry()
    dev_reg.async_get_or_create(
        config_entry_id=entry.entry_id,
        connections=set(),
        identifiers={(DOMAIN, entry.data[CONF_GATEWAY_ID])},
        manufacturer=ATTR_TRADFRI_MANUFACTURER,
        name=ATTR_TRADFRI_GATEWAY,
        # They just have 1 gateway model. Type is not exposed yet.
        model=ATTR_TRADFRI_GATEWAY_MODEL,
        sw_version=gateway_info.firmware_version,
    )

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    async def async_keep_alive(now: datetime) -> None:
        if hass.is_stopping:
            return

        try:
            await api(gateway.get_gateway_info())
        except RequestError:
            _LOGGER.error("Keep-alive failed")

    listeners.append(
        async_track_time_interval(hass, async_keep_alive,
                                  timedelta(seconds=60)))

    return True
Пример #9
0
def run():
    # Assign configuration variables.
    # The configuration check takes care they are present.
    api_factory = APIFactory(sys.argv[1])
    with open('gateway_psk.txt', 'a+') as file:
        file.seek(0)
        psk = file.read()
        if psk:
            api_factory.psk = psk.strip()
        else:
            psk = api_factory.generate_psk(sys.argv[2])
            print('Generated PSK: ', psk)
            file.write(psk)
    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 2 (true=on)
    print(light.light_control.lights[0].state)

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

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

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

    # Example 5: Change color of light 2
    # 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)
Пример #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]
    porch = lights[int(halloween['porch']['id'])]
    # Print all lights
    #    print(lights)

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

    # 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)

    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_on)
    api(xy_white)
Пример #11
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]

    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()
Пример #12
0
async def run():

    conf = load_json(CONFIG_FILE)

    try:
        identity = conf[HOST].get('identity')
        psk = conf[HOST].get('key')
        ip = conf[HOST].get('ip')
        disp_time = conf[HOST].get('dipslay time')
        logging_level = conf[HOST].get('logging level')
        light_order = conf[HOST].get('light order')
        api_factory = APIFactory(host=ip, psk_id=identity, psk=psk)
    except KeyError:
        identity = uuid.uuid4().hex
        api_factory = APIFactory(host=ip, psk_id=identity)

    if logging_level > 5 or logging_level < 0:
        logging_level = 3

    logging.basicConfig(format="%(asctime)s %(message)s",
                        level=logging_level * 10)
    api = api_factory.request
    gateway = Gateway()

    #wait for network while booting
    while True:
        try:
            devices_command = gateway.get_devices()
            devices_command = await api(devices_command)
            break
        except:
            pass
        await asyncio.sleep(2)

    devices = await api(devices_command)
    lights = [dev for dev in devices if dev.has_light_control]

    for x in lights:
        logging.info(f"{x.path[1]}")

    oled = display(len(lights), disp_time)

    lights_sortet = []
    for x in lights:
        lights_sortet.append(x)

    for idx, x in enumerate(lights):
        lights_sortet[Sort_Light(lights[idx].path[1], light_order)] = x

    for x in lights_sortet:
        logging.info(f"{x.path[1]}")

    def observe_callback(updated_device):
        light = updated_device.light_control.lights[0]
        for i, x in enumerate(lights_sortet):
            if x.light_control.lights[0].device.name == light.device.name:
                print(light.device.name)
                oled.set_status(i, light.state, light.dimmer,
                                updated_device.name)
                # oled.update()
                # oled.show_details(i, updated_device.name)
        logging.info("Received message for: %s" % light)

    def observe_err_callback(err):
        logging.error('observe error:', err)

    if lights:
        light = lights[0]
    else:
        logging.warning("No lights found!")
        light = None

    for light in lights:
        observe_command = light.observe(observe_callback, observe_err_callback)
        # 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)

    for x in range(0, len(lights_sortet)):
        if lights_sortet[x].light_control.lights[0].state == 0:
            oled.set_status(x, 0, 0, lights_sortet[x].name)
        else:
            oled.set_status(x, 1,
                            lights_sortet[x].light_control.lights[0].dimmer,
                            lights_sortet[x].name)

    oled.update()

    logging.info('obsevering startet')
    while True:
        oled.controler()
        await asyncio.sleep(0.01)
    await api_factory.shutdown()
Пример #13
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
    light = lights[3]

    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_color_temp(250)
    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)
Пример #14
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)

    lights = [dev for dev in devices if dev.has_light_control]
    
    #insert lights in the arrays
    for light in lights:
        lightArrayId.append(light.id)
        lightArraySts.append(light.light_control.lights[0].state)
        lightArrayValue.append(light.light_control.lights[0].dimmer)
        lightArrayColor.append(get_color_temp_idx(light.light_control.lights[0].hex_color))        
    
    savelights()
	
    # 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]
        output("Received message for: %s" % light)
        light = updated_device
        x = get_index(light.id, lightArrayId)
        lightArraySts[x] = light.light_control.lights[0].state
        lightArrayValue[x] = light.light_control.lights[0].dimmer
        lightArrayColor[x] = get_color_temp_idx(light.light_control.lights[0].hex_color)
        savelights()

    def observe_err_callback(err):
        output('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.
        ensure_future(api(observe_command))
        # Yield to allow observing to start.
        yield from asyncio.sleep(0)

    print("Waiting for observation to end (2 mins)")
    print("Try altering any light in the app, and watch the events!")
    while True:
	    print("restart")
	    yield from asyncio.sleep(10)
Пример #15
0
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)
devices = api(devices_commands)
lights = [ dev for dev in devices if dev.has_light_control ]
print("Gateway reports {} lights".format(len(lights)))

unreachable_count = load_dict(POWER_STATUS_FILE)
print("Database reports {} lights".format(len(unreachable_count)))

if len(unreachable_count) != len(lights):
	unreachable_count = {}

	for light in lights:
		unreachable_count[light.name] = 0

	save_dict(POWER_STATUS_FILE, unreachable_count)
Пример #16
0
class TradfriManager(metaclass=Singleton):

    api_factory = None
    api = None
    gateway = None
    enabled = False
    initialized = False
    last_init = 0

    def __init__(self):
        self.tradfri_state = TradfriState()
        self.observing_end = 0
        self.observing = False
        self.observe_thread = None

    def init(self):
        if self.initialized:
            Logger().write(LogVerbosity.Info, "already init")
            return

        if sys.platform != "linux" and sys.platform != "linux2":
            Logger().write(LogVerbosity.Info, "Lighting: Not initializing, no coap client available on windows")
            self.initialized = True
            self.tradfri_state.update_group(DeviceGroup(1, "Test group", True, 128, 6))
            self.tradfri_state.update_group(DeviceGroup(2, "Test group 2", False, 18, 6))
            return

        if current_time() - self.last_init < 5000:
            Logger().write(LogVerbosity.Info, "Tried initialization less than 5s ago")
            return

        Logger().write(LogVerbosity.All, "Start LightManager init")
        self.enabled = True
        if not self.initialized:
            ip = Settings.get_string("tradfri_hub_ip")
            identity = Database().get_stat_string("LightingId")
            key = Database().get_stat_string("LightingKey")

            if identity is None or key is None:
                Logger().write(LogVerbosity.Info, "Lighting: No identity/key found, going to generate new")
                # We don't have all information to connect, reset and start from scratch
                Database().remove_stat("LightingId")
                Database().remove_stat("LightingKey")
                key = None

                identity = uuid.uuid4().hex
                Database().update_stat("LightingId", identity)  # Generate and save a new id
                self.api_factory = APIFactory(host=ip, psk_id=identity)
            else:
                self.api_factory = APIFactory(host=ip, psk_id=identity, psk=key)

            self.api = self.api_factory.request
            self.gateway = Gateway()

            if key is None:
                try:
                    security_code = SecureSettings.get_string("tradfri_hub_code")  # the code at the bottom of the hub
                    key = self.api_factory.generate_psk(security_code)
                    Database().update_stat("LightingKey", key)  # Save the new key
                    Logger().write(LogVerbosity.Info, "Lighting: New key retrieved")
                except Exception as e:
                    Logger().write_error(e, "Unhandled exception")
                    return
            else:
                Logger().write(LogVerbosity.Info, "Lighting: Previously saved key found")

            try:
                self.initialized = True
                groups = self.get_device_groups()
                for group in groups:
                    self.tradfri_state.update_group(group)
            except Exception as e:
                Logger().write(LogVerbosity.Info, "Failed to init tradfri, clearing previous key to try generate new")
                self.initialized = False
                Database().remove_stat("LightingId")
                Database().remove_stat("LightingKey")
                Logger().write_error(e, "Failed to get groups from hub")

    def start_observing(self):
        Logger().write(LogVerbosity.Debug, "Start observing light data")
        self.observing = True
        if self.observing_end > current_time():
            Logger().write(LogVerbosity.All, "Still observing, not starting again")
            return  # still observing, the check observing thread will renew

        if not self.check_state():
            return

        self.observing_end = current_time() + 30000
        groups_commands = self.api(self.gateway.get_groups())
        result = self.api(groups_commands)
        for group in result:
            self.observe_group(group)

    def observe_group(self, group):
        Logger().write(LogVerbosity.All, "Starting observe for group " + group.name)
        self.observe_thread = CustomThread(lambda: self.api(group.observe(
            self.tradfri_state.update_group,
            lambda x: self.check_observe(group), duration=30)), "Light group observer", [])
        self.observe_thread.start()

    def check_observe(self, group):
        if self.observing:
            # Restart observing since it timed out
            Logger().write(LogVerbosity.Debug, "Restarting observing for group " + str(group.name))
            self.observe_group(group)

    def stop_observing(self):
        Logger().write(LogVerbosity.Debug, "Stop observing light data")
        self.observing = False

    def get_devices(self):
        if not self.check_state():
            return []

        Logger().write(LogVerbosity.All, "Get devices")
        devices_commands = self.api(self.gateway.get_devices())
        devices = self.api(devices_commands)
        return [d for d in [self.parse_device(x) for x in devices] if d is not None]

    def set_state(self, device_id, state):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set device state")
        device = self.api(self.gateway.get_device(device_id))
        if device.has_light_control:
            self.api(device.light_control.set_state(state))
        else:
            self.api(device.socket_control.set_state(state))

    def set_light_warmth(self, device_id, warmth):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set light warmth")
        device = self.api(self.gateway.get_device(device_id))
        self.api(device.light_control.set_color_temp(warmth))

    def set_light_dimmer(self, device_id, amount):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set light dimmer")
        device = self.api(self.gateway.get_device(device_id))
        self.api(device.light_control.set_dimmer(amount))

    def set_device_name(self, device_id, name):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set device name")
        device = self.api(self.gateway.get_device(device_id))
        self.api(device.set_name(name))

    def get_device_groups(self):
        if not self.check_state():
            return []

        Logger().write(LogVerbosity.All, "Get device groups")
        groups_commands = self.api(self.gateway.get_groups())
        result = self.api(groups_commands)
        Logger().write(LogVerbosity.All, "Get device groups: " + str([x.raw for x in result]))
        return [DeviceGroup(group.id, group.name, group.state, group.dimmer, len(group.member_ids)) for group in result]

    def get_devices_in_group(self, group):
        if not self.check_state():
            return []

        Logger().write(LogVerbosity.All, "Get lights in group")
        group = self.api(self.gateway.get_group(group))
        members = group.member_ids
        result = [self.api(self.gateway.get_device(x)) for x in members]
        return [d for d in [self.parse_device(x) for x in result] if d is not None]

    def set_group_name(self, group, name):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set group name")
        group = self.api(self.gateway.get_group(group))
        self.api(group.set_name(name))

    def set_group_state(self, group, state):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set group state")
        group = self.api(self.gateway.get_group(group))
        self.api(group.set_state(state))

    def set_group_dimmer(self, group, dimmer):
        if not self.check_state():
            return

        Logger().write(LogVerbosity.All, "Set group dimmer")
        group = self.api(self.gateway.get_group(group))
        self.api(group.set_dimmer(dimmer))

    def check_state(self):
        if not self.enabled:
            return False  # not available

        if not self.initialized:
            self.init()
            if not self.initialized:
                return False  # init failed
        return True

    @staticmethod
    def parse_device(data):
        if data.has_light_control:
            lights = []
            for light in data.light_control.lights:
                lights.append(LightDevice(
                    light.state,
                    light.dimmer,
                    light.color_temp,
                    light.hex_color))

            return LightControl(data.id,
                                data.name,
                                data.application_type,
                                data.last_seen.timestamp(),
                                data.reachable,
                                data.light_control.can_set_dimmer,
                                data.light_control.can_set_temp,
                                data.light_control.can_set_color,
                                lights)

        elif data.has_socket_control:
            sockets = []
            for socket in data.socket_control.sockets:
                sockets.append(SocketDevice(socket.state))

            return SocketControl(data.id, data.name, data.application_type, data.last_seen.timestamp(), data.reachable, sockets)
Пример #17
0
class Hub(object):
    def __init__(self, graph, ip, key):
        self.graph = graph
        self.ip, self.key = ip, key
        self.api = APIFactory(ip, psk=key)
        self.gateway = Gateway()

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

        self.ctx = ROOM['tradfriHub']
        self.graph.patch(Patch(
            addQuads=[(s,p,o,self.ctx) for s,p,o in self.deviceStatements()]))

        self.curStmts = []

        task.LoopingCall(self.updateCur).start(60)
        for dev in self.devices:
            self.startObserve(dev)
            
    def startObserve(self, dev):
        def onUpdate(dev):
            reactor.callFromThread(self.updateCur, dev)
        def onErr(err):
            log.warn('%r; restart observe on %r', err, dev)
            reactor.callLater(1, self.startObserve, dev)
        reactor.callInThread(self.api.request, dev.observe(onUpdate, onErr))

    def description(self):
        return {
            'uri': 'huburi',
            'devices': [{
                'uri': devUri(dev),
                'className': self.__class__.__name__,
                'pinNumber': None,
                'outputPatterns': [(devUri(dev), ROOM['brightness'], None)],
                'watchPrefixes': [],
                'outputWidgets': [{
                    'element': 'output-slider',
                    'min': 0, 'max': 1, 'step': 1 / 255,
                    'subj': devUri(dev),
                    'pred': ROOM['brightness'],
                }] * dev.has_light_control,
            } for dev in self.devices],
            'graph': 'http://sticker:9059/graph', #todo
        }
        
    def updateCur(self, dev=None):
        cur = [(s,p,o,self.ctx) for s,p,o in
               self.currentStateStatements([dev] if dev else self.devices)]
        self.graph.patch(Patch(addQuads=cur, delQuads=self.curStmts))
        self.curStmts = cur
                
    def deviceStatements(self):
        for dev in self.devices:
            uri = devUri(dev)
            yield (uri, RDF.type, ROOM['IkeaDevice'])
            yield (uri, ROOM['ikeaId'], Literal(dev.id))
            if dev.last_seen:
                utcSeen = dev.last_seen
                yield (uri, ROOM['lastSeen'],
                       Literal(utcSeen.replace(tzinfo=tzutc()).astimezone(tzlocal())))
                yield (uri, ROOM['reachable'], ROOM['yes'] if dev.reachable else ROOM['no'])
            yield (uri, RDFS.label, Literal(dev.name))
            # no connection between remotes and lights?
            
    def currentStateStatements(self, devs):
        for dev in self.devices:  # could scan just devs, but the Patch line needs a fix
            uri = devUri(dev)
            di = dev.device_info
            if di.battery_level is not None:
                yield (uri, ROOM['batteryLevel'], Literal(di.battery_level / 100))
            if dev.has_light_control:
                lc = dev.light_control
                #import ipdb;ipdb.set_trace()

                lightUri = devUri(dev)
                print lc.raw
                if not lc.raw[0][ATTR_LIGHT_STATE]:
                    level = 0
                else:
                    level = lc.raw[0][ATTR_LIGHT_DIMMER] / 255
                yield (lightUri, ROOM['brightness'], Literal(level))
                #if light.hex_color:
                #    yield (lightUri, ROOM['kelvinColor'], Literal(light.kelvin_color))
                #    yield (lightUri, ROOM['color'], Literal('#%s' % light.hex_color))
            

    def outputStatements(self, stmts):
        for stmt in stmts:
            for dev in self.devices:
                uri = devUri(dev)
                if stmt[0] == uri:
                    if stmt[1] == ROOM['brightness']:
                        try:
                            self.api.request(dev.light_control.set_dimmer(
                                int(255 * float(stmt[2])), transition_time=3))
                        except:
                            traceback.print_exc()
                            raise
        self.updateCur()
Пример #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 = 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)

    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.
        asyncio.ensure_future(api(observe_command))
        # Yield to allow observing to start.
        await 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)
        await api(state_command)

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

    await api_factory.shutdown()
Пример #19
0
		conf[ip_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.")


def outputq(x):
	print(str(datetime.datetime.now().time())[:8] + " "+ str(x))
	sys.stdout.flush()
	
api = api_factory.request

gateway = Gateway()

#get all devices
devices_command = gateway.get_devices()
devices_commands = api(devices_command)
devices = api(devices_commands)
# create list of available bulbs
lamps = [dev for dev in devices if dev.has_light_control]

# get all available groups
groups_command = gateway.get_groups()
groups_commands = api(groups_command)
groupc = api(groups_commands)
groups = [dev for dev in groupc]
	
lights = [dev for dev in devices if dev.has_light_control]
#-------------------------------------------------------------------
	
# supported_features 1=mono 23=color
Пример #20
0
class LightApi:

    LIGHT_TIMEOUT = 10
    DEFAULT_CONFIG_PATH = "config/lights.conf"

    def __init__(self):
        pass

    async def set_lights(self, states):
        async def set_light(state):
            light = self.find(state["id"])
            if "color_temp" in state:
                await self.set_temperature(light, state["color_temp"])
            if "dimmer" in state:
                await self.set_brightness(light, state["dimmer"])
            if "state" in state:
                await self.set_state(light, state["state"])

        tasks = [set_light(s) for s in states]
        await asyncio.wait(tasks, timeout=LightApi.LIGHT_TIMEOUT)

    async def set_brightness(self, light, level):
        command = light.light_control.set_dimmer(level)
        await self.api(command)

    async def set_temperature(self, light, mired=None):
        min_mired = light.light_control.min_mireds
        max_mired = light.light_control.max_mireds
        if mired is None:
            mired = max_mired
        if min_mired > mired:
            mired = min_mired
        if max_mired < mired:
            mired = max_mired
        command = light.light_control.set_color_temp(mired)
        await self.api(command)

    async def set_state(self, light, state):
        command = light.light_control.set_state(state)
        await self.api(command)

    def get_lights(self):
        def light_stats(light):
            return {
                "name": light.name,
                "id": light.id,
                "color_temp": light.light_control.lights[0].color_temp,
                "dimmer": light.light_control.lights[0].dimmer,
                "state": light.light_control.lights[0].state,
                "can_set_color": light.light_control.can_set_color,
                "can_set_dimmer": light.light_control.can_set_dimmer,
                "can_set_temp": light.light_control.can_set_temp,
                "can_set_xy": light.light_control.can_set_xy,
                "min_mireds": light.light_control.min_mireds,
                "min_hue": light.light_control.min_hue,
                "min_saturation": light.light_control.min_saturation,
                "max_mireds": light.light_control.max_mireds,
                "max_hue": light.light_control.max_hue,
                "max_saturation": light.light_control.max_saturation,
            }

        return [light_stats(l) for l in self.lights]

    def get_config(self, config_path=None):
        config = None
        if config_path is None:
            config_path = LightApi.DEFAULT_CONFIG_PATH
        if os.path.isfile(config_path):
            with open(config_path) as f:
                config = json.load(f)
        return config

    def find(self, id):
        for light in self.lights:
            if light.id == id:
                return light
        return None

    async def create_api_factory(self, config_path):
        config = self.get_config(config_path)
        if config is None:
            assert "GATEWAY_IP" in os.environ and "GATEWAY_KEY" in os.environ, "Gateway IP or key missing"
            host = os.environ["GATEWAY_IP"]
            key = os.environ["GATEWAY_KEY"]
            identity = uuid.uuid4().hex
            api_factory = APIFactory(host=host, psk_id=identity)
            psk = await api_factory.generate_psk(key)
            config = {
                "host": host,
                "psk_id": identity,
                "psk": psk,
            }
            self.save_config(config, config_path)
        else:
            api_factory = APIFactory(host=config["host"],
                                     psk_id=config["psk_id"],
                                     psk=config["psk"])
        return api_factory

    def save_config(self, config, config_path=None):
        if config_path is None:
            config_path = LightApi.DEFAULT_CONFIG_PATH
        with open(config_path, "w") as f:
            json.dump(config, f)

    async def _async_init(self, config_path):
        self.api_factory = await self.create_api_factory(config_path)
        self.api = self.api_factory.request
        self.gateway = Gateway()
        self.devices_command = self.gateway.get_devices()
        self.devices_commands = await self.api(self.devices_command)
        self.devices = await self.api(self.devices_commands)
        self.lights = [dev for dev in self.devices if dev.has_light_control]
Пример #21
0
 def get_lights(api):
     gateway = TradfriGateway()
     devices_command = gateway.get_devices()
     devices_commands = api(devices_command)
     devices = api(devices_commands)
     return [dev for dev in devices if dev.has_light_control]
Пример #22
0
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 = 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 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 = 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)

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

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

        # Example 3: What is the name of the light
        print(f"Name: {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:
        assert blind.blind_control is not None
        blind_command = blind.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:
        task = tasks[0]
    else:
        print("No tasks found!")
        task = None

    if task:
        task_control_tasks = task.task_control.tasks
        if task_control_tasks:
            task_control_task = task_control_tasks[0]
            print(task_control_task.transition_time)

            # Example 7: Set the dimmer stop value to 30 for light#1 in task#1
            dim_command_2 = task_control_task.item_controller.set_dimmer(30)
            api(dim_command_2)

    if light:
        print("Sleeping for 2 min to listen for more observation events")
        print(
            f"Try altering the light ({light.name}) in the app, and watch the events!"
        )
        time.sleep(120)