2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.automation.pwm.internal.handler;
15 import static org.openhab.automation.pwm.internal.PWMConstants.*;
17 import java.math.BigDecimal;
18 import java.util.Collections;
19 import java.util.Objects;
20 import java.util.Optional;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.automation.pwm.internal.PWMException;
28 import org.openhab.automation.pwm.internal.handler.state.StateMachine;
29 import org.openhab.core.automation.ModuleHandlerCallback;
30 import org.openhab.core.automation.Trigger;
31 import org.openhab.core.automation.handler.BaseTriggerModuleHandler;
32 import org.openhab.core.automation.handler.TriggerHandlerCallback;
33 import org.openhab.core.config.core.Configuration;
34 import org.openhab.core.events.Event;
35 import org.openhab.core.events.EventFilter;
36 import org.openhab.core.events.EventSubscriber;
37 import org.openhab.core.items.Item;
38 import org.openhab.core.items.ItemNotFoundException;
39 import org.openhab.core.items.ItemRegistry;
40 import org.openhab.core.items.events.ItemStateEvent;
41 import org.openhab.core.library.types.DecimalType;
42 import org.openhab.core.library.types.OnOffType;
43 import org.openhab.core.library.types.StringType;
44 import org.openhab.core.types.State;
45 import org.openhab.core.types.UnDefType;
46 import org.osgi.framework.BundleContext;
47 import org.osgi.framework.ServiceRegistration;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
52 * Represents a Trigger module in the rules engine.
54 * @author Fabian Wolter - Initial Contribution
57 public class PWMTriggerHandler extends BaseTriggerModuleHandler implements EventSubscriber {
58 public static final String MODULE_TYPE_ID = AUTOMATION_NAME + ".trigger";
59 private static final Set<String> SUBSCRIBED_EVENT_TYPES = Set.of(ItemStateEvent.TYPE);
60 private final Logger logger = LoggerFactory.getLogger(PWMTriggerHandler.class);
61 private final BundleContext bundleContext;
62 private final EventFilter eventFilter;
63 private final Optional<Double> minDutyCycle;
64 private final Optional<Double> maxDutyCycle;
65 private final boolean isEquateMinToZero;
66 private final boolean isEquateMaxToHundred;
67 private final Optional<Double> deadManSwitchTimeoutMs;
68 private final Item dutyCycleItem;
69 private @Nullable ServiceRegistration<?> eventSubscriberRegistration;
70 private @Nullable ScheduledFuture<?> deadMeanSwitchTimer;
71 private @Nullable StateMachine stateMachine;
73 public PWMTriggerHandler(Trigger module, ItemRegistry itemRegistry, BundleContext bundleContext) {
75 this.bundleContext = bundleContext;
77 Configuration config = module.getConfiguration();
79 String dutycycleItemName = (String) Objects.requireNonNull(config.get(CONFIG_DUTY_CYCLE_ITEM),
80 "DutyCycle item is not set");
82 minDutyCycle = getOptionalDoubleFromConfig(config, CONFIG_MIN_DUTYCYCLE);
83 isEquateMinToZero = getBooleanFromConfig(config, CONFIG_EQUATE_MIN_TO_ZERO);
84 maxDutyCycle = getOptionalDoubleFromConfig(config, CONFIG_MAX_DUTYCYCLE);
85 isEquateMaxToHundred = getBooleanFromConfig(config, CONFIG_EQUATE_MAX_TO_HUNDRED);
86 deadManSwitchTimeoutMs = getOptionalDoubleFromConfig(config, CONFIG_DEAD_MAN_SWITCH);
89 dutyCycleItem = itemRegistry.getItem(dutycycleItemName);
90 } catch (ItemNotFoundException e) {
91 throw new IllegalArgumentException("Dutycycle item not found: " + dutycycleItemName, e);
94 eventFilter = event -> event.getTopic().equals("openhab/items/" + dutycycleItemName + "/state");
98 public void setCallback(ModuleHandlerCallback callback) {
99 super.setCallback(callback);
101 double periodSec = getDoubleFromConfig(module.getConfiguration(), CONFIG_PERIOD);
102 stateMachine = new StateMachine(getCallback().getScheduler(), this::setOutput, (long) (periodSec * 1000));
104 eventSubscriberRegistration = bundleContext.registerService(EventSubscriber.class.getName(), this, null);
107 private double getDoubleFromConfig(Configuration config, String key) {
108 return ((BigDecimal) Objects.requireNonNull(config.get(key), key + " is not set")).doubleValue();
111 private Optional<Double> getOptionalDoubleFromConfig(Configuration config, String key) {
112 Object o = config.get(key);
114 if (o instanceof BigDecimal) {
115 return Optional.of(((BigDecimal) o).doubleValue());
118 return Optional.empty();
121 private boolean getBooleanFromConfig(Configuration config, String key) {
122 return ((Boolean) config.get(key)).booleanValue();
126 public void receive(Event event) {
127 if (!(event instanceof ItemStateEvent)) {
131 ItemStateEvent changedEvent = (ItemStateEvent) event;
132 synchronized (this) {
134 double newDutycycle = getDutyCycleValueInPercent(changedEvent.getItemState());
135 double newDutycycleBeforeLimit = newDutycycle;
137 restartDeadManSwitchTimer();
139 // set duty cycle to 0% if it is 0% or it is smaller than min duty cycle and equateMinToZero is true
140 // set duty cycle to min duty cycle if it is smaller than min duty cycle
141 final double newDutyCycleFinal1 = newDutycycle;
142 newDutycycle = minDutyCycle.map(minDutycycle -> {
143 long dutycycleRounded1 = Math.round(newDutyCycleFinal1);
144 if (dutycycleRounded1 <= 0 || (dutycycleRounded1 <= minDutycycle && isEquateMinToZero)) {
147 return Math.max(minDutycycle, newDutyCycleFinal1);
149 }).orElse(newDutycycle);
151 // set duty cycle to 100% if it is 100% or it is larger then max duty cycle and equateMaxToHundred is
153 // set duty cycle to max duty cycle if it is larger then max duty cycle
154 final double newDutyCycleFinal2 = newDutycycle;
155 newDutycycle = maxDutyCycle.map(maxDutycycle -> {
156 long dutycycleRounded2 = Math.round(newDutyCycleFinal2);
157 if (dutycycleRounded2 >= 100 || (dutycycleRounded2 >= maxDutycycle && isEquateMaxToHundred)) {
160 return Math.min(maxDutycycle, newDutyCycleFinal2);
162 }).orElse(newDutycycle);
164 logger.debug("Received new duty cycle: {} {}", newDutycycleBeforeLimit,
165 newDutycycle != newDutycycleBeforeLimit ? "Limited to: " + newDutycycle : "");
167 StateMachine localStateMachine = stateMachine;
168 if (localStateMachine != null) {
169 localStateMachine.setDutycycle(newDutycycle);
171 logger.debug("Initialization not finished");
173 } catch (PWMException e) {
174 logger.warn("{}", e.getMessage());
179 private void restartDeadManSwitchTimer() {
180 ScheduledFuture<?> timer = deadMeanSwitchTimer;
185 deadManSwitchTimeoutMs.ifPresent(timeout -> {
186 deadMeanSwitchTimer = getCallback().getScheduler().schedule(this::activateDeadManSwitch,
187 timeout.longValue(), TimeUnit.MILLISECONDS);
191 private void activateDeadManSwitch() {
192 logger.warn("Dead-man switch activated. Disabling output");
194 StateMachine localStateMachine = stateMachine;
195 if (localStateMachine != null) {
196 localStateMachine.stop();
200 private void setOutput(boolean enable) {
201 getCallback().triggered(module, Collections.singletonMap(OUTPUT, OnOffType.from(enable)));
204 private TriggerHandlerCallback getCallback() {
205 ModuleHandlerCallback localCallback = callback;
206 if (localCallback != null && localCallback instanceof TriggerHandlerCallback) {
207 return (TriggerHandlerCallback) localCallback;
210 throw new IllegalStateException();
213 private double getDutyCycleValueInPercent(State state) throws PWMException {
214 if (state instanceof DecimalType) {
215 return ((DecimalType) state).doubleValue();
216 } else if (state instanceof StringType) {
218 return Integer.parseInt(state.toString());
219 } catch (NumberFormatException e) {
222 } else if (state instanceof UnDefType) {
223 throw new PWMException("Duty cycle item '" + dutyCycleItem.getName() + "' has no valid value");
225 throw new PWMException("Duty cycle item not of type DecimalType: " + state.getClass().getSimpleName());
229 public Set<String> getSubscribedEventTypes() {
230 return SUBSCRIBED_EVENT_TYPES;
234 public @Nullable EventFilter getEventFilter() {
239 public void dispose() {
240 ServiceRegistration<?> localEventSubscriberRegistration = eventSubscriberRegistration;
241 if (localEventSubscriberRegistration != null) {
242 localEventSubscriberRegistration.unregister();
245 StateMachine localStateMachine = stateMachine;
246 if (localStateMachine != null) {
247 localStateMachine.stop();