Add Ridwell integration (#57590)

This commit is contained in:
Aaron Bach 2021-10-30 08:27:48 -06:00 committed by GitHub
parent aacc009cbb
commit f7dea3aa1d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 548 additions and 0 deletions

View File

@ -871,6 +871,8 @@ omit =
homeassistant/components/remote_rpi_gpio/*
homeassistant/components/rest/notify.py
homeassistant/components/rest/switch.py
homeassistant/components/ridwell/__init__.py
homeassistant/components/ridwell/sensor.py
homeassistant/components/ring/camera.py
homeassistant/components/ripple/sensor.py
homeassistant/components/rocketchat/notify.py

View File

@ -101,6 +101,7 @@ homeassistant.components.recorder.repack
homeassistant.components.recorder.statistics
homeassistant.components.remote.*
homeassistant.components.renault.*
homeassistant.components.ridwell.*
homeassistant.components.rituals_perfume_genie.*
homeassistant.components.rpi_power.*
homeassistant.components.samsungtv.*

View File

@ -431,6 +431,7 @@ homeassistant/components/renault/* @epenet
homeassistant/components/repetier/* @MTrab
homeassistant/components/rflink/* @javicalle
homeassistant/components/rfxtrx/* @danielhiversen @elupus @RobBie1221
homeassistant/components/ridwell/* @bachya
homeassistant/components/ring/* @balloob
homeassistant/components/risco/* @OnFreund
homeassistant/components/rituals_perfume_genie/* @milanmeu

View File

@ -0,0 +1,84 @@
"""The Ridwell integration."""
from __future__ import annotations
import asyncio
from datetime import timedelta
from aioridwell import async_get_client
from aioridwell.client import RidwellAccount, RidwellPickupEvent
from aioridwell.errors import InvalidCredentialsError, RidwellError
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.helpers import aiohttp_client
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DATA_ACCOUNT, DATA_COORDINATOR, DOMAIN, LOGGER
DEFAULT_UPDATE_INTERVAL = timedelta(hours=1)
PLATFORMS: list[str] = ["sensor"]
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up Ridwell from a config entry."""
hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = {}
session = aiohttp_client.async_get_clientsession(hass)
try:
client = await async_get_client(
entry.data[CONF_USERNAME], entry.data[CONF_PASSWORD], session=session
)
except InvalidCredentialsError as err:
raise ConfigEntryAuthFailed("Invalid username/password") from err
except RidwellError as err:
raise ConfigEntryNotReady(err) from err
accounts = await client.async_get_accounts()
async def async_update_data() -> dict[str, RidwellPickupEvent]:
"""Get the latest pickup events."""
data = {}
async def async_get_pickups(account: RidwellAccount) -> None:
"""Get the latest pickups for an account."""
data[account.account_id] = await account.async_get_next_pickup_event()
tasks = [async_get_pickups(account) for account in accounts.values()]
results = await asyncio.gather(*tasks, return_exceptions=True)
for result in results:
if isinstance(result, InvalidCredentialsError):
raise ConfigEntryAuthFailed("Invalid username/password") from result
if isinstance(result, RidwellError):
raise UpdateFailed(result) from result
return data
coordinator = DataUpdateCoordinator(
hass,
LOGGER,
name=entry.title,
update_interval=DEFAULT_UPDATE_INTERVAL,
update_method=async_update_data,
)
await coordinator.async_config_entry_first_refresh()
hass.data[DOMAIN][entry.entry_id][DATA_ACCOUNT] = accounts
hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR] = coordinator
hass.config_entries.async_setup_platforms(entry, PLATFORMS)
return True
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Unload a config entry."""
unload_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if unload_ok:
hass.data[DOMAIN].pop(entry.entry_id)
return unload_ok

View File

@ -0,0 +1,132 @@
"""Config flow for Ridwell integration."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from aioridwell import async_get_client
from aioridwell.errors import InvalidCredentialsError, RidwellError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import callback
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers import aiohttp_client, config_validation as cv
from homeassistant.helpers.typing import ConfigType
from .const import DOMAIN, LOGGER
STEP_REAUTH_CONFIRM_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_PASSWORD): cv.string,
}
)
STEP_USER_DATA_SCHEMA = vol.Schema(
{
vol.Required(CONF_USERNAME): cv.string,
vol.Required(CONF_PASSWORD): cv.string,
}
)
class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
"""Handle a config flow for WattTime."""
VERSION = 1
def __init__(self) -> None:
"""Initialize."""
self._password: str | None = None
self._reauthing: bool = False
self._username: str | None = None
@callback
def _async_show_errors(
self, errors: dict, error_step_id: str, error_schema: vol.Schema
) -> FlowResult:
"""Show an error on the correct form."""
return self.async_show_form(
step_id=error_step_id,
data_schema=error_schema,
errors=errors,
description_placeholders={CONF_USERNAME: self._username},
)
async def _async_validate(
self, error_step_id: str, error_schema: vol.Schema
) -> FlowResult:
"""Validate input credentials and proceed accordingly."""
session = aiohttp_client.async_get_clientsession(self.hass)
if TYPE_CHECKING:
assert self._password
assert self._username
try:
await async_get_client(self._username, self._password, session=session)
except InvalidCredentialsError:
return self._async_show_errors(
{"base": "invalid_auth"}, error_step_id, error_schema
)
except RidwellError as err:
LOGGER.error("Unknown Ridwell error: %s", err)
return self._async_show_errors(
{"base": "unknown"}, error_step_id, error_schema
)
if self._reauthing:
if existing_entry := await self.async_set_unique_id(self._username):
self.hass.config_entries.async_update_entry(
existing_entry,
data={**existing_entry.data, CONF_PASSWORD: self._password},
)
self.hass.async_create_task(
self.hass.config_entries.async_reload(existing_entry.entry_id)
)
return self.async_abort(reason="reauth_successful")
return self.async_create_entry(
title=self._username,
data={CONF_USERNAME: self._username, CONF_PASSWORD: self._password},
)
async def async_step_reauth(self, config: ConfigType) -> FlowResult:
"""Handle configuration by re-auth."""
self._reauthing = True
self._username = config[CONF_USERNAME]
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle re-auth completion."""
if not user_input:
return self.async_show_form(
step_id="reauth_confirm",
data_schema=STEP_REAUTH_CONFIRM_DATA_SCHEMA,
description_placeholders={CONF_USERNAME: self._username},
)
self._password = user_input[CONF_PASSWORD]
return await self._async_validate(
"reauth_confirm", STEP_REAUTH_CONFIRM_DATA_SCHEMA
)
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step."""
if not user_input:
return self.async_show_form(
step_id="user", data_schema=STEP_USER_DATA_SCHEMA
)
await self.async_set_unique_id(user_input[CONF_USERNAME].lower())
self._abort_if_unique_id_configured()
self._username = user_input[CONF_USERNAME]
self._password = user_input[CONF_PASSWORD]
return await self._async_validate("user", STEP_USER_DATA_SCHEMA)

View File

@ -0,0 +1,9 @@
"""Constants for the Ridwell integration."""
import logging
DOMAIN = "ridwell"
LOGGER = logging.getLogger(__package__)
DATA_ACCOUNT = "account"
DATA_COORDINATOR = "coordinator"

View File

@ -0,0 +1,13 @@
{
"domain": "ridwell",
"name": "Ridwell",
"config_flow": true,
"documentation": "https://www.home-assistant.io/integrations/ridwell",
"requirements": [
"aioridwell==0.2.0"
],
"codeowners": [
"@bachya"
],
"iot_class": "cloud_polling"
}

View File

@ -0,0 +1,93 @@
"""Support for Ridwell sensors."""
from __future__ import annotations
from collections.abc import Mapping
from datetime import date, datetime
from typing import Any
from aioridwell.client import RidwellAccount
from homeassistant.components.sensor import SensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import ATTR_ATTRIBUTION, DEVICE_CLASS_TIMESTAMP
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import StateType
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
)
from homeassistant.util.dt import as_utc
from .const import DATA_ACCOUNT, DATA_COORDINATOR, DOMAIN
ATTR_CATEGORY = "category"
ATTR_PICKUP_STATE = "pickup_state"
ATTR_PICKUP_TYPES = "pickup_types"
ATTR_QUANTITY = "quantity"
DEFAULT_ATTRIBUTION = "Pickup data provided by Ridwell"
@callback
def async_get_utc_midnight(target_date: date) -> datetime:
"""Get UTC midnight for a given date."""
return as_utc(datetime.combine(target_date, datetime.min.time()))
async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
"""Set up WattTime sensors based on a config entry."""
accounts = hass.data[DOMAIN][entry.entry_id][DATA_ACCOUNT]
coordinator = hass.data[DOMAIN][entry.entry_id][DATA_COORDINATOR]
async_add_entities(
[RidwellSensor(coordinator, account) for account in accounts.values()]
)
class RidwellSensor(CoordinatorEntity, SensorEntity):
"""Define a Ridwell pickup sensor."""
_attr_device_class = DEVICE_CLASS_TIMESTAMP
def __init__(
self, coordinator: DataUpdateCoordinator, account: RidwellAccount
) -> None:
"""Initialize the sensor."""
super().__init__(coordinator)
self._account = account
self._attr_name = f"Ridwell Pickup ({account.address['street1']})"
self._attr_unique_id = account.account_id
@property
def extra_state_attributes(self) -> Mapping[str, Any]:
"""Return entity specific state attributes."""
event = self.coordinator.data[self._account.account_id]
attrs: dict[str, Any] = {
ATTR_ATTRIBUTION: DEFAULT_ATTRIBUTION,
ATTR_PICKUP_TYPES: {},
ATTR_PICKUP_STATE: event.state,
}
for pickup in event.pickups:
if pickup.name not in attrs[ATTR_PICKUP_TYPES]:
attrs[ATTR_PICKUP_TYPES][pickup.name] = {
ATTR_CATEGORY: pickup.category,
ATTR_QUANTITY: pickup.quantity,
}
else:
# Ridwell's API will return distinct objects, even if they have the
# same name (e.g. two pickups of Latex Paint will show up as two
# objects) so, we sum the quantities:
attrs[ATTR_PICKUP_TYPES][pickup.name]["quantity"] += pickup.quantity
return attrs
@property
def native_value(self) -> StateType:
"""Return the value reported by the sensor."""
event = self.coordinator.data[self._account.account_id]
return async_get_utc_midnight(event.pickup_date).isoformat()

View File

@ -0,0 +1,28 @@
{
"config": {
"step": {
"reauth_confirm": {
"title": "[%key:common::config_flow::title::reauth%]",
"description": "Please re-enter the password for {username}:",
"data": {
"password": "[%key:common::config_flow::data::password%]"
}
},
"user": {
"description": "Input your username and password:",
"data": {
"username": "[%key:common::config_flow::data::username%]",
"password": "[%key:common::config_flow::data::password%]"
}
}
},
"error": {
"invalid_auth": "[%key:common::config_flow::error::invalid_auth%]",
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]"
}
}
}

View File

@ -0,0 +1,28 @@
{
"config": {
"abort": {
"already_configured": "Device is already configured",
"reauth_successful": "Re-authentication was successful"
},
"error": {
"invalid_auth": "Invalid authentication",
"unknown": "Unexpected error"
},
"step": {
"reauth_confirm": {
"data": {
"password": "Password"
},
"description": "Please re-enter the password for {username}:",
"title": "Reauthenticate Integration"
},
"user": {
"data": {
"password": "Password",
"username": "Username"
},
"description": "Input your username and password:"
}
}
}
}

View File

@ -238,6 +238,7 @@ FLOWS = [
"recollect_waste",
"renault",
"rfxtrx",
"ridwell",
"ring",
"risco",
"rituals_perfume_genie",

View File

@ -1122,6 +1122,17 @@ no_implicit_optional = true
warn_return_any = true
warn_unreachable = true
[mypy-homeassistant.components.ridwell.*]
check_untyped_defs = true
disallow_incomplete_defs = true
disallow_subclassing_any = true
disallow_untyped_calls = true
disallow_untyped_decorators = true
disallow_untyped_defs = true
no_implicit_optional = true
warn_return_any = true
warn_unreachable = true
[mypy-homeassistant.components.rituals_perfume_genie.*]
check_untyped_defs = true
disallow_incomplete_defs = true

View File

@ -242,6 +242,9 @@ aiopylgtv==0.4.0
# homeassistant.components.recollect_waste
aiorecollect==1.0.8
# homeassistant.components.ridwell
aioridwell==0.2.0
# homeassistant.components.shelly
aioshelly==1.0.2

View File

@ -169,6 +169,9 @@ aiopylgtv==0.4.0
# homeassistant.components.recollect_waste
aiorecollect==1.0.8
# homeassistant.components.ridwell
aioridwell==0.2.0
# homeassistant.components.shelly
aioshelly==1.0.2

View File

@ -0,0 +1 @@
"""Tests for the Ridwell integration."""

View File

@ -0,0 +1,138 @@
"""Test the Ridwell config flow."""
from unittest.mock import AsyncMock, patch
from aioridwell.errors import InvalidCredentialsError, RidwellError
import pytest
from homeassistant import config_entries
from homeassistant.components.ridwell.const import DOMAIN
from homeassistant.const import CONF_PASSWORD, CONF_USERNAME
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import (
RESULT_TYPE_ABORT,
RESULT_TYPE_CREATE_ENTRY,
RESULT_TYPE_FORM,
)
from tests.common import MockConfigEntry
@pytest.fixture(name="client")
def client_fixture():
"""Define a fixture for an aioridwell client."""
return AsyncMock(return_value=None)
@pytest.fixture(name="client_login")
def client_login_fixture(client):
"""Define a fixture for patching the aioridwell coroutine to get a client."""
with patch(
"homeassistant.components.ridwell.config_flow.async_get_client"
) as mock_client:
mock_client.side_effect = client
yield mock_client
async def test_duplicate_error(hass: HomeAssistant):
"""Test that errors are shown when duplicate entries are added."""
MockConfigEntry(
domain=DOMAIN,
unique_id="user@email.com",
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
).add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "already_configured"
async def test_show_form_user(hass: HomeAssistant) -> None:
"""Test showing the form to input credentials."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == RESULT_TYPE_FORM
assert result["step_id"] == "user"
assert result["errors"] is None
async def test_step_reauth(hass: HomeAssistant, client_login) -> None:
"""Test a full reauth flow."""
MockConfigEntry(
domain=DOMAIN,
unique_id="user@email.com",
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
).add_to_hass(hass)
with patch(
"homeassistant.components.ridwell.async_setup_entry",
return_value=True,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_REAUTH},
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input={CONF_PASSWORD: "password"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_ABORT
assert result["reason"] == "reauth_successful"
assert len(hass.config_entries.async_entries()) == 1
async def test_step_user(hass: HomeAssistant, client_login) -> None:
"""Test that the full user step succeeds."""
with patch(
"homeassistant.components.ridwell.async_setup_entry",
return_value=True,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
await hass.async_block_till_done()
assert result["type"] == RESULT_TYPE_CREATE_ENTRY
@pytest.mark.parametrize(
"client",
[AsyncMock(side_effect=InvalidCredentialsError)],
)
async def test_step_user_invalid_credentials(hass: HomeAssistant, client_login) -> None:
"""Test that invalid credentials are handled correctly."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {"base": "invalid_auth"}
@pytest.mark.parametrize(
"client",
[AsyncMock(side_effect=RidwellError)],
)
async def test_step_user_unknown_error(hass: HomeAssistant, client_login) -> None:
"""Test that an unknown Ridwell error is handled correctly."""
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_USER},
data={CONF_USERNAME: "user@email.com", CONF_PASSWORD: "password"},
)
assert result["type"] == RESULT_TYPE_FORM
assert result["errors"] == {"base": "unknown"}