]> git.basschouten.com Git - openhab-addons.git/blob
c185d34d93ff93822da9bbb070469bd56c22fcf2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.substringBeforeLast;
17 import static org.openhab.core.thing.Thing.PROPERTY_MODEL_ID;
18
19 import java.io.IOException;
20 import java.util.Map;
21 import java.util.Set;
22 import java.util.TreeMap;
23
24 import javax.jmdns.ServiceInfo;
25
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;
53
54 /**
55  * This class identifies Shelly devices by their mDNS service information.
56  *
57  * @author Markus Michels - Initial contribution
58  */
59 @NonNullByDefault
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;
67
68     @Activate
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());
77     }
78
79     @Override
80     public Set<ThingTypeUID> getSupportedThingTypeUIDs() {
81         return SUPPORTED_THING_TYPES_UIDS;
82     }
83
84     @Override
85     public String getServiceType() {
86         return SERVICE_TYPE;
87     }
88
89     /**
90      * Process updates to Binding Config
91      *
92      * @param componentContext
93      */
94     @Modified
95     protected void modified(final ComponentContext componentContext) {
96         logger.debug("Shelly Binding Configuration refreshed");
97         bindingConfig.updateFromProperties(componentContext.getProperties());
98     }
99
100     @Nullable
101     @Override
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")) {
105             return null;
106         }
107
108         String address = "";
109         try {
110             String mode = "";
111             String model = "unknown";
112             String deviceName = "";
113             ThingUID thingUID = null;
114             ShellyDeviceProfile profile;
115             Map<String, Object> properties = new TreeMap<>();
116
117             name = service.getName().toLowerCase();
118             String[] hostAddresses = service.getHostAddresses();
119             if ((hostAddresses != null) && (hostAddresses.length > 0)) {
120                 address = hostAddresses[0];
121             }
122             if (address.isEmpty()) {
123                 logger.trace("{}: Shelly device discovered with empty IP address (service-name={})", name, service);
124                 return null;
125             }
126             String thingType = service.getQualifiedName().contains(SERVICE_TYPE) && name.contains("-")
127                     ? substringBeforeLast(name, "-")
128                     : name;
129             logger.debug("{}: Shelly device discovered: IP-Adress={}, type={}", name, address, thingType);
130
131             // Get device settings
132             Configuration serviceConfig = configurationAdmin.getConfiguration("binding.shelly");
133             if (serviceConfig.getProperties() != null) {
134                 bindingConfig.updateFromProperties(serviceConfig.getProperties());
135             }
136
137             ShellyThingConfiguration config = new ShellyThingConfiguration();
138             config.deviceIp = address;
139             config.userId = bindingConfig.defaultUserId;
140             config.password = bindingConfig.defaultPassword;
141
142             try {
143                 ShellyHttpApi api = new ShellyHttpApi(name, config, httpClient);
144
145                 profile = api.getDeviceProfile(thingType);
146                 logger.debug("{}: Shelly settings : {}", name, profile.settingsJson);
147                 deviceName = profile.name;
148                 model = profile.deviceType;
149                 mode = profile.mode;
150
151                 properties = ShellyBaseHandler.fillDeviceProperties(profile);
152                 logger.trace("{}: thingType={}, deviceType={}, mode={}, symbolic name={}", name, thingType,
153                         profile.deviceType, mode.isEmpty() ? "<standard>" : mode, deviceName);
154
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));
161
162                     // create shellyunknown thing - will be changed during thing initialization with valid credentials
163                     thingUID = ShellyThingCreator.getThingUID(name, model, mode, true);
164                 } else {
165                     logger.debug("{}: {}", name, messages.get("discovery.failed", address, e.toString()));
166                 }
167             } catch (IllegalArgumentException e) { // maybe some format description was buggy
168                 logger.debug("{}: Discovery failed!", name, e);
169             }
170
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);
179
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();
185             }
186         } catch (IOException | NullPointerException e) {
187             // maybe some format description was buggy
188             logger.debug("{}: Exception on processing serviceInfo '{}'", name, service.getNiceTextString(), e);
189         }
190         return null;
191     }
192
193     private void addProperty(Map<String, Object> properties, String key, @Nullable String value) {
194         properties.put(key, value != null ? value : "");
195     }
196
197     @Nullable
198     @Override
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!");
203         }
204         String serviceName = service.getName();
205         if (serviceName == null) {
206             throw new IllegalArgumentException("serviceName must not be null!");
207         }
208         serviceName = serviceName.toLowerCase();
209         if (!serviceName.contains(VENDOR.toLowerCase())) {
210             logger.debug("Not a " + VENDOR + " device!");
211             return null;
212         }
213         return ShellyThingCreator.getThingUID(serviceName, "", "", false);
214     }
215 }