From 395093351428d349246e4c1de526b159a167f382 Mon Sep 17 00:00:00 2001 From: G Johansson Date: Thu, 6 Jan 2022 16:33:06 +0100 Subject: [PATCH] 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 --- CODEOWNERS | 4 +- .../config_flow.py | 9 +++- .../trafikverket_weatherstation/const.py | 10 +++++ .../trafikverket_weatherstation/manifest.json | 2 +- .../trafikverket_weatherstation/sensor.py | 45 +++++++++---------- 5 files changed, 42 insertions(+), 28 deletions(-) diff --git a/CODEOWNERS b/CODEOWNERS index 98cadaf29200..69753c5e60c7 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -958,8 +958,8 @@ tests/components/trace/* @home-assistant/core homeassistant/components/tractive/* @Danielhiversen @zhulik @bieniu tests/components/tractive/* @Danielhiversen @zhulik @bieniu homeassistant/components/trafikverket_train/* @endor-force -homeassistant/components/trafikverket_weatherstation/* @endor-force -tests/components/trafikverket_weatherstation/* @endor-force +homeassistant/components/trafikverket_weatherstation/* @endor-force @gjohansson-ST +tests/components/trafikverket_weatherstation/* @endor-force @gjohansson-ST homeassistant/components/transmission/* @engrbm87 @JPHutchins tests/components/transmission/* @engrbm87 @JPHutchins homeassistant/components/tts/* @pvizeli diff --git a/homeassistant/components/trafikverket_weatherstation/config_flow.py b/homeassistant/components/trafikverket_weatherstation/config_flow.py index 103af1c7eb41..5f364bb74722 100644 --- a/homeassistant/components/trafikverket_weatherstation/config_flow.py +++ b/homeassistant/components/trafikverket_weatherstation/config_flow.py @@ -1,11 +1,14 @@ """Adds config flow for Trafikverket Weather integration.""" from __future__ import annotations +from typing import Any + from pytrafikverket.trafikverket_weather import TrafikverketWeather import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_API_KEY +from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers.aiohttp_client import async_get_clientsession import homeassistant.helpers.config_validation as cv @@ -36,7 +39,7 @@ class TVWeatherConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): return str(err) 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.""" self.context.update( @@ -46,7 +49,9 @@ class TVWeatherConfigFlow(config_entries.ConfigFlow, domain=DOMAIN): self._async_abort_entries_match({CONF_STATION: config[CONF_STATION]}) 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.""" errors = {} diff --git a/homeassistant/components/trafikverket_weatherstation/const.py b/homeassistant/components/trafikverket_weatherstation/const.py index 3c2cfc4d165c..7bb53dc5356a 100644 --- a/homeassistant/components/trafikverket_weatherstation/const.py +++ b/homeassistant/components/trafikverket_weatherstation/const.py @@ -7,3 +7,13 @@ PLATFORMS = [Platform.SENSOR] ATTRIBUTION = "Data provided by Trafikverket" ATTR_MEASURE_TIME = "measure_time" ATTR_ACTIVE = "active" + +NONE_IS_ZERO_SENSORS = { + "air_temp", + "road_temp", + "wind_direction", + "wind_speed", + "wind_speed_max", + "humidity", + "precipitation_amount", +} diff --git a/homeassistant/components/trafikverket_weatherstation/manifest.json b/homeassistant/components/trafikverket_weatherstation/manifest.json index 202d2683d2d0..6490468dc03f 100644 --- a/homeassistant/components/trafikverket_weatherstation/manifest.json +++ b/homeassistant/components/trafikverket_weatherstation/manifest.json @@ -3,7 +3,7 @@ "name": "Trafikverket Weather Station", "documentation": "https://www.home-assistant.io/integrations/trafikverket_weatherstation", "requirements": ["pytrafikverket==0.1.6.2"], - "codeowners": ["@endor-force"], + "codeowners": ["@endor-force", "@gjohansson-ST"], "config_flow": true, "iot_class": "cloud_polling" } diff --git a/homeassistant/components/trafikverket_weatherstation/sensor.py b/homeassistant/components/trafikverket_weatherstation/sensor.py index 753a300c96bb..b4ae196ae00d 100644 --- a/homeassistant/components/trafikverket_weatherstation/sensor.py +++ b/homeassistant/components/trafikverket_weatherstation/sensor.py @@ -5,7 +5,6 @@ import asyncio from dataclasses import dataclass from datetime import timedelta import logging -from typing import Any import aiohttp 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.const import ( - ATTR_ATTRIBUTION, CONF_API_KEY, CONF_MONITORED_CONDITIONS, CONF_NAME, @@ -37,7 +35,14 @@ from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType 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__) @@ -198,6 +203,7 @@ class TrafikverketWeatherStation(SensorEntity): """Representation of a Trafikverket sensor.""" entity_description: TrafikverketSensorEntityDescription + _attr_attribution = ATTRIBUTION def __init__( self, @@ -213,32 +219,25 @@ class TrafikverketWeatherStation(SensorEntity): self._station = sensor_station self._weather_api = weather_api 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) async def async_update(self) -> None: """Get the latest data from Trafikverket and updates the states.""" try: 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: _LOGGER.error("Could not fetch weather data: %s", error) return - self._active = self._weather.active - self._measure_time = self._weather.measure_time + self._attr_native_value = getattr( + 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, + }