define and use switch._unsub_trackers

This commit is contained in:
Bas Nijholt 2020-09-29 10:48:35 +02:00
commit 58b4c639dd
2 changed files with 13 additions and 14 deletions

View file

@ -99,9 +99,7 @@ async def async_unload_entry(hass, config_entry: ConfigEntry) -> bool:
data = hass.data[DOMAIN]
data[config_entry.entry_id][UNDO_UPDATE_LISTENER]()
switch = data[config_entry.entry_id][SWITCH_DOMAIN]
while switch.unsub_trackers:
unsub = switch.unsub_trackers.pop()
unsub()
switch._unsub_trackers() # pylint: disable=protected-access
if unload_ok:
data.pop(config_entry.entry_id)

View file

@ -263,10 +263,10 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity):
"""Call when entity about to be added to hass."""
if self._lights:
if self.hass.is_running:
await self._setup_listeners()
await self._setup_trackers()
else:
self.hass.bus.async_listen_once(
EVENT_HOMEASSISTANT_START, self._setup_listeners
EVENT_HOMEASSISTANT_START, self._setup_trackers
)
last_state = await self.async_get_last_state()
if last_state and last_state.state == STATE_ON:
@ -294,13 +294,8 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity):
self.turn_on_off_listener.lights.update(all_lights)
self._lights = list(all_lights)
async def _setup_listeners(self, _=None):
if self.unsub_trackers:
_LOGGER.error(
"%s: Calling '_setup_listeners' when they are already set up", self.name
)
return
async def _setup_trackers(self, _=None):
assert not self.unsub_trackers
self._unpack_light_groups()
rm_interval = async_track_time_interval(
self.hass, self._async_update_at_interval, self._interval
@ -342,13 +337,15 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity):
return {key: None for key in attrs}
return attrs
async def async_turn_on(self, adjust_lights=True, setup_listeners=True):
async def async_turn_on(
self, adjust_lights=True, setup_listeners=True
): # pylint: disable=arguments-differ
"""Turn on adaptive lighting."""
if self.is_on:
return
self._state = True
if setup_listeners:
self._setup_listeners()
self._setup_trackers()
if adjust_lights:
await self._update_lights(transition=self._initial_transition, force=True)
@ -357,6 +354,10 @@ class AdaptiveSwitch(SwitchEntity, RestoreEntity):
if not self.is_on:
return
self._state = False
self._unsub_trackers()
def _unsub_trackers(self):
assert self.unsub_trackers
while self.unsub_trackers:
unsub = self.unsub_trackers.pop()
unsub()