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