Event Trigger
The event trigger enables you to execute actions when an event occurs in Home Assistant. It implements the same functionality as the Home Assistant event trigger, providing a seamless integration between SmartBeans and Home Assistant.
Annotating Methods
The @OnEventTrigger
annotation allows you to invoke any SmartBean method when the event occurs. The event type is
specified using the type
attribute. The event type is the same as the event type you specify in Home Assistant.
public class ASampleBean implements SmartBean {
private SmartBeans sb;
@OnEventTrigger(type = "MY_CUSTOM_EVENT")
public void onCustomEvent() {
sb.log("Custom event occured");
}
}
Filter Event Data
You can optionally specify the event data to only trigger the method when the event data matches the specified data.
public class ASampleBean implements SmartBean {
private SmartBeans sb;
@OnEventTrigger(type = "MY_CUSTOM_EVENT", data = @Param(name = "mood", value = "happy"))
public void onHappy() {
sb.log("Someone is happy.");
}
}
Events
Your annotated method can optionally include a Event
parameter. When the trigger is fired, SmartBeans provides an
event object that gives you access to the event parameters. Through this object, you can retrieve the event data.
public class ASampleBean implements SmartBean {
private SmartBeans sb;
@OnEventTrigger(type = "MY_CUSTOM_EVENT")
public void onHappy(Event event) {
sb.log("Someone is " + event.getData().asString("mood") + ".");
}
}
Register Triggers Programmatically
As an alternative to the annotation-based approach, you can register triggers programmatically using the
registerTrigger()
method of the SmartBeans
API. To register a event trigger, you can use the event()
factory method of the Triggers
class. This factory provides a fluent API to create the same triggers as with
annotations. There are two main reasons to choose the programmatic approach over annotations:
- You need to create triggers with dynamic parameters, for example when the event type is generated by business logic.
- You need to register or unregister the trigger at a specific point in time, rather than having it permanently active.
Here is an example of registering and unregistering a trigger with the programmatic approach:
public class ASampleBean implements SmartBean {
private SmartBeans sb;
private TriggerRegistration<Event> eventTriggerRegistration;
public void registerEventTrigger() {
eventTriggerRegistration = sb.registerTrigger(
Triggers.event()
.ofType("MY_CUSTOM_EVENT")
.withData(data -> data.setAttribute("mood", "happy"))
);
eventTriggerRegistration.onTrigger(this::onCustomEvent);
}
public void unregisterEventTrigger() {
eventTriggerRegistration.unregister();
}
private void onCustomEvent(Event event) {
sb.log("Custom event occured.");
}
}