Skip to content

Commit

Permalink
Remove YAML config and setup UI config
Browse files Browse the repository at this point in the history
  • Loading branch information
jdejaegh committed Dec 26, 2023
1 parent 5a7c0ae commit e5c5a92
Show file tree
Hide file tree
Showing 8 changed files with 267 additions and 149 deletions.
42 changes: 37 additions & 5 deletions custom_components/irm_kmi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
"""Integration for IRM KMI weather"""

from homeassistant.components.weather import Forecast
class IrmKmiForecast(Forecast):
"""Forecast class with additional attributes for IRM KMI"""
text_fr: str | None
text_nl: str | None
# File inspired from https://github.com/ludeeus/integration_blueprint

from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.const import CONF_ZONE

from .const import DOMAIN, PLATFORMS
from .coordinator import IrmKmiCoordinator
from .weather import IrmKmiWeather


async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up this integration using UI."""
hass.data.setdefault(DOMAIN, {})

hass.data[DOMAIN][entry.entry_id] = coordinator = IrmKmiCoordinator(hass, entry.data[CONF_ZONE])

# https://developers.home-assistant.io/docs/integration_fetching_data#coordinated-single-api-poll-for-data-for-all-entities
await coordinator.async_config_entry_first_refresh()

await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(async_reload_entry))

return True


async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Handle removal of an entry."""
if unloaded := await hass.config_entries.async_unload_platforms(entry, PLATFORMS):
hass.data[DOMAIN].pop(entry.entry_id)
return unloaded


async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry."""
await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry)
18 changes: 11 additions & 7 deletions custom_components/irm_kmi/api.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""API Client for IRM KMI weather"""
from __future__ import annotations

import logging
import asyncio
import socket

Expand All @@ -9,6 +10,8 @@
import hashlib
from datetime import datetime

_LOGGER = logging.getLogger(__name__)


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


class IrmKmiApiAuthenticationError(
IrmKmiApiError
):
"""Exception to indicate an authentication error."""


def _api_key(method_name: str):
"""Get API key."""
return hashlib.md5(f"r9EnW374jkJ9acc;{method_name};{datetime.now().strftime('%d/%m/%Y')}".encode()).hexdigest()


class IrmKmiApiClient:
"""Sample API Client."""

COORD_DECIMALS = 6
def __init__(self, session: aiohttp.ClientSession) -> None:
"""Sample API Client."""
self._session = session
Expand All @@ -54,6 +51,11 @@ async def get_forecasts_city(self, city_id: int) -> any:

async def get_forecasts_coord(self, coord: dict) -> any:
"""Get forecasts for given city."""
assert 'lat' in coord
assert 'long' in coord
coord['lat'] = round(coord['lat'], self.COORD_DECIMALS)
coord['long'] = round(coord['long'], self.COORD_DECIMALS)

return await self._api_wrapper(
params={"s": "getForecasts"} | coord
)
Expand All @@ -75,13 +77,15 @@ async def _api_wrapper(

try:
async with async_timeout.timeout(10):
_LOGGER.debug(f"Calling for {params}")
response = await self._session.request(
method=method,
url=f"{self._base_url}{path}",
headers=headers,
json=data,
params=params
)
_LOGGER.debug(f"API status code {response.status}")
response.raise_for_status()
return await response.json()

Expand Down
41 changes: 41 additions & 0 deletions custom_components/irm_kmi/config_flow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import logging
import voluptuous as vol

from homeassistant.components.zone import DOMAIN as ZONE_DOMAIN
from homeassistant.config_entries import ConfigFlow
from homeassistant.const import CONF_ZONE
from homeassistant.data_entry_flow import FlowResult
from homeassistant.helpers.selector import EntitySelector, EntitySelectorConfig

from .const import DOMAIN

_LOGGER = logging.getLogger(__name__)


class IrmKmiConfigFlow(ConfigFlow, domain=DOMAIN):
VERSION = 1

async def async_step_user(self, user_input: dict | None = None) -> FlowResult:

if user_input is not None:
_LOGGER.debug(f"Provided config user is: {user_input}")

await self.async_set_unique_id(user_input[CONF_ZONE])
self._abort_if_unique_id_configured()

state = self.hass.states.get(user_input[CONF_ZONE])
return self.async_create_entry(
title=state.name if state else "IRM KMI",
data={CONF_ZONE: user_input[CONF_ZONE]},
)

return self.async_show_form(
step_id="user",
data_schema=vol.Schema(
{
vol.Required(CONF_ZONE): EntitySelector(
EntitySelectorConfig(domain=ZONE_DOMAIN),
),
}
),
)
6 changes: 6 additions & 0 deletions custom_components/irm_kmi/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,14 @@
ATTR_CONDITION_CLEAR_NIGHT,
ATTR_CONDITION_EXCEPTIONAL
)
from homeassistant.const import Platform

DOMAIN = 'irm_kmi'
PLATFORMS: list[Platform] = [Platform.WEATHER]
OUT_OF_BENELUX = ["außerhalb der Benelux (Brussels)",
"Hors de Belgique (Bxl)",
"Outside the Benelux (Brussels)",
"Buiten de Benelux (Brussel)"]

# map ('ww', 'dayNight') tuple from IRM KMI to HA conditions
IRM_KMI_TO_HA_CONDITION_MAP = {
Expand Down
Loading

0 comments on commit e5c5a92

Please sign in to comment.