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.TapoErrorConstants.*;
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_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 long now = System.currentTimeMillis();
146 if (now > this.lastSent + TAPO_SEND_MIN_GAP_MS) {
150 PayloadBuilder plBuilder = new PayloadBuilder();
151 plBuilder.method = DEVICE_CMD_SETINFO;
152 plBuilder.addParameter(name, value);
153 String payload = plBuilder.getPayload();
155 sendSecurePasstrhroug(payload, DEVICE_CMD_SETINFO);
157 logger.debug("({}) command not sent becauso of min_gap: {}", uid, now + " <- " + lastSent);
162 * send "set_device_info" command to child's device
164 * @param index of the child
165 * @param childProperty to modify
166 * @param value for the property
168 public void sendChildCommand(Integer index, String childProperty, Object value) {
169 long now = System.currentTimeMillis();
170 if (now > this.lastSent + TAPO_SEND_MIN_GAP_MS) {
172 getChild(index).ifPresent(child -> {
173 child.setDeviceOn(Boolean.valueOf((Boolean) value));
174 TapoSubRequest request = new TapoSubRequest(child.getDeviceId(), DEVICE_CMD_SETINFO, child);
175 sendSecurePasstrhroug(GSON.toJson(request), request.method());
178 logger.debug("({}) command not sent because of min_gap: {}", uid, now + " <- " + lastSent);
183 * send multiple "set_device_info" commands to device
185 * @param map HashMap<String, Object> (name, value of parameter)
187 public void sendDeviceCommands(HashMap<String, Object> map) {
188 long now = System.currentTimeMillis();
189 if (now > this.lastSent + TAPO_SEND_MIN_GAP_MS) {
193 PayloadBuilder plBuilder = new PayloadBuilder();
194 plBuilder.method = DEVICE_CMD_SETINFO;
195 for (HashMap.Entry<String, Object> entry : map.entrySet()) {
196 plBuilder.addParameter(entry.getKey(), entry.getValue());
198 String payload = plBuilder.getPayload();
200 sendSecurePasstrhroug(payload, DEVICE_CMD_SETINFO);
202 logger.debug("({}) command not sent becauso of min_gap: {}", uid, now + " <- " + lastSent);
207 * Query Info from Device and refresh deviceInfo
209 public void queryInfo() {
215 * Query Info from Device and refresh deviceInfo
218 * @param ignoreGap ignore gap to last query. query anyway
220 public void queryInfo(boolean ignoreGap) {
221 logger.trace("({}) DeviceConnetor_queryInfo from '{}'", uid, deviceURL);
222 queryCommand(DEVICE_CMD_GETINFO, ignoreGap);
226 * Query Info from Child Devices and refresh deviceInfo
229 public void queryChildDevices() {
230 logger.trace("({}) DeviceConnetor_queryChildDevices from '{}'", uid, deviceURL);
231 queryCommand(DEVICE_CMD_CHILD_DEVICE_LIST, false);
235 * Get energy usage from device
237 public void getEnergyUsage() {
238 queryCommand(DEVICE_CMD_GETENERGY, true);
242 * Send Custom DeviceQuery
244 * @param queryCommand Command to be queried
245 * @param ignoreGap ignore gap to last query. query anyway
247 public void queryCommand(String queryCommand, boolean ignoreGap) {
248 logger.trace("({}) DeviceConnetor_queryCommand '{}' from '{}'", uid, queryCommand, deviceURL);
249 long now = System.currentTimeMillis();
250 if (ignoreGap || now > this.lastQuery + TAPO_SEND_MIN_GAP_MS) {
251 this.lastQuery = now;
254 PayloadBuilder plBuilder = new PayloadBuilder();
255 plBuilder.method = queryCommand;
256 String payload = plBuilder.getPayload();
258 sendSecurePasstrhroug(payload, queryCommand);
260 logger.debug("({}) command not sent because of min_gap: {}", uid, now + " <- " + lastQuery);
265 * SEND SECUREPASSTHROUGH
266 * encprypt payload and send to device
268 * @param payload payload sent to device
269 * @param command command executed - this will handle result
271 protected void sendSecurePasstrhroug(String payload, String command) {
272 /* encrypt payload */
273 logger.trace("({}) encrypting payload '{}'", uid, payload);
274 String encryptedPayload = encryptPayload(payload);
276 /* create secured payload */
277 PayloadBuilder plBuilder = new PayloadBuilder();
278 plBuilder.method = "securePassthrough";
279 plBuilder.addParameter("request", encryptedPayload);
280 String securePassthroughPayload = plBuilder.getPayload();
282 sendAsyncRequest(deviceURL, securePassthroughPayload, command);
285 /***********************************
289 ************************************/
292 * Handle SuccessResponse (setDeviceInfo)
294 * @param responseBody String with responseBody from device
297 protected void handleSuccessResponse(String responseBody) {
298 JsonObject jsnResult = getJsonFromResponse(responseBody);
299 Integer errorCode = jsonObjectToInt(jsnResult, "error_code", ERR_JSON_DECODE_FAIL);
300 if (errorCode != 0) {
301 logger.debug("({}) set deviceInfo not successful: {}", uid, jsnResult);
302 this.device.handleConnectionState();
304 this.device.responsePasstrough(responseBody);
309 * handle JsonResponse (getDeviceInfo)
311 * @param responseBody String with responseBody from device
314 protected void handleDeviceResult(String responseBody) {
315 JsonObject jsnResult = getJsonFromResponse(responseBody);
316 if (jsnResult.has(JSON_KEY_ID)) {
317 this.deviceInfo = new TapoDeviceInfo(jsnResult);
318 this.device.setDeviceInfo(deviceInfo);
320 this.deviceInfo = new TapoDeviceInfo();
321 this.device.handleConnectionState();
323 this.device.responsePasstrough(responseBody);
327 * handle JsonResponse (getEnergyData)
329 * @param responseBody String with responseBody from device
332 protected void handleEnergyResult(String responseBody) {
333 JsonObject jsnResult = getJsonFromResponse(responseBody);
334 if (jsnResult.has(JSON_KEY_ENERGY_POWER)) {
335 this.energyData = new TapoEnergyData(jsnResult);
336 this.device.setEnergyData(energyData);
338 this.energyData = new TapoEnergyData();
340 this.device.responsePasstrough(responseBody);
344 * handle JsonResponse (getChildDeviceList)
346 * @param responseBody String with responseBody from device
349 protected void handleChildDevices(String responseBody) {
350 JsonObject jsnResult = getJsonFromResponse(responseBody);
351 if (jsnResult.has(JSON_KEY_CHILD_START_INDEX)) {
352 this.childData = Objects.requireNonNull(GSON.fromJson(jsnResult, TapoChildData.class));
353 this.device.setChildData(childData);
355 this.childData = new TapoChildData();
357 this.device.responsePasstrough(responseBody);
361 * handle custom response
363 * @param responseBody String with responseBody from device
366 protected void handleCustomResponse(String responseBody) {
367 this.device.responsePasstrough(responseBody);
373 * @param te TapoErrorHandler
376 protected void handleError(TapoErrorHandler tapoError) {
377 this.device.setError(tapoError);
381 * get Json from response
383 * @param responseBody
384 * @return JsonObject with result
386 private JsonObject getJsonFromResponse(String responseBody) {
387 JsonObject jsonObject = GSON.fromJson(responseBody, JsonObject.class);
388 /* get errocode (0=success) */
389 if (jsonObject != null) {
390 Integer errorCode = jsonObjectToInt(jsonObject, "error_code");
391 if (errorCode == 0) {
392 /* decrypt response */
393 jsonObject = GSON.fromJson(responseBody, JsonObject.class);
394 logger.trace("({}) received result: {}", uid, responseBody);
395 if (jsonObject != null) {
396 /* return result if set / else request was successful */
397 if (jsonObject.has("result")) {
398 return jsonObject.getAsJsonObject("result");
404 /* return errorcode from device */
405 TapoErrorHandler te = new TapoErrorHandler(errorCode, "device answers with errorcode");
406 logger.debug("({}) device answers with errorcode {} - {}", uid, errorCode, te.getMessage());
411 logger.debug("({}) sendPayload exception {}", uid, responseBody);
412 handleError(new TapoErrorHandler(ERR_HTTP_RESPONSE));
413 return new JsonObject();
416 /***********************************
420 ************************************/
423 * Check if device is online
425 * @return true if device is online
427 public Boolean isOnline() {
428 return isOnline(false);
432 * Check if device is online
434 * @param raiseError if true
435 * @return true if device is online
437 public Boolean isOnline(Boolean raiseError) {
441 logger.trace("({}) device is offline (no ping)", uid);
443 handleError(new TapoErrorHandler(ERR_DEVICE_OFFLINE));
453 * @return String ipAdress
455 public String getIP() {
456 return this.ipAddress;
462 * @return true if ping successfull
464 public Boolean pingDevice() {
466 InetAddress address = InetAddress.getByName(this.ipAddress);
467 return address.isReachable(TAPO_PING_TIMEOUT_MS);
468 } catch (Exception e) {
469 logger.debug("({}) InetAdress throws: {}", uid, e.getMessage());
474 private Optional<TapoChild> getChild(int position) {
475 return childData.getChildDeviceList().stream().filter(child -> child.getPosition() == position).findFirst();