Code improvements to trafikverket_weatherstation (#62854)

* Code cleanup

* Fix extra state attributes

* Fix review comments

* Fix precipitation_amount if None

* Fix sensors returning None

* Use const for sensors reporting None
This commit is contained in:
G Johansson 2022-01-06 16:33:06 +01:00 committed by GitHub
parent c341adb0d6
commit 3950933514
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 42 additions and 28 deletions

View File

@ -958,8 +958,8 @@ tests/components/trace/* @home-assistant/core
homeassistant/components/tractive/* @Danielhiversen @zhulik @bieniu homeassistant/components/tractive/* @Danielhiversen @zhulik @bieniu
tests/components/tractive/* @Danielhiversen @zhulik @bieniu tests/components/tractive/* @Danielhiversen @zhulik @bieniu
homeassistant/components/trafikverket_train/* @endor-force homeassistant/components/trafikverket_train/* @endor-force
homeassistant/components/trafikverket_weatherstation/* @endor-force homeassistant/components/trafikverket_weatherstation/* @endor-force @gjohansson-ST
tests/components/trafikverket_weatherstation/* @endor-force tests/components/trafikverket_weatherstation/* @endor-force @gjohansson-ST
homeassistant/components/transmission/* @engrbm87 @JPHutchins homeassistant/components/transmission/* @engrbm87 @JPHutchins
tests/components/transmission/* @engrbm87 @JPHutchins tests/components/transmission/* @engrbm87 @JPHutchins
homeassistant/components/tts/* @pvizeli homeassistant/components/tts/* @pvizeli

View File

@ -1,11 +1,14 @@
"""Adds config flow for Trafikverket Weather integration.""" """Adds config flow for Trafikverket Weather integration."""
from __future__ import annotations from __future__ import annotations
from typing import Any
from pytrafikverket.trafikverket_weather import TrafikverketWeather from pytrafikverket.trafikverket_weather import TrafikverketWeather
import voluptuous as vol import voluptuous as vol
from homeassistant import config_entries from homeassistant import config_entries
from homeassistant.const import CONF_API_KEY from homeassistant.const import CONF_API_KEY
from homeassistant.data_entry_flow import FlowResult
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
@ -36,7 +39,7 @@ class TVWeatherConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
return str(err) return str(err)
return "connected" return "connected"
async def async_step_import(self, config: dict): async def async_step_import(self, config: dict[str, Any]) -> FlowResult:
"""Import a configuration from config.yaml.""" """Import a configuration from config.yaml."""
self.context.update( self.context.update(
@ -46,7 +49,9 @@ class TVWeatherConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
self._async_abort_entries_match({CONF_STATION: config[CONF_STATION]}) self._async_abort_entries_match({CONF_STATION: config[CONF_STATION]})
return await self.async_step_user(user_input=config) return await self.async_step_user(user_input=config)
async def async_step_user(self, user_input=None): async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> FlowResult:
"""Handle the initial step.""" """Handle the initial step."""
errors = {} errors = {}

View File

@ -7,3 +7,13 @@ PLATFORMS = [Platform.SENSOR]
ATTRIBUTION = "Data provided by Trafikverket" ATTRIBUTION = "Data provided by Trafikverket"
ATTR_MEASURE_TIME = "measure_time" ATTR_MEASURE_TIME = "measure_time"
ATTR_ACTIVE = "active" ATTR_ACTIVE = "active"
NONE_IS_ZERO_SENSORS = {
"air_temp",
"road_temp",
"wind_direction",
"wind_speed",
"wind_speed_max",
"humidity",
"precipitation_amount",
}

View File

@ -3,7 +3,7 @@
"name": "Trafikverket Weather Station", "name": "Trafikverket Weather Station",
"documentation": "https://www.home-assistant.io/integrations/trafikverket_weatherstation", "documentation": "https://www.home-assistant.io/integrations/trafikverket_weatherstation",
"requirements": ["pytrafikverket==0.1.6.2"], "requirements": ["pytrafikverket==0.1.6.2"],
"codeowners": ["@endor-force"], "codeowners": ["@endor-force", "@gjohansson-ST"],
"config_flow": true, "config_flow": true,
"iot_class": "cloud_polling" "iot_class": "cloud_polling"
} }

View File

@ -5,7 +5,6 @@ import asyncio
from dataclasses import dataclass from dataclasses import dataclass
from datetime import timedelta from datetime import timedelta
import logging import logging
from typing import Any
import aiohttp import aiohttp
from pytrafikverket.trafikverket_weather import TrafikverketWeather, WeatherStationInfo from pytrafikverket.trafikverket_weather import TrafikverketWeather, WeatherStationInfo
@ -20,7 +19,6 @@ from homeassistant.components.sensor import (
) )
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import ( from homeassistant.const import (
ATTR_ATTRIBUTION,
CONF_API_KEY, CONF_API_KEY,
CONF_MONITORED_CONDITIONS, CONF_MONITORED_CONDITIONS,
CONF_NAME, CONF_NAME,
@ -37,7 +35,14 @@ 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
from .const import ATTR_ACTIVE, ATTR_MEASURE_TIME, ATTRIBUTION, CONF_STATION, DOMAIN from .const import (
ATTR_ACTIVE,
ATTR_MEASURE_TIME,
ATTRIBUTION,
CONF_STATION,
DOMAIN,
NONE_IS_ZERO_SENSORS,
)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -198,6 +203,7 @@ class TrafikverketWeatherStation(SensorEntity):
"""Representation of a Trafikverket sensor.""" """Representation of a Trafikverket sensor."""
entity_description: TrafikverketSensorEntityDescription entity_description: TrafikverketSensorEntityDescription
_attr_attribution = ATTRIBUTION
def __init__( def __init__(
self, self,
@ -213,32 +219,25 @@ class TrafikverketWeatherStation(SensorEntity):
self._station = sensor_station self._station = sensor_station
self._weather_api = weather_api self._weather_api = weather_api
self._weather: WeatherStationInfo | None = None self._weather: WeatherStationInfo | None = None
self._active: bool | None = None
self._measure_time: str | None = None
@property
def extra_state_attributes(self) -> dict[str, Any]:
"""Return the state attributes of Trafikverket Weatherstation."""
_additional_attributes: dict[str, Any] = {
ATTR_ATTRIBUTION: ATTRIBUTION,
}
if self._active:
_additional_attributes[ATTR_ACTIVE] = self._active
if self._measure_time:
_additional_attributes[ATTR_MEASURE_TIME] = self._measure_time
return _additional_attributes
@Throttle(MIN_TIME_BETWEEN_UPDATES) @Throttle(MIN_TIME_BETWEEN_UPDATES)
async def async_update(self) -> None: async def async_update(self) -> None:
"""Get the latest data from Trafikverket and updates the states.""" """Get the latest data from Trafikverket and updates the states."""
try: try:
self._weather = await self._weather_api.async_get_weather(self._station) self._weather = await self._weather_api.async_get_weather(self._station)
self._attr_native_value = getattr(
self._weather, self.entity_description.api_key
)
except (asyncio.TimeoutError, aiohttp.ClientError, ValueError) as error: except (asyncio.TimeoutError, aiohttp.ClientError, ValueError) as error:
_LOGGER.error("Could not fetch weather data: %s", error) _LOGGER.error("Could not fetch weather data: %s", error)
return return
self._active = self._weather.active self._attr_native_value = getattr(
self._measure_time = self._weather.measure_time self._weather, self.entity_description.api_key
)
if (
self._attr_native_value is None
and self.entity_description.key in NONE_IS_ZERO_SENSORS
):
self._attr_native_value = 0
self._attr_extra_state_attributes = {
ATTR_ACTIVE: self._weather.active,
ATTR_MEASURE_TIME: self._weather.measure_time,
}