2 * Copyright (c) 2010-2024 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.io.homekit.internal.accessories;
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;
22 import java.util.Optional;
23 import java.util.concurrent.CompletableFuture;
24 import java.util.concurrent.ExecutionException;
26 import javax.json.Json;
27 import javax.json.JsonObjectBuilder;
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;
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;
60 * Abstract class for Homekit Accessory implementations, this provides the
61 * accessory metadata using information from the underlying Item.
63 * @author Andy Lintner - Initial contribution
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;
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);
94 * Gives an accessory an opportunity to populate additional characteristics after all optional
95 * charactericteristics have been added.
97 * @throws HomekitException
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());
107 if (!isLinkedService()) {
108 if (!rawCharacteristics.containsKey(IdentifyCharacteristic.class)) {
109 rawCharacteristics.put(IdentifyCharacteristic.class, new IdentifyCharacteristic(v -> {
112 if (!rawCharacteristics.containsKey(ManufacturerCharacteristic.class)) {
113 rawCharacteristics.put(ManufacturerCharacteristic.class, new ManufacturerCharacteristic(() -> {
114 return CompletableFuture.completedFuture("none");
117 if (!rawCharacteristics.containsKey(ModelCharacteristic.class)) {
118 rawCharacteristics.put(ModelCharacteristic.class, new ModelCharacteristic(() -> {
119 return CompletableFuture.completedFuture("none");
122 if (!rawCharacteristics.containsKey(SerialNumberCharacteristic.class)) {
123 rawCharacteristics.put(SerialNumberCharacteristic.class, new SerialNumberCharacteristic(() -> {
124 return CompletableFuture.completedFuture(accessory.getItem().getName());
127 if (!rawCharacteristics.containsKey(FirmwareRevisionCharacteristic.class)) {
128 rawCharacteristics.put(FirmwareRevisionCharacteristic.class, new FirmwareRevisionCharacteristic(() -> {
129 return CompletableFuture.completedFuture("none");
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());
140 getCharacteristic(HardwareRevisionCharacteristic.class)
141 .ifPresent(c -> service.addOptionalCharacteristic(c));
143 // make sure this is the first service
144 services.add(0, service);
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.
153 public boolean isLinkable(HomekitAccessory parentAccessory) {
158 * Sets if this accessory is being used as a linked service.
160 public void setIsLinkedService(boolean value) {
161 isLinkedService = value;
165 * @return If this accessory is being used as a linked service.
167 public boolean isLinkedService() {
168 return isLinkedService;
172 * @return If this accessory is only valid as a linked service, not as a standalone accessory.
174 public boolean isLinkedServiceOnly() {
179 public Optional<HomekitTaggedItem> getCharacteristic(HomekitCharacteristicType type) {
180 return characteristics.stream().filter(c -> c.getCharacteristicType() == type).findAny();
185 return accessory.getId();
189 public CompletableFuture<String> getName() {
190 return getCharacteristic(NameCharacteristic.class).get().getValue();
194 public CompletableFuture<String> getManufacturer() {
195 return getCharacteristic(ManufacturerCharacteristic.class).get().getValue();
199 public CompletableFuture<String> getModel() {
200 return getCharacteristic(ModelCharacteristic.class).get().getValue();
204 public CompletableFuture<String> getSerialNumber() {
205 return getCharacteristic(SerialNumberCharacteristic.class).get().getValue();
209 public CompletableFuture<String> getFirmwareRevision() {
210 return getCharacteristic(FirmwareRevisionCharacteristic.class).get().getValue();
214 public void identify() {
216 getCharacteristic(IdentifyCharacteristic.class).get().setValue(true);
217 } catch (Exception e) {
222 public HomekitTaggedItem getRootAccessory() {
227 public Collection<Service> getServices() {
228 return this.services;
231 protected HomekitAccessoryUpdater getUpdater() {
235 protected HomekitSettings getSettings() {
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);
246 logger.warn("Missing mandatory characteristic {}", characteristicType);
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());
256 logger.warn("Missing mandatory characteristic {}", characteristicType);
260 protected @Nullable State getState(HomekitCharacteristicType characteristic) {
261 final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
262 if (taggedItem.isPresent()) {
263 return taggedItem.get().getItem().getState();
265 logger.debug("State for characteristic {} at accessory {} cannot be retrieved.", characteristic,
266 accessory.getName());
270 protected @Nullable <T extends State> T getStateAs(HomekitCharacteristicType characteristic, Class<T> type) {
271 final State state = getState(characteristic);
273 return state.as(type);
278 protected @Nullable Double getStateAsTemperature(HomekitCharacteristicType characteristic) {
279 return HomekitCharacteristicFactory.stateAsTemperature(getState(characteristic));
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);
290 logger.warn("Unsupported item type for characteristic {} at accessory {}. Expected {}, got {}",
291 characteristic, accessory.getItem().getName(), type, taggedItem.get().getItem().getClass());
294 logger.warn("Mandatory characteristic {} not found at accessory {}. ", characteristic,
295 accessory.getItem().getName());
297 return Optional.empty();
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.
305 * @param key configuration key
306 * @param defaultValue default value
307 * @param <T> expected type
308 * @return configuration value
311 protected <T> T getAccessoryConfiguration(String key, T defaultValue) {
312 return accessory.getConfiguration(key, defaultValue);
316 * return configuration attached to the root accessory, e.g. groupItem.
318 * @param key configuration key
319 * @param defaultValue default value
320 * @return configuration value
323 protected boolean getAccessoryConfigurationAsBoolean(String key, boolean defaultValue) {
324 return accessory.getConfigurationAsBoolean(key, defaultValue);
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.
332 * @param characteristicType characteristic type
333 * @param key configuration key
334 * @param defaultValue default value
335 * @param <T> expected type
336 * @return configuration value
339 protected <T> T getAccessoryConfiguration(HomekitCharacteristicType characteristicType, String key,
341 return getCharacteristic(characteristicType)
342 .map(homekitTaggedItem -> homekitTaggedItem.getConfiguration(key, defaultValue)).orElse(defaultValue);
346 protected <T extends Enum<T> & CharacteristicEnum> Map<T, String> createMapping(
347 HomekitCharacteristicType characteristicType, Class<T> klazz) {
348 return createMapping(characteristicType, klazz, null, false);
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);
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);
364 * create mapping with values from item configuration
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
372 protected <T extends Enum<T> & CharacteristicEnum> Map<T, String> createMapping(
373 HomekitCharacteristicType characteristicType, Class<T> klazz, @Nullable List<T> customEnumList,
375 HomekitTaggedItem item = getCharacteristic(characteristicType).get();
376 return HomekitCharacteristicFactory.createMapping(item, klazz, customEnumList, inverted);
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
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
390 public <T> T getKeyFromMapping(HomekitCharacteristicType characteristicType, Map<T, String> mapping,
392 final Optional<HomekitTaggedItem> c = getCharacteristic(characteristicType);
394 return HomekitCharacteristicFactory.getKeyFromMapping(c.get(), mapping, defaultValue);
400 protected void addCharacteristic(HomekitTaggedItem item, Characteristic characteristic)
401 throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
402 characteristics.add(item);
403 addCharacteristic(characteristic);
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.
410 * @param characteristic
411 * @throws NoSuchMethodException
412 * @throws IllegalAccessException
413 * @throws InvocationTargetException
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());
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,
433 * Takes the NameCharacteristic that normally exists on the AccessoryInformationService,
434 * and puts it on the primary service.
436 public void promoteNameCharacteristic() {
437 var characteristic = getCharacteristic(NameCharacteristic.class);
438 if (!characteristic.isPresent()) {
442 var service = getPrimaryService();
443 if (service != null) {
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
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.
458 public <T> Optional<T> getCharacteristic(Class<? extends T> klazz) {
459 return Optional.ofNullable((T) rawCharacteristics.get(klazz));
463 * create boolean reader with ON state mapped to trueOnOffValue or trueOpenClosedValue depending of item type
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
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);
481 * create boolean reader for a number item with ON state mapped to the value of the
482 * item being above a given threshold
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
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);
500 * create boolean reader with default ON/OFF mapping considering inverted flag
502 * @param characteristicType characteristic id
503 * @return boolean reader
504 * @throws IncompleteAccessoryException
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);
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.
521 public String toJson() {
522 var builder = Json.createArrayBuilder();
523 getServices().forEach(s -> {
524 builder.add(serviceToJson(s));
526 return builder.build().toString();
529 private JsonObjectBuilder serviceToJson(Service service) {
530 var serviceBuilder = Json.createObjectBuilder();
531 serviceBuilder.add("type", service.getType());
532 var characteristics = Json.createArrayBuilder();
534 service.getCharacteristics().stream().sorted((l, r) -> l.getClass().getName().compareTo(r.getClass().getName()))
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);
551 cBuilder.add("value", defaultValue.toString());
557 characteristics.add(cBuilder.build());
558 } catch (InterruptedException | ExecutionException e) {
561 serviceBuilder.add("c", characteristics);
563 if (!service.getLinkedServices().isEmpty()) {
564 var linkedServices = Json.createArrayBuilder();
565 service.getLinkedServices().forEach(s -> linkedServices.add(serviceToJson(s)));
566 serviceBuilder.add("ls", linkedServices);
568 return serviceBuilder;