2 * Copyright (c) 2010-2021 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.binding.shelly.internal.discovery;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
17 import static org.openhab.core.thing.Thing.PROPERTY_MODEL_ID;
19 import java.io.IOException;
22 import java.util.TreeMap;
24 import javax.jmdns.ServiceInfo;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.eclipse.jetty.client.HttpClient;
29 import org.openhab.binding.shelly.internal.api.ShellyApiException;
30 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
31 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
32 import org.openhab.binding.shelly.internal.api.ShellyHttpApi;
33 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
34 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
35 import org.openhab.binding.shelly.internal.handler.ShellyBaseHandler;
36 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
37 import org.openhab.core.config.discovery.DiscoveryResult;
38 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
39 import org.openhab.core.config.discovery.mdns.MDNSDiscoveryParticipant;
40 import org.openhab.core.i18n.LocaleProvider;
41 import org.openhab.core.io.net.http.HttpClientFactory;
42 import org.openhab.core.thing.ThingTypeUID;
43 import org.openhab.core.thing.ThingUID;
44 import org.osgi.service.cm.Configuration;
45 import org.osgi.service.cm.ConfigurationAdmin;
46 import org.osgi.service.component.ComponentContext;
47 import org.osgi.service.component.annotations.Activate;
48 import org.osgi.service.component.annotations.Component;
49 import org.osgi.service.component.annotations.Modified;
50 import org.osgi.service.component.annotations.Reference;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * This class identifies Shelly devices by their mDNS service information.
57 * @author Markus Michels - Initial contribution
60 @Component(service = MDNSDiscoveryParticipant.class)
61 public class ShellyDiscoveryParticipant implements MDNSDiscoveryParticipant {
62 private final Logger logger = LoggerFactory.getLogger(ShellyDiscoveryParticipant.class);
63 private final ShellyBindingConfiguration bindingConfig = new ShellyBindingConfiguration();
64 private final ShellyTranslationProvider messages;
65 private final HttpClient httpClient;
66 private final ConfigurationAdmin configurationAdmin;
69 public ShellyDiscoveryParticipant(@Reference ConfigurationAdmin configurationAdmin,
70 @Reference HttpClientFactory httpClientFactory, @Reference LocaleProvider localeProvider,
71 @Reference ShellyTranslationProvider translationProvider, ComponentContext componentContext) {
72 logger.debug("Activating ShellyDiscovery service");
73 this.configurationAdmin = configurationAdmin;
74 this.messages = translationProvider;
75 this.httpClient = httpClientFactory.getCommonHttpClient();
76 bindingConfig.updateFromProperties(componentContext.getProperties());
80 public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
81 return SUPPORTED_THING_TYPES_UIDS;
85 public String getServiceType() {
90 * Process updates to Binding Config
92 * @param componentContext
95 protected void modified(final ComponentContext componentContext) {
96 logger.debug("Shelly Binding Configuration refreshed");
97 bindingConfig.updateFromProperties(componentContext.getProperties());
102 public DiscoveryResult createResult(final ServiceInfo service) {
103 String name = service.getName().toLowerCase(); // Duao: Name starts with" Shelly" rather than "shelly"
104 if (!name.startsWith("shelly")) {
111 String model = "unknown";
112 String deviceName = "";
113 ThingUID thingUID = null;
114 ShellyDeviceProfile profile = null;
115 Map<String, Object> properties = new TreeMap<>();
117 name = service.getName().toLowerCase();
118 address = service.getHostAddress();
119 if ((address == null) || address.isEmpty()) {
120 logger.trace("{}: Shelly device discovered with empty IP address (service-name={})", name, service);
123 String thingType = service.getQualifiedName().contains(SERVICE_TYPE) && name.contains("-")
124 ? substringBeforeLast(name, "-")
126 logger.debug("{}: Shelly device discovered: IP-Adress={}, type={}", name, address, thingType);
128 // Get device settings
129 Configuration serviceConfig = configurationAdmin.getConfiguration("binding.shelly");
130 if (serviceConfig.getProperties() != null) {
131 bindingConfig.updateFromProperties(serviceConfig.getProperties());
134 ShellyThingConfiguration config = new ShellyThingConfiguration();
135 config.deviceIp = address;
136 config.userId = bindingConfig.defaultUserId;
137 config.password = bindingConfig.defaultPassword;
140 ShellyHttpApi api = new ShellyHttpApi(name, config, httpClient);
142 profile = api.getDeviceProfile(thingType);
143 logger.debug("{}: Shelly settings : {}", name, profile.settingsJson);
144 deviceName = getString(profile.settings.name);
145 model = getString(profile.settings.device.type);
148 properties = ShellyBaseHandler.fillDeviceProperties(profile);
149 logger.trace("{}: thingType={}, deviceType={}, mode={}, symbolic name={}", name, thingType,
150 profile.deviceType, mode.isEmpty() ? "<standard>" : mode, deviceName);
152 // get thing type from device name
153 thingUID = ShellyThingCreator.getThingUID(name, model, mode, false);
154 } catch (ShellyApiException e) {
155 ShellyApiResult result = e.getApiResult();
156 if (result.isHttpAccessUnauthorized()) {
157 logger.info("{}: {}", name, messages.get("discovery.protected", address));
159 // create shellyunknown thing - will be changed during thing initialization with valid credentials
160 thingUID = ShellyThingCreator.getThingUID(name, model, mode, true);
162 logger.info("{}: {}", name, messages.get("discovery.failed", address, e.toString()));
164 } catch (IllegalArgumentException e) { // maybe some format description was buggy
165 logger.debug("{}: Discovery failed!", name, e);
168 if (thingUID != null) {
169 addProperty(properties, CONFIG_DEVICEIP, address);
170 addProperty(properties, PROPERTY_MODEL_ID, model);
171 addProperty(properties, PROPERTY_SERVICE_NAME, name);
172 addProperty(properties, PROPERTY_DEV_NAME, deviceName);
173 addProperty(properties, PROPERTY_DEV_TYPE, thingType);
174 addProperty(properties, PROPERTY_DEV_MODE, mode);
176 logger.debug("{}: Adding Shelly {}, UID={}", name, deviceName, thingUID.getAsString());
177 String thingLabel = deviceName.isEmpty() ? name + " - " + address
178 : deviceName + " (" + name + "@" + address + ")";
179 return DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel(thingLabel)
180 .withRepresentationProperty(PROPERTY_DEV_NAME).build();
182 } catch (IOException | NullPointerException e) {
183 // maybe some format description was buggy
184 logger.debug("{}: Exception on processing serviceInfo '{}'", name, service.getNiceTextString(), e);
189 private void addProperty(Map<String, Object> properties, String key, @Nullable String value) {
190 properties.put(key, value != null ? value : "");
195 public ThingUID getThingUID(@Nullable ServiceInfo service) throws IllegalArgumentException {
196 logger.debug("ServiceInfo {}", service);
197 if (service == null) {
198 throw new IllegalArgumentException("service must not be null!");
200 String serviceName = service.getName();
201 if (serviceName == null) {
202 throw new IllegalArgumentException("serviceName must not be null!");
204 serviceName = serviceName.toLowerCase();
205 if (!serviceName.contains(VENDOR.toLowerCase())) {
206 logger.debug("Not a " + VENDOR + " device!");
209 return ShellyThingCreator.getThingUID(serviceName, "", "", false);