]> git.basschouten.com Git - openhab-addons.git/blob
f0fcbcf8673d350463fb543f6d94a321ec4fd6dd
[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.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;
41
42 import io.github.hapjava.accessories.HomekitAccessory;
43 import io.github.hapjava.server.impl.HomekitRoot;
44
45 /**
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.
48  *
49  * @author Andy Lintner - Initial contribution
50  */
51 @NonNullByDefault
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;
64
65     private final Set<String> pendingUpdates = new HashSet<>();
66
67     private final ScheduledExecutorService scheduler = ThreadPoolManager
68             .getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
69
70     /**
71      * Rather than reacting to item added/removed/modified changes directly, we mark them as dirty (and the groups to
72      * which they belong)
73      *
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
76      * group is complete.
77      */
78     private final Debouncer applyUpdatesDebouncer;
79
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>() {
89             @Override
90             public void added(final Metadata metadata) {
91                 try {
92                     markDirty(itemRegistry.getItem(metadata.getUID().getItemName()));
93                 } catch (ItemNotFoundException e) {
94                     logger.debug("Could not found item for metadata {}", metadata);
95                 }
96             }
97
98             @Override
99             public void removed(final Metadata metadata) {
100                 try {
101                     markDirty(itemRegistry.getItem(metadata.getUID().getItemName()));
102                 } catch (ItemNotFoundException e) {
103                     logger.debug("Could not found item for metadata {}", metadata);
104                 }
105             }
106
107             @Override
108             public void updated(final Metadata metadata, final Metadata e1) {
109                 try {
110                     markDirty(itemRegistry.getItem(metadata.getUID().getItemName()));
111                     if (!metadata.getUID().getItemName().equals(e1.getUID().getItemName())) {
112                         markDirty(itemRegistry.getItem(e1.getUID().getItemName()));
113                     }
114                 } catch (ItemNotFoundException e) {
115                     logger.debug("Could not found item for metadata {}", metadata);
116                 }
117             }
118         };
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());
124     }
125
126     private void initialiseRevision() {
127         int revision;
128         try {
129             String revisionString = storage.get(REVISION_CONFIG);
130             if (revisionString == null) {
131                 throw new NumberFormatException();
132             }
133             revision = Integer.parseInt(revisionString);
134         } catch (NumberFormatException e) {
135             revision = 1;
136             storage.put(REVISION_CONFIG, "" + revision);
137         }
138         try {
139             String accessoryCountString = storage.get(ACCESSORY_COUNT);
140             if (accessoryCountString == null) {
141                 throw new NumberFormatException();
142             }
143             lastAccessoryCount = Integer.parseInt(accessoryCountString);
144         } catch (NumberFormatException e) {
145             lastAccessoryCount = 0;
146             storage.put(ACCESSORY_COUNT, "" + accessoryRegistry.getAllAccessories().size());
147         }
148         accessoryRegistry.setConfigurationRevision(revision);
149     }
150
151     @Override
152     public synchronized void added(Item item) {
153         markDirty(item);
154     }
155
156     @Override
157     public void allItemsChanged(Collection<String> oldItemNames) {
158         clearAccessories();
159     }
160
161     /**
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.
164      *
165      * @param item The item that has been changed or removed.
166      */
167     private synchronized void markDirty(Item item) {
168         logger.trace("Mark dirty item {}", item.getName());
169         pendingUpdates.add(item.getName());
170         /*
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.
173          */
174         for (Item accessoryGroup : HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry)) {
175             pendingUpdates.add(accessoryGroup.getName());
176         }
177         applyUpdatesDebouncer.call();
178     }
179
180     @Override
181     public synchronized void removed(Item item) {
182         markDirty(item);
183     }
184
185     private Optional<Item> getItemOptional(String name) {
186         try {
187             return Optional.of(itemRegistry.getItem(name));
188         } catch (ItemNotFoundException e) {
189             return Optional.empty();
190         }
191     }
192
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,
197                 lastAccessoryCount);
198         storage.put(REVISION_CONFIG, "" + newRevision);
199         storage.put(ACCESSORY_COUNT, "" + lastAccessoryCount);
200     }
201
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);
208         }
209         if (!pendingUpdates.isEmpty()) {
210             makeNewConfigurationRevision();
211             pendingUpdates.clear();
212         }
213     }
214
215     @Override
216     public void updated(Item oldElement, Item element) {
217         markDirty(oldElement);
218         markDirty(element);
219     }
220
221     public int getLastAccessoryCount() {
222         return lastAccessoryCount;
223     }
224
225     public synchronized void clearAccessories() {
226         accessoryRegistry.clear();
227     }
228
229     public synchronized void setBridge(HomekitRoot bridge) {
230         accessoryRegistry.setBridge(bridge);
231     }
232
233     public synchronized void unsetBridge() {
234         applyUpdatesDebouncer.stop();
235         accessoryRegistry.unsetBridge();
236     }
237
238     public void setUpdater(HomekitAccessoryUpdater updater) {
239         this.updater = updater;
240     }
241
242     public void updateSettings(HomekitSettings settings) {
243         this.settings = settings;
244     }
245
246     public void stop() {
247         this.itemRegistry.removeRegistryChangeListener(this);
248         this.metadataRegistry.removeRegistryChangeListener(metadataChangeListener);
249     }
250
251     public Map<String, HomekitAccessory> getAccessories() {
252         return this.accessoryRegistry.getAllAccessories();
253     }
254
255     public int getConfigurationRevision() {
256         return this.accessoryRegistry.getConfigurationRevision();
257     }
258
259     /**
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.
269      *
270      * Examples:
271      * // Single Line HomeKit Accessory
272      * Switch light "Light" {homekit="Lighting"}
273      *
274      * // One HomeKit accessory defined using group
275      * Group gLight "Light Group" {homekit="Lighting"}
276      * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
277      *
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"}
281      *
282      * @param item openHAB item
283      */
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))));
294         }
295     }
296
297     private void createRootAccessory(HomekitTaggedItem taggedItem) {
298         try {
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());
303         }
304     }
305 }