2 * Copyright (c) 2010-2024 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;
20 import java.net.Inet4Address;
23 import java.util.TreeMap;
25 import javax.jmdns.ServiceInfo;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.eclipse.jetty.client.HttpClient;
30 import org.openhab.binding.shelly.internal.api.ShellyApiException;
31 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
32 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
33 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
34 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
35 import org.openhab.binding.shelly.internal.api1.Shelly1HttpApi;
36 import org.openhab.binding.shelly.internal.api2.Shelly2ApiRpc;
37 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
38 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
39 import org.openhab.binding.shelly.internal.handler.ShellyBaseHandler;
40 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
41 import org.openhab.core.config.discovery.DiscoveryResult;
42 import org.openhab.core.config.discovery.DiscoveryResultBuilder;
43 import org.openhab.core.config.discovery.mdns.MDNSDiscoveryParticipant;
44 import org.openhab.core.i18n.LocaleProvider;
45 import org.openhab.core.io.net.http.HttpClientFactory;
46 import org.openhab.core.thing.ThingTypeUID;
47 import org.openhab.core.thing.ThingUID;
48 import org.osgi.service.cm.Configuration;
49 import org.osgi.service.cm.ConfigurationAdmin;
50 import org.osgi.service.component.ComponentContext;
51 import org.osgi.service.component.annotations.Activate;
52 import org.osgi.service.component.annotations.Component;
53 import org.osgi.service.component.annotations.Modified;
54 import org.osgi.service.component.annotations.Reference;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * This class identifies Shelly devices by their mDNS service information.
61 * @author Markus Michels - Initial contribution
64 @Component(service = MDNSDiscoveryParticipant.class)
65 public class ShellyDiscoveryParticipant implements MDNSDiscoveryParticipant {
66 private final Logger logger = LoggerFactory.getLogger(ShellyDiscoveryParticipant.class);
67 private final ShellyBindingConfiguration bindingConfig = new ShellyBindingConfiguration();
68 private final ShellyTranslationProvider messages;
69 private final HttpClient httpClient;
70 private final ConfigurationAdmin configurationAdmin;
73 public ShellyDiscoveryParticipant(@Reference ConfigurationAdmin configurationAdmin,
74 @Reference HttpClientFactory httpClientFactory, @Reference LocaleProvider localeProvider,
75 @Reference ShellyTranslationProvider translationProvider, ComponentContext componentContext) {
76 logger.debug("Activating ShellyDiscovery service");
77 this.configurationAdmin = configurationAdmin;
78 this.messages = translationProvider;
79 this.httpClient = httpClientFactory.getCommonHttpClient();
80 bindingConfig.updateFromProperties(componentContext.getProperties());
84 public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
85 return SUPPORTED_THING_TYPES_UIDS;
89 public String getServiceType() {
94 * Process updates to Binding Config
96 * @param componentContext
99 protected void modified(final ComponentContext componentContext) {
100 logger.debug("Shelly Binding Configuration refreshed");
101 bindingConfig.updateFromProperties(componentContext.getProperties());
106 public DiscoveryResult createResult(final ServiceInfo service) {
107 String name = service.getName().toLowerCase(); // Shelly Duo: Name starts with" Shelly" rather than "shelly"
108 if (!name.startsWith("shelly")) {
115 String model = "unknown";
116 String deviceName = "";
117 ThingUID thingUID = null;
118 ShellyDeviceProfile profile;
119 Map<String, Object> properties = new TreeMap<>();
121 name = service.getName().toLowerCase();
122 Inet4Address[] hostAddresses = service.getInet4Addresses();
123 if ((hostAddresses != null) && (hostAddresses.length > 0)) {
124 address = substringAfter(hostAddresses[0].toString(), "/");
126 if (address.isEmpty()) {
127 logger.trace("{}: Shelly device discovered with empty IP address (service-name={})", name, service);
130 String thingType = service.getQualifiedName().contains(SERVICE_TYPE) && name.contains("-")
131 ? substringBeforeLast(name, "-")
133 logger.debug("{}: Shelly device discovered: IP-Adress={}, type={}", name, address, thingType);
135 // Get device settings
136 Configuration serviceConfig = configurationAdmin.getConfiguration("binding.shelly");
137 if (serviceConfig.getProperties() != null) {
138 bindingConfig.updateFromProperties(serviceConfig.getProperties());
141 ShellyThingConfiguration config = new ShellyThingConfiguration();
142 config.deviceIp = address;
143 config.userId = bindingConfig.defaultUserId;
144 config.password = bindingConfig.defaultPassword;
146 String gen = getString(service.getPropertyString("gen"));
147 boolean gen2 = "2".equals(gen) || "3".equals(gen);
148 ShellyApiInterface api = null;
149 boolean auth = false;
150 ShellySettingsDevice devInfo;
152 api = gen2 ? new Shelly2ApiRpc(name, config, httpClient) : new Shelly1HttpApi(name, config, httpClient);
154 devInfo = api.getDeviceInfo();
155 model = devInfo.type;
156 gen2 = !(devInfo.gen == 1); // gen 2+3
157 auth = getBool(devInfo.auth);
158 if (devInfo.name != null) {
159 deviceName = devInfo.name;
162 profile = api.getDeviceProfile(thingType, devInfo);
164 logger.debug("{}: Shelly settings : {}", name, profile.settingsJson);
165 deviceName = profile.name;
167 properties = ShellyBaseHandler.fillDeviceProperties(profile);
168 logger.trace("{}: thingType={}, deviceType={}, mode={}, symbolic name={}", name, thingType,
169 devInfo.type, mode.isEmpty() ? "<standard>" : mode, deviceName);
171 // get thing type from device name
172 thingUID = ShellyThingCreator.getThingUID(name, model, mode, false);
173 } catch (ShellyApiException e) {
174 ShellyApiResult result = e.getApiResult();
175 if (result.isHttpAccessUnauthorized()) {
176 logger.info("{}: {}", name, messages.get("discovery.protected", address));
178 // create shellyunknown thing - will be changed during thing initialization with valid credentials
179 thingUID = ShellyThingCreator.getThingUID(name, model, mode, true);
181 logger.debug("{}: {}", name, messages.get("discovery.failed", address, e.toString()));
183 } catch (IllegalArgumentException e) { // maybe some format description was buggy
184 logger.debug("{}: Discovery failed!", name, e);
191 if (thingUID != null) {
192 addProperty(properties, CONFIG_DEVICEIP, address);
193 addProperty(properties, PROPERTY_MODEL_ID, model);
194 addProperty(properties, PROPERTY_SERVICE_NAME, name);
195 addProperty(properties, PROPERTY_DEV_NAME, deviceName);
196 addProperty(properties, PROPERTY_DEV_TYPE, thingType);
197 addProperty(properties, PROPERTY_DEV_GEN, gen2 ? "2" : "1");
198 addProperty(properties, PROPERTY_DEV_MODE, mode);
199 addProperty(properties, PROPERTY_DEV_AUTH, auth ? "yes" : "no");
201 logger.debug("{}: Adding Shelly {}, UID={}", name, deviceName, thingUID.getAsString());
202 String thingLabel = deviceName.isEmpty() ? name + " - " + address
203 : deviceName + " (" + name + "@" + address + ")";
204 return DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel(thingLabel)
205 .withRepresentationProperty(PROPERTY_SERVICE_NAME).build();
207 } catch (IOException | NullPointerException e) {
208 // maybe some format description was buggy
209 logger.debug("{}: Exception on processing serviceInfo '{}'", name, service.getNiceTextString(), e);
214 private void addProperty(Map<String, Object> properties, String key, @Nullable String value) {
215 properties.put(key, value != null ? value : "");
220 public ThingUID getThingUID(@Nullable ServiceInfo service) throws IllegalArgumentException {
221 logger.debug("ServiceInfo {}", service);
222 if (service == null) {
223 throw new IllegalArgumentException("service must not be null!");
225 String serviceName = service.getName();
226 if (serviceName == null) {
227 throw new IllegalArgumentException("serviceName must not be null!");
229 serviceName = serviceName.toLowerCase();
230 if (!serviceName.contains(VENDOR.toLowerCase())) {
231 logger.debug("Not a " + VENDOR + " device!");
234 return ShellyThingCreator.getThingUID(serviceName, "", "", false);