Esempio n. 1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
    """Set up DoorBird from a config entry."""

    _async_import_options_from_data_if_missing(hass, entry)

    doorstation_config = entry.data
    doorstation_options = entry.options
    config_entry_id = entry.entry_id

    device_ip = doorstation_config[CONF_HOST]
    username = doorstation_config[CONF_USERNAME]
    password = doorstation_config[CONF_PASSWORD]

    device = DoorBird(device_ip, username, password)
    try:
        status, info = await hass.async_add_executor_job(_init_doorbird_device, device)
    except urllib.error.HTTPError as err:
        if err.code == HTTP_UNAUTHORIZED:
            _LOGGER.error(
                "Authorization rejected by DoorBird for %s@%s", username, device_ip
            )
            return False
        raise ConfigEntryNotReady from err
    except OSError as oserr:
        _LOGGER.error("Failed to setup doorbird at %s: %s", device_ip, oserr)
        raise ConfigEntryNotReady from oserr

    if not status[0]:
        _LOGGER.error(
            "Could not connect to DoorBird as %s@%s: Error %s",
            username,
            device_ip,
            str(status[1]),
        )
        raise ConfigEntryNotReady

    token = doorstation_config.get(CONF_TOKEN, config_entry_id)
    custom_url = doorstation_config.get(CONF_CUSTOM_URL)
    name = doorstation_config.get(CONF_NAME)
    events = doorstation_options.get(CONF_EVENTS, [])
    doorstation = ConfiguredDoorBird(device, name, custom_url, token)
    doorstation.update_events(events)
    # Subscribe to doorbell or motion events
    if not await _async_register_events(hass, doorstation):
        raise ConfigEntryNotReady

    undo_listener = entry.add_update_listener(_update_listener)

    hass.data[DOMAIN][config_entry_id] = {
        DOOR_STATION: doorstation,
        DOOR_STATION_INFO: info,
        UNDO_UPDATE_LISTENER: undo_listener,
    }

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

    return True
Esempio n. 2
0
def setup(hass, config):
    """Set up the DoorBird component."""
    from doorbirdpy import DoorBird

    # Provide an endpoint for the doorstations to call to trigger events
    hass.http.register_view(DoorbirdRequestView())

    doorstations = []

    for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVICES]):
        device_ip = doorstation_config.get(CONF_HOST)
        username = doorstation_config.get(CONF_USERNAME)
        password = doorstation_config.get(CONF_PASSWORD)
        custom_url = doorstation_config.get(CONF_CUSTOM_URL)
        events = doorstation_config.get(CONF_MONITORED_CONDITIONS)
        name = (doorstation_config.get(CONF_NAME)
                or 'DoorBird {}'.format(index + 1))

        device = DoorBird(device_ip, username, password)
        status = device.ready()

        if status[0]:
            _LOGGER.info("Connected to DoorBird at %s as %s", device_ip,
                         username)
            doorstation = ConfiguredDoorbird(device, name, events, custom_url)
            doorstations.append(doorstation)
        elif status[1] == 401:
            _LOGGER.error("Authorization rejected by DoorBird at %s",
                          device_ip)
            return False
        else:
            _LOGGER.error("Could not connect to DoorBird at %s: Error %s",
                          device_ip, str(status[1]))
            return False

        # SETUP EVENT SUBSCRIBERS
        if events is not None:
            # This will make HA the only service that receives events.
            doorstation.device.reset_notifications()

            # Subscribe to doorbell or motion events
            subscribe_events(hass, doorstation)

    hass.data[DOMAIN] = doorstations

    return True
Esempio n. 3
0
def setup(hass, config):
    """Set up the DoorBird component."""
    from doorbirdpy import DoorBird

    # Provide an endpoint for the doorstations to call to trigger events
    hass.http.register_view(DoorbirdRequestView())

    doorstations = []

    for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVICES]):
        device_ip = doorstation_config.get(CONF_HOST)
        username = doorstation_config.get(CONF_USERNAME)
        password = doorstation_config.get(CONF_PASSWORD)
        custom_url = doorstation_config.get(CONF_CUSTOM_URL)
        events = doorstation_config.get(CONF_MONITORED_CONDITIONS)
        name = (doorstation_config.get(CONF_NAME)
                or 'DoorBird {}'.format(index + 1))

        device = DoorBird(device_ip, username, password)
        status = device.ready()

        if status[0]:
            _LOGGER.info("Connected to DoorBird at %s as %s", device_ip,
                         username)
            doorstation = ConfiguredDoorbird(device, name, events, custom_url)
            doorstations.append(doorstation)
        elif status[1] == 401:
            _LOGGER.error("Authorization rejected by DoorBird at %s",
                          device_ip)
            return False
        else:
            _LOGGER.error("Could not connect to DoorBird at %s: Error %s",
                          device_ip, str(status[1]))
            return False

        # SETUP EVENT SUBSCRIBERS
        if events is not None:
            # This will make HA the only service that receives events.
            doorstation.device.reset_notifications()

            # Subscribe to doorbell or motion events
            subscribe_events(hass, doorstation)

    hass.data[DOMAIN] = doorstations

    return True
