From 2a96d4c39ed89b4c9547330c009c8d76a365615b Mon Sep 17 00:00:00 2001 From: Seth <48533968+WillCodeForCats@users.noreply.github.com> Date: Fri, 30 Oct 2026 01:14:13 -0700 Subject: [PATCH] Close shared modbus connections when HA stops or restarts (#189514) Co-authored-by: Paulus Schoutsen --- homeassistant/components/modbus/connection.py | 30 +++++++++- tests/components/modbus/test_connection.py | 58 +++++++++++++++++++ 2 files changed, 86 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/modbus/connection.py b/homeassistant/components/modbus/connection.py index 64bff8799236..3ea64d031497 100644 --- a/homeassistant/components/modbus/connection.py +++ b/homeassistant/components/modbus/connection.py @@ -1,8 +1,10 @@ """Hand out Modbus units over connections shared between integrations.""" +import asyncio from collections.abc import AsyncIterator, Callable, Coroutine from contextlib import asynccontextmanager from dataclasses import dataclass, field +from functools import partial import logging from typing import Any @@ -16,7 +18,8 @@ from modbus_connection import ( from modbus_connection.tmodbus import ModbusConnection from homeassistant.config_entries import ConfigEntry -from homeassistant.core import HomeAssistant, callback +from homeassistant.const import EVENT_HOMEASSISTANT_STOP +from homeassistant.core import Event, HomeAssistant, callback from homeassistant.exceptions import HomeAssistantError from homeassistant.util.hass_dict import HassKey @@ -82,6 +85,25 @@ class ModbusConnectionInfo: """The unit ids each config entry holds, keyed by entry id.""" +async def _async_close_all(hass: HomeAssistant, event: Event) -> None: + """Close every shared connection when Home Assistant stops.""" + connections = hass.data.get(DATA_MODBUS_CONNECTIONS, {}) + shared_connections = list(connections.values()) + # Drop them first, so a hold released later does not close one twice. + connections.clear() + results = await asyncio.gather( + *(shared.connection.close() for shared in shared_connections), + return_exceptions=True, + ) + for shared, result in zip(shared_connections, results, strict=True): + if isinstance(result, Exception): + _LOGGER.error( + "Error closing the Modbus connection to %s", + shared.params.endpoint, + exc_info=result, + ) + + @callback def _async_acquire( hass: HomeAssistant, @@ -100,7 +122,11 @@ def _async_acquire( """ params = _canonical(params) endpoint = params.endpoint - connections = hass.data.setdefault(DATA_MODBUS_CONNECTIONS, {}) + if (connections := hass.data.get(DATA_MODBUS_CONNECTIONS)) is None: + connections = hass.data[DATA_MODBUS_CONNECTIONS] = {} + hass.bus.async_listen_once( + EVENT_HOMEASSISTANT_STOP, partial(_async_close_all, hass) + ) if (shared := connections.get(endpoint)) is None: shared = connections[endpoint] = _SharedConnection( params, ModbusConnection(params) diff --git a/tests/components/modbus/test_connection.py b/tests/components/modbus/test_connection.py index 95e64f0a34f2..d6a9cefe6fc1 100644 --- a/tests/components/modbus/test_connection.py +++ b/tests/components/modbus/test_connection.py @@ -20,6 +20,7 @@ from homeassistant.components.modbus.connection import ( async_get_unit, ) from homeassistant.config_entries import ConfigFlow +from homeassistant.const import EVENT_HOMEASSISTANT_STOP from homeassistant.core import HomeAssistant from homeassistant.exceptions import HomeAssistantError @@ -203,6 +204,63 @@ async def test_the_last_consumer_closes_the_connection( assert not hass.data[DATA_MODBUS_CONNECTIONS] +async def test_stopping_home_assistant_closes_every_connection( + hass: HomeAssistant, consumer: ConsumerFactory +) -> None: + """Entries are not unloaded on shutdown, so stopping closes the connections.""" + one = consumer() + await hass.config_entries.async_setup(one.entry_id) + two = consumer() + await hass.config_entries.async_setup(two.entry_id) + + async_get_unit(hass, one, ModbusTcpParams(host="1.2.3.4", port=502), 1) + async_get_unit(hass, two, ModbusTcpParams(host="5.6.7.8", port=502), 1) + first, second = (s.connection for s in hass.data[DATA_MODBUS_CONNECTIONS].values()) + + with ( + patch.object(first, "close") as first_close, + patch.object(second, "close") as second_close, + ): + hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) + await hass.async_block_till_done() + + first_close.assert_called_once() + second_close.assert_called_once() + assert not hass.data[DATA_MODBUS_CONNECTIONS] + + # A release after the stop must not close a connection a second time. + await hass.config_entries.async_unload(one.entry_id) + await hass.async_block_till_done() + + first_close.assert_called_once() + + +async def test_a_connection_failing_to_close_on_stop_does_not_block_the_rest( + hass: HomeAssistant, + consumer: ConsumerFactory, + caplog: pytest.LogCaptureFixture, +) -> None: + """One connection raising while closing is logged and the others still close.""" + one = consumer() + await hass.config_entries.async_setup(one.entry_id) + two = consumer() + await hass.config_entries.async_setup(two.entry_id) + + async_get_unit(hass, one, ModbusTcpParams(host="1.2.3.4", port=502), 1) + async_get_unit(hass, two, ModbusTcpParams(host="5.6.7.8", port=502), 1) + first, second = (s.connection for s in hass.data[DATA_MODBUS_CONNECTIONS].values()) + + with ( + patch.object(first, "close", side_effect=OSError("boom")), + patch.object(second, "close") as second_close, + ): + hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP) + await hass.async_block_till_done() + + second_close.assert_called_once() + assert "Error closing the Modbus connection to" in caplog.text + + async def test_one_entry_holding_twice_releases_twice( hass: HomeAssistant, consumer: ConsumerFactory ) -> None: