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