Compare commits

...

2 Commits

Author SHA1 Message Date
Lukas Svoboda 5395103c01
Merge pull request #49 from schizza/webook_switching
Refactoring webhook switching.
Added routing management to automaticly update coordinator to avoid restarting HA on configuration change or on new sensor discovery.
2025-02-15 18:23:06 +01:00
schizza 808fad1d97 webhook refactor,
Refactoring webhook switching.
Added routing management to automaticly update coordinator to avoid restarting HA on configuration change or on new sensor discovery.
2025-02-15 18:16:54 +01:00
8 changed files with 165 additions and 49 deletions

View File

@ -22,6 +22,7 @@ from .const import (
WSLINK, WSLINK,
WSLINK_URL, WSLINK_URL,
) )
from .routes import Routes, unregistred
from .utils import ( from .utils import (
anonymize, anonymize,
check_disabled, check_disabled,
@ -54,7 +55,7 @@ class WeatherDataUpdateCoordinator(DataUpdateCoordinator):
async def recieved_data(self, webdata): async def recieved_data(self, webdata):
"""Handle incoming data query.""" """Handle incoming data query."""
_wslink = self.config_entry.data.get(WSLINK) _wslink = self.config_entry.options.get(WSLINK)
data = webdata.query data = webdata.query
response = None response = None
@ -108,7 +109,7 @@ class WeatherDataUpdateCoordinator(DataUpdateCoordinator):
if _loaded_sensors := loaded_sensors(self.config_entry): if _loaded_sensors := loaded_sensors(self.config_entry):
sensors.extend(_loaded_sensors) sensors.extend(_loaded_sensors)
await update_options(self.hass, self.config_entry, SENSORS_TO_LOAD, sensors) await update_options(self.hass, self.config_entry, SENSORS_TO_LOAD, sensors)
await self.hass.config_entries.async_reload(self.config.entry_id) # await self.hass.config_entries.async_reload(self.config.entry_id)
self.async_set_updated_data(remaped_items) self.async_set_updated_data(remaped_items)
@ -120,16 +121,54 @@ class WeatherDataUpdateCoordinator(DataUpdateCoordinator):
def register_path( def register_path(
hass: HomeAssistant, url_path: str, coordinator: WeatherDataUpdateCoordinator hass: HomeAssistant,
url_path: str,
coordinator: WeatherDataUpdateCoordinator,
config: ConfigEntry,
): ):
"""Register path to handle incoming data.""" """Register path to handle incoming data."""
_wslink = hass.config_entries.async_get_entry(WSLINK) hass_data = hass.data.setdefault(DOMAIN, {})
debug = config.options.get(DEV_DBG)
_wslink = config.options.get(WSLINK)
routes: Routes = hass_data.get("routes") if "routes" in hass_data else None
if routes is None:
routes = Routes()
_LOGGER.info("Routes not found, creating new routes")
if debug:
_LOGGER.debug("Enabled route is: %s, WSLink is %s", url_path, _wslink)
try: try:
route = hass.http.app.router.add_route( default_route = hass.http.app.router.add_get(
"GET", url_path, coordinator.recieved_data DEFAULT_URL,
coordinator.recieved_data if not _wslink else unregistred,
name="weather_default_url",
) )
if debug:
_LOGGER.debug("Default route: %s", default_route)
wslink_route = hass.http.app.router.add_get(
WSLINK_URL,
coordinator.recieved_data if _wslink else unregistred,
name="weather_wslink_url",
)
if debug:
_LOGGER.debug("WSLink route: %s", wslink_route)
routes.add_route(
DEFAULT_URL,
default_route,
coordinator.recieved_data if not _wslink else unregistred,
not _wslink,
)
routes.add_route(
WSLINK_URL, wslink_route, coordinator.recieved_data, _wslink
)
hass_data["routes"] = routes
except RuntimeError as Ex: # pylint: disable=(broad-except) except RuntimeError as Ex: # pylint: disable=(broad-except)
if ( if (
@ -137,25 +176,22 @@ def register_path(
in Ex.args in Ex.args
): ):
_LOGGER.info("Handler to URL (%s) already registred", url_path) _LOGGER.info("Handler to URL (%s) already registred", url_path)
return True return False
_LOGGER.error("Unable to register URL handler! (%s)", Ex.args) _LOGGER.error("Unable to register URL handler! (%s)", Ex.args)
return False return False
_LOGGER.info( _LOGGER.info(
"Registered path to handle weather data: %s", "Registered path to handle weather data: %s",
route.get_info(), # pylint: disable=used-before-assignment routes.get_enabled(), # pylint: disable=used-before-assignment
) )
return True
if _wslink:
routes.switch_route(coordinator.recieved_data, WSLINK_URL)
else:
routes.switch_route(coordinator.recieved_data, DEFAULT_URL)
def unregister_path(hass: HomeAssistant): return routes
"""Unregister path to handle incoming data."""
_LOGGER.error(
"""Unable to delete webhook from API! Restart HA before adding integration!
If this error is raised while adding sensors or reloading configuration, you can ignore this error
"""
)
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
@ -163,16 +199,25 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
coordinator = WeatherDataUpdateCoordinator(hass, entry) coordinator = WeatherDataUpdateCoordinator(hass, entry)
hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator hass_data = hass.data.setdefault(DOMAIN, {})
hass_data[entry.entry_id] = coordinator
_wslink = entry.data.get(WSLINK) _wslink = entry.options.get(WSLINK)
debug = entry.options.get(DEV_DBG)
_LOGGER.info("WS Link is %s", "enbled" if _wslink else "disabled") if debug:
_LOGGER.debug("WS Link is %s", "enbled" if _wslink else "disabled")
if not register_path(hass, DEFAULT_URL if not _wslink else WSLINK_URL, coordinator): route = register_path(
hass, DEFAULT_URL if not _wslink else WSLINK_URL, coordinator, entry
)
if not route:
_LOGGER.error("Fatal: path not registered!") _LOGGER.error("Fatal: path not registered!")
raise PlatformNotReady raise PlatformNotReady
hass_data["route"] = route
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS) await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
entry.async_on_unload(entry.add_update_listener(update_listener)) entry.async_on_unload(entry.add_update_listener(update_listener))
@ -182,10 +227,8 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
async def update_listener(hass: HomeAssistant, entry: ConfigEntry): async def update_listener(hass: HomeAssistant, entry: ConfigEntry):
"""Update setup listener.""" """Update setup listener."""
# Disabled as on fire async_reload, integration stops writing data,
# and we don't need to reload config entry for proper work.
# await hass.config_entries.async_reload(entry.entry_id) await hass.config_entries.async_reload(entry.entry_id)
_LOGGER.info("Settings updated") _LOGGER.info("Settings updated")
@ -196,6 +239,5 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS) _ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
if _ok: if _ok:
hass.data[DOMAIN].pop(entry.entry_id) hass.data[DOMAIN].pop(entry.entry_id)
unregister_path(hass)
return _ok return _ok

View File

@ -50,7 +50,7 @@ class ConfigOptionsFlowHandler(OptionsFlow):
def _get_entry_data(self): def _get_entry_data(self):
"""Get entry data.""" """Get entry data."""
self.user_data: dict[str, str] = { self.user_data: dict[str, Any] = {
API_ID: self.config_entry.options.get(API_ID), API_ID: self.config_entry.options.get(API_ID),
API_KEY: self.config_entry.options.get(API_KEY), API_KEY: self.config_entry.options.get(API_KEY),
WSLINK: self.config_entry.options.get(WSLINK), WSLINK: self.config_entry.options.get(WSLINK),
@ -208,7 +208,6 @@ class ConfigFlow(ConfigFlow, domain=DOMAIN):
errors=errors, errors=errors,
) )
@staticmethod @staticmethod
@callback @callback
def async_get_options_flow(config_entry) -> ConfigOptionsFlowHandler: def async_get_options_flow(config_entry) -> ConfigOptionsFlowHandler:

View File

@ -10,6 +10,6 @@
"issue_tracker": "https://github.com/schizza/SWS-12500-custom-component/issues", "issue_tracker": "https://github.com/schizza/SWS-12500-custom-component/issues",
"requirements": [], "requirements": [],
"ssdp": [], "ssdp": [],
"version": "0.1.4.0", "version": "1.5.0",
"zeroconf": [] "zeroconf": []
} }

