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(GARAGE_DOOR_OPENER,
93 new HomekitCharacteristicType[] { CURRENT_DOOR_STATE, TARGET_DOOR_STATE, OBSTRUCTION_STATUS });
94 put(HEATER_COOLER, new HomekitCharacteristicType[] { ACTIVE_STATUS, CURRENT_HEATER_COOLER_STATE,
95 TARGET_HEATER_COOLER_STATE, CURRENT_TEMPERATURE });
96 put(WINDOW, new HomekitCharacteristicType[] { CURRENT_POSITION, TARGET_POSITION, POSITION_STATE });
97 put(DOOR, new HomekitCharacteristicType[] { CURRENT_POSITION, TARGET_POSITION, POSITION_STATE });
101 /** List of service implementation for each accessory type. **/
102 private final static Map<HomekitAccessoryType, Class<? extends AbstractHomekitAccessoryImpl>> SERVICE_IMPL_MAP = new HashMap<HomekitAccessoryType, Class<? extends AbstractHomekitAccessoryImpl>>() {
104 put(LEAK_SENSOR, HomekitLeakSensorImpl.class);
105 put(MOTION_SENSOR, HomekitMotionSensorImpl.class);
106 put(OCCUPANCY_SENSOR, HomekitOccupancySensorImpl.class);
107 put(CONTACT_SENSOR, HomekitContactSensorImpl.class);
108 put(SMOKE_SENSOR, HomekitSmokeSensorImpl.class);
109 put(HUMIDITY_SENSOR, HomekitHumiditySensorImpl.class);
110 put(AIR_QUALITY_SENSOR, HomekitAirQualitySensorImpl.class);
111 put(SWITCH, HomekitSwitchImpl.class);
112 put(CARBON_DIOXIDE_SENSOR, HomekitCarbonDioxideSensorImpl.class);
113 put(CARBON_MONOXIDE_SENSOR, HomekitCarbonMonoxideSensorImpl.class);
114 put(WINDOW_COVERING, HomekitWindowCoveringImpl.class);
115 put(LIGHTBULB, HomekitLightbulbImpl.class);
116 put(FAN, HomekitFanImpl.class);
117 put(LIGHT_SENSOR, HomekitLightSensorImpl.class);
118 put(TEMPERATURE_SENSOR, HomekitTemperatureSensorImpl.class);
119 put(THERMOSTAT, HomekitThermostatImpl.class);
120 put(LOCK, HomekitLockImpl.class);
121 put(VALVE, HomekitValveImpl.class);
122 put(SECURITY_SYSTEM, HomekitSecuritySystemImpl.class);
123 put(OUTLET, HomekitOutletImpl.class);
124 put(SPEAKER, HomekitSpeakerImpl.class);
125 put(GARAGE_DOOR_OPENER, HomekitGarageDoorOpenerImpl.class);
126 put(DOOR, HomekitDoorImpl.class);
127 put(WINDOW, HomekitWindowImpl.class);
128 put(HEATER_COOLER, HomekitHeaterCoolerImpl.class);
133 * creates HomeKit accessory for a openhab item.
135 * @param taggedItem openhab item tagged as HomeKit item
136 * @param metadataRegistry openhab metadata registry required to get item meta information
137 * @param updater OH HomeKit update class that ensure the status sync between OH item and corresponding HomeKit
139 * @param settings OH settings
140 * @return HomeKit accessory
141 * @throws HomekitException exception in case HomeKit accessory could not be created, e.g. due missing mandatory
144 @SuppressWarnings("null")
145 public static HomekitAccessory create(HomekitTaggedItem taggedItem, MetadataRegistry metadataRegistry,
146 HomekitAccessoryUpdater updater, HomekitSettings settings) throws HomekitException {
147 final HomekitAccessoryType accessoryType = taggedItem.getAccessoryType();
148 logger.trace("Constructing {} of accessory type {}", taggedItem.getName(), accessoryType.getTag());
149 final List<HomekitTaggedItem> requiredCharacteristics = getMandatoryCharacteristics(taggedItem,
151 final HomekitCharacteristicType[] mandatoryCharacteristics = MANDATORY_CHARACTERISTICS.get(accessoryType);
152 if ((mandatoryCharacteristics != null) && (requiredCharacteristics.size() < mandatoryCharacteristics.length)) {
153 logger.warn("Accessory of type {} must have following characteristics {}. Found only {}",
154 accessoryType.getTag(), mandatoryCharacteristics, requiredCharacteristics);
155 throw new HomekitException("Missing mandatory characteristics");
157 AbstractHomekitAccessoryImpl accessoryImpl;
159 final @Nullable Class<? extends AbstractHomekitAccessoryImpl> accessoryImplClass = SERVICE_IMPL_MAP
161 if (accessoryImplClass != null) {
162 accessoryImpl = accessoryImplClass
163 .getConstructor(HomekitTaggedItem.class, List.class, HomekitAccessoryUpdater.class,
164 HomekitSettings.class)
165 .newInstance(taggedItem, requiredCharacteristics, updater, settings);
166 addOptionalCharacteristics(taggedItem, accessoryImpl, metadataRegistry);
167 return accessoryImpl;
169 logger.warn("Unsupported HomeKit type: {}", accessoryType.getTag());
170 throw new HomekitException("Unsupported HomeKit type: " + accessoryType);
172 } catch (NoSuchMethodException | IllegalAccessException | InstantiationException
173 | InvocationTargetException e) {
174 logger.warn("Cannot instantiate accessory implementation for accessory {}", accessoryType.getTag(), e);
175 throw new HomekitException("Cannot instantiate accessory implementation for accessory " + accessoryType);
180 * return HomeKit accessory types for a OH item based on meta data
182 * @param item OH item
183 * @param metadataRegistry meta data registry
184 * @return list of HomeKit accessory types and characteristics.
186 public static List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> getAccessoryTypes(Item item,
187 MetadataRegistry metadataRegistry) {
188 final List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> accessories = new ArrayList<>();
189 final @Nullable Metadata metadata = metadataRegistry.get(new MetadataKey(METADATA_KEY, item.getUID()));
190 if (metadata != null) {
191 String[] tags = metadata.getValue().split(",");
192 for (String tag : tags) {
193 final String[] meta = tag.split("\\.");
194 Optional<HomekitAccessoryType> accessoryType = HomekitAccessoryType.valueOfTag(meta[0].trim());
195 if (accessoryType.isPresent()) { // it accessory, check for characteristic
196 HomekitAccessoryType type = accessoryType.get();
197 if (meta.length > 1) {
198 // it has characteristic as well
199 accessories.add(new SimpleEntry<>(type,
200 HomekitCharacteristicType.valueOfTag(meta[1].trim()).orElse(EMPTY)));
201 } else {// it has no characteristic
202 accessories.add(new SimpleEntry<>(type, EMPTY));
204 } else { // it is no accessory, so, maybe it is a characteristic
205 HomekitCharacteristicType.valueOfTag(meta[0].trim())
206 .ifPresent(c -> accessories.add(new SimpleEntry<>(DUMMY, c)));
213 public static @Nullable Map<String, Object> getItemConfiguration(Item item, MetadataRegistry metadataRegistry) {
214 final @Nullable Metadata metadata = metadataRegistry.get(new MetadataKey(METADATA_KEY, item.getUID()));
215 return metadata != null ? metadata.getConfiguration() : null;
219 * return list of HomeKit relevant groups linked to an accessory
221 * @param item OH item
222 * @param itemRegistry item registry
223 * @param metadataRegistry metadata registry
224 * @return list of relevant group items
226 public static List<GroupItem> getAccessoryGroups(Item item, ItemRegistry itemRegistry,
227 MetadataRegistry metadataRegistry) {
228 return item.getGroupNames().stream().flatMap(name -> {
229 final @Nullable Item groupItem = itemRegistry.get(name);
230 if ((groupItem instanceof GroupItem) && ((GroupItem) groupItem).getBaseItem() == null) {
231 return Stream.of((GroupItem) groupItem);
233 return Stream.empty();
235 }).filter(groupItem -> !getAccessoryTypes(groupItem, metadataRegistry).isEmpty()).collect(Collectors.toList());
239 * collect all mandatory characteristics for a given tagged item, e.g. collect all mandatory HomeKit items from a
242 * @param taggedItem HomeKit tagged item
243 * @param metadataRegistry meta data registry
244 * @return list of mandatory
246 private static List<HomekitTaggedItem> getMandatoryCharacteristics(HomekitTaggedItem taggedItem,
247 MetadataRegistry metadataRegistry) {
248 List<HomekitTaggedItem> collectedCharacteristics = new ArrayList<>();
249 if (taggedItem.isGroup()) {
250 for (Item item : ((GroupItem) taggedItem.getItem()).getAllMembers()) {
251 addMandatoryCharacteristics(taggedItem, collectedCharacteristics, item, metadataRegistry);
254 addMandatoryCharacteristics(taggedItem, collectedCharacteristics, taggedItem.getItem(), metadataRegistry);
256 logger.trace("Mandatory characteristics for item {} characteristics {}", taggedItem.getName(),
257 collectedCharacteristics);
258 return collectedCharacteristics;
262 * add mandatory HomeKit items for a given main item to a list of characteristics.
263 * Main item is use only to determine, which characteristics are mandatory.
264 * The characteristics are added to item.
265 * e.g. mainItem could be a group tagged as "thermostat" and item could be item linked to the group and marked as
268 * @param mainItem main item
269 * @param characteristics list of characteristics
270 * @param item current item
271 * @param metadataRegistry meta date registry
273 private static void addMandatoryCharacteristics(HomekitTaggedItem mainItem, List<HomekitTaggedItem> characteristics,
274 Item item, MetadataRegistry metadataRegistry) {
275 // get list of mandatory characteristics
276 HomekitCharacteristicType[] mandatoryCharacteristics = MANDATORY_CHARACTERISTICS
277 .get(mainItem.getAccessoryType());
278 if ((mandatoryCharacteristics == null) || (mandatoryCharacteristics.length == 0)) {
279 // no mandatory characteristics linked to accessory type of mainItem. we are done
282 // check whether we adding characteristic to the main item, and if yes, use existing item proxy.
283 // if we adding no to the main item (typical for groups), create new proxy item.
284 final HomekitOHItemProxy itemProxy = mainItem.getItem().equals(item) ? mainItem.getProxyItem()
285 : new HomekitOHItemProxy(item);
286 // an item can have several tags, e.g. "ActiveStatus, InUse". we iterate here over all his tags
287 for (Entry<HomekitAccessoryType, HomekitCharacteristicType> accessory : getAccessoryTypes(item,
289 // if the item has only accessory tag, e.g. TemperatureSensor,
290 // the we will link all mandatory characteristic to this item,
291 // e.g. we will link CurrentTemperature in case of TemperatureSensor.
292 if (isRootAccessory(accessory)) {
293 Arrays.stream(mandatoryCharacteristics)
294 .forEach(c -> characteristics.add(new HomekitTaggedItem(itemProxy, accessory.getKey(), c,
295 mainItem.isGroup() ? (GroupItem) mainItem.getItem() : null,
296 HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry))));
298 // item has characteristic tag on it, so, adding it as that characteristic.
300 final HomekitCharacteristicType characteristic = accessory.getValue();
302 // check whether it is a mandatory characteristic. optional will be added later by another method.
303 if (isMandatoryCharacteristic(mainItem.getAccessoryType(), characteristic)) {
304 characteristics.add(new HomekitTaggedItem(itemProxy, accessory.getKey(), characteristic,
305 mainItem.isGroup() ? (GroupItem) mainItem.getItem() : null,
306 HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry)));
313 * add optional characteristic for given accessory.
315 * @param taggedItem main item
316 * @param accessory accessory
317 * @param metadataRegistry metadata registry
319 private static void addOptionalCharacteristics(HomekitTaggedItem taggedItem, AbstractHomekitAccessoryImpl accessory,
320 MetadataRegistry metadataRegistry) {
321 Map<HomekitCharacteristicType, GenericItem> characteristics = getOptionalCharacteristics(
322 accessory.getRootAccessory(), metadataRegistry);
323 Service service = accessory.getPrimaryService();
324 HashMap<String, HomekitOHItemProxy> proxyItems = new HashMap<>();
325 proxyItems.put(taggedItem.getItem().getUID(), taggedItem.getProxyItem());
326 // an accessory can have multiple optional characteristics. iterate over them.
327 characteristics.forEach((type, item) -> {
329 // check whether a proxyItem already exists, if not create one.
330 final HomekitOHItemProxy proxyItem = Objects
331 .requireNonNull(proxyItems.computeIfAbsent(item.getUID(), k -> new HomekitOHItemProxy(item)));
332 final HomekitTaggedItem optionalItem = new HomekitTaggedItem(proxyItem,
333 accessory.getRootAccessory().getAccessoryType(), type,
334 accessory.getRootAccessory().getRootDeviceGroupItem(),
335 getItemConfiguration(item, metadataRegistry));
336 final Characteristic characteristic = HomekitCharacteristicFactory.createCharacteristic(optionalItem,
337 accessory.getUpdater());
338 // find the corresponding add method at service and call it.
339 service.getClass().getMethod("addOptionalCharacteristic", characteristic.getClass()).invoke(service,
341 accessory.addCharacteristic(optionalItem);
342 } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | HomekitException e) {
343 logger.warn("Unsupported optional HomeKit characteristic: service type {}, characteristic type {}",
344 service.getType(), type.getTag());
350 * collect optional HomeKit characteristics for a OH item.
352 * @param taggedItem main OH item
353 * @param metadataRegistry OH metadata registry
354 * @return a map with characteristics and corresponding OH items
356 private static Map<HomekitCharacteristicType, GenericItem> getOptionalCharacteristics(HomekitTaggedItem taggedItem,
357 MetadataRegistry metadataRegistry) {
358 Map<HomekitCharacteristicType, GenericItem> characteristicItems = new HashMap<>();
359 if (taggedItem.isGroup()) {
360 GroupItem groupItem = (GroupItem) taggedItem.getItem();
361 groupItem.getMembers().forEach(item -> getAccessoryTypes(item, metadataRegistry).stream()
362 .filter(c -> !isRootAccessory(c))
363 .filter(c -> !isMandatoryCharacteristic(taggedItem.getAccessoryType(), c.getValue()))
364 .forEach(characteristic -> characteristicItems.put(characteristic.getValue(), (GenericItem) item)));
366 getAccessoryTypes(taggedItem.getItem(), metadataRegistry).stream().filter(c -> !isRootAccessory(c))
367 .filter(c -> !isMandatoryCharacteristic(taggedItem.getAccessoryType(), c.getValue()))
368 .forEach(characteristic -> characteristicItems.put(characteristic.getValue(),
369 (GenericItem) taggedItem.getItem()));
371 logger.trace("Optional characteristics for item {} characteristics {}", taggedItem.getName(),
372 characteristicItems);
373 return Collections.unmodifiableMap(characteristicItems);
377 * return true is characteristic is a mandatory characteristic for the accessory.
379 * @param accessory accessory
380 * @param characteristic characteristic
381 * @return true if characteristic is mandatory, false if not mandatory
383 private static boolean isMandatoryCharacteristic(HomekitAccessoryType accessory,
384 HomekitCharacteristicType characteristic) {
385 return MANDATORY_CHARACTERISTICS.containsKey(accessory)
386 && Arrays.asList(MANDATORY_CHARACTERISTICS.get(accessory)).contains(characteristic);
390 * check whether accessory is root accessory, i.e. without characteristic tag.
392 * @param accessory accessory
393 * @return true if accessory has not characteristic.
395 private static boolean isRootAccessory(Entry<HomekitAccessoryType, HomekitCharacteristicType> accessory) {
396 return ((accessory.getValue() == null) || (accessory.getValue() == EMPTY));