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.MetadataRegistry;
36 import org.openhab.core.storage.Storage;
37 import org.openhab.core.storage.StorageService;
38 import org.openhab.io.homekit.internal.accessories.HomekitAccessoryFactory;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 import io.github.hapjava.accessories.HomekitAccessory;
43 import io.github.hapjava.server.impl.HomekitRoot;
46 * Listens for changes to the item and metadata registry. When changes are detected, check
47 * for HomeKit tags and, if present, add the items to the HomekitAccessoryRegistry.
49 * @author Andy Lintner - Initial contribution
52 public class HomekitChangeListener implements ItemRegistryChangeListener {
53 private final Logger logger = LoggerFactory.getLogger(HomekitChangeListener.class);
54 private final static String REVISION_CONFIG = "revision";
55 private final static String ACCESSORY_COUNT = "accessory_count";
56 private final ItemRegistry itemRegistry;
57 private final HomekitAccessoryRegistry accessoryRegistry = new HomekitAccessoryRegistry();
58 private final MetadataRegistry metadataRegistry;
59 private final Storage<String> storage;
60 private final RegistryChangeListener<Metadata> metadataChangeListener;
61 private HomekitAccessoryUpdater updater = new HomekitAccessoryUpdater();
62 private HomekitSettings settings;
63 private int lastAccessoryCount;
65 private final Set<String> pendingUpdates = new HashSet<>();
67 private final ScheduledExecutorService scheduler = ThreadPoolManager
68 .getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
71 * Rather than reacting to item added/removed/modified changes directly, we mark them as dirty (and the groups to
74 * 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,
75 * rather than for each update at a time, preventing us from showing an error message with each addition until the
78 private final Debouncer applyUpdatesDebouncer;
80 HomekitChangeListener(ItemRegistry itemRegistry, HomekitSettings settings, MetadataRegistry metadataRegistry,
81 StorageService storageService) {
82 this.itemRegistry = itemRegistry;
83 this.settings = settings;
84 this.metadataRegistry = metadataRegistry;
85 storage = storageService.getStorage(HomekitAuthInfoImpl.STORAGE_KEY);
86 this.applyUpdatesDebouncer = new Debouncer("update-homekit-devices", scheduler, Duration.ofMillis(1000),
87 Clock.systemUTC(), this::applyUpdates);
88 metadataChangeListener = new RegistryChangeListener<Metadata>() {
90 public void added(final Metadata metadata) {
92 markDirty(itemRegistry.getItem(metadata.getUID().getItemName()));
93 } catch (ItemNotFoundException e) {
94 logger.debug("Could not found item for metadata {}", metadata);
99 public void removed(final Metadata metadata) {
101 markDirty(itemRegistry.getItem(metadata.getUID().getItemName()));
102 } catch (ItemNotFoundException e) {
103 logger.debug("Could not found item for metadata {}", metadata);
108 public void updated(final Metadata metadata, final Metadata e1) {
110 markDirty(itemRegistry.getItem(metadata.getUID().getItemName()));
111 if (!metadata.getUID().getItemName().equals(e1.getUID().getItemName())) {
112 markDirty(itemRegistry.getItem(e1.getUID().getItemName()));
114 } catch (ItemNotFoundException e) {
115 logger.debug("Could not found item for metadata {}", metadata);
119 itemRegistry.addRegistryChangeListener(this);
120 metadataRegistry.addRegistryChangeListener(metadataChangeListener);
121 itemRegistry.getItems().forEach(this::createRootAccessories);
122 initialiseRevision();
123 logger.info("Created {} HomeKit items.", accessoryRegistry.getAllAccessories().size());
126 private void initialiseRevision() {
129 String revisionString = storage.get(REVISION_CONFIG);
130 if (revisionString == null) {
131 throw new NumberFormatException();
133 revision = Integer.parseInt(revisionString);
134 } catch (NumberFormatException e) {
136 storage.put(REVISION_CONFIG, "" + revision);
139 String accessoryCountString = storage.get(ACCESSORY_COUNT);
140 if (accessoryCountString == null) {
141 throw new NumberFormatException();
143 lastAccessoryCount = Integer.parseInt(accessoryCountString);
144 } catch (NumberFormatException e) {
145 lastAccessoryCount = 0;
146 storage.put(ACCESSORY_COUNT, "" + accessoryRegistry.getAllAccessories().size());
148 accessoryRegistry.setConfigurationRevision(revision);
152 public synchronized void added(Item item) {
157 public void allItemsChanged(Collection<String> oldItemNames) {
162 * Mark an item as dirty, plus any accessory groups to which it pertains, so that after a debounce period the
163 * accessory update can be applied.
165 * @param item The item that has been changed or removed.
167 private synchronized void markDirty(Item item) {
168 logger.trace("Mark dirty item {}", item.getName());
169 pendingUpdates.add(item.getName());
171 * If findMyAccessoryGroups fails because the accessory group has already been deleted, then we can count on a
172 * later update telling us that the accessory group was removed.
174 for (Item accessoryGroup : HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry)) {
175 pendingUpdates.add(accessoryGroup.getName());
177 applyUpdatesDebouncer.call();
181 public synchronized void removed(Item item) {
185 private Optional<Item> getItemOptional(String name) {
187 return Optional.of(itemRegistry.getItem(name));
188 } catch (ItemNotFoundException e) {
189 return Optional.empty();
193 public void makeNewConfigurationRevision() {
194 final int newRevision = accessoryRegistry.makeNewConfigurationRevision();
195 lastAccessoryCount = accessoryRegistry.getAllAccessories().size();
196 logger.trace("make new configuration revision. new revision number {}, number of accessories {}", newRevision,
198 storage.put(REVISION_CONFIG, "" + newRevision);
199 storage.put(ACCESSORY_COUNT, "" + lastAccessoryCount);
202 private synchronized void applyUpdates() {
203 logger.trace("apply updates");
204 for (final String name : pendingUpdates) {
205 accessoryRegistry.remove(name);
206 logger.trace(" add items {}", name);
207 getItemOptional(name).ifPresent(this::createRootAccessories);
209 if (!pendingUpdates.isEmpty()) {
210 makeNewConfigurationRevision();
211 pendingUpdates.clear();
216 public void updated(Item oldElement, Item element) {
217 markDirty(oldElement);
221 public int getLastAccessoryCount() {
222 return lastAccessoryCount;
225 public synchronized void clearAccessories() {
226 accessoryRegistry.clear();
229 public synchronized void setBridge(HomekitRoot bridge) {
230 accessoryRegistry.setBridge(bridge);
233 public synchronized void unsetBridge() {
234 applyUpdatesDebouncer.stop();
235 accessoryRegistry.unsetBridge();
238 public void setUpdater(HomekitAccessoryUpdater updater) {
239 this.updater = updater;
242 public void updateSettings(HomekitSettings settings) {
243 this.settings = settings;
247 this.itemRegistry.removeRegistryChangeListener(this);
248 this.metadataRegistry.removeRegistryChangeListener(metadataChangeListener);
251 public Map<String, HomekitAccessory> getAccessories() {
252 return this.accessoryRegistry.getAllAccessories();
255 public int getConfigurationRevision() {
256 return this.accessoryRegistry.getConfigurationRevision();
260 * creates one or more HomeKit items for given openhab item.
261 * one OpenHAB item can linked to several HomeKit accessories or characteristics.
262 * OpenHAB Item is a good candidate for homeKit accessory IF
263 * - it has HomeKit accessory types, i.e. HomeKit accessory tag AND
264 * - has no group with HomeKit tag, i.e. single line accessory ODER
265 * - has groups with HomeKit tag, but all groups are with baseItem, e.g. Group:Switch,
266 * so that the groups already complete accessory and group members can be a standalone HomeKit accessory.
267 * In contrast, items which are part of groups without BaseItem are additional HomeKit characteristics of the
268 * accessory defined by that group and dont need to be created as RootAccessory here.
271 * // Single Line HomeKit Accessory
272 * Switch light "Light" {homekit="Lighting"}
274 * // One HomeKit accessory defined using group
275 * Group gLight "Light Group" {homekit="Lighting"}
276 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
278 * // 2 HomeKit accessories: one is switch attached to group, another one a single switch
279 * Group:Switch:OR(ON,OFF) gLight "Light Group " {homekit="Lighting"}
280 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
282 * @param item openHAB item
284 private void createRootAccessories(Item item) {
285 final List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> accessoryTypes = HomekitAccessoryFactory
286 .getAccessoryTypes(item, metadataRegistry);
287 final List<GroupItem> groups = HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry);
288 if (!accessoryTypes.isEmpty()
289 && (groups.isEmpty() || groups.stream().noneMatch(g -> g.getBaseItem() == null))) {
290 logger.trace("Item {} is a HomeKit accessory of types {}", item.getName(), accessoryTypes);
291 final HomekitOHItemProxy itemProxy = new HomekitOHItemProxy(item);
292 accessoryTypes.forEach(rootAccessory -> createRootAccessory(new HomekitTaggedItem(itemProxy,
293 rootAccessory.getKey(), HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry))));
297 private void createRootAccessory(HomekitTaggedItem taggedItem) {
299 accessoryRegistry.addRootAccessory(taggedItem.getName(),
300 HomekitAccessoryFactory.create(taggedItem, metadataRegistry, updater, settings));
301 } catch (HomekitException e) {
302 logger.warn("Could not add device {}: {}", taggedItem.getItem().getUID(), e.getMessage());