Example #1
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the Unifi Protect config entries."""
    _async_import_options_from_data_if_missing(hass, entry)

    session = async_create_clientsession(hass, cookie_jar=CookieJar(unsafe=True))
    protectserver = UpvServer(
        session,
        entry.data[CONF_HOST],
        entry.data[CONF_PORT],
        entry.data[CONF_USERNAME],
        entry.data[CONF_PASSWORD],
    )

    _LOGGER.debug("Connect to Unfi Protect")
    protect_data = UnifiProtectData(hass, protectserver, SCAN_INTERVAL)

    try:
        nvr_info = await protectserver.server_information()
    except NotAuthorized:
        _LOGGER.error(
            "Could not Authorize against Unifi Protect. Please reinstall the Integration"
        )
        return False
    except (asyncio.TimeoutError, NvrError, ServerDisconnectedError) as notreadyerror:
        raise ConfigEntryNotReady from notreadyerror

    if nvr_info["server_version"] < MIN_REQUIRED_PROTECT_V:
        _LOGGER.error(
            "You are running V%s of UniFi Protect. Minimum required version is V%s. Please upgrade UniFi Protect and then retry",
            nvr_info["server_version"],
            MIN_REQUIRED_PROTECT_V,
        )
        return False

    if entry.unique_id is None:
        hass.config_entries.async_update_entry(entry, unique_id=nvr_info[SERVER_ID])

    await protect_data.async_setup()
    if not protect_data.last_update_success:
        raise ConfigEntryNotReady

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = UnifiProtectEntryData(
        protect_data=protect_data,
        upv=protectserver,
        server_info=nvr_info,
        disable_stream=entry.options.get(CONF_DISABLE_RTSP, False),
        doorbell_text=entry.options.get(CONF_DOORBELL_TEXT, None),
    )

    await _async_get_or_create_nvr_device_in_registry(hass, entry, nvr_info)

    hass.config_entries.async_setup_platforms(entry, PLATFORMS)

    entry.async_on_unload(entry.add_update_listener(_async_options_updated))
    entry.async_on_unload(
        hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, protect_data.async_stop)
    )

    return True
Example #2
0
    async def async_step_user(self, user_input=None):
        """Handle a flow initiated by the user."""
        if user_input is None:
            return await self._show_setup_form(user_input)

        errors = {}

        session = async_create_clientsession(self.hass,
                                             cookie_jar=CookieJar(unsafe=True))

        unifiprotect = UpvServer(
            session,
            user_input[CONF_HOST],
            user_input[CONF_PORT],
            user_input[CONF_USERNAME],
            user_input[CONF_PASSWORD],
        )

        try:
            server_info = await unifiprotect.server_information()
        except NotAuthorized as ex:
            _LOGGER.debug(ex)
            errors["base"] = "connection_error"
            return await self._show_setup_form(errors)
        except NvrError as ex:
            _LOGGER.debug(ex)
            errors["base"] = "nvr_error"
            return await self._show_setup_form(errors)

        unique_id = server_info[SERVER_ID]
        server_name = server_info[SERVER_NAME]

        await self.async_set_unique_id(unique_id)
        self._abort_if_unique_id_configured()

        return self.async_create_entry(
            title=server_name,
            data={
                CONF_ID: server_name,
                CONF_HOST: user_input[CONF_HOST],
                CONF_PORT: user_input[CONF_PORT],
                CONF_USERNAME: user_input.get(CONF_USERNAME),
                CONF_PASSWORD: user_input.get(CONF_PASSWORD),
                CONF_DISABLE_RTSP: user_input.get(CONF_DISABLE_RTSP),
                CONF_SNAPSHOT_DIRECT: user_input.get(CONF_SNAPSHOT_DIRECT),
                CONF_IR_ON: user_input.get(CONF_IR_ON),
                CONF_IR_OFF: user_input.get(CONF_IR_OFF),
                CONF_SCAN_INTERVAL: user_input.get(CONF_SCAN_INTERVAL),
            },
        )
async def _get_controller_id(hass: HomeAssistantType, controller_config) -> str:
    session = async_create_clientsession(
        hass, cookie_jar=CookieJar(unsafe=True)
    )

    unifi_protect = UpvServer(
        session,
        controller_config[CONF_HOST],
        controller_config[CONF_PORT],
        controller_config[CONF_USERNAME],
        controller_config[CONF_PASSWORD],
    )

    return await unifi_protect.unique_id()
Example #4
0
    async def async_step_user(self, user_input=None):
        """Handle a flow initiated by the user."""
        if user_input is None:
            return await self._show_setup_form(user_input)

        errors = {}

        session = async_create_clientsession(
            self.hass, cookie_jar=CookieJar(unsafe=True)
        )

        unifiprotect = UpvServer(
            session,
            user_input[CONF_HOST],
            user_input[CONF_PORT],
            user_input[CONF_USERNAME],
            user_input[CONF_PASSWORD],
        )

        try:
            unique_id = await unifiprotect.unique_id()
        except NotAuthorized as e:
            _LOGGER.debug(e)
            errors["base"] = "connection_error"
            return await self._show_setup_form(errors)
        except NvrError as e:
            _LOGGER.debug(e)
            errors["base"] = "nvr_error"
            return await self._show_setup_form(errors)

        entries = self._async_current_entries()
        for entry in entries:
            if entry.data[CONF_ID] == unique_id:
                return self.async_abort(reason="server_exists")

        return self.async_create_entry(
            title=unique_id,
            data={
                CONF_ID: unique_id,
                CONF_HOST: user_input[CONF_HOST],
                CONF_PORT: user_input[CONF_PORT],
                CONF_USERNAME: user_input.get(CONF_USERNAME),
                CONF_PASSWORD: user_input.get(CONF_PASSWORD),
                CONF_SCAN_INTERVAL: user_input.get(CONF_SCAN_INTERVAL),
                CONF_SNAPSHOT_DIRECT: user_input.get(CONF_SNAPSHOT_DIRECT),
                CONF_IR_ON: user_input.get(CONF_IR_ON),
                CONF_IR_OFF: user_input.get(CONF_IR_OFF),
            },
        )
Example #5
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.
    """

    session = async_create_clientsession(hass,
                                         cookie_jar=CookieJar(unsafe=True))

    unifiprotect = UpvServer(
        session,
        data[CONF_HOST],
        data[CONF_PORT],
        data[CONF_USERNAME],
        data[CONF_PASSWORD],
    )

    unique_id = await unifiprotect.unique_id()

    return unique_id
