Huawei LTE cleanups (#48959)

This commit is contained in:
Ville Skyttä 2021-04-10 03:08:13 +03:00 committed by GitHub
parent 441c304f11
commit 4149cc9662
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 22 additions and 69 deletions

View File

@ -48,11 +48,7 @@ from homeassistant.helpers import (
device_registry as dr, device_registry as dr,
discovery, discovery,
) )
from homeassistant.helpers.dispatcher import ( from homeassistant.helpers.dispatcher import async_dispatcher_connect, dispatcher_send
async_dispatcher_connect,
async_dispatcher_send,
dispatcher_send,
)
from homeassistant.helpers.entity import Entity from homeassistant.helpers.entity import Entity
from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.event import async_track_time_interval
from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.helpers.typing import ConfigType, HomeAssistantType
@ -82,7 +78,6 @@ from .const import (
SERVICE_REBOOT, SERVICE_REBOOT,
SERVICE_RESUME_INTEGRATION, SERVICE_RESUME_INTEGRATION,
SERVICE_SUSPEND_INTEGRATION, SERVICE_SUSPEND_INTEGRATION,
UPDATE_OPTIONS_SIGNAL,
UPDATE_SIGNAL, UPDATE_SIGNAL,
) )
@ -436,11 +431,6 @@ async def async_setup_entry(hass: HomeAssistantType, config_entry: ConfigEntry)
hass.data[DOMAIN].hass_config, hass.data[DOMAIN].hass_config,
) )
# Add config entry options update listener
router.unload_handlers.append(
config_entry.add_update_listener(async_signal_options_update)
)
def _update_router(*_: Any) -> None: def _update_router(*_: Any) -> None:
""" """
Update router data. Update router data.
@ -492,9 +482,8 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
def service_handler(service: ServiceCall) -> None: def service_handler(service: ServiceCall) -> None:
"""Apply a service.""" """Apply a service."""
url = service.data.get(CONF_URL)
routers = hass.data[DOMAIN].routers routers = hass.data[DOMAIN].routers
if url: if url := service.data.get(CONF_URL):
router = routers.get(url) router = routers.get(url)
elif not routers: elif not routers:
_LOGGER.error("%s: no routers configured", service.service) _LOGGER.error("%s: no routers configured", service.service)
@ -559,13 +548,6 @@ async def async_setup(hass: HomeAssistantType, config: ConfigType) -> bool:
return True return True
async def async_signal_options_update(
hass: HomeAssistantType, config_entry: ConfigEntry
) -> None:
"""Handle config entry options update."""
async_dispatcher_send(hass, UPDATE_OPTIONS_SIGNAL, config_entry)
async def async_migrate_entry( async def async_migrate_entry(
hass: HomeAssistantType, config_entry: ConfigEntry hass: HomeAssistantType, config_entry: ConfigEntry
) -> bool: ) -> bool:
@ -631,30 +613,17 @@ class HuaweiLteBaseEntity(Entity):
"""Update state.""" """Update state."""
raise NotImplementedError raise NotImplementedError
async def async_update_options(self, config_entry: ConfigEntry) -> None:
"""Update config entry options."""
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Connect to update signals.""" """Connect to update signals."""
self._unsub_handlers.append( self._unsub_handlers.append(
async_dispatcher_connect(self.hass, UPDATE_SIGNAL, self._async_maybe_update) async_dispatcher_connect(self.hass, UPDATE_SIGNAL, self._async_maybe_update)
) )
self._unsub_handlers.append(
async_dispatcher_connect(
self.hass, UPDATE_OPTIONS_SIGNAL, self._async_maybe_update_options
)
)
async def _async_maybe_update(self, url: str) -> None: async def _async_maybe_update(self, url: str) -> None:
"""Update state if the update signal comes from our router.""" """Update state if the update signal comes from our router."""
if url == self.router.url: if url == self.router.url:
self.async_schedule_update_ha_state(True) self.async_schedule_update_ha_state(True)
async def _async_maybe_update_options(self, config_entry: ConfigEntry) -> None:
"""Update options if the update signal comes from our router."""
if config_entry.data[CONF_URL] == self.router.url:
await self.async_update_options(config_entry)
async def async_will_remove_from_hass(self) -> None: async def async_will_remove_from_hass(self) -> None:
"""Invoke unsubscription handlers.""" """Invoke unsubscription handlers."""
for unsub in self._unsub_handlers: for unsub in self._unsub_handlers:

View File

@ -1,7 +1,6 @@
"""Config flow for the Huawei LTE platform.""" """Config flow for the Huawei LTE platform."""
from __future__ import annotations from __future__ import annotations
from collections import OrderedDict
import logging import logging
from typing import Any from typing import Any
from urllib.parse import urlparse from urllib.parse import urlparse
@ -65,32 +64,21 @@ class ConfigFlowHandler(config_entries.ConfigFlow, domain=DOMAIN):
return self.async_show_form( return self.async_show_form(
step_id="user", step_id="user",
data_schema=vol.Schema( data_schema=vol.Schema(
OrderedDict( {
(
(
vol.Required( vol.Required(
CONF_URL, CONF_URL,
default=user_input.get( default=user_input.get(
CONF_URL, CONF_URL,
self.context.get(CONF_URL, ""), self.context.get(CONF_URL, ""),
), ),
), ): str,
str,
),
(
vol.Optional( vol.Optional(
CONF_USERNAME, default=user_input.get(CONF_USERNAME, "") CONF_USERNAME, default=user_input.get(CONF_USERNAME, "")
), ): str,
str,
),
(
vol.Optional( vol.Optional(
CONF_PASSWORD, default=user_input.get(CONF_PASSWORD, "") CONF_PASSWORD, default=user_input.get(CONF_PASSWORD, "")
), ): str,
str, }
),
)
)
), ),
errors=errors or {}, errors=errors or {},
) )

View File

@ -6,7 +6,6 @@ DEFAULT_DEVICE_NAME = "LTE"
DEFAULT_NOTIFY_SERVICE_NAME = DOMAIN DEFAULT_NOTIFY_SERVICE_NAME = DOMAIN
UPDATE_SIGNAL = f"{DOMAIN}_update" UPDATE_SIGNAL = f"{DOMAIN}_update"
UPDATE_OPTIONS_SIGNAL = f"{DOMAIN}_options_update"
CONNECTION_TIMEOUT = 10 CONNECTION_TIMEOUT = 10
NOTIFY_SUPPRESS_TIMEOUT = 30 NOTIFY_SUPPRESS_TIMEOUT = 30

View File

@ -105,6 +105,7 @@ def async_add_new_entities(
def _better_snakecase(text: str) -> str: def _better_snakecase(text: str) -> str:
# Awaiting https://github.com/okunishinishi/python-stringcase/pull/18
if text == text.upper(): if text == text.upper():
# All uppercase to all lowercase to get http for HTTP, not h_t_t_p # All uppercase to all lowercase to get http for HTTP, not h_t_t_p
text = text.lower() text = text.lower()

View File

@ -337,11 +337,9 @@ async def async_setup_entry(
router = hass.data[DOMAIN].routers[config_entry.data[CONF_URL]] router = hass.data[DOMAIN].routers[config_entry.data[CONF_URL]]
sensors: list[Entity] = [] sensors: list[Entity] = []
for key in SENSOR_KEYS: for key in SENSOR_KEYS:
items = router.data.get(key) if not (items := router.data.get(key)):
if not items:
continue continue
key_meta = SENSOR_META.get(key) if key_meta := SENSOR_META.get(key):
if key_meta:
if key_meta.include: if key_meta.include:
items = filter(key_meta.include.search, items) items = filter(key_meta.include.search, items)
if key_meta.exclude: if key_meta.exclude:
@ -361,10 +359,9 @@ def format_default(value: StateType) -> tuple[StateType, str | None]:
unit = None unit = None
if value is not None: if value is not None:
# Clean up value and infer unit, e.g. -71dBm, 15 dB # Clean up value and infer unit, e.g. -71dBm, 15 dB
match = re.match( if match := re.match(
r"([>=<]*)(?P<value>.+?)\s*(?P<unit>[a-zA-Z]+)\s*$", str(value) r"([>=<]*)(?P<value>.+?)\s*(?P<unit>[a-zA-Z]+)\s*$", str(value)
) ):
if match:
try: try:
value = float(match.group("value")) value = float(match.group("value"))
unit = match.group("unit") unit = match.group("unit")

View File

@ -33,8 +33,7 @@
"init": { "init": {
"data": { "data": {
"name": "Notification service name (change requires restart)", "name": "Notification service name (change requires restart)",
"recipient": "SMS notification recipients", "recipient": "SMS notification recipients"
"track_new_devices": "Track new devices"
} }
} }
} }