]> git.basschouten.com Git - openhab-addons.git/blob
937b33abf7df41f24e720af959fdd576db1d0e2c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.automation.pwm.internal.handler;
14
15 import static org.openhab.automation.pwm.internal.PWMConstants.*;
16
17 import java.math.BigDecimal;
18 import java.util.Collections;
19 import java.util.Objects;
20 import java.util.Optional;
21 import java.util.Set;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
24
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;
50
51 /**
52  * Represents a Trigger module in the rules engine.
53  *
54  * @author Fabian Wolter - Initial Contribution
55  */
56 @NonNullByDefault
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;
72
73     public PWMTriggerHandler(Trigger module, ItemRegistry itemRegistry, BundleContext bundleContext) {
74         super(module);
75         this.bundleContext = bundleContext;
76
77         Configuration config = module.getConfiguration();
78
79         String dutycycleItemName = (String) Objects.requireNonNull(config.get(CONFIG_DUTY_CYCLE_ITEM),
80                 "DutyCycle item is not set");
81
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);
87
88         try {
89             dutyCycleItem = itemRegistry.getItem(dutycycleItemName);
90         } catch (ItemNotFoundException e) {
91             throw new IllegalArgumentException("Dutycycle item not found: " + dutycycleItemName, e);
92         }
93
94         eventFilter = event -> event.getTopic().equals("openhab/items/" + dutycycleItemName + "/state");
95     }
96
97     @Override
98     public void setCallback(ModuleHandlerCallback callback) {
99         super.setCallback(callback);
100
101         double periodSec = getDoubleFromConfig(module.getConfiguration(), CONFIG_PERIOD);
102         stateMachine = new StateMachine(getCallback().getScheduler(), this::setOutput, (long) (periodSec * 1000));
103
104         eventSubscriberRegistration = bundleContext.registerService(EventSubscriber.class.getName(), this, null);
105     }
106
107     private double getDoubleFromConfig(Configuration config, String key) {
108         return ((BigDecimal) Objects.requireNonNull(config.get(key), key + " is not set")).doubleValue();
109     }
110
111     private Optional<Double> getOptionalDoubleFromConfig(Configuration config, String key) {
112         Object o = config.get(key);
113
114         if (o instanceof BigDecimal) {
115             return Optional.of(((BigDecimal) o).doubleValue());
116         }
117
118         return Optional.empty();
119     }
120
121     private boolean getBooleanFromConfig(Configuration config, String key) {
122         return ((Boolean) config.get(key)).booleanValue();
123     }
124
125     @Override
126     public void receive(Event event) {
127         if (!(event instanceof ItemStateEvent)) {
128             return;
129         }
130
131         ItemStateEvent changedEvent = (ItemStateEvent) event;
132         synchronized (this) {
133             try {
134                 double newDutycycle = getDutyCycleValueInPercent(changedEvent.getItemState());
135                 double newDutycycleBeforeLimit = newDutycycle;
136
137                 restartDeadManSwitchTimer();
138
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)) {
145                         return 0d;
146                     } else {
147                         return Math.max(minDutycycle, newDutyCycleFinal1);
148                     }
149                 }).orElse(newDutycycle);
150
151                 // set duty cycle to 100% if it is 100% or it is larger then max duty cycle and equateMaxToHundred is
152                 // true
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)) {
158                         return 100d;
159                     } else {
160                         return Math.min(maxDutycycle, newDutyCycleFinal2);
161                     }
162                 }).orElse(newDutycycle);
163
164                 logger.debug("Received new duty cycle: {} {}", newDutycycleBeforeLimit,
165                         newDutycycle != newDutycycleBeforeLimit ? "Limited to: " + newDutycycle : "");
166
167                 StateMachine localStateMachine = stateMachine;
168                 if (localStateMachine != null) {
169                     localStateMachine.setDutycycle(newDutycycle);
170                 } else {
171                     logger.debug("Initialization not finished");
172                 }
173             } catch (PWMException e) {
174                 logger.warn("{}", e.getMessage());
175             }
176         }
177     }
178
179     private void restartDeadManSwitchTimer() {
180         ScheduledFuture<?> timer = deadMeanSwitchTimer;
181         if (timer != null) {
182             timer.cancel(true);
183         }
184
185         deadManSwitchTimeoutMs.ifPresent(timeout -> {
186             deadMeanSwitchTimer = getCallback().getScheduler().schedule(this::activateDeadManSwitch,
187                     timeout.longValue(), TimeUnit.MILLISECONDS);
188         });
189     }
190
191     private void activateDeadManSwitch() {
192         logger.warn("Dead-man switch activated. Disabling output");
193
194         StateMachine localStateMachine = stateMachine;
195         if (localStateMachine != null) {
196             localStateMachine.stop();
197         }
198     }
199
200     private void setOutput(boolean enable) {
201         getCallback().triggered(module, Collections.singletonMap(OUTPUT, OnOffType.from(enable)));
202     }
203
204     private TriggerHandlerCallback getCallback() {
205         ModuleHandlerCallback localCallback = callback;
206         if (localCallback != null && localCallback instanceof TriggerHandlerCallback) {
207             return (TriggerHandlerCallback) localCallback;
208         }
209
210         throw new IllegalStateException();
211     }
212
213     private double getDutyCycleValueInPercent(State state) throws PWMException {
214         if (state instanceof DecimalType) {
215             return ((DecimalType) state).doubleValue();
216         } else if (state instanceof StringType) {
217             try {
218                 return Integer.parseInt(state.toString());
219             } catch (NumberFormatException e) {
220                 // nothing
221             }
222         } else if (state instanceof UnDefType) {
223             throw new PWMException("Duty cycle item '" + dutyCycleItem.getName() + "' has no valid value");
224         }
225         throw new PWMException("Duty cycle item not of type DecimalType: " + state.getClass().getSimpleName());
226     }
227
228     @Override
229     public Set<String> getSubscribedEventTypes() {
230         return SUBSCRIBED_EVENT_TYPES;
231     }
232
233     @Override
234     public @Nullable EventFilter getEventFilter() {
235         return eventFilter;
236     }
237
238     @Override
239     public void dispose() {
240         ServiceRegistration<?> localEventSubscriberRegistration = eventSubscriberRegistration;
241         if (localEventSubscriberRegistration != null) {
242             localEventSubscriberRegistration.unregister();
243         }
244
245         StateMachine localStateMachine = stateMachine;
246         if (localStateMachine != null) {
247             localStateMachine.stop();
248         }
249
250         super.dispose();
251     }
252 }