Working with Async

Although we have a backwards compatible API, using the async core directly will be a lot faster. Most core components have already been rewritten to leverage the async core. This includes the EntityComponent helper (foundation of light, switch, etc), scripts, groups and automation.

So if you are making calls to the core (the hass object) from within a callback or coroutine, use the methods that start with async_. If you need to call an async_ function that is a coroutine, your task must also be a coroutine.

Make sure that all properties defined on your entity do not result in I/O being done. All data has to be fetched inside the update method and cached on the entity. This is because these properties are read from within the event loop and thus doing I/O will result in the core of Home Assistant waiting until your I/O is done.

Calling async functions from threads

Sometimes it will happen that you’re in a thread and you want to call a function that is only available as async. Home Assistant includes a few async helper utilities to help with this.

In the following example, say_hello will schedule async_say_hello and block till the function has run and get the result back.

Dealing with passed in functions

If your code takes in functions from other code, you will not know which category the function belongs to and how they should be invoked. This usually only occurs if your code supplies an event helper like mqtt.async_subscribe or track_state_change_listener.

To help with this, there are two helper methods on the hass object that you can call from inside the event loop:

hass.async_run_job

Use this method if the function should be called as soon as possible. This will call callbacks immediately, schedule coroutines for execution on the event loop and schedule other functions to be run inside the thread pool.

Callback

Call immediately.

Coroutine

Schedule for execution on the event loop.

Other functions

Schedule for execution in the thread pool.

hass.async_add_job

Use this method if the function should be called but not get priority over already scheduled calls.