2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.io.hueemulation.internal;
15 import java.net.InetAddress;
16 import java.net.UnknownHostException;
17 import java.util.Collections;
18 import java.util.LinkedHashSet;
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;
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;
59 import com.google.gson.Gson;
60 import com.google.gson.GsonBuilder;
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.
66 * Also manages the pairing timeout. The service is restarted after a pairing timeout, due to the ConfigAdmin
67 * configuration change.
69 * This is a central component and required by all other components and may not
70 * depend on anything in this bundle.
72 * @author David Graeff - Initial contribution
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" })
80 public class ConfigStore {
82 public static final String METAKEY = "HUEEMU";
83 public static final String EVENT_ADDRESS_CHANGED = "ESH_EMU_CONFIG_ADDR_CHANGED";
85 private final Logger logger = LoggerFactory.getLogger(ConfigStore.class);
87 public HueDataStore ds = new HueDataStore();
89 protected @NonNullByDefault({}) ScheduledExecutorService scheduler;
90 private @Nullable ScheduledFuture<?> pairingOffFuture;
91 private @Nullable ScheduledFuture<?> writeUUIDFuture;
94 * This is the main gson instance, to be obtained by all components that operate on the dto data fields
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();
105 protected @NonNullByDefault({}) ConfigurationAdmin configAdmin;
108 protected @NonNullByDefault({}) NetworkAddressService networkAddressService;
111 protected @NonNullByDefault({}) MetadataRegistry metadataRegistry;
114 protected @NonNullByDefault({}) EventAdmin eventAdmin;
116 //// objects, set within activate()
117 private Set<InetAddress> discoveryIps = Collections.emptySet();
118 protected volatile @NonNullByDefault({}) HueEmulationConfig config;
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();
125 private int highestAssignedHueID = 1;
127 public ConfigStore() {
128 scheduler = ThreadPoolManager.getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
132 * For test dependency injection
134 * @param networkAddressService The network address service
135 * @param configAdmin The configuration admin service
136 * @param metadataRegistry The metadataRegistry service
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;
147 public void activate(Map<String, Object> properties) {
148 this.config = new Configuration(properties).as(HueEmulationConfig.class);
150 determineHighestAssignedHueID();
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);
160 modified(properties);
164 private @Nullable InetAddress byName(@Nullable String address) {
165 if (address == null) {
169 return InetAddress.getByName(address);
170 } catch (UnknownHostException e) {
171 logger.warn("Given IP address could not be resolved: {}", address, e);
177 public void modified(Map<String, Object> properties) {
178 this.config = new Configuration(properties).as(HueEmulationConfig.class);
180 switchFilter = Collections.unmodifiableSet(
181 Stream.of(config.restrictToTagsSwitches.split(",")).map(String::trim).collect(Collectors.toSet()));
183 colorFilter = Collections.unmodifiableSet(
184 Stream.of(config.restrictToTagsColorLights.split(",")).map(String::trim).collect(Collectors.toSet()));
186 whiteFilter = Collections.unmodifiableSet(
187 Stream.of(config.restrictToTagsWhiteLights.split(",")).map(String::trim).collect(Collectors.toSet()));
189 ignoreItemsFilter = Collections.unmodifiableSet(
190 Stream.of(config.ignoreItemsWithTags.split(",")).map(String::trim).collect(Collectors.toSet()));
192 // Use either the user configured
193 InetAddress configuredAddress = null;
194 int networkPrefixLength = 24; // Default for most networks: 255.255.255.0
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()));
200 discoveryIps = new LinkedHashSet<>();
201 configuredAddress = byName(networkAddressService.getPrimaryIpv4HostAddress());
202 if (configuredAddress != null) {
203 discoveryIps.add(configuredAddress);
205 for (CidrAddress a : NetUtil.getAllInterfaceAddresses()) {
206 if (a.getAddress().equals(configuredAddress)) {
207 networkPrefixLength = a.getPrefix();
209 discoveryIps.add(a.getAddress());
214 if (discoveryIps.isEmpty()) {
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();
223 configuredAddress = discoveryIps.iterator().next();
226 logger.info("Using discovery ip {}", configuredAddress.getHostAddress());
228 // Get and apply configurations
229 ds.config.createNewUserOnEveryEndpoint = config.createNewUserOnEveryEndpoint;
230 ds.config.networkopenduration = config.pairingTimeout;
231 ds.config.devicename = config.devicename;
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);
239 if (config.permanentV1bridge) {
240 ds.config.makeV1bridge();
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)
249 if (eventAdmin != null) {
250 eventAdmin.postEvent(new Event(EVENT_ADDRESS_CHANGED, Collections.emptyMap()));
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);
265 public void deactive(int reason) {
266 ScheduledFuture<?> future = pairingOffFuture;
267 if (future != null) {
268 future.cancel(false);
270 future = writeUUIDFuture;
271 if (future != null) {
272 future.cancel(false);
276 protected void determineHighestAssignedHueID() {
277 for (Metadata metadata : metadataRegistry.getAll()) {
278 if (!metadata.getUID().getNamespace().equals(METAKEY)) {
282 int hueId = Integer.parseInt(metadata.getValue());
283 if (hueId > highestAssignedHueID) {
284 highestAssignedHueID = hueId;
286 } catch (NumberFormatException e) {
287 logger.warn("A non numeric hue ID '{}' was assigned. Ignoring!", metadata.getValue());
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.
296 * @param item The item to map
297 * @return A stringified integer number
299 public String mapItemUIDtoHueID(Item item) {
300 MetadataKey key = new MetadataKey(METAKEY, item.getUID());
301 Metadata metadata = metadataRegistry.get(key);
303 if (metadata != null) {
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());
312 ++highestAssignedHueID;
313 hueId = highestAssignedHueID;
314 metadataRegistry.add(new Metadata(key, String.valueOf(hueId), null));
317 return String.valueOf(hueId);
320 public boolean isReady() {
321 return !discoveryIps.isEmpty();
324 public HueEmulationConfig getConfig() {
328 public int getHighestAssignedHueID() {
329 return highestAssignedHueID;
333 * Sets the link button state.
335 * Starts a pairing timeout thread if set to true.
336 * Stops any already running timers.
338 * @param linkbutton New link button state
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();
349 ScheduledFuture<?> future = pairingOffFuture;
350 if (future != null) {
351 future.cancel(false);
354 logger.info("Hue Emulation pairing disabled");
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();
364 config.createNewUserOnEveryEndpoint = false;
365 config.temporarilyEmulateV1bridge = false;
366 WriteConfig.unsetPairingMode(configAdmin);
367 }, ds.config.networkopenduration * 1000, TimeUnit.MILLISECONDS);
370 public Set<InetAddress> getDiscoveryIps() {