2 * Copyright (c) 2010-2021 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.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;
36 import com.google.gson.JsonParseException;
39 * The {@link CloudConnector} is responsible for connecting OH to the Xiaomi cloud communication.
41 * @author Marcel Verpaalen - Initial contribution
43 @Component(service = CloudConnector.class)
45 public class CloudConnector {
47 private static final long CACHE_EXPIRY = TimeUnit.SECONDS.toMillis(60);
49 private static enum DeviceListState {
56 private volatile DeviceListState deviceListState = DeviceListState.STARTING;
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);
67 private ExpiringCache<Boolean> logonCache = new ExpiringCache<Boolean>(CACHE_EXPIRY, () -> {
71 private ExpiringCache<String> refreshDeviceList = new ExpiringCache<String>(CACHE_EXPIRY, () -> {
72 if (deviceListState == DeviceListState.FAILED && !isConnected()) {
73 return ("Could not connect to Xiaomi cloud");
75 final @Nullable MiCloudConnector cl = this.cloudConnector;
77 return ("Could not connect to Xiaomi cloud");
79 deviceListState = DeviceListState.REFRESHING;
81 for (String server : country.split(",")) {
83 deviceList.addAll(cl.getDevices(server));
84 } catch (JsonParseException e) {
85 logger.debug("Parsing error getting devices: {}", e.getMessage());
88 deviceListState = DeviceListState.AVAILABLE;
89 return "done";// deviceList;
93 public CloudConnector(@Reference HttpClientFactory httpClientFactory) {
94 this.httpClient = httpClientFactory.createHttpClient(BINDING_ID);
98 public void dispose() {
99 final MiCloudConnector cl = cloudConnector;
103 cloudConnector = null;
106 public boolean isConnected() {
107 final MiCloudConnector cl = cloudConnector;
108 if (cl != null && cl.hasLoginToken()) {
111 final @Nullable Boolean c = logonCache.getValue();
112 if (c != null && c.booleanValue()) {
115 deviceListState = DeviceListState.FAILED;
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");
124 return cl.sendRPCCommand(device, country.trim().toLowerCase(), command.getCommandString());
127 public @Nullable RawType getMap(String mapId, String country) throws MiCloudException {
128 logger.debug("Getting vacuum map {} from Xiaomi cloud server: '{}'", mapId, country);
131 final @Nullable MiCloudConnector cl = this.cloudConnector;
132 if (cl == null || !isConnected()) {
133 throw new MiCloudException("Cannot execute request. Cloud service not available");
135 if (country.isEmpty()) {
136 logger.debug("Server not defined in thing. Trying servers: {}", this.country);
137 for (String mapCountryServer : this.country.split(",")) {
138 mapCountry = mapCountryServer.trim().toLowerCase();
139 mapUrl = cl.getMapUrl(mapId, mapCountry);
140 logger.debug("Map download from server {} returned {}", mapCountry, mapUrl);
141 if (!mapUrl.isEmpty()) {
146 mapCountry = country.trim().toLowerCase();
147 mapUrl = cl.getMapUrl(mapId, mapCountry);
149 if (mapUrl.isBlank()) {
150 logger.debug("Cannot download map data: Returned map URL is empty");
154 RawType mapData = HttpUtil.downloadData(mapUrl, null, false, -1);
155 if (mapData != null) {
158 logger.debug("Could not download '{}'", mapUrl);
161 } catch (IllegalArgumentException e) {
162 logger.debug("Error downloading map: {}", e.getMessage());
167 public void setCredentials(@Nullable String username, @Nullable String password, @Nullable String country) {
168 if (country != null) {
169 this.country = country;
171 if (username != null && password != null) {
172 this.username = username;
173 this.password = password;
177 private boolean logon() {
178 if (username.isEmpty() || password.isEmpty()) {
179 logger.debug("No Xiaomi cloud credentials. Cloud connectivity disabled");
180 logger.debug("Logon details: username: '{}', pass: '{}', country: '{}'", username,
181 password.replaceAll(".", "*"), country);
185 final MiCloudConnector cl = new MiCloudConnector(username, password, httpClient);
186 this.cloudConnector = cl;
187 connected = cl.login();
191 deviceListState = DeviceListState.FAILED;
193 } catch (MiCloudException e) {
195 deviceListState = DeviceListState.FAILED;
196 logger.debug("Xiaomi cloud login failed: {}", e.getMessage());
201 public List<CloudDeviceDTO> getDevicesList() {
202 refreshDeviceList.getValue();
206 public @Nullable CloudDeviceDTO getDeviceInfo(String id) {
208 if (deviceListState != DeviceListState.AVAILABLE) {
211 String did = Long.toString(Long.parseUnsignedLong(id, 16));
212 List<CloudDeviceDTO> devicedata = new ArrayList<>();
213 for (CloudDeviceDTO deviceDetails : deviceList) {
214 if (deviceDetails.getDid().contentEquals(did)) {
215 devicedata.add(deviceDetails);
218 if (devicedata.isEmpty()) {
221 for (CloudDeviceDTO device : devicedata) {
222 if (device.getIsOnline()) {
226 if (devicedata.size() > 1) {
227 logger.debug("Found multiple servers for device {} {} returning first", devicedata.get(0).getDid(),
228 devicedata.get(0).getName());
230 return devicedata.get(0);