Esempio n. 4
0
def setup(hass, config):
    """Set up the DoorBird component."""
    from doorbirdpy import DoorBird

    device_ip = config[DOMAIN].get(CONF_HOST)
    username = config[DOMAIN].get(CONF_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD)

    device = DoorBird(device_ip, username, password)
    status = device.ready()

    if status[0]:
        _LOGGER.info("Connected to DoorBird at %s as %s", device_ip, username)
        hass.data[DOMAIN] = device
    elif status[1] == 401:
        _LOGGER.error("Authorization rejected by DoorBird at %s", device_ip)
        return False
    else:
        _LOGGER.error("Could not connect to DoorBird at %s: Error %s",
                      device_ip, str(status[1]))
        return False

    if config[DOMAIN].get(CONF_DOORBELL_EVENTS):
        # Provide an endpoint for the device to call to trigger events
        hass.http.register_view(DoorbirdRequestView())

        # This will make HA the only service that gets doorbell events
        url = '{}{}/{}'.format(
            hass.config.api.base_url, API_URL, SENSOR_DOORBELL)
        device.reset_notifications()
        device.subscribe_notification(SENSOR_DOORBELL, url)

    return True
Esempio n. 5
0
async def async_verify_supported_device(hass, host):
    """Verify the doorbell state endpoint returns a 401."""
    device = DoorBird(host, "", "")
    try:
        await hass.async_add_executor_job(device.doorbell_state)
    except requests.exceptions.HTTPError as err:
        if err.response.status_code == HTTP_UNAUTHORIZED:
            return True
    except OSError:
        return False
    return False
Esempio n. 6
0
def setup(hass, config):
    """Set up the DoorBird component."""
    device_ip = config[DOMAIN].get(CONF_HOST)
    username = config[DOMAIN].get(CONF_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD)

    from doorbirdpy import DoorBird
    device = DoorBird(device_ip, username, password)
    status = device.ready()

    if status[0]:
        _LOGGER.info("Connected to DoorBird at %s as %s", device_ip, username)
        hass.data[DOMAIN] = device
        return True
    elif status[1] == 401:
        _LOGGER.error("Authorization rejected by DoorBird at %s", device_ip)
        return False
    else:
        _LOGGER.error("Could not connect to DoorBird at %s: Error %s",
                      device_ip, str(status[1]))
        return False
def setup(hass, config):
    """Set up the DoorBird component."""
    device_ip = config[DOMAIN].get(CONF_HOST)
    username = config[DOMAIN].get(CONF_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD)

    from doorbirdpy import DoorBird
    device = DoorBird(device_ip, username, password)
    status = device.ready()

    if status[0]:
        _LOGGER.info("Connected to DoorBird at %s as %s", device_ip, username)
        hass.data[DOMAIN] = device
        return True
    elif status[1] == 401:
        _LOGGER.error("Authorization rejected by DoorBird at %s", device_ip)
        return False
    else:
        _LOGGER.error("Could not connect to DoorBird at %s: Error %s",
                      device_ip, str(status[1]))
        return False
Esempio n. 8
0
def setup(hass, config):
    """Set up the DoorBird component."""
    from doorbirdpy import DoorBird

    device_ip = config[DOMAIN].get(CONF_HOST)
    username = config[DOMAIN].get(CONF_USERNAME)
    password = config[DOMAIN].get(CONF_PASSWORD)

    device = DoorBird(device_ip, username, password)
    status = device.ready()

    if status[0]:
        _LOGGER.info("Connected to DoorBird at %s as %s", device_ip, username)
        hass.data[DOMAIN] = device
    elif status[1] == 401:
        _LOGGER.error("Authorization rejected by DoorBird at %s", device_ip)
        return False
    else:
        _LOGGER.error("Could not connect to DoorBird at %s: Error %s",
                      device_ip, str(status[1]))
        return False

    if config[DOMAIN].get(CONF_DOORBELL_EVENTS):
        # Provide an endpoint for the device to call to trigger events
        hass.http.register_view(DoorbirdRequestView())

        # This will make HA the only service that gets doorbell events
        url = '{}{}/{}'.format(
            hass.config.api.base_url, API_URL, SENSOR_DOORBELL)
        device.reset_notifications()
        device.subscribe_notification(SENSOR_DOORBELL, url)

    return True
Esempio n. 9
0
async def validate_input(hass: core.HomeAssistant, data):
    """Validate the user input allows us to connect."""
    device = DoorBird(data[CONF_HOST], data[CONF_USERNAME], data[CONF_PASSWORD])
    try:
        status, info = await hass.async_add_executor_job(_check_device, device)
    except requests.exceptions.HTTPError as err:
        if err.response.status_code == HTTPStatus.UNAUTHORIZED:
            raise InvalidAuth from err
        raise CannotConnect from err
    except OSError as err:
        raise CannotConnect from err

    if not status[0]:
        raise CannotConnect

    mac_addr = get_mac_address_from_doorstation_info(info)

    # Return info that you want to store in the config entry.
    return {"title": data[CONF_HOST], "mac_addr": mac_addr}
Esempio n. 10
0
async def validate_input(hass: core.HomeAssistant, data):
    """Validate the user input allows us to connect.

    Data has the keys from DATA_SCHEMA with values provided by the user.
    """
    device = DoorBird(data[CONF_HOST], data[CONF_USERNAME], data[CONF_PASSWORD])
    try:
        status = await hass.async_add_executor_job(device.ready)
        info = await hass.async_add_executor_job(device.info)
    except urllib.error.HTTPError as err:
        if err.code == HTTP_UNAUTHORIZED:
            raise InvalidAuth from err
        raise CannotConnect from err
    except OSError as err:
        raise CannotConnect from err

    if not status[0]:
        raise CannotConnect

    mac_addr = get_mac_address_from_doorstation_info(info)

    # Return info that you want to store in the config entry.
    return {"title": data[CONF_HOST], "mac_addr": mac_addr}
Esempio n. 11
0
def setup(hass, config):
    """Set up the DoorBird component."""

    # Provide an endpoint for the doorstations to call to trigger events
    hass.http.register_view(DoorBirdRequestView)

    doorstations = []

    for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVICES]):
        device_ip = doorstation_config.get(CONF_HOST)
        username = doorstation_config.get(CONF_USERNAME)
        password = doorstation_config.get(CONF_PASSWORD)
        custom_url = doorstation_config.get(CONF_CUSTOM_URL)
        events = doorstation_config.get(CONF_EVENTS)
        token = doorstation_config.get(CONF_TOKEN)
        name = doorstation_config.get(CONF_NAME) or f"DoorBird {index + 1}"

        try:
            device = DoorBird(device_ip, username, password)
            status = device.ready()
        except OSError as oserr:
            _LOGGER.error("Failed to setup doorbird at %s: %s; not retrying",
                          device_ip, oserr)
            continue

        if status[0]:
            doorstation = ConfiguredDoorBird(device, name, events, custom_url,
                                             token)
            doorstations.append(doorstation)
            _LOGGER.info(
                'Connected to DoorBird "%s" as %s@%s',
                doorstation.name,
                username,
                device_ip,
            )
        elif status[1] == 401:
            _LOGGER.error("Authorization rejected by DoorBird for %s@%s",
                          username, device_ip)
            return False
        else:
            _LOGGER.error(
                "Could not connect to DoorBird as %s@%s: Error %s",
                username,
                device_ip,
                str(status[1]),
            )
            return False

        # Subscribe to doorbell or motion events
        if events:
            try:
                doorstation.register_events(hass)
            except HTTPError:
                hass.components.persistent_notification.create(
                    "Doorbird configuration failed.  Please verify that API "
                    "Operator permission is enabled for the Doorbird user. "
                    "A restart will be required once permissions have been "
                    "verified.",
                    title="Doorbird Configuration Failure",
                    notification_id="doorbird_schedule_error",
                )

                return False

    hass.data[DOMAIN] = doorstations

    def _reset_device_favorites_handler(event):
        """Handle clearing favorites on device."""
        token = event.data.get("token")

        if token is None:
            return

        doorstation = get_doorstation_by_token(hass, token)

        if doorstation is None:
            _LOGGER.error("Device not found for provided token.")

        # Clear webhooks
        favorites = doorstation.device.favorites()

        for favorite_type in favorites:
            for favorite_id in favorites[favorite_type]:
                doorstation.device.delete_favorite(favorite_type, favorite_id)

    hass.bus.listen(RESET_DEVICE_FAVORITES, _reset_device_favorites_handler)

    return True
