Skip to content

Commit e5c5a92

Browse files
committed
Remove YAML config and setup UI config
1 parent 5a7c0ae commit e5c5a92

File tree

8 files changed

+267
-149
lines changed

8 files changed

+267
-149
lines changed

custom_components/irm_kmi/__init__.py

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,39 @@
11
"""Integration for IRM KMI weather"""
22

3-
from homeassistant.components.weather import Forecast
4-
class IrmKmiForecast(Forecast):
5-
"""Forecast class with additional attributes for IRM KMI"""
6-
text_fr: str | None
7-
text_nl: str | None
3+
# File inspired from https://github.com/ludeeus/integration_blueprint
4+
5+
from homeassistant.config_entries import ConfigEntry
6+
from homeassistant.core import HomeAssistant
7+
from homeassistant.const import CONF_ZONE
8+
9+
from .const import DOMAIN, PLATFORMS
10+
from .coordinator import IrmKmiCoordinator
11+
from .weather import IrmKmiWeather
12+
13+
14+
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
15+
"""Set up this integration using UI."""
16+
hass.data.setdefault(DOMAIN, {})
17+
18+
hass.data[DOMAIN][entry.entry_id] = coordinator = IrmKmiCoordinator(hass, entry.data[CONF_ZONE])
19+
20+
# https://developers.home-assistant.io/docs/integration_fetching_data#coordinated-single-api-poll-for-data-for-all-entities
21+
await coordinator.async_config_entry_first_refresh()
22+
23+
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
24+
entry.async_on_unload(entry.add_update_listener(async_reload_entry))
25+
26+
return True
27+
28+
29+
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
30+
"""Handle removal of an entry."""
31+
if unloaded := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
32+
hass.data[DOMAIN].pop(entry.entry_id)
33+
return unloaded
34+
35+
36+
async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
37+
"""Reload config entry."""
38+
await async_unload_entry(hass, entry)
39+
await async_setup_entry(hass, entry)

custom_components/irm_kmi/api.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
"""API Client for IRM KMI weather"""
22
from __future__ import annotations
33

4+
import logging
45
import asyncio
56
import socket
67

@@ -9,6 +10,8 @@
910
import hashlib
1011
from datetime import datetime
1112

13+
_LOGGER = logging.getLogger(__name__)
14+
1215

1316
class IrmKmiApiError(Exception):
1417
"""Exception to indicate a general API error."""
@@ -26,20 +29,14 @@ class IrmKmiApiParametersError(
2629
"""Exception to indicate a parameter error."""
2730

2831

29-
class IrmKmiApiAuthenticationError(
30-
IrmKmiApiError
31-
):
32-
"""Exception to indicate an authentication error."""
33-
34-
3532
def _api_key(method_name: str):
3633
"""Get API key."""
3734
return hashlib.md5(f"r9EnW374jkJ9acc;{method_name};{datetime.now().strftime('%d/%m/%Y')}".encode()).hexdigest()
3835

3936

4037
class IrmKmiApiClient:
4138
"""Sample API Client."""
42-
39+
COORD_DECIMALS = 6
4340
def __init__(self, session: aiohttp.ClientSession) -> None:
4441
"""Sample API Client."""
4542
self._session = session
@@ -54,6 +51,11 @@ async def get_forecasts_city(self, city_id: int) -> any:
5451

5552
async def get_forecasts_coord(self, coord: dict) -> any:
5653
"""Get forecasts for given city."""
54+
assert 'lat' in coord
55+
assert 'long' in coord
56+
coord['lat'] = round(coord['lat'], self.COORD_DECIMALS)
57+
coord['long'] = round(coord['long'], self.COORD_DECIMALS)
58+
5759
return await self._api_wrapper(
5860
params={"s": "getForecasts"} | coord
5961
)
@@ -75,13 +77,15 @@ async def _api_wrapper(
7577

7678
try:
7779
async with async_timeout.timeout(10):
80+
_LOGGER.debug(f"Calling for {params}")
7881
response = await self._session.request(
7982
method=method,
8083
url=f"{self._base_url}{path}",
8184
headers=headers,
8285
json=data,
8386
params=params
8487
)
88+
_LOGGER.debug(f"API status code {response.status}")
8589
response.raise_for_status()
8690
return await response.json()
8791

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
import logging
2+
import voluptuous as vol
3+
4+
from homeassistant.components.zone import DOMAIN as ZONE_DOMAIN
5+
from homeassistant.config_entries import ConfigFlow
6+
from homeassistant.const import CONF_ZONE
7+
from homeassistant.data_entry_flow import FlowResult
8+
from homeassistant.helpers.selector import EntitySelector, EntitySelectorConfig
9+
10+
from .const import DOMAIN
11+
12+
_LOGGER = logging.getLogger(__name__)
13+
14+
15+
class IrmKmiConfigFlow(ConfigFlow, domain=DOMAIN):
16+
VERSION = 1
17+
18+
async def async_step_user(self, user_input: dict | None = None) -> FlowResult:
19+
20+
if user_input is not None:
21+
_LOGGER.debug(f"Provided config user is: {user_input}")
22+
23+
await self.async_set_unique_id(user_input[CONF_ZONE])
24+
self._abort_if_unique_id_configured()
25+
26+
state = self.hass.states.get(user_input[CONF_ZONE])
27+
return self.async_create_entry(
28+
title=state.name if state else "IRM KMI",
29+
data={CONF_ZONE: user_input[CONF_ZONE]},
30+
)
31+
32+
return self.async_show_form(
33+
step_id="user",
34+
data_schema=vol.Schema(
35+
{
36+
vol.Required(CONF_ZONE): EntitySelector(
37+
EntitySelectorConfig(domain=ZONE_DOMAIN),
38+
),
39+
}
40+
),
41+
)

custom_components/irm_kmi/const.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,14 @@
1111
ATTR_CONDITION_CLEAR_NIGHT,
1212
ATTR_CONDITION_EXCEPTIONAL
1313
)
14+
from homeassistant.const import Platform
1415

1516
DOMAIN = 'irm_kmi'
17+
PLATFORMS: list[Platform] = [Platform.WEATHER]
18+
OUT_OF_BENELUX = ["außerhalb der Benelux (Brussels)",
19+
"Hors de Belgique (Bxl)",
20+
"Outside the Benelux (Brussels)",
21+
"Buiten de Benelux (Brussel)"]
1622

1723
# map ('ww', 'dayNight') tuple from IRM KMI to HA conditions
1824
IRM_KMI_TO_HA_CONDITION_MAP = {

0 commit comments

Comments
 (0)