2 * Copyright (c) 2010-2022 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.util.ArrayList;
16 import java.util.Collection;
17 import java.util.List;
19 import java.util.Map.Entry;
20 import java.util.Optional;
21 import java.util.concurrent.CompletableFuture;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.openhab.core.items.GenericItem;
26 import org.openhab.core.items.Item;
27 import org.openhab.core.library.types.OnOffType;
28 import org.openhab.core.library.types.OpenClosedType;
29 import org.openhab.core.library.types.StringType;
30 import org.openhab.core.types.State;
31 import org.openhab.io.homekit.internal.HomekitAccessoryUpdater;
32 import org.openhab.io.homekit.internal.HomekitCharacteristicType;
33 import org.openhab.io.homekit.internal.HomekitSettings;
34 import org.openhab.io.homekit.internal.HomekitTaggedItem;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import io.github.hapjava.accessories.HomekitAccessory;
39 import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback;
40 import io.github.hapjava.services.Service;
43 * Abstract class for Homekit Accessory implementations, this provides the
44 * accessory metadata using information from the underlying Item.
46 * @author Andy Lintner - Initial contribution
48 abstract class AbstractHomekitAccessoryImpl implements HomekitAccessory {
49 private final Logger logger = LoggerFactory.getLogger(AbstractHomekitAccessoryImpl.class);
50 private final List<HomekitTaggedItem> characteristics;
51 private final HomekitTaggedItem accessory;
52 private final HomekitAccessoryUpdater updater;
53 private final HomekitSettings settings;
54 private final List<Service> services;
56 public AbstractHomekitAccessoryImpl(HomekitTaggedItem accessory, List<HomekitTaggedItem> characteristics,
57 HomekitAccessoryUpdater updater, HomekitSettings settings) {
58 this.characteristics = characteristics;
59 this.accessory = accessory;
60 this.updater = updater;
61 this.services = new ArrayList<>();
62 this.settings = settings;
66 protected Optional<HomekitTaggedItem> getCharacteristic(HomekitCharacteristicType type) {
67 return characteristics.stream().filter(c -> c.getCharacteristicType() == type).findAny();
72 return accessory.getId();
76 public CompletableFuture<String> getName() {
77 return CompletableFuture.completedFuture(accessory.getItem().getLabel());
81 public CompletableFuture<String> getManufacturer() {
82 return CompletableFuture.completedFuture("none");
86 public CompletableFuture<String> getModel() {
87 return CompletableFuture.completedFuture("none");
91 public CompletableFuture<String> getSerialNumber() {
92 return CompletableFuture.completedFuture(accessory.getItem().getName());
96 public CompletableFuture<String> getFirmwareRevision() {
97 return CompletableFuture.completedFuture("none");
101 public void identify() {
102 // We're not going to support this for now
105 public HomekitTaggedItem getRootAccessory() {
110 public Collection<Service> getServices() {
111 return this.services;
114 protected HomekitAccessoryUpdater getUpdater() {
118 protected HomekitSettings getSettings() {
123 protected void subscribe(HomekitCharacteristicType characteristicType,
124 HomekitCharacteristicChangeCallback callback) {
125 final Optional<HomekitTaggedItem> characteristic = getCharacteristic(characteristicType);
126 if (characteristic.isPresent()) {
127 getUpdater().subscribe((GenericItem) characteristic.get().getItem(), characteristicType.getTag(), callback);
129 logger.warn("Missing mandatory characteristic {}", characteristicType);
134 protected void unsubscribe(HomekitCharacteristicType characteristicType) {
135 final Optional<HomekitTaggedItem> characteristic = getCharacteristic(characteristicType);
136 if (characteristic.isPresent()) {
137 getUpdater().unsubscribe((GenericItem) characteristic.get().getItem(), characteristicType.getTag());
139 logger.warn("Missing mandatory characteristic {}", characteristicType);
143 protected @Nullable <T extends State> T getStateAs(HomekitCharacteristicType characteristic, Class<T> type) {
144 final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
145 if (taggedItem.isPresent()) {
146 final State state = taggedItem.get().getItem().getStateAs(type);
148 return state.as(type);
151 logger.debug("State for characteristic {} at accessory {} cannot be retrieved.", characteristic,
152 accessory.getName());
157 protected <T extends Item> Optional<T> getItem(HomekitCharacteristicType characteristic, Class<T> type) {
158 final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
159 if (taggedItem.isPresent()) {
160 final Item item = taggedItem.get().getItem();
161 if (type.isInstance(item)) {
162 return Optional.of((T) item);
164 logger.warn("Unsupported item type for characteristic {} at accessory {}. Expected {}, got {}",
165 characteristic, accessory.getItem().getName(), type, taggedItem.get().getItem().getClass());
168 logger.warn("Mandatory characteristic {} not found at accessory {}. ", characteristic,
169 accessory.getItem().getName());
172 return Optional.empty();
176 * return configuration attached to the root accessory, e.g. groupItem.
177 * Note: result will be casted to the type of the default value.
178 * The type for number is BigDecimal.
180 * @param key configuration key
181 * @param defaultValue default value
182 * @param <T> expected type
183 * @return configuration value
186 protected <T> T getAccessoryConfiguration(String key, T defaultValue) {
187 return accessory.getConfiguration(key, defaultValue);
191 * return configuration of the characteristic item, e.g. currentTemperature.
192 * Note: result will be casted to the type of the default value.
193 * The type for number is BigDecimal.
195 * @param characteristicType characteristic type
196 * @param key configuration key
197 * @param defaultValue default value
198 * @param <T> expected type
199 * @return configuration value
202 protected <T> T getAccessoryConfiguration(HomekitCharacteristicType characteristicType, String key,
204 return getCharacteristic(characteristicType)
205 .map(homekitTaggedItem -> homekitTaggedItem.getConfiguration(key, defaultValue)).orElse(defaultValue);
209 * update mapping with values from item configuration.
210 * it checks for all keys from the mapping whether there is configuration at item with the same key and if yes,
213 * @param characteristicType characteristicType to identify item
214 * @param map mapping to update
215 * @param customEnumList list to store custom state enumeration
218 protected <T> void updateMapping(HomekitCharacteristicType characteristicType, Map<T, String> map,
219 @Nullable List<T> customEnumList) {
220 getCharacteristic(characteristicType).ifPresent(c -> {
221 final Map<String, Object> configuration = c.getConfiguration();
222 if (configuration != null) {
223 map.forEach((k, current_value) -> {
224 final Object new_value = configuration.get(k.toString());
225 if (new_value instanceof String) {
226 map.put(k, (String) new_value);
227 if (customEnumList != null) {
228 customEnumList.add(k);
237 protected <T> void updateMapping(HomekitCharacteristicType characteristicType, Map<T, String> map) {
238 updateMapping(characteristicType, map, null);
242 * takes item state as value and retrieves the key for that value from mapping.
243 * e.g. used to map StringItem value to HomeKit Enum
245 * @param characteristicType characteristicType to identify item
246 * @param mapping mapping
247 * @param defaultValue default value if nothing found in mapping
248 * @param <T> type of the result derived from
249 * @return key for the value
252 protected <T> T getKeyFromMapping(HomekitCharacteristicType characteristicType, Map<T, String> mapping,
254 final Optional<HomekitTaggedItem> c = getCharacteristic(characteristicType);
256 final State state = c.get().getItem().getState();
257 logger.trace("getKeyFromMapping: characteristic {}, state {}, mapping {}", characteristicType.getTag(),
259 if (state instanceof StringType) {
260 return mapping.entrySet().stream().filter(entry -> state.toString().equalsIgnoreCase(entry.getValue()))
261 .findAny().map(Entry::getKey).orElseGet(() -> {
263 "Wrong value {} for {} characteristic of the item {}. Expected one of following {}. Returning {}.",
264 state.toString(), characteristicType.getTag(), c.get().getName(), mapping.values(),
274 protected void addCharacteristic(HomekitTaggedItem characteristic) {
275 characteristics.add(characteristic);
279 * create boolean reader with ON state mapped to trueOnOffValue or trueOpenClosedValue depending of item type
281 * @param characteristicType characteristic id
282 * @param trueOnOffValue ON value for switch
283 * @param trueOpenClosedValue ON value for contact
284 * @return boolean read
285 * @throws IncompleteAccessoryException
288 protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType,
289 OnOffType trueOnOffValue, OpenClosedType trueOpenClosedValue) throws IncompleteAccessoryException {
290 return new BooleanItemReader(
291 getItem(characteristicType, GenericItem.class)
292 .orElseThrow(() -> new IncompleteAccessoryException(characteristicType)),
293 trueOnOffValue, trueOpenClosedValue);
297 * create boolean reader with default ON/OFF mapping considering inverted flag
299 * @param characteristicType characteristic id
300 * @return boolean reader
301 * @throws IncompleteAccessoryException
304 protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType)
305 throws IncompleteAccessoryException {
306 final HomekitTaggedItem taggedItem = getCharacteristic(characteristicType)
307 .orElseThrow(() -> new IncompleteAccessoryException(characteristicType));
308 return new BooleanItemReader(taggedItem.getItem(), taggedItem.isInverted() ? OnOffType.OFF : OnOffType.ON,
309 taggedItem.isInverted() ? OpenClosedType.CLOSED : OpenClosedType.OPEN);