Compare commits

..

No commits in common. "5395103c013eac95bbdfd83a349fbf443b7bf499" and "bbb6a23b6c98f60e6ad722c45360be2aea514b8f" have entirely different histories.

8 changed files with 49 additions and 165 deletions

View File

@ -22,7 +22,6 @@ 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,
@ -55,7 +54,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.options.get(WSLINK) _wslink = self.config_entry.data.get(WSLINK)
data = webdata.query data = webdata.query
response = None response = None
@ -109,7 +108,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)
@ -121,77 +120,42 @@ class WeatherDataUpdateCoordinator(DataUpdateCoordinator):
def register_path( def register_path(
hass: HomeAssistant, hass: HomeAssistant, url_path: str, coordinator: WeatherDataUpdateCoordinator
url_path: str,
coordinator: WeatherDataUpdateCoordinator,
config: ConfigEntry,
): ):
"""Register path to handle incoming data.""" """Register path to handle incoming data."""
hass_data = hass.data.setdefault(DOMAIN, {}) _wslink = hass.config_entries.async_get_entry(WSLINK)
debug = config.options.get(DEV_DBG)
_wslink = config.options.get(WSLINK)
routes: Routes = hass_data.get("routes") if "routes" in hass_data else None try:
route = hass.http.app.router.add_route(
if routes is None: "GET", url_path, coordinator.recieved_data
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:
default_route = hass.http.app.router.add_get(
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)
if (
"Added route will never be executed, method GET is already registered"
in Ex.args
):
_LOGGER.info("Handler to URL (%s) already registred", url_path)
return False
_LOGGER.error("Unable to register URL handler! (%s)", Ex.args)
return False
_LOGGER.info(
"Registered path to handle weather data: %s",
routes.get_enabled(), # pylint: disable=used-before-assignment
) )
if _wslink: except RuntimeError as Ex: # pylint: disable=(broad-except)
routes.switch_route(coordinator.recieved_data, WSLINK_URL) if (
else: "Added route will never be executed, method GET is already registered"
routes.switch_route(coordinator.recieved_data, DEFAULT_URL) in Ex.args
):
_LOGGER.info("Handler to URL (%s) already registred", url_path)
return True
return routes _LOGGER.error("Unable to register URL handler! (%s)", Ex.args)
return False
_LOGGER.info(
"Registered path to handle weather data: %s",
route.get_info(), # pylint: disable=used-before-assignment
)
return True
def unregister_path(hass: HomeAssistant):
"""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:
@ -199,25 +163,16 @@ async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
coordinator = WeatherDataUpdateCoordinator(hass, entry) coordinator = WeatherDataUpdateCoordinator(hass, entry)
hass_data = hass.data.setdefault(DOMAIN, {}) hass.data.setdefault(DOMAIN, {})[entry.entry_id] = coordinator
hass_data[entry.entry_id] = coordinator
_wslink = entry.options.get(WSLINK) _wslink = entry.data.get(WSLINK)
debug = entry.options.get(DEV_DBG)
if debug: _LOGGER.info("WS Link is %s", "enbled" if _wslink else "disabled")
_LOGGER.debug("WS Link is %s", "enbled" if _wslink else "disabled")
route = register_path( if not register_path(hass, DEFAULT_URL if not _wslink else WSLINK_URL, coordinator):
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))
@ -227,8 +182,10 @@ 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")
@ -239,5 +196,6 @@ 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, Any] = { self.user_data: dict[str, str] = {
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,6 +208,7 @@ 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": "1.5.0", "version": "0.1.4.0",
"zeroconf": [] "zeroconf": []
} }

View File

@ -1,76 +0,0 @@
"""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" "message": "{added_sensors}\n<b>HomeAssistant needs to be restarted for proper integreation run.</b>"
} }
} }
} }

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" "message": "{added_sensors}\n<b>Je třeba restartovat Home Assistenta pro správnou funkci komponenty.</b>"
} }
} }
} }

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" "message": "{added_sensors}\n<b>HomeAssistant needs to be restarted for proper integreation run.</b>"
} }
} }
} }

View File

@ -46,7 +46,6 @@ 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(
@ -102,7 +101,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
@ -132,7 +131,9 @@ def loaded_sensors(config_entry: ConfigEntry) -> list | None:
"""Get loaded sensors.""" """Get loaded sensors."""
return ( return (
config_entry.options.get(SENSORS_TO_LOAD) or [] config_entry.options.get(SENSORS_TO_LOAD)
if config_entry.options.get(SENSORS_TO_LOAD)
else []
) )