]> git.basschouten.com Git - openhab-addons.git/blob
17262aa4cbab13378563e92eb201ef6a3b99dea8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.io.homekit.internal.accessories;
14
15 import static org.openhab.io.homekit.internal.HomekitAccessoryType.*;
16 import static org.openhab.io.homekit.internal.HomekitCharacteristicType.*;
17
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.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Objects;
29 import java.util.Optional;
30 import java.util.Set;
31 import java.util.TreeMap;
32 import java.util.stream.Collectors;
33 import java.util.stream.Stream;
34
35 import org.eclipse.jdt.annotation.NonNullByDefault;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.openhab.core.items.GenericItem;
38 import org.openhab.core.items.GroupItem;
39 import org.openhab.core.items.Item;
40 import org.openhab.core.items.ItemRegistry;
41 import org.openhab.core.items.Metadata;
42 import org.openhab.core.items.MetadataKey;
43 import org.openhab.core.items.MetadataRegistry;
44 import org.openhab.io.homekit.internal.HomekitAccessoryType;
45 import org.openhab.io.homekit.internal.HomekitAccessoryUpdater;
46 import org.openhab.io.homekit.internal.HomekitCharacteristicType;
47 import org.openhab.io.homekit.internal.HomekitException;
48 import org.openhab.io.homekit.internal.HomekitOHItemProxy;
49 import org.openhab.io.homekit.internal.HomekitSettings;
50 import org.openhab.io.homekit.internal.HomekitTaggedItem;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 import io.github.hapjava.characteristics.Characteristic;
55 import io.github.hapjava.characteristics.impl.common.NameCharacteristic;
56
57 /**
58  * Creates a HomekitAccessory for a given HomekitTaggedItem.
59  *
60  * @author Andy Lintner - Initial contribution
61  * @author Eugen Freiter - refactoring for optional characteristics
62  */
63 @NonNullByDefault
64 public class HomekitAccessoryFactory {
65     private static final Logger LOGGER = LoggerFactory.getLogger(HomekitAccessoryFactory.class);
66     public static final String METADATA_KEY = "homekit"; // prefix for HomeKit meta information in items.xml
67
68     /** List of mandatory attributes for each accessory type. **/
69     private static final Map<HomekitAccessoryType, HomekitCharacteristicType[]> MANDATORY_CHARACTERISTICS = new HashMap<HomekitAccessoryType, HomekitCharacteristicType[]>() {
70         {
71             put(ACCESSORY_GROUP, new HomekitCharacteristicType[] {});
72             put(LEAK_SENSOR, new HomekitCharacteristicType[] { LEAK_DETECTED_STATE });
73             put(MOTION_SENSOR, new HomekitCharacteristicType[] { MOTION_DETECTED_STATE });
74             put(OCCUPANCY_SENSOR, new HomekitCharacteristicType[] { OCCUPANCY_DETECTED_STATE });
75             put(CONTACT_SENSOR, new HomekitCharacteristicType[] { CONTACT_SENSOR_STATE });
76             put(SMOKE_SENSOR, new HomekitCharacteristicType[] { SMOKE_DETECTED_STATE });
77             put(HUMIDITY_SENSOR, new HomekitCharacteristicType[] { RELATIVE_HUMIDITY });
78             put(AIR_QUALITY_SENSOR, new HomekitCharacteristicType[] { AIR_QUALITY });
79             put(SWITCH, new HomekitCharacteristicType[] { ON_STATE });
80             put(CARBON_DIOXIDE_SENSOR, new HomekitCharacteristicType[] { CARBON_DIOXIDE_DETECTED_STATE });
81             put(CARBON_MONOXIDE_SENSOR, new HomekitCharacteristicType[] { CARBON_MONOXIDE_DETECTED_STATE });
82             put(WINDOW_COVERING, new HomekitCharacteristicType[] { TARGET_POSITION, CURRENT_POSITION, POSITION_STATE });
83             put(LIGHTBULB, new HomekitCharacteristicType[] { ON_STATE });
84             put(BASIC_FAN, new HomekitCharacteristicType[] { ON_STATE });
85             put(FAN, new HomekitCharacteristicType[] { ACTIVE_STATUS });
86             put(LIGHT_SENSOR, new HomekitCharacteristicType[] { LIGHT_LEVEL });
87             put(TEMPERATURE_SENSOR, new HomekitCharacteristicType[] { CURRENT_TEMPERATURE });
88             put(THERMOSTAT, new HomekitCharacteristicType[] { CURRENT_HEATING_COOLING_STATE,
89                     TARGET_HEATING_COOLING_STATE, CURRENT_TEMPERATURE, TARGET_TEMPERATURE });
90             put(LOCK, new HomekitCharacteristicType[] { LOCK_CURRENT_STATE, LOCK_TARGET_STATE });
91             put(VALVE, new HomekitCharacteristicType[] { ACTIVE_STATUS, INUSE_STATUS });
92             put(SECURITY_SYSTEM,
93                     new HomekitCharacteristicType[] { SECURITY_SYSTEM_CURRENT_STATE, SECURITY_SYSTEM_TARGET_STATE });
94             put(OUTLET, new HomekitCharacteristicType[] { ON_STATE, INUSE_STATUS });
95             put(SPEAKER, new HomekitCharacteristicType[] { MUTE });
96             put(SMART_SPEAKER, new HomekitCharacteristicType[] { CURRENT_MEDIA_STATE, TARGET_MEDIA_STATE });
97             put(GARAGE_DOOR_OPENER,
98                     new HomekitCharacteristicType[] { CURRENT_DOOR_STATE, TARGET_DOOR_STATE, OBSTRUCTION_STATUS });
99             put(HEATER_COOLER, new HomekitCharacteristicType[] { ACTIVE_STATUS, CURRENT_HEATER_COOLER_STATE,
100                     TARGET_HEATER_COOLER_STATE, CURRENT_TEMPERATURE });
101             put(WINDOW, new HomekitCharacteristicType[] { CURRENT_POSITION, TARGET_POSITION, POSITION_STATE });
102             put(DOOR, new HomekitCharacteristicType[] { CURRENT_POSITION, TARGET_POSITION, POSITION_STATE });
103             put(BATTERY, new HomekitCharacteristicType[] { BATTERY_LEVEL, BATTERY_LOW_STATUS });
104             put(FILTER_MAINTENANCE, new HomekitCharacteristicType[] { FILTER_CHANGE_INDICATION });
105             put(SLAT, new HomekitCharacteristicType[] { CURRENT_SLAT_STATE });
106             put(FAUCET, new HomekitCharacteristicType[] { ACTIVE_STATUS });
107             put(MICROPHONE, new HomekitCharacteristicType[] { MUTE });
108             put(TELEVISION, new HomekitCharacteristicType[] { ACTIVE });
109             put(INPUT_SOURCE, new HomekitCharacteristicType[] {});
110             put(TELEVISION_SPEAKER, new HomekitCharacteristicType[] { MUTE });
111             put(IRRIGATION_SYSTEM, new HomekitCharacteristicType[] { ACTIVE, INUSE_STATUS, PROGRAM_MODE });
112         }
113     };
114
115     /** List of service implementation for each accessory type. **/
116     private static final Map<HomekitAccessoryType, Class<? extends AbstractHomekitAccessoryImpl>> SERVICE_IMPL_MAP = new HashMap<HomekitAccessoryType, Class<? extends AbstractHomekitAccessoryImpl>>() {
117         {
118             put(ACCESSORY_GROUP, HomekitAccessoryGroupImpl.class);
119             put(LEAK_SENSOR, HomekitLeakSensorImpl.class);
120             put(MOTION_SENSOR, HomekitMotionSensorImpl.class);
121             put(OCCUPANCY_SENSOR, HomekitOccupancySensorImpl.class);
122             put(CONTACT_SENSOR, HomekitContactSensorImpl.class);
123             put(SMOKE_SENSOR, HomekitSmokeSensorImpl.class);
124             put(HUMIDITY_SENSOR, HomekitHumiditySensorImpl.class);
125             put(AIR_QUALITY_SENSOR, HomekitAirQualitySensorImpl.class);
126             put(SWITCH, HomekitSwitchImpl.class);
127             put(CARBON_DIOXIDE_SENSOR, HomekitCarbonDioxideSensorImpl.class);
128             put(CARBON_MONOXIDE_SENSOR, HomekitCarbonMonoxideSensorImpl.class);
129             put(WINDOW_COVERING, HomekitWindowCoveringImpl.class);
130             put(LIGHTBULB, HomekitLightbulbImpl.class);
131             put(BASIC_FAN, HomekitBasicFanImpl.class);
132             put(FAN, HomekitFanImpl.class);
133             put(LIGHT_SENSOR, HomekitLightSensorImpl.class);
134             put(TEMPERATURE_SENSOR, HomekitTemperatureSensorImpl.class);
135             put(THERMOSTAT, HomekitThermostatImpl.class);
136             put(LOCK, HomekitLockImpl.class);
137             put(VALVE, HomekitValveImpl.class);
138             put(SECURITY_SYSTEM, HomekitSecuritySystemImpl.class);
139             put(OUTLET, HomekitOutletImpl.class);
140             put(SPEAKER, HomekitSpeakerImpl.class);
141             put(SMART_SPEAKER, HomekitSmartSpeakerImpl.class);
142             put(GARAGE_DOOR_OPENER, HomekitGarageDoorOpenerImpl.class);
143             put(DOOR, HomekitDoorImpl.class);
144             put(WINDOW, HomekitWindowImpl.class);
145             put(HEATER_COOLER, HomekitHeaterCoolerImpl.class);
146             put(BATTERY, HomekitBatteryImpl.class);
147             put(FILTER_MAINTENANCE, HomekitFilterMaintenanceImpl.class);
148             put(SLAT, HomekitSlatImpl.class);
149             put(FAUCET, HomekitFaucetImpl.class);
150             put(MICROPHONE, HomekitMicrophoneImpl.class);
151             put(TELEVISION, HomekitTelevisionImpl.class);
152             put(INPUT_SOURCE, HomekitInputSourceImpl.class);
153             put(TELEVISION_SPEAKER, HomekitTelevisionSpeakerImpl.class);
154             put(IRRIGATION_SYSTEM, HomekitIrrigationSystemImpl.class);
155         }
156     };
157
158     private static List<HomekitCharacteristicType> getRequiredCharacteristics(HomekitTaggedItem taggedItem) {
159         final List<HomekitCharacteristicType> characteristics = new ArrayList<>();
160         if (MANDATORY_CHARACTERISTICS.containsKey(taggedItem.getAccessoryType())) {
161             characteristics.addAll(Arrays.asList(MANDATORY_CHARACTERISTICS.get(taggedItem.getAccessoryType())));
162         }
163         if (taggedItem.getAccessoryType() == BATTERY) {
164             final boolean isChargeable = taggedItem.getConfigurationAsBoolean(HomekitBatteryImpl.BATTERY_TYPE, false);
165             if (isChargeable) {
166                 characteristics.add(BATTERY_CHARGING_STATE);
167             }
168         }
169         return characteristics;
170     }
171
172     /**
173      * creates HomeKit accessory for an openhab item.
174      *
175      * @param taggedItem openhab item tagged as HomeKit item
176      * @param metadataRegistry openhab metadata registry required to get item meta information
177      * @param updater OH HomeKit update class that ensure the status sync between OH item and corresponding HomeKit
178      *            characteristic.
179      * @param settings OH settings
180      * @return HomeKit accessory
181      * @throws HomekitException exception in case HomeKit accessory could not be created, e.g. due missing mandatory
182      *             characteristic
183      */
184     public static AbstractHomekitAccessoryImpl create(HomekitTaggedItem taggedItem, MetadataRegistry metadataRegistry,
185             HomekitAccessoryUpdater updater, HomekitSettings settings) throws HomekitException {
186         Set<HomekitTaggedItem> ancestorServices = new HashSet<>();
187         return create(taggedItem, metadataRegistry, updater, settings, ancestorServices);
188     }
189
190     @SuppressWarnings("null")
191     private static AbstractHomekitAccessoryImpl create(HomekitTaggedItem taggedItem, MetadataRegistry metadataRegistry,
192             HomekitAccessoryUpdater updater, HomekitSettings settings, Set<HomekitTaggedItem> ancestorServices)
193             throws HomekitException {
194         final HomekitAccessoryType accessoryType = taggedItem.getAccessoryType();
195         LOGGER.trace("Constructing {} of accessory type {}", taggedItem.getName(), accessoryType.getTag());
196         final List<HomekitTaggedItem> foundCharacteristics = getMandatoryCharacteristicsFromItem(taggedItem,
197                 metadataRegistry);
198         final List<HomekitCharacteristicType> mandatoryCharacteristics = getRequiredCharacteristics(taggedItem);
199         if (foundCharacteristics.size() < mandatoryCharacteristics.size()) {
200             LOGGER.warn("Accessory of type {} must have following characteristics {}. Found only {}",
201                     accessoryType.getTag(), mandatoryCharacteristics, foundCharacteristics);
202             throw new HomekitException("Missing mandatory characteristics");
203         }
204         AbstractHomekitAccessoryImpl accessoryImpl;
205         try {
206             final @Nullable Class<? extends AbstractHomekitAccessoryImpl> accessoryImplClass = SERVICE_IMPL_MAP
207                     .get(accessoryType);
208             if (accessoryImplClass != null) {
209                 if (ancestorServices.contains(taggedItem)) {
210                     LOGGER.warn("Item {} has already been created. Perhaps you have circular Homekit accessory groups?",
211                             taggedItem.getName());
212                     throw new HomekitException("Circular accessory references");
213                 }
214                 ancestorServices.add(taggedItem);
215                 accessoryImpl = accessoryImplClass.getConstructor(HomekitTaggedItem.class, List.class,
216                         HomekitAccessoryUpdater.class, HomekitSettings.class)
217                         .newInstance(taggedItem, foundCharacteristics, updater, settings);
218                 addOptionalCharacteristics(taggedItem, accessoryImpl, metadataRegistry);
219                 addOptionalMetadataCharacteristics(taggedItem, accessoryImpl);
220                 accessoryImpl.init();
221                 addLinkedServices(taggedItem, accessoryImpl, metadataRegistry, updater, settings, ancestorServices);
222                 return accessoryImpl;
223             } else {
224                 LOGGER.warn("Unsupported HomeKit type: {}", accessoryType.getTag());
225                 throw new HomekitException("Unsupported HomeKit type: " + accessoryType);
226             }
227         } catch (NoSuchMethodException | IllegalAccessException | InstantiationException
228                 | InvocationTargetException e) {
229             LOGGER.warn("Cannot instantiate accessory implementation for accessory {}", accessoryType.getTag(), e);
230             throw new HomekitException("Cannot instantiate accessory implementation for accessory " + accessoryType);
231         }
232     }
233
234     /**
235      * return HomeKit accessory types for an OH item based on meta data
236      *
237      * @param item OH item
238      * @param metadataRegistry meta data registry
239      * @return list of HomeKit accessory types and characteristics.
240      */
241     public static List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> getAccessoryTypes(Item item,
242             MetadataRegistry metadataRegistry) {
243         final List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> accessories = new ArrayList<>();
244         final @Nullable Metadata metadata = metadataRegistry.get(new MetadataKey(METADATA_KEY, item.getUID()));
245         if (metadata != null) {
246             String[] tags = metadata.getValue().split(",");
247             for (String tag : tags) {
248                 final String[] meta = tag.split("\\.");
249                 Optional<HomekitAccessoryType> accessoryType = HomekitAccessoryType.valueOfTag(meta[0].trim());
250                 if (accessoryType.isPresent()) { // it accessory, check for characteristic
251                     HomekitAccessoryType type = accessoryType.get();
252                     if (meta.length > 1) {
253                         // it has characteristic as well
254                         accessories.add(new SimpleEntry<>(type,
255                                 HomekitCharacteristicType.valueOfTag(meta[1].trim()).orElse(EMPTY)));
256                     } else {// it has no characteristic
257                         accessories.add(new SimpleEntry<>(type, EMPTY));
258                     }
259                 } else { // it is no accessory, so, maybe it is a characteristic
260                     HomekitCharacteristicType.valueOfTag(meta[0].trim())
261                             .ifPresent(c -> accessories.add(new SimpleEntry<>(DUMMY, c)));
262                 }
263             }
264         }
265         return accessories;
266     }
267
268     public static @Nullable Map<String, Object> getItemConfiguration(Item item, MetadataRegistry metadataRegistry) {
269         final @Nullable Metadata metadata = metadataRegistry.get(new MetadataKey(METADATA_KEY, item.getUID()));
270         return metadata != null ? metadata.getConfiguration() : null;
271     }
272
273     /**
274      * return list of HomeKit relevant groups linked to an accessory
275      *
276      * @param item OH item
277      * @param itemRegistry item registry
278      * @param metadataRegistry metadata registry
279      * @return list of relevant group items
280      */
281     public static List<GroupItem> getAccessoryGroups(Item item, ItemRegistry itemRegistry,
282             MetadataRegistry metadataRegistry) {
283         return item.getGroupNames().stream().flatMap(name -> {
284             final @Nullable Item itemFromRegistry = itemRegistry.get(name);
285             if (itemFromRegistry instanceof GroupItem groupItem) {
286                 return Stream.of(groupItem);
287             } else {
288                 return Stream.empty();
289             }
290         }).filter(groupItem -> !getAccessoryTypes(groupItem, metadataRegistry).isEmpty()).collect(Collectors.toList());
291     }
292
293     /**
294      * collect all mandatory characteristics for a given tagged item, e.g. collect all mandatory HomeKit items from a
295      * GroupItem
296      *
297      * @param taggedItem HomeKit tagged item
298      * @param metadataRegistry meta data registry
299      * @return list of mandatory
300      */
301     private static List<HomekitTaggedItem> getMandatoryCharacteristicsFromItem(HomekitTaggedItem taggedItem,
302             MetadataRegistry metadataRegistry) {
303         List<HomekitTaggedItem> collectedCharacteristics = new ArrayList<>();
304         if (taggedItem.isGroup()) {
305             for (Item item : ((GroupItem) taggedItem.getItem()).getMembers()) {
306                 addMandatoryCharacteristics(taggedItem, collectedCharacteristics, item, metadataRegistry);
307             }
308         } else {
309             addMandatoryCharacteristics(taggedItem, collectedCharacteristics, taggedItem.getItem(), metadataRegistry);
310         }
311         LOGGER.trace("Mandatory characteristics: {}", collectedCharacteristics);
312         return collectedCharacteristics;
313     }
314
315     /**
316      * add mandatory HomeKit items for a given main item to a list of characteristics.
317      * Main item is use only to determine, which characteristics are mandatory.
318      * The characteristics are added to item.
319      * e.g. mainItem could be a group tagged as "thermostat" and item could be item linked to the group and marked as
320      * TargetTemperature
321      *
322      * @param mainItem main item
323      * @param characteristics list of characteristics
324      * @param item current item
325      * @param metadataRegistry meta date registry
326      */
327     private static void addMandatoryCharacteristics(HomekitTaggedItem mainItem, List<HomekitTaggedItem> characteristics,
328             Item item, MetadataRegistry metadataRegistry) {
329         // get list of mandatory characteristics
330         List<HomekitCharacteristicType> mandatoryCharacteristics = getRequiredCharacteristics(mainItem);
331         if (mandatoryCharacteristics.isEmpty()) {
332             // no mandatory characteristics linked to accessory type of mainItem. we are done
333             return;
334         }
335         // check whether we are adding characteristic to the main item, and if yes, use existing item proxy.
336         // if we are adding not to the main item (typical for groups), create new proxy item.
337         final HomekitOHItemProxy itemProxy = mainItem.getItem().equals(item) ? mainItem.getProxyItem()
338                 : new HomekitOHItemProxy(item);
339         // an item can have several tags, e.g. "ActiveStatus, InUse". we iterate here over all his tags
340         for (Entry<HomekitAccessoryType, HomekitCharacteristicType> accessory : getAccessoryTypes(item,
341                 metadataRegistry)) {
342             // if the item has only accessory tag, e.g. TemperatureSensor,
343             // then we will link all mandatory characteristic to this item,
344             // e.g. we will link CurrentTemperature in case of TemperatureSensor.
345             // Note that accessories that are members of other accessories do _not_
346             // count - we're already constructing another root accessory.
347             if (isRootAccessory(accessory) && mainItem.getItem().equals(item)) {
348                 mandatoryCharacteristics.forEach(c -> characteristics.add(new HomekitTaggedItem(itemProxy,
349                         accessory.getKey(), c, mainItem.isGroup() ? (GroupItem) mainItem.getItem() : null,
350                         HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry))));
351             } else {
352                 // item has characteristic tag on it, so, adding it as that characteristic.
353
354                 final HomekitCharacteristicType characteristic = accessory.getValue();
355
356                 // check whether it is a mandatory characteristic. optional will be added later by another method.
357                 if (belongsToType(mainItem.getAccessoryType(), accessory)
358                         && isMandatoryCharacteristic(mainItem, characteristic)) {
359                     characteristics.add(new HomekitTaggedItem(itemProxy, accessory.getKey(), characteristic,
360                             mainItem.isGroup() ? (GroupItem) mainItem.getItem() : null,
361                             HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry)));
362                 }
363             }
364         }
365     }
366
367     /**
368      * add optional characteristics for given accessory.
369      *
370      * @param taggedItem main item
371      * @param accessory accessory
372      * @param metadataRegistry metadata registry
373      */
374     private static void addOptionalCharacteristics(HomekitTaggedItem taggedItem, AbstractHomekitAccessoryImpl accessory,
375             MetadataRegistry metadataRegistry) {
376         Map<HomekitCharacteristicType, GenericItem> characteristics = getOptionalCharacteristics(
377                 accessory.getRootAccessory(), metadataRegistry);
378         HashMap<String, HomekitOHItemProxy> proxyItems = new HashMap<>();
379         proxyItems.put(taggedItem.getItem().getUID(), taggedItem.getProxyItem());
380         // an accessory can have multiple optional characteristics. iterate over them.
381         characteristics.forEach((type, item) -> {
382             try {
383                 // check whether a proxyItem already exists, if not create one.
384                 final HomekitOHItemProxy proxyItem = Objects
385                         .requireNonNull(proxyItems.computeIfAbsent(item.getUID(), k -> new HomekitOHItemProxy(item)));
386                 final HomekitTaggedItem optionalItem = new HomekitTaggedItem(proxyItem,
387                         accessory.getRootAccessory().getAccessoryType(), type,
388                         accessory.getRootAccessory().getRootDeviceGroupItem(),
389                         getItemConfiguration(item, metadataRegistry));
390                 final Characteristic characteristic = HomekitCharacteristicFactory.createCharacteristic(optionalItem,
391                         accessory.getUpdater());
392                 accessory.addCharacteristic(optionalItem, characteristic);
393             } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | HomekitException e) {
394                 LOGGER.warn("Unsupported optional HomeKit characteristic: type {}, characteristic type {}",
395                         accessory.getPrimaryService(), type.getTag());
396             }
397         });
398     }
399
400     /**
401      * add optional characteristics for given accessory from metadata
402      *
403      * @param taggedItem main item
404      * @param accessory accessory
405      */
406     private static void addOptionalMetadataCharacteristics(HomekitTaggedItem taggedItem,
407             AbstractHomekitAccessoryImpl accessory)
408             throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, HomekitException {
409         // Check every metadata key looking for a characteristics we can create
410         var config = taggedItem.getConfiguration();
411         if (config == null) {
412             return;
413         }
414         for (var entry : config.entrySet().stream().sorted((lhs, rhs) -> lhs.getKey().compareTo(rhs.getKey()))
415                 .collect(Collectors.toList())) {
416             var characteristic = HomekitMetadataCharacteristicFactory.createCharacteristic(entry.getKey(),
417                     entry.getValue());
418             if (characteristic.isPresent()) {
419                 accessory.addCharacteristic(characteristic.get());
420             }
421         }
422     }
423
424     /**
425      * creates HomeKit services for an openhab item that are members of this group item.
426      *
427      * @param taggedItem openhab item tagged as HomeKit item
428      * @param AbstractHomekitAccessoryImpl the accessory to add services to
429      * @param metadataRegistry openhab metadata registry required to get item meta information
430      * @param updater OH HomeKit update class that ensure the status sync between OH item and corresponding HomeKit
431      *            characteristic.
432      * @param settings OH settings
433      * @param ancestorServices set of all accessories/services under the same root accessory, for
434      *            for preventing circular references
435      * @throws HomekitException exception in case HomeKit accessory could not be created, e.g. due missing mandatory
436      *             characteristic
437      */
438     private static void addLinkedServices(HomekitTaggedItem taggedItem, AbstractHomekitAccessoryImpl accessory,
439             MetadataRegistry metadataRegistry, HomekitAccessoryUpdater updater, HomekitSettings settings,
440             Set<HomekitTaggedItem> ancestorServices) throws HomekitException {
441         final var item = taggedItem.getItem();
442         if (!(item instanceof GroupItem)) {
443             return;
444         }
445
446         for (var groupMember : ((GroupItem) item).getMembers().stream()
447                 .sorted((lhs, rhs) -> lhs.getName().compareTo(rhs.getName())).collect(Collectors.toList())) {
448             final var characteristicTypes = getAccessoryTypes(groupMember, metadataRegistry);
449             var accessoryTypes = characteristicTypes.stream().filter(HomekitAccessoryFactory::isRootAccessory)
450                     .collect(Collectors.toList());
451
452             LOGGER.trace("accessory types for {} are {}", groupMember.getName(), accessoryTypes);
453             if (accessoryTypes.isEmpty()) {
454                 continue;
455             }
456
457             if (accessoryTypes.size() > 1) {
458                 LOGGER.warn("Item {} is a HomeKit sub-accessory, but multiple accessory types are not allowed.",
459                         groupMember.getName());
460                 continue;
461             }
462
463             final @Nullable Map<String, Object> itemConfiguration = getItemConfiguration(groupMember, metadataRegistry);
464
465             final var accessoryType = accessoryTypes.iterator().next().getKey();
466             LOGGER.trace("Item {} is a HomeKit sub-accessory of type {}.", groupMember.getName(), accessoryType);
467             final var itemProxy = new HomekitOHItemProxy(groupMember);
468             final var subTaggedItem = new HomekitTaggedItem(itemProxy, accessoryType, itemConfiguration);
469             final var subAccessory = create(subTaggedItem, metadataRegistry, updater, settings, ancestorServices);
470
471             try {
472                 subAccessory.addCharacteristic(new NameCharacteristic(() -> subAccessory.getName()));
473             } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
474                 // This should never happen; all services should support NameCharacteristic as an optional
475                 // Characteristic.
476                 // If HAP-Java defined a service that doesn't support addOptionalCharacteristic(NameCharacteristic),
477                 // Then it's a bug there, and we're just going to ignore the exception here.
478             }
479
480             if (subAccessory.isLinkable(accessory)) {
481                 accessory.getPrimaryService().addLinkedService(subAccessory.getPrimaryService());
482             } else {
483                 accessory.getServices().add(subAccessory.getPrimaryService());
484             }
485         }
486     }
487
488     /**
489      * collect optional HomeKit characteristics for a OH item.
490      *
491      * @param taggedItem main OH item
492      * @param metadataRegistry OH metadata registry
493      * @return a map with characteristics and corresponding OH items
494      */
495     private static Map<HomekitCharacteristicType, GenericItem> getOptionalCharacteristics(HomekitTaggedItem taggedItem,
496             MetadataRegistry metadataRegistry) {
497         Map<HomekitCharacteristicType, GenericItem> characteristicItems = new TreeMap<>();
498         if (taggedItem.isGroup()) {
499             GroupItem groupItem = (GroupItem) taggedItem.getItem();
500             groupItem.getMembers().forEach(item -> getAccessoryTypes(item, metadataRegistry).stream()
501                     .filter(c -> !isRootAccessory(c)).filter(c -> belongsToType(taggedItem.getAccessoryType(), c))
502                     .filter(c -> !isMandatoryCharacteristic(taggedItem, c.getValue()))
503                     .forEach(characteristic -> characteristicItems.put(characteristic.getValue(), (GenericItem) item)));
504         } else {
505             getAccessoryTypes(taggedItem.getItem(), metadataRegistry).stream().filter(c -> !isRootAccessory(c))
506                     .filter(c -> !isMandatoryCharacteristic(taggedItem, c.getValue()))
507                     .forEach(characteristic -> characteristicItems.put(characteristic.getValue(),
508                             (GenericItem) taggedItem.getItem()));
509         }
510         LOGGER.trace("Optional characteristics for item {}: {}", taggedItem.getName(), characteristicItems.values());
511         return Collections.unmodifiableMap(characteristicItems);
512     }
513
514     /**
515      * return true is characteristic is a mandatory characteristic for the accessory.
516      *
517      * @param item item
518      * @param characteristic characteristic
519      * @return true if characteristic is mandatory, false if not mandatory
520      */
521     private static boolean isMandatoryCharacteristic(HomekitTaggedItem item, HomekitCharacteristicType characteristic) {
522         return MANDATORY_CHARACTERISTICS.containsKey(item.getAccessoryType())
523                 && getRequiredCharacteristics(item).contains(characteristic);
524     }
525
526     /**
527      * check whether accessory is root accessory, i.e. without characteristic tag.
528      *
529      * @param accessory accessory
530      * @return true if accessory has not characteristic.
531      */
532     private static boolean isRootAccessory(Entry<HomekitAccessoryType, HomekitCharacteristicType> accessory) {
533         return ((accessory.getValue() == null) || (accessory.getValue() == EMPTY));
534     }
535
536     /**
537      * check whether characteristic belongs to the specific accessory type.
538      * characteristic with no accessory type mentioned in metadata are considered as candidates for all types.
539      *
540      * @param accessoryType accessory type
541      * @param characteristic characteristic
542      * @return true if characteristic belongs to the accessory type.
543      */
544     private static boolean belongsToType(HomekitAccessoryType accessoryType,
545             Entry<HomekitAccessoryType, HomekitCharacteristicType> characteristic) {
546         return ((characteristic.getKey() == accessoryType) || (characteristic.getKey() == DUMMY));
547     }
548 }