]> git.basschouten.com Git - openhab-addons.git/blob
ed8390cfd8f3a8081330de5fb1704bfcc034f637
[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.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;
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             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>() {
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
194         /*
195          * if metadata of a group item was changed, mark all group member as dirty.
196          */
197         if (item instanceof GroupItem) {
198             ((GroupItem) item).getMembers().forEach(groupMember -> pendingUpdates.add(groupMember.getName()));
199         }
200         applyUpdatesDebouncer.call();
201     }
202
203     @Override
204     public synchronized void removed(Item item) {
205         if (hasHomeKitMetadata(item)) {
206             markDirty(item);
207         }
208     }
209
210     private Optional<Item> getItemOptional(String name) {
211         try {
212             return Optional.of(itemRegistry.getItem(name));
213         } catch (ItemNotFoundException e) {
214             return Optional.empty();
215         }
216     }
217
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,
222                 lastAccessoryCount);
223         storage.put(REVISION_CONFIG, "" + newRevision);
224         storage.put(ACCESSORY_COUNT, "" + lastAccessoryCount);
225     }
226
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);
233         }
234         if (!pendingUpdates.isEmpty()) {
235             makeNewConfigurationRevision();
236             pendingUpdates.clear();
237         }
238     }
239
240     @Override
241     public void updated(Item oldElement, Item element) {
242         markDirty(oldElement);
243         markDirty(element);
244     }
245
246     public int getLastAccessoryCount() {
247         return lastAccessoryCount;
248     }
249
250     public synchronized void clearAccessories() {
251         accessoryRegistry.clear();
252     }
253
254     public synchronized void setBridge(HomekitRoot bridge) {
255         accessoryRegistry.setBridge(bridge);
256     }
257
258     public synchronized void unsetBridge() {
259         applyUpdatesDebouncer.stop();
260         accessoryRegistry.unsetBridge();
261     }
262
263     public void setUpdater(HomekitAccessoryUpdater updater) {
264         this.updater = updater;
265     }
266
267     public void updateSettings(HomekitSettings settings) {
268         this.settings = settings;
269     }
270
271     public void stop() {
272         this.itemRegistry.removeRegistryChangeListener(this);
273         this.metadataRegistry.removeRegistryChangeListener(metadataChangeListener);
274     }
275
276     public Map<String, HomekitAccessory> getAccessories() {
277         return this.accessoryRegistry.getAllAccessories();
278     }
279
280     public int getConfigurationRevision() {
281         return this.accessoryRegistry.getConfigurationRevision();
282     }
283
284     /**
285      * select primary accessory type from list of types.
286      * selection logic:
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
290      * primary
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
293      *
294      * @param item openhab item
295      * @param accessoryTypes list of accessory type attached to the item
296      * @return primary accessory type
297      */
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,
302                     metadataRegistry);
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();
309                 }
310             }
311         }
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();
314     }
315
316     /**
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
320      * IF
321      * - it has HomeKit accessory types defined using HomeKit accessory metadata
322      * - AND is not part of a group with HomeKit metadata
323      * e.g.
324      * Switch light "Light" {homekit="Lighting"}
325      * Group gLight "Light Group" {homekit="Lighting"}
326      *
327      * OR
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
330      * e.g.
331      * Group:Switch:OR(ON,OFF) gLight "Light Group " {homekit="Lighting"}
332      * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
333      *
334      *
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.
337      * e.g.
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"
341      *
342      * Examples:
343      * // Single line HomeKit Accessory
344      * Switch light "Light" {homekit="Lighting"}
345      *
346      * // One HomeKit accessory defined using group
347      * Group gLight "Light Group" {homekit="Lighting"}
348      * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
349      *
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"}
353      *
354      * @param item openHAB item
355      */
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));
368             try {
369                 final HomekitAccessory accessory = HomekitAccessoryFactory.create(taggedItem, metadataRegistry, updater,
370                         settings);
371
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));
377                             try {
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);
383                             }
384                         });
385                 accessoryRegistry.addRootAccessory(taggedItem.getName(), accessory);
386             } catch (HomekitException e) {
387                 logger.warn("Cannot create accessory {}", taggedItem);
388             }
389         }
390     }
391 }