View File

@ -0,0 +1,76 @@
"""Store routes info."""
from dataclasses import dataclass
from logging import getLogger
from aiohttp.web import AbstractRoute, Response
_LOGGER = getLogger(__name__)
@dataclass
class Route:
"""Store route info."""
url_path: str
route: AbstractRoute
handler: callable
enabled: bool = False
def __str__(self):
"""Return string representation."""
return f"{self.url_path} -> {self.handler}"
class Routes:
"""Store routes info."""
def __init__(self) -> None:
"""Initialize routes."""
self.routes = {}
def switch_route(self, coordinator: callable, url_path: str):
"""Switch route."""
for url, route in self.routes.items():
if url == url_path:
_LOGGER.info("New coordinator to route: %s", route.url_path)
route.enabled = True
route.handler = coordinator
route.route._handler = coordinator # noqa: SLF001
else:
route.enabled = False
route.handler = unregistred
route.route._handler = unregistred # noqa: SLF001
def add_route(
self,
url_path: str,
route: AbstractRoute,
handler: callable,
enabled: bool = False,
):
"""Add route."""
self.routes[url_path] = Route(url_path, route, handler, enabled)
def get_route(self, url_path: str) -> Route:
"""Get route."""
return self.routes.get(url_path)
def get_enabled(self) -> str:
"""Get enabled routes."""
enabled_routes = [
route.url_path for route in self.routes.values() if route.enabled
]
return "".join(enabled_routes) if enabled_routes else "None"
def __str__(self):
"""Return string representation."""
return "\n".join([str(route) for route in self.routes.values()])
async def unregistred(*args, **kwargs):
"""Unregister path to handle incoming data."""
_LOGGER.error("Recieved data to unregistred webhook. Check your settings")
return Response(body=f"{'Unregistred webhook.'}", status=404)

