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