Close shared modbus connections when HA stops or restarts (#189514)

Co-authored-by: Paulus Schoutsen <balloob@gmail.com>
This commit is contained in:
Seth
2026-10-30 04:14:13 -04:00
committed by GitHub
co-authored by Paulus Schoutsen
parent 03383090d7
commit 2a96d4c39e
2 changed files with 86 additions and 2 deletions
+28 -2
View File
@@ -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)
@@ -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: