]> git.basschouten.com Git - openhab-addons.git/blob
d846c1204641ef26ba0722720d9f4044a25e23f3
[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.hueemulation.internal;
14
15 import java.net.InetAddress;
16 import java.net.UnknownHostException;
17 import java.util.Collections;
18 import java.util.LinkedHashSet;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.UUID;
22 import java.util.concurrent.ScheduledExecutorService;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25 import java.util.stream.Collectors;
26 import java.util.stream.Stream;
27
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.core.config.core.ConfigurableService;
31 import org.openhab.core.config.core.Configuration;
32 import org.openhab.core.common.ThreadPoolManager;
33 import org.openhab.core.items.Item;
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.net.CidrAddress;
38 import org.openhab.core.net.NetUtil;
39 import org.openhab.core.net.NetworkAddressService;
40 import org.openhab.io.hueemulation.internal.dto.HueAuthorizedConfig;
41 import org.openhab.io.hueemulation.internal.dto.HueDataStore;
42 import org.openhab.io.hueemulation.internal.dto.HueGroupEntry;
43 import org.openhab.io.hueemulation.internal.dto.HueLightEntry;
44 import org.openhab.io.hueemulation.internal.dto.HueRuleEntry;
45 import org.openhab.io.hueemulation.internal.dto.HueSensorEntry;
46 import org.openhab.io.hueemulation.internal.dto.response.HueSuccessGeneric;
47 import org.openhab.io.hueemulation.internal.dto.response.HueSuccessResponseStateChanged;
48 import org.osgi.service.cm.ConfigurationAdmin;
49 import org.osgi.service.component.annotations.Activate;
50 import org.osgi.service.component.annotations.Component;
51 import org.osgi.service.component.annotations.Deactivate;
52 import org.osgi.service.component.annotations.Modified;
53 import org.osgi.service.component.annotations.Reference;
54 import org.osgi.service.event.Event;
55 import org.osgi.service.event.EventAdmin;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
58
59 import com.google.gson.Gson;
60 import com.google.gson.GsonBuilder;
61
62 /**
63  * This component sets up the hue data store and gets the service configuration.
64  * It also determines the address for the upnp service by the given configuration.
65  * <p>
66  * Also manages the pairing timeout. The service is restarted after a pairing timeout, due to the ConfigAdmin
67  * configuration change.
68  * <p>
69  * This is a central component and required by all other components and may not
70  * depend on anything in this bundle.
71  *
72  * @author David Graeff - Initial contribution
73  */
74 @Component(immediate = false, service = { ConfigStore.class }, configurationPid = {
75         HueEmulationService.CONFIG_PID }, property = { "com.eclipsesource.jaxrs.publish=false",
76                 ConfigurableService.SERVICE_PROPERTY_DESCRIPTION_URI + "=io:hueemulation",
77                 ConfigurableService.SERVICE_PROPERTY_CATEGORY + "=io",
78                 ConfigurableService.SERVICE_PROPERTY_LABEL + "=Hue Emulation" })
79 @NonNullByDefault
80 public class ConfigStore {
81
82     public static final String METAKEY = "HUEEMU";
83     public static final String EVENT_ADDRESS_CHANGED = "ESH_EMU_CONFIG_ADDR_CHANGED";
84
85     private final Logger logger = LoggerFactory.getLogger(ConfigStore.class);
86
87     public HueDataStore ds = new HueDataStore();
88
89     protected @NonNullByDefault({}) ScheduledExecutorService scheduler;
90     private @Nullable ScheduledFuture<?> pairingOffFuture;
91     private @Nullable ScheduledFuture<?> writeUUIDFuture;
92
93     /**
94      * This is the main gson instance, to be obtained by all components that operate on the dto data fields
95      */
96     public final Gson gson = new GsonBuilder().registerTypeAdapter(HueLightEntry.class, new HueLightEntry.Serializer())
97             .registerTypeAdapter(HueSensorEntry.class, new HueSensorEntry.Serializer())
98             .registerTypeAdapter(HueRuleEntry.Condition.class, new HueRuleEntry.SerializerCondition())
99             .registerTypeAdapter(HueAuthorizedConfig.class, new HueAuthorizedConfig.Serializer())
100             .registerTypeAdapter(HueSuccessGeneric.class, new HueSuccessGeneric.Serializer())
101             .registerTypeAdapter(HueSuccessResponseStateChanged.class, new HueSuccessResponseStateChanged.Serializer())
102             .registerTypeAdapter(HueGroupEntry.class, new HueGroupEntry.Serializer(this)).create();
103
104     @Reference
105     protected @NonNullByDefault({}) ConfigurationAdmin configAdmin;
106
107     @Reference
108     protected @NonNullByDefault({}) NetworkAddressService networkAddressService;
109
110     @Reference
111     protected @NonNullByDefault({}) MetadataRegistry metadataRegistry;
112
113     @Reference
114     protected @NonNullByDefault({}) EventAdmin eventAdmin;
115
116     //// objects, set within activate()
117     private Set<InetAddress> discoveryIps = Collections.emptySet();
118     protected volatile @NonNullByDefault({}) HueEmulationConfig config;
119
120     public Set<String> switchFilter = Collections.emptySet();
121     public Set<String> colorFilter = Collections.emptySet();
122     public Set<String> whiteFilter = Collections.emptySet();
123     public Set<String> ignoreItemsFilter = Collections.emptySet();
124
125     private int highestAssignedHueID = 1;
126
127     public ConfigStore() {
128         scheduler = ThreadPoolManager.getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
129     }
130
131     /**
132      * For test dependency injection
133      *
134      * @param networkAddressService The network address service
135      * @param configAdmin The configuration admin service
136      * @param metadataRegistry The metadataRegistry service
137      */
138     public ConfigStore(NetworkAddressService networkAddressService, ConfigurationAdmin configAdmin,
139             @Nullable MetadataRegistry metadataRegistry, ScheduledExecutorService scheduler) {
140         this.networkAddressService = networkAddressService;
141         this.configAdmin = configAdmin;
142         this.metadataRegistry = metadataRegistry;
143         this.scheduler = scheduler;
144     }
145
146     @Activate
147     public void activate(Map<String, Object> properties) {
148         this.config = new Configuration(properties).as(HueEmulationConfig.class);
149
150         determineHighestAssignedHueID();
151
152         if (config.uuid.isEmpty()) {
153             config.uuid = UUID.randomUUID().toString();
154             writeUUIDFuture = scheduler.schedule(() -> {
155                 logger.info("No unique ID assigned yet. Assigning {} and restarting...", config.uuid);
156                 WriteConfig.setUUID(configAdmin, config.uuid);
157             }, 100, TimeUnit.MILLISECONDS);
158             return;
159         } else {
160             modified(properties);
161         }
162     }
163
164     private @Nullable InetAddress byName(@Nullable String address) {
165         if (address == null) {
166             return null;
167         }
168         try {
169             return InetAddress.getByName(address);
170         } catch (UnknownHostException e) {
171             logger.warn("Given IP address could not be resolved: {}", address, e);
172             return null;
173         }
174     }
175
176     @Modified
177     public void modified(Map<String, Object> properties) {
178         this.config = new Configuration(properties).as(HueEmulationConfig.class);
179
180         switchFilter = Collections.unmodifiableSet(
181                 Stream.of(config.restrictToTagsSwitches.split(",")).map(String::trim).collect(Collectors.toSet()));
182
183         colorFilter = Collections.unmodifiableSet(
184                 Stream.of(config.restrictToTagsColorLights.split(",")).map(String::trim).collect(Collectors.toSet()));
185
186         whiteFilter = Collections.unmodifiableSet(
187                 Stream.of(config.restrictToTagsWhiteLights.split(",")).map(String::trim).collect(Collectors.toSet()));
188
189         ignoreItemsFilter = Collections.unmodifiableSet(
190                 Stream.of(config.ignoreItemsWithTags.split(",")).map(String::trim).collect(Collectors.toSet()));
191
192         // Use either the user configured
193         InetAddress configuredAddress = null;
194         int networkPrefixLength = 24; // Default for most networks: 255.255.255.0
195
196         if (config.discoveryIp != null) {
197             discoveryIps = Collections.unmodifiableSet(Stream.of(config.discoveryIp.split(",")).map(String::trim)
198                     .map(this::byName).filter(e -> e != null).collect(Collectors.toSet()));
199         } else {
200             discoveryIps = new LinkedHashSet<>();
201             configuredAddress = byName(networkAddressService.getPrimaryIpv4HostAddress());
202             if (configuredAddress != null) {
203                 discoveryIps.add(configuredAddress);
204             }
205             for (CidrAddress a : NetUtil.getAllInterfaceAddresses()) {
206                 if (a.getAddress().equals(configuredAddress)) {
207                     networkPrefixLength = a.getPrefix();
208                 } else {
209                     discoveryIps.add(a.getAddress());
210                 }
211             }
212         }
213
214         if (discoveryIps.isEmpty()) {
215             try {
216                 logger.info("No discovery ip specified. Trying to determine the host address");
217                 configuredAddress = InetAddress.getLocalHost();
218             } catch (Exception e) {
219                 logger.info("Host address cannot be determined. Trying loopback address");
220                 configuredAddress = InetAddress.getLoopbackAddress();
221             }
222         } else {
223             configuredAddress = discoveryIps.iterator().next();
224         }
225
226         logger.info("Using discovery ip {}", configuredAddress.getHostAddress());
227
228         // Get and apply configurations
229         ds.config.createNewUserOnEveryEndpoint = config.createNewUserOnEveryEndpoint;
230         ds.config.networkopenduration = config.pairingTimeout;
231         ds.config.devicename = config.devicename;
232
233         ds.config.uuid = config.uuid;
234         ds.config.bridgeid = config.uuid.replace("-", "").toUpperCase();
235         if (ds.config.bridgeid.length() > 12) {
236             ds.config.bridgeid = ds.config.bridgeid.substring(0, 12);
237         }
238
239         if (config.permanentV1bridge) {
240             ds.config.makeV1bridge();
241         }
242
243         setLinkbutton(config.pairingEnabled, config.createNewUserOnEveryEndpoint, config.temporarilyEmulateV1bridge);
244         ds.config.mac = NetworkUtils.getMAC(configuredAddress);
245         ds.config.ipaddress = getConfiguredHostAddress(configuredAddress);
246         ds.config.netmask = networkPrefixLength < 32 ? NetUtil.networkPrefixLengthToNetmask(networkPrefixLength)
247                 : "255.255.255.0";
248
249         if (eventAdmin != null) {
250             eventAdmin.postEvent(new Event(EVENT_ADDRESS_CHANGED, Collections.emptyMap()));
251         }
252     }
253
254     private String getConfiguredHostAddress(InetAddress configuredAddress) {
255         String hostAddress = configuredAddress.getHostAddress();
256         int percentIndex = hostAddress.indexOf("%");
257         if (percentIndex != -1) {
258             return hostAddress.substring(0, percentIndex);
259         } else {
260             return hostAddress;
261         }
262     }
263
264     @Deactivate
265     public void deactive(int reason) {
266         ScheduledFuture<?> future = pairingOffFuture;
267         if (future != null) {
268             future.cancel(false);
269         }
270         future = writeUUIDFuture;
271         if (future != null) {
272             future.cancel(false);
273         }
274     }
275
276     protected void determineHighestAssignedHueID() {
277         for (Metadata metadata : metadataRegistry.getAll()) {
278             if (!metadata.getUID().getNamespace().equals(METAKEY)) {
279                 continue;
280             }
281             try {
282                 int hueId = Integer.parseInt(metadata.getValue());
283                 if (hueId > highestAssignedHueID) {
284                     highestAssignedHueID = hueId;
285                 }
286             } catch (NumberFormatException e) {
287                 logger.warn("A non numeric hue ID '{}' was assigned. Ignoring!", metadata.getValue());
288             }
289         }
290     }
291
292     /**
293      * Although hue IDs are strings, a lot of implementations out there assume them to be numbers. Therefore
294      * we map each item to a number and store that in the meta data provider.
295      *
296      * @param item The item to map
297      * @return A stringified integer number
298      */
299     public String mapItemUIDtoHueID(Item item) {
300         MetadataKey key = new MetadataKey(METAKEY, item.getUID());
301         Metadata metadata = metadataRegistry.get(key);
302         int hueId = 0;
303         if (metadata != null) {
304             try {
305                 hueId = Integer.parseInt(metadata.getValue());
306             } catch (NumberFormatException e) {
307                 logger.warn("A non numeric hue ID '{}' was assigned. Ignore and reassign a different id now!",
308                         metadata.getValue());
309             }
310         }
311         if (hueId == 0) {
312             ++highestAssignedHueID;
313             hueId = highestAssignedHueID;
314             metadataRegistry.add(new Metadata(key, String.valueOf(hueId), null));
315         }
316
317         return String.valueOf(hueId);
318     }
319
320     public boolean isReady() {
321         return !discoveryIps.isEmpty();
322     }
323
324     public HueEmulationConfig getConfig() {
325         return config;
326     }
327
328     public int getHighestAssignedHueID() {
329         return highestAssignedHueID;
330     }
331
332     /**
333      * Sets the link button state.
334      *
335      * Starts a pairing timeout thread if set to true.
336      * Stops any already running timers.
337      *
338      * @param linkbutton New link button state
339      */
340     public void setLinkbutton(boolean linkbutton, boolean createUsersOnEveryEndpoint,
341             boolean temporarilyEmulateV1bridge) {
342         ds.config.linkbutton = linkbutton;
343         config.createNewUserOnEveryEndpoint = createUsersOnEveryEndpoint;
344         if (temporarilyEmulateV1bridge) {
345             ds.config.makeV1bridge();
346         } else if (!config.permanentV1bridge) {
347             ds.config.makeV2bridge();
348         }
349         ScheduledFuture<?> future = pairingOffFuture;
350         if (future != null) {
351             future.cancel(false);
352         }
353         if (!linkbutton) {
354             logger.info("Hue Emulation pairing disabled");
355             return;
356         }
357
358         logger.info("Hue Emulation pairing enabled for {}s", ds.config.networkopenduration);
359         pairingOffFuture = scheduler.schedule(() -> {
360             logger.info("Hue Emulation disable pairing...");
361             if (!config.permanentV1bridge) { // Restore bridge version
362                 ds.config.makeV2bridge();
363             }
364             config.createNewUserOnEveryEndpoint = false;
365             config.temporarilyEmulateV1bridge = false;
366             WriteConfig.unsetPairingMode(configAdmin);
367         }, ds.config.networkopenduration * 1000, TimeUnit.MILLISECONDS);
368     }
369
370     public Set<InetAddress> getDiscoveryIps() {
371         return discoveryIps;
372     }
373 }