diff --git a/homeassistant/components/foreca/__init__.py b/homeassistant/components/foreca/__init__.py index 6ed8686e5788..b1ca3e9da261 100644 --- a/homeassistant/components/foreca/__init__.py +++ b/homeassistant/components/foreca/__init__.py @@ -4,13 +4,24 @@ from pyforeca import ForecaApiClient from homeassistant.const import CONF_API_KEY, Platform from homeassistant.core import HomeAssistant +from homeassistant.helpers import config_validation as cv from homeassistant.helpers.aiohttp_client import async_get_clientsession +from homeassistant.helpers.typing import ConfigType -from .const import SUBENTRY_TYPE_LOCATION +from .const import DOMAIN, SUBENTRY_TYPE_LOCATION from .coordinator import ForecaConfigEntry, ForecaUpdateCoordinator +from .services import async_setup_services PLATFORMS = [Platform.SENSOR, Platform.WEATHER] +CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) + + +async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: + """Set up the Foreca actions.""" + async_setup_services(hass) + return True + async def async_setup_entry(hass: HomeAssistant, entry: ForecaConfigEntry) -> None: """Set up Foreca from a config entry.""" diff --git a/homeassistant/components/foreca/icons.json b/homeassistant/components/foreca/icons.json new file mode 100644 index 000000000000..2aef3a2e6140 --- /dev/null +++ b/homeassistant/components/foreca/icons.json @@ -0,0 +1,7 @@ +{ + "services": { + "get_forecasts_extra": { + "service": "mdi:weather-cloudy-clock" + } + } +} diff --git a/homeassistant/components/foreca/quality_scale.yaml b/homeassistant/components/foreca/quality_scale.yaml index 1ee0978a3983..7e7167027547 100644 --- a/homeassistant/components/foreca/quality_scale.yaml +++ b/homeassistant/components/foreca/quality_scale.yaml @@ -1,17 +1,13 @@ rules: # Bronze - action-setup: - status: exempt - comment: The integration does not register actions. + action-setup: done appropriate-polling: done brands: done common-modules: done config-flow-test-coverage: done config-flow: done dependency-transparency: done - docs-actions: - status: exempt - comment: The integration does not register actions. + docs-actions: done docs-conditions: status: exempt comment: The integration does not register conditions. @@ -32,9 +28,7 @@ rules: unique-config-entry: done # Silver - action-exceptions: - status: exempt - comment: The integration does not register actions. + action-exceptions: done config-entry-unloading: done docs-configuration-parameters: status: exempt diff --git a/homeassistant/components/foreca/services.py b/homeassistant/components/foreca/services.py new file mode 100644 index 000000000000..cd3dfa60c44e --- /dev/null +++ b/homeassistant/components/foreca/services.py @@ -0,0 +1,41 @@ +"""Actions for the Foreca integration.""" + +from enum import StrEnum + +import probatio + +from homeassistant.components.weather import DOMAIN as WEATHER_DOMAIN +from homeassistant.core import HomeAssistant, SupportsResponse, callback +from homeassistant.helpers import service + +from .const import DOMAIN + + +class ForecaService(StrEnum): + """Foreca actions.""" + + GET_FORECASTS_EXTRA = "get_forecasts_extra" + + +class ForecaServiceArgument(StrEnum): + """Foreca action fields.""" + + TYPE = "type" + + +@callback +def async_setup_services(hass: HomeAssistant) -> None: + """Register the Foreca actions.""" + service.async_register_platform_entity_service( + hass, + DOMAIN, + ForecaService.GET_FORECASTS_EXTRA, + entity_domain=WEATHER_DOMAIN, + schema={ + probatio.Required(ForecaServiceArgument.TYPE): probatio.In( + ["daily", "hourly"] + ) + }, + func="async_get_forecasts_extra", + supports_response=SupportsResponse.ONLY, + ) diff --git a/homeassistant/components/foreca/services.yaml b/homeassistant/components/foreca/services.yaml new file mode 100644 index 000000000000..1cf47b423e70 --- /dev/null +++ b/homeassistant/components/foreca/services.yaml @@ -0,0 +1,14 @@ +get_forecasts_extra: + target: + entity: + domain: weather + integration: foreca + fields: + type: + required: true + selector: + select: + options: + - "daily" + - "hourly" + translation_key: forecast_type diff --git a/homeassistant/components/foreca/strings.json b/homeassistant/components/foreca/strings.json index c1ad2d05b93e..adbc7096dba4 100644 --- a/homeassistant/components/foreca/strings.json +++ b/homeassistant/components/foreca/strings.json @@ -55,5 +55,25 @@ "name": "Thunderstorm probability" } } + }, + "selector": { + "forecast_type": { + "options": { + "daily": "Daily", + "hourly": "Hourly" + } + } + }, + "services": { + "get_forecasts_extra": { + "description": "Retrieves the forecast values that weather.get_forecasts has no place for, such as precipitation type, snow, solar radiation, sunshine and sunrise. They come from the forecast already fetched, so the action makes no API requests.", + "fields": { + "type": { + "description": "The forecast to return the values for.", + "name": "Forecast type" + } + }, + "name": "Get extra forecast values" + } } } diff --git a/homeassistant/components/foreca/weather.py b/homeassistant/components/foreca/weather.py index e7ccef50fb0a..2867686fe4c5 100644 --- a/homeassistant/components/foreca/weather.py +++ b/homeassistant/components/foreca/weather.py @@ -5,6 +5,10 @@ from typing import override from pyforeca import DailyForecast, HourlyForecast from homeassistant.components.weather import ( + ATTR_WEATHER_PRECIPITATION_UNIT, + ATTR_WEATHER_TEMPERATURE_UNIT, + ATTR_WEATHER_VISIBILITY_UNIT, + UNIT_CONVERSIONS, Forecast, SingleCoordinatorWeatherEntity, WeatherEntityFeature, @@ -16,9 +20,10 @@ from homeassistant.const import ( UnitOfSpeed, UnitOfTemperature, ) -from homeassistant.core import HomeAssistant, callback +from homeassistant.core import HomeAssistant, ServiceResponse, callback from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback from homeassistant.util import dt as dt_util +from homeassistant.util.json import JsonValueType from .const import symbol_to_condition from .coordinator import ForecaConfigEntry, ForecaUpdateCoordinator @@ -26,6 +31,9 @@ from .entity import ForecaEntity PARALLEL_UPDATES = 0 +_CONFIDENCE = {"g": "good", "y": "normal", "o": "low"} +_ROUNDING_PRECISION = 2 + async def async_setup_entry( hass: HomeAssistant, @@ -199,3 +207,95 @@ class ForecaWeather( for hour in self.coordinator.data.hourly if (forecast := _hourly_to_forecast(hour)) is not None ] + + async def async_get_forecasts_extra(self, type: str) -> ServiceResponse: + """Return the forecast values that weather.get_forecasts has no field for.""" + if type == "hourly": + return { + "forecast": [ + extra + for hour in self.coordinator.data.hourly + if (extra := self._hourly_extra(hour)) is not None + ] + } + return { + "forecast": [ + extra + for day in self.coordinator.data.daily + if (extra := self._daily_extra(day)) is not None + ] + } + + def _hourly_extra(self, hour: HourlyForecast) -> dict[str, JsonValueType] | None: + """Return an hour's values that a Home Assistant forecast cannot hold.""" + if (timestamp := dt_util.parse_datetime(hour.time or "")) is None: + return None + return { + "datetime": timestamp.isoformat(), + "precipitation_type": hour.precip_type, + "snow_accumulation": self._snow(hour.snow_accum), + "snow_depth": self._snow(hour.snow_depth), + "solar_radiation": hour.solar_radiation, + "thunderstorm_probability": hour.thunder_prob, + "visibility": self._visibility(hour.visibility), + } + + def _daily_extra(self, day: DailyForecast) -> dict[str, JsonValueType] | None: + """Return a day's values that a Home Assistant forecast cannot hold.""" + if (date := dt_util.parse_date(day.date or "")) is None: + return None + return { + "datetime": dt_util.start_of_local_day(date).isoformat(), + "apparent_templow": self._temperature(day.min_feels_like_temp), + "max_humidity": day.max_rel_humidity, + "min_humidity": day.min_rel_humidity, + "min_dew_point": self._temperature(day.min_dew_point), + "min_visibility": self._visibility(day.min_visibility), + "snow_accumulation": self._snow(day.snow_accum), + "snow_depth": self._snow(day.snow_depth), + "sunshine_duration": day.sunhours, + "solar_radiation_sum": day.solar_radiation_sum, + "sunrise": _from_epoch(day.sunrise_epoch), + "sunset": _from_epoch(day.sunset_epoch), + "confidence": _CONFIDENCE.get(day.confidence or ""), + } + + def _temperature(self, value: float | None) -> float | None: + """Convert a temperature in °C to the entity's temperature unit.""" + if value is None: + return None + return round( + UNIT_CONVERSIONS[ATTR_WEATHER_TEMPERATURE_UNIT]( + value, UnitOfTemperature.CELSIUS, self._temperature_unit + ), + _ROUNDING_PRECISION, + ) + + def _visibility(self, value: float | None) -> float | None: + """Convert a distance in metres to the entity's visibility unit.""" + if value is None: + return None + return round( + UNIT_CONVERSIONS[ATTR_WEATHER_VISIBILITY_UNIT]( + value, UnitOfLength.METERS, self._visibility_unit + ), + _ROUNDING_PRECISION, + ) + + def _snow(self, value: float | None) -> float | None: + """Convert a snow thickness in cm to the entity's precipitation unit.""" + if value is None: + return None + return round( + UNIT_CONVERSIONS[ATTR_WEATHER_PRECIPITATION_UNIT]( + value, UnitOfPrecipitationDepth.CENTIMETERS, self._precipitation_unit + ), + _ROUNDING_PRECISION, + ) + + +def _from_epoch(epoch: int | None) -> str | None: + """Return a Unix time as an ISO 8601 timestamp in UTC.""" + if epoch is None: + return None + return dt_util.utc_from_timestamp(epoch).isoformat() diff --git a/tests/components/foreca/conftest.py b/tests/components/foreca/conftest.py index 049575406881..587f58815b0d 100644 --- a/tests/components/foreca/conftest.py +++ b/tests/components/foreca/conftest.py @@ -46,8 +46,11 @@ HOURLY = [ cloudiness=60, uv_index=1, precip_type="rain", + snow_accum=0.3, + thunder_prob=12, + visibility=24000, solar_radiation=141.0, - snow_depth=0.0, + snow_depth=2.0, ) ] @@ -65,7 +68,17 @@ DAILY = [ max_wind_gust=11.0, wind_dir=225, uv_index=3, + min_feels_like_temp=7.4, + max_rel_humidity=93, + min_rel_humidity=51, + min_dew_point=4.6, + min_visibility=8000, + snow_accum=1.5, + snow_depth=4.0, sunhours=6.4, + solar_radiation_sum=2875, + sunrise_epoch=1788318000, + sunset_epoch=1788368400, confidence="g", ), DailyForecast( diff --git a/tests/components/foreca/snapshots/test_weather.ambr b/tests/components/foreca/snapshots/test_weather.ambr index 1a7b8564bd0b..3027c21a7b3d 100644 --- a/tests/components/foreca/snapshots/test_weather.ambr +++ b/tests/components/foreca/snapshots/test_weather.ambr @@ -55,6 +55,116 @@ }), }) # --- +# name: test_forecasts_extra[metric-daily] + dict({ + 'weather.helsinki': dict({ + 'forecast': list([ + dict({ + 'apparent_templow': 7.4, + 'confidence': 'good', + 'datetime': '2026-09-02T00:00:00-07:00', + 'max_humidity': 93, + 'min_dew_point': 4.6, + 'min_humidity': 51, + 'min_visibility': 8.0, + 'snow_accumulation': 15.0, + 'snow_depth': 40.0, + 'solar_radiation_sum': 2875, + 'sunrise': '2026-09-02T03:00:00+00:00', + 'sunset': '2026-09-02T17:00:00+00:00', + 'sunshine_duration': 6.4, + }), + dict({ + 'apparent_templow': None, + 'confidence': None, + 'datetime': '2026-09-03T00:00:00-07:00', + 'max_humidity': None, + 'min_dew_point': None, + 'min_humidity': None, + 'min_visibility': None, + 'snow_accumulation': None, + 'snow_depth': None, + 'solar_radiation_sum': None, + 'sunrise': None, + 'sunset': None, + 'sunshine_duration': None, + }), + ]), + }), + }) +# --- +# name: test_forecasts_extra[metric-hourly] + dict({ + 'weather.helsinki': dict({ + 'forecast': list([ + dict({ + 'datetime': '2026-09-01T18:00:00+03:00', + 'precipitation_type': 'rain', + 'snow_accumulation': 3.0, + 'snow_depth': 20.0, + 'solar_radiation': 141.0, + 'thunderstorm_probability': 12, + 'visibility': 24.0, + }), + ]), + }), + }) +# --- +# name: test_forecasts_extra[us_customary-daily] + dict({ + 'weather.helsinki': dict({ + 'forecast': list([ + dict({ + 'apparent_templow': 45.32, + 'confidence': 'good', + 'datetime': '2026-09-02T00:00:00-07:00', + 'max_humidity': 93, + 'min_dew_point': 40.28, + 'min_humidity': 51, + 'min_visibility': 4.97, + 'snow_accumulation': 0.59, + 'snow_depth': 1.57, + 'solar_radiation_sum': 2875, + 'sunrise': '2026-09-02T03:00:00+00:00', + 'sunset': '2026-09-02T17:00:00+00:00', + 'sunshine_duration': 6.4, + }), + dict({ + 'apparent_templow': None, + 'confidence': None, + 'datetime': '2026-09-03T00:00:00-07:00', + 'max_humidity': None, + 'min_dew_point': None, + 'min_humidity': None, + 'min_visibility': None, + 'snow_accumulation': None, + 'snow_depth': None, + 'solar_radiation_sum': None, + 'sunrise': None, + 'sunset': None, + 'sunshine_duration': None, + }), + ]), + }), + }) +# --- +# name: test_forecasts_extra[us_customary-hourly] + dict({ + 'weather.helsinki': dict({ + 'forecast': list([ + dict({ + 'datetime': '2026-09-01T18:00:00+03:00', + 'precipitation_type': 'rain', + 'snow_accumulation': 0.12, + 'snow_depth': 0.79, + 'solar_radiation': 141.0, + 'thunderstorm_probability': 12, + 'visibility': 14.91, + }), + ]), + }), + }) +# --- # name: test_weather[weather.helsinki-entry] EntityRegistryEntrySnapshot({ 'aliases': list([ diff --git a/tests/components/foreca/test_weather.py b/tests/components/foreca/test_weather.py index 10129a6070ec..d7a90820e42f 100644 --- a/tests/components/foreca/test_weather.py +++ b/tests/components/foreca/test_weather.py @@ -3,19 +3,35 @@ from datetime import date from unittest.mock import MagicMock, patch -from pyforeca import DailyForecast, HourlyForecast +from freezegun.api import FrozenDateTimeFactory +from pyforeca import DailyForecast, ForecaConnectionError, HourlyForecast import pytest -from pytest_homeassistant.common import MockConfigEntry, snapshot_platform +from pytest_homeassistant.common import ( + MockConfigEntry, + async_fire_time_changed, + snapshot_platform, +) from syrupy.assertion import SnapshotAssertion +from homeassistant.components.foreca.const import DOMAIN, UPDATE_INTERVAL +from homeassistant.components.foreca.services import ( + ForecaService, + ForecaServiceArgument, +) from homeassistant.components.weather import ( DOMAIN as WEATHER_DOMAIN, SERVICE_GET_FORECASTS, ) -from homeassistant.const import ATTR_ENTITY_ID, Platform +from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, Platform from homeassistant.core import HomeAssistant +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import entity_registry as er from homeassistant.util import dt as dt_util +from homeassistant.util.unit_system import ( + METRIC_SYSTEM, + US_CUSTOMARY_SYSTEM, + UnitSystem, +) from . import init_integration @@ -113,3 +129,90 @@ async def test_daily_forecast_lands_on_the_right_local_day( # The date has to survive being rendered where Home Assistant is, which is # what midnight UTC would break. assert dt_util.as_local(timestamp).date() == date(2026, 9, 2) + + +@pytest.mark.usefixtures("mock_foreca_client") +@pytest.mark.parametrize("forecast_type", ["daily", "hourly"]) +@pytest.mark.parametrize( + "unit_system", + [ + pytest.param(METRIC_SYSTEM, id="metric"), + pytest.param(US_CUSTOMARY_SYSTEM, id="us_customary"), + ], +) +async def test_forecasts_extra( + hass: HomeAssistant, + snapshot: SnapshotAssertion, + mock_config_entry: MockConfigEntry, + forecast_type: str, + unit_system: UnitSystem, +) -> None: + """Test the extra forecast values in the entity's units.""" + hass.config.units = unit_system + with patch("homeassistant.components.foreca.PLATFORMS", [Platform.WEATHER]): + await init_integration(hass, mock_config_entry) + + response = await hass.services.async_call( + DOMAIN, + ForecaService.GET_FORECASTS_EXTRA, + {ATTR_ENTITY_ID: ENTITY_ID, ForecaServiceArgument.TYPE: forecast_type}, + blocking=True, + return_response=True, + ) + assert response == snapshot + + +@pytest.mark.parametrize( + ("forecast_type", "mocked_method", "undated"), + [ + ("daily", "forecast_daily", [DailyForecast(date=None)]), + ("hourly", "forecast_hourly", [HourlyForecast(time=None)]), + ], +) +async def test_forecasts_extra_without_a_time_is_dropped( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_foreca_client: MagicMock, + forecast_type: str, + mocked_method: str, + undated: list[DailyForecast] | list[HourlyForecast], +) -> None: + """Test that a forecast entry without a date or time is left out.""" + getattr(mock_foreca_client, mocked_method).return_value = undated + with patch("homeassistant.components.foreca.PLATFORMS", [Platform.WEATHER]): + await init_integration(hass, mock_config_entry) + + response = await hass.services.async_call( + DOMAIN, + ForecaService.GET_FORECASTS_EXTRA, + {ATTR_ENTITY_ID: ENTITY_ID, ForecaServiceArgument.TYPE: forecast_type}, + blocking=True, + return_response=True, + ) + assert response == {ENTITY_ID: {"forecast": []}} + + +async def test_forecasts_extra_fails_while_unavailable( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + mock_foreca_client: MagicMock, + freezer: FrozenDateTimeFactory, +) -> None: + """Test the action raises instead of returning stale data after a failed update.""" + with patch("homeassistant.components.foreca.PLATFORMS", [Platform.WEATHER]): + await init_integration(hass, mock_config_entry) + + mock_foreca_client.current.side_effect = ForecaConnectionError + freezer.tick(UPDATE_INTERVAL) + async_fire_time_changed(hass) + await hass.async_block_till_done() + assert hass.states.get(ENTITY_ID).state == STATE_UNAVAILABLE + + with pytest.raises(HomeAssistantError): + await hass.services.async_call( + DOMAIN, + ForecaService.GET_FORECASTS_EXTRA, + {ATTR_ENTITY_ID: ENTITY_ID, ForecaServiceArgument.TYPE: "daily"}, + blocking=True, + return_response=True, + )