From 366db1c65c9fffce96f22a67dc7972f9372faaad Mon Sep 17 00:00:00 2001 From: Raman Gupta <7243222+raman325@users.noreply.github.com> Date: Sun, 22 Nov 2026 03:48:39 -0500 Subject: [PATCH] Add get_minute_forecast action to Tomorrow.io (#192376) Co-authored-by: Claude Opus 5.5 --- .../components/tomorrowio/__init__.py | 2 + .../components/tomorrowio/icons.json | 5 + .../components/tomorrowio/services.py | 29 ++ .../components/tomorrowio/services.yaml | 5 + .../components/tomorrowio/strings.json | 8 +- .../components/tomorrowio/weather.py | 37 ++- .../tomorrowio/snapshots/test_weather.ambr | 278 ++++++++++++++++++ tests/components/tomorrowio/test_weather.py | 87 +++++- 8 files changed, 442 insertions(+), 9 deletions(-) create mode 100644 homeassistant/components/tomorrowio/services.py create mode 100644 homeassistant/components/tomorrowio/services.yaml diff --git a/homeassistant/components/tomorrowio/__init__.py b/homeassistant/components/tomorrowio/__init__.py index 61e4bd561e50..cabbee1a3bcf 100644 --- a/homeassistant/components/tomorrowio/__init__.py +++ b/homeassistant/components/tomorrowio/__init__.py @@ -30,6 +30,7 @@ from .const import ( SUBENTRY_TYPE_LOCATION, ) from .coordinator import TomorrowioConfigEntry, TomorrowioDataUpdateCoordinator +from .services import async_setup_services CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN) PLATFORMS = [Platform.SENSOR, Platform.WEATHER] @@ -38,6 +39,7 @@ PLATFORMS = [Platform.SENSOR, Platform.WEATHER] async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool: """Set up the Tomorrow.io integration.""" await async_migrate_integration(hass) + async_setup_services(hass) return True diff --git a/homeassistant/components/tomorrowio/icons.json b/homeassistant/components/tomorrowio/icons.json index cf0b20342872..a6838cabcf51 100644 --- a/homeassistant/components/tomorrowio/icons.json +++ b/homeassistant/components/tomorrowio/icons.json @@ -44,5 +44,10 @@ "default": "mdi:weather-windy" } } + }, + "services": { + "get_minute_forecast": { + "service": "mdi:weather-pouring" + } } } diff --git a/homeassistant/components/tomorrowio/services.py b/homeassistant/components/tomorrowio/services.py new file mode 100644 index 000000000000..d800e38c2d41 --- /dev/null +++ b/homeassistant/components/tomorrowio/services.py @@ -0,0 +1,29 @@ +"""Services for the Tomorrow.io integration.""" + +from enum import StrEnum + +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 TomorrowioService(StrEnum): + """Store keys for Tomorrow.io services.""" + + GET_MINUTE_FORECAST = "get_minute_forecast" + + +@callback +def async_setup_services(hass: HomeAssistant) -> None: + """Set up the services for the Tomorrow.io integration.""" + service.async_register_platform_entity_service( + hass, + DOMAIN, + TomorrowioService.GET_MINUTE_FORECAST, + entity_domain=WEATHER_DOMAIN, + schema=None, + func="async_get_minute_forecast", + supports_response=SupportsResponse.ONLY, + ) diff --git a/homeassistant/components/tomorrowio/services.yaml b/homeassistant/components/tomorrowio/services.yaml new file mode 100644 index 000000000000..d63e5caae2dc --- /dev/null +++ b/homeassistant/components/tomorrowio/services.yaml @@ -0,0 +1,5 @@ +get_minute_forecast: + target: + entity: + domain: weather + integration: tomorrowio diff --git a/homeassistant/components/tomorrowio/strings.json b/homeassistant/components/tomorrowio/strings.json index 30cd1750eecc..9d62b0b0d8e3 100644 --- a/homeassistant/components/tomorrowio/strings.json +++ b/homeassistant/components/tomorrowio/strings.json @@ -41,7 +41,7 @@ "data_description": { "location": "The location to get weather data for", "name": "The name of the location", - "timestep": "If you choose to enable the `nowcast` forecast entity, you can configure the number of minutes between each forecast. The number of forecasts provided depends on the number of minutes chosen between forecasts." + "timestep": "The number of minutes between the forecasts returned by the \"Get minute forecast\" action. Up to 30 forecasts are returned, so shorter intervals cover less time." } } } @@ -177,5 +177,11 @@ "name": "Wind gust" } } + }, + "services": { + "get_minute_forecast": { + "description": "Retrieves the minute-level forecast (nowcast) for a location, in intervals of the length configured for that location. The data comes from the latest scheduled update, so this action does not use any API requests. Precipitation is the amount expected in each interval, in the weather entity's precipitation unit.", + "name": "Get minute forecast" + } } } diff --git a/homeassistant/components/tomorrowio/weather.py b/homeassistant/components/tomorrowio/weather.py index 753de8863acf..b2c7baa8a136 100644 --- a/homeassistant/components/tomorrowio/weather.py +++ b/homeassistant/components/tomorrowio/weather.py @@ -1,7 +1,7 @@ """Weather component that handles meteorological data for your location.""" -from datetime import datetime -from typing import override +from datetime import datetime, timedelta +from typing import Any, cast, override from pytomorrowio.const import DAILY, FORECASTS, HOURLY, NOWCAST, WeatherCode @@ -13,10 +13,13 @@ from homeassistant.components.weather import ( ATTR_FORECAST_NATIVE_TEMP, ATTR_FORECAST_NATIVE_TEMP_LOW, ATTR_FORECAST_NATIVE_WIND_SPEED, + ATTR_FORECAST_PRECIPITATION, ATTR_FORECAST_PRECIPITATION_PROBABILITY, ATTR_FORECAST_TIME, ATTR_FORECAST_WIND_BEARING, + ATTR_WEATHER_PRECIPITATION_UNIT, DOMAIN as WEATHER_DOMAIN, + UNIT_CONVERSIONS, Forecast, SingleCoordinatorWeatherEntity, WeatherEntityFeature, @@ -253,8 +256,9 @@ class TomorrowioWeatherEntity(TomorrowioEntity, SingleCoordinatorWeatherEntity): max_forecasts = MAX_FORECASTS[forecast_type] forecast_count = 0 + now = dt_util.utcnow() # Convert utcnow to local to be compatible with tests - today = dt_util.as_local(dt_util.utcnow()).date() + today = dt_util.as_local(now).date() # Set default values (in cases where keys don't exist), None will be # returned. Override properties per forecast type as needed @@ -291,12 +295,14 @@ class TomorrowioWeatherEntity(TomorrowioEntity, SingleCoordinatorWeatherEntity): if precipitation: precipitation = precipitation * 24 elif forecast_type == NOWCAST: + timestep = self._subentry.data[CONF_TIMESTEP] + # Data can be up to one update old, so skip intervals that ended + if forecast_dt + timedelta(minutes=timestep) <= now: + continue # Precipitation is forecasted in CONF_TIMESTEP increments but in a # per hour rate, so value needs to be converted to an amount. if precipitation: - precipitation = ( - precipitation / 60 * self._subentry.data[CONF_TIMESTEP] - ) + precipitation = precipitation / 60 * timestep forecasts.append( self._forecast_dict( @@ -331,3 +337,22 @@ class TomorrowioWeatherEntity(TomorrowioEntity, SingleCoordinatorWeatherEntity): def _async_forecast_hourly(self) -> list[Forecast] | None: """Return the hourly forecast in native units.""" return self._forecast(HOURLY) + + async def async_get_minute_forecast(self) -> dict[str, Any]: + """Return the nowcast forecast in the units configured by the user.""" + native_forecasts = self._forecast(NOWCAST) or [] + forecasts = cast(list[dict[str, Any]], self._convert_forecast(native_forecasts)) + # Per-interval amounts are too small to survive the rounding in + # _convert_forecast, so they are converted without rounding + for native, forecast in zip(native_forecasts, forecasts, strict=True): + if ( + precipitation := native.get(ATTR_FORECAST_NATIVE_PRECIPITATION) + ) is not None: + forecast[ATTR_FORECAST_PRECIPITATION] = UNIT_CONVERSIONS[ + ATTR_WEATHER_PRECIPITATION_UNIT + ]( + precipitation, + UnitOfPrecipitationDepth.MILLIMETERS, + self._precipitation_unit, + ) + return {"forecast": forecasts} diff --git a/tests/components/tomorrowio/snapshots/test_weather.ambr b/tests/components/tomorrowio/snapshots/test_weather.ambr index 6278b50b7f7d..f2d361a1effd 100644 --- a/tests/components/tomorrowio/snapshots/test_weather.ambr +++ b/tests/components/tomorrowio/snapshots/test_weather.ambr @@ -735,6 +735,284 @@ }), ]) # --- +# name: test_minute_forecast_service + dict({ + 'weather.tomorrow_io_daily': dict({ + 'forecast': list([ + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T17:53:00+00:00', + 'precipitation': 0.1, + 'precipitation_probability': 0, + 'temperature': 43.9, + 'wind_bearing': 315.14, + 'wind_speed': 33.52, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T17:58:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 43.7, + 'wind_bearing': 315.14, + 'wind_speed': 33.41, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:03:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 43.7, + 'wind_bearing': 315.14, + 'wind_speed': 33.34, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:08:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 43.8, + 'wind_bearing': 315.14, + 'wind_speed': 33.19, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:13:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 43.9, + 'wind_bearing': 315.14, + 'wind_speed': 33.01, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:18:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 44.0, + 'wind_bearing': 315.14, + 'wind_speed': 32.87, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:23:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 44.2, + 'wind_bearing': 315.14, + 'wind_speed': 32.62, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:28:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 44.3, + 'wind_bearing': 315.14, + 'wind_speed': 32.47, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:33:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 44.4, + 'wind_bearing': 321.71, + 'wind_speed': 32.29, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:38:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 44.6, + 'wind_bearing': 321.71, + 'wind_speed': 32.15, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:43:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 44.7, + 'wind_bearing': 321.71, + 'wind_speed': 31.97, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:48:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 44.8, + 'wind_bearing': 321.71, + 'wind_speed': 31.82, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:53:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 44.9, + 'wind_bearing': 321.71, + 'wind_speed': 31.64, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T18:58:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.1, + 'wind_bearing': 321.71, + 'wind_speed': 31.5, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:03:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.2, + 'wind_bearing': 321.71, + 'wind_speed': 31.5, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:08:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.2, + 'wind_bearing': 321.71, + 'wind_speed': 31.5, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:13:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.3, + 'wind_bearing': 321.71, + 'wind_speed': 31.57, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:18:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.4, + 'wind_bearing': 321.71, + 'wind_speed': 31.64, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:23:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.4, + 'wind_bearing': 321.71, + 'wind_speed': 31.72, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:28:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.5, + 'wind_bearing': 321.71, + 'wind_speed': 31.72, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:33:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.5, + 'wind_bearing': 323.38, + 'wind_speed': 31.82, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:38:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.6, + 'wind_bearing': 323.38, + 'wind_speed': 31.9, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:43:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.7, + 'wind_bearing': 323.38, + 'wind_speed': 31.97, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:48:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.8, + 'wind_bearing': 323.38, + 'wind_speed': 32.04, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:53:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.8, + 'wind_bearing': 323.38, + 'wind_speed': 32.04, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T19:58:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.9, + 'wind_bearing': 323.38, + 'wind_speed': 32.15, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T20:03:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.9, + 'wind_bearing': 323.38, + 'wind_speed': 32.29, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T20:08:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.8, + 'wind_bearing': 323.38, + 'wind_speed': 32.47, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T20:13:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.8, + 'wind_bearing': 323.38, + 'wind_speed': 32.62, + }), + dict({ + 'condition': 'sunny', + 'datetime': '2021-03-07T20:18:00+00:00', + 'precipitation': 0, + 'precipitation_probability': 0, + 'temperature': 45.7, + 'wind_bearing': 323.38, + 'wind_speed': 32.76, + }), + ]), + }), + }) +# --- # name: test_v4_forecast_service[get_forecasts] dict({ 'weather.tomorrow_io_daily': dict({ diff --git a/tests/components/tomorrowio/test_weather.py b/tests/components/tomorrowio/test_weather.py index dd5bfe79ff79..5abed58d233b 100644 --- a/tests/components/tomorrowio/test_weather.py +++ b/tests/components/tomorrowio/test_weather.py @@ -2,12 +2,14 @@ from datetime import datetime, timedelta from typing import Any +from unittest.mock import AsyncMock from freezegun import freeze_time from freezegun.api import FrozenDateTimeFactory import pytest from pytest_homeassistant.common import async_fire_time_changed from pytest_homeassistant.typing import WebSocketGenerator +from pytomorrowio.const import FORECASTS, NOWCAST from syrupy.assertion import SnapshotAssertion from homeassistant.components.tomorrowio.const import ATTRIBUTION, DOMAIN @@ -19,12 +21,13 @@ from homeassistant.components.weather import ( WeatherService, ) from homeassistant.config_entries import RELOAD_AFTER_UPDATE_DELAY -from homeassistant.const import ATTR_ATTRIBUTION, ATTR_FRIENDLY_NAME +from homeassistant.const import ATTR_ATTRIBUTION, ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME from homeassistant.core import HomeAssistant, State, callback from homeassistant.helpers import entity_registry as er from homeassistant.util import dt as dt_util +from homeassistant.util.unit_system import US_CUSTOMARY_SYSTEM -from . import make_v2_config_entry +from . import make_location_subentry_data, make_v2_config_entry from .const import API_V4_ENTRY_DATA, BASE_UNIQUE_ID @@ -350,3 +353,83 @@ async def test_forecast_subscription( assert forecast2 != [] assert forecast2 == snapshot + + +MINUTE_FORECAST_ENTITY_ID = "weather.tomorrow_io_daily" + + +async def _setup_minute_forecast( + hass: HomeAssistant, freezer: FrozenDateTimeFactory +) -> None: + """Set up a location with 5 minute nowcast intervals.""" + # The first nowcast interval (17:48-17:53) has already ended at 17:55 + freezer.move_to(datetime(2021, 3, 7, 17, 55, tzinfo=dt_util.UTC)) + config_entry = make_v2_config_entry( + subentries_data=[make_location_subentry_data(timestep=5)] + ) + config_entry.add_to_hass(hass) + assert await hass.config_entries.async_setup(config_entry.entry_id) + await hass.async_block_till_done() + + +async def _get_minute_forecast(hass: HomeAssistant) -> dict[str, Any]: + """Call the get_minute_forecast action.""" + return await hass.services.async_call( + DOMAIN, + "get_minute_forecast", + {ATTR_ENTITY_ID: MINUTE_FORECAST_ENTITY_ID}, + blocking=True, + return_response=True, + ) + + +async def test_minute_forecast_service( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + tomorrowio_config_entry_update: AsyncMock, + snapshot: SnapshotAssertion, +) -> None: + """Test the get_minute_forecast action.""" + nowcast = tomorrowio_config_entry_update.return_value[FORECASTS][NOWCAST] + # 1.2 mm/h over a 5 minute interval is 0.1 mm + nowcast[1]["values"]["precipitationIntensityAvg"] = 1.2 + await _setup_minute_forecast(hass, freezer) + + response = await _get_minute_forecast(hass) + + forecast = response[MINUTE_FORECAST_ENTITY_ID]["forecast"] + assert forecast[0]["datetime"] == "2021-03-07T17:53:00+00:00" + assert forecast[0]["precipitation"] == pytest.approx(0.1) + assert response == snapshot + + +async def test_minute_forecast_service_keeps_small_amounts( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + tomorrowio_config_entry_update: AsyncMock, +) -> None: + """Test small per-interval amounts survive conversion to coarser units.""" + hass.config.units = US_CUSTOMARY_SYSTEM + nowcast = tomorrowio_config_entry_update.return_value[FORECASTS][NOWCAST] + nowcast[1]["values"]["precipitationIntensityAvg"] = 1.2 + await _setup_minute_forecast(hass, freezer) + + response = await _get_minute_forecast(hass) + + # 0.1 mm is 0.0039 in; rounding to two decimals would report 0.0 + amount = response[MINUTE_FORECAST_ENTITY_ID]["forecast"][0]["precipitation"] + assert amount == pytest.approx(0.1 / 25.4) + + +async def test_minute_forecast_service_no_data( + hass: HomeAssistant, + freezer: FrozenDateTimeFactory, + tomorrowio_config_entry_update: AsyncMock, +) -> None: + """Test the get_minute_forecast action without nowcast data.""" + tomorrowio_config_entry_update.return_value[FORECASTS][NOWCAST] = [] + await _setup_minute_forecast(hass, freezer) + + assert await _get_minute_forecast(hass) == { + MINUTE_FORECAST_ENTITY_ID: {"forecast": []} + }