]> git.basschouten.com Git - openhab-addons.git/blob
eb4966f16203e990ae200c7ccdf684912c97d0fe
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.tapocontrol.internal.api;
14
15 import static org.openhab.binding.tapocontrol.internal.constants.TapoBindingSettings.*;
16 import static org.openhab.binding.tapocontrol.internal.constants.TapoErrorConstants.*;
17 import static org.openhab.binding.tapocontrol.internal.helpers.TapoUtils.*;
18
19 import java.util.concurrent.TimeUnit;
20 import java.util.concurrent.TimeoutException;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.eclipse.jetty.client.HttpResponse;
25 import org.eclipse.jetty.client.api.ContentResponse;
26 import org.eclipse.jetty.client.api.Request;
27 import org.eclipse.jetty.client.api.Result;
28 import org.eclipse.jetty.client.util.BufferingResponseListener;
29 import org.eclipse.jetty.client.util.StringContentProvider;
30 import org.eclipse.jetty.http.HttpMethod;
31 import org.openhab.binding.tapocontrol.internal.device.TapoBridgeHandler;
32 import org.openhab.binding.tapocontrol.internal.device.TapoDevice;
33 import org.openhab.binding.tapocontrol.internal.helpers.PayloadBuilder;
34 import org.openhab.binding.tapocontrol.internal.helpers.TapoCipher;
35 import org.openhab.binding.tapocontrol.internal.helpers.TapoErrorHandler;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.gson.Gson;
40 import com.google.gson.JsonObject;
41
42 /**
43  * Handler class for TAPO Smart Home device connections.
44  * This class uses synchronous HttpClient-Requests for login to device
45  *
46  * @author Christian Wild - Initial contribution
47  */
48 @NonNullByDefault
49 public class TapoDeviceHttpApi {
50     private final Logger logger = LoggerFactory.getLogger(TapoDeviceHttpApi.class);
51     private final String uid;
52     private final TapoCipher tapoCipher;
53     private final TapoBridgeHandler bridge;
54     private Gson gson;
55     private String token = "";
56     private String cookie = "";
57     protected String deviceURL = "";
58     protected String ipAddress = "";
59
60     /**
61      * INIT CLASS
62      *
63      * @param config TapoControlConfiguration class
64      */
65     public TapoDeviceHttpApi(TapoDevice device, TapoBridgeHandler bridgeThingHandler) {
66         this.bridge = bridgeThingHandler;
67         this.tapoCipher = new TapoCipher();
68         this.gson = new Gson();
69         this.uid = device.getThingUID().getAsString();
70         String ipAddress = device.getIpAddress();
71         setDeviceURL(ipAddress);
72     }
73
74     /***********************************
75      *
76      * DELEGATING FUNCTIONS
77      * will normaly be delegated to extension-classes(TapoDeviceConnector)
78      *
79      ************************************/
80     /**
81      * handle SuccessResponse (setDeviceInfo)
82      * 
83      * @param responseBody String with responseBody from device
84      */
85     protected void handleSuccessResponse(String responseBody) {
86     }
87
88     /**
89      * handle JsonResponse (getDeviceInfo)
90      * 
91      * @param responseBody String with responseBody from device
92      */
93     protected void handleDeviceResult(String responseBody) {
94     }
95
96     /**
97      * handle JsonResponse (getEnergyData)
98      * 
99      * @param responseBody String with responseBody from device
100      */
101     protected void handleEnergyResult(String responseBody) {
102     }
103
104     /**
105      * handle custom response
106      * 
107      * @param responseBody String with responseBody from device
108      */
109     protected void handleCustomResponse(String responseBody) {
110     }
111
112     /**
113      * handle error
114      * 
115      * @param te TapoErrorHandler
116      */
117     protected void handleError(TapoErrorHandler tapoError) {
118     }
119
120     /***********************************
121      *
122      * LOGIN FUNCTIONS
123      *
124      ************************************/
125
126     /**
127      * Create Handshake and set cookie
128      *
129      * @return true if handshake (cookie) was created
130      */
131     protected String createHandshake() {
132         String cookie = "";
133         try {
134             /* create payload for handshake */
135             PayloadBuilder plBuilder = new PayloadBuilder();
136             plBuilder.method = "handshake";
137             plBuilder.addParameter("key", bridge.getCredentials().getPublicKey()); // ?.decode("UTF-8")
138             String payload = plBuilder.getPayload();
139
140             /* send request (create ) */
141             logger.trace("({}) create handhsake with payload: {}", uid, payload.toString());
142             ContentResponse response = sendRequest(this.deviceURL, payload);
143             if (response != null && getErrorCode(response) == 0) {
144                 String encryptedKey = getKeyFromResponse(response);
145                 this.tapoCipher.setKey(encryptedKey, bridge.getCredentials());
146                 cookie = getCookieFromResponse(response);
147             }
148         } catch (Exception e) {
149             logger.debug("({}) could not createHandshake: {}", uid, e.toString());
150             handleError(new TapoErrorHandler(ERR_HAND_SHAKE_FAILED, "could not createHandshake"));
151         }
152         return cookie;
153     }
154
155     /**
156      * return encrypted key from 'handshake' request
157      * 
158      * @param response ContentResponse from "handshake" method
159      * @return
160      */
161     private String getKeyFromResponse(ContentResponse response) {
162         String rBody = response.getContentAsString();
163         JsonObject jsonObj = gson.fromJson(rBody, JsonObject.class);
164         if (jsonObj != null) {
165             logger.trace("({}) received awnser: {}", uid, rBody);
166             return jsonObjectToString(jsonObj.getAsJsonObject("result"), "key");
167         } else {
168             logger.warn("({}) could not getKeyFromResponse '{}'", uid, rBody);
169             handleError(new TapoErrorHandler(ERR_HAND_SHAKE_FAILED, "could not getKeyFromResponse"));
170         }
171         return "";
172     }
173
174     /**
175      * return cookie from 'handshake' request
176      * 
177      * @param response ContentResponse from "handshake" metho
178      * @return
179      */
180     private String getCookieFromResponse(ContentResponse response) {
181         String cookie = "";
182         try {
183             cookie = response.getHeaders().get("Set-Cookie").split(";")[0];
184             logger.trace("({}) got cookie: '{}'", uid, cookie);
185         } catch (Exception e) {
186             logger.warn("({}) could not getCookieFromResponse", uid);
187             handleError(new TapoErrorHandler(ERR_HAND_SHAKE_FAILED, "could not getCookieFromResponse"));
188         }
189         return cookie;
190     }
191
192     /**
193      * Query Token from device
194      * 
195      * @return String with token returned from device
196      */
197     protected String queryToken() {
198         String token = "";
199         try {
200             /* encrypt login credentials */
201             PayloadBuilder plBuilder = new PayloadBuilder();
202             plBuilder.method = "login_device";
203             plBuilder.addParameter("username", bridge.getCredentials().getEncodedEmail());
204             plBuilder.addParameter("password", bridge.getCredentials().getEncodedPassword());
205             String payload = plBuilder.getPayload();
206             String encryptedPayload = this.encryptPayload(payload);
207
208             /* create secured login informations */
209             plBuilder = new PayloadBuilder();
210             plBuilder.method = "securePassthrough";
211             plBuilder.addParameter("request", encryptedPayload);
212             String securePassthroughPayload = plBuilder.getPayload();
213
214             /* sendRequest and get Token */
215             ContentResponse response = sendRequest(deviceURL, securePassthroughPayload);
216             token = getTokenFromResponse(response);
217         } catch (Exception e) {
218             logger.debug("({}) error building login payload: {}", uid, e.toString());
219             handleError(new TapoErrorHandler(e, "error building login payload"));
220         }
221         return token;
222     }
223
224     /**
225      * get Token from "login"-request
226      * 
227      * @param response
228      * @return
229      */
230     private String getTokenFromResponse(@Nullable ContentResponse response) {
231         String result = "";
232         TapoErrorHandler tapoError = new TapoErrorHandler();
233         if (response != null && response.getStatus() == 200) {
234             String rBody = response.getContentAsString();
235             String decryptedResponse = this.decryptResponse(rBody);
236             logger.trace("({}) received result: {}", uid, decryptedResponse);
237
238             /* get errocode (0=success) */
239             JsonObject jsonObject = gson.fromJson(decryptedResponse, JsonObject.class);
240             if (jsonObject != null) {
241                 Integer errorCode = jsonObjectToInt(jsonObject, "error_code", ERR_JSON_DECODE_FAIL);
242                 if (errorCode == 0) {
243                     /* return result if set / else request was successfull */
244                     result = jsonObjectToString(jsonObject.getAsJsonObject("result"), "token");
245                 } else {
246                     /* return errorcode from device */
247                     tapoError.raiseError(errorCode, "could not get token");
248                     logger.debug("({}) login recieved errorCode {} - {}", uid, errorCode, tapoError.getMessage());
249                 }
250             } else {
251                 logger.debug("({}) unexpected json-response '{}'", uid, decryptedResponse);
252                 tapoError.raiseError(ERR_JSON_ENCODE_FAIL, "could not get token");
253             }
254         } else {
255             logger.debug("({}) invalid response while login", uid);
256             tapoError.raiseError(ERR_HTTP_RESPONSE, "invalid response while login");
257         }
258         /* handle error */
259         if (tapoError.hasError()) {
260             handleError(tapoError);
261         }
262         return result;
263     }
264
265     /***********************************
266      *
267      * HTTP-ACTIONS
268      *
269      ************************************/
270     /**
271      * SEND SYNCHRON HTTP-REQUEST
272      * 
273      * @param url url request is sent to
274      * @param payload payload (String) to send
275      * @return ContentResponse of request
276      */
277     @Nullable
278     protected ContentResponse sendRequest(String url, String payload) {
279         logger.trace("({}) sendRequest to '{}' with cookie '{}'", uid, url, this.cookie);
280
281         Request httpRequest = bridge.getHttpClient().newRequest(url).method(HttpMethod.POST.toString());
282
283         /* set header */
284         httpRequest = setHeaders(httpRequest);
285         httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS);
286
287         /* add request body */
288         httpRequest.content(new StringContentProvider(payload, CONTENT_CHARSET), CONTENT_TYPE_JSON);
289
290         try {
291             ContentResponse httpResponse = httpRequest.send();
292             return httpResponse;
293         } catch (InterruptedException e) {
294             logger.debug("({}) sending request interrupted: {}", uid, e.toString());
295             handleError(new TapoErrorHandler(e));
296         } catch (TimeoutException e) {
297             logger.debug("({}) sending request timeout: {}", uid, e.toString());
298             handleError(new TapoErrorHandler(ERR_CONNECT_TIMEOUT, e.toString()));
299         } catch (Exception e) {
300             logger.debug("({}) sending request failed: {}", uid, e.toString());
301             handleError(new TapoErrorHandler(e));
302         }
303         return null;
304     }
305
306     /**
307      * SEND ASYNCHRONOUS HTTP-REQUEST
308      * (don't wait for awnser with programm code)
309      * 
310      * @param url string url request is sent to
311      * @param payload data-payload
312      * @param command command executed - this will handle RepsonseType
313      */
314     protected void sendAsyncRequest(String url, String payload, String command) {
315         logger.trace("({}) sendAsncRequest to '{}' with cookie '{}'", uid, url, this.cookie);
316         try {
317             Request httpRequest = bridge.getHttpClient().newRequest(url).method(HttpMethod.POST.toString());
318
319             /* set header */
320             httpRequest = setHeaders(httpRequest);
321
322             /* add request body */
323             httpRequest.content(new StringContentProvider(payload, CONTENT_CHARSET), CONTENT_TYPE_JSON);
324
325             httpRequest.timeout(TAPO_HTTP_TIMEOUT_MS, TimeUnit.MILLISECONDS).send(new BufferingResponseListener() {
326                 @NonNullByDefault({})
327                 @Override
328                 public void onComplete(Result result) {
329                     final HttpResponse response = (HttpResponse) result.getResponse();
330                     if (result.getFailure() != null) {
331                         /* handle result errors */
332                         Throwable e = result.getFailure();
333                         String errorMessage = getValueOrDefault(e.getMessage(), "");
334                         if (e instanceof TimeoutException) {
335                             logger.debug("({}) sendAsyncRequest timeout'{}'", uid, errorMessage);
336                             handleError(new TapoErrorHandler(ERR_CONNECT_TIMEOUT, errorMessage));
337                         } else {
338                             logger.debug("({}) sendAsyncRequest failed'{}'", uid, errorMessage);
339                             handleError(new TapoErrorHandler(new Exception(e), errorMessage));
340                         }
341                     } else if (response.getStatus() != 200) {
342                         logger.debug("({}) sendAsyncRequest response error'{}'", uid, response.getStatus());
343                         handleError(new TapoErrorHandler(ERR_HTTP_RESPONSE, getContentAsString()));
344                     } else {
345                         /* request succesfull */
346                         String rBody = getContentAsString();
347                         rBody = decryptResponse(rBody);
348                         logger.trace("({}) requestCompleted '{}'", uid, rBody);
349                         /* handle result */
350                         switch (command) {
351                             case DEVICE_CMD_SETINFO:
352                                 handleSuccessResponse(rBody);
353                                 break;
354                             case DEVICE_CMD_GETINFO:
355                                 handleDeviceResult(rBody);
356                                 break;
357                             case DEVICE_CMD_GETENERGY:
358                                 handleEnergyResult(rBody);
359                                 break;
360                             case DEVICE_CMD_CUSTOM:
361                                 handleCustomResponse(rBody);
362                                 break;
363                         }
364                     }
365                 }
366             });
367         } catch (Exception e) {
368             handleError(new TapoErrorHandler(e));
369         }
370     }
371
372     /**
373      * return error code from response
374      * 
375      * @param response
376      * @return 0 if request was successfull
377      */
378     protected Integer getErrorCode(@Nullable ContentResponse response) {
379         try {
380             if (response != null) {
381                 String responseBody = response.getContentAsString();
382                 return getErrorCode(responseBody);
383             } else {
384                 return ERR_HTTP_RESPONSE;
385             }
386         } catch (Exception e) {
387             return ERR_HTTP_RESPONSE;
388         }
389     }
390
391     /**
392      * return error code from responseBody
393      * 
394      * @param responseBody
395      * @return 0 if request was successfull
396      */
397     protected Integer getErrorCode(String responseBody) {
398         try {
399             JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
400             /* get errocode (0=success) */
401             Integer errorCode = jsonObjectToInt(jsonObject, "error_code", ERR_JSON_DECODE_FAIL);
402             if (errorCode == 0) {
403                 return 0;
404             } else {
405                 logger.debug("({}) device returns errorcode '{}'", uid, errorCode);
406                 handleError(new TapoErrorHandler(errorCode));
407                 return errorCode;
408             }
409         } catch (Exception e) {
410             return ERR_HTTP_RESPONSE;
411         }
412     }
413
414     /**
415      * SET HTTP-HEADERS
416      */
417     private Request setHeaders(Request httpRequest) {
418         /* set header */
419         httpRequest.header("content-type", CONTENT_TYPE_JSON);
420         httpRequest.header("Accept", CONTENT_TYPE_JSON);
421         if (!this.cookie.isEmpty()) {
422             httpRequest.header(HTTP_AUTH_TYPE_COOKIE, this.cookie);
423         }
424         return httpRequest;
425     }
426
427     /***********************************
428      *
429      * ENCRYPTION / CODING
430      *
431      ************************************/
432
433     /**
434      * Decrypt Response
435      * 
436      * @param responseBody encrypted string from response-body
437      * @return String decrypted responseBody
438      */
439     protected String decryptResponse(String responseBody) {
440         try {
441             JsonObject jsonObject = gson.fromJson(responseBody, JsonObject.class);
442             if (jsonObject != null) {
443                 String encryptedResponse = jsonObjectToString(jsonObject.getAsJsonObject("result"), "response");
444                 return tapoCipher.decode(encryptedResponse);
445             } else {
446                 handleError(new TapoErrorHandler(ERR_JSON_DECODE_FAIL));
447             }
448         } catch (Exception ex) {
449             logger.debug("({}) exception '{}' decryptingResponse: '{}'", uid, ex.toString(), responseBody);
450         }
451         return responseBody;
452     }
453
454     /**
455      * encrypt payload
456      * 
457      * @param payload
458      * @return encrypted payload
459      */
460     protected String encryptPayload(String payload) {
461         try {
462             return tapoCipher.encode(payload);
463         } catch (Exception ex) {
464             logger.debug("({}) exception encoding Payload '{}'", uid, ex.toString());
465             return "";
466         }
467     }
468
469     /**
470      * perform logout (dispose cookie)
471      */
472     public void logout() {
473         logger.trace("DeviceHttpApi_logout");
474         unsetToken();
475         unsetCookie();
476     }
477
478     /***********************************
479      *
480      * GET RESULTS
481      *
482      ************************************/
483     /**
484      * Logged In
485      * 
486      * @return true if logged in
487      */
488     public Boolean loggedIn() {
489         return loggedIn(false);
490     }
491
492     /**
493      * Logged In
494      * 
495      * @param raiseError if true
496      * @return true if logged in
497      */
498     public Boolean loggedIn(Boolean raiseError) {
499         if (!this.token.isBlank() && !this.cookie.isBlank()) {
500             return true;
501         } else {
502             logger.trace("({}) not logged in", uid);
503             if (raiseError) {
504                 handleError(new TapoErrorHandler(ERR_LOGIN));
505             }
506             return false;
507         }
508     }
509
510     /***********************************
511      *
512      * SET VALUES
513      *
514      ************************************/
515
516     /**
517      * Set new ipAddress
518      * 
519      * @param new ipAdress
520      */
521     public void setDeviceURL(String ipAddress) {
522         this.ipAddress = ipAddress;
523         this.deviceURL = String.format(TAPO_DEVICE_URL, ipAddress);
524     }
525
526     /**
527      * Set new ipAdresss with token
528      * 
529      * @param ipAddress ipAddres of device
530      * @param token token from login-ressult
531      */
532     public void setDeviceURL(String ipAddress, String token) {
533         this.ipAddress = ipAddress;
534         this.deviceURL = String.format(TAPO_DEVICE_URL, ipAddress);
535     }
536
537     /**
538      * Set new token
539      * 
540      * @param deviceURL
541      * @param token
542      */
543     protected void setToken(String token) {
544         if (!token.isBlank()) {
545             String url = this.deviceURL.replaceAll("\\?token=\\w*", "");
546             this.deviceURL = url + "?token=" + token;
547         }
548         this.token = token;
549     }
550
551     /**
552      * Unset Token (device logout)
553      */
554     protected void unsetToken() {
555         this.deviceURL = this.deviceURL.replaceAll("\\?token=\\w*", "");
556         this.token = "";
557     }
558
559     /**
560      * Set new cookie
561      * 
562      * @param cookie
563      */
564     protected void setCookie(String cookie) {
565         this.cookie = cookie;
566     }
567
568     /**
569      * Unset Cookie (device logout)
570      */
571     protected void unsetCookie() {
572         bridge.getHttpClient().getCookieStore().removeAll();
573         this.cookie = "";
574     }
575 }