View File

@ -103,7 +103,7 @@
"notify": { "notify": {
"added": { "added": {
"title": "New sensors for SWS 12500 found.", "title": "New sensors for SWS 12500 found.",
"message": "{added_sensors}\n<b>HomeAssistant needs to be restarted for proper integreation run.</b>" "message": "{added_sensors}\n"
} }
} }
} }

View File

@ -110,7 +110,7 @@
"notify": { "notify": {
"added": { "added": {
"title": "Nalezeny nové senzory pro SWS 12500.", "title": "Nalezeny nové senzory pro SWS 12500.",
"message": "{added_sensors}\n<b>Je třeba restartovat Home Assistenta pro správnou funkci komponenty.</b>" "message": "{added_sensors}\n"
} }
} }
} }

View File

@ -111,7 +111,7 @@
"notify": { "notify": {
"added": { "added": {
"title": "New sensors for SWS 12500 found.", "title": "New sensors for SWS 12500 found.",
"message": "{added_sensors}\n<b>HomeAssistant needs to be restarted for proper integreation run.</b>" "message": "{added_sensors}\n"
} }
} }
} }

View File

@ -46,6 +46,7 @@ async def translations(
) )
if localize_key in _translations: if localize_key in _translations:
return _translations[localize_key] return _translations[localize_key]
return None
async def translated_notification( async def translated_notification(
@ -101,7 +102,7 @@ def anonymize(data):
anonym = {} anonym = {}
for k in data: for k in data:
if k not in ("ID", "PASSWORD", "wsid", "wspw"): if k not in {"ID", "PASSWORD", "wsid", "wspw"}:
anonym[k] = data[k] anonym[k] = data[k]
return anonym return anonym
@ -131,9 +132,7 @@ def loaded_sensors(config_entry: ConfigEntry) -> list | None:
"""Get loaded sensors.""" """Get loaded sensors."""
return ( return (
config_entry.options.get(SENSORS_TO_LOAD) config_entry.options.get(SENSORS_TO_LOAD) or []
if config_entry.options.get(SENSORS_TO_LOAD)
else []
) )