Make the mqtt discovery update tasks eager and fix race (#117105)

* Fix mqtt discovery race for update rapidly followed on creation

* Revert unrelated renaming local var
This commit is contained in:
Jan Bouwhuis 2024-05-08 21:42:11 +02:00 committed by GitHub
parent 6b3ffad77a
commit 20b29242f1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -1015,8 +1015,7 @@ class MqttDiscoveryUpdate(Entity):
self.hass.async_create_task( self.hass.async_create_task(
_async_process_discovery_update_and_remove( _async_process_discovery_update_and_remove(
payload, self._discovery_data payload, self._discovery_data
), )
eager_start=False,
) )
elif self._discovery_update: elif self._discovery_update:
if old_payload != self._discovery_data[ATTR_DISCOVERY_PAYLOAD]: if old_payload != self._discovery_data[ATTR_DISCOVERY_PAYLOAD]:
@ -1025,8 +1024,7 @@ class MqttDiscoveryUpdate(Entity):
self.hass.async_create_task( self.hass.async_create_task(
_async_process_discovery_update( _async_process_discovery_update(
payload, self._discovery_update, self._discovery_data payload, self._discovery_update, self._discovery_data
), )
eager_start=False,
) )
else: else:
# Non-empty, unchanged payload: Ignore to avoid changing states # Non-empty, unchanged payload: Ignore to avoid changing states
@ -1059,6 +1057,15 @@ class MqttDiscoveryUpdate(Entity):
# rediscovered after a restart # rediscovered after a restart
await async_remove_discovery_payload(self.hass, self._discovery_data) await async_remove_discovery_payload(self.hass, self._discovery_data)
@final
async def add_to_platform_finish(self) -> None:
"""Finish adding entity to platform."""
await super().add_to_platform_finish()
# Only send the discovery done after the entity is fully added
# and the state is written to the state machine.
if self._discovery_data is not None:
send_discovery_done(self.hass, self._discovery_data)
@callback @callback
def add_to_platform_abort(self) -> None: def add_to_platform_abort(self) -> None:
"""Abort adding an entity to a platform.""" """Abort adding an entity to a platform."""
@ -1218,8 +1225,6 @@ class MqttEntity(
self._prepare_subscribe_topics() self._prepare_subscribe_topics()
await self._subscribe_topics() await self._subscribe_topics()
await self.mqtt_async_added_to_hass() await self.mqtt_async_added_to_hass()
if self._discovery_data is not None:
send_discovery_done(self.hass, self._discovery_data)
async def mqtt_async_added_to_hass(self) -> None: async def mqtt_async_added_to_hass(self) -> None:
"""Call before the discovery message is acknowledged. """Call before the discovery message is acknowledged.