]> git.basschouten.com Git - openhab-addons.git/blob
4f8394b62dcae3390c95a83856cc694060a15e11
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.accessories;
14
15 import static org.openhab.io.homekit.internal.HomekitCharacteristicType.ACTIVE_STATUS;
16 import static org.openhab.io.homekit.internal.HomekitCharacteristicType.INUSE_STATUS;
17 import static org.openhab.io.homekit.internal.HomekitCharacteristicType.REMAINING_DURATION;
18
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.concurrent.CompletableFuture;
23 import java.util.concurrent.Executors;
24 import java.util.concurrent.ScheduledExecutorService;
25 import java.util.concurrent.ScheduledFuture;
26 import java.util.concurrent.TimeUnit;
27
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.openhab.core.items.GenericItem;
30 import org.openhab.core.library.items.SwitchItem;
31 import org.openhab.core.library.types.DecimalType;
32 import org.openhab.core.library.types.OnOffType;
33 import org.openhab.core.library.types.OpenClosedType;
34 import org.openhab.core.types.RefreshType;
35 import org.openhab.io.homekit.internal.HomekitAccessoryUpdater;
36 import org.openhab.io.homekit.internal.HomekitCharacteristicType;
37 import org.openhab.io.homekit.internal.HomekitSettings;
38 import org.openhab.io.homekit.internal.HomekitTaggedItem;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
41
42 import io.github.hapjava.accessories.ValveAccessory;
43 import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback;
44 import io.github.hapjava.characteristics.impl.common.ActiveEnum;
45 import io.github.hapjava.characteristics.impl.common.InUseEnum;
46 import io.github.hapjava.characteristics.impl.valve.RemainingDurationCharacteristic;
47 import io.github.hapjava.characteristics.impl.valve.ValveTypeEnum;
48 import io.github.hapjava.services.impl.ValveService;
49
50 /**
51  *
52  * @author Tim Harper - Initial contribution
53  * @author Eugen Freiter - timer implementation
54  */
55 public class HomekitValveImpl extends AbstractHomekitAccessoryImpl implements ValveAccessory {
56     private final Logger logger = LoggerFactory.getLogger(HomekitValveImpl.class);
57     private static final String CONFIG_VALVE_TYPE = "homekitValveType";
58     public static final String CONFIG_DEFAULT_DURATION = "homekitDefaultDuration";
59     private static final String CONFIG_TIMER = "homekitTimer";
60
61     private static final Map<String, ValveTypeEnum> CONFIG_VALVE_TYPE_MAPPING = new HashMap<String, ValveTypeEnum>() {
62         {
63             put("GENERIC", ValveTypeEnum.GENERIC);
64             put("IRRIGATION", ValveTypeEnum.IRRIGATION);
65             put("SHOWER", ValveTypeEnum.SHOWER);
66             put("FAUCET", ValveTypeEnum.WATER_FAUCET);
67         }
68     };
69     private final BooleanItemReader inUseReader;
70     private final BooleanItemReader activeReader;
71     private final ScheduledExecutorService timerService = Executors.newSingleThreadScheduledExecutor();
72     private ScheduledFuture<?> valveTimer;
73     private final boolean homekitTimer;
74
75     public HomekitValveImpl(HomekitTaggedItem taggedItem, List<HomekitTaggedItem> mandatoryCharacteristics,
76             HomekitAccessoryUpdater updater, HomekitSettings settings) throws IncompleteAccessoryException {
77         super(taggedItem, mandatoryCharacteristics, updater, settings);
78         inUseReader = createBooleanReader(INUSE_STATUS, OnOffType.ON, OpenClosedType.OPEN);
79         activeReader = createBooleanReader(ACTIVE_STATUS, OnOffType.ON, OpenClosedType.OPEN);
80         ValveService service = new ValveService(this);
81         getServices().add(service);
82         final String timerConfig = getAccessoryConfiguration(CONFIG_TIMER, "");
83         homekitTimer = timerConfig.equalsIgnoreCase("yes") || timerConfig.equalsIgnoreCase("true");
84         if (homekitTimer) {
85             addRemainingDurationCharacteristic(taggedItem, updater, service);
86         }
87     }
88
89     private void addRemainingDurationCharacteristic(HomekitTaggedItem taggedItem, HomekitAccessoryUpdater updater,
90             ValveService service) {
91         logger.trace("addRemainingDurationCharacteristic for {}", taggedItem);
92         service.addOptionalCharacteristic(new RemainingDurationCharacteristic(() -> {
93             int remainingTime = 0;
94             ScheduledFuture<?> future = valveTimer;
95             if (future != null && !future.isDone()) {
96                 remainingTime = Math.toIntExact(future.getDelay(TimeUnit.SECONDS));
97             }
98             return CompletableFuture.completedFuture(remainingTime);
99         }, HomekitCharacteristicFactory.getSubscriber(taggedItem, REMAINING_DURATION, updater),
100                 HomekitCharacteristicFactory.getUnsubscriber(taggedItem, REMAINING_DURATION, updater)));
101     }
102
103     /**
104      * return duration set by home app at corresponding OH items. if ot set, then return the default duration from
105      * configuration.
106      * 
107      * @return duraion
108      */
109     private int getDuration() {
110         int duration = 0;
111         final @Nullable DecimalType durationState = getStateAs(HomekitCharacteristicType.DURATION, DecimalType.class);
112         if (durationState != null) {
113             duration = durationState.intValue();
114         }
115         return duration;
116     }
117
118     private void startTimer() {
119         int duration = getDuration();
120         logger.trace("start timer for duration {}", duration);
121         if (duration > 0) {
122             stopTimer();
123             valveTimer = timerService.schedule(() -> {
124                 logger.trace("valve timer is over. switching off the valve");
125                 switchOffValve();
126                 // let home app refresh the remaining duration, which is 0
127                 ((GenericItem) getRootAccessory().getItem()).send(RefreshType.REFRESH);
128             }, duration, TimeUnit.SECONDS);
129             logger.trace("started valve timer for {} seconds.", duration);
130         } else {
131             logger.debug("valve timer not started as duration = 0");
132         }
133     }
134
135     private void stopTimer() {
136         ScheduledFuture<?> future = valveTimer;
137         if (future != null && !future.isDone()) {
138             future.cancel(true);
139         }
140     }
141
142     @Override
143     public CompletableFuture<ActiveEnum> getValveActive() {
144         return CompletableFuture
145                 .completedFuture(this.activeReader.getValue() ? ActiveEnum.ACTIVE : ActiveEnum.INACTIVE);
146     }
147
148     @Override
149     public CompletableFuture<Void> setValveActive(ActiveEnum state) {
150         getItem(ACTIVE_STATUS, SwitchItem.class).ifPresent(item -> {
151             item.send(OnOffType.from(state == ActiveEnum.ACTIVE));
152             if (homekitTimer) {
153                 if ((state == ActiveEnum.ACTIVE)) {
154                     startTimer();
155                 } else {
156                     stopTimer();
157                 }
158                 // let home app refresh the remaining duration
159                 ((GenericItem) getRootAccessory().getItem()).send(RefreshType.REFRESH);
160             }
161         });
162         return CompletableFuture.completedFuture(null);
163     }
164
165     private void switchOffValve() {
166         getItem(ACTIVE_STATUS, SwitchItem.class).ifPresent(item -> item.send(OnOffType.OFF));
167     }
168
169     @Override
170     public void subscribeValveActive(HomekitCharacteristicChangeCallback callback) {
171         subscribe(ACTIVE_STATUS, callback);
172     }
173
174     @Override
175     public void unsubscribeValveActive() {
176         unsubscribe(ACTIVE_STATUS);
177     }
178
179     @Override
180     public CompletableFuture<InUseEnum> getValveInUse() {
181         return CompletableFuture.completedFuture(inUseReader.getValue() ? InUseEnum.IN_USE : InUseEnum.NOT_IN_USE);
182     }
183
184     @Override
185     public void subscribeValveInUse(HomekitCharacteristicChangeCallback callback) {
186         subscribe(INUSE_STATUS, callback);
187     }
188
189     @Override
190     public void unsubscribeValveInUse() {
191         unsubscribe(INUSE_STATUS);
192     }
193
194     @Override
195     public CompletableFuture<ValveTypeEnum> getValveType() {
196         final String valveType = getAccessoryConfiguration(CONFIG_VALVE_TYPE, "GENERIC");
197         ValveTypeEnum type = CONFIG_VALVE_TYPE_MAPPING.get(valveType.toUpperCase());
198         return CompletableFuture.completedFuture(type != null ? type : ValveTypeEnum.GENERIC);
199     }
200
201     @Override
202     public void subscribeValveType(HomekitCharacteristicChangeCallback callback) {
203         // nothing changes here
204     }
205
206     @Override
207     public void unsubscribeValveType() {
208         // nothing changes here
209     }
210 }