mirror of
https://github.com/home-assistant/core.git
synced 2025-04-25 01:38:02 +00:00
Improve type hint in foobot sensor entity (#77164)
This commit is contained in:
parent
3031caafed
commit
8896229ea6
@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
import asyncio
|
||||
from datetime import timedelta
|
||||
import logging
|
||||
from typing import Any
|
||||
|
||||
import aiohttp
|
||||
from foobot_async import FoobotClient
|
||||
@ -16,7 +17,6 @@ from homeassistant.components.sensor import (
|
||||
)
|
||||
from homeassistant.const import (
|
||||
ATTR_TEMPERATURE,
|
||||
ATTR_TIME,
|
||||
CONCENTRATION_MICROGRAMS_PER_CUBIC_METER,
|
||||
CONCENTRATION_PARTS_PER_BILLION,
|
||||
CONCENTRATION_PARTS_PER_MILLION,
|
||||
@ -24,14 +24,12 @@ from homeassistant.const import (
|
||||
CONF_USERNAME,
|
||||
PERCENTAGE,
|
||||
TEMP_CELSIUS,
|
||||
TIME_SECONDS,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.exceptions import PlatformNotReady
|
||||
from homeassistant.helpers.aiohttp_client import async_get_clientsession
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from homeassistant.helpers.config_validation import PLATFORM_SCHEMA
|
||||
from homeassistant.helpers.entity import Entity
|
||||
from homeassistant.helpers.entity_platform import AddEntitiesCallback
|
||||
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
|
||||
from homeassistant.util import Throttle
|
||||
@ -45,11 +43,6 @@ ATTR_VOLATILE_ORGANIC_COMPOUNDS = "VOC"
|
||||
ATTR_FOOBOT_INDEX = "index"
|
||||
|
||||
SENSOR_TYPES: tuple[SensorEntityDescription, ...] = (
|
||||
SensorEntityDescription(
|
||||
key="time",
|
||||
name=ATTR_TIME,
|
||||
native_unit_of_measurement=TIME_SECONDS,
|
||||
),
|
||||
SensorEntityDescription(
|
||||
key="pm",
|
||||
name=ATTR_PM2_5,
|
||||
@ -105,15 +98,15 @@ async def async_setup_platform(
|
||||
discovery_info: DiscoveryInfoType | None = None,
|
||||
) -> None:
|
||||
"""Set up the devices associated with the account."""
|
||||
token = config.get(CONF_TOKEN)
|
||||
username = config.get(CONF_USERNAME)
|
||||
token: str = config[CONF_TOKEN]
|
||||
username: str = config[CONF_USERNAME]
|
||||
|
||||
client = FoobotClient(
|
||||
token, username, async_get_clientsession(hass), timeout=TIMEOUT
|
||||
)
|
||||
entities = []
|
||||
entities: list[FoobotSensor] = []
|
||||
try:
|
||||
devices = await client.get_devices()
|
||||
devices: list[dict[str, Any]] = await client.get_devices()
|
||||
_LOGGER.debug("The following devices were found: %s", devices)
|
||||
for device in devices:
|
||||
foobot_data = FoobotData(client, device["uuid"])
|
||||
@ -121,7 +114,6 @@ async def async_setup_platform(
|
||||
[
|
||||
FoobotSensor(foobot_data, device, description)
|
||||
for description in SENSOR_TYPES
|
||||
if description.key != "time"
|
||||
]
|
||||
)
|
||||
except (
|
||||
@ -141,7 +133,12 @@ async def async_setup_platform(
|
||||
class FoobotSensor(SensorEntity):
|
||||
"""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."""
|
||||
self.entity_description = description
|
||||
self.foobot_data = data
|
||||
@ -150,34 +147,30 @@ class FoobotSensor(SensorEntity):
|
||||
self._attr_unique_id = f"{device['uuid']}_{description.key}"
|
||||
|
||||
@property
|
||||
def native_value(self):
|
||||
def native_value(self) -> float | None:
|
||||
"""Return the state of the device."""
|
||||
try:
|
||||
data = self.foobot_data.data[self.entity_description.key]
|
||||
except (KeyError, TypeError):
|
||||
data = None
|
||||
return data
|
||||
return self.foobot_data.data.get(self.entity_description.key)
|
||||
|
||||
async def async_update(self) -> None:
|
||||
"""Get the latest data."""
|
||||
await self.foobot_data.async_update()
|
||||
|
||||
|
||||
class FoobotData(Entity):
|
||||
class FoobotData:
|
||||
"""Get data from Foobot API."""
|
||||
|
||||
def __init__(self, client, uuid):
|
||||
def __init__(self, client: FoobotClient, uuid: str) -> None:
|
||||
"""Initialize the data object."""
|
||||
self._client = client
|
||||
self._uuid = uuid
|
||||
self.data = {}
|
||||
self.data: dict[str, float] = {}
|
||||
|
||||
@Throttle(SCAN_INTERVAL)
|
||||
async def async_update(self):
|
||||
async def async_update(self) -> bool:
|
||||
"""Get the data from Foobot API."""
|
||||
interval = SCAN_INTERVAL.total_seconds()
|
||||
try:
|
||||
response = await self._client.get_last_data(
|
||||
response: list[dict[str, Any]] = await self._client.get_last_data(
|
||||
self._uuid, interval, interval + 1
|
||||
)
|
||||
except (
|
||||
|
@ -64,9 +64,7 @@ async def test_setup_timeout_error(hass, aioclient_mock):
|
||||
re.compile("api.foobot.io/v2/owner/.*"), exc=asyncio.TimeoutError()
|
||||
)
|
||||
with pytest.raises(PlatformNotReady):
|
||||
await foobot.async_setup_platform(
|
||||
hass, {"sensor": VALID_CONFIG}, fake_async_add_entities
|
||||
)
|
||||
await foobot.async_setup_platform(hass, VALID_CONFIG, fake_async_add_entities)
|
||||
|
||||
|
||||
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:
|
||||
aioclient_mock.get(re.compile("api.foobot.io/v2/owner/.*"), status=error)
|
||||
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
|
||||
|
||||
@ -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)
|
||||
with pytest.raises(PlatformNotReady):
|
||||
await foobot.async_setup_platform(
|
||||
hass, {"sensor": VALID_CONFIG}, fake_async_add_entities
|
||||
hass, VALID_CONFIG, fake_async_add_entities
|
||||
)
|
||||
|
Loading…
x
Reference in New Issue
Block a user