Improve type hint in foobot sensor entity (#77164)

This commit is contained in:
epenet 2022-08-26 10:33:17 +02:00 committed by GitHub
parent 3031caafed
commit 8896229ea6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 21 additions and 30 deletions

View File

@ -4,6 +4,7 @@ from __future__ import annotations
import asyncio import asyncio
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Any
import aiohttp import aiohttp
from foobot_async import FoobotClient from foobot_async import FoobotClient
@ -16,7 +17,6 @@ from homeassistant.components.sensor import (
) )
from homeassistant.const import ( from homeassistant.const import (
ATTR_TEMPERATURE, ATTR_TEMPERATURE,
ATTR_TIME,
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER, CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
CONCENTRATION_PARTS_PER_BILLION, CONCENTRATION_PARTS_PER_BILLION,
CONCENTRATION_PARTS_PER_MILLION, CONCENTRATION_PARTS_PER_MILLION,
@ -24,14 +24,12 @@ from homeassistant.const import (
CONF_USERNAME, CONF_USERNAME,
PERCENTAGE, PERCENTAGE,
TEMP_CELSIUS, TEMP_CELSIUS,
TIME_SECONDS,
) )
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import PlatformNotReady from homeassistant.exceptions import PlatformNotReady
from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA from homeassistant.helpers.config_validation import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
from homeassistant.util import Throttle from homeassistant.util import Throttle
@ -45,11 +43,6 @@ ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC"
ATTR_FOOBOT_INDEX = "index" ATTR_FOOBOT_INDEX = "index"
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = ( SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
SensorEntityDescription(
key="time",
name=ATTR_TIME,
native_unit_of_measurement=TIME_SECONDS,
),
SensorEntityDescription( SensorEntityDescription(
key="pm", key="pm",
name=ATTR_PM2_5, name=ATTR_PM2_5,
@ -105,15 +98,15 @@ async def async_setup_platform(
discovery_info: DiscoveryInfoType | None = None, discovery_info: DiscoveryInfoType | None = None,
) -> None: ) -> None:
"""Set up the devices associated with the account.""" """Set up the devices associated with the account."""
token = config.get(CONF_TOKEN) token: str = config[CONF_TOKEN]
username = config.get(CONF_USERNAME) username: str = config[CONF_USERNAME]
client = FoobotClient( client = FoobotClient(
token, username, async_get_clientsession(hass), timeout=TIMEOUT token, username, async_get_clientsession(hass), timeout=TIMEOUT
) )
entities = [] entities: list[FoobotSensor] = []
try: try:
devices = await client.get_devices() devices: list[dict[str, Any]] = await client.get_devices()
_LOGGER.debug("The following devices were found: %s", devices) _LOGGER.debug("The following devices were found: %s", devices)
for device in devices: for device in devices:
foobot_data = FoobotData(client, device["uuid"]) foobot_data = FoobotData(client, device["uuid"])
@ -121,7 +114,6 @@ async def async_setup_platform(
[ [
FoobotSensor(foobot_data, device, description) FoobotSensor(foobot_data, device, description)
for description in SENSOR_TYPES for description in SENSOR_TYPES
if description.key != "time"
] ]
) )
except ( except (
@ -141,7 +133,12 @@ async def async_setup_platform(
class FoobotSensor(SensorEntity): class FoobotSensor(SensorEntity):
"""Implementation of a Foobot sensor.""" """Implementation of a Foobot sensor."""
def __init__(self, data, device, description: SensorEntityDescription): def __init__(
self,
data: FoobotData,
device: dict[str, Any],
description: SensorEntityDescription,
) -> None:
"""Initialize the sensor.""" """Initialize the sensor."""
self.entity_description = description self.entity_description = description
self.foobot_data = data self.foobot_data = data
@ -150,34 +147,30 @@ class FoobotSensor(SensorEntity):
self._attr_unique_id = f"{device['uuid']}_{description.key}" self._attr_unique_id = f"{device['uuid']}_{description.key}"
@property @property
def native_value(self): def native_value(self) -> float | None:
"""Return the state of the device.""" """Return the state of the device."""
try: return self.foobot_data.data.get(self.entity_description.key)
data = self.foobot_data.data[self.entity_description.key]
except (KeyError, TypeError):
data = None
return data
async def async_update(self) -> None: async def async_update(self) -> None:
"""Get the latest data.""" """Get the latest data."""
await self.foobot_data.async_update() await self.foobot_data.async_update()
class FoobotData(Entity): class FoobotData:
"""Get data from Foobot API.""" """Get data from Foobot API."""
def __init__(self, client, uuid): def __init__(self, client: FoobotClient, uuid: str) -> None:
"""Initialize the data object.""" """Initialize the data object."""
self._client = client self._client = client
self._uuid = uuid self._uuid = uuid
self.data = {} self.data: dict[str, float] = {}
@Throttle(SCAN_INTERVAL) @Throttle(SCAN_INTERVAL)
async def async_update(self): async def async_update(self) -> bool:
"""Get the data from Foobot API.""" """Get the data from Foobot API."""
interval = SCAN_INTERVAL.total_seconds() interval = SCAN_INTERVAL.total_seconds()
try: try:
response = await self._client.get_last_data( response: list[dict[str, Any]] = await self._client.get_last_data(
self._uuid, interval, interval + 1 self._uuid, interval, interval + 1
) )
except ( except (

View File

@ -64,9 +64,7 @@ async def test_setup_timeout_error(hass, aioclient_mock):
re.compile("api.foobot.io/v2/owner/.*"), exc=asyncio.TimeoutError() re.compile("api.foobot.io/v2/owner/.*"), exc=asyncio.TimeoutError()
) )
with pytest.raises(PlatformNotReady): with pytest.raises(PlatformNotReady):
await foobot.async_setup_platform( await foobot.async_setup_platform(hass, VALID_CONFIG, fake_async_add_entities)
hass, {"sensor": VALID_CONFIG}, fake_async_add_entities
)
async def test_setup_permanent_error(hass, aioclient_mock): async def test_setup_permanent_error(hass, aioclient_mock):
@ -77,7 +75,7 @@ async def test_setup_permanent_error(hass, aioclient_mock):
for error in errors: for error in errors:
aioclient_mock.get(re.compile("api.foobot.io/v2/owner/.*"), status=error) aioclient_mock.get(re.compile("api.foobot.io/v2/owner/.*"), status=error)
result = await foobot.async_setup_platform( result = await foobot.async_setup_platform(
hass, {"sensor": VALID_CONFIG}, fake_async_add_entities hass, VALID_CONFIG, fake_async_add_entities
) )
assert result is None assert result is None
@ -91,5 +89,5 @@ async def test_setup_temporary_error(hass, aioclient_mock):
aioclient_mock.get(re.compile("api.foobot.io/v2/owner/.*"), status=error) aioclient_mock.get(re.compile("api.foobot.io/v2/owner/.*"), status=error)
with pytest.raises(PlatformNotReady): with pytest.raises(PlatformNotReady):
await foobot.async_setup_platform( await foobot.async_setup_platform(
hass, {"sensor": VALID_CONFIG}, fake_async_add_entities hass, VALID_CONFIG, fake_async_add_entities
) )