]> git.basschouten.com Git - openhab-addons.git/blob
e3148fd1991199bb531bdd1c2561ce8c662bd72b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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;
14
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;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Optional;
23 import java.util.Set;
24 import java.util.concurrent.ScheduledExecutorService;
25
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;
42
43 import io.github.hapjava.accessories.HomekitAccessory;
44 import io.github.hapjava.server.impl.HomekitRoot;
45
46 /**
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.
49  *
50  * @author Andy Lintner - Initial contribution
51  */
52 @NonNullByDefault
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;
65
66     private final Set<String> pendingUpdates = new HashSet<>();
67
68     private final ScheduledExecutorService scheduler = ThreadPoolManager
69             .getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
70
71     /**
72      * Rather than reacting to item added/removed/modified changes directly, we mark them as dirty (and the groups to
73      * which they belong)
74      *
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
77      * group is complete.
78      */
79     private final Debouncer applyUpdatesDebouncer;
80
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>() {
90             @Override
91             public void added(final Metadata metadata) {
92                 final MetadataKey uid = metadata.getUID();
93                 if (HomekitAccessoryFactory.METADATA_KEY.equalsIgnoreCase(uid.getNamespace())) {
94                     try {
95                         markDirty(itemRegistry.getItem(uid.getItemName()));
96                     } catch (ItemNotFoundException e) {
97                         logger.debug("Could not find item for metadata {}", metadata);
98                     }
99                 }
100             }
101
102             @Override
103             public void removed(final Metadata metadata) {
104                 final MetadataKey uid = metadata.getUID();
105                 if (HomekitAccessoryFactory.METADATA_KEY.equalsIgnoreCase(uid.getNamespace())) {
106                     try {
107                         markDirty(itemRegistry.getItem(uid.getItemName()));
108                     } catch (ItemNotFoundException e) {
109                         logger.debug("Could not find item for metadata {}", metadata);
110                     }
111                 }
112             }
113
114             @Override
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())) {
120                     try {
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);
125                     }
126                 }
127             }
128         };
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());
134     }
135
136     private void initialiseRevision() {
137         int revision;
138         try {
139             String revisionString = storage.get(REVISION_CONFIG);
140             if (revisionString == null) {
141                 throw new NumberFormatException();
142             }
143             revision = Integer.parseInt(revisionString);
144         } catch (NumberFormatException e) {
145             revision = 1;
146             storage.put(REVISION_CONFIG, "" + revision);
147         }
148         try {
149             String accessoryCountString = storage.get(ACCESSORY_COUNT);
150             if (accessoryCountString == null) {
151                 throw new NumberFormatException();
152             }
153             lastAccessoryCount = Integer.parseInt(accessoryCountString);
154         } catch (NumberFormatException e) {
155             lastAccessoryCount = 0;
156             storage.put(ACCESSORY_COUNT, "" + accessoryRegistry.getAllAccessories().size());
157         }
158         accessoryRegistry.setConfigurationRevision(revision);
159     }
160
161     private boolean hasHomeKitMetadata(Item item) {
162         return metadataRegistry.get(new MetadataKey(HomekitAccessoryFactory.METADATA_KEY, item.getUID())) != null;
163     }
164
165     @Override
166     public synchronized void added(Item item) {
167         if (hasHomeKitMetadata(item)) {
168             markDirty(item);
169         }
170     }
171
172     @Override
173     public void allItemsChanged(Collection<String> oldItemNames) {
174         clearAccessories();
175     }
176
177     /**
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.
180      *
181      * @param item The item that has been changed or removed.
182      */
183     private synchronized void markDirty(Item item) {
184         logger.trace("Mark dirty item {}", item.getName());
185         pendingUpdates.add(item.getName());
186         /*
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.
189          */
190         for (Item accessoryGroup : HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry)) {
191             pendingUpdates.add(accessoryGroup.getName());
192         }
193         applyUpdatesDebouncer.call();
194     }
195
196     @Override
197     public synchronized void removed(Item item) {
198         if (hasHomeKitMetadata(item)) {
199             markDirty(item);
200         }
201     }
202
203     private Optional<Item> getItemOptional(String name) {
204         try {
205             return Optional.of(itemRegistry.getItem(name));
206         } catch (ItemNotFoundException e) {
207             return Optional.empty();
208         }
209     }
210
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,
215                 lastAccessoryCount);
216         storage.put(REVISION_CONFIG, "" + newRevision);
217         storage.put(ACCESSORY_COUNT, "" + lastAccessoryCount);
218     }
219
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);
226         }
227         if (!pendingUpdates.isEmpty()) {
228             makeNewConfigurationRevision();
229             pendingUpdates.clear();
230         }
231     }
232
233     @Override
234     public void updated(Item oldElement, Item element) {
235         markDirty(oldElement);
236         markDirty(element);
237     }
238
239     public int getLastAccessoryCount() {
240         return lastAccessoryCount;
241     }
242
243     public synchronized void clearAccessories() {
244         accessoryRegistry.clear();
245     }
246
247     public synchronized void setBridge(HomekitRoot bridge) {
248         accessoryRegistry.setBridge(bridge);
249     }
250
251     public synchronized void unsetBridge() {
252         applyUpdatesDebouncer.stop();
253         accessoryRegistry.unsetBridge();
254     }
255
256     public void setUpdater(HomekitAccessoryUpdater updater) {
257         this.updater = updater;
258     }
259
260     public void updateSettings(HomekitSettings settings) {
261         this.settings = settings;
262     }
263
264     public void stop() {
265         this.itemRegistry.removeRegistryChangeListener(this);
266         this.metadataRegistry.removeRegistryChangeListener(metadataChangeListener);
267     }
268
269     public Map<String, HomekitAccessory> getAccessories() {
270         return this.accessoryRegistry.getAllAccessories();
271     }
272
273     public int getConfigurationRevision() {
274         return this.accessoryRegistry.getConfigurationRevision();
275     }
276
277     /**
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.
287      *
288      * Examples:
289      * // Single Line HomeKit Accessory
290      * Switch light "Light" {homekit="Lighting"}
291      *
292      * // One HomeKit accessory defined using group
293      * Group gLight "Light Group" {homekit="Lighting"}
294      * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
295      *
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"}
299      *
300      * @param item openHAB item
301      */
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))));
312         }
313     }
314
315     private void createRootAccessory(HomekitTaggedItem taggedItem) {
316         try {
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());
321         }
322     }
323 }