2 * Copyright (c) 2010-2020 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.items.GroupItem;
29 import org.openhab.core.items.Item;
30 import org.openhab.core.items.ItemNotFoundException;
31 import org.openhab.core.items.ItemRegistry;
32 import org.openhab.core.items.ItemRegistryChangeListener;
33 import org.openhab.core.items.MetadataRegistry;
34 import org.openhab.core.storage.Storage;
35 import org.openhab.core.storage.StorageService;
36 import org.openhab.io.homekit.internal.accessories.HomekitAccessoryFactory;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
40 import io.github.hapjava.accessories.HomekitAccessory;
41 import io.github.hapjava.server.impl.HomekitRoot;
44 * Listens for changes to the item registry. When changes are detected, check
45 * for HomeKit tags and, if present, add the items to the HomekitAccessoryRegistry.
47 * @author Andy Lintner - Initial contribution
50 public class HomekitChangeListener implements ItemRegistryChangeListener {
51 private final Logger logger = LoggerFactory.getLogger(HomekitChangeListener.class);
52 private final static String REVISION_CONFIG = "revision";
53 private final static String ACCESSORY_COUNT = "accessory_count";
54 private final ItemRegistry itemRegistry;
55 private final HomekitAccessoryRegistry accessoryRegistry = new HomekitAccessoryRegistry();
56 private final MetadataRegistry metadataRegistry;
57 private final Storage<String> storage;
58 private HomekitAccessoryUpdater updater = new HomekitAccessoryUpdater();
59 private HomekitSettings settings;
60 private int lastAccessoryCount;
62 private final Set<String> pendingUpdates = new HashSet<>();
64 private final ScheduledExecutorService scheduler = ThreadPoolManager
65 .getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
68 * Rather than reacting to item added/removed/modified changes directly, we mark them as dirty (and the groups to
71 * 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,
72 * rather than for each update at a time, preventing us from showing an error message with each addition until the
75 private final Debouncer applyUpdatesDebouncer;
77 HomekitChangeListener(ItemRegistry itemRegistry, HomekitSettings settings, MetadataRegistry metadataRegistry,
78 StorageService storageService) {
79 this.itemRegistry = itemRegistry;
80 this.settings = settings;
81 this.metadataRegistry = metadataRegistry;
82 storage = storageService.getStorage(HomekitAuthInfoImpl.STORAGE_KEY);
83 this.applyUpdatesDebouncer = new Debouncer("update-homekit-devices", scheduler, Duration.ofMillis(1000),
84 Clock.systemUTC(), this::applyUpdates);
86 itemRegistry.addRegistryChangeListener(this);
87 itemRegistry.getItems().forEach(this::createRootAccessories);
89 logger.info("Created {} HomeKit items.", accessoryRegistry.getAllAccessories().size());
92 private void initialiseRevision() {
95 revision = Integer.parseInt(storage.get(REVISION_CONFIG));
96 } catch (NumberFormatException e) {
98 storage.put(REVISION_CONFIG, "" + revision);
101 lastAccessoryCount = Integer.parseInt(storage.get(ACCESSORY_COUNT));
102 } catch (NumberFormatException e) {
103 lastAccessoryCount = 0;
104 storage.put(ACCESSORY_COUNT, "" + accessoryRegistry.getAllAccessories().size());
106 accessoryRegistry.setConfigurationRevision(revision);
110 public synchronized void added(Item item) {
115 public void allItemsChanged(Collection<String> oldItemNames) {
120 * Mark an item as dirty, plus any accessory groups to which it pertains, so that after a debounce period the
121 * accessory update can be applied.
123 * @param item The item that has been changed or removed.
125 private synchronized void markDirty(Item item) {
126 logger.trace("Mark dirty item {}", item.getName());
127 pendingUpdates.add(item.getName());
129 * If findMyAccessoryGroups fails because the accessory group has already been deleted, then we can count on a
130 * later update telling us that the accessory group was removed.
132 for (Item accessoryGroup : HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry)) {
133 pendingUpdates.add(accessoryGroup.getName());
135 applyUpdatesDebouncer.call();
139 public synchronized void removed(Item item) {
143 private Optional<Item> getItemOptional(String name) {
145 return Optional.of(itemRegistry.getItem(name));
146 } catch (ItemNotFoundException e) {
147 return Optional.empty();
151 public void makeNewConfigurationRevision() {
152 final int newRevision = accessoryRegistry.makeNewConfigurationRevision();
153 lastAccessoryCount = accessoryRegistry.getAllAccessories().size();
154 logger.trace("make new configuration revision. new revision number {}, number of accessories {}", newRevision,
156 storage.put(REVISION_CONFIG, "" + newRevision);
157 storage.put(ACCESSORY_COUNT, "" + lastAccessoryCount);
160 private synchronized void applyUpdates() {
161 logger.trace("apply updates");
162 for (final String name : pendingUpdates) {
163 accessoryRegistry.remove(name);
164 logger.trace(" add items {}", name);
165 getItemOptional(name).ifPresent(this::createRootAccessories);
167 if (!pendingUpdates.isEmpty()) {
168 makeNewConfigurationRevision();
169 pendingUpdates.clear();
174 public void updated(Item oldElement, Item element) {
175 markDirty(oldElement);
179 public int getLastAccessoryCount() {
180 return lastAccessoryCount;
183 public synchronized void clearAccessories() {
184 accessoryRegistry.clear();
187 public synchronized void setBridge(HomekitRoot bridge) {
188 accessoryRegistry.setBridge(bridge);
191 public synchronized void unsetBridge() {
192 applyUpdatesDebouncer.stop();
193 accessoryRegistry.unsetBridge();
196 public void setUpdater(HomekitAccessoryUpdater updater) {
197 this.updater = updater;
200 public void updateSettings(HomekitSettings settings) {
201 this.settings = settings;
205 this.itemRegistry.removeRegistryChangeListener(this);
208 public Map<String, HomekitAccessory> getAccessories() {
209 return this.accessoryRegistry.getAllAccessories();
212 public int getConfigurationRevision() {
213 return this.accessoryRegistry.getConfigurationRevision();
217 * creates one or more HomeKit items for given openhab item.
218 * one OpenHAB item can linked to several HomeKit accessories or characteristics.
219 * OpenHAB Item is a good candidate for homeKit accessory IF
220 * - it has HomeKit accessory types, i.e. HomeKit accessory tag AND
221 * - has no group with HomeKit tag, i.e. single line accessory ODER
222 * - has groups with HomeKit tag, but all groups are with baseItem, e.g. Group:Switch,
223 * so that the groups already complete accessory and group members can be a standalone HomeKit accessory.
224 * In contrast, items which are part of groups without BaseItem are additional HomeKit characteristics of the
225 * accessory defined by that group and dont need to be created as RootAccessory here.
228 * // Single Line HomeKit Accessory
229 * Switch light "Light" {homekit="Lighting"}
231 * // One HomeKit accessory defined using group
232 * Group gLight "Light Group" {homekit="Lighting"}
233 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
235 * // 2 HomeKit accessories: one is switch attached to group, another one a single switch
236 * Group:Switch:OR(ON,OFF) gLight "Light Group " {homekit="Lighting"}
237 * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
239 * @param item openHAB item
241 private void createRootAccessories(Item item) {
242 final List<Entry<HomekitAccessoryType, HomekitCharacteristicType>> accessoryTypes = HomekitAccessoryFactory
243 .getAccessoryTypes(item, metadataRegistry);
244 final List<GroupItem> groups = HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry);
245 if (!accessoryTypes.isEmpty()
246 && (groups.isEmpty() || groups.stream().noneMatch(g -> g.getBaseItem() == null))) {
247 logger.trace("Item {} is a HomeKit accessory of types {}", item.getName(), accessoryTypes);
248 final HomekitOHItemProxy itemProxy = new HomekitOHItemProxy(item);
249 accessoryTypes.forEach(rootAccessory -> createRootAccessory(new HomekitTaggedItem(itemProxy,
250 rootAccessory.getKey(), HomekitAccessoryFactory.getItemConfiguration(item, metadataRegistry))));
254 private void createRootAccessory(HomekitTaggedItem taggedItem) {
256 accessoryRegistry.addRootAccessory(taggedItem.getName(),
257 HomekitAccessoryFactory.create(taggedItem, metadataRegistry, updater, settings));
258 } catch (HomekitException e) {
259 logger.warn("Could not add device {}: {}", taggedItem.getItem().getUID(), e.getMessage());