Can an entity listen for HASS events?

I can’t do hass.bus.listen(...) immediately on account of hass not yet being initialized, have to wait until add_devices has completed (which I can’t do directly in async_setup_platform because async_add_devices is async …

If I try doing it later on in trigger_update, I get ‘RuntimeError: Cannot be called from within the event loop’, if I try it inside of async_update, device_state_attributes, etc, then HASS just locks up with no output (error or otherwise).

Is it not possible for an entity to listen to events? Doing so will be much cleaner than having my entities have to write to each other’s properties (after somehow finding each other), or having multiple entities hooked to the same callbacks in the library for the device I’m communicating with …

I can send an event from the other entity just fine, just can’t listen for it …

You should be able to start listening for events with async_listen in the __init__ method of your entity.

import asyncio
from logging import getLogger
from homeassistant.helpers.entity import Entity

_LOGGER = getLogger(__name__)

def async_setup_platform(hass, config, async_add_devices, discovery_info=None):
    async_add_devices([MySensor(hass)])

class MySensor(Entity):
    def __init__(self, hass):
        hass.bus.async_listen("event type", self._handle_event)

    def _handle_event(self, call):
        _LOGGER.info("Event received: %s", call.data)
1 Like

:man_facepalming: That makes sense.

edit: tested and it works.