Skip to content

Commit

Permalink
Remove obsolete code, add low temperature forecast sensor (#141), rem…
Browse files Browse the repository at this point in the history
…ove redundant sensors
  • Loading branch information
Limych committed May 18, 2024
1 parent 9870fc2 commit b48e69a
Show file tree
Hide file tree
Showing 9 changed files with 65 additions and 154 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ I put a lot of work into making this repo and component available and updated to
> > How many days ahead to make forecast sensors.\
> > **Note:** If you only need a forecast sensors for today, specify `0`.

When `sensors` option are enabled, it creates 21 sensors. Each shows one aspect of current weather. Only few basic sensors are enabled by default. But you can enable any sensor through device settings.
When `sensors` option are enabled, it creates 20 sensors. Each shows one aspect of current weather. Only few basic sensors are enabled by default. But you can enable any sensor through device settings.

When you add `forecast_days` option, integration creates additional 21 sensors for each day. Each shows one aspect of forecast weather for that day. As usual, only few basic sensors are enabled by default.

Expand All @@ -125,10 +125,13 @@ List of sensors that will be created:
> A human-readable text summary.
>
> **temperature**\
> The current temperature of air.
> The air temperature.
>
> **apparent_temperature**\
> The current apparent air temperature.
> The apparent air temperature.
>
> **low_temperature**\
> The lowest air temperature per day.
>
> **humidity**\
> The relative humidity of air.
Expand Down
34 changes: 22 additions & 12 deletions custom_components/gismeteo/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,13 @@
ATTR_FORECAST_NATIVE_TEMP_LOW,
ATTR_FORECAST_NATIVE_WIND_GUST_SPEED,
ATTR_FORECAST_NATIVE_WIND_SPEED,
ATTR_FORECAST_TEMP_LOW,
ATTR_FORECAST_TIME,
ATTR_FORECAST_UV_INDEX,
ATTR_FORECAST_WIND_BEARING,
Forecast,
)
from homeassistant.const import ATTR_ID, ATTR_LATITUDE, ATTR_LONGITUDE, STATE_UNKNOWN
from homeassistant.const import ATTR_ID, ATTR_LATITUDE, ATTR_LONGITUDE
from homeassistant.helpers.typing import StateType
from homeassistant.util import Throttle, dt as dt_util

from .cache import Cache
Expand Down Expand Up @@ -175,8 +175,8 @@ def current_data(self) -> dict[str, Any]:

def forecast_data(self, pos: int, mode: str = ForecastMode.HOURLY):
"""Return forecast data."""
forecast = []
now = dt_util.now()
forecast = []
for data in (
self._forecast_hourly
if mode == ForecastMode.HOURLY
Expand Down Expand Up @@ -300,8 +300,8 @@ async def async_get_parsed(self) -> dict[str, Any]:
return {}

@staticmethod
def _get(var: dict, ind: str, func: Callable | None = None) -> Any:
res = var.get(ind)
def _get(var: dict, k: str, func: Callable | None = None) -> StateType:
res = var.get(k)
if func is not None:
try:
res = func(res)
Expand Down Expand Up @@ -367,6 +367,11 @@ def temperature(self, src=None) -> float | None:
src = src or self._current
return src.get(ATTR_FORECAST_NATIVE_TEMP)

def templow(self, src=None) -> float | None:
"""Return the low temperature of the day."""
src = src or self._current
return src.get(ATTR_FORECAST_NATIVE_TEMP_LOW)

def apparent_temperature(self, src=None) -> float | None:
"""Return the apparent temperature."""
temp = self.temperature(src)
Expand All @@ -382,8 +387,7 @@ def apparent_temperature(self, src=None) -> float | None:
def water_temperature(self, src=None):
"""Return the temperature of water."""
src = src or self._current
temperature = src.get(ATTR_FORECAST_WATER_TEMPERATURE)
return float(temperature) if temperature is not None else STATE_UNKNOWN
return src.get(ATTR_FORECAST_WATER_TEMPERATURE)

def pressure(self, src=None) -> float | None:
"""Return the pressure in mmHg."""
Expand Down Expand Up @@ -582,8 +586,13 @@ def forecast(self, mode: str = ForecastMode.HOURLY) -> list[GismeteoForecast]:
if v is not None
}

