]> git.basschouten.com Git - openhab-addons.git/blob
228de13211e489cb85e888a0711b45c4af1933d4
[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 java.lang.reflect.InvocationTargetException;
16 import java.math.BigDecimal;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.HashMap;
20 import java.util.List;
21 import java.util.Map;
22 import java.util.Optional;
23 import java.util.concurrent.CompletableFuture;
24 import java.util.concurrent.ExecutionException;
25
26 import javax.json.Json;
27 import javax.json.JsonObjectBuilder;
28
29 import org.eclipse.jdt.annotation.NonNullByDefault;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.openhab.core.items.GenericItem;
32 import org.openhab.core.items.Item;
33 import org.openhab.core.library.types.OnOffType;
34 import org.openhab.core.library.types.OpenClosedType;
35 import org.openhab.core.types.State;
36 import org.openhab.io.homekit.internal.HomekitAccessoryUpdater;
37 import org.openhab.io.homekit.internal.HomekitCharacteristicType;
38 import org.openhab.io.homekit.internal.HomekitException;
39 import org.openhab.io.homekit.internal.HomekitSettings;
40 import org.openhab.io.homekit.internal.HomekitTaggedItem;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import io.github.hapjava.accessories.HomekitAccessory;
45 import io.github.hapjava.characteristics.Characteristic;
46 import io.github.hapjava.characteristics.CharacteristicEnum;
47 import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback;
48 import io.github.hapjava.characteristics.impl.accessoryinformation.FirmwareRevisionCharacteristic;
49 import io.github.hapjava.characteristics.impl.accessoryinformation.HardwareRevisionCharacteristic;
50 import io.github.hapjava.characteristics.impl.accessoryinformation.IdentifyCharacteristic;
51 import io.github.hapjava.characteristics.impl.accessoryinformation.ManufacturerCharacteristic;
52 import io.github.hapjava.characteristics.impl.accessoryinformation.ModelCharacteristic;
53 import io.github.hapjava.characteristics.impl.accessoryinformation.SerialNumberCharacteristic;
54 import io.github.hapjava.characteristics.impl.base.BaseCharacteristic;
55 import io.github.hapjava.characteristics.impl.common.NameCharacteristic;
56 import io.github.hapjava.services.Service;
57 import io.github.hapjava.services.impl.AccessoryInformationService;
58
59 /**
60  * Abstract class for Homekit Accessory implementations, this provides the
61  * accessory metadata using information from the underlying Item.
62  *
63  * @author Andy Lintner - Initial contribution
64  */
65 public abstract class AbstractHomekitAccessoryImpl implements HomekitAccessory {
66     private final Logger logger = LoggerFactory.getLogger(AbstractHomekitAccessoryImpl.class);
67     private final List<HomekitTaggedItem> characteristics;
68     private final HomekitTaggedItem accessory;
69     private final HomekitAccessoryUpdater updater;
70     private final HomekitSettings settings;
71     private final List<Service> services;
72     private final Map<Class<? extends Characteristic>, Characteristic> rawCharacteristics;
73     private boolean isLinkedService = false;
74
75     public AbstractHomekitAccessoryImpl(HomekitTaggedItem accessory, List<HomekitTaggedItem> characteristics,
76             HomekitAccessoryUpdater updater, HomekitSettings settings) {
77         this.characteristics = characteristics;
78         this.accessory = accessory;
79         this.updater = updater;
80         this.services = new ArrayList<>();
81         this.settings = settings;
82         this.rawCharacteristics = new HashMap<>();
83         // create raw characteristics for mandatory characteristics
84         characteristics.forEach(c -> {
85             var rawCharacteristic = HomekitCharacteristicFactory.createNullableCharacteristic(c, updater);
86             // not all mandatory characteristics are creatable via HomekitCharacteristicFactory (yet)
87             if (rawCharacteristic != null) {
88                 rawCharacteristics.put(rawCharacteristic.getClass(), rawCharacteristic);
89             }
90         });
91     }
92
93     /**
94      * Gives an accessory an opportunity to populate additional characteristics after all optional
95      * charactericteristics have been added.
96      * 
97      * @throws HomekitException
98      */
99     public void init() throws HomekitException {
100         // initialize the AccessoryInformation Service with defaults if not specified
101         if (!rawCharacteristics.containsKey(NameCharacteristic.class)) {
102             rawCharacteristics.put(NameCharacteristic.class, new NameCharacteristic(() -> {
103                 return CompletableFuture.completedFuture(accessory.getItem().getLabel());
104             }));
105         }
106
107         if (!isLinkedService()) {
108             if (!rawCharacteristics.containsKey(IdentifyCharacteristic.class)) {
109                 rawCharacteristics.put(IdentifyCharacteristic.class, new IdentifyCharacteristic(v -> {
110                 }));
111             }
112             if (!rawCharacteristics.containsKey(ManufacturerCharacteristic.class)) {
113                 rawCharacteristics.put(ManufacturerCharacteristic.class, new ManufacturerCharacteristic(() -> {
114                     return CompletableFuture.completedFuture("none");
115                 }));
116             }
117             if (!rawCharacteristics.containsKey(ModelCharacteristic.class)) {
118                 rawCharacteristics.put(ModelCharacteristic.class, new ModelCharacteristic(() -> {
119                     return CompletableFuture.completedFuture("none");
120                 }));
121             }
122             if (!rawCharacteristics.containsKey(SerialNumberCharacteristic.class)) {
123                 rawCharacteristics.put(SerialNumberCharacteristic.class, new SerialNumberCharacteristic(() -> {
124                     return CompletableFuture.completedFuture(accessory.getItem().getName());
125                 }));
126             }
127             if (!rawCharacteristics.containsKey(FirmwareRevisionCharacteristic.class)) {
128                 rawCharacteristics.put(FirmwareRevisionCharacteristic.class, new FirmwareRevisionCharacteristic(() -> {
129                     return CompletableFuture.completedFuture("none");
130                 }));
131             }
132
133             var service = new AccessoryInformationService(getCharacteristic(IdentifyCharacteristic.class).get(),
134                     getCharacteristic(ManufacturerCharacteristic.class).get(),
135                     getCharacteristic(ModelCharacteristic.class).get(),
136                     getCharacteristic(NameCharacteristic.class).get(),
137                     getCharacteristic(SerialNumberCharacteristic.class).get(),
138                     getCharacteristic(FirmwareRevisionCharacteristic.class).get());
139
140             getCharacteristic(HardwareRevisionCharacteristic.class)
141                     .ifPresent(c -> service.addOptionalCharacteristic(c));
142
143             // make sure this is the first service
144             services.add(0, service);
145         }
146     }
147
148     /**
149      * @param parentAccessory The primary service to link to.
150      * @return If this accessory should be nested as a linked service below a primary service,
151      *         rather than as a sibling.
152      */
153     public boolean isLinkable(HomekitAccessory parentAccessory) {
154         return false;
155     }
156
157     /**
158      * Sets if this accessory is being used as a linked service.
159      */
160     public void setIsLinkedService(boolean value) {
161         isLinkedService = value;
162     }
163
164     /**
165      * @return If this accessory is being used as a linked service.
166      */
167     public boolean isLinkedService() {
168         return isLinkedService;
169     }
170
171     /**
172      * @return If this accessory is only valid as a linked service, not as a standalone accessory.
173      */
174     public boolean isLinkedServiceOnly() {
175         return false;
176     }
177
178     @NonNullByDefault
179     public Optional<HomekitTaggedItem> getCharacteristic(HomekitCharacteristicType type) {
180         return characteristics.stream().filter(c -> c.getCharacteristicType() == type).findAny();
181     }
182
183     @Override
184     public int getId() {
185         return accessory.getId();
186     }
187
188     @Override
189     public CompletableFuture<String> getName() {
190         return getCharacteristic(NameCharacteristic.class).get().getValue();
191     }
192
193     @Override
194     public CompletableFuture<String> getManufacturer() {
195         return getCharacteristic(ManufacturerCharacteristic.class).get().getValue();
196     }
197
198     @Override
199     public CompletableFuture<String> getModel() {
200         return getCharacteristic(ModelCharacteristic.class).get().getValue();
201     }
202
203     @Override
204     public CompletableFuture<String> getSerialNumber() {
205         return getCharacteristic(SerialNumberCharacteristic.class).get().getValue();
206     }
207
208     @Override
209     public CompletableFuture<String> getFirmwareRevision() {
210         return getCharacteristic(FirmwareRevisionCharacteristic.class).get().getValue();
211     }
212
213     @Override
214     public void identify() {
215         try {
216             getCharacteristic(IdentifyCharacteristic.class).get().setValue(true);
217         } catch (Exception e) {
218             // ignore
219         }
220     }
221
222     public HomekitTaggedItem getRootAccessory() {
223         return accessory;
224     }
225
226     @Override
227     public Collection<Service> getServices() {
228         return this.services;
229     }
230
231     protected HomekitAccessoryUpdater getUpdater() {
232         return updater;
233     }
234
235     protected HomekitSettings getSettings() {
236         return settings;
237     }
238
239     @NonNullByDefault
240     protected void subscribe(HomekitCharacteristicType characteristicType,
241             HomekitCharacteristicChangeCallback callback) {
242         final Optional<HomekitTaggedItem> characteristic = getCharacteristic(characteristicType);
243         if (characteristic.isPresent()) {
244             getUpdater().subscribe((GenericItem) characteristic.get().getItem(), characteristicType.getTag(), callback);
245         } else {
246             logger.warn("Missing mandatory characteristic {}", characteristicType);
247         }
248     }
249
250     @NonNullByDefault
251     protected void unsubscribe(HomekitCharacteristicType characteristicType) {
252         final Optional<HomekitTaggedItem> characteristic = getCharacteristic(characteristicType);
253         if (characteristic.isPresent()) {
254             getUpdater().unsubscribe((GenericItem) characteristic.get().getItem(), characteristicType.getTag());
255         } else {
256             logger.warn("Missing mandatory characteristic {}", characteristicType);
257         }
258     }
259
260     protected @Nullable State getState(HomekitCharacteristicType characteristic) {
261         final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
262         if (taggedItem.isPresent()) {
263             return taggedItem.get().getItem().getState();
264         }
265         logger.debug("State for characteristic {} at accessory {} cannot be retrieved.", characteristic,
266                 accessory.getName());
267         return null;
268     }
269
270     protected @Nullable <T extends State> T getStateAs(HomekitCharacteristicType characteristic, Class<T> type) {
271         final State state = getState(characteristic);
272         if (state != null) {
273             return state.as(type);
274         }
275         return null;
276     }
277
278     protected @Nullable Double getStateAsTemperature(HomekitCharacteristicType characteristic) {
279         return HomekitCharacteristicFactory.stateAsTemperature(getState(characteristic));
280     }
281
282     @NonNullByDefault
283     protected <T extends Item> Optional<T> getItem(HomekitCharacteristicType characteristic, Class<T> type) {
284         final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
285         if (taggedItem.isPresent()) {
286             final Item item = taggedItem.get().getItem();
287             if (type.isInstance(item)) {
288                 return Optional.of((T) item);
289             } else {
290                 logger.warn("Unsupported item type for characteristic {} at accessory {}. Expected {}, got {}",
291                         characteristic, accessory.getItem().getName(), type, taggedItem.get().getItem().getClass());
292             }
293         } else {
294             logger.warn("Mandatory characteristic {} not found at accessory {}. ", characteristic,
295                     accessory.getItem().getName());
296         }
297         return Optional.empty();
298     }
299
300     /**
301      * return configuration attached to the root accessory, e.g. groupItem.
302      * Note: result will be casted to the type of the default value.
303      * The type for number is BigDecimal.
304      *
305      * @param key configuration key
306      * @param defaultValue default value
307      * @param <T> expected type
308      * @return configuration value
309      */
310     @NonNullByDefault
311     protected <T> T getAccessoryConfiguration(String key, T defaultValue) {
312         return accessory.getConfiguration(key, defaultValue);
313     }
314
315     /**
316      * return configuration attached to the root accessory, e.g. groupItem.
317      *
318      * @param key configuration key
319      * @param defaultValue default value
320      * @return configuration value
321      */
322     @NonNullByDefault
323     protected boolean getAccessoryConfigurationAsBoolean(String key, boolean defaultValue) {
324         return accessory.getConfigurationAsBoolean(key, defaultValue);
325     }
326
327     /**
328      * return configuration of the characteristic item, e.g. currentTemperature.
329      * Note: result will be casted to the type of the default value.
330      * The type for number is BigDecimal.
331      *
332      * @param characteristicType characteristic type
333      * @param key configuration key
334      * @param defaultValue default value
335      * @param <T> expected type
336      * @return configuration value
337      */
338     @NonNullByDefault
339     protected <T> T getAccessoryConfiguration(HomekitCharacteristicType characteristicType, String key,
340             T defaultValue) {
341         return getCharacteristic(characteristicType)
342                 .map(homekitTaggedItem -> homekitTaggedItem.getConfiguration(key, defaultValue)).orElse(defaultValue);
343     }
344
345     @NonNullByDefault
346     protected <T extends Enum<T> & CharacteristicEnum> Map<T, String> createMapping(
347             HomekitCharacteristicType characteristicType, Class<T> klazz) {
348         return createMapping(characteristicType, klazz, null, false);
349     }
350
351     @NonNullByDefault
352     protected <T extends Enum<T> & CharacteristicEnum> Map<T, String> createMapping(
353             HomekitCharacteristicType characteristicType, Class<T> klazz, boolean inverted) {
354         return createMapping(characteristicType, klazz, null, inverted);
355     }
356
357     @NonNullByDefault
358     protected <T extends Enum<T> & CharacteristicEnum> Map<T, String> createMapping(
359             HomekitCharacteristicType characteristicType, Class<T> klazz, @Nullable List<T> customEnumList) {
360         return createMapping(characteristicType, klazz, customEnumList, false);
361     }
362
363     /**
364      * create mapping with values from item configuration
365      * 
366      * @param characteristicType to identify item; must be present
367      * @param customEnumList list to store custom state enumeration
368      * @param inverted if ON/OFF and OPEN/CLOSED should be inverted by default (inverted on the item will double-invert)
369      * @return mapping of enum values to custom string values
370      */
371     @NonNullByDefault
372     protected <T extends Enum<T> & CharacteristicEnum> Map<T, String> createMapping(
373             HomekitCharacteristicType characteristicType, Class<T> klazz, @Nullable List<T> customEnumList,
374             boolean inverted) {
375         HomekitTaggedItem item = getCharacteristic(characteristicType).get();
376         return HomekitCharacteristicFactory.createMapping(item, klazz, customEnumList, inverted);
377     }
378
379     /**
380      * takes item state as value and retrieves the key for that value from mapping.
381      * e.g. used to map StringItem value to HomeKit Enum
382      *
383      * @param characteristicType characteristicType to identify item
384      * @param mapping mapping
385      * @param defaultValue default value if nothing found in mapping
386      * @param <T> type of the result derived from
387      * @return key for the value
388      */
389     @NonNullByDefault
390     public <T> T getKeyFromMapping(HomekitCharacteristicType characteristicType, Map<T, String> mapping,
391             T defaultValue) {
392         final Optional<HomekitTaggedItem> c = getCharacteristic(characteristicType);
393         if (c.isPresent()) {
394             return HomekitCharacteristicFactory.getKeyFromMapping(c.get(), mapping, defaultValue);
395         }
396         return defaultValue;
397     }
398
399     @NonNullByDefault
400     protected void addCharacteristic(HomekitTaggedItem item, Characteristic characteristic)
401             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
402         characteristics.add(item);
403         addCharacteristic(characteristic);
404     }
405
406     /**
407      * If the primary service does not yet exist, it won't be added to it. It's the resposibility
408      * of the caller to add characteristics when the primary service is created.
409      *
410      * @param characteristic
411      * @throws NoSuchMethodException
412      * @throws IllegalAccessException
413      * @throws InvocationTargetException
414      */
415     @NonNullByDefault
416     public void addCharacteristic(Characteristic characteristic)
417             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
418         if (rawCharacteristics.containsKey(characteristic.getClass())) {
419             logger.warn("Accessory {} already has a characteristic of type {}; ignoring additional definition.",
420                     accessory.getName(), characteristic.getClass().getSimpleName());
421             return;
422         }
423         rawCharacteristics.put(characteristic.getClass(), characteristic);
424         var service = getPrimaryService();
425         if (service != null) {
426             // find the corresponding add method at service and call it.
427             service.getClass().getMethod("addOptionalCharacteristic", characteristic.getClass()).invoke(service,
428                     characteristic);
429         }
430     }
431
432     /**
433      * Takes the NameCharacteristic that normally exists on the AccessoryInformationService,
434      * and puts it on the primary service.
435      */
436     public void promoteNameCharacteristic() {
437         var characteristic = getCharacteristic(NameCharacteristic.class);
438         if (!characteristic.isPresent()) {
439             return;
440         }
441
442         var service = getPrimaryService();
443         if (service != null) {
444             try {
445                 // find the corresponding add method at service and call it.
446                 service.getClass().getMethod("addOptionalCharacteristic", NameCharacteristic.class).invoke(service,
447                         characteristic.get());
448             } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
449                 // This should never happen; all services should support NameCharacteristic as an optional
450                 // Characteristic.
451                 // If HAP-Java defined a service that doesn't support addOptionalCharacteristic(NameCharacteristic),
452                 // Then it's a bug there, and we're just going to ignore the exception here.
453             }
454         }
455     }
456
457     @NonNullByDefault
458     public <T> Optional<T> getCharacteristic(Class<? extends T> klazz) {
459         return Optional.ofNullable((T) rawCharacteristics.get(klazz));
460     }
461
462     /**
463      * create boolean reader with ON state mapped to trueOnOffValue or trueOpenClosedValue depending of item type
464      *
465      * @param characteristicType characteristic id
466      * @param trueOnOffValue ON value for switch
467      * @param trueOpenClosedValue ON value for contact
468      * @return boolean read
469      * @throws IncompleteAccessoryException
470      */
471     @NonNullByDefault
472     protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType,
473             OnOffType trueOnOffValue, OpenClosedType trueOpenClosedValue) throws IncompleteAccessoryException {
474         return new BooleanItemReader(
475                 getItem(characteristicType, GenericItem.class)
476                         .orElseThrow(() -> new IncompleteAccessoryException(characteristicType)),
477                 trueOnOffValue, trueOpenClosedValue);
478     }
479
480     /**
481      * create boolean reader for a number item with ON state mapped to the value of the
482      * item being above a given threshold
483      *
484      * @param characteristicType characteristic id
485      * @param trueThreshold threshold for true of number item
486      * @param invertThreshold result is true if item is less than threshold, instead of more
487      * @return boolean read
488      * @throws IncompleteAccessoryException
489      */
490     @NonNullByDefault
491     protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType,
492             BigDecimal trueThreshold, boolean invertThreshold) throws IncompleteAccessoryException {
493         final HomekitTaggedItem taggedItem = getCharacteristic(characteristicType)
494                 .orElseThrow(() -> new IncompleteAccessoryException(characteristicType));
495         return new BooleanItemReader(taggedItem.getItem(), OnOffType.from(!taggedItem.isInverted()),
496                 taggedItem.isInverted() ? OpenClosedType.CLOSED : OpenClosedType.OPEN, trueThreshold, invertThreshold);
497     }
498
499     /**
500      * create boolean reader with default ON/OFF mapping considering inverted flag
501      *
502      * @param characteristicType characteristic id
503      * @return boolean reader
504      * @throws IncompleteAccessoryException
505      */
506     @NonNullByDefault
507     protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType)
508             throws IncompleteAccessoryException {
509         final HomekitTaggedItem taggedItem = getCharacteristic(characteristicType)
510                 .orElseThrow(() -> new IncompleteAccessoryException(characteristicType));
511         return new BooleanItemReader(taggedItem.getItem(), OnOffType.from(!taggedItem.isInverted()),
512                 taggedItem.isInverted() ? OpenClosedType.CLOSED : OpenClosedType.OPEN);
513     }
514
515     /**
516      * Calculates a string as json of the configuration for this accessory, suitable for seeing
517      * if the structure has changed, and building a dummy accessory for it. It is _not_ suitable
518      * for actual publishing to by HAP-Java to iOS devices, since all the IIDs will be set to 0.
519      * The IIDs will get replaced by actual values by HAP-Java inside of DummyHomekitCharacteristic.
520      */
521     public String toJson() {
522         var builder = Json.createArrayBuilder();
523         getServices().forEach(s -> {
524             builder.add(serviceToJson(s));
525         });
526         return builder.build().toString();
527     }
528
529     private JsonObjectBuilder serviceToJson(Service service) {
530         var serviceBuilder = Json.createObjectBuilder();
531         serviceBuilder.add("type", service.getType());
532         var characteristics = Json.createArrayBuilder();
533
534         service.getCharacteristics().stream().sorted((l, r) -> l.getClass().getName().compareTo(r.getClass().getName()))
535                 .forEach(c -> {
536                     try {
537                         var cJson = c.toJson(0).get();
538                         var cBuilder = Json.createObjectBuilder();
539                         // Need to copy over everything except the current value, which we instead
540                         // reach in and get the default value
541                         cJson.forEach((k, v) -> {
542                             if ("value".equals(k)) {
543                                 Object defaultValue = ((BaseCharacteristic) c).getDefault();
544                                 if (defaultValue instanceof Boolean) {
545                                     cBuilder.add("value", (boolean) defaultValue);
546                                 } else if (defaultValue instanceof Integer) {
547                                     cBuilder.add("value", (int) defaultValue);
548                                 } else if (defaultValue instanceof Double) {
549                                     cBuilder.add("value", (double) defaultValue);
550                                 } else {
551                                     cBuilder.add("value", defaultValue.toString());
552                                 }
553                             } else {
554                                 cBuilder.add(k, v);
555                             }
556                         });
557                         characteristics.add(cBuilder.build());
558                     } catch (InterruptedException | ExecutionException e) {
559                     }
560                 });
561         serviceBuilder.add("c", characteristics);
562
563         if (!service.getLinkedServices().isEmpty()) {
564             var linkedServices = Json.createArrayBuilder();
565             service.getLinkedServices().forEach(s -> linkedServices.add(serviceToJson(s)));
566             serviceBuilder.add("ls", linkedServices);
567         }
568         return serviceBuilder;
569     }
570 }