Centralize wemo exception handling (#46705)
This commit is contained in:
parent
b2df9aaaf1
commit
8bee3cda37
5 changed files with 48 additions and 92 deletions
|
@ -1,10 +1,12 @@
|
|||
"""Classes shared among Wemo entities."""
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, Generator, Optional
|
||||
|
||||
import async_timeout
|
||||
from pywemo import WeMoDevice
|
||||
from pywemo.ouimeaux_device.api.service import ActionException
|
||||
|
||||
from homeassistant.helpers.entity import Entity
|
||||
|
||||
|
@ -13,6 +15,18 @@ from .const import DOMAIN as WEMO_DOMAIN
|
|||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ExceptionHandlerStatus:
|
||||
"""Exit status from the _wemo_exception_handler context manager."""
|
||||
|
||||
# An exception if one was raised in the _wemo_exception_handler.
|
||||
exception: Optional[Exception] = None
|
||||
|
||||
@property
|
||||
def success(self) -> bool:
|
||||
"""Return True if the handler completed with no exception."""
|
||||
return self.exception is None
|
||||
|
||||
|
||||
class WemoEntity(Entity):
|
||||
"""Common methods for Wemo entities.
|
||||
|
||||
|
@ -36,6 +50,23 @@ class WemoEntity(Entity):
|
|||
"""Return true if switch is available."""
|
||||
return self._available
|
||||
|
||||
@contextlib.contextmanager
|
||||
def _wemo_exception_handler(
|
||||
self, message: str
|
||||
) -> Generator[ExceptionHandlerStatus, None, None]:
|
||||
"""Wrap device calls to set `_available` when wemo exceptions happen."""
|
||||
status = ExceptionHandlerStatus()
|
||||
try:
|
||||
yield status
|
||||
except ActionException as err:
|
||||
status.exception = err
|
||||
_LOGGER.warning("Could not %s for %s (%s)", message, self.name, err)
|
||||
self._available = False
|
||||
else:
|
||||
if not self._available:
|
||||
_LOGGER.info("Reconnected to %s", self.name)
|
||||
self._available = True
|
||||
|
||||
def _update(self, force_update: Optional[bool] = True):
|
||||
"""Update the device state."""
|
||||
raise NotImplementedError()
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue