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