Example #1
0
    def configuration_callback(callback_data):
        """Handle the submitted configuration."""
        try:
            from pytradfri.api.aiocoap_api import APIFactory
        except ImportError:
            _LOGGER.exception("Looks like something isn't installed!")
            return

        api_factory = APIFactory(host, psk_id=GATEWAY_IDENTITY)
        psk = yield from api_factory.generate_psk(callback_data.get('key'))
        res = yield from _setup_gateway(hass, config, host, psk,
                                        DEFAULT_ALLOW_TRADFRI_GROUPS)

        if not res:
            hass.async_add_job(configurator.notify_errors, instance,
                               "Unable to connect.")
            return

        def success():
            """Set up was successful."""
            conf = _read_config(hass)
            conf[host] = {'key': psk}
            _write_config(hass, conf)
            hass.async_add_job(configurator.request_done, instance)

        hass.async_add_job(success)
Example #2
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)
Example #3
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()
Example #4
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
Example #5
0
def run_pytradfri():
    api_factory = APIFactory('192.168.1.123', 'myUserName',
                             'password123456789')
    api = api_factory.request

    gateway = Gateway()

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

    groups_command = gateway.get_groups()
    groups_commands = yield from api(groups_command)
    groups = yield from api(groups_commands)

    for device in devices:
        observe_command = device.observe(observe_device_callback, observe_err_callback, duration=0)
        # Start observation as a second task on the loop.
        ensure_future(api(observe_command))
        yield from asyncio.sleep(0)

    for group in groups:
        observe_command = group.observe(observe_group_callback, observe_err_callback, duration=0)
        # Start observation as a second task on the loop.
        ensure_future(api(observe_command))
        yield from asyncio.sleep(0)

    # Sleep in an infinite loop to keep this running but also allow other tasks to execute
    while True:
        yield from asyncio.sleep(1)
Example #6
0
async def get_gateway_info(hass, host, identity, key):
    """Return info for the gateway."""
    from pytradfri.api.aiocoap_api import APIFactory
    from pytradfri import Gateway, RequestError

    try:
        factory = APIFactory(
            host,
            psk_id=identity,
            psk=key,
            loop=hass.loop
        )

        api = factory.request
        gateway = Gateway()
        gateway_info_result = await api(gateway.get_gateway_info())

        await factory.shutdown()
    except (OSError, RequestError):
        # We're also catching OSError as PyTradfri doesn't catch that one yet
        # Upstream PR: https://github.com/ggravlingen/pytradfri/pull/189
        raise AuthError('cannot_connect')

    return {
        CONF_HOST: host,
        CONF_IDENTITY: identity,
        CONF_KEY: key,
        CONF_GATEWAY_ID: gateway_info_result.id,
    }
Example #7
0
async def tradfri_get_api_device(device_id):
    api_factory = APIFactory(host=GATEWAY_IP,
                             psk_id=GATEWAY_ID,
                             psk=GATEWAY_PSK)
    api = api_factory.request
    gateway = Gateway()
    device = await api(gateway.get_device(device_id))
    return api, device
Example #8
0
async def connect_to_gateway(hostConfig):

    api_factory = APIFactory(hostConfig["Gateway"], hostConfig["Identity"],
                             hostConfig["Passkey"])
    api = api_factory.request
    gateway = Gateway()

    return api, gateway, api_factory
Example #9
0
async def load_api(host, key):
    conf = load_config()
    if host in conf:
        logging.info('PSK from config file')
        identity = conf[host].get('identity')
        psk = conf[host].get('key')
        return APIFactory(host=host, psk_id=identity, psk=psk)
    else:
        return await initialize_api_connection(host, key)
Example #10
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()
Example #11
0
async def test_request_returns_list(monkeypatch):
    monkeypatch.setattr('aiocoap.Context.create_client_context',
                        mock_create_context)

    api = APIFactory('127.0.0.1').request

    command = Command('', '')

    response = await api([command, command, command])

    assert type(response) == list
Example #12
0
def test_request_returns_single(monkeypatch):
    monkeypatch.setattr('aiocoap.Context.create_client_context',
                        mock_create_context)

    api = APIFactory('127.0.0.1').request

    command = Command('', '')

    response = yield from api(command)

    assert type(response) != list
Example #13
0
async def async_setup_entry(hass, entry):
    """Create a gateway."""
    # host, identity, key, allow_tradfri_groups
    from pytradfri import Gateway, RequestError  # pylint: disable=import-error
    from pytradfri.api.aiocoap_api import APIFactory

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

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

    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())
    except RequestError:
        _LOGGER.error("Tradfri setup failed.")
        return False

    hass.data.setdefault(KEY_API, {})[entry.entry_id] = api
    hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway

    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="IKEA",
        name="Gateway",
        # They just have 1 gateway model. Type is not exposed yet.
        model="E1526",
        sw_version=gateway_info.firmware_version,
    )

    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(entry, "light")
    )
    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(entry, "sensor")
    )
    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(entry, "switch")
    )

    return True
Example #14
0
 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
Example #15
0
async def async_setup_entry(hass, entry):
    """Create a gateway."""
    # host, identity, key, allow_tradfri_groups

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

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

    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())
    except RequestError:
        await factory.shutdown()
        raise ConfigEntryNotReady

    hass.data.setdefault(KEY_API, {})[entry.entry_id] = api
    hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway

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

    for device in TRADFRI_DEVICE_TYPES:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, device))

    async def keepalive():
        while True:
            await api(gateway.get_gateway_info())
            await asyncio.sleep(45)

    asyncio.ensure_future(keepalive(), loop=asyncio.get_event_loop())

    return True
Example #16
0
    def configuration_callback(callback_data):
        """Handle the submitted configuration."""
        try:
            from pytradfri.api.aiocoap_api import APIFactory
            from pytradfri import RequestError
        except ImportError:
            _LOGGER.exception("Looks like something isn't installed!")
            return

        identity = uuid4().hex
        security_code = callback_data.get('security_code')

        api_factory = APIFactory(host, psk_id=identity, loop=hass.loop)
        # Need To Fix: currently entering a wrong security code sends
        # pytradfri aiocoap API into an endless loop.
        # Should just raise a requestError or something.
        try:
            key = yield from api_factory.generate_psk(security_code)
        except RequestError:
            configurator.async_notify_errors(hass, instance,
                                             "Security Code not accepted.")
            return

        res = yield from _setup_gateway(hass, config, host, identity, key,
                                        DEFAULT_ALLOW_TRADFRI_GROUPS)

        if not res:
            configurator.async_notify_errors(hass, instance,
                                             "Unable to connect.")
            return

        def success():
            """Set up was successful."""
            conf = load_json(hass.config.path(CONFIG_FILE))
            conf[host] = {'identity': identity, 'key': key}
            save_json(hass.config.path(CONFIG_FILE), conf)
            configurator.request_done(instance)

        hass.async_add_job(success)
Example #17
0
async def initialize_api_connection(host, key):
    identity = uuid.uuid4().hex
    api_factory = APIFactory(host=host, psk_id=identity)
    psk =  await api_factory.generate_psk(key)
    logging.info('Generated PSK')

    conf = load_config()
    conf[host] =  {
        'identity': identity,
        'key': psk
    }
    save_config(conf)
    return api_factory
Example #18
0
async def create_psk(args):
    hostConfig = host_config()

    identity = uuid.uuid4().hex
    api_factory = APIFactory(host=args.IP, psk_id=identity)

    psk = await api_factory.generate_psk(args.KEY)
    hostConfig.set_config_items(Gateway=args.IP,
                                Identity=identity,
                                Passkey=psk)

    hostConfig.save()

    print("Config created!")
    return
Example #19
0
async def authenticate(hass, host, security_code):
    """Authenticate with a Tradfri hub."""

    identity = uuid4().hex

    api_factory = APIFactory(host, psk_id=identity)

    try:
        with async_timeout.timeout(5):
            key = await api_factory.generate_psk(security_code)
    except RequestError:
        raise AuthError("invalid_security_code")
    except asyncio.TimeoutError:
        raise AuthError("timeout")

    return await get_gateway_info(hass, host, identity, key)
Example #20
0
async def authenticate(hass, host, security_code):
    """Authenticate with a Tradfri hub."""
    from pytradfri.api.aiocoap_api import APIFactory
    from pytradfri import RequestError

    identity = uuid4().hex

    api_factory = APIFactory(host, psk_id=identity, loop=hass.loop)

    try:
        with async_timeout.timeout(5):
            key = await api_factory.generate_psk(security_code)
    except RequestError:
        raise AuthError('invalid_security_code')
    except asyncio.TimeoutError:
        raise AuthError('timeout')

    return await get_gateway_info(hass, host, identity, key)
