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 static org.openhab.io.homekit.internal.HomekitAccessoryType.*;
16 import static org.openhab.io.homekit.internal.HomekitCharacteristicType.*;
18 import java.lang.reflect.InvocationTargetException;
19 import java.util.AbstractMap.SimpleEntry;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Map.Entry;
27 import java.util.Objects;
28 import java.util.Optional;
29 import java.util.stream.Collectors;
30 import java.util.stream.Stream;
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.openhab.core.items.GenericItem;
35 import org.openhab.core.items.GroupItem;
36 import org.openhab.core.items.Item;
37 import org.openhab.core.items.ItemRegistry;
38 import org.openhab.core.items.Metadata;
39 import org.openhab.core.items.MetadataKey;
40 import org.openhab.core.items.MetadataRegistry;
41 import org.openhab.io.homekit.internal.HomekitAccessoryType;
42 import org.openhab.io.homekit.internal.HomekitAccessoryUpdater;
43 import org.openhab.io.homekit.internal.HomekitCharacteristicType;
44 import org.openhab.io.homekit.internal.HomekitException;
45 import org.openhab.io.homekit.internal.HomekitOHItemProxy;
46 import org.openhab.io.homekit.internal.HomekitSettings;
47 import org.openhab.io.homekit.internal.HomekitTaggedItem;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
51 import io.github.hapjava.accessories.HomekitAccessory;
52 import io.github.hapjava.characteristics.Characteristic;
53 import io.github.hapjava.services.Service;
56 * Creates a HomekitAccessory for a given HomekitTaggedItem.
58 * @author Andy Lintner - Initial contribution
59 * @author Eugen Freiter - refactoring for optional characteristics
62 public class HomekitAccessoryFactory {
63 private static final Logger logger = LoggerFactory.getLogger(HomekitAccessoryFactory.class);
64 public final static String METADATA_KEY = "homekit"; // prefix for HomeKit meta information in items.xml
66 /** List of mandatory attributes for each accessory type. **/
67 private final static Map<HomekitAccessoryType, HomekitCharacteristicType[]> MANDATORY_CHARACTERISTICS = new HashMap<HomekitAccessoryType, HomekitCharacteristicType[]>() {
69 put(LEAK_SENSOR, new HomekitCharacteristicType[] { LEAK_DETECTED_STATE });
70 put(MOTION_SENSOR, new HomekitCharacteristicType[] { MOTION_DETECTED_STATE });
71 put(OCCUPANCY_SENSOR, new HomekitCharacteristicType[] { OCCUPANCY_DETECTED_STATE });
72 put(CONTACT_SENSOR, new HomekitCharacteristicType[] { CONTACT_SENSOR_STATE });
73 put(SMOKE_SENSOR, new HomekitCharacteristicType[] { SMOKE_DETECTED_STATE });
74 put(HUMIDITY_SENSOR, new HomekitCharacteristicType[] { RELATIVE_HUMIDITY });
75 put(AIR_QUALITY_SENSOR, new HomekitCharacteristicType[] { AIR_QUALITY });
76 put(SWITCH, new HomekitCharacteristicType[] { ON_STATE });
77 put(CARBON_DIOXIDE_SENSOR, new HomekitCharacteristicType[] { CARBON_DIOXIDE_DETECTED_STATE });
78 put(CARBON_MONOXIDE_SENSOR, new HomekitCharacteristicType[] { CARBON_MONOXIDE_DETECTED_STATE });
79 put(WINDOW_COVERING, new HomekitCharacteristicType[] { TARGET_POSITION, CURRENT_POSITION, POSITION_STATE });
80 put(LIGHTBULB, new HomekitCharacteristicType[] { ON_STATE });
81 put(FAN, new HomekitCharacteristicType[] { ACTIVE_STATUS });
82 put(LIGHT_SENSOR, new HomekitCharacteristicType[] { LIGHT_LEVEL });
83 put(TEMPERATURE_SENSOR, new HomekitCharacteristicType[] { CURRENT_TEMPERATURE });
84 put(THERMOSTAT, new HomekitCharacteristicType[] { CURRENT_HEATING_COOLING_STATE,
85 TARGET_HEATING_COOLING_STATE, CURRENT_TEMPERATURE, TARGET_TEMPERATURE });
86 put(LOCK, new HomekitCharacteristicType[] { LOCK_CURRENT_STATE, LOCK_TARGET_STATE });
87 put(VALVE, new HomekitCharacteristicType[] { ACTIVE_STATUS, INUSE_STATUS });
89 new HomekitCharacteristicType[] { SECURITY_SYSTEM_CURRENT_STATE, SECURITY_SYSTEM_TARGET_STATE });
90 put(OUTLET, new HomekitCharacteristicType[] { ON_STATE, INUSE_STATUS });
91 put(SPEAKER, new HomekitCharacteristicType[] { MUTE });
92 put(SMART_SPEAKER, new HomekitCharacteristicType[] { CURRENT_MEDIA_STATE, TARGET_MEDIA_STATE });
93 put(GARAGE_DOOR_OPENER,
94 new HomekitCharacteristicType[] { CURRENT_DOOR_STATE, TARGET_DOOR_STATE, OBSTRUCTION_STATUS });
95 put(HEATER_COOLER, new HomekitCharacteristicType[] { ACTIVE_STATUS, CURRENT_HEATER_COOLER_STATE,
96 TARGET_HEATER_COOLER_STATE, CURRENT_TEMPERATURE });
97 put(WINDOW, new HomekitCharacteristicType[] { CURRENT_POSITION, TARGET_POSITION, POSITION_STATE });
98 put(DOOR, new HomekitCharacteristicType[] { CURRENT_POSITION, TARGET_POSITION, POSITION_STATE });
99 put(BATTERY, new HomekitCharacteristicType[] { BATTERY_LEVEL, BATTERY_LOW_STATUS });
100 put(FILTER_MAINTENANCE, new HomekitCharacteristicType[] { FILTER_CHANGE_INDICATION });
101 put(SLAT, new HomekitCharacteristicType[] { CURRENT_SLAT_STATE });
102 put(FAUCET, new HomekitCharacteristicType[] { ACTIVE_STATUS });
103 put(MICROPHONE, new HomekitCharacteristicType[] { MUTE });
107 /** List of service implementation for each accessory type. **/
108 private final static Map<HomekitAccessoryType, Class<? extends AbstractHomekitAccessoryImpl>> SERVICE_IMPL_MAP = new HashMap<HomekitAccessoryType, Class<? extends AbstractHomekitAccessoryImpl>>() {
110 put(LEAK_SENSOR, HomekitLeakSensorImpl.class);
111 put(MOTION_SENSOR, HomekitMotionSensorImpl.class);
112 put(OCCUPANCY_SENSOR, HomekitOccupancySensorImpl.class);
113 put(CONTACT_SENSOR, HomekitContactSensorImpl.class);
114 put(SMOKE_SENSOR, HomekitSmokeSensorImpl.class);
115 put(HUMIDITY_SENSOR, HomekitHumiditySensorImpl.class);
116 put(AIR_QUALITY_SENSOR, HomekitAirQualitySensorImpl.class);
117 put(SWITCH, HomekitSwitchImpl.class);
118 put(CARBON_DIOXIDE_SENSOR, HomekitCarbonDioxideSensorImpl.class);
119 put(CARBON_MONOXIDE_SENSOR, HomekitCarbonMonoxideSensorImpl.class);
120 put(WINDOW_COVERING, HomekitWindowCoveringImpl.class);
121 put(LIGHTBULB, HomekitLightbulbImpl.class);
122 put(FAN, HomekitFanImpl.class);
123 put(LIGHT_SENSOR, HomekitLightSensorImpl.class);
124 put(TEMPERATURE_SENSOR, HomekitTemperatureSensorImpl.class);
125 put(THERMOSTAT, HomekitThermostatImpl.class);
126 put(LOCK, HomekitLockImpl.class);
127 put(VALVE, HomekitValveImpl.class);
128 put(SECURITY_SYSTEM, HomekitSecuritySystemImpl.class);
129 put(OUTLET, HomekitOutletImpl.class);
130 put(SPEAKER, HomekitSpeakerImpl.class);
131 put(SMART_SPEAKER, HomekitSmartSpeakerImpl.class);
132 put(GARAGE_DOOR_OPENER, HomekitGarageDoorOpenerImpl.class);
133 put(DOOR, HomekitDoorImpl.class);
134 put(WINDOW, HomekitWindowImpl.class);
135 put(HEATER_COOLER, HomekitHeaterCoolerImpl.class);
136 put(BATTERY, HomekitBatteryImpl.class);
137 put(FILTER_MAINTENANCE, HomekitFilterMaintenanceImpl.class);
138 put(SLAT, HomekitSlatImpl.class);
139 put(FAUCET, HomekitFaucetImpl.class);
140 put(MICROPHONE, HomekitMicrophoneImpl.class);
145 * creates HomeKit accessory for a openhab item.
147 * @param taggedItem openhab item tagged as HomeKit item
148 * @param metadataRegistry openhab metadata registry required to get item meta information
149 * @param updater OH HomeKit update class that ensure the status sync between OH item and corresponding HomeKit
151 * @param settings OH settings
152 * @return HomeKit accessory
153 * @throws HomekitException exception in case HomeKit accessory could not be created, e.g. due missing mandatory
156 @SuppressWarnings("null")
157 public static HomekitAccessory create(HomekitTaggedItem taggedItem, MetadataRegistry metadataRegistry,
158 HomekitAccessoryUpdater updater, HomekitSettings settings) throws HomekitException {
159 final HomekitAccessoryType accessoryType = taggedItem.getAccessoryType();
160 logger.trace("Constructing {} of accessory type {}", taggedItem.getName(), accessoryType.getTag());
161 final List<HomekitTaggedItem> requiredCharacteristics = getMandatoryCharacteristics(taggedItem,
163 final HomekitCharacteristicType[] mandatoryCharacteristics = MANDATORY_CHARACTERISTICS.get(accessoryType);
164 if ((mandatoryCharacteristics != null) && (requiredCharacteristics.size() < mandatoryCharacteristics.length)) {
165 logger.warn("Accessory of type {} must have following characteristics {}. Found only {}",
166 accessoryType.getTag(), mandatoryCharacteristics, requiredCharacteristics);
167 throw new HomekitException("Missing mandatory characteristics");
169 AbstractHomekitAccessoryImpl accessoryImpl;
171 final @Nullable Class<? extends AbstractHomekitAccessoryImpl> accessoryImplClass = SERVICE_IMPL_MAP
173 if (accessoryImplClass != null) {
174 accessoryImpl = accessoryImplClass
175 .getConstructor(HomekitTaggedItem.class, List.class, HomekitAccessoryUpdater.class,
176 HomekitSettings.class)
177 .newInstance(taggedItem, requiredCharacteristics, updater, settings);
178 addOptionalCharacteristics(taggedItem, accessoryImpl, metadataRegistry);
179 return accessoryImpl;
181 logger.warn("Unsupported HomeKit type: {}", accessoryType.getTag());
182 throw new HomekitException("Unsupported HomeKit type: " + accessoryType);
184 } catch (NoSuchMethodException | IllegalAccessException | InstantiationException
185 | InvocationTargetException e) {
186 logger.warn("Cannot instantiate accessory implementation for accessory {}", accessoryType.getTag(), e);
187 throw new HomekitException("Cannot instantiate accessory implementation for accessory " + accessoryType);
192 * return HomeKit accessory types for a OH item based on meta data
194 * @param item OH item
195 * @param metadataRegistry meta data registry
196 * @return list of HomeKit accessory types and characteristics.
198 public static List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> getAccessoryTypes(Item item,
199 MetadataRegistry metadataRegistry) {
200 final List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> accessories = new ArrayList<>();
201 final @Nullable Metadata metadata = metadataRegistry.get(new MetadataKey(METADATA_KEY, item.getUID()));
202 if (metadata != null) {
203 String[] tags = metadata.getValue().split(",");
204 for (String tag : tags) {
205 final String[] meta = tag.split("\\.");
206 Optional<HomekitAccessoryType> accessoryType = HomekitAccessoryType.valueOfTag(meta[0].trim());
207 if (accessoryType.isPresent()) { // it accessory, check for characteristic
208 HomekitAccessoryType type = accessoryType.get();
209 if (meta.length > 1) {
210 // it has characteristic as well
211 accessories.add(new SimpleEntry<>(type,
212 HomekitCharacteristicType.valueOfTag(meta[1].trim()).orElse(EMPTY)));
213 } else {// it has no characteristic
214 accessories.add(new SimpleEntry<>(type, EMPTY));
216 } else { // it is no accessory, so, maybe it is a characteristic
217 HomekitCharacteristicType.valueOfTag(meta[0].trim())
218 .ifPresent(c -> accessories.add(new SimpleEntry<>(DUMMY, c)));
225 public static @Nullable Map<String, Object> getItemConfiguration(Item item, MetadataRegistry metadataRegistry) {
226 final @Nullable Metadata metadata = metadataRegistry.get(new MetadataKey(METADATA_KEY, item.getUID()));
227 return metadata != null ? metadata.getConfiguration() : null;
231 * return list of HomeKit relevant groups linked to an accessory
233 * @param item OH item
234 * @param itemRegistry item registry
235 * @param metadataRegistry metadata registry
236 * @return list of relevant group items
238 public static List<GroupItem> getAccessoryGroups(Item item, ItemRegistry itemRegistry,
239 MetadataRegistry metadataRegistry) {
240 return (item instanceof GroupItem) ? Collections.emptyList() : item.getGroupNames().stream().flatMap(name -> {
241 final @Nullable Item groupItem = itemRegistry.get(name);
242 if ((groupItem instanceof GroupItem) && ((GroupItem) groupItem).getBaseItem() == null) {
243 return Stream.of((GroupItem) groupItem);
245 return Stream.empty();
247 }).filter(groupItem -> !getAccessoryTypes(groupItem, metadataRegistry).isEmpty()).collect(Collectors.toList());
251 * collect all mandatory characteristics for a given tagged item, e.g. collect all mandatory HomeKit items from a
254 * @param taggedItem HomeKit tagged item
255 * @param metadataRegistry meta data registry
256 * @return list of mandatory
258 private static List<HomekitTaggedItem> getMandatoryCharacteristics(HomekitTaggedItem taggedItem,
259 MetadataRegistry metadataRegistry) {
260 List<HomekitTaggedItem> collectedCharacteristics = new ArrayList<>();
261 if (taggedItem.isGroup()) {
262 for (Item item : ((GroupItem) taggedItem.getItem()).getAllMembers()) {
263 addMandatoryCharacteristics(taggedItem, collectedCharacteristics, item, metadataRegistry);
266 addMandatoryCharacteristics(taggedItem, collectedCharacteristics, taggedItem.getItem(), metadataRegistry);
268 logger.trace("Mandatory characteristics for item {} characteristics {}", taggedItem.getName(),
269 collectedCharacteristics);
270 return collectedCharacteristics;
274 * add mandatory HomeKit items for a given main item to a list of characteristics.
275 * Main item is use only to determine, which characteristics are mandatory.
276 * The characteristics are added to item.
277 * e.g. mainItem could be a group tagged as "thermostat" and item could be item linked to the group and marked as
280 * @param mainItem main item
281 * @param characteristics list of characteristics
282 * @param item current item
283 * @param metadataRegistry meta date registry
285 private static void addMandatoryCharacteristics(HomekitTaggedItem mainItem, List<HomekitTaggedItem> characteristics,
286 Item item, MetadataRegistry metadataRegistry) {
287 // get list of mandatory characteristics
288 HomekitCharacteristicType[] mandatoryCharacteristics = MANDATORY_CHARACTERISTICS
289 .get(mainItem.getAccessoryType());
290 if ((mandatoryCharacteristics == null) || (mandatoryCharacteristics.length == 0)) {
291 // no mandatory characteristics linked to accessory type of mainItem. we are done
294 // check whether we are adding characteristic to the main item, and if yes, use existing item proxy.
295 // if we are adding not to the main item (typical for groups), create new proxy item.
296 final HomekitOHItemProxy itemProxy = mainItem.getItem().equals(item) ? mainItem.getProxyItem()
297 : new HomekitOHItemProxy(item);
298 // an item can have several tags, e.g. "ActiveStatus, InUse". we iterate here over all his tags
299 for (Entry<HomekitAccessoryType, HomekitCharacteristicType> accessory : getAccessoryTypes(item,
301 // if the item has only accessory tag, e.g. TemperatureSensor,
302 // the we will link all mandatory characteristic to this item,
303 // e.g. we will link CurrentTemperature in case of TemperatureSensor.
304 if (isRootAccessory(accessory)) {
305 Arrays.stream(mandatoryCharacteristics)
306 .forEach(c -> characteristics.add(new HomekitTaggedItem(itemProxy, accessory.getKey(), c,
307 mainItem.isGroup() ? (GroupItem) mainItem.getItem() : null,
308 HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry))));
310 // item has characteristic tag on it, so, adding it as that characteristic.
312 final HomekitCharacteristicType characteristic = accessory.getValue();
314 // check whether it is a mandatory characteristic. optional will be added later by another method.
315 if (belongsToType(mainItem.getAccessoryType(), accessory)
316 && isMandatoryCharacteristic(mainItem.getAccessoryType(), characteristic)) {
317 characteristics.add(new HomekitTaggedItem(itemProxy, accessory.getKey(), characteristic,
318 mainItem.isGroup() ? (GroupItem) mainItem.getItem() : null,
319 HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry)));
326 * add optional characteristic for given accessory.
328 * @param taggedItem main item
329 * @param accessory accessory
330 * @param metadataRegistry metadata registry
332 private static void addOptionalCharacteristics(HomekitTaggedItem taggedItem, AbstractHomekitAccessoryImpl accessory,
333 MetadataRegistry metadataRegistry) {
334 Map<HomekitCharacteristicType, GenericItem> characteristics = getOptionalCharacteristics(
335 accessory.getRootAccessory(), metadataRegistry);
336 Service service = accessory.getPrimaryService();
337 HashMap<String, HomekitOHItemProxy> proxyItems = new HashMap<>();
338 proxyItems.put(taggedItem.getItem().getUID(), taggedItem.getProxyItem());
339 // an accessory can have multiple optional characteristics. iterate over them.
340 characteristics.forEach((type, item) -> {
342 // check whether a proxyItem already exists, if not create one.
343 final HomekitOHItemProxy proxyItem = Objects
344 .requireNonNull(proxyItems.computeIfAbsent(item.getUID(), k -> new HomekitOHItemProxy(item)));
345 final HomekitTaggedItem optionalItem = new HomekitTaggedItem(proxyItem,
346 accessory.getRootAccessory().getAccessoryType(), type,
347 accessory.getRootAccessory().getRootDeviceGroupItem(),
348 getItemConfiguration(item, metadataRegistry));
349 final Characteristic characteristic = HomekitCharacteristicFactory.createCharacteristic(optionalItem,
350 accessory.getUpdater());
351 // find the corresponding add method at service and call it.
352 service.getClass().getMethod("addOptionalCharacteristic", characteristic.getClass()).invoke(service,
354 accessory.addCharacteristic(optionalItem);
355 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | HomekitException e) {
356 logger.warn("Unsupported optional HomeKit characteristic: service type {}, characteristic type {}",
357 service.getType(), type.getTag());
363 * collect optional HomeKit characteristics for a OH item.
365 * @param taggedItem main OH item
366 * @param metadataRegistry OH metadata registry
367 * @return a map with characteristics and corresponding OH items
369 private static Map<HomekitCharacteristicType, GenericItem> getOptionalCharacteristics(HomekitTaggedItem taggedItem,
370 MetadataRegistry metadataRegistry) {
371 Map<HomekitCharacteristicType, GenericItem> characteristicItems = new HashMap<>();
372 if (taggedItem.isGroup()) {
373 GroupItem groupItem = (GroupItem) taggedItem.getItem();
374 groupItem.getMembers().forEach(item -> getAccessoryTypes(item, metadataRegistry).stream()
375 .filter(c -> !isRootAccessory(c)).filter(c -> belongsToType(taggedItem.getAccessoryType(), c))
376 .filter(c -> !isMandatoryCharacteristic(taggedItem.getAccessoryType(), c.getValue()))
377 .forEach(characteristic -> characteristicItems.put(characteristic.getValue(), (GenericItem) item)));
379 getAccessoryTypes(taggedItem.getItem(), metadataRegistry).stream().filter(c -> !isRootAccessory(c))
380 .filter(c -> !isMandatoryCharacteristic(taggedItem.getAccessoryType(), c.getValue()))
381 .forEach(characteristic -> characteristicItems.put(characteristic.getValue(),
382 (GenericItem) taggedItem.getItem()));
384 logger.trace("Optional characteristics for item {} characteristics {}", taggedItem.getName(),
385 characteristicItems);
386 return Collections.unmodifiableMap(characteristicItems);
390 * return true is characteristic is a mandatory characteristic for the accessory.
392 * @param accessory accessory
393 * @param characteristic characteristic
394 * @return true if characteristic is mandatory, false if not mandatory
396 private static boolean isMandatoryCharacteristic(HomekitAccessoryType accessory,
397 HomekitCharacteristicType characteristic) {
398 return MANDATORY_CHARACTERISTICS.containsKey(accessory)
399 && Arrays.asList(MANDATORY_CHARACTERISTICS.get(accessory)).contains(characteristic);
403 * check whether accessory is root accessory, i.e. without characteristic tag.
405 * @param accessory accessory
406 * @return true if accessory has not characteristic.
408 private static boolean isRootAccessory(Entry<HomekitAccessoryType, HomekitCharacteristicType> accessory) {
409 return ((accessory.getValue() == null) || (accessory.getValue() == EMPTY));
413 * check whether characteristic belongs to the specific accessory type.
414 * characteristic with no accessory type mentioned in metadata are considered as candidates for all types.
416 * @param accessoryType accessory type
417 * @param characteristic characteristic
418 * @return true if characteristic belongs to the accessory type.
420 private static boolean belongsToType(HomekitAccessoryType accessoryType,
421 Entry<HomekitAccessoryType, HomekitCharacteristicType> characteristic) {
422 return ((characteristic.getKey() == accessoryType) || (characteristic.getKey() == DUMMY));