Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 17 additions & 13 deletions homeassistant/components/huawei_lte/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
ResponseErrorNotSupportedException,
)
from requests.exceptions import Timeout
from url_normalize import url_normalize
import voluptuous as vol

from homeassistant.config_entries import ConfigEntry
Expand All @@ -39,7 +40,11 @@
Platform,
)
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.exceptions import ConfigEntryAuthFailed, ConfigEntryNotReady
from homeassistant.exceptions import (
ConfigEntryAuthFailed,
ConfigEntryNotReady,
ServiceValidationError,
)
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
Expand Down Expand Up @@ -90,7 +95,7 @@

CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)

SERVICE_SCHEMA = vol.Schema({vol.Optional(CONF_URL): cv.url})
SERVICE_SCHEMA = vol.Schema({vol.Optional(CONF_URL): cv.string})

PLATFORMS = [
Platform.BINARY_SENSOR,
Expand Down Expand Up @@ -465,26 +470,22 @@ def service_handler(service: ServiceCall) -> None:
because the latter is not available anywhere in the UI.
"""
routers = hass.data[DOMAIN].routers
if url := service.data.get(CONF_URL):
if url := url_normalize(service.data.get(CONF_URL), default_scheme="http"):
router = next(
(router for router in routers.values() if router.url == url), None
)
elif not routers:
_LOGGER.error("%s: no routers configured", service.service)
return
raise ServiceValidationError("No routers configured")
elif len(routers) == 1:
router = next(iter(routers.values()))
else:
_LOGGER.error(
"%s: more than one router configured, must specify one of URLs %s",
service.service,
sorted(router.url for router in routers.values()),
raise ServiceValidationError(
f"More than one router configured, must specify one of URLs {sorted(router.url for router in routers.values())}"
)
return
if not router:
_LOGGER.error("%s: router %s unavailable", service.service, url)
return
raise ServiceValidationError(f"Router {url} not available")

was_suspended = router.suspended
if service.service == SERVICE_RESUME_INTEGRATION:
# Login will be handled automatically on demand
router.suspended = False
Expand All @@ -494,7 +495,10 @@ def service_handler(service: ServiceCall) -> None:
router.suspended = True
_LOGGER.debug("%s: %s", service.service, "done")
else:
_LOGGER.error("%s: unsupported service", service.service)
raise ServiceValidationError(f"Unsupported service {service.service}")
if was_suspended != router.suspended:
# Make interactive entities' availability update
dispatcher_send(hass, UPDATE_SIGNAL, router.config_entry.unique_id)

for service in ADMIN_SERVICES:
async_register_admin_service(
Expand Down
10 changes: 4 additions & 6 deletions homeassistant/components/huawei_lte/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,11 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers import entity_platform

from .const import DOMAIN
from .entity import HuaweiLteBaseEntityWithDevice
from .entity import HuaweiLteBaseInteractiveEntity

_LOGGER = logging.getLogger(__name__)

Expand All @@ -36,7 +37,7 @@ async def async_setup_entry(
async_add_entities(buttons)


class BaseButton(HuaweiLteBaseEntityWithDevice, ButtonEntity):
class BaseButton(HuaweiLteBaseInteractiveEntity, ButtonEntity):
"""Huawei LTE button base class."""

@property
Expand All @@ -50,10 +51,7 @@ async def async_update(self) -> None:
def press(self) -> None:
"""Press button."""
if self.router.suspended:
_LOGGER.debug(
"%s: ignored, integration suspended", self.entity_description.key
)
return
raise ServiceValidationError("Integration is suspended")
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TBH I'm not sure if this (ditto in select and switch) is required/that useful now that the interactive entities' availability is updated based on if the parent router is suspended, but I guess it doesn't hurt.

result = self._press()
_LOGGER.debug("%s: %s", self.entity_description.key, result)

Expand Down
9 changes: 9 additions & 0 deletions homeassistant/components/huawei_lte/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,3 +66,12 @@ def device_info(self) -> DeviceInfo:
connections=self.router.device_connections,
identifiers=self.router.device_identifiers,
)


class HuaweiLteBaseInteractiveEntity(HuaweiLteBaseEntityWithDevice):
"""Base interactive entity."""

@property
def available(self) -> bool:
"""Return if entity is available."""
return super().available and not self.router.suspended
7 changes: 5 additions & 2 deletions homeassistant/components/huawei_lte/select.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback

from . import Router
from .const import DOMAIN, KEY_NET_NET_MODE
from .entity import HuaweiLteBaseEntityWithDevice
from .entity import HuaweiLteBaseInteractiveEntity

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -74,7 +75,7 @@ async def async_setup_entry(
async_add_entities(selects, True)


class HuaweiLteSelectEntity(HuaweiLteBaseEntityWithDevice, SelectEntity):
class HuaweiLteSelectEntity(HuaweiLteBaseInteractiveEntity, SelectEntity):
"""Huawei LTE select entity."""

entity_description: HuaweiSelectEntityDescription
Expand All @@ -95,6 +96,8 @@ def __init__(

def select_option(self, option: str) -> None:
"""Change the selected option."""
if self.router.suspended:
raise ServiceValidationError("Integration is suspended")
self.entity_description.setter_fn(option)

@property
Expand Down
9 changes: 7 additions & 2 deletions homeassistant/components/huawei_lte/switch.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ServiceValidationError
from homeassistant.helpers.entity import Entity
from homeassistant.helpers.entity_platform import AddConfigEntryEntitiesCallback

Expand All @@ -20,7 +21,7 @@
KEY_DIALUP_MOBILE_DATASWITCH,
KEY_WLAN_WIFI_GUEST_NETWORK_SWITCH,
)
from .entity import HuaweiLteBaseEntityWithDevice
from .entity import HuaweiLteBaseInteractiveEntity

_LOGGER = logging.getLogger(__name__)

Expand All @@ -43,7 +44,7 @@ async def async_setup_entry(
async_add_entities(switches, True)


class HuaweiLteBaseSwitch(HuaweiLteBaseEntityWithDevice, SwitchEntity):
class HuaweiLteBaseSwitch(HuaweiLteBaseInteractiveEntity, SwitchEntity):
"""Huawei LTE switch device base class."""

key: str
Expand All @@ -57,10 +58,14 @@ def _turn(self, state: bool) -> None:

def turn_on(self, **kwargs: Any) -> None:
"""Turn switch on."""
if self.router.suspended:
raise ServiceValidationError("Integration is suspended")
self._turn(state=True)

def turn_off(self, **kwargs: Any) -> None:
"""Turn switch off."""
if self.router.suspended:
raise ServiceValidationError("Integration is suspended")
self._turn(state=False)

async def async_added_to_hass(self) -> None:
Expand Down
2 changes: 1 addition & 1 deletion tests/components/huawei_lte/test_button.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from tests.common import MockConfigEntry

MOCK_CONF_URL = "http://huawei-lte.example.com"
MOCK_CONF_URL = "http://192.168.1.1/"


@patch("homeassistant.components.huawei_lte.Connection", MagicMock())
Expand Down
Loading