From ea946c90b3d969ceb41d4edebded95c23b9be55d Mon Sep 17 00:00:00 2001 From: jan iversen Date: Tue, 12 Aug 2025 19:38:17 +0200 Subject: [PATCH] Modbus: Cancel connect background task if stopping/restarting. (#150507) --- homeassistant/components/modbus/modbus.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/modbus/modbus.py b/homeassistant/components/modbus/modbus.py index 5ddde2973ee..9e0ba63b4a0 100644 --- a/homeassistant/components/modbus/modbus.py +++ b/homeassistant/components/modbus/modbus.py @@ -262,6 +262,7 @@ class ModbusHub: self._config_type = client_config[CONF_TYPE] self._config_delay = client_config[CONF_DELAY] self._pb_request: dict[str, RunEntry] = {} + self._connect_task: asyncio.Task self._pb_class = { SERIAL: AsyncModbusSerialClient, TCP: AsyncModbusTcpClient, @@ -336,7 +337,7 @@ class ModbusHub: entry.attr, func, entry.value_attr_name ) - self.hass.async_create_background_task( + self._connect_task = self.hass.async_create_background_task( self.async_pb_connect(), "modbus-connect" ) @@ -365,6 +366,9 @@ class ModbusHub: if self._async_cancel_listener: self._async_cancel_listener() self._async_cancel_listener = None + if not self._connect_task.done(): + self._connect_task.cancel() + async with self._lock: if self._client: try: