Exemplo n.º 1
0
async def get_bridge(hass, host, username=None):
    """Create a bridge object and verify authentication."""
    import aiohue

    bridge = aiohue.Bridge(
        host,
        username=username,
        websession=aiohttp_client.async_get_clientsession(hass))

    try:
        with async_timeout.timeout(5):
            # Create username if we don't have one
            if not username:
                await bridge.create_user('home-assistant')
            # Initialize bridge (and validate our username)
            await bridge.initialize()

        return bridge
    except (aiohue.LinkButtonNotPressed, aiohue.Unauthorized):
        LOGGER.warning("Connected to Hue at %s but not registered.", host)
        raise AuthenticationRequired
    except (asyncio.TimeoutError, aiohue.RequestError):
        LOGGER.error("Error connecting to the Hue bridge at %s", host)
        raise CannotConnect
    except aiohue.AiohueException:
        LOGGER.exception('Unknown Hue linking error occurred')
        raise AuthenticationRequired
Exemplo n.º 2
0
    async def async_step_link(self, user_input=None):
        """Attempt to link with the Hue bridge."""
        import aiohue
        errors = {}

        if user_input is not None:
            bridge = aiohue.Bridge(self.host, websession=self._websession)
            try:
                with async_timeout.timeout(5):
                    # Create auth token
                    await bridge.create_user('home-assistant')
                    # Fetches name and id
                    await bridge.initialize()
            except (asyncio.TimeoutError, aiohue.RequestError,
                    aiohue.LinkButtonNotPressed):
                errors['base'] = 'Failed to register, please try again.'
            except aiohue.AiohueException:
                errors['base'] = 'Unknown linking error occurred.'
                _LOGGER.exception('Uknown Hue linking error occurred')
            else:
                return self.async_create_entry(title=bridge.config.name,
                                               data={
                                                   'host': bridge.host,
                                                   'bridge_id':
                                                   bridge.config.bridgeid,
                                                   'username': bridge.username,
                                               })

        return self.async_show_form(
            step_id='link',
            title='Link Hub',
            description=CONFIG_INSTRUCTIONS,
            errors=errors,
        )
Exemplo n.º 3
0
async def get_bridge(hass, host, username=None):
    """Create a bridge object and verify authentication."""
    bridge = aiohue.Bridge(
        host,
        username=username,
        websession=aiohttp_client.async_get_clientsession(hass))

    try:
        with async_timeout.timeout(10):
            # Create username if we don't have one
            if not username:
                device_name = unicode_slug.slugify(hass.config.location_name,
                                                   max_length=19)
                await bridge.create_user(f"home-assistant#{device_name}")

            # Initialize bridge (and validate our username)
            await bridge.initialize()

        return bridge
    except (aiohue.LinkButtonNotPressed, aiohue.Unauthorized):
        raise AuthenticationRequired
    except (asyncio.TimeoutError, aiohue.RequestError):
        raise CannotConnect
    except aiohue.AiohueException:
        LOGGER.exception("Unknown Hue linking error occurred")
        raise AuthenticationRequired
Exemplo n.º 4
0
    async def async_setup(self):
        """Set up a phue bridge based on host parameter."""
        import aiohue

        api = aiohue.Bridge(self.host,
                            username=self.username,
                            websession=aiohttp_client.async_get_clientsession(
                                self.hass))

        try:
            with async_timeout.timeout(5):
                # Initialize bridge and validate our username
                if not self.username:
                    await api.create_user('home-assistant')
                await api.initialize()
        except (aiohue.LinkButtonNotPressed, aiohue.Unauthorized):
            _LOGGER.warning("Connected to Hue at %s but not registered.",
                            self.host)
            self.async_request_configuration()
            return
        except (asyncio.TimeoutError, aiohue.RequestError):
            _LOGGER.error("Error connecting to the Hue bridge at %s",
                          self.host)
            return
        except aiohue.AiohueException:
            _LOGGER.exception('Unknown Hue linking error occurred')
            self.async_request_configuration()
            return
        except Exception:  # pylint: disable=broad-except
            _LOGGER.exception("Unknown error connecting with Hue bridge at %s",
                              self.host)
            return

        self.hass.data[DOMAIN][self.host] = self

        # If we came here and configuring this host, mark as done
        if self.config_request_id:
            request_id = self.config_request_id
            self.config_request_id = None
            self.hass.components.configurator.async_request_done(request_id)

            self.username = api.username

            # Save config file
            await self.hass.async_add_job(
                save_json, self.hass.config.path(self.filename),
                {self.host: {
                    'username': api.username
                }})

        self.api = api

        self.hass.async_add_job(
            discovery.async_load_platform(self.hass, 'light', DOMAIN,
                                          {'host': self.host}))

        self.hass.services.async_register(DOMAIN,
                                          SERVICE_HUE_SCENE,
                                          self.hue_activate_scene,
                                          schema=SCENE_SCHEMA)
