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