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;
15 import java.time.Clock;
16 import java.time.Duration;
17 import java.util.Collection;
18 import java.util.HashSet;
19 import java.util.List;
21 import java.util.Map.Entry;
22 import java.util.Optional;
24 import java.util.concurrent.ScheduledExecutorService;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.core.common.ThreadPoolManager;
29 import org.openhab.core.common.registry.RegistryChangeListener;
30 import org.openhab.core.items.GroupItem;
31 import org.openhab.core.items.Item;
32 import org.openhab.core.items.ItemNotFoundException;
33 import org.openhab.core.items.ItemRegistry;
34 import org.openhab.core.items.ItemRegistryChangeListener;
35 import org.openhab.core.items.Metadata;
36 import org.openhab.core.items.MetadataKey;
37 import org.openhab.core.items.MetadataRegistry;
38 import org.openhab.core.storage.Storage;
39 import org.openhab.io.homekit.internal.accessories.HomekitAccessoryFactory;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
43 import io.github.hapjava.accessories.HomekitAccessory;
44 import io.github.hapjava.server.impl.HomekitRoot;
47 * Listens for changes to the item and metadata registry. When changes are detected, check
48 * for HomeKit tags and, if present, add the items to the HomekitAccessoryRegistry.
50 * @author Andy Lintner - Initial contribution
53 public class HomekitChangeListener implements ItemRegistryChangeListener {
54 private final Logger logger = LoggerFactory.getLogger(HomekitChangeListener.class);
55 private final static String REVISION_CONFIG = "revision";
56 private final static String ACCESSORY_COUNT = "accessory_count";
57 private final ItemRegistry itemRegistry;
58 private final HomekitAccessoryRegistry accessoryRegistry = new HomekitAccessoryRegistry();
59 private final MetadataRegistry metadataRegistry;
60 private final Storage<String> storage;
61 private final RegistryChangeListener<Metadata> metadataChangeListener;
62 private HomekitAccessoryUpdater updater = new HomekitAccessoryUpdater();
63 private HomekitSettings settings;
64 private int lastAccessoryCount;
66 private final Set<String> pendingUpdates = new HashSet<>();
68 private final ScheduledExecutorService scheduler = ThreadPoolManager
69 .getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
72 * Rather than reacting to item added/removed/modified changes directly, we mark them as dirty (and the groups to
75 * We wait for a second to pass until no more items are changed. This allows us to add a group of items all at once,
76 * rather than for each update at a time, preventing us from showing an error message with each addition until the
79 private final Debouncer applyUpdatesDebouncer;
81 HomekitChangeListener(ItemRegistry itemRegistry, HomekitSettings settings, MetadataRegistry metadataRegistry,
82 Storage<String> storage) {
83 this.itemRegistry = itemRegistry;
84 this.settings = settings;
85 this.metadataRegistry = metadataRegistry;
86 this.storage = storage;
87 this.applyUpdatesDebouncer = new Debouncer("update-homekit-devices", scheduler, Duration.ofMillis(1000),
88 Clock.systemUTC(), this::applyUpdates);
89 metadataChangeListener = new RegistryChangeListener<Metadata>() {
91 public void added(final Metadata metadata) {
92 final MetadataKey uid = metadata.getUID();
93 if (HomekitAccessoryFactory.METADATA_KEY.equalsIgnoreCase(uid.getNamespace())) {
95 markDirty(itemRegistry.getItem(uid.getItemName()));
96 } catch (ItemNotFoundException e) {
97 logger.debug("Could not find item for metadata {}", metadata);
103 public void removed(final Metadata metadata) {
104 final MetadataKey uid = metadata.getUID();
105 if (HomekitAccessoryFactory.METADATA_KEY.equalsIgnoreCase(uid.getNamespace())) {
107 markDirty(itemRegistry.getItem(uid.getItemName()));
108 } catch (ItemNotFoundException e) {
109 logger.debug("Could not find item for metadata {}", metadata);
115 public void updated(final Metadata oldMetadata, final Metadata newMetadata) {
116 final MetadataKey oldUid = oldMetadata.getUID();
117 final MetadataKey newUid = newMetadata.getUID();
118 if (HomekitAccessoryFactory.METADATA_KEY.equalsIgnoreCase(oldUid.getNamespace())
119 || HomekitAccessoryFactory.METADATA_KEY.equalsIgnoreCase(newUid.getNamespace())) {
121 // the item name is same in old and new metadata, so we can take any.
122 markDirty(itemRegistry.getItem(oldUid.getItemName()));
123 } catch (ItemNotFoundException e) {
124 logger.debug("Could not find item for metadata {}", oldMetadata);
129 itemRegistry.addRegistryChangeListener(this);
130 metadataRegistry.addRegistryChangeListener(metadataChangeListener);
131 itemRegistry.getItems().forEach(this::createRootAccessories);
132 initialiseRevision();
133 logger.info("Created {} HomeKit items.", accessoryRegistry.getAllAccessories().size());
136 private void initialiseRevision() {
139 String revisionString = storage.get(REVISION_CONFIG);
140 if (revisionString == null) {
141 throw new NumberFormatException();
143 revision = Integer.parseInt(revisionString);
144 } catch (NumberFormatException e) {
146 storage.put(REVISION_CONFIG, "" + revision);
149 String accessoryCountString = storage.get(ACCESSORY_COUNT);
150 if (accessoryCountString == null) {
151 throw new NumberFormatException();
153 lastAccessoryCount = Integer.parseInt(accessoryCountString);
154 } catch (NumberFormatException e) {
155 lastAccessoryCount = 0;
156 storage.put(ACCESSORY_COUNT, "" + accessoryRegistry.getAllAccessories().size());
158 accessoryRegistry.setConfigurationRevision(revision);
161 private boolean hasHomeKitMetadata(Item item) {
162 return metadataRegistry.get(new MetadataKey(HomekitAccessoryFactory.METADATA_KEY, item.getUID())) != null;
166 public synchronized void added(Item item) {
167 if (hasHomeKitMetadata(item)) {
173 public void allItemsChanged(Collection<String> oldItemNames) {
178 * Mark an item as dirty, plus any accessory groups to which it pertains, so that after a debounce period the
179 * accessory update can be applied.
181 * @param item The item that has been changed or removed.
183 private synchronized void markDirty(Item item) {
184 logger.trace("Mark dirty item {}", item.getName());
185 pendingUpdates.add(item.getName());
187 * If findMyAccessoryGroups fails because the accessory group has already been deleted, then we can count on a
188 * later update telling us that the accessory group was removed.
190 for (Item accessoryGroup : HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry)) {
191 pendingUpdates.add(accessoryGroup.getName());
195 * if metadata of a group item was changed, mark all group member as dirty.
197 if (item instanceof GroupItem) {
198 ((GroupItem) item).getMembers().forEach(groupMember -> pendingUpdates.add(groupMember.getName()));
200 applyUpdatesDebouncer.call();
204 public synchronized void removed(Item item) {
205 if (hasHomeKitMetadata(item)) {
210 private Optional<Item> getItemOptional(String name) {
212 return Optional.of(itemRegistry.getItem(name));
213 } catch (ItemNotFoundException e) {
214 return Optional.empty();
218 public void makeNewConfigurationRevision() {
219 final int newRevision = accessoryRegistry.makeNewConfigurationRevision();
220 lastAccessoryCount = accessoryRegistry.getAllAccessories().size();
221 logger.trace("Make new configuration revision. new revision number {}, number of accessories {}", newRevision,
223 storage.put(REVISION_CONFIG, "" + newRevision);
224 storage.put(ACCESSORY_COUNT, "" + lastAccessoryCount);
227 private synchronized void applyUpdates() {
228 logger.trace("Apply updates");
229 for (final String name : pendingUpdates) {
230 accessoryRegistry.remove(name);
231 logger.trace(" Add items {}", name);
232 getItemOptional(name).ifPresent(this::createRootAccessories);
234 if (!pendingUpdates.isEmpty()) {
235 makeNewConfigurationRevision();
236 pendingUpdates.clear();
241 public void updated(Item oldElement, Item element) {
242 markDirty(oldElement);
246 public int getLastAccessoryCount() {
247 return lastAccessoryCount;
250 public synchronized void clearAccessories() {
251 accessoryRegistry.clear();
254 public synchronized void setBridge(HomekitRoot bridge) {
255 accessoryRegistry.setBridge(bridge);
258 public synchronized void unsetBridge() {
259 applyUpdatesDebouncer.stop();
260 accessoryRegistry.unsetBridge();
263 public void setUpdater(HomekitAccessoryUpdater updater) {
264 this.updater = updater;
267 public void updateSettings(HomekitSettings settings) {
268 this.settings = settings;
272 this.itemRegistry.removeRegistryChangeListener(this);
273 this.metadataRegistry.removeRegistryChangeListener(metadataChangeListener);
276 public Map<String, HomekitAccessory> getAccessories() {
277 return this.accessoryRegistry.getAllAccessories();
280 public int getConfigurationRevision() {
281 return this.accessoryRegistry.getConfigurationRevision();
285 * select primary accessory type from list of types.
287 * - if accessory has only one type, it is the primary type
288 * - if accessory has no primary type defined per configuration, then the first type on the list is the primary type
289 * - if accessory has primary type defined per configuration and this type is on the list of types, then it is the
291 * - if accessory has primary type defined per configuration and this type is NOT on the list of types, then the
292 * first type on the list is the primary type
294 * @param item openhab item
295 * @param accessoryTypes list of accessory type attached to the item
296 * @return primary accessory type
298 private HomekitAccessoryType getPrimaryAccessoryType(Item item,
299 List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> accessoryTypes) {
300 if (accessoryTypes.size() > 1) {
301 final @Nullable Map<String, Object> configuration = HomekitAccessoryFactory.getItemConfiguration(item,
303 if (configuration != null) {
304 final @Nullable Object value = configuration.get(HomekitTaggedItem.PRIMARY_SERVICE);
305 if (value instanceof String) {
306 return accessoryTypes.stream()
307 .filter(aType -> ((String) value).equalsIgnoreCase(aType.getKey().getTag())).findAny()
308 .orElse(accessoryTypes.get(0)).getKey();
312 // no primary accessory found or there is only one type, so return the first type from the list
313 return accessoryTypes.get(0).getKey();
317 * creates one or more HomeKit items for given openhab item.
318 * one OpenHAB item can be linked to several HomeKit accessories.
319 * OpenHAB item is a good candidate for a HomeKit accessory
321 * - it has HomeKit accessory types defined using HomeKit accessory metadata
322 * - AND is not part of a group with HomeKit metadata
324 * Switch light "Light" {homekit="Lighting"}
325 * Group gLight "Light Group" {homekit="Lighting"}
328 * - it has HomeKit accessory types defined using HomeKit accessory metadata
329 * - AND is part of groups with HomeKit metadata, but all groups have baseItem
331 * Group:Switch:OR(ON,OFF) gLight "Light Group " {homekit="Lighting"}
332 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
335 * In contrast, items which are part of groups without BaseItem are additional HomeKit characteristics of the
336 * accessory defined by that group and don't need to be created as accessory here.
338 * Group gLight "Light Group " {homekit="Lighting"}
339 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
340 * is not the root accessory but only a characteristic "OnState"
343 * // Single line HomeKit Accessory
344 * Switch light "Light" {homekit="Lighting"}
346 * // One HomeKit accessory defined using group
347 * Group gLight "Light Group" {homekit="Lighting"}
348 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
350 * // 2 HomeKit accessories: one is switch attached to group, another one a single switch
351 * Group:Switch:OR(ON,OFF) gLight "Light Group " {homekit="Lighting"}
352 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
354 * @param item openHAB item
356 private void createRootAccessories(Item item) {
357 final List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> accessoryTypes = HomekitAccessoryFactory
358 .getAccessoryTypes(item, metadataRegistry);
359 final List<GroupItem> groups = HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry);
360 if (!accessoryTypes.isEmpty()
361 && (groups.isEmpty() || groups.stream().noneMatch(g -> g.getBaseItem() == null))) {
362 final HomekitAccessoryType primaryAccessoryType = getPrimaryAccessoryType(item, accessoryTypes);
363 logger.trace("Item {} is a HomeKit accessory of types {}. Primary type is {}", item.getName(),
364 accessoryTypes, primaryAccessoryType);
365 final HomekitOHItemProxy itemProxy = new HomekitOHItemProxy(item);
366 final HomekitTaggedItem taggedItem = new HomekitTaggedItem(new HomekitOHItemProxy(item),
367 primaryAccessoryType, HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry));
369 final HomekitAccessory accessory = HomekitAccessoryFactory.create(taggedItem, metadataRegistry, updater,
372 accessoryTypes.stream().filter(aType -> !primaryAccessoryType.equals(aType.getKey()))
373 .forEach(additionalAccessoryType -> {
374 final HomekitTaggedItem additionalTaggedItem = new HomekitTaggedItem(itemProxy,
375 additionalAccessoryType.getKey(),
376 HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry));
378 final HomekitAccessory additionalAccessory = HomekitAccessoryFactory
379 .create(additionalTaggedItem, metadataRegistry, updater, settings);
380 accessory.getServices().add(additionalAccessory.getPrimaryService());
381 } catch (HomekitException e) {
382 logger.warn("Cannot create additional accessory {}", additionalTaggedItem);
385 accessoryRegistry.addRootAccessory(taggedItem.getName(), accessory);
386 } catch (HomekitException e) {
387 logger.warn("Cannot create accessory {}", taggedItem);