Exemplo n.º 5
0
    async def async_setup(self, tries=0):
        """Set up a phue bridge based on host parameter."""
        host = self.host
        hass = self.hass

        bridge = aiohue.Bridge(
            host,
            username=self.config_entry.data["username"],
            websession=aiohttp_client.async_get_clientsession(hass),
        )

        try:
            await authenticate_bridge(hass, bridge)

        except AuthenticationRequired:
            # Usernames can become invalid if hub is reset or user removed.
            # We are going to fail the config entry setup and initiate a new
            # linking procedure. When linking succeeds, it will remove the
            # old config entry.
            create_config_flow(hass, host)
            return False

        except CannotConnect as err:
            LOGGER.error("Error connecting to the Hue bridge at %s", host)
            raise ConfigEntryNotReady from err

        except Exception:  # pylint: disable=broad-except
            LOGGER.exception("Unknown error connecting with Hue bridge at %s",
                             host)
            return False

        self.api = bridge
        self.sensor_manager = SensorManager(self)

        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(
                self.config_entry, "light"))
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(
                self.config_entry, "binary_sensor"))
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(
                self.config_entry, "sensor"))

        hass.services.async_register(DOMAIN,
                                     SERVICE_HUE_SCENE,
                                     self.hue_activate_scene,
                                     schema=SCENE_SCHEMA)

        self.parallel_updates_semaphore = asyncio.Semaphore(
            3 if self.api.config.modelid == "BSB001" else 10)

        self.unsub_config_entry_listener = self.config_entry.add_update_listener(
            _update_listener)

        self.authorized = True
        return True
Exemplo n.º 6
0
    def _async_get_bridge(self, host: str, bridge_id: Optional[str] = None):
        """Return a bridge object."""
        if bridge_id is not None:
            bridge_id = normalize_bridge_id(bridge_id)

        return aiohue.Bridge(
            host,
            websession=aiohttp_client.async_get_clientsession(self.hass),
            bridge_id=bridge_id,
        )
Exemplo n.º 7
0
    async def update_hue_run(self, websession):
        try:
            entriesJson = open('/config/.storage/core.config_entries', )
            response = json.load(entriesJson)

            for entry in response["data"]["entries"]:
                if entry["title"] == "Philips hue":
                    break
            bridge = aiohue.Bridge(
                entry["data"]["host"],
                username=entry["data"]["username"],
                websession=websession,
            )
        except Exception as e:
            raise e
        if bridge is None:
            bridges = await discover_nupnp(websession)
            if self._hue_bridge is not None:
                bridge = aiohue.Bridge(
                    self._hue_bridge,
                    username=self._hue_username,
                    websession=websession,
                )
            else:
                bridges = await discover_nupnp(websession)
                bridge = bridges[0]
                bridge.username = self._hue_username

        await bridge.initialize()
        for id in bridge.scenes:
            scene = bridge.scenes[id]
            if self._hue_keyword in scene.name:
                color_temp = self._calc_ct()
                lightstates = await scene.lightstates
                for light_id in scene.lights:
                    await scene.set_lightstate(id=light_id,
                                               on=lightstates[light_id]["on"],
                                               bri=round(self._brightness),
                                               ct=color_temp)
Exemplo n.º 8
0
 async def connect(self):
     self.bridge = aiohue.Bridge(
         self.config["host"],
         username=self.config[USERNAME],
         websession=aiohttp.ClientSession(),
     )
     try:
         if not self.config[USERNAME]:
             await self.bridge.create_user("riva")
         await self.bridge.initialize()
     except aiohue.Unauthorized:
         pass
     except aiohue.LinkButtonNotPressed:
         pass
Exemplo n.º 9
0
    async def async_setup(self, tries=0):
        """Set up a phue bridge based on host parameter."""
        host = self.host
        opp = self.opp

        bridge = aiohue.Bridge(
            host,
            username=self.config_entry.data["username"],
            websession=aiohttp_client.async_get_clientsession(opp),
        )

        try:
            await authenticate_bridge(opp, bridge)

        except AuthenticationRequired:
            # Usernames can become invalid if hub is reset or user removed.
            # We are going to fail the config entry setup and initiate a new
            # linking procedure. When linking succeeds, it will remove the
            # old config entry.
            create_config_flow(opp, host)
            return False

        except CannotConnect as err:
            raise ConfigEntryNotReady(
                f"Error connecting to the Hue bridge at {host}") from err

        except Exception:  # pylint: disable=broad-except
            LOGGER.exception("Unknown error connecting with Hue bridge at %s",
                             host)
            return False

        self.api = bridge
        if bridge.sensors is not None:
            self.sensor_manager = SensorManager(self)

        opp.data.setdefault(DOMAIN, {})[self.config_entry.entry_id] = self
        opp.config_entries.async_setup_platforms(self.config_entry, PLATFORMS)

        self.parallel_updates_semaphore = asyncio.Semaphore(
            3 if self.api.config.modelid == "BSB001" else 10)

        self.reset_jobs.append(
            self.config_entry.add_update_listener(_update_listener))
        self.reset_jobs.append(
            asyncio.create_task(self._subscribe_events()).cancel)

        self.authorized = True
        return True