mirror of
https://github.com/home-assistant/core.git
synced 2025-07-25 22:27:07 +00:00
Let PAHO MQTT client handle connection to MQTT server (#35983)
* Let PAHO client handle connection to MQTT server
This commit is contained in:
parent
514c64619a
commit
8de863ecf1
@ -29,11 +29,7 @@ from homeassistant.const import (
|
|||||||
EVENT_HOMEASSISTANT_STOP,
|
EVENT_HOMEASSISTANT_STOP,
|
||||||
)
|
)
|
||||||
from homeassistant.core import Event, ServiceCall, callback
|
from homeassistant.core import Event, ServiceCall, callback
|
||||||
from homeassistant.exceptions import (
|
from homeassistant.exceptions import HomeAssistantError, Unauthorized
|
||||||
ConfigEntryNotReady,
|
|
||||||
HomeAssistantError,
|
|
||||||
Unauthorized,
|
|
||||||
)
|
|
||||||
from homeassistant.helpers import config_validation as cv, event, template
|
from homeassistant.helpers import config_validation as cv, event, template
|
||||||
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
||||||
from homeassistant.helpers.entity import Entity
|
from homeassistant.helpers.entity import Entity
|
||||||
@ -649,13 +645,7 @@ async def async_setup_entry(hass, entry):
|
|||||||
tls_version=tls_version,
|
tls_version=tls_version,
|
||||||
)
|
)
|
||||||
|
|
||||||
result: str = await hass.data[DATA_MQTT].async_connect()
|
await hass.data[DATA_MQTT].async_connect()
|
||||||
|
|
||||||
if result == CONNECTION_FAILED:
|
|
||||||
return False
|
|
||||||
|
|
||||||
if result == CONNECTION_FAILED_RECOVERABLE:
|
|
||||||
raise ConfigEntryNotReady
|
|
||||||
|
|
||||||
async def async_stop_mqtt(_event: Event):
|
async def async_stop_mqtt(_event: Event):
|
||||||
"""Stop MQTT component."""
|
"""Stop MQTT component."""
|
||||||
@ -835,15 +825,14 @@ class MQTT:
|
|||||||
self._mqttc.connect, self.broker, self.port, self.keepalive
|
self._mqttc.connect, self.broker, self.port, self.keepalive
|
||||||
)
|
)
|
||||||
except OSError as err:
|
except OSError as err:
|
||||||
_LOGGER.error("Failed to connect due to exception: %s", err)
|
_LOGGER.error("Failed to connect to MQTT server due to exception: %s", err)
|
||||||
return CONNECTION_FAILED_RECOVERABLE
|
|
||||||
|
|
||||||
if result != 0:
|
if result is not None and result != 0:
|
||||||
_LOGGER.error("Failed to connect: %s", mqtt.error_string(result))
|
_LOGGER.error(
|
||||||
return CONNECTION_FAILED
|
"Failed to connect to MQTT server: %s", mqtt.error_string(result)
|
||||||
|
)
|
||||||
|
|
||||||
self._mqttc.loop_start()
|
self._mqttc.loop_start()
|
||||||
return CONNECTION_SUCCESS
|
|
||||||
|
|
||||||
async def async_disconnect(self):
|
async def async_disconnect(self):
|
||||||
"""Stop the MQTT client."""
|
"""Stop the MQTT client."""
|
||||||
@ -933,6 +922,7 @@ class MQTT:
|
|||||||
return
|
return
|
||||||
|
|
||||||
self.connected = True
|
self.connected = True
|
||||||
|
_LOGGER.info("Connected to MQTT server (%s)", result_code)
|
||||||
|
|
||||||
# Group subscriptions to only re-subscribe once for each topic.
|
# Group subscriptions to only re-subscribe once for each topic.
|
||||||
keyfunc = attrgetter("topic")
|
keyfunc = attrgetter("topic")
|
||||||
@ -999,7 +989,7 @@ class MQTT:
|
|||||||
def _mqtt_on_disconnect(self, _mqttc, _userdata, result_code: int) -> None:
|
def _mqtt_on_disconnect(self, _mqttc, _userdata, result_code: int) -> None:
|
||||||
"""Disconnected callback."""
|
"""Disconnected callback."""
|
||||||
self.connected = False
|
self.connected = False
|
||||||
_LOGGER.warning("Disconnected from MQTT (%s).", result_code)
|
_LOGGER.warning("Disconnected from MQTT server (%s)", result_code)
|
||||||
|
|
||||||
|
|
||||||
def _raise_on_error(result_code: int) -> None:
|
def _raise_on_error(result_code: int) -> None:
|
||||||
|
@ -18,7 +18,6 @@ from homeassistant.const import (
|
|||||||
TEMP_CELSIUS,
|
TEMP_CELSIUS,
|
||||||
)
|
)
|
||||||
from homeassistant.core import callback
|
from homeassistant.core import callback
|
||||||
from homeassistant.exceptions import ConfigEntryNotReady
|
|
||||||
from homeassistant.helpers import device_registry
|
from homeassistant.helpers import device_registry
|
||||||
from homeassistant.setup import async_setup_component
|
from homeassistant.setup import async_setup_component
|
||||||
from homeassistant.util.dt import utcnow
|
from homeassistant.util.dt import utcnow
|
||||||
@ -678,23 +677,24 @@ async def test_setup_embedded_with_embedded(hass):
|
|||||||
assert _start.call_count == 1
|
assert _start.call_count == 1
|
||||||
|
|
||||||
|
|
||||||
async def test_setup_fails_if_no_connect_broker(hass):
|
async def test_setup_logs_error_if_no_connect_broker(hass, caplog):
|
||||||
"""Test for setup failure if connection to broker is missing."""
|
"""Test for setup failure if connection to broker is missing."""
|
||||||
entry = MockConfigEntry(domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"})
|
entry = MockConfigEntry(domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"})
|
||||||
|
|
||||||
with patch("paho.mqtt.client.Client") as mock_client:
|
with patch("paho.mqtt.client.Client") as mock_client:
|
||||||
mock_client().connect = lambda *args: 1
|
mock_client().connect = lambda *args: 1
|
||||||
assert not await mqtt.async_setup_entry(hass, entry)
|
assert await mqtt.async_setup_entry(hass, entry)
|
||||||
|
assert "Failed to connect to MQTT server:" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
async def test_setup_raises_ConfigEntryNotReady_if_no_connect_broker(hass):
|
async def test_setup_raises_ConfigEntryNotReady_if_no_connect_broker(hass, caplog):
|
||||||
"""Test for setup failure if connection to broker is missing."""
|
"""Test for setup failure if connection to broker is missing."""
|
||||||
entry = MockConfigEntry(domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"})
|
entry = MockConfigEntry(domain=mqtt.DOMAIN, data={mqtt.CONF_BROKER: "test-broker"})
|
||||||
|
|
||||||
with patch("paho.mqtt.client.Client") as mock_client:
|
with patch("paho.mqtt.client.Client") as mock_client:
|
||||||
mock_client().connect = MagicMock(side_effect=OSError("Connection error"))
|
mock_client().connect = MagicMock(side_effect=OSError("Connection error"))
|
||||||
with pytest.raises(ConfigEntryNotReady):
|
assert await mqtt.async_setup_entry(hass, entry)
|
||||||
await mqtt.async_setup_entry(hass, entry)
|
assert "Failed to connect to MQTT server due to exception:" in caplog.text
|
||||||
|
|
||||||
|
|
||||||
async def test_setup_uses_certificate_on_certificate_set_to_auto(hass, mock_mqtt):
|
async def test_setup_uses_certificate_on_certificate_set_to_auto(hass, mock_mqtt):
|
||||||
|
Loading…
x
Reference in New Issue
Block a user