Ejemplo n.º 1
0
    async def async_step_user(
        self, user_input: dict[str, Any] | None = None
    ) -> FlowResult:
        """Handle a flow start."""
        # Supporting a single account.
        entries = self._async_current_entries()
        if entries:
            return self.async_abort(reason="single_instance_allowed")

        errors = {}

        if user_input is not None:
            username = user_input[CONF_USERNAME]
            password = user_input[CONF_PASSWORD]

            try:
                async with AqualinkClient(username, password):
                    pass
            except AqualinkServiceUnauthorizedException:
                errors["base"] = "invalid_auth"
            except AqualinkServiceException:
                errors["base"] = "cannot_connect"
            else:
                return self.async_create_entry(title=username, data=user_input)

        return self.async_show_form(
            step_id="user",
            data_schema=vol.Schema(
                {
                    vol.Required(CONF_USERNAME): str,
                    vol.Required(CONF_PASSWORD): str,
                }
            ),
            errors=errors,
        )
Ejemplo n.º 2
0
    async def test_context_manager_with_client(self) -> None:
        client = httpx.AsyncClient()
        async with AqualinkClient("user", "pass", httpx_client=client):
            pass

        # Clean up.
        await client.aclose()
Ejemplo n.º 3
0
    async def test_update_not_implemented(self) -> None:
        data = {"id": 1, "serial_number": "ABCDEFG", "device_type": "fake"}
        aqualink = AqualinkClient("user", "pass")
        system = AqualinkSystem(aqualink, data)

        with pytest.raises(NotImplementedError):
            await system.update()
Ejemplo n.º 4
0
    async def test_get_devices(self) -> None:
        data = {"id": 1, "serial_number": "ABCDEFG", "device_type": "fake"}
        aqualink = AqualinkClient("user", "pass")
        system = AqualinkSystem(aqualink, data)
        system.devices = {"foo": "bar"}

        with patch.object(system, "update") as mock_update:
            await system.get_devices()
            mock_update.assert_not_called()
Ejemplo n.º 5
0
    async def test_context_manager_with_session(self):
        session = aiohttp.ClientSession()
        async with AqualinkClient("user", "pass", session=session):
            pass

        # We passed the session so we're not closing the session automatically.
        assert session.closed is False

        # Clean up.
        await session.close()
Ejemplo n.º 6
0
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
    """Set up Aqualink from a config entry."""
    username = entry.data[CONF_USERNAME]
    password = entry.data[CONF_PASSWORD]

    hass.data.setdefault(DOMAIN, {})

    # These will contain the initialized devices
    binary_sensors = hass.data[DOMAIN][BINARY_SENSOR_DOMAIN] = []
    climates = hass.data[DOMAIN][CLIMATE_DOMAIN] = []
    lights = hass.data[DOMAIN][LIGHT_DOMAIN] = []
    sensors = hass.data[DOMAIN][SENSOR_DOMAIN] = []
    switches = hass.data[DOMAIN][SWITCH_DOMAIN] = []

    session = async_get_clientsession(hass)
    aqualink = AqualinkClient(username, password, session)
    try:
        await aqualink.login()
    except AqualinkServiceException as login_exception:
        _LOGGER.error("Failed to login: %s", login_exception)
        return False
    except (
            asyncio.TimeoutError,
            aiohttp.client_exceptions.ClientConnectorError,
    ) as aio_exception:
        raise ConfigEntryNotReady(
            f"Error while attempting login: {aio_exception}"
        ) from aio_exception

    try:
        systems = await aqualink.get_systems()
    except AqualinkServiceException as svc_exception:
        raise ConfigEntryNotReady(
            f"Error while attempting to retrieve systems list: {svc_exception}"
        ) from svc_exception

    systems = list(systems.values())
    if not systems:
        _LOGGER.error("No systems detected or supported")
        return False

    # Only supporting the first system for now.
    try:
        devices = await systems[0].get_devices()
    except AqualinkServiceException as svc_exception:
        raise ConfigEntryNotReady(
            f"Error while attempting to retrieve devices list: {svc_exception}"
        ) from svc_exception

    for dev in devices.values():
        if isinstance(dev, AqualinkThermostat):
            climates += [dev]
        elif isinstance(dev, AqualinkLight):
            lights += [dev]
        elif isinstance(dev, AqualinkBinarySensor):
            binary_sensors += [dev]
        elif isinstance(dev, AqualinkSensor):
            sensors += [dev]
        elif isinstance(dev, AqualinkToggle):
            switches += [dev]

    forward_setup = hass.config_entries.async_forward_entry_setup
    if binary_sensors:
        _LOGGER.debug("Got %s binary sensors: %s", len(binary_sensors),
                      binary_sensors)
        hass.async_create_task(forward_setup(entry, Platform.BINARY_SENSOR))
    if climates:
        _LOGGER.debug("Got %s climates: %s", len(climates), climates)
        hass.async_create_task(forward_setup(entry, Platform.CLIMATE))
    if lights:
        _LOGGER.debug("Got %s lights: %s", len(lights), lights)
        hass.async_create_task(forward_setup(entry, Platform.LIGHT))
    if sensors:
        _LOGGER.debug("Got %s sensors: %s", len(sensors), sensors)
        hass.async_create_task(forward_setup(entry, Platform.SENSOR))
    if switches:
        _LOGGER.debug("Got %s switches: %s", len(switches), switches)
        hass.async_create_task(forward_setup(entry, Platform.SWITCH))

    async def _async_systems_update(now):
        """Refresh internal state for all systems."""
        prev = systems[0].online

        try:
            await systems[0].update()
        except AqualinkServiceException as svc_exception:
            if prev is not None:
                _LOGGER.warning("Failed to refresh iAqualink state: %s",
                                svc_exception)
        else:
            cur = systems[0].online
            if cur is True and prev is not True:
                _LOGGER.warning("Reconnected to iAqualink")

        async_dispatcher_send(hass, DOMAIN)

    async_track_time_interval(hass, _async_systems_update, UPDATE_INTERVAL)

    return True
Ejemplo n.º 7
0
 def setUp(self) -> None:
     self.aqualink = AqualinkClient("foo", "bar")
Ejemplo n.º 8
0
def client_fixture():
    """Create client fixture."""
    return AqualinkClient(username=MOCK_USERNAME, password=MOCK_PASSWORD)
Ejemplo n.º 9
0
    def setUp(self) -> None:
        super().setUp()

        self.client = AqualinkClient("foo", "bar")
        self.addAsyncCleanup(self.client.close)
Ejemplo n.º 10
0
 def setUp(self) -> None:
     self.aqualink = AqualinkClient("user", "pass")