From 9d4de2a7221cff92263cad5bd68c0570d8172ea1 Mon Sep 17 00:00:00 2001 From: PeteBa Date: Sun, 16 Dec 2018 20:54:33 +0000 Subject: [PATCH] Initialise plant attributes at startup (#19315) * Initialise plant attributes at startup * Pvizeli review comments * Martin review change --- homeassistant/components/plant.py | 11 ++++++++--- tests/components/test_plant.py | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/homeassistant/components/plant.py b/homeassistant/components/plant.py index 9659fd4f7e1ef7..cdd3c8463aa9e6 100644 --- a/homeassistant/components/plant.py +++ b/homeassistant/components/plant.py @@ -105,9 +105,6 @@ async def async_setup(hass, config): for plant_name, plant_config in config[DOMAIN].items(): _LOGGER.info("Added plant %s", plant_name) entity = Plant(plant_name, plant_config) - sensor_entity_ids = list(plant_config[CONF_SENSORS].values()) - _LOGGER.debug("Subscribing to entity_ids %s", sensor_entity_ids) - async_track_state_change(hass, sensor_entity_ids, entity.state_changed) entities.append(entity) await component.async_add_entities(entities) @@ -250,6 +247,14 @@ async def async_added_to_hass(self): # only use the database if it's configured self.hass.async_add_job(self._load_history_from_db) + async_track_state_change(self.hass, list(self._sensormap), + self.state_changed) + + for entity_id in self._sensormap: + state = self.hass.states.get(entity_id) + if state is not None: + self.state_changed(entity_id, None, state) + async def _load_history_from_db(self): """Load the history of the brightness values from the database. diff --git a/tests/components/test_plant.py b/tests/components/test_plant.py index 6118e30925ea27..13cfb310bcdc37 100644 --- a/tests/components/test_plant.py +++ b/tests/components/test_plant.py @@ -86,6 +86,20 @@ def test_low_battery(self): assert sensor.state == 'problem' assert sensor.state_attributes['problem'] == 'battery low' + def test_initial_states(self): + """Test plant initialises attributes if sensor already exists.""" + self.hass.states.set(MOISTURE_ENTITY, 5, + {ATTR_UNIT_OF_MEASUREMENT: 'us/cm'}) + plant_name = 'some_plant' + assert setup_component(self.hass, plant.DOMAIN, { + plant.DOMAIN: { + plant_name: GOOD_CONFIG + } + }) + self.hass.block_till_done() + state = self.hass.states.get('plant.'+plant_name) + assert 5 == state.attributes[plant.READING_MOISTURE] + def test_update_states(self): """Test updating the state of a sensor.