2 * Copyright (c) 2010-2023 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.HomekitCharacteristicChangeCallback;
47 import io.github.hapjava.characteristics.impl.base.BaseCharacteristic;
48 import io.github.hapjava.services.Service;
51 * Abstract class for Homekit Accessory implementations, this provides the
52 * accessory metadata using information from the underlying Item.
54 * @author Andy Lintner - Initial contribution
56 public abstract class AbstractHomekitAccessoryImpl implements HomekitAccessory {
57 private final Logger logger = LoggerFactory.getLogger(AbstractHomekitAccessoryImpl.class);
58 private final List<HomekitTaggedItem> characteristics;
59 private final HomekitTaggedItem accessory;
60 private final HomekitAccessoryUpdater updater;
61 private final HomekitSettings settings;
62 private final List<Service> services;
63 private final Map<Class<? extends Characteristic>, Characteristic> rawCharacteristics;
65 public AbstractHomekitAccessoryImpl(HomekitTaggedItem accessory, List<HomekitTaggedItem> characteristics,
66 HomekitAccessoryUpdater updater, HomekitSettings settings) {
67 this.characteristics = characteristics;
68 this.accessory = accessory;
69 this.updater = updater;
70 this.services = new ArrayList<>();
71 this.settings = settings;
72 this.rawCharacteristics = new HashMap<>();
73 // create raw characteristics for mandatory characteristics
74 characteristics.forEach(c -> {
75 var rawCharacteristic = HomekitCharacteristicFactory.createNullableCharacteristic(c, updater);
76 // not all mandatory characteristics are creatable via HomekitCharacteristicFactory (yet)
77 if (rawCharacteristic != null) {
78 rawCharacteristics.put(rawCharacteristic.getClass(), rawCharacteristic);
84 * Gives an accessory an opportunity to populate additional characteristics after all optional
85 * charactericteristics have been added.
87 public void init() throws HomekitException {
91 * @param parentAccessory The primary service to link to.
92 * @return If this accessory should be nested as a linked service below a primary service,
93 * rather than as a sibling.
95 public boolean isLinkable(HomekitAccessory parentAccessory) {
100 * @return If this accessory is only valid as a linked service, not as a standalone accessory.
102 public boolean isLinkedServiceOnly() {
107 public Optional<HomekitTaggedItem> getCharacteristic(HomekitCharacteristicType type) {
108 return characteristics.stream().filter(c -> c.getCharacteristicType() == type).findAny();
113 return accessory.getId();
117 public CompletableFuture<String> getName() {
118 return CompletableFuture.completedFuture(accessory.getItem().getLabel());
122 public CompletableFuture<String> getManufacturer() {
123 return CompletableFuture.completedFuture("none");
127 public CompletableFuture<String> getModel() {
128 return CompletableFuture.completedFuture("none");
132 public CompletableFuture<String> getSerialNumber() {
133 return CompletableFuture.completedFuture(accessory.getItem().getName());
137 public CompletableFuture<String> getFirmwareRevision() {
138 return CompletableFuture.completedFuture("none");
142 public void identify() {
143 // We're not going to support this for now
146 public HomekitTaggedItem getRootAccessory() {
151 public Collection<Service> getServices() {
152 return this.services;
155 protected HomekitAccessoryUpdater getUpdater() {
159 protected HomekitSettings getSettings() {
164 protected void subscribe(HomekitCharacteristicType characteristicType,
165 HomekitCharacteristicChangeCallback callback) {
166 final Optional<HomekitTaggedItem> characteristic = getCharacteristic(characteristicType);
167 if (characteristic.isPresent()) {
168 getUpdater().subscribe((GenericItem) characteristic.get().getItem(), characteristicType.getTag(), callback);
170 logger.warn("Missing mandatory characteristic {}", characteristicType);
175 protected void unsubscribe(HomekitCharacteristicType characteristicType) {
176 final Optional<HomekitTaggedItem> characteristic = getCharacteristic(characteristicType);
177 if (characteristic.isPresent()) {
178 getUpdater().unsubscribe((GenericItem) characteristic.get().getItem(), characteristicType.getTag());
180 logger.warn("Missing mandatory characteristic {}", characteristicType);
184 protected @Nullable State getState(HomekitCharacteristicType characteristic) {
185 final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
186 if (taggedItem.isPresent()) {
187 return taggedItem.get().getItem().getState();
189 logger.debug("State for characteristic {} at accessory {} cannot be retrieved.", characteristic,
190 accessory.getName());
194 protected @Nullable <T extends State> T getStateAs(HomekitCharacteristicType characteristic, Class<T> type) {
195 final State state = getState(characteristic);
197 return state.as(type);
202 protected @Nullable Double getStateAsTemperature(HomekitCharacteristicType characteristic) {
203 return HomekitCharacteristicFactory.stateAsTemperature(getState(characteristic));
207 protected <T extends Item> Optional<T> getItem(HomekitCharacteristicType characteristic, Class<T> type) {
208 final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
209 if (taggedItem.isPresent()) {
210 final Item item = taggedItem.get().getItem();
211 if (type.isInstance(item)) {
212 return Optional.of((T) item);
214 logger.warn("Unsupported item type for characteristic {} at accessory {}. Expected {}, got {}",
215 characteristic, accessory.getItem().getName(), type, taggedItem.get().getItem().getClass());
218 logger.warn("Mandatory characteristic {} not found at accessory {}. ", characteristic,
219 accessory.getItem().getName());
222 return Optional.empty();
226 * return configuration attached to the root accessory, e.g. groupItem.
227 * Note: result will be casted to the type of the default value.
228 * The type for number is BigDecimal.
230 * @param key configuration key
231 * @param defaultValue default value
232 * @param <T> expected type
233 * @return configuration value
236 protected <T> T getAccessoryConfiguration(String key, T defaultValue) {
237 return accessory.getConfiguration(key, defaultValue);
241 * return configuration attached to the root accessory, e.g. groupItem.
243 * @param key configuration key
244 * @param defaultValue default value
245 * @return configuration value
248 protected boolean getAccessoryConfigurationAsBoolean(String key, boolean defaultValue) {
249 return accessory.getConfigurationAsBoolean(key, defaultValue);
253 * return configuration of the characteristic item, e.g. currentTemperature.
254 * Note: result will be casted to the type of the default value.
255 * The type for number is BigDecimal.
257 * @param characteristicType characteristic type
258 * @param key configuration key
259 * @param defaultValue default value
260 * @param <T> expected type
261 * @return configuration value
264 protected <T> T getAccessoryConfiguration(HomekitCharacteristicType characteristicType, String key,
266 return getCharacteristic(characteristicType)
267 .map(homekitTaggedItem -> homekitTaggedItem.getConfiguration(key, defaultValue)).orElse(defaultValue);
271 * update mapping with values from item configuration.
272 * it checks for all keys from the mapping whether there is configuration at item with the same key and if yes,
275 * @param characteristicType characteristicType to identify item
276 * @param map mapping to update
277 * @param customEnumList list to store custom state enumeration
280 public <T> void updateMapping(HomekitCharacteristicType characteristicType, Map<T, String> map,
281 @Nullable List<T> customEnumList) {
282 getCharacteristic(characteristicType).ifPresent(c -> {
283 final Map<String, Object> configuration = c.getConfiguration();
284 if (configuration != null) {
285 HomekitCharacteristicFactory.updateMapping(configuration, map, customEnumList);
291 public <T> void updateMapping(HomekitCharacteristicType characteristicType, Map<T, String> map) {
292 updateMapping(characteristicType, map, null);
296 * takes item state as value and retrieves the key for that value from mapping.
297 * e.g. used to map StringItem value to HomeKit Enum
299 * @param characteristicType characteristicType to identify item
300 * @param mapping mapping
301 * @param defaultValue default value if nothing found in mapping
302 * @param <T> type of the result derived from
303 * @return key for the value
306 public <T> T getKeyFromMapping(HomekitCharacteristicType characteristicType, Map<T, String> mapping,
308 final Optional<HomekitTaggedItem> c = getCharacteristic(characteristicType);
310 return HomekitCharacteristicFactory.getKeyFromMapping(c.get(), mapping, defaultValue);
316 protected void addCharacteristic(HomekitTaggedItem item, Characteristic characteristic)
317 throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
318 characteristics.add(item);
319 addCharacteristic(characteristic);
323 * If the primary service does not yet exist, it won't be added to it. It's the resposibility
324 * of the caller to add characteristics when the primary service is created.
327 * @param characteristic
330 public void addCharacteristic(Characteristic characteristic)
331 throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
332 if (rawCharacteristics.containsKey(characteristic.getClass())) {
333 logger.warn("Accessory {} already has a characteristic of type {}; ignoring additional definition.",
334 accessory.getName(), characteristic.getClass().getSimpleName());
337 rawCharacteristics.put(characteristic.getClass(), characteristic);
338 var service = getPrimaryService();
339 if (service != null) {
340 // find the corresponding add method at service and call it.
341 service.getClass().getMethod("addOptionalCharacteristic", characteristic.getClass()).invoke(service,
347 public <T> Optional<T> getCharacteristic(Class<? extends T> klazz) {
348 return Optional.ofNullable((T) rawCharacteristics.get(klazz));
352 * create boolean reader with ON state mapped to trueOnOffValue or trueOpenClosedValue depending of item type
354 * @param characteristicType characteristic id
355 * @param trueOnOffValue ON value for switch
356 * @param trueOpenClosedValue ON value for contact
357 * @return boolean read
358 * @throws IncompleteAccessoryException
361 protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType,
362 OnOffType trueOnOffValue, OpenClosedType trueOpenClosedValue) throws IncompleteAccessoryException {
363 return new BooleanItemReader(
364 getItem(characteristicType, GenericItem.class)
365 .orElseThrow(() -> new IncompleteAccessoryException(characteristicType)),
366 trueOnOffValue, trueOpenClosedValue);
370 * create boolean reader for a number item with ON state mapped to the value of the
371 * item being above a given threshold
373 * @param characteristicType characteristic id
374 * @param trueThreshold threshold for true of number item
375 * @param invertThreshold result is true if item is less than threshold, instead of more
376 * @return boolean read
377 * @throws IncompleteAccessoryException
380 protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType,
381 BigDecimal trueThreshold, boolean invertThreshold) throws IncompleteAccessoryException {
382 final HomekitTaggedItem taggedItem = getCharacteristic(characteristicType)
383 .orElseThrow(() -> new IncompleteAccessoryException(characteristicType));
384 return new BooleanItemReader(taggedItem.getItem(), taggedItem.isInverted() ? OnOffType.OFF : OnOffType.ON,
385 taggedItem.isInverted() ? OpenClosedType.CLOSED : OpenClosedType.OPEN, trueThreshold, invertThreshold);
389 * create boolean reader with default ON/OFF mapping considering inverted flag
391 * @param characteristicType characteristic id
392 * @return boolean reader
393 * @throws IncompleteAccessoryException
396 protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType)
397 throws IncompleteAccessoryException {
398 final HomekitTaggedItem taggedItem = getCharacteristic(characteristicType)
399 .orElseThrow(() -> new IncompleteAccessoryException(characteristicType));
400 return new BooleanItemReader(taggedItem.getItem(), taggedItem.isInverted() ? OnOffType.OFF : OnOffType.ON,
401 taggedItem.isInverted() ? OpenClosedType.CLOSED : OpenClosedType.OPEN);
405 * Calculates a string as json of the configuration for this accessory, suitable for seeing
406 * if the structure has changed, and building a dummy accessory for it. It is _not_ suitable
407 * for actual publishing to by HAP-Java to iOS devices, since all the IIDs will be set to 0.
408 * The IIDs will get replaced by actual values by HAP-Java inside of DummyHomekitCharacteristic.
410 public String toJson() {
411 var builder = Json.createArrayBuilder();
412 getServices().forEach(s -> {
413 builder.add(serviceToJson(s));
415 return builder.build().toString();
418 private JsonObjectBuilder serviceToJson(Service service) {
419 var serviceBuilder = Json.createObjectBuilder();
420 serviceBuilder.add("type", service.getType());
421 var characteristics = Json.createArrayBuilder();
423 service.getCharacteristics().stream().sorted((l, r) -> l.getClass().getName().compareTo(r.getClass().getName()))
426 var cJson = c.toJson(0).get();
427 var cBuilder = Json.createObjectBuilder();
428 // Need to copy over everything except the current value, which we instead
429 // reach in and get the default value
430 cJson.forEach((k, v) -> {
431 if (k.equals("value")) {
432 Object defaultValue = ((BaseCharacteristic) c).getDefault();
433 if (defaultValue instanceof Boolean) {
434 cBuilder.add("value", (boolean) defaultValue);
435 } else if (defaultValue instanceof Integer) {
436 cBuilder.add("value", (int) defaultValue);
437 } else if (defaultValue instanceof Double) {
438 cBuilder.add("value", (double) defaultValue);
440 cBuilder.add("value", defaultValue.toString());
446 characteristics.add(cBuilder.build());
447 } catch (InterruptedException | ExecutionException e) {
450 serviceBuilder.add("c", characteristics);
452 if (!service.getLinkedServices().isEmpty()) {
453 var linkedServices = Json.createArrayBuilder();
454 service.getLinkedServices().forEach(s -> linkedServices.add(serviceToJson(s)));
455 serviceBuilder.add("ls", linkedServices);
457 return serviceBuilder;