Add support for more config options

This commit is contained in:
Jules 2023-12-29 23:05:50 +01:00
parent 974d6baca2
commit 2b8fa6e444
Signed by: jdejaegh
GPG key ID: 99D6D184CA66933A
4 changed files with 47 additions and 7 deletions

View file

@ -1,18 +1,23 @@
"""Integration for IRM KMI weather""" """Integration for IRM KMI weather"""
# File inspired from https://github.com/ludeeus/integration_blueprint # File inspired from https://github.com/ludeeus/integration_blueprint
import logging
from homeassistant.config_entries import ConfigEntry from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryError from homeassistant.exceptions import ConfigEntryError
from .const import DOMAIN, PLATFORMS from .const import DOMAIN, PLATFORMS, CONF_DARK_MODE, CONF_STYLE_STD, CONF_STYLE
from .coordinator import IrmKmiCoordinator from .coordinator import IrmKmiCoordinator
from .weather import IrmKmiWeather from .weather import IrmKmiWeather
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
"""Set up this integration using UI.""" """Set up this integration using UI."""
_LOGGER.debug(f"Setting up entry v{entry.version}")
hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})
hass.data[DOMAIN][entry.entry_id] = coordinator = IrmKmiCoordinator(hass, entry) hass.data[DOMAIN][entry.entry_id] = coordinator = IrmKmiCoordinator(hass, entry)
@ -41,3 +46,24 @@ async def async_reload_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
"""Reload config entry.""" """Reload config entry."""
await async_unload_entry(hass, entry) await async_unload_entry(hass, entry)
await async_setup_entry(hass, entry) await async_setup_entry(hass, entry)
async def async_migrate_entry(hass, config_entry: ConfigEntry):
"""Migrate old entry."""
_LOGGER.debug(f"Migrating from version {config_entry.version}")
if config_entry.version > 1:
# This means the user has downgraded from a future version
return False
new = {**config_entry.data}
if config_entry.version == 1:
new = new | {CONF_STYLE: CONF_STYLE_STD, CONF_DARK_MODE: True}
config_entry.version = 2
hass.config_entries.async_update_entry(config_entry, data=new)
_LOGGER.debug(f"Migration to version {config_entry.version} successful")
return True

View file

@ -19,7 +19,7 @@ _LOGGER = logging.getLogger(__name__)
class IrmKmiConfigFlow(ConfigFlow, domain=DOMAIN): class IrmKmiConfigFlow(ConfigFlow, domain=DOMAIN):
VERSION = 1 VERSION = 2
async def async_step_user(self, user_input: dict | None = None) -> FlowResult: async def async_step_user(self, user_input: dict | None = None) -> FlowResult:
"""Define the user step of the configuration flow.""" """Define the user step of the configuration flow."""

View file

@ -38,6 +38,13 @@ CONF_STYLE_OPTIONS: Final = [
CONF_DARK_MODE: Final = "dark_mode" CONF_DARK_MODE: Final = "dark_mode"
STYLE_TO_PARAM_MAP: Final = {
CONF_STYLE_STD: 1,
CONF_STYLE_CONTRAST: 2,
CONF_STYLE_YELLOW_RED: 3,
CONF_STYLE_SATELLITE: 4
}
# map ('ww', 'dayNight') tuple from IRM KMI to HA conditions # map ('ww', 'dayNight') tuple from IRM KMI to HA conditions
IRM_KMI_TO_HA_CONDITION_MAP: Final = { IRM_KMI_TO_HA_CONDITION_MAP: Final = {
(0, 'd'): ATTR_CONDITION_SUNNY, (0, 'd'): ATTR_CONDITION_SUNNY,

View file

@ -18,8 +18,9 @@ from homeassistant.helpers.update_coordinator import (DataUpdateCoordinator,
from PIL import Image, ImageDraw, ImageFont from PIL import Image, ImageDraw, ImageFont
from .api import IrmKmiApiClient, IrmKmiApiError from .api import IrmKmiApiClient, IrmKmiApiError
from .const import CONF_DARK_MODE, CONF_STYLE, CONF_STYLE_SATELLITE
from .const import IRM_KMI_TO_HA_CONDITION_MAP as CDT_MAP from .const import IRM_KMI_TO_HA_CONDITION_MAP as CDT_MAP
from .const import LANGS, OUT_OF_BENELUX from .const import LANGS, OUT_OF_BENELUX, STYLE_TO_PARAM_MAP
from .data import (AnimationFrameData, CurrentWeatherData, IrmKmiForecast, from .data import (AnimationFrameData, CurrentWeatherData, IrmKmiForecast,
ProcessedCoordinatorData, RadarAnimationData) ProcessedCoordinatorData, RadarAnimationData)
from .utils import disable_from_config from .utils import disable_from_config
@ -126,13 +127,15 @@ class IrmKmiCoordinator(DataUpdateCoordinator):
localisation_layer_url: str) -> tuple[Any]: localisation_layer_url: str) -> tuple[Any]:
"""Download a batch of images to create the radar frames.""" """Download a batch of images to create the radar frames."""
coroutines = list() coroutines = list()
dark_mode = self._config_entry.data[CONF_DARK_MODE]
style = self._config_entry.data[CONF_STYLE]
coroutines.append( coroutines.append(
self._api_client.get_image(localisation_layer_url, self._api_client.get_image(localisation_layer_url,
params={'th': 'd' if country == 'NL' else 'n'})) params={'th': 'd' if country == 'NL' or not dark_mode else 'n'}))
for frame in animation_data: for frame in animation_data:
if frame.get('uri', None) is not None: if frame.get('uri', None) is not None:
coroutines.append(self._api_client.get_image(frame.get('uri'))) coroutines.append(self._api_client.get_image(frame.get('uri'), params={'rs': STYLE_TO_PARAM_MAP[style]}))
async with async_timeout.timeout(20): async with async_timeout.timeout(20):
images_from_api = await asyncio.gather(*coroutines) images_from_api = await asyncio.gather(*coroutines)
@ -149,13 +152,17 @@ class IrmKmiCoordinator(DataUpdateCoordinator):
Adds text in the top right to specify the timestamp of each image.""" Adds text in the top right to specify the timestamp of each image."""
background: Image background: Image
fill_color: tuple fill_color: tuple
dark_mode = self._config_entry.data[CONF_DARK_MODE]
satellite_mode = self._config_entry.data[CONF_STYLE] == CONF_STYLE_SATELLITE
if country == 'NL': if country == 'NL':
background = Image.open("custom_components/irm_kmi/resources/nl.png").convert('RGBA') background = Image.open("custom_components/irm_kmi/resources/nl.png").convert('RGBA')
fill_color = (0, 0, 0) fill_color = (0, 0, 0)
else: else:
background = Image.open("custom_components/irm_kmi/resources/be_black.png").convert('RGBA') image_path = (f"custom_components/irm_kmi/resources/be_"
fill_color = (255, 255, 255) f"{'satellite' if satellite_mode else 'black' if dark_mode else 'white'}.png")
background = (Image.open(image_path).convert('RGBA'))
fill_color = (255, 255, 255) if dark_mode or satellite_mode else (0, 0, 0)
most_recent_frame = None most_recent_frame = None
tz = pytz.timezone(self.hass.config.time_zone) tz = pytz.timezone(self.hass.config.time_zone)