Migrate event consumers from handle_<event> methods to typed on_event subscriptions

Open
#928 2 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
22/100
Issue type
Refactor
Clarity
Mostly clear
Activity status
Active
Tech stack
python
Domain
embedded-iot

Research direction

Start with EventBase and _handle_event_protocol in zha/event.py, then the event classes in zha/zigbee/device.py and zha/application/gateway.py, where the event_type and event keys disagree. The Home Assistant side is homeassistant/components/zha/helpers.py, where the two proxies register on_all_events. Done means the proxies use typed on_event subscriptions and the key convention is settled. Section 1 needs a maintainer decision on the key before the rest can proceed.

Written by the indexing model from the issue text.

Description

code quality

Follow-up to #923 and the discussion in home-assistant/core#184549. This tracks moving every consumer off the legacy handle_<event> protocol and onto typed on_event subscriptions, so the protocol can be removed afterwards.

Background

EventBase in zha/event.py offers two ways to consume events:

  • Legacy protocol: the subscriber registers on_all_events(self._handle_event_protocol) and receives every event the object emits. _handle_event_protocol then looks up a method named handle_<event.event> by name. Since #923, events without such a method are silently ignored instead of logging "Received unknown event".
  • Typed subscription (the new system): on_event(<event name>, callback) registers one explicit callback for one event. Home Assistant already uses this for firmware version updates (DeviceFirmwareInfoUpdatedEvent), entity state (subscribe_state), event entities and infrared receivers.

In zha dev (0ea5e1ad) and HA Core dev, the only remaining users of the legacy protocol are Home Assistant's two ZHA proxy classes. zha itself only defines it (plus tests in tests/test_event.py). The handle_attribute_updated methods on zha entities are plain callbacks passed to cluster.on_event(...), so they are not affected.

1. zha: make the subscription key consistent per event class

The event_type and event fields of zha's event dataclasses don't mean the same thing across classes, so on_event(SomeEvent.event_type, ...) only works for some of them:

  • Device events (zha/zigbee/device.py: ZHAEvent, DeviceFirmwareInfoUpdatedEvent, DeviceEntityAddedEvent, DeviceEntityRemovedEvent, DeviceConfiguredEvent, ClusterBindEvent, ClusterConfigureReportingEvent): event_type == event, and they are emitted under that name. Both keys work.
  • Gateway events (zha/application/gateway.py: ConnectionLostEvent, DeviceJoinedEvent, DeviceLeftEvent, RawDeviceInitializedEvent, DeviceFullInitEvent, DeviceRemovedEvent): every class has event_type = ZHA_GW_MSG ("zha_gateway_message"), but each is emitted under its event name (device_joined, device_left, ...). Nothing is ever emitted under "zha_gateway_message", so gateway.on_event(DeviceJoinedEvent.event_type, cb) subscribes successfully but never fires.
  • GroupEvent is one class for four events. event is a per-instance field set in Gateway._emit_group_gateway_message (group_added, group_removed, group_member_added, group_member_removed), so there is no class-level key to subscribe with. Subscribers have to use the ZHA_GW_MSG_GROUP_* constants.
  • Entity events (EntityStateChangedEvent, EntityEventTriggeredEvent, EntityInfraredSignalReceivedEvent): event_type = "entity", emitted under event. HA subscribes with .event.

Tasks:

  • Decide on one canonical subscription key per event class (e.g. a unique event_type per class that is also the emitted name, or always event), and apply it to the gateway and entity events. Check first whether anything depends on the current event_type values.
  • Split GroupEvent into one class per event (or otherwise give each a class-level key).

HA can migrate (section 2) before this, by subscribing with the names that are actually emitted. This section is about making on_event(SomeEvent.<key>, ...) the one obvious pattern.

2. Home Assistant: migrate the ZHA proxies (homeassistant/components/zha/helpers.py)

ZHADeviceProxy registers self.device.on_all_events(self._handle_event_protocol) in __init__ and again in async_rebind_device. Its handlers:

  • handle_zha_event (ZHAEvent)
  • handle_zha_cluster_bind (ClusterBindEvent)
  • handle_zha_cluster_configure_reporting (ClusterConfigureReportingEvent)
  • handle_zha_device_configured (DeviceConfiguredEvent)
  • handle_zha_device_entity_added_event (DeviceEntityAddedEvent)
  • handle_zha_device_entity_removed_event (DeviceEntityRemovedEvent)

ZHAGatewayProxy registers self.gateway.on_all_events(self._handle_event_protocol). Its handlers:

  • handle_connection_lost (ConnectionLostEvent)
  • handle_device_joined (DeviceJoinedEvent)
  • handle_raw_device_initialized (RawDeviceInitializedEvent)
  • handle_device_fully_initialized (DeviceFullInitEvent)
  • handle_device_left (DeviceLeftEvent)
  • handle_device_removed (DeviceRemovedEvent)
  • handle_group_added, handle_group_removed, handle_group_member_added, handle_group_member_removed (GroupEvent)

Both proxies subclass zha's EventBase only to inherit _handle_event_protocol. They never emit, and all of the handlers above are synchronous. After the migration they can stop subclassing EventBase.

3. zha: remove the legacy protocol

  • Once a Home Assistant release no longer calls it, remove EventBase._handle_event_protocol from zha/event.py, along with its tests in tests/test_event.py.
  • Re-evaluate whether the per-instance event field is still needed once nothing dispatches on it. It depends on the key chosen in section 1.

Related, outside zha's EventBase

  • zigpy has its own copy of EventBase (zigpy/event/event_base.py), and its _handle_event_protocol still logs "Received unknown event". Nothing in zigpy, zha or HA's ZHA integration calls zigpy's copy (zha and HA use zha.event.EventBase), so it can be removed there too.

  • One layer down, zha still consumes zigpy through the name-dispatched ListenableMixin.listener_event / add_listener pattern:

    • the gateway is registered as a listener on the application controller and on its groups (connection_lost, device_joined, raw_device_initialized, device_initialized, device_reinterviewed, device_left, device_removed, group_*, handle_message);
    • cluster_command on the virtual entities and the IAS ACE alarm control panel;
    • quirks' zha_send_event, received by _ClusterEventForwarder in zha/zigbee/endpoint.py.

    So far zigpy emits typed events only for ZCL attribute events, the OTA query cache and image-available events, and Green Power commands, so moving these needs new typed events in zigpy first. That may deserve its own zigpy issue.

Dominant language
Python
Stars
96
Forks
84
Avg merge
2d 4h
Merged PRs (30d)
30

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from zigpy/zha

All issues in zigpy/zha

Similar issues

More Python issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.