Skip to content

Commit dc4115b

Browse files
committed
Add more attributes to current weather entity
1 parent 11c3b11 commit dc4115b

File tree

3 files changed

+69
-10
lines changed

3 files changed

+69
-10
lines changed

custom_components/irm_kmi/api.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -40,10 +40,7 @@ def _api_key(method_name: str):
4040
class IrmKmiApiClient:
4141
"""Sample API Client."""
4242

43-
def __init__(
44-
self,
45-
session: aiohttp.ClientSession,
46-
) -> None:
43+
def __init__(self, session: aiohttp.ClientSession) -> None:
4744
"""Sample API Client."""
4845
self._session = session
4946
self._base_url = "https://app.meteo.be/services/appv4/"
@@ -55,6 +52,12 @@ async def get_forecasts_city(self, city_id: int) -> any:
5552
"s": "getForecasts"}
5653
)
5754

55+
async def get_forecasts_coord(self, coord: dict) -> any:
56+
"""Get forecasts for given city."""
57+
return await self._api_wrapper(
58+
params={"s": "getForecasts"} | coord
59+
)
60+
5861
async def _api_wrapper(
5962
self,
6063
params: dict,

custom_components/irm_kmi/coordinator.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,11 @@
1515

1616
_LOGGER = logging.getLogger(__name__)
1717

18+
1819
class IrmKmiCoordinator(DataUpdateCoordinator):
1920
"""Coordinator to update data from IRM KMI"""
2021

21-
def __init__(self, hass, city_id):
22+
def __init__(self, hass, coord: dict):
2223
"""Initialize my coordinator."""
2324
super().__init__(
2425
hass,
@@ -29,7 +30,7 @@ def __init__(self, hass, city_id):
2930
update_interval=timedelta(seconds=30),
3031
)
3132
self._api_client = IrmKmiApiClient(session=async_get_clientsession(hass))
32-
self._city_id = city_id
33+
self._coord = coord
3334

3435
async def _async_update_data(self):
3536
"""Fetch data from API endpoint.
@@ -44,7 +45,7 @@ async def _async_update_data(self):
4445
# Grab active context variables to limit data required to be fetched from API
4546
# Note: using context is not required if there is no need or ability to limit
4647
# data retrieved from API.
47-
data = await self._api_client.get_forecasts_city(city_id=self._city_id)
48+
data = await self._api_client.get_forecasts_coord(self._coord)
4849
return data
4950
except IrmKmiApiError as err:
5051
raise UpdateFailed(f"Error communicating with API: {err}")

custom_components/irm_kmi/weather.py

Lines changed: 58 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
import logging
22

3+
from datetime import datetime
4+
35
from homeassistant.components.weather import WeatherEntity
4-
from homeassistant.const import UnitOfTemperature
6+
from homeassistant.const import UnitOfTemperature, UnitOfSpeed, UnitOfPrecipitationDepth, UnitOfPressure
57
from homeassistant.helpers.update_coordinator import (
68
CoordinatorEntity,
79
)
@@ -14,7 +16,8 @@
1416

1517
async def async_setup_platform(hass, config, async_add_entities, discovery_info=None):
1618
_LOGGER.debug(f"IRM KMI setup. Config: {config}")
17-
coordinator = IrmKmiCoordinator(hass, city_id=config.get("city_id"))
19+
coordinator = IrmKmiCoordinator(hass, coord={'lat': config.get("lat"), 'long': config.get("lon")})
20+
1821
await coordinator.async_request_refresh()
1922

2023
async_add_entities([IrmKmiWeather(
@@ -29,6 +32,14 @@ def __init__(self, coordinator: IrmKmiCoordinator, name: str) -> None:
2932
super().__init__(coordinator)
3033
self._name = name
3134

35+
def _current_hour_data(self) -> dict | None:
36+
data = self.coordinator.data.get('for', {}).get('hourly')
37+
if data is None or not isinstance(data, list) or len(data) == 0:
38+
return None
39+
data = data[0]
40+
if datetime.now().strftime('%H') != data['hour']:
41+
return None
42+
return data
3243
@property
3344
def name(self) -> str:
3445
return self._name
@@ -44,5 +55,49 @@ def native_temperature(self) -> float | None:
4455
return self.coordinator.data.get('obs', {}).get('temp')
4556

4657
@property
47-
def native_temperature_unit(self) -> str:
58+
def native_temperature_unit(self) -> str | None:
4859
return UnitOfTemperature.CELSIUS
60+
61+
@property
62+
def native_wind_speed_unit(self) -> str | None:
63+
return UnitOfSpeed.KILOMETERS_PER_HOUR
64+
65+
@property
66+
def native_wind_speed(self) -> float | None:
67+
data = self._current_hour_data()
68+
return data.get('windSpeedKm', None)
69+
70+
@property
71+
def native_wind_gust_speed(self) -> float | None:
72+
data = self._current_hour_data()
73+
return data.get('windPeakSpeedKm', None)
74+
75+
@property
76+
def wind_bearing(self) -> float | str | None:
77+
data = self._current_hour_data()
78+
return data.get('windDirection', None)
79+
80+
@property
81+
def native_precipitation_unit(self) -> str | None:
82+
return UnitOfPrecipitationDepth.MILLIMETERS
83+
84+
@property
85+
def native_pressure(self) -> float | None:
86+
data = self._current_hour_data()
87+
return data.get('pressure', None)
88+
89+
@property
90+
def native_pressure_unit(self) -> str | None:
91+
return UnitOfPressure.HPA
92+
93+
@property
94+
def uv_index(self) -> float | None:
95+
data = self.coordinator.data.get('module', None)
96+
if data is None or not isinstance(data, list):
97+
return None
98+
99+
for module in data:
100+
if module.get('type', None) == 'uv':
101+
return module.get('data', {}).get('levelValue')
102+
103+
return None

0 commit comments

Comments
 (0)