Skip to main content

Sun Trigger

The sun trigger enables you to execute actions when the sun is setting or rising. It implements the same functionality as the Home Assistant sun trigger, providing a seamless integration between SmartBeans and Home Assistant.

Annotating Methods

The @OnSunriseTrigger and @OnSunsetTrigger annotations let you invoke any SmartBean method at sunrise or sunset.

public class ASampleBean implements SmartBean {

private SmartBeans sb;

@OnSunriseTrigger
public void whenSunIsRising() {
sb.log("sun is rising...");
}

@OnSunsetTrigger
public void whenSunIsSetting() {
sb.log("sun is setting...");
}
}

Define Offset

By specifying an offset, the method is scheduled relative to sunrise or sunset. The offset can be positive (after) or negative (before) and may be provided either as a number of seconds or in the hh:mm:ss format, optionally prefixed with + or -.

public class ASampleBean implements SmartBean {

private SmartBeans sb;

@OnSunsetTrigger(offset = "-00:45:00")
public void whenSunIsSetting() {
sb.log("sunset is in 45 minutes!");
}
}

Sun Events

Your annotated method can optionally include a SunEvent parameter. When the trigger is fired, SmartBeans provides an event object that gives you access to the event parameters. At the moment this is just the name of the event itself and access to generic trigger data, but it may be extended in the future.

public class ASampleBean implements SmartBean {

private SmartBeans sb;

@OnSunsetTrigger(offset = "-00:45:00")
public void whenSunIsSetting(SunEvent event) {
sb.log(event.getEvent() + " is in 45 minutes!");
}
}

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 sun trigger, you can use the sun() 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:

  1. You need to create triggers with dynamic parameters, for example when the offset is generated by business logic.
  2. 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<SunEvent> sunTriggerRegistration;

public void registerSunTrigger() {
sunTriggerRegistration = sb.registerTrigger(
Triggers.sun()
.sunset()
.withOffset(Duration.ofMinutes(45).negated())
);
sunTriggerRegistration.onTrigger(this::onSunset);
}

public void unregisterMqttTrigger() {
sunTriggerRegistration.unregister();
}

private void onSunset(SunEvent event) {
sb.log("Sunset in 45 minutes!");
}
}