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.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;
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 = HueEmulationService.CONFIG_PID)
75 @ConfigurableService(category = "io", label = "Hue Emulation", description_uri = "io:hueemulation")
77 public class ConfigStore {
79 public static final String METAKEY = "HUEEMU";
80 public static final String EVENT_ADDRESS_CHANGED = "ESH_EMU_CONFIG_ADDR_CHANGED";
82 private final Logger logger = LoggerFactory.getLogger(ConfigStore.class);
84 public HueDataStore ds = new HueDataStore();
86 protected @NonNullByDefault({}) ScheduledExecutorService scheduler;
87 private @Nullable ScheduledFuture<?> pairingOffFuture;
88 private @Nullable ScheduledFuture<?> writeUUIDFuture;
91 * This is the main gson instance, to be obtained by all components that operate on the dto data fields
93 public final Gson gson = new GsonBuilder().registerTypeAdapter(HueLightEntry.class, new HueLightEntry.Serializer())
94 .registerTypeAdapter(HueSensorEntry.class, new HueSensorEntry.Serializer())
95 .registerTypeAdapter(HueRuleEntry.Condition.class, new HueRuleEntry.SerializerCondition())
96 .registerTypeAdapter(HueAuthorizedConfig.class, new HueAuthorizedConfig.Serializer())
97 .registerTypeAdapter(HueSuccessGeneric.class, new HueSuccessGeneric.Serializer())
98 .registerTypeAdapter(HueSuccessResponseStateChanged.class, new HueSuccessResponseStateChanged.Serializer())
99 .registerTypeAdapter(HueGroupEntry.class, new HueGroupEntry.Serializer(this)).create();
102 protected @NonNullByDefault({}) ConfigurationAdmin configAdmin;
105 protected @NonNullByDefault({}) NetworkAddressService networkAddressService;
108 protected @NonNullByDefault({}) MetadataRegistry metadataRegistry;
111 protected @NonNullByDefault({}) EventAdmin eventAdmin;
113 //// objects, set within activate()
114 private Set<InetAddress> discoveryIps = Collections.emptySet();
115 protected volatile @NonNullByDefault({}) HueEmulationConfig config;
117 public Set<String> switchFilter = Collections.emptySet();
118 public Set<String> colorFilter = Collections.emptySet();
119 public Set<String> whiteFilter = Collections.emptySet();
120 public Set<String> ignoreItemsFilter = Collections.emptySet();
122 private int highestAssignedHueID = 1;
124 public ConfigStore() {
125 scheduler = ThreadPoolManager.getScheduledPool(ThreadPoolManager.THREAD_POOL_NAME_COMMON);
129 * For test dependency injection
131 * @param networkAddressService The network address service
132 * @param configAdmin The configuration admin service
133 * @param metadataRegistry The metadataRegistry service
135 public ConfigStore(NetworkAddressService networkAddressService, ConfigurationAdmin configAdmin,
136 @Nullable MetadataRegistry metadataRegistry, ScheduledExecutorService scheduler) {
137 this.networkAddressService = networkAddressService;
138 this.configAdmin = configAdmin;
139 this.metadataRegistry = metadataRegistry;
140 this.scheduler = scheduler;
144 public void activate(Map<String, Object> properties) {
145 this.config = new Configuration(properties).as(HueEmulationConfig.class);
147 determineHighestAssignedHueID();
149 if (config.uuid.isEmpty()) {
150 config.uuid = UUID.randomUUID().toString();
151 writeUUIDFuture = scheduler.schedule(() -> {
152 logger.info("No unique ID assigned yet. Assigning {} and restarting...", config.uuid);
153 WriteConfig.setUUID(configAdmin, config.uuid);
154 }, 100, TimeUnit.MILLISECONDS);
157 modified(properties);
161 private @Nullable InetAddress byName(@Nullable String address) {
162 if (address == null) {
166 return InetAddress.getByName(address);
167 } catch (UnknownHostException e) {
168 logger.warn("Given IP address could not be resolved: {}", address, e);
174 public void modified(Map<String, Object> properties) {
175 this.config = new Configuration(properties).as(HueEmulationConfig.class);
177 switchFilter = Collections.unmodifiableSet(
178 Stream.of(config.restrictToTagsSwitches.split(",")).map(String::trim).collect(Collectors.toSet()));
180 colorFilter = Collections.unmodifiableSet(
181 Stream.of(config.restrictToTagsColorLights.split(",")).map(String::trim).collect(Collectors.toSet()));
183 whiteFilter = Collections.unmodifiableSet(
184 Stream.of(config.restrictToTagsWhiteLights.split(",")).map(String::trim).collect(Collectors.toSet()));
186 ignoreItemsFilter = Collections.unmodifiableSet(
187 Stream.of(config.ignoreItemsWithTags.split(",")).map(String::trim).collect(Collectors.toSet()));
189 // Use either the user configured
190 InetAddress configuredAddress = null;
191 int networkPrefixLength = 24; // Default for most networks: 255.255.255.0
193 if (config.discoveryIp != null) {
194 discoveryIps = Collections.unmodifiableSet(Stream.of(config.discoveryIp.split(",")).map(String::trim)
195 .map(this::byName).filter(e -> e != null).collect(Collectors.toSet()));
197 discoveryIps = new LinkedHashSet<>();
198 configuredAddress = byName(networkAddressService.getPrimaryIpv4HostAddress());
199 if (configuredAddress != null) {
200 discoveryIps.add(configuredAddress);
202 for (CidrAddress a : NetUtil.getAllInterfaceAddresses()) {
203 if (a.getAddress().equals(configuredAddress)) {
204 networkPrefixLength = a.getPrefix();
206 discoveryIps.add(a.getAddress());
211 if (discoveryIps.isEmpty()) {
213 logger.info("No discovery ip specified. Trying to determine the host address");
214 configuredAddress = InetAddress.getLocalHost();
215 } catch (Exception e) {
216 logger.info("Host address cannot be determined. Trying loopback address");
217 configuredAddress = InetAddress.getLoopbackAddress();
220 configuredAddress = discoveryIps.iterator().next();
223 logger.info("Using discovery ip {}", configuredAddress.getHostAddress());
225 // Get and apply configurations
226 ds.config.createNewUserOnEveryEndpoint = config.createNewUserOnEveryEndpoint;
227 ds.config.networkopenduration = config.pairingTimeout;
228 ds.config.devicename = config.devicename;
230 ds.config.uuid = config.uuid;
231 ds.config.bridgeid = config.uuid.replace("-", "").toUpperCase();
232 if (ds.config.bridgeid.length() > 12) {
233 ds.config.bridgeid = ds.config.bridgeid.substring(0, 12);
236 if (config.permanentV1bridge) {
237 ds.config.makeV1bridge();
240 setLinkbutton(config.pairingEnabled, config.createNewUserOnEveryEndpoint, config.temporarilyEmulateV1bridge);
241 ds.config.mac = NetworkUtils.getMAC(configuredAddress);
242 ds.config.ipaddress = getConfiguredHostAddress(configuredAddress);
243 ds.config.netmask = networkPrefixLength < 32 ? NetUtil.networkPrefixLengthToNetmask(networkPrefixLength)
246 if (eventAdmin != null) {
247 eventAdmin.postEvent(new Event(EVENT_ADDRESS_CHANGED, Collections.emptyMap()));
251 private String getConfiguredHostAddress(InetAddress configuredAddress) {
252 String hostAddress = configuredAddress.getHostAddress();
253 int percentIndex = hostAddress.indexOf("%");
254 if (percentIndex != -1) {
255 return hostAddress.substring(0, percentIndex);
262 public void deactive(int reason) {
263 ScheduledFuture<?> future = pairingOffFuture;
264 if (future != null) {
265 future.cancel(false);
267 future = writeUUIDFuture;
268 if (future != null) {
269 future.cancel(false);
273 protected void determineHighestAssignedHueID() {
274 for (Metadata metadata : metadataRegistry.getAll()) {
275 if (!metadata.getUID().getNamespace().equals(METAKEY)) {
279 int hueId = Integer.parseInt(metadata.getValue());
280 if (hueId > highestAssignedHueID) {
281 highestAssignedHueID = hueId;
283 } catch (NumberFormatException e) {
284 logger.warn("A non numeric hue ID '{}' was assigned. Ignoring!", metadata.getValue());
290 * Although hue IDs are strings, a lot of implementations out there assume them to be numbers. Therefore
291 * we map each item to a number and store that in the meta data provider.
293 * @param item The item to map
294 * @return A stringified integer number
296 public String mapItemUIDtoHueID(Item item) {
297 MetadataKey key = new MetadataKey(METAKEY, item.getUID());
298 Metadata metadata = metadataRegistry.get(key);
300 if (metadata != null) {
302 hueId = Integer.parseInt(metadata.getValue());
303 } catch (NumberFormatException e) {
304 logger.warn("A non numeric hue ID '{}' was assigned. Ignore and reassign a different id now!",
305 metadata.getValue());
309 ++highestAssignedHueID;
310 hueId = highestAssignedHueID;
311 metadataRegistry.add(new Metadata(key, String.valueOf(hueId), null));
314 return String.valueOf(hueId);
317 public boolean isReady() {
318 return !discoveryIps.isEmpty();
321 public HueEmulationConfig getConfig() {
325 public int getHighestAssignedHueID() {
326 return highestAssignedHueID;
330 * Sets the link button state.
332 * Starts a pairing timeout thread if set to true.
333 * Stops any already running timers.
335 * @param linkbutton New link button state
337 public void setLinkbutton(boolean linkbutton, boolean createUsersOnEveryEndpoint,
338 boolean temporarilyEmulateV1bridge) {
339 ds.config.linkbutton = linkbutton;
340 config.createNewUserOnEveryEndpoint = createUsersOnEveryEndpoint;
341 if (temporarilyEmulateV1bridge) {
342 ds.config.makeV1bridge();
343 } else if (!config.permanentV1bridge) {
344 ds.config.makeV2bridge();
346 ScheduledFuture<?> future = pairingOffFuture;
347 if (future != null) {
348 future.cancel(false);
351 logger.info("Hue Emulation pairing disabled");
355 logger.info("Hue Emulation pairing enabled for {}s", ds.config.networkopenduration);
356 pairingOffFuture = scheduler.schedule(() -> {
357 logger.info("Hue Emulation disable pairing...");
358 if (!config.permanentV1bridge) { // Restore bridge version
359 ds.config.makeV2bridge();
361 config.createNewUserOnEveryEndpoint = false;
362 config.temporarilyEmulateV1bridge = false;
363 WriteConfig.unsetPairingMode(configAdmin);
364 }, ds.config.networkopenduration * 1000, TimeUnit.MILLISECONDS);
367 public Set<InetAddress> getDiscoveryIps() {