Example #21
0
async def get_gateway_info(hass, host, identity, key):
    """Return info for the gateway."""
    from pytradfri.api.aiocoap_api import APIFactory
    from pytradfri import Gateway, RequestError

    try:
        factory = APIFactory(host, psk_id=identity, psk=key, loop=hass.loop)
        api = factory.request
        gateway = Gateway()
        gateway_info_result = await api(gateway.get_gateway_info())
    except RequestError:
        raise AuthError('cannot_connect')

    return {
        CONF_HOST: host,
        CONF_IDENTITY: identity,
        CONF_KEY: key,
        CONF_GATEWAY_ID: gateway_info_result.id,
    }
Example #22
0
async def old_getConfig(args=None):
    hostConfig = {}
    showConfig = False

    CONFIGFILE = "{0}/gateway.json".format(
        appdirs.user_config_dir(appname="tradfri"))
    logging.debug("Looking for config: {}".format(CONFIGFILE))

    # print(CONFIGFILE)
    if args is not None:
        if args.command == "showconfig":
            showConfig = True

        if args.command == "config":
            identity = uuid.uuid4().hex
            api_factory = APIFactory(host=args.IP, psk_id=identity)

            psk = await api_factory.generate_psk(args.KEY)
            hostConfig["Gateway"] = args.IP
            hostConfig["Identity"] = identity
            hostConfig["Passkey"] = psk

            CONFDIR = appdirs.user_config_dir(appname="tradfri")
            if not os.path.exists(CONFDIR):
                os.makedirs(CONFDIR)

            with open(CONFIGFILE, "w") as outfile:
                json.dump(hostConfig, outfile)

            print("Config created!")
            return hostConfig

    if os.path.isfile(CONFIGFILE):
        with open(CONFIGFILE) as json_data_file:
            hostConfig = json.load(json_data_file)
        if showConfig:
            print(hostConfig)
        return hostConfig
    else:
        logging.error("Config-file not found")
        raise ConfigNotFound
Example #23
0
async def _setup_gateway(hass, hass_config, host, identity, key,
                         allow_tradfri_groups):
    """Create a gateway."""
    from pytradfri import Gateway, RequestError  # pylint: disable=import-error
    try:
        from pytradfri.api.aiocoap_api import APIFactory
    except ImportError:
        _LOGGER.exception("Looks like something isn't installed!")
        return False

    try:
        factory = APIFactory(host, psk_id=identity, psk=key, loop=hass.loop)
        api = factory.request
        gateway = Gateway()
        gateway_info_result = await api(gateway.get_gateway_info())
    except RequestError:
        _LOGGER.exception("Tradfri setup failed.")
        return False

    gateway_id = gateway_info_result.id
    hass.data.setdefault(KEY_API, {})
    hass.data.setdefault(KEY_GATEWAY, {})
    gateways = hass.data[KEY_GATEWAY]
    hass.data[KEY_API][gateway_id] = api

    hass.data.setdefault(KEY_TRADFRI_GROUPS, {})
    tradfri_groups = hass.data[KEY_TRADFRI_GROUPS]
    tradfri_groups[gateway_id] = allow_tradfri_groups

    # Check if already set up
    if gateway_id in gateways:
        return True

    gateways[gateway_id] = gateway
    hass.async_add_job(
        discovery.async_load_platform(hass, 'light', DOMAIN,
                                      {'gateway': gateway_id}, hass_config))
    hass.async_add_job(
        discovery.async_load_platform(hass, 'sensor', DOMAIN,
                                      {'gateway': gateway_id}, hass_config))
    return True
Example #24
0
async def async_setup_entry(hass, entry):
    """Create a gateway."""
    # host, identity, key, allow_tradfri_groups
    from pytradfri import Gateway, RequestError  # pylint: disable=import-error
    from pytradfri.api.aiocoap_api import APIFactory

    factory = APIFactory(entry.data[CONF_HOST],
                         psk_id=entry.data[CONF_IDENTITY],
                         psk=entry.data[CONF_KEY],
                         loop=hass.loop)
    api = factory.request
    gateway = Gateway()

    try:
        gateway_info = await api(gateway.get_gateway_info())
    except RequestError:
        _LOGGER.error("Tradfri setup failed.")
        return False

    hass.data.setdefault(KEY_API, {})[entry.entry_id] = api
    hass.data.setdefault(KEY_GATEWAY, {})[entry.entry_id] = gateway

    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='IKEA',
        name='Gateway',
        # They just have 1 gateway model. Type is not exposed yet.
        model='E1526',
        sw_version=gateway_info.firmware_version,
    )

    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(entry, 'light'))
    hass.async_create_task(
        hass.config_entries.async_forward_entry_setup(entry, 'sensor'))

    return True
