Skip to content

RFC: Event platform #419

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 1 commit into
base: dev
Choose a base branch
from
Draft

Conversation

puddly
Copy link
Contributor

@puddly puddly commented Apr 16, 2025

This is a stub PR that explores implementing the Home Assistant Core "event" platform for ZHA. This platform is a little different from the others in that it does not expose state but rather expects events to be triggered at runtime via core_entity.trigger_event(event_type).

The functionality exposed by this platform has always been a pain point for ZHA (since we rely on device automation triggers at the moment) and I think brings up the first difficulty with quirks v2. Below is a sample implementation that fits within the constraints of quirks v2:

class DevelcoButtonEventTypes(StrEnum):
    PRESSED = "pressed"
    RELEASED = "released"


def setup_triggers(device: Device, trigger_event: Callable[[str], None]) -> None:
    """Map device events to event entity triggers."""

    class Listener:
        def attribute_updated(
            self, attribute_id: int, value: Any, timestamp: datetime
        ) -> None:
            if attribute_id != BinaryInput.present_value:
                return

            if value:
                trigger_event(DevelcoButtonEventTypes.PRESSED)
            else:
                trigger_event(DevelcoButtonEventTypes.RELEASED)

    device.endpoints[1].binary_input.add_listener(Listener())


# Quirk defined here
(
    QuirkBuilder("develco", "button")
    .event(
        unique_id_suffix="button",
        translation_key="button",
        fallback_name="Button",
        event_types=DevelcoButtonEventTypes,
        setup_triggers=setup_triggers,
    )
    .add_to_registry()
)

An alternative implementation that relies on quirks directly creating ZHA entities is something that I somewhat prefer:

from zha.platforms.event import EventEntity

class DevelcoButtonEntity(EventEntity):
    _attr_event_types = DevelcoButtonEventTypes
    _attr_translation_key = "button"
    _unique_id_suffix = "button"
    _fallback_name = "Button"

    def on_add(self):
        self.device.endpoints[1].binary_input.add_listener(self)  # TODO: make this better in zigpy...
        self._on_remove_callbacks.append(lambda: self.device.remove_listener(self))

    def attribute_updated(
        self, attribute_id: int, value: Any, timestamp: datetime
    ) -> None:
        if attribute_id != BinaryInput.present_value:
            return

        if value:
            self.trigger_event(DevelcoButtonEventTypes.PRESSED)
        else:
            self.trigger_event(DevelcoButtonEventTypes.RELEASED)

(
    QuirkBuilder("develco", "button")
    .prevent_default_entity_creation(...)
    .register_entity(DevelcoButtonEntity)
    .add_to_registry()
)

Copy link

codecov bot commented Apr 16, 2025

Codecov Report

Attention: Patch coverage is 5.55556% with 34 lines in your changes missing coverage. Please review.

Project coverage is 96.37%. Comparing base (5ed0dbf) to head (9e513e2).

Files with missing lines Patch % Lines
zha/application/platforms/event/__init__.py 0.00% 29 Missing ⚠️
zha/application/platforms/event/const.py 0.00% 5 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##              dev     #419      +/-   ##
==========================================
- Coverage   96.70%   96.37%   -0.34%     
==========================================
  Files          61       63       +2     
  Lines        9874     9910      +36     
==========================================
+ Hits         9549     9551       +2     
- Misses        325      359      +34     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant