]> git.basschouten.com Git - openhab-addons.git/blob
7800dde387c9e1b525437c00e69ef2b70fbf21fb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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
14 package org.openhab.io.homekit.internal;
15
16 import static org.openhab.io.homekit.internal.HomekitCommandType.*;
17 import static org.openhab.io.homekit.internal.HomekitDimmerMode.*;
18
19 import java.util.Map;
20 import java.util.concurrent.ConcurrentHashMap;
21 import java.util.concurrent.ScheduledExecutorService;
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.core.common.ThreadPoolManager;
28 import org.openhab.core.items.Item;
29 import org.openhab.core.library.items.ColorItem;
30 import org.openhab.core.library.items.DimmerItem;
31 import org.openhab.core.library.types.DecimalType;
32 import org.openhab.core.library.types.HSBType;
33 import org.openhab.core.library.types.OnOffType;
34 import org.openhab.core.library.types.PercentType;
35 import org.openhab.core.types.State;
36 import org.openhab.core.types.UnDefType;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 /**
41  *
42  * Proxy class that can collect multiple commands for the same openHAB item and merge them to one command.
43  * e.g. Hue and Saturation update for Color Item
44  * 
45  * @author Eugen Freiter - Initial contribution
46  *
47  */
48 @NonNullByDefault
49 public class HomekitOHItemProxy {
50     private final Logger logger = LoggerFactory.getLogger(HomekitOHItemProxy.class);
51     private static final int DEFAULT_DELAY = 50; // in ms
52     private final Item item;
53     private final Map<HomekitCommandType, State> commandCache = new ConcurrentHashMap<>();
54     private final ScheduledExecutorService scheduler = ThreadPoolManager
55             .getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
56     private @NonNullByDefault({}) ScheduledFuture<?> future;
57     private HomekitDimmerMode dimmerMode = DIMMER_MODE_NORMAL;
58     // delay, how long wait for further commands. in ms.
59     private int delay = DEFAULT_DELAY;
60
61     public HomekitOHItemProxy(Item item) {
62         this.item = item;
63     }
64
65     public Item getItem() {
66         return item;
67     }
68
69     public void setDimmerMode(HomekitDimmerMode mode) {
70         dimmerMode = mode;
71     }
72
73     public void setDelay(int delay) {
74         this.delay = delay;
75     }
76
77     @SuppressWarnings("null")
78     private void sendCommand() {
79         if (!(item instanceof DimmerItem)) {
80             // currently supports only DimmerItem and ColorItem (which extends DimmerItem)
81             logger.debug("unexpected item type {}. Only DimmerItem and ColorItem are supported.", item);
82             return;
83         }
84         final OnOffType on = (OnOffType) commandCache.remove(ON_COMMAND);
85         final PercentType brightness = (PercentType) commandCache.remove(BRIGHTNESS_COMMAND);
86         final DecimalType hue = (DecimalType) commandCache.remove(HUE_COMMAND);
87         final PercentType saturation = (PercentType) commandCache.remove(SATURATION_COMMAND);
88         final @Nullable OnOffType currentOnState = ((DimmerItem) item).getStateAs(OnOffType.class);
89         if (on != null) {
90             // always sends OFF.
91             // sends ON only if
92             // - DIMMER_MODE_NONE is enabled OR
93             // - DIMMER_MODE_FILTER_BRIGHTNESS_100 is enabled OR
94             // - DIMMER_MODE_FILTER_ON_EXCEPT100 is not enabled and brightness is null or below 100
95             if ((on == OnOffType.OFF) || (dimmerMode == DIMMER_MODE_NORMAL)
96                     || (dimmerMode == DIMMER_MODE_FILTER_BRIGHTNESS_100)
97                     || ((dimmerMode == DIMMER_MODE_FILTER_ON_EXCEPT_BRIGHTNESS_100) && (currentOnState != OnOffType.ON)
98                             && ((brightness == null) || (brightness.intValue() == 100)))) {
99                 logger.trace("send OnOff command for item {} with value {}", item, on);
100                 ((DimmerItem) item).send(on);
101             }
102         }
103
104         // if hue or saturation present, send an HSBType state update. no filter applied for HUE & Saturation
105         if ((hue != null) || (saturation != null)) {
106             if (item instanceof ColorItem) {
107                 // logic for ColorItem = combine hue, saturation and brightness update to one command
108                 final HSBType currentState = item.getState() instanceof UnDefType ? HSBType.BLACK
109                         : (HSBType) item.getState();
110                 ((ColorItem) item).send(new HSBType(hue != null ? hue : currentState.getHue(),
111                         saturation != null ? saturation : currentState.getSaturation(),
112                         brightness != null ? brightness : currentState.getBrightness()));
113                 logger.trace("send HSB command for item {} with following values hue={} saturation={} brightness={}",
114                         item, hue, saturation, brightness);
115             }
116         } else if ((brightness != null) && (item instanceof DimmerItem)) {
117             // sends brightness:
118             // - DIMMER_MODE_NONE
119             // - DIMMER_MODE_FILTER_ON
120             // - other modes (DIMMER_MODE_FILTER_BRIGHTNESS_100 or DIMMER_MODE_FILTER_ON_EXCEPT_BRIGHTNESS_100) and
121             // <100%.
122             if ((dimmerMode == DIMMER_MODE_NORMAL) || (dimmerMode == DIMMER_MODE_FILTER_ON)
123                     || (brightness.intValue() < 100) || (currentOnState == OnOffType.ON)) {
124                 logger.trace("send Brightness command for item {} with value {}", item, brightness);
125                 ((DimmerItem) item).send(brightness);
126             }
127         }
128         commandCache.clear();
129     }
130
131     public synchronized void sendCommandProxy(HomekitCommandType commandType, State state) {
132         commandCache.put(commandType, state);
133         logger.trace("add command to command cache: item {}, command type {}, command state {}. cache state after: {}",
134                 this, commandType, state, commandCache);
135         // if cache has already HUE+SATURATION or BRIGHTNESS+ON then we don't expect any further relevant command
136         if (((item instanceof ColorItem) && commandCache.containsKey(HUE_COMMAND)
137                 && commandCache.containsKey(SATURATION_COMMAND))
138                 || (commandCache.containsKey(BRIGHTNESS_COMMAND) && commandCache.containsKey(ON_COMMAND))) {
139             if (future != null) {
140                 future.cancel(false);
141             }
142             sendCommand();
143             return;
144         }
145         // if timer is not already set, create a new one to ensure that the command command is send even if no follow up
146         // commands are received.
147         if (future == null || future.isDone()) {
148             future = scheduler.schedule(() -> {
149                 logger.trace("timer of {} ms is over, sending the command", delay);
150                 sendCommand();
151             }, delay, TimeUnit.MILLISECONDS);
152         }
153     }
154 }