if mode == ForecastMode.DAILY and i.get(ATTR_FORECAST_TEMP_LOW) is not None:
data[ATTR_FORECAST_NATIVE_TEMP_LOW] = i.get(ATTR_FORECAST_TEMP_LOW)
if (
mode == ForecastMode.DAILY
and i.get(ATTR_FORECAST_NATIVE_TEMP_LOW) is not None
):
data[ATTR_FORECAST_NATIVE_TEMP_LOW] = i.get(
ATTR_FORECAST_NATIVE_TEMP_LOW
)

if fc_time < now:
forecast = [data]
Expand Down Expand Up @@ -668,7 +677,8 @@ async def async_update(self) -> bool:
ATTR_FORECAST_IS_DAYTIME: sunrise < tstamp < sunset,
ATTR_FORECAST_CONDITION: self._get(fc_v, "descr"),
ATTR_FORECAST_NATIVE_TEMP: self._get(fc_v, "t", int),
ATTR_FORECAST_NATIVE_PRESSURE: self._get(fc_v, "p", int),
ATTR_FORECAST_NATIVE_PRESSURE: self._get(fc_v, "p", int)
or None,
ATTR_FORECAST_HUMIDITY: self._get(fc_v, "hum", int),
ATTR_FORECAST_NATIVE_WIND_SPEED: self._get(fc_v, "ws", int),
ATTR_FORECAST_WIND_BEARING: self._get(fc_v, "wd", int),
Expand Down Expand Up @@ -721,8 +731,8 @@ async def async_update(self) -> bool:
ATTR_FORECAST_TIME: tstamp,
ATTR_FORECAST_CONDITION: self._get(day, "descr"),
ATTR_FORECAST_NATIVE_TEMP: self._get(day, "tmax", int),
ATTR_FORECAST_TEMP_LOW: self._get(day, "tmin", int),
ATTR_FORECAST_NATIVE_PRESSURE: self._get(day, "p", int),
ATTR_FORECAST_NATIVE_TEMP_LOW: self._get(day, "tmin", int),
ATTR_FORECAST_NATIVE_PRESSURE: self._get(day, "p", int) or None,
ATTR_FORECAST_HUMIDITY: self._get(day, "hum", int),
ATTR_FORECAST_NATIVE_WIND_SPEED: self._get(day, "ws", int),
ATTR_FORECAST_WIND_BEARING: self._get(day, "wd", int),
Expand Down
25 changes: 9 additions & 16 deletions custom_components/gismeteo/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
ATTR_FORECAST_HUMIDITY,
ATTR_FORECAST_PRESSURE,
ATTR_FORECAST_TEMP,
ATTR_FORECAST_TEMP_LOW,
ATTR_FORECAST_WIND_BEARING,
ATTR_FORECAST_WIND_GUST_SPEED,
ATTR_FORECAST_WIND_SPEED,
Expand All @@ -36,7 +37,7 @@
# Base component constants
NAME: Final = "Gismeteo"
DOMAIN: Final = "gismeteo"
VERSION: Final = "3.0.0-beta3"
VERSION: Final = "3.0.0-beta4"
ATTRIBUTION: Final = "Data provided by Gismeteo"
ISSUE_URL: Final = "https://github.com/Limych/ha-gismeteo/issues"
#
Expand Down Expand Up @@ -184,13 +185,6 @@ class ForecastMode(StrEnum):
native_unit_of_measurement=UnitOfSpeed.METERS_PER_SECOND,
entity_registry_enabled_default=False,
),
SensorEntityDescription(
key=ATTR_FORECAST_WIND_GUST_SPEED,
translation_key="wind_gust_speed",
icon="mdi:weather-windy",
native_unit_of_measurement=UnitOfSpeed.METERS_PER_SECOND,
entity_registry_enabled_default=False,
),
SensorEntityDescription(
key=ATTR_FORECAST_WIND_BEARING,
translation_key="wind_bearing",
Expand Down Expand Up @@ -286,6 +280,13 @@ class ForecastMode(StrEnum):
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
),
SensorEntityDescription(
key=ATTR_FORECAST_TEMP_LOW,
translation_key="temperature_low_forecast",
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
entity_registry_enabled_default=False,
),
SensorEntityDescription(
key=ATTR_FORECAST_APPARENT_TEMP,
translation_key="apparent_temperature_forecast",
Expand Down Expand Up @@ -336,7 +337,6 @@ class ForecastMode(StrEnum):
key=ATTR_FORECAST_WIND_BEARING_LABEL,
translation_key="wind_bearing_label_forecast",
icon="mdi:weather-windy",
native_unit_of_measurement=DEGREE,
entity_registry_enabled_default=False,
),
SensorEntityDescription(
Expand Down Expand Up @@ -374,13 +374,6 @@ class ForecastMode(StrEnum):
icon="mdi:magnet-on",
entity_registry_enabled_default=False,
),
SensorEntityDescription(
key=ATTR_FORECAST_WATER_TEMPERATURE,
translation_key="water_temperature_forecast",
device_class=SensorDeviceClass.TEMPERATURE,
native_unit_of_measurement=UnitOfTemperature.CELSIUS,
entity_registry_enabled_default=False,
),
SensorEntityDescription(
key=ATTR_FORECAST_UV_INDEX,
translation_key="uv_index_forecast",
Expand Down
2 changes: 1 addition & 1 deletion custom_components/gismeteo/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,5 @@
"requirements": [
"beautifulsoup4~=4.12"
],
"version": "3.0.0-beta3"
"version": "3.0.0-beta4"
}
67 changes: 7 additions & 60 deletions custom_components/gismeteo/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,29 +11,21 @@
from decimal import Decimal
from functools import cached_property
import logging
from typing import Final

