Calling back to update the config entry from a thread

Using this code, it is still erroring about being on a thread and I should use add_job, but I am using add_job? Any idea why this is failing?

    def _update_config_entry():
        hass.config_entries.async_update_entry(
            config_entry,
            data={**config_entry.data, "entity_ts": datetime.now(UTC)},
        )

    def _async_registry_updated(event: Event[EventEntityRegistryUpdatedData]) -> None:
        # Reload entities and then update the other pieces of the system.
        _LOGGER.debug(
            "%s: Updateing entity from area change", config_entry.data[CONF_NAME]
        )
        hass.add_job(_update_config_entry)

calls hass.config_entries.async_update_entry from a thread. For more information, see Thread Safety with asyncio | Home Assistant Developer Docs at custom_components/simply_magic_areas/init.py,

I fixed this using a lambda

 def _update_config_entry():
        hass.loop.call_soon_threadsafe(
            lambda: hass.config_entries.async_update_entry(
                config_entry,
                data={**config_entry.data, "entity_ts": datetime.now(UTC)},
            )
        )

I think you need to decorate your _update_config_entry with @callback per this.

def add_job[*_Ts](
        self, target: Callable[[*_Ts], Any] | Coroutine[Any, Any, Any], *args: *_Ts
    ) -> None:
        """Add a job to be executed by the event loop or by an executor.

        If the job is either a coroutine or decorated with @callback, it will be
        run by the event loop, if not it will be run by an executor.

        target: target to call.
        args: parameters for method to call.
        """
2 Likes