Example #6
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up the Unifi Protect config entries."""

    if not entry.options:
        hass.config_entries.async_update_entry(
            entry,
            options={
                CONF_SCAN_INTERVAL:
                entry.data.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL),
                CONF_SNAPSHOT_DIRECT:
                entry.data.get(CONF_SNAPSHOT_DIRECT, False),
            },
        )
    if not entry.options.get(CONF_DISABLE_RTSP):
        hass.config_entries.async_update_entry(entry,
                                               options={
                                                   CONF_DISABLE_RTSP:
                                                   entry.data.get(
                                                       CONF_DISABLE_RTSP,
                                                       False)
                                               })

    session = async_create_clientsession(hass,
                                         cookie_jar=CookieJar(unsafe=True))
    protectserver = UpvServer(
        session,
        entry.data[CONF_HOST],
        entry.data[CONF_PORT],
        entry.data[CONF_USERNAME],
        entry.data[CONF_PASSWORD],
    )

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = protectserver
    _LOGGER.debug("Connect to Unfi Protect")

    events_update_interval = entry.options.get(CONF_SCAN_INTERVAL,
                                               DEFAULT_SCAN_INTERVAL)

    protect_data = UnifiProtectData(hass, protectserver,
                                    timedelta(seconds=events_update_interval))

    try:
        nvr_info = await protectserver.server_information()
    except NotAuthorized:
        _LOGGER.error(
            "Could not Authorize against Unifi Protect. Please reinstall the Integration."
        )
        return False
    except (NvrError, ServerDisconnectedError) as notreadyerror:
        raise ConfigEntryNotReady from notreadyerror

    if entry.unique_id is None:
        hass.config_entries.async_update_entry(entry,
                                               unique_id=nvr_info[SERVER_ID])

    await protect_data.async_setup()
    if not protect_data.last_update_success:
        raise ConfigEntryNotReady

    update_listener = entry.add_update_listener(_async_options_updated)

    data = hass.data[DOMAIN][entry.entry_id] = {
        "protect_data": protect_data,
        "upv": protectserver,
        "snapshot_direct": entry.options.get(CONF_SNAPSHOT_DIRECT, False),
        "server_info": nvr_info,
        "update_listener": update_listener,
        "disable_stream": entry.options[CONF_DISABLE_RTSP],
    }

    async def _async_stop_protect_data(event):
        """Stop updates."""
        await protect_data.async_stop()

    data["stop_event_listener"] = hass.bus.async_listen_once(
        EVENT_HOMEASSISTANT_STOP, _async_stop_protect_data)

    await _async_get_or_create_nvr_device_in_registry(hass, entry, nvr_info)

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

    return True
Example #7
0
async def async_setup_entry(hass: HomeAssistantType, entry: ConfigEntry) -> bool:
    """Set up the Unifi Protect config entries."""

    if not entry.options:
        hass.config_entries.async_update_entry(
            entry,
            options={
                CONF_SCAN_INTERVAL: entry.data.get(
                    CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
                ),
                CONF_SNAPSHOT_DIRECT: entry.data.get(CONF_SNAPSHOT_DIRECT, False),
            },
        )

    session = async_create_clientsession(hass, cookie_jar=CookieJar(unsafe=True))
    protectserver = UpvServer(
        session,
        entry.data[CONF_HOST],
        entry.data[CONF_PORT],
        entry.data[CONF_USERNAME],
        entry.data[CONF_PASSWORD],
    )

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = protectserver
    _LOGGER.debug("Connect to Unfi Protect")

    events_update_interval = entry.options.get(
        CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL
    )

    protect_data = UnifiProtectData(
        hass, protectserver, timedelta(seconds=events_update_interval)
    )

    try:
        nvr_info = await protectserver.server_information()
    except NotAuthorized:
        _LOGGER.error(
            "Could not Authorize against Unifi Protect. Please reinstall the Integration."
        )
        return
    except (NvrError, ServerDisconnectedError) as notreadyerror:
        raise ConfigEntryNotReady from notreadyerror

    await protect_data.async_setup()

    update_listener = entry.add_update_listener(_async_options_updated)

    hass.data[DOMAIN][entry.entry_id] = {
        "protect_data": protect_data,
        "upv": protectserver,
        "snapshot_direct": entry.options.get(CONF_SNAPSHOT_DIRECT, False),
        "server_info": nvr_info,
        "update_listener": update_listener,
    }

    await _async_get_or_create_nvr_device_in_registry(hass, entry, nvr_info)

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

    return True
Example #8
0
async def async_setup_entry(hass: HomeAssistantType,
                            entry: ConfigEntry) -> bool:
    """Set up the Unifi Protect config entries."""

    if not entry.options:
        hass.config_entries.async_update_entry(
            entry,
            options={
                "scan_interval":
                entry.data.get(CONF_SCAN_INTERVAL, DEFAULT_SCAN_INTERVAL),
            },
        )

    session = async_create_clientsession(hass,
                                         cookie_jar=CookieJar(unsafe=True))
    protectserver = UpvServer(
        session,
        entry.data[CONF_HOST],
        entry.data[CONF_PORT],
        entry.data[CONF_USERNAME],
        entry.data[CONF_PASSWORD],
    )

    hass.data.setdefault(DOMAIN, {})[entry.entry_id] = protectserver
    _LOGGER.debug("Connect to Unfi Protect")

    events_update_interval = entry.options.get(CONF_SCAN_INTERVAL,
                                               DEFAULT_SCAN_INTERVAL)

    coordinator = DataUpdateCoordinator(
        hass,
        _LOGGER,
        name=DOMAIN,
        update_method=protectserver.update,
        update_interval=timedelta(seconds=events_update_interval),
    )

    try:
        nvr_info = await protectserver.server_information()
    except NotAuthorized:
        _LOGGER.error(
            "Could not Authorize against Unifi Protect. Please reinstall the Integration."
        )
        return
    except NvrError:
        raise ConfigEntryNotReady

    await coordinator.async_refresh()
    hass.data[DOMAIN][entry.entry_id] = {
        "coordinator": coordinator,
        "upv": protectserver,
    }

    await _async_get_or_create_nvr_device_in_registry(hass, entry, nvr_info)

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

    if not entry.update_listeners:
        entry.add_update_listener(async_update_options)

    return True
Example #9
0
async def test_upvserver_creation():
    """Test we can create the object."""

    upv = UpvServer(None, "127.0.0.1", 0, "username", "password")
    assert upv
Example #10
0
async def async_setup_entry(hass: HomeAssistantType,
                            entry: ConfigEntry) -> bool:
    """Set up the Unifi Protect config entries."""

    session = async_create_clientsession(hass,
                                         cookie_jar=CookieJar(unsafe=True))
    protectserver = UpvServer(
        session,
        entry.data[CONF_HOST],
        entry.data[CONF_PORT],
        entry.data[CONF_USERNAME],
        entry.data[CONF_PASSWORD],
    )

    unique_id = entry.data[CONF_ID]

    hass.data.setdefault(DOMAIN, {})[unique_id] = protectserver

    coordinator = DataUpdateCoordinator(
        hass,
        _LOGGER,
        name=DOMAIN,
        update_method=protectserver.update,
        update_interval=SCAN_INTERVAL,
    )
    # Fetch initial data so we have data when entities subscribe
    await coordinator.async_refresh()
    hass.data[DOMAIN][entry.data[CONF_ID]] = {
        "coordinator": coordinator,
        "upv": protectserver,
    }

    async def async_set_recording_mode(call):
        """Call Set Recording Mode."""
        await async_handle_set_recording_mode(
            hass, call, hass.data[DOMAIN][entry.data[CONF_ID]])

    async def async_save_thumbnail(call):
        """Call save video service handler."""
        await async_handle_save_thumbnail_service(
            hass, call, hass.data[DOMAIN][entry.data[CONF_ID]])

    async def async_set_ir_mode(call):
        """Call Set Infrared Mode."""
        await async_handle_set_ir_mode(hass, call,
                                       hass.data[DOMAIN][entry.data[CONF_ID]])

    hass.services.async_register(
        DOMAIN,
        SERVICE_SET_RECORDING_MODE,
        async_set_recording_mode,
        schema=SET_RECORDING_MODE_SCHEMA,
    )

    hass.services.async_register(
        DOMAIN,
        SERVICE_SAVE_THUMBNAIL,
        async_save_thumbnail,
        schema=SAVE_THUMBNAIL_SCHEMA,
    )
    hass.services.async_register(
        DOMAIN,
        SERVICE_SET_IR_MODE,
        async_set_ir_mode,
        schema=SET_IR_MODE_SCHEMA,
    )

    for platform in UNIFI_PROTECT_PLATFORMS:
        hass.async_create_task(
            hass.config_entries.async_forward_entry_setup(entry, platform))
    return True
Example #11
0
async def old_protect_client():
    client = UpvServer(None, "127.0.0.1", 0, "username", "password")
    yield await setup_client(client, MockWebsocket())
    await cleanup_client(client)