]> git.basschouten.com Git - openhab-addons.git/blob
626b7515c2ba51a458dd1e7ade8feec800fe797a
[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.miio.internal.cloud;
14
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.BINDING_ID;
16
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.concurrent.TimeUnit;
20
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.eclipse.jetty.client.HttpClient;
24 import org.openhab.binding.miio.internal.MiIoSendCommand;
25 import org.openhab.core.cache.ExpiringCache;
26 import org.openhab.core.io.net.http.HttpClientFactory;
27 import org.openhab.core.io.net.http.HttpUtil;
28 import org.openhab.core.library.types.RawType;
29 import org.osgi.service.component.annotations.Activate;
30 import org.osgi.service.component.annotations.Component;
31 import org.osgi.service.component.annotations.Deactivate;
32 import org.osgi.service.component.annotations.Reference;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import com.google.gson.JsonParseException;
37
38 /**
39  * The {@link CloudConnector} is responsible for connecting OH to the Xiaomi cloud communication.
40  *
41  * @author Marcel Verpaalen - Initial contribution
42  */
43 @Component(service = CloudConnector.class)
44 @NonNullByDefault
45 public class CloudConnector {
46
47     private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(60);
48
49     private static enum DeviceListState {
50         FAILED,
51         STARTING,
52         REFRESHING,
53         AVAILABLE,
54     }
55
56     private volatile DeviceListState deviceListState = DeviceListState.STARTING;
57
58     private String username = "";
59     private String password = "";
60     private String country = "ru,us,tw,sg,cn,de,i2";
61     private List<CloudDeviceDTO> deviceList = new ArrayList<>();
62     private boolean connected;
63     private final HttpClient httpClient;
64     private @Nullable MiCloudConnector cloudConnector;
65     private final Logger logger = LoggerFactory.getLogger(CloudConnector.class);
66
67     private ExpiringCache<Boolean> logonCache = new ExpiringCache<Boolean>(CACHE_EXPIRY, () -> {
68         return logon();
69     });
70
71     private ExpiringCache<String> refreshDeviceList = new ExpiringCache<String>(CACHE_EXPIRY, () -> {
72         if (deviceListState == DeviceListState.FAILED && !isConnected()) {
73             return ("Could not connect to Xiaomi cloud");
74         }
75         final @Nullable MiCloudConnector cl = this.cloudConnector;
76         if (cl == null) {
77             return ("Could not connect to Xiaomi cloud");
78         }
79         deviceListState = DeviceListState.REFRESHING;
80         deviceList.clear();
81         for (String server : country.split(",")) {
82             try {
83                 deviceList.addAll(cl.getDevices(server));
84             } catch (JsonParseException e) {
85                 logger.debug("Parsing error getting devices: {}", e.getMessage());
86             }
87         }
88         deviceListState = DeviceListState.AVAILABLE;
89         return "done";// deviceList;
90     });
91
92     @Activate
93     public CloudConnector(@Reference HttpClientFactory httpClientFactory) {
94         this.httpClient = httpClientFactory.createHttpClient(BINDING_ID);
95     }
96
97     @Deactivate
98     public void dispose() {
99         final MiCloudConnector cl = cloudConnector;
100         if (cl != null) {
101             cl.stopClient();
102         }
103         cloudConnector = null;
104     }
105
106     public boolean isConnected() {
107         final MiCloudConnector cl = cloudConnector;
108         if (cl != null && cl.hasLoginToken()) {
109             return true;
110         }
111         final @Nullable Boolean c = logonCache.getValue();
112         if (c != null && c.booleanValue()) {
113             return true;
114         }
115         deviceListState = DeviceListState.FAILED;
116         return false;
117     }
118
119     public String sendRPCCommand(String device, String country, MiIoSendCommand command) throws MiCloudException {
120         final @Nullable MiCloudConnector cl = this.cloudConnector;
121         if (cl == null || !isConnected()) {
122             throw new MiCloudException("Cannot execute request. Cloud service not available");
123         }
124         return cl.sendRPCCommand(device, country.trim().toLowerCase(), command.getCommandString());
125     }
126
127     public String sendCloudCommand(String urlPart, String country, String parameters) throws MiCloudException {
128         final @Nullable MiCloudConnector cl = this.cloudConnector;
129         if (cl == null || !isConnected()) {
130             throw new MiCloudException("Cannot execute request. Cloud service not available");
131         }
132         return cl.request(urlPart, country, parameters);
133     }
134
135     public @Nullable RawType getMap(String mapId, String country) throws MiCloudException {
136         logger.debug("Getting vacuum map {} from Xiaomi cloud server: '{}'", mapId, country);
137         String mapCountry;
138         String mapUrl = "";
139         final @Nullable MiCloudConnector cl = this.cloudConnector;
140         if (cl == null || !isConnected()) {
141             throw new MiCloudException("Cannot execute request. Cloud service not available");
142         }
143         if (country.isEmpty()) {
144             logger.debug("Server not defined in thing. Trying servers: {}", this.country);
145             for (String mapCountryServer : this.country.split(",")) {
146                 mapCountry = mapCountryServer.trim().toLowerCase();
147                 mapUrl = cl.getMapUrl(mapId, mapCountry);
148                 logger.debug("Map download from server {} returned {}", mapCountry, mapUrl);
149                 if (!mapUrl.isEmpty()) {
150                     break;
151                 }
152             }
153         } else {
154             mapCountry = country.trim().toLowerCase();
155             mapUrl = cl.getMapUrl(mapId, mapCountry);
156         }
157         if (mapUrl.isBlank()) {
158             logger.debug("Cannot download map data: Returned map URL is empty");
159             return null;
160         }
161         try {
162             RawType mapData = HttpUtil.downloadData(mapUrl, null, false, -1);
163             if (mapData != null) {
164                 return mapData;
165             } else {
166                 logger.debug("Could not download '{}'", mapUrl);
167                 return null;
168             }
169         } catch (IllegalArgumentException e) {
170             logger.debug("Error downloading map: {}", e.getMessage());
171         }
172         return null;
173     }
174
175     public void setCredentials(@Nullable String username, @Nullable String password, @Nullable String country) {
176         if (country != null) {
177             this.country = country;
178         }
179         if (username != null && password != null) {
180             this.username = username;
181             this.password = password;
182         }
183     }
184
185     private boolean logon() {
186         if (username.isEmpty() || password.isEmpty()) {
187             logger.debug("No Xiaomi cloud credentials. Cloud connectivity disabled");
188             logger.debug("Logon details: username: '{}', pass: '{}', country: '{}'", username,
189                     password.replaceAll(".", "*"), country);
190             return connected;
191         }
192         try {
193             final MiCloudConnector cl = new MiCloudConnector(username, password, httpClient);
194             this.cloudConnector = cl;
195             connected = cl.login();
196             if (connected) {
197                 getDevicesList();
198             } else {
199                 deviceListState = DeviceListState.FAILED;
200             }
201         } catch (MiCloudException e) {
202             connected = false;
203             deviceListState = DeviceListState.FAILED;
204             logger.debug("Xiaomi cloud login failed: {}", e.getMessage());
205         }
206         return connected;
207     }
208
209     public List<CloudDeviceDTO> getDevicesList() {
210         refreshDeviceList.getValue();
211         return deviceList;
212     }
213
214     public @Nullable CloudDeviceDTO getDeviceInfo(String id) {
215         getDevicesList();
216         if (deviceListState != DeviceListState.AVAILABLE) {
217             return null;
218         }
219         List<CloudDeviceDTO> devicedata = new ArrayList<>();
220         for (CloudDeviceDTO deviceDetails : deviceList) {
221             if (deviceDetails.getDid().contentEquals(id)) {
222                 devicedata.add(deviceDetails);
223             }
224         }
225         if (devicedata.isEmpty()) {
226             return null;
227         }
228         for (CloudDeviceDTO device : devicedata) {
229             if (device.getIsOnline()) {
230                 return device;
231             }
232         }
233         if (devicedata.size() > 1) {
234             logger.debug("Found multiple servers for device {} {} returning first", devicedata.get(0).getDid(),
235                     devicedata.get(0).getName());
236         }
237         return devicedata.get(0);
238     }
239 }