Only subscribe when MQTT client is connected. (#34557)

pull/34563/head
Erik Montnemery 2020-04-22 23:38:04 +02:00 committed by GitHub
parent d6ab36bf8e
commit 4448eb94a1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 15 additions and 1 deletions

View File

@ -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:

View File

@ -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),