]> git.basschouten.com Git - openhab-addons.git/blob
f607bd25e271cf1a4f38c5a5869f23174bdc64c8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.binding.hue.internal.discovery;
14
15 import static org.openhab.binding.hue.internal.HueBindingConstants.*;
16
17 import java.net.URL;
18 import java.util.Dictionary;
19 import java.util.Map;
20 import java.util.Set;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23 import java.util.regex.PatternSyntaxException;
24
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.jupnp.model.meta.DeviceDetails;
28 import org.jupnp.model.meta.ModelDetails;
29 import org.jupnp.model.meta.RemoteDevice;
30 import org.openhab.binding.hue.internal.handler.HueBridgeHandler;
31 import org.openhab.core.config.discovery.DiscoveryResult;
32 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
33 import org.openhab.core.config.discovery.DiscoveryService;
34 import org.openhab.core.config.discovery.upnp.UpnpDiscoveryParticipant;
35 import org.openhab.core.thing.Thing;
36 import org.openhab.core.thing.ThingTypeUID;
37 import org.openhab.core.thing.ThingUID;
38 import org.osgi.service.component.ComponentContext;
39 import org.osgi.service.component.annotations.Activate;
40 import org.osgi.service.component.annotations.Component;
41 import org.osgi.service.component.annotations.Modified;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
44
45 /**
46  * The {@link HueBridgeUPNPDiscoveryParticipant} is responsible for discovering new and removed Hue Bridges. It uses the
47  * central {@link org.openhab.core.config.discovery.upnp.internal.UpnpDiscoveryService}.
48  *
49  * The discovery through UPnP was replaced by mDNS discovery for recent bridges (V2).
50  * For old bridges (V1), the UPnP discovery is still required (as mDNS is not implemented).
51  * This class allows discovering only old bridges using UPnP.
52  *
53  * @author Laurent Garnier - Initial contribution
54  */
55 @Component(configurationPid = "discovery.hue")
56 @NonNullByDefault
57 public class HueBridgeUPNPDiscoveryParticipant implements UpnpDiscoveryParticipant {
58
59     private static final String EXPECTED_MODEL_NAME_PREFIX = "Philips hue bridge";
60
61     private final Logger logger = LoggerFactory.getLogger(HueBridgeUPNPDiscoveryParticipant.class);
62
63     private long removalGracePeriod = 50L;
64
65     private boolean isAutoDiscoveryEnabled = true;
66
67     @Activate
68     protected void activate(ComponentContext componentContext) {
69         activateOrModifyService(componentContext);
70     }
71
72     @Modified
73     protected void modified(ComponentContext componentContext) {
74         activateOrModifyService(componentContext);
75     }
76
77     private void activateOrModifyService(ComponentContext componentContext) {
78         Dictionary<String, @Nullable Object> properties = componentContext.getProperties();
79         String autoDiscoveryPropertyValue = (String) properties
80                 .get(DiscoveryService.CONFIG_PROPERTY_BACKGROUND_DISCOVERY);
81         if (autoDiscoveryPropertyValue != null && !autoDiscoveryPropertyValue.isBlank()) {
82             isAutoDiscoveryEnabled = Boolean.valueOf(autoDiscoveryPropertyValue);
83         }
84         String removalGracePeriodPropertyValue = (String) properties.get(REMOVAL_GRACE_PERIOD);
85         if (removalGracePeriodPropertyValue != null && !removalGracePeriodPropertyValue.isBlank()) {
86             try {
87                 removalGracePeriod = Long.parseLong(removalGracePeriodPropertyValue);
88             } catch (NumberFormatException e) {
89                 logger.warn("Configuration property '{}' has invalid value: {}", REMOVAL_GRACE_PERIOD,
90                         removalGracePeriodPropertyValue);
91             }
92         }
93     }
94
95     @Override
96     public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
97         return HueBridgeHandler.SUPPORTED_THING_TYPES;
98     }
99
100     @Override
101     public @Nullable DiscoveryResult createResult(RemoteDevice device) {
102         if (!isAutoDiscoveryEnabled) {
103             return null;
104         }
105         DeviceDetails details = device.getDetails();
106         ThingUID uid = getThingUID(device);
107         if (details == null || uid == null) {
108             return null;
109         }
110         URL baseUrl = details.getBaseURL();
111         String serialNumber = details.getSerialNumber();
112         if (baseUrl == null || serialNumber == null || serialNumber.isBlank()) {
113             return null;
114         }
115         String label = String.format(DISCOVERY_LABEL_PATTERN, baseUrl.getHost());
116         String modelName = EXPECTED_MODEL_NAME_PREFIX;
117         ModelDetails modelDetails = details.getModelDetails();
118         if (modelDetails != null && modelDetails.getModelName() != null && modelDetails.getModelNumber() != null) {
119             modelName = String.format("%s (%s)", modelDetails.getModelName(), modelDetails.getModelNumber());
120         }
121         return DiscoveryResultBuilder.create(uid) //
122                 .withProperties(Map.of( //
123                         HOST, baseUrl.getHost(), //
124                         PORT, baseUrl.getPort(), //
125                         PROTOCOL, baseUrl.getProtocol(), //
126                         Thing.PROPERTY_MODEL_ID, modelName, //
127                         Thing.PROPERTY_SERIAL_NUMBER, serialNumber.toLowerCase())) //
128                 .withLabel(label) //
129                 .withRepresentationProperty(Thing.PROPERTY_SERIAL_NUMBER) //
130                 .build();
131     }
132
133     @Override
134     public @Nullable ThingUID getThingUID(RemoteDevice device) {
135         DeviceDetails details = device.getDetails();
136         if (details == null) {
137             return null;
138         }
139         String serialNumber = details.getSerialNumber();
140         ModelDetails modelDetails = details.getModelDetails();
141         if (serialNumber == null || serialNumber.isBlank() || modelDetails == null) {
142             return null;
143         }
144         String modelName = modelDetails.getModelName();
145         // Model name has the format "Philips hue bridge <year>" with <year> being 2012
146         // for a hue bridge V1 or 2015 for a hue bridge V2.
147         if (modelName == null || !modelName.startsWith(EXPECTED_MODEL_NAME_PREFIX)) {
148             return null;
149         }
150         try {
151             Pattern pattern = Pattern.compile("\\d{4}");
152             Matcher matcher = pattern.matcher(modelName);
153             int year = Integer.parseInt(matcher.find() ? matcher.group() : "9999");
154             // The bridge is ignored if year is greater or equal to 2015
155             if (year >= 2015) {
156                 return null;
157             }
158         } catch (PatternSyntaxException | NumberFormatException e) {
159             // No int value found, this bridge is ignored
160             return null;
161         }
162         return new ThingUID(THING_TYPE_BRIDGE, serialNumber.toLowerCase());
163     }
164
165     @Override
166     public long getRemovalGracePeriodSeconds(RemoteDevice device) {
167         return removalGracePeriod;
168     }
169 }