diff --git a/homeassistant/components/mqtt/__init__.py b/homeassistant/components/mqtt/__init__.py index 248769099ae..25b2b0381ea 100644 --- a/homeassistant/components/mqtt/__init__.py +++ b/homeassistant/components/mqtt/__init__.py @@ -872,7 +872,9 @@ class MQTT: subscription = Subscription(topic, msg_callback, qos, encoding) self.subscriptions.append(subscription) - await self._async_perform_subscription(topic, qos) + # Only subscribe if currently connected. + if self.connected: + await self._async_perform_subscription(topic, qos) @callback def async_remove() -> None: diff --git a/tests/components/mqtt/test_init.py b/tests/components/mqtt/test_init.py index 75c6d49d156..290b70953af 100644 --- a/tests/components/mqtt/test_init.py +++ b/tests/components/mqtt/test_init.py @@ -580,6 +580,9 @@ class TestMQTTCallbacks(unittest.TestCase): self.hass.data["mqtt"]._mqttc.subscribe.side_effect = side_effect + # Fake that the client is connected + self.hass.data["mqtt"].connected = True + calls_a = mock.MagicMock() mqtt.subscribe(self.hass, "test/state", calls_a) self.hass.block_till_done() @@ -592,6 +595,9 @@ class TestMQTTCallbacks(unittest.TestCase): def test_not_calling_unsubscribe_with_active_subscribers(self): """Test not calling unsubscribe() when other subscribers are active.""" + # Fake that the client is connected + self.hass.data["mqtt"].connected = True + unsub = mqtt.subscribe(self.hass, "test/state", None) mqtt.subscribe(self.hass, "test/state", None) self.hass.block_till_done() @@ -603,6 +609,9 @@ class TestMQTTCallbacks(unittest.TestCase): def test_restore_subscriptions_on_reconnect(self): """Test subscriptions are restored on reconnect.""" + # Fake that the client is connected + self.hass.data["mqtt"].connected = True + mqtt.subscribe(self.hass, "test/state", None) self.hass.block_till_done() assert self.hass.data["mqtt"]._mqttc.subscribe.call_count == 1 @@ -614,6 +623,9 @@ class TestMQTTCallbacks(unittest.TestCase): def test_restore_all_active_subscriptions_on_reconnect(self): """Test active subscriptions are restored correctly on reconnect.""" + # Fake that the client is connected + self.hass.data["mqtt"].connected = True + self.hass.data["mqtt"]._mqttc.subscribe.side_effect = ( (0, 1), (0, 2),