]> git.basschouten.com Git - openhab-addons.git/blob
793b710f7db9e46274832217e2d2fe261ed42716
[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.shelly.internal.discovery;
14
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;
18
19 import java.io.IOException;
20 import java.net.Inet4Address;
21 import java.util.Map;
22 import java.util.Set;
23 import java.util.TreeMap;
24
25 import javax.jmdns.ServiceInfo;
26
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;
57
58 /**
59  * This class identifies Shelly devices by their mDNS service information.
60  *
61  * @author Markus Michels - Initial contribution
62  */
63 @NonNullByDefault
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;
71
72     @Activate
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());
81     }
82
83     @Override
84     public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
85         return SUPPORTED_THING_TYPES_UIDS;
86     }
87
88     @Override
89     public String getServiceType() {
90         return SERVICE_TYPE;
91     }
92
93     /**
94      * Process updates to Binding Config
95      *
96      * @param componentContext
97      */
98     @Modified
99     protected void modified(final ComponentContext componentContext) {
100         logger.debug("Shelly Binding Configuration refreshed");
101         bindingConfig.updateFromProperties(componentContext.getProperties());
102     }
103
104     @Nullable
105     @Override
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")) {
109             return null;
110         }
111
112         String address = "";
113         try {
114             String mode = "";
115             String model = "unknown";
116             String deviceName = "";
117             ThingUID thingUID = null;
118             ShellyDeviceProfile profile;
119             Map<String, Object> properties = new TreeMap<>();
120
121             name = service.getName().toLowerCase();
122             Inet4Address[] hostAddresses = service.getInet4Addresses();
123             if ((hostAddresses != null) && (hostAddresses.length > 0)) {
124                 address = substringAfter(hostAddresses[0].toString(), "/");
125             }
126             if (address.isEmpty()) {
127                 logger.trace("{}: Shelly device discovered with empty IP address (service-name={})", name, service);
128                 return null;
129             }
130             String thingType = service.getQualifiedName().contains(SERVICE_TYPE) && name.contains("-")
131                     ? substringBeforeLast(name, "-")
132                     : name;
133             logger.debug("{}: Shelly device discovered: IP-Adress={}, type={}", name, address, thingType);
134
135             // Get device settings
136             Configuration serviceConfig = configurationAdmin.getConfiguration("binding.shelly");
137             if (serviceConfig.getProperties() != null) {
138                 bindingConfig.updateFromProperties(serviceConfig.getProperties());
139             }
140
141             ShellyThingConfiguration config = new ShellyThingConfiguration();
142             config.deviceIp = address;
143             config.userId = bindingConfig.defaultUserId;
144             config.password = bindingConfig.defaultPassword;
145
146             boolean gen2 = "2".equals(service.getPropertyString("gen"));
147             ShellyApiInterface api = null;
148             ShellySettingsDevice devInfo;
149             try {
150                 api = gen2 ? new Shelly2ApiRpc(name, config, httpClient) : new Shelly1HttpApi(name, config, httpClient);
151                 api.initialize();
152                 devInfo = api.getDeviceInfo();
153                 model = devInfo.type;
154                 if (devInfo.name != null) {
155                     deviceName = devInfo.name;
156                 }
157                 profile = api.getDeviceProfile(thingType, devInfo);
158                 api.close();
159                 logger.debug("{}: Shelly settings : {}", name, profile.settingsJson);
160                 deviceName = profile.name;
161                 mode = devInfo.mode;
162                 properties = ShellyBaseHandler.fillDeviceProperties(profile);
163                 logger.trace("{}: thingType={}, deviceType={}, mode={}, symbolic name={}", name, thingType,
164                         devInfo.type, mode.isEmpty() ? "<standard>" : mode, deviceName);
165
166                 // get thing type from device name
167                 thingUID = ShellyThingCreator.getThingUID(name, model, mode, false);
168             } catch (ShellyApiException e) {
169                 ShellyApiResult result = e.getApiResult();
170                 if (result.isHttpAccessUnauthorized()) {
171                     logger.info("{}: {}", name, messages.get("discovery.protected", address));
172
173                     // create shellyunknown thing - will be changed during thing initialization with valid credentials
174                     thingUID = ShellyThingCreator.getThingUID(name, model, mode, true);
175                 } else {
176                     logger.debug("{}: {}", name, messages.get("discovery.failed", address, e.toString()));
177                 }
178             } catch (IllegalArgumentException e) { // maybe some format description was buggy
179                 logger.debug("{}: Discovery failed!", name, e);
180             } finally {
181                 if (api != null) {
182                     api.close();
183                 }
184             }
185
186             if (thingUID != null) {
187                 addProperty(properties, CONFIG_DEVICEIP, address);
188                 addProperty(properties, PROPERTY_MODEL_ID, model);
189                 addProperty(properties, PROPERTY_SERVICE_NAME, name);
190                 addProperty(properties, PROPERTY_DEV_NAME, deviceName);
191                 addProperty(properties, PROPERTY_DEV_TYPE, thingType);
192                 addProperty(properties, PROPERTY_DEV_GEN, gen2 ? "2" : "1");
193                 addProperty(properties, PROPERTY_DEV_MODE, mode);
194
195                 logger.debug("{}: Adding Shelly {}, UID={}", name, deviceName, thingUID.getAsString());
196                 String thingLabel = deviceName.isEmpty() ? name + " - " + address
197                         : deviceName + " (" + name + "@" + address + ")";
198                 return DiscoveryResultBuilder.create(thingUID).withProperties(properties).withLabel(thingLabel)
199                         .withRepresentationProperty(PROPERTY_SERVICE_NAME).build();
200             }
201         } catch (IOException | NullPointerException e) {
202             // maybe some format description was buggy
203             logger.debug("{}: Exception on processing serviceInfo '{}'", name, service.getNiceTextString(), e);
204         }
205         return null;
206     }
207
208     private void addProperty(Map<String, Object> properties, String key, @Nullable String value) {
209         properties.put(key, value != null ? value : "");
210     }
211
212     @Nullable
213     @Override
214     public ThingUID getThingUID(@Nullable ServiceInfo service) throws IllegalArgumentException {
215         logger.debug("ServiceInfo {}", service);
216         if (service == null) {
217             throw new IllegalArgumentException("service must not be null!");
218         }
219         String serviceName = service.getName();
220         if (serviceName == null) {
221             throw new IllegalArgumentException("serviceName must not be null!");
222         }
223         serviceName = serviceName.toLowerCase();
224         if (!serviceName.contains(VENDOR.toLowerCase())) {
225             logger.debug("Not a " + VENDOR + " device!");
226             return null;
227         }
228         return ShellyThingCreator.getThingUID(serviceName, "", "", false);
229     }
230 }