Esempio n. 1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up Bond from a config entry."""
    host = entry.data[CONF_HOST]
    token = entry.data[CONF_ACCESS_TOKEN]

    bond = Bond(host=host,
                token=token,
                timeout=ClientTimeout(total=_API_TIMEOUT))
    hub = BondHub(bond)
    try:
        await hub.setup()
    except (ClientError, AsyncIOTimeoutError, OSError) as error:
        raise ConfigEntryNotReady from error

    hass.data[DOMAIN][entry.entry_id] = hub

    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=entry.entry_id,
        identifiers={(DOMAIN, hub.bond_id)},
        manufacturer="Olibra",
        name=hub.bond_id,
        model=hub.target,
        sw_version=hub.fw_ver,
    )

    for component in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, component))

    return True
Esempio n. 2
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Bond from a config entry."""
    host = entry.data[CONF_HOST]
    token = entry.data[CONF_ACCESS_TOKEN]
    config_entry_id = entry.entry_id

    bond = Bond(
        host=host,
        token=token,
        timeout=ClientTimeout(total=_API_TIMEOUT),
        session=async_get_clientsession(hass),
    )
    hub = BondHub(bond)
    try:
        await hub.setup()
    except ClientResponseError as ex:
        if ex.status == HTTPStatus.UNAUTHORIZED:
            _LOGGER.error("Bond token no longer valid: %s", ex)
            return False
        raise ConfigEntryNotReady from ex
    except (ClientError, AsyncIOTimeoutError, OSError) as error:
        raise ConfigEntryNotReady from error

    bpup_subs = BPUPSubscriptions()
    stop_bpup = await start_bpup(host, bpup_subs)

    @callback
    def _async_stop_event(*_: Any) -> None:
        stop_bpup()

    entry.async_on_unload(_async_stop_event)
    entry.async_on_unload(
        hass.bus.async_listen(EVENT_HOMEASSISTANT_STOP, _async_stop_event))
    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        HUB: hub,
        BPUP_SUBS: bpup_subs,
    }

    if not entry.unique_id:
        hass.config_entries.async_update_entry(entry, unique_id=hub.bond_id)

    assert hub.bond_id is not None
    hub_name = hub.name or hub.bond_id
    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=config_entry_id,
        identifiers={(DOMAIN, hub.bond_id)},
        manufacturer=BRIDGE_MAKE,
        name=hub_name,
        model=hub.target,
        sw_version=hub.fw_ver,
        suggested_area=hub.location,
    )

    _async_remove_old_device_identifiers(config_entry_id, device_registry, hub)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 3
0
async def _validate_input(opp: OpenPeerPower,
                          data: dict[str, Any]) -> tuple[str, str]:
    """Validate the user input allows us to connect."""

    bond = Bond(data[CONF_HOST],
                data[CONF_ACCESS_TOKEN],
                session=async_get_clientsession(opp))
    try:
        hub = BondHub(bond)
        await hub.setup(max_devices=1)
    except ClientConnectionError as error:
        raise InputValidationError("cannot_connect") from error
    except ClientResponseError as error:
        if error.status == HTTP_UNAUTHORIZED:
            raise InputValidationError("invalid_auth") from error
        raise InputValidationError("unknown") from error
    except Exception as error:
        _LOGGER.exception("Unexpected exception")
        raise InputValidationError("unknown") from error

    # Return unique ID from the hub to be stored in the config entry.
    if not hub.bond_id:
        raise InputValidationError("old_firmware")

    return hub.bond_id, hub.name
Esempio n. 4
0
async def async_get_token(hass: HomeAssistant, host: str) -> str | None:
    """Try to fetch the token from the bond device."""
    bond = Bond(host, "", session=async_get_clientsession(hass))
    try:
        response: dict[str, str] = await bond.token()
    except ClientConnectionError:
        return None
    return response.get("token")
Esempio n. 5
0
async def async_setup_entry(opp: OpenPeerPower, entry: ConfigEntry) -> bool:
    """Set up Bond from a config entry."""
    host = entry.data[CONF_HOST]
    token = entry.data[CONF_ACCESS_TOKEN]
    config_entry_id = entry.entry_id

    bond = Bond(
        host=host,
        token=token,
        timeout=ClientTimeout(total=_API_TIMEOUT),
        session=async_get_clientsession(opp),
    )
    hub = BondHub(bond)
    try:
        await hub.setup()
    except (ClientError, AsyncIOTimeoutError, OSError) as error:
        raise ConfigEntryNotReady from error

    bpup_subs = BPUPSubscriptions()
    stop_bpup = await start_bpup(host, bpup_subs)

    @callback
    def _async_stop_event(event: Event) -> None:
        stop_bpup()

    stop_event_cancel = opp.bus.async_listen(EVENT_OPENPEERPOWER_STOP,
                                             _async_stop_event)
    opp.data.setdefault(DOMAIN, {})
    opp.data[DOMAIN][entry.entry_id] = {
        HUB: hub,
        BPUP_SUBS: bpup_subs,
        BPUP_STOP: stop_bpup,
        _STOP_CANCEL: stop_event_cancel,
    }

    if not entry.unique_id:
        opp.config_entries.async_update_entry(entry, unique_id=hub.bond_id)

    assert hub.bond_id is not None
    hub_name = hub.name or hub.bond_id
    device_registry = await dr.async_get_registry(opp)
    device_registry.async_get_or_create(
        config_entry_id=config_entry_id,
        identifiers={(DOMAIN, hub.bond_id)},
        manufacturer=BRIDGE_MAKE,
        name=hub_name,
        model=hub.target,
        sw_version=hub.fw_ver,
        suggested_area=hub.location,
    )

    _async_remove_old_device_identifiers(config_entry_id, device_registry, hub)

    opp.config_entries.async_setup_platforms(entry, PLATFORMS)

    return True
