2 * Copyright (c) 2010-2023 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.tapocontrol.internal.api;
15 import static org.openhab.binding.tapocontrol.internal.constants.TapoBindingSettings.*;
16 import static org.openhab.binding.tapocontrol.internal.constants.TapoErrorCode.*;
17 import static org.openhab.binding.tapocontrol.internal.constants.TapoThingConstants.*;
18 import static org.openhab.binding.tapocontrol.internal.helpers.TapoUtils.jsonObjectToInt;
20 import java.net.InetAddress;
21 import java.util.HashMap;
22 import java.util.Objects;
23 import java.util.Optional;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.openhab.binding.tapocontrol.internal.device.TapoBridgeHandler;
27 import org.openhab.binding.tapocontrol.internal.device.TapoDevice;
28 import org.openhab.binding.tapocontrol.internal.helpers.PayloadBuilder;
29 import org.openhab.binding.tapocontrol.internal.helpers.TapoErrorHandler;
30 import org.openhab.binding.tapocontrol.internal.structures.TapoChild;
31 import org.openhab.binding.tapocontrol.internal.structures.TapoChildData;
32 import org.openhab.binding.tapocontrol.internal.structures.TapoDeviceInfo;
33 import org.openhab.binding.tapocontrol.internal.structures.TapoEnergyData;
34 import org.openhab.binding.tapocontrol.internal.structures.TapoSubRequest;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import com.google.gson.JsonObject;
41 * Handler class for TAPO Smart Home device connections.
42 * This class uses asynchronous HttpClient-Requests
44 * @author Christian Wild - Initial contribution
47 public class TapoDeviceConnector extends TapoDeviceHttpApi {
49 private final Logger logger = LoggerFactory.getLogger(TapoDeviceConnector.class);
51 private TapoDeviceInfo deviceInfo = new TapoDeviceInfo();
52 private TapoEnergyData energyData = new TapoEnergyData();
53 private TapoChildData childData = new TapoChildData();
54 private long lastQuery = 0L;
55 private long lastSent = 0L;
56 private long lastLogin = 0L;
61 * @param config TapoControlConfiguration class
63 public TapoDeviceConnector(TapoDevice device, TapoBridgeHandler bridgeThingHandler) {
64 super(device, bridgeThingHandler);
67 /***********************************
71 ************************************/
75 * @return true if success
77 public boolean login() {
78 if (this.pingDevice()) {
79 logger.trace("({}) sending login to url '{}'", uid, deviceURL);
81 long now = System.currentTimeMillis();
82 if (now > this.lastLogin + TAPO_LOGIN_MIN_GAP_MS) {
87 /* create ssl-handschake (cookie) */
88 String cookie = createHandshake();
89 if (!cookie.isBlank()) {
91 String token = queryToken();
95 logger.trace("({}) not done cause of min_gap '{}'", uid, TAPO_LOGIN_MIN_GAP_MS);
97 return this.loggedIn();
99 logger.debug("({}) no ping while login '{}'", uid, this.ipAddress);
100 handleError(new TapoErrorHandler(ERR_BINDING_DEVICE_OFFLINE, "no ping while login"));
105 /***********************************
109 ************************************/
112 * send custom command to device
114 * @param plBuilder Payloadbuilder with unencrypted payload
116 public void sendCustomQuery(String queryMethod) {
118 PayloadBuilder plBuilder = new PayloadBuilder();
119 plBuilder.method = queryMethod;
120 sendCustomPayload(plBuilder);
124 * send custom command to device
126 * @param plBuilder Payloadbuilder with unencrypted payload
128 public void sendCustomPayload(PayloadBuilder plBuilder) {
129 long now = System.currentTimeMillis();
130 if (now > this.lastSent + TAPO_SEND_MIN_GAP_MS) {
131 String payload = plBuilder.getPayload();
132 sendSecurePasstrhroug(payload, DEVICE_CMD_CUSTOM);
134 logger.debug("({}) command not sent becauso of min_gap: {}", uid, now + " <- " + lastSent);
139 * send "set_device_info" command to device
141 * @param name Name of command to send
142 * @param value Value to send to control
144 public void sendDeviceCommand(String name, Object value) {
145 sendDeviceCommand(DEVICE_CMD_SETINFO, name, value);
149 * send "set_device_info" command to device
151 * @param method Method command belongs to
152 * @param name Name of command to send
153 * @param value Value to send to control
155 public void sendDeviceCommand(String method, String name, Object value) {
156 long now = System.currentTimeMillis();
157 if (now > this.lastSent + TAPO_SEND_MIN_GAP_MS) {
161 PayloadBuilder plBuilder = new PayloadBuilder();
162 plBuilder.method = method;
163 plBuilder.addParameter(name, value);
164 String payload = plBuilder.getPayload();
166 sendSecurePasstrhroug(payload, method);
168 logger.debug("({}) command not sent becauso of min_gap: {}", uid, now + " <- " + lastSent);
173 * send "set_device_info" command to child's device
175 * @param index of the child
176 * @param childProperty to modify
177 * @param value for the property
179 public void sendChildCommand(Integer index, String childProperty, Object value) {
180 long now = System.currentTimeMillis();
181 if (now > this.lastSent + TAPO_SEND_MIN_GAP_MS) {
183 getChild(index).ifPresent(child -> {
184 child.setDeviceOn(Boolean.valueOf((Boolean) value));
185 TapoSubRequest request = new TapoSubRequest(child.getDeviceId(), DEVICE_CMD_SETINFO, child);
186 sendSecurePasstrhroug(GSON.toJson(request), request.method());
189 logger.debug("({}) command not sent because of min_gap: {}", uid, now + " <- " + lastSent);
194 * send multiple "set_device_info" commands to device
196 * @param map HashMap<String, Object> (name, value of parameter)
198 public void sendDeviceCommands(HashMap<String, Object> map) {
199 sendDeviceCommands(DEVICE_CMD_SETINFO, map);
203 * send multiple commands to device
205 * @param method Method command belongs to
206 * @param map HashMap<String, Object> (name, value of parameter)
208 public void sendDeviceCommands(String method, HashMap<String, Object> map) {
209 long now = System.currentTimeMillis();
210 if (now > this.lastSent + TAPO_SEND_MIN_GAP_MS) {
214 PayloadBuilder plBuilder = new PayloadBuilder();
215 plBuilder.method = method;
216 for (HashMap.Entry<String, Object> entry : map.entrySet()) {
217 plBuilder.addParameter(entry.getKey(), entry.getValue());
219 String payload = plBuilder.getPayload();
221 sendSecurePasstrhroug(payload, method);
223 logger.debug("({}) command not sent becauso of min_gap: {}", uid, now + " <- " + lastSent);
228 * Query Info from Device and refresh deviceInfo
230 public void queryInfo() {
235 * Query Info from Device and refresh deviceInfo
238 * @param ignoreGap ignore gap to last query. query anyway
240 public void queryInfo(boolean ignoreGap) {
241 logger.trace("({}) DeviceConnector_queryInfo from '{}'", uid, deviceURL);
242 queryCommand(DEVICE_CMD_GETINFO, ignoreGap);
246 * Query Info from Child Devices and refresh deviceInfo
249 public void queryChildDevices() {
250 logger.trace("({}) DeviceConnector_queryChildDevices from '{}'", uid, deviceURL);
251 queryCommand(DEVICE_CMD_CHILD_DEVICE_LIST, true);
255 * Get energy usage from device
257 public void getEnergyUsage() {
258 queryCommand(DEVICE_CMD_GETENERGY, true);
262 * Send Custom DeviceQuery
264 * @param queryCommand Command to be queried
265 * @param ignoreGap ignore gap to last query. query anyway
267 public void queryCommand(String queryCommand, boolean ignoreGap) {
268 logger.trace("({}) DeviceConnector_queryCommand '{}' from '{}'", uid, queryCommand, deviceURL);
269 long now = System.currentTimeMillis();
270 if (ignoreGap || now > this.lastQuery + TAPO_SEND_MIN_GAP_MS) {
271 this.lastQuery = now;
274 PayloadBuilder plBuilder = new PayloadBuilder();
275 plBuilder.method = queryCommand;
276 String payload = plBuilder.getPayload();
278 sendSecurePasstrhroug(payload, queryCommand);
280 logger.debug("({}) command not sent because of min_gap: {}", uid, now + " <- " + lastQuery);
285 * SEND SECUREPASSTHROUGH
286 * encprypt payload and send to device
288 * @param payload payload sent to device
289 * @param command command executed - this will handle result
291 protected void sendSecurePasstrhroug(String payload, String command) {
292 /* encrypt payload */
293 logger.trace("({}) encrypting payload '{}'", uid, payload);
294 String encryptedPayload = encryptPayload(payload);
296 /* create secured payload */
297 PayloadBuilder plBuilder = new PayloadBuilder();
298 plBuilder.method = "securePassthrough";
299 plBuilder.addParameter("request", encryptedPayload);
300 String securePassthroughPayload = plBuilder.getPayload();
302 sendAsyncRequest(deviceURL, securePassthroughPayload, command);
305 /***********************************
309 ************************************/
312 * Handle SuccessResponse (setDeviceInfo)
314 * @param responseBody String with responseBody from device
317 protected void handleSuccessResponse(String responseBody) {
318 JsonObject jsnResult = getJsonFromResponse(responseBody);
319 Integer errorCode = jsonObjectToInt(jsnResult, "error_code", ERR_API_JSON_DECODE_FAIL.getCode());
320 if (errorCode != 0) {
321 logger.debug("({}) set deviceInfo not successful: {}", uid, jsnResult);
322 this.device.handleConnectionState();
324 this.device.responsePasstrough(responseBody);
329 * handle JsonResponse (getDeviceInfo)
331 * @param responseBody String with responseBody from device
334 protected void handleDeviceResult(String responseBody) {
335 JsonObject jsnResult = getJsonFromResponse(responseBody);
336 if (jsnResult.has(JSON_KEY_ID)) {
337 this.deviceInfo = new TapoDeviceInfo(jsnResult);
338 this.device.setDeviceInfo(deviceInfo);
340 this.deviceInfo = new TapoDeviceInfo();
341 this.device.handleConnectionState();
343 this.device.responsePasstrough(responseBody);
347 * handle JsonResponse (getEnergyData)
349 * @param responseBody String with responseBody from device
352 protected void handleEnergyResult(String responseBody) {
353 JsonObject jsnResult = getJsonFromResponse(responseBody);
354 if (jsnResult.has(JSON_KEY_ENERGY_POWER)) {
355 this.energyData = new TapoEnergyData(jsnResult);
356 this.device.setEnergyData(energyData);
358 this.energyData = new TapoEnergyData();
360 this.device.responsePasstrough(responseBody);
364 * handle JsonResponse (getChildDeviceList)
366 * @param responseBody String with responseBody from device
369 protected void handleChildDevices(String responseBody) {
370 JsonObject jsnResult = getJsonFromResponse(responseBody);
371 if (jsnResult.has(JSON_KEY_CHILD_START_INDEX)) {
372 this.childData = Objects.requireNonNull(GSON.fromJson(jsnResult, TapoChildData.class));
373 this.device.setChildData(childData);
375 this.childData = new TapoChildData();
377 this.device.responsePasstrough(responseBody);
381 * handle custom response
383 * @param responseBody String with responseBody from device
386 protected void handleCustomResponse(String responseBody) {
387 this.device.responsePasstrough(responseBody);
393 * @param te TapoErrorHandler
396 protected void handleError(TapoErrorHandler tapoError) {
397 this.device.setError(tapoError);
401 * get Json from response
403 * @param responseBody
404 * @return JsonObject with result
406 private JsonObject getJsonFromResponse(String responseBody) {
407 JsonObject jsonObject = GSON.fromJson(responseBody, JsonObject.class);
408 /* get errocode (0=success) */
409 if (jsonObject != null) {
410 Integer errorCode = jsonObjectToInt(jsonObject, "error_code");
411 if (errorCode == 0) {
412 /* decrypt response */
413 jsonObject = GSON.fromJson(responseBody, JsonObject.class);
414 logger.trace("({}) received result: {}", uid, responseBody);
415 if (jsonObject != null) {
416 /* return result if set / else request was successful */
417 if (jsonObject.has("result")) {
418 return jsonObject.getAsJsonObject("result");
424 /* return errorcode from device */
425 TapoErrorHandler te = new TapoErrorHandler(errorCode, "device answers with errorcode");
426 logger.debug("({}) device answers with errorcode {} - {}", uid, errorCode, te.getMessage());
431 logger.debug("({}) sendPayload exception {}", uid, responseBody);
432 handleError(new TapoErrorHandler(ERR_BINDING_HTTP_RESPONSE));
433 return new JsonObject();
436 /***********************************
440 ************************************/
443 * Check if device is online
445 * @return true if device is online
447 public Boolean isOnline() {
448 return isOnline(false);
452 * Check if device is online
454 * @param raiseError if true
455 * @return true if device is online
457 public Boolean isOnline(Boolean raiseError) {
461 logger.trace("({}) device is offline (no ping)", uid);
463 handleError(new TapoErrorHandler(ERR_BINDING_DEVICE_OFFLINE));
473 * @return String ipAdress
475 public String getIP() {
476 return this.ipAddress;
482 * @return true if ping successfull
484 public Boolean pingDevice() {
486 InetAddress address = InetAddress.getByName(this.ipAddress);
487 return address.isReachable(TAPO_PING_TIMEOUT_MS);
488 } catch (Exception e) {
489 logger.debug("({}) InetAdress throws: {}", uid, e.getMessage());
494 private Optional<TapoChild> getChild(int position) {
495 return childData.getChildDeviceList().stream().filter(child -> child.getPosition() == position).findFirst();