from homeassistant.components.sensor import (
PLATFORM_SCHEMA,
SensorEntity,
SensorEntityDescription,
)
from homeassistant.components.weather import (
ATTR_FORECAST_APPARENT_TEMP,
ATTR_FORECAST_CLOUD_COVERAGE,
ATTR_FORECAST_CONDITION,
)
from homeassistant.components.weather import ATTR_FORECAST_CONDITION
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.const import CONF_MONITORED_CONDITIONS, CONF_NAME, Platform
from homeassistant.const import CONF_NAME, Platform
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.typing import ConfigType, StateType

from . import GismeteoDataUpdateCoordinator, _convert_yaml_config, deslugify
from .const import (
ATTR_FORECAST_GEOMAGNETIC_FIELD,
ATTR_FORECAST_RAIN_AMOUNT,
ATTR_FORECAST_SNOW_AMOUNT,
ATTRIBUTION,
CONF_FORECAST_DAYS,
CONF_PLATFORM_FORMAT,
Expand All @@ -50,60 +42,16 @@

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({})

DEPRECATED_SENSOR_TYPES: Final = {
"weather": ATTR_FORECAST_CONDITION,
"temperature_feels_like": ATTR_FORECAST_APPARENT_TEMP,
"clouds": ATTR_FORECAST_CLOUD_COVERAGE,
"rain": ATTR_FORECAST_RAIN_AMOUNT,
"snow": ATTR_FORECAST_SNOW_AMOUNT,
"geomagnetic": ATTR_FORECAST_GEOMAGNETIC_FIELD,
}


def _fix_types(types: list[str], warn=True) -> list[str]:
"""Remove unwanted values from types."""
types = set(types)

dep_types = ["forecast", "pressure_mmhg"]
dep_types.extend(DEPRECATED_SENSOR_TYPES.keys())
for stype in dep_types:
if stype in types:
types.remove(stype)

if stype in DEPRECATED_SENSOR_TYPES:
types.add(DEPRECATED_SENSOR_TYPES[stype])
if warn:
_LOGGER.warning(
'The "%s" condition is deprecated,'
' please replace it with "%s"',
stype,
DEPRECATED_SENSOR_TYPES[stype],
)

return [x.key for x in SENSOR_DESCRIPTIONS if x.key in types]


def _gen_entities(
location_name: str,
coordinator: GismeteoDataUpdateCoordinator,
config: ConfigType,
warn: bool,
):
"""Generate entities."""
entities = []

types = _fix_types(
config.get(CONF_MONITORED_CONDITIONS, [x.key for x in SENSOR_DESCRIPTIONS]),
warn=warn,
)

entities.extend(
[
GismeteoSensor(coordinator, desc, location_name)
for desc in SENSOR_DESCRIPTIONS
if desc.key in types
]
)
entities = [
GismeteoSensor(coordinator, desc, location_name) for desc in SENSOR_DESCRIPTIONS
]

days = config.get(CONF_FORECAST_DAYS)
if days is not None:
Expand All @@ -112,7 +60,6 @@ def _gen_entities(
[
GismeteoSensor(coordinator, desc, location_name, day)
for desc in FORECAST_SENSOR_DESCRIPTIONS
if desc.key in types
]
)

Expand All @@ -137,7 +84,7 @@ async def async_setup_entry(
location_name = cfg.get(CONF_NAME, deslugify(uid))
coordinator = hass.data[DOMAIN][uid][COORDINATOR]

entities.extend(_gen_entities(location_name, coordinator, cfg, True))
entities.extend(_gen_entities(location_name, coordinator, cfg))

else:
# Setup from config entry
Expand All @@ -150,7 +97,7 @@ async def async_setup_entry(
location_name = config[CONF_NAME]
coordinator = hass.data[DOMAIN][config_entry.entry_id][COORDINATOR]

entities.extend(_gen_entities(location_name, coordinator, config, False))
entities.extend(_gen_entities(location_name, coordinator, config))

async_add_entities(entities)

Expand Down
9 changes: 3 additions & 6 deletions custom_components/gismeteo/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@
"wind_speed": {
"name": "Wind Speed"
},
"wind_gust_speed": {
"name": "Wind Gusts Speed"
},
"wind_bearing": {
"name": "Wind Bearing"
},
Expand Down Expand Up @@ -121,6 +118,9 @@
"temperature_forecast": {
"name": "Temperature Forecast {day}d"
},
"temperature_low_forecast": {
"name": "Low Temperature Forecast {day}d"
},
"apparent_temperature_forecast": {
"name": "Apparent Temperature Forecast {day}d"
},
Expand Down Expand Up @@ -171,9 +171,6 @@
"geomagnetic_field_forecast": {
"name": "Geomagnetic Field Forecast {day}d"
},
"water_temperature_forecast": {
"name": "Water Temperature Forecast {day}d"
},
"uv_index_forecast": {
"name": "UV Index Forecast {day}d"
},
Expand Down
9 changes: 3 additions & 6 deletions custom_components/gismeteo/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,6 @@
"wind_speed": {
"name": "Скорость Ветра"
},
"wind_gust_speed": {
"name": "Скорость Порывов Ветра"
},
"wind_bearing": {
"name": "Направление Ветра"
},
Expand Down Expand Up @@ -121,6 +118,9 @@
"temperature_forecast": {
"name": "Прогноз Температуры {day}д"
},
"temperature_low_forecast": {
"name": "Прогноз Нижней Температуры {day}д"
},
"apparent_temperature_forecast": {
"name": "Прогноз Ощущаемой Температуры {day}д"
},
Expand Down Expand Up @@ -171,9 +171,6 @@
"geomagnetic_field_forecast": {
"name": "Прогноз Геомагнитного Фона {day}д"
},
"water_temperature_forecast": {
"name": "Прогноз Тепературы Воды {day}д"
},
"uv_index_forecast": {
"name": "Прогноз УФ Фона {day}д"
},
Expand Down
Loading

0 comments on commit b48e69a

Please sign in to comment.