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";
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);
141 RawType mapData = HttpUtil.downloadData(mapUrl, null, false, -1);
142 if (mapData != null) {
145 logger.debug("Could not download '{}'", mapUrl);
150 public void setCredentials(@Nullable String username, @Nullable String password, @Nullable String country) {
151 if (country != null) {
152 this.country = country;
154 if (username != null && password != null) {
155 this.username = username;
156 this.password = password;
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);
168 final MiCloudConnector cl = new MiCloudConnector(username, password, httpClient);
169 this.cloudConnector = cl;
170 connected = cl.login();
174 deviceListState = DeviceListState.FAILED;
176 } catch (MiCloudException e) {
178 deviceListState = DeviceListState.FAILED;
179 logger.debug("Xiaomi cloud login failed: {}", e.getMessage());
184 public List<CloudDeviceDTO> getDevicesList() {
185 refreshDeviceList.getValue();
189 public @Nullable CloudDeviceDTO getDeviceInfo(String id) {
191 if (deviceListState != DeviceListState.AVAILABLE) {
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);
201 if (devicedata.isEmpty()) {
204 for (CloudDeviceDTO device : devicedata) {
205 if (device.getIsOnline()) {
209 if (devicedata.size() > 1) {
210 logger.debug("Found multiple servers for device {} {} returning first", devicedata.get(0).getDid(),
211 devicedata.get(0).getName());
213 return devicedata.get(0);