Example #25
0
def run(shutdown):
    # initialization is copy/pasted from example_async.py

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

    # end copy/pasted

    #
    # set and regularly renew the commissioning timeout, remove when done
    #

    @asyncio.coroutine
    def keep_commissioning_alive(readiness):
        try:
            while True:
                yield from api(gateway.set_commissioning_timeout(60))
                if readiness is not None:
                    readiness()
                readiness = None
                yield from asyncio.sleep(45)
        finally:
            yield from 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

    @asyncio.coroutine
    def new_device(devno):
        nonlocal commissioning

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

        device_command = gateway.get_device(devno)
        device = yield from 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)
    yield from api(observe_devices)
    yield from 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
    #

    yield from shutdown

    if commissioning is not None:
        print("Please allow for the commissioning mode to be disabled")
        commissioning.cancel()
Example #26
0
    async def init_api(self):
        try:
            identity = self.conf[self.gateway_address].get('identity')
            psk = self.conf[self.gateway_address].get('key')
            api_factory = APIFactory(host=self.gateway_address,
                                     psk_id=identity,
                                     psk=psk)
        except KeyError:
            identity = uuid.uuid4().hex
            api_factory = APIFactory(host=self.gateway_address,
                                     psk_id=identity)

            try:
                psk = await api_factory.generate_psk(self.security_code)
                # rospy.loginfo('Generated PSK: {}'.format(psk))

                self.conf[self.gateway_address] = {
                    'identity': identity,
                    'key': psk
                }
                save_json(self.psk_config_file, self.conf)
                rospy.logwarn(
                    f'Generated PSK was stored in {self.psk_config_file}')

            except AttributeError:
                rospy.logfatal("Please provide the 'Security Code' from the "
                               "back of your Tradfri gateway using the "
                               "~security_code param.")
                raise

            except RequestTimeout as e:
                rospy.logfatal(e)
                raise

            except Exception as e:
                rospy.logfatal('Unknown error occurred')
                raise

        self.api = api_factory.request

        # Connect to gateway and get configured devices (these are not necessarily available)
        while not self.connected and not rospy.is_shutdown():
            try:
                rospy.loginfo(f'Connecting to gateway: {self.gateway_address}')
                gateway = Gateway()

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

                rospy.loginfo('Requesting configured devices')
                devices = await self.api(devices_commands)

                self.connected = True
            except RequestTimeout:
                rospy.logwarn('Request timed out. Keep trying...')

        # User canceled request, e.g. with Ctrl-C
        if not self.connected:
            return

        # Lights devices
        self.lights = {
            hex(dev.id): dev
            for dev in devices if dev.has_light_control
        }

        if not self.lights_param:
            # if no lights configured, set the param with default values
            self.lights_param = {
                k: {
                    'alias_id': idx + 1
                }
                for idx, k in enumerate(sorted(self.lights.keys()))
            }
            rospy.set_param('~lights', self.lights_param)

        # Print all lights
        rospy.loginfo('Configured (paired) lights: {}'.format(
            [f'ID: {k}, Name: {v.name}' for k, v in self.lights.items()]))

        self.lights_set = {
            int(light_id, 16)
            for light_id in self.lights_param.keys()
        }
        self.discover_set = copy.deepcopy(self.lights_set)

        # Check if user-specified devices are actually available
        while len(self.discover_set) and not rospy.is_shutdown():
            try:
                rospy.loginfo('Looking for lights: {}'.format(
                    {hex(dev_id)
                     for dev_id in self.discover_set}))
                devices = await self.api(devices_commands)
                found_set = {dev.id for dev in devices if dev.reachable}

                self.discover_set.difference_update(found_set)

                # Wait 1 sec and try again
                if len(self.discover_set):
                    await asyncio.sleep(1.0)

            except RequestTimeout:
                rospy.logwarn('Request timed out. Keep trying...')

        # Create subscribers for configured lights
        self.subs_color = []
        self.pubs_color = {}
        for dev_id, params in self.lights_param.items():
            func = partial(self.color_cb, dev_id=dev_id)
            sub = rospy.Subscriber('light{}/color'.format(params['alias_id']),
                                   ColorRGBA, func)
            self.subs_color.append(sub)

        if len(self.lights_param):
            self.sub_all_color = rospy.Subscriber('all_lights/color',
                                                  ColorRGBA, self.all_color_cb)

        rospy.loginfo('Ready')
Example #27
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()
Example #28
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()
Example #29
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)
Example #30
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)
Example #31
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 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()