Skip to content

Commit

Permalink
Handle WebsocketConnectionError during mqtt auto reconnect
Browse files Browse the repository at this point in the history
followup to #133610 to handle the exception in the auto reconnect
path as well

fixes #132985
  • Loading branch information
bdraco committed Dec 21, 2024
1 parent 861d9b3 commit 42a4607
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 2 deletions.
5 changes: 4 additions & 1 deletion homeassistant/components/mqtt/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -695,12 +695,15 @@ def _async_cancel_reconnect(self) -> None:

async def _reconnect_loop(self) -> None:
"""Reconnect to the MQTT server."""
# pylint: disable-next=import-outside-toplevel
import paho.mqtt.client as mqtt

while True:
if not self.connected:
try:
async with self._connection_lock, self._async_connect_in_executor():
await self.hass.async_add_executor_job(self._mqttc.reconnect)
except OSError as err:
except (OSError, mqtt.WebsocketConnectionError) as err:
_LOGGER.debug(
"Error re-connecting to MQTT server due to exception: %s", err
)
Expand Down
10 changes: 9 additions & 1 deletion tests/components/mqtt/test_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -1888,10 +1888,18 @@ async def test_mqtt_subscribes_and_unsubscribes_in_chunks(
assert len(mqtt_client_mock.unsubscribe.mock_calls[1][1][0]) == 2


@pytest.mark.parametrize(
"exception",
[
OSError,
paho_mqtt.WebsocketConnectionError,
],
)
async def test_auto_reconnect(
hass: HomeAssistant,
setup_with_birth_msg_client_mock: MqttMockPahoClient,
caplog: pytest.LogCaptureFixture,
exception: Exception,
) -> None:
"""Test reconnection is automatically done."""
mqtt_client_mock = setup_with_birth_msg_client_mock
Expand All @@ -1902,7 +1910,7 @@ async def test_auto_reconnect(
mqtt_client_mock.on_disconnect(None, None, 0)
await hass.async_block_till_done()

mqtt_client_mock.reconnect.side_effect = OSError("foo")
mqtt_client_mock.reconnect.side_effect = exception("foo")
async_fire_time_changed(
hass, utcnow() + timedelta(seconds=RECONNECT_INTERVAL_SECONDS)
)
Expand Down

0 comments on commit 42a4607

Please sign in to comment.