2 * Copyright (c) 2010-2021 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.math.BigDecimal;
16 import java.math.RoundingMode;
17 import java.util.ArrayList;
18 import java.util.Collection;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import java.util.concurrent.CompletableFuture;
25 import javax.measure.Quantity;
26 import javax.measure.Unit;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.core.items.GenericItem;
31 import org.openhab.core.items.Item;
32 import org.openhab.core.library.types.OnOffType;
33 import org.openhab.core.library.types.OpenClosedType;
34 import org.openhab.core.library.types.StringType;
35 import org.openhab.core.library.unit.ImperialUnits;
36 import org.openhab.core.library.unit.SIUnits;
37 import org.openhab.core.types.State;
38 import org.openhab.io.homekit.internal.HomekitAccessoryUpdater;
39 import org.openhab.io.homekit.internal.HomekitCharacteristicType;
40 import org.openhab.io.homekit.internal.HomekitSettings;
41 import org.openhab.io.homekit.internal.HomekitTaggedItem;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
45 import io.github.hapjava.accessories.HomekitAccessory;
46 import io.github.hapjava.characteristics.HomekitCharacteristicChangeCallback;
47 import io.github.hapjava.services.Service;
50 * Abstract class for Homekit Accessory implementations, this provides the
51 * accessory metadata using information from the underlying Item.
53 * @author Andy Lintner - Initial contribution
55 abstract class AbstractHomekitAccessoryImpl implements HomekitAccessory {
56 private final Logger logger = LoggerFactory.getLogger(AbstractHomekitAccessoryImpl.class);
57 private final List<HomekitTaggedItem> characteristics;
58 private final HomekitTaggedItem accessory;
59 private final HomekitAccessoryUpdater updater;
60 private final HomekitSettings settings;
61 private final List<Service> services;
63 public AbstractHomekitAccessoryImpl(HomekitTaggedItem accessory, List<HomekitTaggedItem> characteristics,
64 HomekitAccessoryUpdater updater, HomekitSettings settings) {
65 this.characteristics = characteristics;
66 this.accessory = accessory;
67 this.updater = updater;
68 this.services = new ArrayList<>();
69 this.settings = settings;
73 protected Optional<HomekitTaggedItem> getCharacteristic(HomekitCharacteristicType type) {
74 return characteristics.stream().filter(c -> c.getCharacteristicType() == type).findAny();
79 return accessory.getId();
83 public CompletableFuture<String> getName() {
84 return CompletableFuture.completedFuture(accessory.getItem().getLabel());
88 public CompletableFuture<String> getManufacturer() {
89 return CompletableFuture.completedFuture("none");
93 public CompletableFuture<String> getModel() {
94 return CompletableFuture.completedFuture("none");
98 public CompletableFuture<String> getSerialNumber() {
99 return CompletableFuture.completedFuture(accessory.getItem().getName());
103 public CompletableFuture<String> getFirmwareRevision() {
104 return CompletableFuture.completedFuture("none");
108 public void identify() {
109 // We're not going to support this for now
112 public HomekitTaggedItem getRootAccessory() {
116 public Collection<Service> getServices() {
117 return this.services;
120 protected HomekitAccessoryUpdater getUpdater() {
124 protected HomekitSettings getSettings() {
129 protected void subscribe(HomekitCharacteristicType characteristicType,
130 HomekitCharacteristicChangeCallback callback) {
131 final Optional<HomekitTaggedItem> characteristic = getCharacteristic(characteristicType);
132 if (characteristic.isPresent()) {
133 getUpdater().subscribe((GenericItem) characteristic.get().getItem(), characteristicType.getTag(), callback);
135 logger.warn("Missing mandatory characteristic {}", characteristicType);
140 protected void unsubscribe(HomekitCharacteristicType characteristicType) {
141 final Optional<HomekitTaggedItem> characteristic = getCharacteristic(characteristicType);
142 if (characteristic.isPresent()) {
143 getUpdater().unsubscribe((GenericItem) characteristic.get().getItem(), characteristicType.getTag());
145 logger.warn("Missing mandatory characteristic {}", characteristicType);
149 protected @Nullable <T extends State> T getStateAs(HomekitCharacteristicType characteristic, Class<T> type) {
150 final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
151 if (taggedItem.isPresent()) {
152 final State state = taggedItem.get().getItem().getStateAs(type);
154 return state.as(type);
157 logger.debug("State for characteristic {} at accessory {} cannot be retrieved.", characteristic,
158 accessory.getName());
163 protected <T extends Item> Optional<T> getItem(HomekitCharacteristicType characteristic, Class<T> type) {
164 final Optional<HomekitTaggedItem> taggedItem = getCharacteristic(characteristic);
165 if (taggedItem.isPresent()) {
166 final Item item = taggedItem.get().getItem();
167 if (type.isInstance(item)) {
168 return Optional.of((T) item);
170 logger.warn("Unsupported item type for characteristic {} at accessory {}. Expected {}, got {}",
171 characteristic, accessory.getItem().getName(), type, taggedItem.get().getItem().getClass());
174 logger.warn("Mandatory characteristic {} not found at accessory {}. ", characteristic,
175 accessory.getItem().getName());
178 return Optional.empty();
182 * return configuration attached to the root accessory, e.g. groupItem.
183 * Note: result will be casted to the type of the default value.
184 * The type for number is BigDecimal.
186 * @param key configuration key
187 * @param defaultValue default value
188 * @param <T> expected type
189 * @return configuration value
192 protected <T> T getAccessoryConfiguration(String key, T defaultValue) {
193 return accessory.getConfiguration(key, defaultValue);
197 * return configuration of the characteristic item, e.g. currentTemperature.
198 * Note: result will be casted to the type of the default value.
199 * The type for number is BigDecimal.
201 * @param characteristicType characteristic type
202 * @param key configuration key
203 * @param defaultValue default value
204 * @param <T> expected type
205 * @return configuration value
208 protected <T> T getAccessoryConfiguration(HomekitCharacteristicType characteristicType, String key,
210 return getCharacteristic(characteristicType)
211 .map(homekitTaggedItem -> homekitTaggedItem.getConfiguration(key, defaultValue)).orElse(defaultValue);
215 * update mapping with values from item configuration.
216 * it checks for all keys from the mapping whether there is configuration at item with the same key and if yes,
219 * @param characteristicType characteristicType to identify item
220 * @param map mapping to update
221 * @param customEnumList list to store custom state enumeration
224 protected <T> void updateMapping(HomekitCharacteristicType characteristicType, Map<T, String> map,
225 @Nullable List<T> customEnumList) {
226 getCharacteristic(characteristicType).ifPresent(c -> {
227 final Map<String, Object> configuration = c.getConfiguration();
228 if (configuration != null) {
229 map.forEach((k, current_value) -> {
230 final Object new_value = configuration.get(k.toString());
231 if (new_value instanceof String) {
232 map.put(k, (String) new_value);
233 if (customEnumList != null) {
234 customEnumList.add(k);
243 protected <T> void updateMapping(HomekitCharacteristicType characteristicType, Map<T, String> map) {
244 updateMapping(characteristicType, map, null);
248 * takes item state as value and retrieves the key for that value from mapping.
249 * e.g. used to map StringItem value to HomeKit Enum
251 * @param characteristicType characteristicType to identify item
252 * @param mapping mapping
253 * @param defaultValue default value if nothing found in mapping
254 * @param <T> type of the result derived from
255 * @return key for the value
258 protected <T> T getKeyFromMapping(HomekitCharacteristicType characteristicType, Map<T, String> mapping,
260 final Optional<HomekitTaggedItem> c = getCharacteristic(characteristicType);
262 final State state = c.get().getItem().getState();
263 logger.trace("getKeyFromMapping: characteristic {}, state {}, mapping {}", characteristicType.getTag(),
265 if (state instanceof StringType) {
266 return mapping.entrySet().stream().filter(entry -> state.toString().equalsIgnoreCase(entry.getValue()))
267 .findAny().map(Entry::getKey).orElseGet(() -> {
269 "Wrong value {} for {} characteristic of the item {}. Expected one of following {}. Returning {}.",
270 state.toString(), characteristicType.getTag(), c.get().getName(), mapping.values(),
280 protected void addCharacteristic(HomekitTaggedItem characteristic) {
281 characteristics.add(characteristic);
285 private <T extends Quantity<T>> double convertAndRound(double value, Unit<T> from, Unit<T> to) {
286 double rawValue = from == to ? value : from.getConverterTo(to).convert(value);
287 return new BigDecimal(rawValue).setScale(1, RoundingMode.HALF_UP).doubleValue();
291 protected double convertToCelsius(double degrees) {
292 return convertAndRound(degrees,
293 getSettings().useFahrenheitTemperature ? ImperialUnits.FAHRENHEIT : SIUnits.CELSIUS, SIUnits.CELSIUS);
297 protected double convertFromCelsius(double degrees) {
298 return convertAndRound(degrees,
299 getSettings().useFahrenheitTemperature ? SIUnits.CELSIUS : ImperialUnits.FAHRENHEIT,
300 ImperialUnits.FAHRENHEIT);
304 protected BooleanItemReader createBooleanReader(HomekitCharacteristicType characteristicType,
305 OnOffType trueOnOffValue, OpenClosedType trueOpenClosedValue) throws IncompleteAccessoryException {
306 return new BooleanItemReader(
307 getItem(characteristicType, GenericItem.class)
308 .orElseThrow(() -> new IncompleteAccessoryException(characteristicType)),
309 trueOnOffValue, trueOpenClosedValue);