2 * Copyright (c) 2010-2022 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.substringBeforeLast;
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(); // Shelly Duo: 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;
115 Map<String, Object> properties = new TreeMap<>();
117 name = service.getName().toLowerCase();
118 String[] hostAddresses = service.getHostAddresses();
119 if ((hostAddresses != null) && (hostAddresses.length > 0)) {
120 address = hostAddresses[0];
122 if (address.isEmpty()) {
123 logger.trace("{}: Shelly device discovered with empty IP address (service-name={})", name, service);
126 String thingType = service.getQualifiedName().contains(SERVICE_TYPE) && name.contains("-")
127 ? substringBeforeLast(name, "-")
129 logger.debug("{}: Shelly device discovered: IP-Adress={}, type={}", name, address, thingType);
131 // Get device settings
132 Configuration serviceConfig = configurationAdmin.getConfiguration("binding.shelly");
133 if (serviceConfig.getProperties() != null) {
134 bindingConfig.updateFromProperties(serviceConfig.getProperties());
137 ShellyThingConfiguration config = new ShellyThingConfiguration();
138 config.deviceIp = address;
139 config.userId = bindingConfig.defaultUserId;
140 config.password = bindingConfig.defaultPassword;
143 ShellyHttpApi api = new ShellyHttpApi(name, config, httpClient);
145 profile = api.getDeviceProfile(thingType);
146 logger.debug("{}: Shelly settings : {}", name, profile.settingsJson);
147 deviceName = profile.name;
148 model = profile.deviceType;
151 properties = ShellyBaseHandler.fillDeviceProperties(profile);
152 logger.trace("{}: thingType={}, deviceType={}, mode={}, symbolic name={}", name, thingType,
153 profile.deviceType, mode.isEmpty() ? "<standard>" : mode, deviceName);
155 // get thing type from device name
156 thingUID = ShellyThingCreator.getThingUID(name, model, mode, false);
157 } catch (ShellyApiException e) {
158 ShellyApiResult result = e.getApiResult();
159 if (result.isHttpAccessUnauthorized()) {
160 logger.info("{}: {}", name, messages.get("discovery.protected", address));
162 // create shellyunknown thing - will be changed during thing initialization with valid credentials
163 thingUID = ShellyThingCreator.getThingUID(name, model, mode, true);
165 logger.debug("{}: {}", name, messages.get("discovery.failed", address, e.toString()));
167 } catch (IllegalArgumentException e) { // maybe some format description was buggy
168 logger.debug("{}: Discovery failed!", name, e);
171 if (thingUID != null) {
172 addProperty(properties, CONFIG_DEVICEIP, address);
173 addProperty(properties, PROPERTY_MODEL_ID, model);
174 addProperty(properties, PROPERTY_SERVICE_NAME, name);
175 addProperty(properties, PROPERTY_DEV_NAME, deviceName);
176 addProperty(properties, PROPERTY_DEV_TYPE, thingType);
177 addProperty(properties, PROPERTY_DEV_GEN, "1");
178 addProperty(properties, PROPERTY_DEV_MODE, mode);
180 logger.debug("{}: Adding Shelly {}, UID={}", name, deviceName, thingUID.getAsString());
181 String thingLabel = deviceName.isEmpty() ? name + " - " + address
182 : deviceName + " (" + name + "@" + address + ")";
183 return DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel(thingLabel)
184 .withRepresentationProperty(PROPERTY_DEV_NAME).build();
186 } catch (IOException | NullPointerException e) {
187 // maybe some format description was buggy
188 logger.debug("{}: Exception on processing serviceInfo '{}'", name, service.getNiceTextString(), e);
193 private void addProperty(Map<String, Object> properties, String key, @Nullable String value) {
194 properties.put(key, value != null ? value : "");
199 public ThingUID getThingUID(@Nullable ServiceInfo service) throws IllegalArgumentException {
200 logger.debug("ServiceInfo {}", service);
201 if (service == null) {
202 throw new IllegalArgumentException("service must not be null!");
204 String serviceName = service.getName();
205 if (serviceName == null) {
206 throw new IllegalArgumentException("serviceName must not be null!");
208 serviceName = serviceName.toLowerCase();
209 if (!serviceName.contains(VENDOR.toLowerCase())) {
210 logger.debug("Not a " + VENDOR + " device!");
213 return ShellyThingCreator.getThingUID(serviceName, "", "", false);