From 28026b042847ae63a1bd34d605e1313e9e8a72d2 Mon Sep 17 00:00:00 2001 From: Fabio Manganiello Date: Thu, 7 Apr 2022 01:46:37 +0200 Subject: [PATCH] Trigger an EntityUpdateEvent when an entity state changes --- platypush/entities/_engine.py | 6 ++++++ platypush/message/event/entities.py | 19 +++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 platypush/message/event/entities.py diff --git a/platypush/entities/_engine.py b/platypush/entities/_engine.py index d88e2c9d7..63d9b95be 100644 --- a/platypush/entities/_engine.py +++ b/platypush/entities/_engine.py @@ -7,6 +7,9 @@ from typing import Iterable, List from sqlalchemy import and_, or_ from sqlalchemy.orm import Session +from platypush.context import get_bus +from platypush.message.event.entities import EntityUpdateEvent + from ._base import Entity @@ -130,3 +133,6 @@ class EntitiesEngine(Thread): entities = self._merge_entities(entities, existing_entities) # type: ignore session.add_all(entities) session.commit() + + for entity in entities: + get_bus().post(EntityUpdateEvent(entity=entity)) diff --git a/platypush/message/event/entities.py b/platypush/message/event/entities.py new file mode 100644 index 000000000..6b56100a7 --- /dev/null +++ b/platypush/message/event/entities.py @@ -0,0 +1,19 @@ +from typing import Union + +from platypush.entities import Entity +from platypush.message.event import Event + + +class EntityUpdateEvent(Event): + """ + This even is triggered whenever an entity of any type (a switch, a light, + a sensor, a media player etc.) updates its state. + """ + + def __init__(self, entity: Union[Entity, dict], *args, **kwargs): + if isinstance(entity, Entity): + entity = entity.to_json() + super().__init__(entity=entity, *args, **kwargs) + + +# vim:sw=4:ts=4:et: