Compare commits
2 Commits
bbb6a23b6c
...
5395103c01
| Author | SHA1 | Date |
|---|---|---|
|
|
5395103c01 | |
|
|
808fad1d97 |
|
|
@ -22,6 +22,7 @@ from .const import (
|
|||
WSLINK,
|
||||
WSLINK_URL,
|
||||
)
|
||||
from .routes import Routes, unregistred
|
||||
from .utils import (
|
||||
anonymize,
|
||||
check_disabled,
|
||||
|
|
@ -54,7 +55,7 @@ class WeatherDataUpdateCoordinator(DataUpdateCoordinator):
|
|||
|
||||
async def recieved_data(self, webdata):
|
||||
"""Handle incoming data query."""
|
||||
_wslink = self.config_entry.data.get(WSLINK)
|
||||
_wslink = self.config_entry.options.get(WSLINK)
|
||||
data = webdata.query
|
||||
|
||||
response = None
|
||||
|
|
@ -108,7 +109,7 @@ class WeatherDataUpdateCoordinator(DataUpdateCoordinator):
|
|||
if _loaded_sensors := loaded_sensors(self.config_entry):
|
||||
sensors.extend(_loaded_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)
|
||||
|
||||
|
|
@ -120,16 +121,54 @@ class WeatherDataUpdateCoordinator(DataUpdateCoordinator):
|
|||
|
||||
|
||||
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."""
|
||||
|
||||
_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:
|
||||
route = hass.http.app.router.add_route(
|
||||
"GET", url_path, coordinator.recieved_data
|
||||
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 (
|
||||
|
|
@ -137,25 +176,22 @@ def register_path(
|
|||
in Ex.args
|
||||
):
|
||||
_LOGGER.info("Handler to URL (%s) already registred", url_path)
|
||||
return True
|
||||
return False
|
||||
|
||||
_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
|
||||
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):
|
||||
"""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
|
||||
"""
|
||||
)
|
||||
return routes
|
||||
|
||||
|
||||
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)
|
||||
|
||||
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!")
|
||||
raise PlatformNotReady
|
||||
|
||||
hass_data["route"] = route
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
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):
|
||||
"""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")
|
||||
|
||||
|
|
@ -196,6 +239,5 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|||
_ok = await hass.config_entries.async_unload_platforms(entry, PLATFORMS)
|
||||
if _ok:
|
||||
hass.data[DOMAIN].pop(entry.entry_id)
|
||||
unregister_path(hass)
|
||||
|
||||
return _ok
|
||||
|
|
|
|||
|
|
@ -50,7 +50,7 @@ class ConfigOptionsFlowHandler(OptionsFlow):
|
|||
def _get_entry_data(self):
|
||||
"""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_KEY: self.config_entry.options.get(API_KEY),
|
||||
WSLINK: self.config_entry.options.get(WSLINK),
|
||||
|
|
@ -208,7 +208,6 @@ class ConfigFlow(ConfigFlow, domain=DOMAIN):
|
|||
errors=errors,
|
||||
)
|
||||
|
||||
|
||||
@staticmethod
|
||||
@callback
|
||||
def async_get_options_flow(config_entry) -> ConfigOptionsFlowHandler:
|
||||
|
|
|
|||
|
|
@ -10,6 +10,6 @@
|
|||
"issue_tracker": "https://github.com/schizza/SWS-12500-custom-component/issues",
|
||||
"requirements": [],
|
||||
"ssdp": [],
|
||||
"version": "0.1.4.0",
|
||||
"version": "1.5.0",
|
||||
"zeroconf": []
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
@ -103,7 +103,7 @@
|
|||
"notify": {
|
||||
"added": {
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -110,7 +110,7 @@
|
|||
"notify": {
|
||||
"added": {
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -111,7 +111,7 @@
|
|||
"notify": {
|
||||
"added": {
|
||||
"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"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -46,6 +46,7 @@ async def translations(
|
|||
)
|
||||
if localize_key in _translations:
|
||||
return _translations[localize_key]
|
||||
return None
|
||||
|
||||
|
||||
async def translated_notification(
|
||||
|
|
@ -101,7 +102,7 @@ def anonymize(data):
|
|||
|
||||
anonym = {}
|
||||
for k in data:
|
||||
if k not in ("ID", "PASSWORD", "wsid", "wspw"):
|
||||
if k not in {"ID", "PASSWORD", "wsid", "wspw"}:
|
||||
anonym[k] = data[k]
|
||||
|
||||
return anonym
|
||||
|
|
@ -131,9 +132,7 @@ def loaded_sensors(config_entry: ConfigEntry) -> list | None:
|
|||
"""Get loaded sensors."""
|
||||
|
||||
return (
|
||||
config_entry.options.get(SENSORS_TO_LOAD)
|
||||
if config_entry.options.get(SENSORS_TO_LOAD)
|
||||
else []
|
||||
config_entry.options.get(SENSORS_TO_LOAD) or []
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
Loading…
Reference in New Issue