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.openhab.core.common.ThreadPoolManager;
28 import org.openhab.core.common.registry.RegistryChangeListener;
29 import org.openhab.core.items.GroupItem;
30 import org.openhab.core.items.Item;
31 import org.openhab.core.items.ItemNotFoundException;
32 import org.openhab.core.items.ItemRegistry;
33 import org.openhab.core.items.ItemRegistryChangeListener;
34 import org.openhab.core.items.Metadata;
35 import org.openhab.core.items.MetadataKey;
36 import org.openhab.core.items.MetadataRegistry;
37 import org.openhab.core.storage.Storage;
38 import org.openhab.core.storage.StorageService;
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 StorageService storageService) {
83 this.itemRegistry = itemRegistry;
84 this.settings = settings;
85 this.metadataRegistry = metadataRegistry;
86 storage = storageService.getStorage(HomekitAuthInfoImpl.STORAGE_KEY);
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());
193 applyUpdatesDebouncer.call();
197 public synchronized void removed(Item item) {
198 if (hasHomeKitMetadata(item)) {
203 private Optional<Item> getItemOptional(String name) {
205 return Optional.of(itemRegistry.getItem(name));
206 } catch (ItemNotFoundException e) {
207 return Optional.empty();
211 public void makeNewConfigurationRevision() {
212 final int newRevision = accessoryRegistry.makeNewConfigurationRevision();
213 lastAccessoryCount = accessoryRegistry.getAllAccessories().size();
214 logger.trace("Make new configuration revision. new revision number {}, number of accessories {}", newRevision,
216 storage.put(REVISION_CONFIG, "" + newRevision);
217 storage.put(ACCESSORY_COUNT, "" + lastAccessoryCount);
220 private synchronized void applyUpdates() {
221 logger.trace("Apply updates");
222 for (final String name : pendingUpdates) {
223 accessoryRegistry.remove(name);
224 logger.trace(" Add items {}", name);
225 getItemOptional(name).ifPresent(this::createRootAccessories);
227 if (!pendingUpdates.isEmpty()) {
228 makeNewConfigurationRevision();
229 pendingUpdates.clear();
234 public void updated(Item oldElement, Item element) {
235 markDirty(oldElement);
239 public int getLastAccessoryCount() {
240 return lastAccessoryCount;
243 public synchronized void clearAccessories() {
244 accessoryRegistry.clear();
247 public synchronized void setBridge(HomekitRoot bridge) {
248 accessoryRegistry.setBridge(bridge);
251 public synchronized void unsetBridge() {
252 applyUpdatesDebouncer.stop();
253 accessoryRegistry.unsetBridge();
256 public void setUpdater(HomekitAccessoryUpdater updater) {
257 this.updater = updater;
260 public void updateSettings(HomekitSettings settings) {
261 this.settings = settings;
265 this.itemRegistry.removeRegistryChangeListener(this);
266 this.metadataRegistry.removeRegistryChangeListener(metadataChangeListener);
269 public Map<String, HomekitAccessory> getAccessories() {
270 return this.accessoryRegistry.getAllAccessories();
273 public int getConfigurationRevision() {
274 return this.accessoryRegistry.getConfigurationRevision();
278 * creates one or more HomeKit items for given openhab item.
279 * one OpenHAB item can linked to several HomeKit accessories or characteristics.
280 * OpenHAB Item is a good candidate for homeKit accessory IF
281 * - it has HomeKit accessory types, i.e. HomeKit accessory tag AND
282 * - has no group with HomeKit tag, i.e. single line accessory ODER
283 * - has groups with HomeKit tag, but all groups are with baseItem, e.g. Group:Switch,
284 * so that the groups already complete accessory and group members can be a standalone HomeKit accessory.
285 * In contrast, items which are part of groups without BaseItem are additional HomeKit characteristics of the
286 * accessory defined by that group and dont need to be created as RootAccessory here.
289 * // Single Line HomeKit Accessory
290 * Switch light "Light" {homekit="Lighting"}
292 * // One HomeKit accessory defined using group
293 * Group gLight "Light Group" {homekit="Lighting"}
294 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
296 * // 2 HomeKit accessories: one is switch attached to group, another one a single switch
297 * Group:Switch:OR(ON,OFF) gLight "Light Group " {homekit="Lighting"}
298 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
300 * @param item openHAB item
302 private void createRootAccessories(Item item) {
303 final List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> accessoryTypes = HomekitAccessoryFactory
304 .getAccessoryTypes(item, metadataRegistry);
305 final List<GroupItem> groups = HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry);
306 if (!accessoryTypes.isEmpty()
307 && (groups.isEmpty() || groups.stream().noneMatch(g -> g.getBaseItem() == null))) {
308 logger.trace("Item {} is a HomeKit accessory of types {}", item.getName(), accessoryTypes);
309 final HomekitOHItemProxy itemProxy = new HomekitOHItemProxy(item);
310 accessoryTypes.forEach(rootAccessory -> createRootAccessory(new HomekitTaggedItem(itemProxy,
311 rootAccessory.getKey(), HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry))));
315 private void createRootAccessory(HomekitTaggedItem taggedItem) {
317 accessoryRegistry.addRootAccessory(taggedItem.getName(),
318 HomekitAccessoryFactory.create(taggedItem, metadataRegistry, updater, settings));
319 } catch (HomekitException e) {
320 logger.warn("Could not add device {}: {}", taggedItem.getItem().getUID(), e.getMessage());