Esempio n. 12
0
def setup(hass, config):
    """Set up the DoorBird component."""
    from doorbirdpy import DoorBird

    token = config[DOMAIN].get(CONF_TOKEN)

    # Provide an endpoint for the doorstations to call to trigger events
    hass.http.register_view(DoorBirdRequestView(token))

    # Provide an endpoint for the user to call to clear device changes
    hass.http.register_view(DoorBirdCleanupView(token))

    doorstations = []

    for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVICES]):
        device_ip = doorstation_config.get(CONF_HOST)
        username = doorstation_config.get(CONF_USERNAME)
        password = doorstation_config.get(CONF_PASSWORD)
        doorbell_nums = doorstation_config.get(CONF_DOORBELL_NUMS)
        relay_nums = doorstation_config.get(CONF_RELAY_NUMS)
        custom_url = doorstation_config.get(CONF_CUSTOM_URL)
        events = doorstation_config.get(CONF_MONITORED_CONDITIONS)
        name = (doorstation_config.get(CONF_NAME)
                or 'DoorBird {}'.format(index + 1))

        device = DoorBird(device_ip, username, password)
        status = device.ready()

        if status[0]:
            doorstation = ConfiguredDoorBird(device, name, events, custom_url,
                                             doorbell_nums, relay_nums, token)
            doorstations.append(doorstation)
            _LOGGER.info('Connected to DoorBird "%s" as %s@%s',
                         doorstation.name, username, device_ip)
        elif status[1] == 401:
            _LOGGER.error("Authorization rejected by DoorBird for %s@%s",
                          username, device_ip)
            return False
        else:
            _LOGGER.error("Could not connect to DoorBird as %s@%s: Error %s",
                          username, device_ip, str(status[1]))
            return False

        # Subscribe to doorbell or motion events
        if events:
            try:
                doorstation.update_schedule(hass)
            except HTTPError:
                hass.components.persistent_notification.create(
                    'Doorbird configuration failed.  Please verify that API '
                    'Operator permission is enabled for the Doorbird user. '
                    'A restart will be required once permissions have been '
                    'verified.',
                    title='Doorbird Configuration Failure',
                    notification_id='doorbird_schedule_error')

                return False

    hass.data[DOMAIN] = doorstations

    def _reset_device_favorites_handler(event):
        """Handle clearing favorites on device."""
        slug = event.data.get('slug')

        if slug is None:
            return

        doorstation = get_doorstation_by_slug(hass, slug)

        if doorstation is None:
            _LOGGER.error('Device not found %s', format(slug))

        # Clear webhooks
        favorites = doorstation.device.favorites()

        for favorite_type in favorites:
            for favorite_id in favorites[favorite_type]:
                doorstation.device.delete_favorite(favorite_type, favorite_id)

    hass.bus.listen(RESET_DEVICE_FAVORITES, _reset_device_favorites_handler)

    return True
Esempio n. 13
0
def setup(hass, config):
    """Set up the DoorBird component."""
    from doorbirdpy import DoorBird

    token = config[DOMAIN].get(CONF_TOKEN)

    # Provide an endpoint for the doorstations to call to trigger events
    hass.http.register_view(DoorBirdRequestView(token))

    # Provide an endpoint for the user to call to clear device changes
    hass.http.register_view(DoorBirdCleanupView(token))

    doorstations = []

    for index, doorstation_config in enumerate(config[DOMAIN][CONF_DEVICES]):
        device_ip = doorstation_config.get(CONF_HOST)
        username = doorstation_config.get(CONF_USERNAME)
        password = doorstation_config.get(CONF_PASSWORD)
        doorbell_nums = doorstation_config.get(CONF_DOORBELL_NUMS)
        custom_url = doorstation_config.get(CONF_CUSTOM_URL)
        events = doorstation_config.get(CONF_MONITORED_CONDITIONS)
        name = (doorstation_config.get(CONF_NAME)
                or 'DoorBird {}'.format(index + 1))

        device = DoorBird(device_ip, username, password)
        status = device.ready()

        if status[0]:
            doorstation = ConfiguredDoorBird(device, name, events, custom_url,
                                             doorbell_nums, token)
            doorstations.append(doorstation)
            _LOGGER.info('Connected to DoorBird "%s" as %s@%s',
                         doorstation.name, username, device_ip)
        elif status[1] == 401:
            _LOGGER.error("Authorization rejected by DoorBird for %s@%s",
                          username, device_ip)
            return False
        else:
            _LOGGER.error("Could not connect to DoorBird as %s@%s: Error %s",
                          username, device_ip, str(status[1]))
            return False

        # Subscribe to doorbell or motion events
        if events is not None:
            doorstation.update_schedule(hass)

    hass.data[DOMAIN] = doorstations

    def _reset_device_favorites_handler(event):
        """Handle clearing favorites on device."""
        slug = event.data.get('slug')

        if slug is None:
            return

        doorstation = get_doorstation_by_slug(hass, slug)

        if doorstation is None:
            _LOGGER.error('Device not found %s', format(slug))

        # Clear webhooks
        favorites = doorstation.device.favorites()

        for favorite_type in favorites:
            for favorite_id in favorites[favorite_type]:
                doorstation.device.delete_favorite(favorite_type, favorite_id)

    hass.bus.listen(RESET_DEVICE_FAVORITES, _reset_device_favorites_handler)

    return True