]> git.basschouten.com Git - openhab-addons.git/blob
81bc24158285abaa37ff01c5e9aa5800acb125eb
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.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(); // Duao: 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 = null;
115             Map<String, Object> properties = new TreeMap<>();
116
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);
121                 return null;
122             }
123             String thingType = service.getQualifiedName().contains(SERVICE_TYPE) && name.contains("-")
124                     ? substringBeforeLast(name, "-")
125                     : name;
126             logger.debug("{}: Shelly device discovered: IP-Adress={}, type={}", name, address, thingType);
127
128             // Get device settings
129             Configuration serviceConfig = configurationAdmin.getConfiguration("binding.shelly");
130             if (serviceConfig.getProperties() != null) {
131                 bindingConfig.updateFromProperties(serviceConfig.getProperties());
132             }
133
134             ShellyThingConfiguration config = new ShellyThingConfiguration();
135             config.deviceIp = address;
136             config.userId = bindingConfig.defaultUserId;
137             config.password = bindingConfig.defaultPassword;
138
139             try {
140                 ShellyHttpApi api = new ShellyHttpApi(name, config, httpClient);
141
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);
146                 mode = profile.mode;
147
148                 properties = ShellyBaseHandler.fillDeviceProperties(profile);
149                 logger.trace("{}: thingType={}, deviceType={}, mode={}, symbolic name={}", name, thingType,
150                         profile.deviceType, mode.isEmpty() ? "<standard>" : mode, deviceName);
151
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));
158
159                     // create shellyunknown thing - will be changed during thing initialization with valid credentials
160                     thingUID = ShellyThingCreator.getThingUID(name, model, mode, true);
161                 } else {
162                     logger.info("{}: {}", name, messages.get("discovery.failed", address, e.toString()));
163                 }
164             } catch (IllegalArgumentException e) { // maybe some format description was buggy
165                 logger.debug("{}: Discovery failed!", name, e);
166             }
167
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);
175
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();
181             }
182         } catch (IOException | NullPointerException e) {
183             // maybe some format description was buggy
184             logger.debug("{}: Exception on processing serviceInfo '{}'", name, service.getNiceTextString(), e);
185         }
186         return null;
187     }
188
189     private void addProperty(Map<String, Object> properties, String key, @Nullable String value) {
190         properties.put(key, value != null ? value : "");
191     }
192
193     @Nullable
194     @Override
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!");
199         }
200         String serviceName = service.getName();
201         if (serviceName == null) {
202             throw new IllegalArgumentException("serviceName must not be null!");
203         }
204         serviceName = serviceName.toLowerCase();
205         if (!serviceName.contains(VENDOR.toLowerCase())) {
206             logger.debug("Not a " + VENDOR + " device!");
207             return null;
208         }
209         return ShellyThingCreator.getThingUID(serviceName, "", "", false);
210     }
211 }