2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.miio.internal.cloud;
15 import static org.openhab.binding.miio.internal.MiIoBindingConstants.BINDING_ID;
17 import java.util.ArrayList;
18 import java.util.List;
19 import java.util.concurrent.TimeUnit;
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;
35 import com.google.gson.JsonParseException;
38 * The {@link CloudConnector} is responsible for connecting OH to the Xiaomi cloud communication.
40 * @author Marcel Verpaalen - Initial contribution
42 @Component(service = CloudConnector.class)
44 public class CloudConnector {
46 private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(60);
48 private static enum DeviceListState {
55 private volatile DeviceListState deviceListState = DeviceListState.STARTING;
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);
66 private ExpiringCache<Boolean> logonCache = new ExpiringCache<Boolean>(CACHE_EXPIRY, () -> {
70 private ExpiringCache<String> refreshDeviceList = new ExpiringCache<String>(CACHE_EXPIRY, () -> {
71 if (deviceListState == DeviceListState.FAILED && !isConnected()) {
72 return ("Could not connect to Xiaomi cloud");
74 final @Nullable MiCloudConnector cl = this.cloudConnector;
76 return ("Could not connect to Xiaomi cloud");
78 deviceListState = DeviceListState.REFRESHING;
80 for (String server : country.split(",")) {
82 deviceList.addAll(cl.getDevices(server));
83 } catch (JsonParseException e) {
84 logger.debug("Parsing error getting devices: {}", e.getMessage());
87 deviceListState = DeviceListState.AVAILABLE;
88 return "done";// deviceList;
92 public CloudConnector(@Reference HttpClientFactory httpClientFactory) {
93 this.httpClient = httpClientFactory.createHttpClient(BINDING_ID);
97 public void dispose() {
98 final MiCloudConnector cl = cloudConnector;
102 cloudConnector = null;
105 public boolean isConnected() {
106 final MiCloudConnector cl = cloudConnector;
107 if (cl != null && cl.hasLoginToken()) {
110 final @Nullable Boolean c = logonCache.getValue();
111 if (c != null && c.booleanValue()) {
114 deviceListState = DeviceListState.FAILED;
118 public @Nullable RawType getMap(String mapId, String country) throws MiCloudException {
119 logger.debug("Getting vacuum map {} from Xiaomi cloud server: '{}'", mapId, country);
122 final @Nullable MiCloudConnector cl = this.cloudConnector;
123 if (cl == null || !isConnected()) {
124 throw new MiCloudException("Cannot execute request. Cloudservice not available");
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()) {
137 mapCountry = country.trim().toLowerCase();
138 mapUrl = cl.getMapUrl(mapId, mapCountry);
140 if (mapUrl.isBlank()) {
141 logger.debug("Cannot download map data: Returned map URL is empty");
145 RawType mapData = HttpUtil.downloadData(mapUrl, null, false, -1);
146 if (mapData != null) {
149 logger.debug("Could not download '{}'", mapUrl);
152 } catch (IllegalArgumentException e) {
153 logger.debug("Error downloading map: {}", e.getMessage());
158 public void setCredentials(@Nullable String username, @Nullable String password, @Nullable String country) {
159 if (country != null) {
160 this.country = country;
162 if (username != null && password != null) {
163 this.username = username;
164 this.password = password;
168 private boolean logon() {
169 if (username.isEmpty() || password.isEmpty()) {
170 logger.debug("No Xiaomi cloud credentials. Cloud connectivity disabled");
171 logger.debug("Logon details: username: '{}', pass: '{}', country: '{}'", username,
172 password.replaceAll(".", "*"), country);
176 final MiCloudConnector cl = new MiCloudConnector(username, password, httpClient);
177 this.cloudConnector = cl;
178 connected = cl.login();
182 deviceListState = DeviceListState.FAILED;
184 } catch (MiCloudException e) {
186 deviceListState = DeviceListState.FAILED;
187 logger.debug("Xiaomi cloud login failed: {}", e.getMessage());
192 public List<CloudDeviceDTO> getDevicesList() {
193 refreshDeviceList.getValue();
197 public @Nullable CloudDeviceDTO getDeviceInfo(String id) {
199 if (deviceListState != DeviceListState.AVAILABLE) {
202 String did = Long.toString(Long.parseUnsignedLong(id, 16));
203 List<CloudDeviceDTO> devicedata = new ArrayList<>();
204 for (CloudDeviceDTO deviceDetails : deviceList) {
205 if (deviceDetails.getDid().contentEquals(did)) {
206 devicedata.add(deviceDetails);
209 if (devicedata.isEmpty()) {
212 for (CloudDeviceDTO device : devicedata) {
213 if (device.getIsOnline()) {
217 if (devicedata.size() > 1) {
218 logger.debug("Found multiple servers for device {} {} returning first", devicedata.get(0).getDid(),
219 devicedata.get(0).getName());
221 return devicedata.get(0);