diff --git a/homeassistant/components/modbus/modbus.py b/homeassistant/components/modbus/modbus.py index fb30d245850..627950fe003 100644 --- a/homeassistant/components/modbus/modbus.py +++ b/homeassistant/components/modbus/modbus.py @@ -310,6 +310,13 @@ class ModbusHub: _LOGGER.error(log_text) self._in_error = error_state + async def async_pymodbus_connect(self) -> None: + """Connect to device, async.""" + async with self._lock: + if not await self.hass.async_add_executor_job(self._pymodbus_connect): + err = f"{self.name} connect failed, retry in pymodbus" + self._log_error(err, error_state=False) + async def async_setup(self) -> bool: """Set up pymodbus client.""" try: @@ -322,11 +329,9 @@ class ModbusHub: func = getattr(self._client, entry.func_name) self._pb_call[entry.call_type] = RunEntry(entry.attr, func) - async with self._lock: - if not await self.hass.async_add_executor_job(self._pymodbus_connect): - err = f"{self.name} connect failed, retry in pymodbus" - self._log_error(err, error_state=False) - return False + self.hass.async_create_background_task( + self.async_pymodbus_connect(), "modbus-connect" + ) # Start counting down to allow modbus requests. if self._config_delay: diff --git a/tests/components/modbus/test_init.py b/tests/components/modbus/test_init.py index d9d2e0055fe..75f2f9d3e63 100644 --- a/tests/components/modbus/test_init.py +++ b/tests/components/modbus/test_init.py @@ -704,7 +704,7 @@ async def test_pymodbus_connect_fail( caplog.set_level(logging.WARNING) ExceptionMessage = "test connect exception" mock_pymodbus.connect.side_effect = ModbusException(ExceptionMessage) - assert await async_setup_component(hass, DOMAIN, config) is False + assert await async_setup_component(hass, DOMAIN, config) is True assert ExceptionMessage in caplog.text