mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Don't hang AlarmDecoder setup or leave connections behind (#190499)
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
"""Support for AlarmDecoder devices."""
|
||||
|
||||
from collections.abc import Callable
|
||||
from dataclasses import dataclass
|
||||
from datetime import timedelta
|
||||
import asyncio
|
||||
from dataclasses import dataclass, field
|
||||
import logging
|
||||
import threading
|
||||
|
||||
from adext import AdExt
|
||||
from alarmdecoder.devices import SerialDevice, SocketDevice
|
||||
@@ -17,10 +17,10 @@ from homeassistant.const import (
|
||||
EVENT_HOMEASSISTANT_STOP,
|
||||
Platform,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.core import HomeAssistant, callback
|
||||
from homeassistant.exceptions import ConfigEntryNotReady
|
||||
from homeassistant.helpers import config_validation as cv
|
||||
from homeassistant.helpers.dispatcher import dispatcher_send
|
||||
from homeassistant.helpers.event import async_call_later
|
||||
from homeassistant.helpers.typing import ConfigType
|
||||
|
||||
from .const import (
|
||||
@@ -40,6 +40,8 @@ from .services import async_setup_services
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONFIG_SCHEMA = cv.config_entry_only_config_schema(DOMAIN)
|
||||
INIT_TIMEOUT = 30
|
||||
RECONNECT_DELAY = 5
|
||||
PLATFORMS = [
|
||||
Platform.ALARM_CONTROL_PANEL,
|
||||
Platform.BINARY_SENSOR,
|
||||
@@ -54,9 +56,10 @@ class AlarmDecoderData:
|
||||
"""Runtime data for the AlarmDecoder class."""
|
||||
|
||||
client: AdExt
|
||||
remove_update_listener: Callable[[], None]
|
||||
remove_stop_listener: Callable[[], None]
|
||||
restart: bool
|
||||
restart: bool = False
|
||||
closed: bool = False
|
||||
connecting: bool = False
|
||||
lock: threading.Lock = field(default_factory=threading.Lock)
|
||||
|
||||
|
||||
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
||||
@@ -69,37 +72,76 @@ async def async_setup_entry(
|
||||
hass: HomeAssistant, entry: AlarmDecoderConfigEntry
|
||||
) -> None:
|
||||
"""Set up AlarmDecoder config flow."""
|
||||
undo_listener = entry.add_update_listener(_update_listener)
|
||||
entry.async_on_unload(entry.add_update_listener(_update_listener))
|
||||
|
||||
ad_connection = entry.data
|
||||
protocol = ad_connection[CONF_PROTOCOL]
|
||||
|
||||
def stop_alarmdecoder(event):
|
||||
"""Handle the shutdown of AlarmDecoder."""
|
||||
if not entry.runtime_data:
|
||||
return
|
||||
_LOGGER.debug("Shutting down alarmdecoder")
|
||||
entry.runtime_data.restart = False
|
||||
close_controller()
|
||||
|
||||
def open_controller() -> None:
|
||||
"""Connect, unless already closed, and honor a close that came meanwhile."""
|
||||
with data.lock:
|
||||
if data.closed:
|
||||
return
|
||||
data.connecting = True
|
||||
try:
|
||||
controller.open(baud)
|
||||
finally:
|
||||
with data.lock:
|
||||
data.connecting = False
|
||||
closed = data.closed
|
||||
if closed:
|
||||
controller.close()
|
||||
data.restart = True
|
||||
|
||||
def close_controller() -> None:
|
||||
"""Close the connection once, or leave that to a connect in progress."""
|
||||
with data.lock:
|
||||
if data.closed:
|
||||
return
|
||||
data.closed = True
|
||||
# close() can't interrupt connect(), which would then leave the
|
||||
# connection open, so open_controller() closes when it finishes.
|
||||
if data.connecting:
|
||||
return
|
||||
controller.close()
|
||||
|
||||
async def open_connection(now=None):
|
||||
"""Open a connection to AlarmDecoder."""
|
||||
try:
|
||||
await hass.async_add_executor_job(controller.open, baud)
|
||||
except NoDeviceError:
|
||||
_LOGGER.debug("Failed to connect. Retrying in 5 seconds")
|
||||
async_call_later(hass, timedelta(seconds=5), open_connection)
|
||||
return
|
||||
_LOGGER.debug("Established a connection with the alarmdecoder")
|
||||
entry.runtime_data.restart = True
|
||||
async def async_close_controller() -> None:
|
||||
"""Close the connection without blocking the event loop."""
|
||||
await hass.async_add_executor_job(close_controller)
|
||||
|
||||
async def async_reconnect() -> None:
|
||||
"""Try to reconnect until it works; unloading the entry cancels this."""
|
||||
while True:
|
||||
try:
|
||||
await hass.async_add_executor_job(open_controller)
|
||||
except NoDeviceError:
|
||||
_LOGGER.debug(
|
||||
"Failed to connect. Retrying in %s seconds", RECONNECT_DELAY
|
||||
)
|
||||
await asyncio.sleep(RECONNECT_DELAY)
|
||||
else:
|
||||
_LOGGER.debug("Established a connection with the alarmdecoder")
|
||||
return
|
||||
|
||||
@callback
|
||||
def start_reconnect() -> None:
|
||||
"""Reconnect in the background, so that it can't hold up startup."""
|
||||
entry.async_create_background_task(
|
||||
hass, async_reconnect(), "alarmdecoder reconnect"
|
||||
)
|
||||
|
||||
def handle_closed_connection(event):
|
||||
"""Restart after unexpected loss of connection."""
|
||||
if not entry.runtime_data.restart:
|
||||
if data.closed or not data.restart:
|
||||
return
|
||||
entry.runtime_data.restart = False
|
||||
data.restart = False
|
||||
_LOGGER.warning("AlarmDecoder unexpectedly lost connection")
|
||||
hass.add_job(open_connection)
|
||||
hass.add_job(start_reconnect)
|
||||
|
||||
def handle_message(sender, message):
|
||||
"""Handle message from AlarmDecoder."""
|
||||
@@ -137,17 +179,23 @@ async def async_setup_entry(
|
||||
controller.on_close += handle_closed_connection
|
||||
controller.on_expander_message += handle_rel_message
|
||||
|
||||
remove_stop_listener = hass.bus.async_listen_once(
|
||||
EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder
|
||||
data = entry.runtime_data = AlarmDecoderData(controller)
|
||||
|
||||
entry.async_on_unload(
|
||||
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_STOP, stop_alarmdecoder)
|
||||
)
|
||||
entry.async_on_unload(async_close_controller)
|
||||
|
||||
entry.runtime_data = AlarmDecoderData(
|
||||
controller, undo_listener, remove_stop_listener, False
|
||||
)
|
||||
|
||||
await open_connection()
|
||||
|
||||
await controller.is_init()
|
||||
try:
|
||||
async with asyncio.timeout(INIT_TIMEOUT):
|
||||
await hass.async_add_executor_job(open_controller)
|
||||
await controller.is_init()
|
||||
except NoDeviceError as err:
|
||||
raise ConfigEntryNotReady(f"Can't connect to the AlarmDecoder: {err}") from err
|
||||
except TimeoutError as err:
|
||||
raise ConfigEntryNotReady(
|
||||
f"No response from the AlarmDecoder within {INIT_TIMEOUT} seconds"
|
||||
) from err
|
||||
|
||||
await hass.config_entries.async_forward_entry_setups(entry, PLATFORMS)
|
||||
|
||||
@@ -156,15 +204,8 @@ async def async_unload_entry(
|
||||
hass: HomeAssistant, entry: AlarmDecoderConfigEntry
|
||||
) -> None:
|
||||
"""Unload a AlarmDecoder entry."""
|
||||
data = entry.runtime_data
|
||||
data.restart = False
|
||||
|
||||
await hass.config_entries.async_unload_platforms_or_raise(entry, PLATFORMS)
|
||||
|
||||
data.remove_update_listener()
|
||||
data.remove_stop_listener()
|
||||
await hass.async_add_executor_job(data.client.close)
|
||||
|
||||
|
||||
async def _update_listener(hass: HomeAssistant, entry: AlarmDecoderConfigEntry) -> None:
|
||||
"""Handle options update."""
|
||||
|
||||
@@ -0,0 +1,308 @@
|
||||
"""Test the AlarmDecoder integration setup."""
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable, Generator
|
||||
import threading
|
||||
from typing import Self
|
||||
from unittest.mock import AsyncMock, MagicMock, patch
|
||||
|
||||
from alarmdecoder.util import NoDeviceError
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
|
||||
from homeassistant.components.alarmdecoder.const import DOMAIN, PROTOCOL_SOCKET
|
||||
from homeassistant.config_entries import ConfigEntryState
|
||||
from homeassistant.const import (
|
||||
CONF_HOST,
|
||||
CONF_PORT,
|
||||
CONF_PROTOCOL,
|
||||
EVENT_HOMEASSISTANT_STOP,
|
||||
)
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_config_entry(hass: HomeAssistant) -> MockConfigEntry:
|
||||
"""Return a socket AlarmDecoder config entry added to hass."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={
|
||||
CONF_PROTOCOL: PROTOCOL_SOCKET,
|
||||
CONF_HOST: "alarmdecoder123",
|
||||
CONF_PORT: 10001,
|
||||
},
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
return entry
|
||||
|
||||
|
||||
class Handlers(list):
|
||||
"""Stand-in for an alarmdecoder event: `+=` adds a handler."""
|
||||
|
||||
def __iadd__(self, handler: Callable[..., None]) -> Self:
|
||||
"""Add a handler."""
|
||||
self.append(handler)
|
||||
return self
|
||||
|
||||
|
||||
def _make_controller() -> MagicMock:
|
||||
"""Return a controller mock that never answers the version request."""
|
||||
controller = MagicMock()
|
||||
controller.is_init = AsyncMock(side_effect=asyncio.Event().wait)
|
||||
for event in (
|
||||
"on_message",
|
||||
"on_rfx_message",
|
||||
"on_zone_fault",
|
||||
"on_zone_restore",
|
||||
"on_close",
|
||||
"on_expander_message",
|
||||
):
|
||||
setattr(controller, event, Handlers())
|
||||
return controller
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def mock_controller() -> Generator[MagicMock]:
|
||||
"""Patch AdExt; return the controller of the first setup attempt.
|
||||
|
||||
Later attempts (Home Assistant's own setup retries) get fresh controllers,
|
||||
so the first one's calls only count what that attempt left behind.
|
||||
"""
|
||||
controllers = [_make_controller() for _ in range(5)]
|
||||
with (
|
||||
patch("homeassistant.components.alarmdecoder.AdExt", side_effect=controllers),
|
||||
patch("homeassistant.components.alarmdecoder.INIT_TIMEOUT", 0.5),
|
||||
patch("homeassistant.components.alarmdecoder.RECONNECT_DELAY", 0.01),
|
||||
patch("homeassistant.components.alarmdecoder.PLATFORMS", []),
|
||||
):
|
||||
yield controllers[0]
|
||||
|
||||
|
||||
class SlowConnect:
|
||||
"""A connect() that hangs until released, in a worker thread like the real one.
|
||||
|
||||
Used as a plain object rather than a mock, which would run on the event loop.
|
||||
"""
|
||||
|
||||
def __init__(self, controller: MagicMock, fails: bool = False) -> None:
|
||||
"""Replace the controller's open and close."""
|
||||
self.started = threading.Event()
|
||||
self.release = threading.Event()
|
||||
self.closed = threading.Event()
|
||||
self.fails = fails
|
||||
self.attempts = 0
|
||||
self.events: list[str] = []
|
||||
controller.open = self.open
|
||||
controller.close.side_effect = self.close
|
||||
|
||||
def open(self, baud: int | None) -> None:
|
||||
"""Hang, then finish."""
|
||||
self.attempts += 1
|
||||
self.started.set()
|
||||
self.release.wait(10)
|
||||
self.events.append("opened")
|
||||
if self.fails:
|
||||
raise NoDeviceError
|
||||
|
||||
def close(self) -> None:
|
||||
"""Record the close."""
|
||||
self.events.append("closed")
|
||||
self.closed.set()
|
||||
|
||||
|
||||
async def _async_setup_connected(
|
||||
hass: HomeAssistant, entry: MockConfigEntry, controller: MagicMock
|
||||
) -> None:
|
||||
"""Set up the entry with a device that answers."""
|
||||
controller.is_init = AsyncMock(return_value=True)
|
||||
await hass.config_entries.async_setup(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert entry.state is ConfigEntryState.LOADED
|
||||
|
||||
|
||||
async def test_setup_retries_without_version_reply(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
) -> None:
|
||||
"""Test setup gives up and retries when the device never answers."""
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
mock_controller.close.assert_called_once()
|
||||
assert not mock_config_entry.update_listeners
|
||||
|
||||
|
||||
async def test_setup_retries_when_unreachable(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
) -> None:
|
||||
"""Test setup gives up right away when the device can't be reached."""
|
||||
mock_controller.open.side_effect = NoDeviceError
|
||||
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
mock_controller.open.assert_called_once()
|
||||
mock_controller.close.assert_called_once()
|
||||
assert not mock_config_entry.update_listeners
|
||||
|
||||
|
||||
async def test_reconnects_after_lost_connection(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
) -> None:
|
||||
"""Test every lost connection is retried until connected again."""
|
||||
await _async_setup_connected(hass, mock_config_entry, mock_controller)
|
||||
mock_controller.open.reset_mock()
|
||||
# The first reconnect attempt fails, the second one connects.
|
||||
mock_controller.open.side_effect = [NoDeviceError, None, None]
|
||||
|
||||
mock_controller.on_close[0](None)
|
||||
await hass.async_block_till_done()
|
||||
await asyncio.sleep(0.05)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert mock_controller.open.call_count == 2
|
||||
|
||||
mock_controller.on_close[0](None)
|
||||
await hass.async_block_till_done(wait_background_tasks=True)
|
||||
assert mock_controller.open.call_count == 3
|
||||
|
||||
|
||||
async def test_unload_stops_reconnecting(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
) -> None:
|
||||
"""Test unloading while reconnecting stops the old controller for good."""
|
||||
await _async_setup_connected(hass, mock_config_entry, mock_controller)
|
||||
mock_controller.open.reset_mock()
|
||||
mock_controller.open.side_effect = NoDeviceError
|
||||
|
||||
mock_controller.on_close[0](None)
|
||||
await hass.async_block_till_done()
|
||||
await asyncio.sleep(0.05)
|
||||
assert mock_controller.open.call_count > 1
|
||||
|
||||
await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
|
||||
attempts = mock_controller.open.call_count
|
||||
|
||||
await asyncio.sleep(0.05)
|
||||
assert mock_controller.open.call_count == attempts
|
||||
mock_controller.close.assert_called_once()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fails", [False, True])
|
||||
async def test_unload_during_reconnect_attempt(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
fails: bool,
|
||||
) -> None:
|
||||
"""Test a reconnect still connecting at unload is closed when it finishes."""
|
||||
await _async_setup_connected(hass, mock_config_entry, mock_controller)
|
||||
connect = SlowConnect(mock_controller, fails)
|
||||
|
||||
mock_controller.on_close[0](None)
|
||||
assert await hass.async_add_executor_job(connect.started.wait, 5)
|
||||
|
||||
await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
assert mock_config_entry.state is ConfigEntryState.NOT_LOADED
|
||||
# Closing now couldn't interrupt the connect.
|
||||
assert connect.events == []
|
||||
|
||||
connect.release.set()
|
||||
assert await hass.async_add_executor_job(connect.closed.wait, 5)
|
||||
await asyncio.sleep(0.05)
|
||||
|
||||
assert connect.attempts == 1
|
||||
assert connect.events == ["opened", "closed"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("fails", [False, True])
|
||||
async def test_setup_timeout_during_connect(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
fails: bool,
|
||||
) -> None:
|
||||
"""Test a connect outlasting the setup timeout is closed when it finishes."""
|
||||
connect = SlowConnect(mock_controller, fails)
|
||||
|
||||
# A tracked task, like bootstrap's setup: this is what startup waits for.
|
||||
hass.async_create_task(hass.config_entries.async_setup(mock_config_entry.entry_id))
|
||||
try:
|
||||
assert await hass.async_add_executor_job(connect.started.wait, 5)
|
||||
async with asyncio.timeout(3):
|
||||
await hass.async_block_till_done()
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
assert connect.events == []
|
||||
finally:
|
||||
connect.release.set()
|
||||
|
||||
assert await hass.async_add_executor_job(connect.closed.wait, 5)
|
||||
await asyncio.sleep(0.05)
|
||||
assert connect.events == ["opened", "closed"]
|
||||
|
||||
|
||||
async def test_reconnect_attempt_does_not_hold_up_startup(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
) -> None:
|
||||
"""Test Home Assistant doesn't wait for a reconnect that is still connecting."""
|
||||
await _async_setup_connected(hass, mock_config_entry, mock_controller)
|
||||
connect = SlowConnect(mock_controller)
|
||||
|
||||
mock_controller.on_close[0](None)
|
||||
try:
|
||||
assert await hass.async_add_executor_job(connect.started.wait, 5)
|
||||
async with asyncio.timeout(3):
|
||||
await hass.async_block_till_done()
|
||||
finally:
|
||||
connect.release.set()
|
||||
|
||||
|
||||
async def test_connect_finishing_after_its_future_was_cancelled(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
) -> None:
|
||||
"""Test the close still waits for connect() if stopping cancels the future."""
|
||||
connect = SlowConnect(mock_controller)
|
||||
|
||||
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
||||
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
|
||||
|
||||
# What hass.async_stop() does to background tasks and executor jobs.
|
||||
for task in list(hass._background_tasks):
|
||||
task.cancel("Home Assistant is stopping")
|
||||
await asyncio.sleep(0.05)
|
||||
assert connect.events == []
|
||||
|
||||
connect.release.set()
|
||||
assert await hass.async_add_executor_job(connect.closed.wait, 5)
|
||||
await asyncio.sleep(0.05)
|
||||
assert connect.events == ["opened", "closed"]
|
||||
|
||||
|
||||
async def test_stop_then_unload_closes_once(
|
||||
hass: HomeAssistant,
|
||||
mock_config_entry: MockConfigEntry,
|
||||
mock_controller: MagicMock,
|
||||
) -> None:
|
||||
"""Test a second close is skipped, as the library raises on one."""
|
||||
await _async_setup_connected(hass, mock_config_entry, mock_controller)
|
||||
|
||||
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
|
||||
await hass.async_block_till_done()
|
||||
await hass.config_entries.async_unload(mock_config_entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
mock_controller.close.assert_called_once()
|
||||
Reference in New Issue
Block a user