diff --git a/homeassistant/components/owntracks/__init__.py b/homeassistant/components/owntracks/__init__.py index a4df4303fa8..1cc7a050aec 100644 --- a/homeassistant/components/owntracks/__init__.py +++ b/homeassistant/components/owntracks/__init__.py @@ -192,6 +192,7 @@ class OwnTracksContext: self.region_mapping = region_mapping self.events_only = events_only self.mqtt_topic = mqtt_topic + self._pending_msg = [] @callback def async_valid_accuracy(self, message): @@ -222,10 +223,19 @@ class OwnTracksContext: return True + @callback + def set_async_see(self, func): + """Set a new async_see function.""" + self.async_see = func + for msg in self._pending_msg: + func(**msg) + self._pending_msg.clear() + + # pylint: disable=method-hidden @callback def async_see(self, **data): """Send a see message to the device tracker.""" - raise NotImplementedError + self._pending_msg.append(data) @callback def async_see_beacons(self, hass, dev_id, kwargs_param): diff --git a/homeassistant/components/owntracks/device_tracker.py b/homeassistant/components/owntracks/device_tracker.py index ed2749262bd..742b7c34435 100644 --- a/homeassistant/components/owntracks/device_tracker.py +++ b/homeassistant/components/owntracks/device_tracker.py @@ -36,7 +36,7 @@ async def async_setup_entry(hass, entry, async_add_entities): ) async_add_entities([entity]) - hass.data[OT_DOMAIN]['context'].async_see = _receive_data + hass.data[OT_DOMAIN]['context'].set_async_see(_receive_data) # Restore previously loaded devices dev_reg = await device_registry.async_get_registry(hass) diff --git a/tests/components/owntracks/test_init.py b/tests/components/owntracks/test_init.py index fafe9678e78..b662bbcd6bd 100644 --- a/tests/components/owntracks/test_init.py +++ b/tests/components/owntracks/test_init.py @@ -4,7 +4,7 @@ import asyncio import pytest from homeassistant.setup import async_setup_component - +from homeassistant.components import owntracks from tests.common import mock_component, MockConfigEntry MINIMAL_LOCATION_MESSAGE = { @@ -160,3 +160,24 @@ def test_returns_error_missing_device(mock_client): json = yield from resp.json() assert json == [] + + +def test_context_delivers_pending_msg(): + """Test that context is able to hold pending messages while being init.""" + context = owntracks.OwnTracksContext( + None, None, None, None, None, None, None, None + ) + context.async_see(hello='world') + context.async_see(world='hello') + received = [] + + context.set_async_see(lambda **data: received.append(data)) + + assert len(received) == 2 + assert received[0] == {'hello': 'world'} + assert received[1] == {'world': 'hello'} + + received.clear() + + context.set_async_see(lambda **data: received.append(data)) + assert len(received) == 0