Esempio n. 6
0
async def test_optional_overrides():
    """Tests using external session."""
    async with ClientSession() as session:
        timeout: ClientTimeout = ClientTimeout(total=1)
        bond: Bond = Bond("test-host", "test-token", session=session, timeout=timeout)
        with aioresponses() as response:
            response.get(
                "http://test-host/v2/sys/version",
                payload={"some": "version"}
            )
            actual = await bond.version()
            assert actual == {"some": "version"}
Esempio n. 7
0
async def validate_input(data):
    """Validate the user input allows us to connect."""

    try:
        bond = Bond(data[CONF_HOST], data[CONF_ACCESS_TOKEN])
        await bond.devices()
    except ClientConnectionError:
        raise CannotConnect
    except ClientResponseError as error:
        if error.status == 401:
            raise InvalidAuth
        raise

    # Return info to be stored in the config entry.
    return {"title": data[CONF_HOST]}
Esempio n. 8
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Bond from a config entry."""
    host = entry.data[CONF_HOST]
    token = entry.data[CONF_ACCESS_TOKEN]
    config_entry_id = entry.entry_id

    bond = Bond(host=host,
                token=token,
                timeout=ClientTimeout(total=_API_TIMEOUT))
    hub = BondHub(bond)
    try:
        await hub.setup()
    except (ClientError, AsyncIOTimeoutError, OSError) as error:
        raise ConfigEntryNotReady from error

    bpup_subs = BPUPSubscriptions()
    stop_bpup = await start_bpup(host, bpup_subs)

    hass.data.setdefault(DOMAIN, {})
    hass.data[DOMAIN][entry.entry_id] = {
        HUB: hub,
        BPUP_SUBS: bpup_subs,
        BPUP_STOP: stop_bpup,
    }

    if not entry.unique_id:
        hass.config_entries.async_update_entry(entry, unique_id=hub.bond_id)

    assert hub.bond_id is not None
    hub_name = hub.name or hub.bond_id
    device_registry = await dr.async_get_registry(hass)
    device_registry.async_get_or_create(
        config_entry_id=config_entry_id,
        identifiers={(DOMAIN, hub.bond_id)},
        manufacturer=BRIDGE_MAKE,
        name=hub_name,
        model=hub.target,
        sw_version=hub.fw_ver,
        suggested_area=hub.location,
    )

    _async_remove_old_device_identifiers(config_entry_id, device_registry, hub)

    for platform in PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, platform))

    return True
Esempio n. 9
0
    async def _async_try_automatic_configure(self) -> None:
        """Try to auto configure the device.

        Failure is acceptable here since the device may have been
        online longer then the allowed setup period, and we will
        instead ask them to manually enter the token.
        """
        bond = Bond(self._discovered[CONF_HOST], "")
        try:
            response = await bond.token()
        except ClientConnectionError:
            return

        token = response.get("token")
        if token is None:
            return

        self._discovered[CONF_ACCESS_TOKEN] = token
        _, hub_name = await _validate_input(self._discovered)
        self._discovered[CONF_NAME] = hub_name
Esempio n. 10
0
async def _validate_input(data: Dict[str, Any]) -> str:
    """Validate the user input allows us to connect."""

    try:
        bond = Bond(data[CONF_HOST], data[CONF_ACCESS_TOKEN])
        version = await bond.version()
        # call to non-version API is needed to validate authentication
        await bond.devices()
    except ClientConnectionError:
        raise InputValidationError("cannot_connect")
    except ClientResponseError as error:
        if error.status == 401:
            raise InputValidationError("invalid_auth")
        raise InputValidationError("unknown")
    except Exception:
        _LOGGER.exception("Unexpected exception")
        raise InputValidationError("unknown")

    # Return unique ID from the hub to be stored in the config entry.
    return version["bondid"]
Esempio n. 11
0
def bond_fixture():
    """Creates Bond fixture."""
    return Bond("test-host", "test-token")