]> git.basschouten.com Git - openhab-addons.git/blob
99fc4162cee6ae28030da317e072f5e006b73ed2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.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;
39
40 import io.github.hapjava.accessories.HomekitAccessory;
41 import io.github.hapjava.server.impl.HomekitRoot;
42
43 /**
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.
46  *
47  * @author Andy Lintner - Initial contribution
48  */
49 @NonNullByDefault
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;
61
62     private final Set<String> pendingUpdates = new HashSet<>();
63
64     private final ScheduledExecutorService scheduler = ThreadPoolManager
65             .getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
66
67     /**
68      * Rather than reacting to item added/removed/modified changes directly, we mark them as dirty (and the groups to
69      * which they belong)
70      *
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
73      * group is complete.
74      */
75     private final Debouncer applyUpdatesDebouncer;
76
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);
85
86         itemRegistry.addRegistryChangeListener(this);
87         itemRegistry.getItems().forEach(this::createRootAccessories);
88         initialiseRevision();
89         logger.info("Created {} HomeKit items.", accessoryRegistry.getAllAccessories().size());
90     }
91
92     private void initialiseRevision() {
93         int revision;
94         try {
95             revision = Integer.parseInt(storage.get(REVISION_CONFIG));
96         } catch (NumberFormatException e) {
97             revision = 1;
98             storage.put(REVISION_CONFIG, "" + revision);
99         }
100         try {
101             lastAccessoryCount = Integer.parseInt(storage.get(ACCESSORY_COUNT));
102         } catch (NumberFormatException e) {
103             lastAccessoryCount = 0;
104             storage.put(ACCESSORY_COUNT, "" + accessoryRegistry.getAllAccessories().size());
105         }
106         accessoryRegistry.setConfigurationRevision(revision);
107     }
108
109     @Override
110     public synchronized void added(Item item) {
111         markDirty(item);
112     }
113
114     @Override
115     public void allItemsChanged(Collection<String> oldItemNames) {
116         clearAccessories();
117     }
118
119     /**
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.
122      *
123      * @param item The item that has been changed or removed.
124      */
125     private synchronized void markDirty(Item item) {
126         logger.trace("Mark dirty item {}", item.getName());
127         pendingUpdates.add(item.getName());
128         /*
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.
131          */
132         for (Item accessoryGroup : HomekitAccessoryFactory.getAccessoryGroups(item, itemRegistry, metadataRegistry)) {
133             pendingUpdates.add(accessoryGroup.getName());
134         }
135         applyUpdatesDebouncer.call();
136     }
137
138     @Override
139     public synchronized void removed(Item item) {
140         markDirty(item);
141     }
142
143     private Optional<Item> getItemOptional(String name) {
144         try {
145             return Optional.of(itemRegistry.getItem(name));
146         } catch (ItemNotFoundException e) {
147             return Optional.empty();
148         }
149     }
150
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,
155                 lastAccessoryCount);
156         storage.put(REVISION_CONFIG, "" + newRevision);
157         storage.put(ACCESSORY_COUNT, "" + lastAccessoryCount);
158     }
159
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);
166         }
167         if (!pendingUpdates.isEmpty()) {
168             makeNewConfigurationRevision();
169             pendingUpdates.clear();
170         }
171     }
172
173     @Override
174     public void updated(Item oldElement, Item element) {
175         markDirty(oldElement);
176         markDirty(element);
177     }
178
179     public int getLastAccessoryCount() {
180         return lastAccessoryCount;
181     }
182
183     public synchronized void clearAccessories() {
184         accessoryRegistry.clear();
185     }
186
187     public synchronized void setBridge(HomekitRoot bridge) {
188         accessoryRegistry.setBridge(bridge);
189     }
190
191     public synchronized void unsetBridge() {
192         applyUpdatesDebouncer.stop();
193         accessoryRegistry.unsetBridge();
194     }
195
196     public void setUpdater(HomekitAccessoryUpdater updater) {
197         this.updater = updater;
198     }
199
200     public void updateSettings(HomekitSettings settings) {
201         this.settings = settings;
202     }
203
204     public void stop() {
205         this.itemRegistry.removeRegistryChangeListener(this);
206     }
207
208     public Map<String, HomekitAccessory> getAccessories() {
209         return this.accessoryRegistry.getAllAccessories();
210     }
211
212     public int getConfigurationRevision() {
213         return this.accessoryRegistry.getConfigurationRevision();
214     }
215
216     /**
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.
226      *
227      * Examples:
228      * // Single Line HomeKit Accessory
229      * Switch light "Light" {homekit="Lighting"}
230      *
231      * // One HomeKit accessory defined using group
232      * Group gLight "Light Group" {homekit="Lighting"}
233      * Switch light "Light" (gLight) {homekit="Lighting.OnState"}
234      *
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"}
238      *
239      * @param item openHAB item
240      */
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))));
251         }
252     }
253
254     private void createRootAccessory(HomekitTaggedItem taggedItem) {
255         try {
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());
260         }
261     }
262 }