]> git.basschouten.com Git - openhab-addons.git/blob
8e8ad79e51b5fc0b07fc91e864cbe34a9dde260e
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.shelly.internal.api;
14
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
18
19 import java.nio.charset.StandardCharsets;
20 import java.util.Base64;
21 import java.util.HashMap;
22 import java.util.Map;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jetty.client.HttpClient;
29 import org.eclipse.jetty.client.api.ContentResponse;
30 import org.eclipse.jetty.client.api.Request;
31 import org.eclipse.jetty.http.HttpHeader;
32 import org.eclipse.jetty.http.HttpMethod;
33 import org.eclipse.jetty.http.HttpStatus;
34 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyControlRoller;
35 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySendKeyList;
36 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySenseKeyCode;
37 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsDevice;
38 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsLight;
39 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsStatus;
40 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyShortLightStatus;
41 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusLight;
42 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusRelay;
43 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusSensor;
44 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
45 import org.openhab.core.library.unit.ImperialUnits;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
48
49 import com.google.gson.Gson;
50 import com.google.gson.JsonSyntaxException;
51
52 import tec.uom.se.unit.Units;
53
54 /**
55  * {@link ShellyHttpApi} wraps the Shelly REST API and provides various low level function to access the device api (not
56  * cloud api).
57  *
58  * @author Markus Michels - Initial contribution
59  */
60 @NonNullByDefault
61 public class ShellyHttpApi {
62     public static final String HTTP_HEADER_AUTH = "Authorization";
63     public static final String HTTP_AUTH_TYPE_BASIC = "Basic";
64     public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
65
66     private final Logger logger = LoggerFactory.getLogger(ShellyHttpApi.class);
67     private final HttpClient httpClient;
68     private ShellyThingConfiguration config = new ShellyThingConfiguration();
69     private String thingName;
70     private final Gson gson = new Gson();
71     private int timeoutErrors = 0;
72     private int timeoutsRecovered = 0;
73
74     private ShellyDeviceProfile profile = new ShellyDeviceProfile();
75
76     public ShellyHttpApi(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
77         this.httpClient = httpClient;
78         this.thingName = thingName;
79         setConfig(thingName, config);
80         profile.initFromThingType(thingName);
81     }
82
83     public void setConfig(String thingName, ShellyThingConfiguration config) {
84         this.thingName = thingName;
85         this.config = config;
86     }
87
88     public ShellySettingsDevice getDevInfo() throws ShellyApiException {
89         return callApi(SHELLY_URL_DEVINFO, ShellySettingsDevice.class);
90     }
91
92     /**
93      * Initialize the device profile
94      *
95      * @param thingType Type of DEVICE as returned from the thing properties (based on discovery)
96      * @return Initialized ShellyDeviceProfile
97      * @throws ShellyApiException
98      */
99     public ShellyDeviceProfile getDeviceProfile(String thingType) throws ShellyApiException {
100         String json = request(SHELLY_URL_SETTINGS);
101         if (json.contains("\"type\":\"SHDM-")) {
102             logger.trace("{}: Detected a Shelly Dimmer: fix Json (replace lights[] tag with dimmers[]", thingName);
103             json = fixDimmerJson(json);
104         }
105
106         // Map settings to device profile for Light and Sense
107         profile.initialize(thingType, json);
108
109         // 2nd level initialization
110         profile.thingName = profile.hostname;
111         if (profile.isLight && (profile.numMeters == 0)) {
112             logger.debug("{}: Get number of meters from light status", thingName);
113             ShellyStatusLight status = getLightStatus();
114             profile.numMeters = status.meters != null ? status.meters.size() : 0;
115         }
116         if (profile.isSense) {
117             profile.irCodes = getIRCodeList();
118             logger.debug("{}: Sense stored key list loaded, {} entries.", thingName, profile.irCodes.size());
119         }
120
121         return profile;
122     }
123
124     public boolean isInitialized() {
125         return profile.initialized;
126     }
127
128     /**
129      * Get generic device settings/status. Json returned from API will be mapped to a Gson object
130      *
131      * @return Device settings/status as ShellySettingsStatus object
132      * @throws ShellyApiException
133      */
134     public ShellySettingsStatus getStatus() throws ShellyApiException {
135         String json = "";
136         try {
137             json = request(SHELLY_URL_STATUS);
138             // Dimmer2 returns invalid json type for loaderror :-(
139             json = json.replace("\"loaderror\":0,", "\"loaderror\":false,");
140             json = json.replace("\"loaderror\":1,", "\"loaderror\":true,");
141             ShellySettingsStatus status = gson.fromJson(json, ShellySettingsStatus.class);
142             status.json = json;
143             return status;
144         } catch (JsonSyntaxException e) {
145             throw new ShellyApiException("Unable to parse JSON: " + json, e);
146         }
147     }
148
149     public ShellyStatusRelay getRelayStatus(Integer relayIndex) throws ShellyApiException {
150         return callApi(SHELLY_URL_STATUS_RELEAY + "/" + relayIndex.toString(), ShellyStatusRelay.class);
151     }
152
153     public ShellyShortLightStatus setRelayTurn(Integer id, String turnMode) throws ShellyApiException {
154         return callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
155                 ShellyShortLightStatus.class);
156     }
157
158     public void setBrightness(Integer id, Integer brightness, boolean autoOn) throws ShellyApiException {
159         String turn = autoOn ? SHELLY_LIGHT_TURN + "=" + SHELLY_API_ON + "&" : "";
160         request(getControlUriPrefix(id) + "?" + turn + "brightness=" + brightness.toString());
161     }
162
163     public ShellyControlRoller getRollerStatus(Integer rollerIndex) throws ShellyApiException {
164         String uri = SHELLY_URL_CONTROL_ROLLER + "/" + rollerIndex.toString() + "/pos";
165         return callApi(uri, ShellyControlRoller.class);
166     }
167
168     public void setRollerTurn(Integer relayIndex, String turnMode) throws ShellyApiException {
169         request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=" + turnMode);
170     }
171
172     public void setRollerPos(Integer relayIndex, Integer position) throws ShellyApiException {
173         request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=to_pos&roller_pos="
174                 + position.toString());
175     }
176
177     public void setRollerTimer(Integer relayIndex, Integer timer) throws ShellyApiException {
178         request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?timer=" + timer.toString());
179     }
180
181     public ShellyShortLightStatus getLightStatus(Integer index) throws ShellyApiException {
182         return callApi(getControlUriPrefix(index), ShellyShortLightStatus.class);
183     }
184
185     public ShellyStatusSensor getSensorStatus() throws ShellyApiException {
186         ShellyStatusSensor status = callApi(SHELLY_URL_STATUS, ShellyStatusSensor.class);
187         if (profile.isSense) {
188             // complete reported data, map C to F or vice versa: C=(F - 32) * 0.5556;
189             status.tmp.tC = status.tmp.units.equals(SHELLY_TEMP_CELSIUS) ? status.tmp.value
190                     : ImperialUnits.FAHRENHEIT.getConverterTo(Units.CELSIUS).convert(getDouble(status.tmp.value))
191                             .doubleValue();
192             status.tmp.tF = status.tmp.units.equals(SHELLY_TEMP_FAHRENHEIT) ? status.tmp.value
193                     : Units.CELSIUS.getConverterTo(ImperialUnits.FAHRENHEIT).convert(getDouble(status.tmp.value))
194                             .doubleValue();
195         }
196         if ((status.charger == null) && (status.externalPower != null)) {
197             // SHelly H&T uses external_power, Sense uses charger
198             status.charger = status.externalPower != 0;
199         }
200
201         return status;
202     }
203
204     public void setTimer(Integer index, String timerName, Double value) throws ShellyApiException {
205         String type = SHELLY_CLASS_RELAY;
206         if (profile.isRoller) {
207             type = SHELLY_CLASS_ROLLER;
208         } else if (profile.isLight) {
209             type = SHELLY_CLASS_LIGHT;
210         }
211         String uri = SHELLY_URL_SETTINGS + "/" + type + "/" + index + "?" + timerName + "="
212                 + ((Integer) value.intValue()).toString();
213         request(uri);
214     }
215
216     public void setLedStatus(String ledName, Boolean value) throws ShellyApiException {
217         request(SHELLY_URL_SETTINGS + "?" + ledName + "=" + (value ? SHELLY_API_TRUE : SHELLY_API_FALSE));
218     }
219
220     public ShellySettingsLight getLightSettings() throws ShellyApiException {
221         return callApi(SHELLY_URL_SETTINGS_LIGHT, ShellySettingsLight.class);
222     }
223
224     public ShellyStatusLight getLightStatus() throws ShellyApiException {
225         return callApi(SHELLY_URL_STATUS, ShellyStatusLight.class);
226     }
227
228     public void setLightSetting(String parm, String value) throws ShellyApiException {
229         request(SHELLY_URL_SETTINGS + "?" + parm + "=" + value);
230     }
231
232     /**
233      * Change between White and Color Mode
234      *
235      * @param mode
236      * @throws ShellyApiException
237      */
238     public void setLightMode(String mode) throws ShellyApiException {
239         if (!mode.isEmpty() && !profile.mode.equals(mode)) {
240             setLightSetting(SHELLY_API_MODE, mode);
241             profile.mode = mode;
242             profile.inColor = profile.isLight && profile.mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
243         }
244     }
245
246     /**
247      * Set a single light parameter
248      *
249      * @param lightIndex Index of the light, usually 0 for Bulb and 0..3 for RGBW2.
250      * @param parm Name of the parameter (see API spec)
251      * @param value The value
252      * @throws ShellyApiException
253      */
254     public void setLightParm(Integer lightIndex, String parm, String value) throws ShellyApiException {
255         // Bulb, RGW2: /<color mode>/<light id>?parm?value
256         // Dimmer: /light/<light id>?parm=value
257         request(getControlUriPrefix(lightIndex) + "?" + parm + "=" + value);
258     }
259
260     public void setLightParms(Integer lightIndex, Map<String, String> parameters) throws ShellyApiException {
261         String url = getControlUriPrefix(lightIndex) + "?";
262         int i = 0;
263         for (String key : parameters.keySet()) {
264             if (i > 0) {
265                 url = url + "&";
266             }
267             url = url + key + "=" + parameters.get(key);
268             i++;
269         }
270         request(url);
271     }
272
273     /**
274      * Retrieve the IR Code list from the Shelly Sense device. The list could be customized by the user. It defines the
275      * symbolic key code, which gets
276      * map into a PRONTO code
277      *
278      * @return Map of key codes
279      * @throws ShellyApiException
280      */
281     public Map<String, String> getIRCodeList() throws ShellyApiException {
282         String result = request(SHELLY_URL_LIST_IR);
283         // take pragmatic approach to make the returned JSon into named arrays for Gson parsing
284         String keyList = substringAfter(result, "[");
285         keyList = substringBeforeLast(keyList, "]");
286         keyList = keyList.replaceAll(java.util.regex.Pattern.quote("\",\""), "\", \"name\": \"");
287         keyList = keyList.replaceAll(java.util.regex.Pattern.quote("["), "{ \"id\":");
288         keyList = keyList.replaceAll(java.util.regex.Pattern.quote("]"), "} ");
289         String json = "{\"key_codes\" : [" + keyList + "] }";
290
291         ShellySendKeyList codes = gson.fromJson(json, ShellySendKeyList.class);
292         Map<String, String> list = new HashMap<>();
293         for (ShellySenseKeyCode key : codes.keyCodes) {
294             list.put(key.id, key.name);
295         }
296         return list;
297     }
298
299     /**
300      * Sends a IR key code to the Shelly Sense.
301      *
302      * @param keyCode A keyCoud could be a symbolic name (as defined in the key map on the device) or a PRONTO Code in
303      *            plain or hex64 format
304      *
305      * @throws ShellyApiException
306      * @throws IllegalArgumentException
307      */
308     public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
309         String type = "";
310         if (profile.irCodes.containsKey(keyCode)) {
311             type = SHELLY_IR_CODET_STORED;
312         } else if ((keyCode.length() > 4) && keyCode.contains(" ")) {
313             type = SHELLY_IR_CODET_PRONTO;
314         } else {
315             type = SHELLY_IR_CODET_PRONTO_HEX;
316         }
317         String url = SHELLY_URL_SEND_IR + "?type=" + type;
318         if (type.equals(SHELLY_IR_CODET_STORED)) {
319             url = url + "&" + "id=" + keyCode;
320         } else if (type.equals(SHELLY_IR_CODET_PRONTO)) {
321             String code = Base64.getEncoder().encodeToString(keyCode.getBytes(StandardCharsets.UTF_8));
322             if (code == null) {
323                 throw new IllegalArgumentException("Unable to BASE64 encode the pronto code: " + keyCode);
324             }
325             url = url + "&" + SHELLY_IR_CODET_PRONTO + "=" + code;
326         } else if (type.equals(SHELLY_IR_CODET_PRONTO_HEX)) {
327             url = url + "&" + SHELLY_IR_CODET_PRONTO_HEX + "=" + keyCode;
328         }
329         request(url);
330     }
331
332     public void setSenseSetting(String setting, String value) throws ShellyApiException {
333         request(SHELLY_URL_SETTINGS + "?" + setting + "=" + value);
334     }
335
336     /**
337      * Set event callback URLs. Depending on the device different event types are supported. In fact all of them will be
338      * redirected to the binding's servlet and act as a trigger to schedule a status update
339      *
340      * @param ShellyApiException
341      * @throws ShellyApiException
342      */
343     public void setActionURLs() throws ShellyApiException {
344         setRelayEvents();
345         setDimmerEvents();
346         setSensorEventUrls();
347     }
348
349     private void setRelayEvents() throws ShellyApiException {
350         if (profile.settings.relays != null) {
351             int num = profile.isRoller ? profile.numRollers : profile.numRelays;
352             for (int i = 0; i < num; i++) {
353                 setEventUrls(i);
354             }
355         }
356     }
357
358     private void setDimmerEvents() throws ShellyApiException {
359         if (profile.settings.dimmers != null) {
360             for (int i = 0; i < profile.settings.dimmers.size(); i++) {
361                 setEventUrls(i);
362             }
363         } else if (profile.isLight) {
364             setEventUrls(0);
365         }
366     }
367
368     /**
369      * Set sensor Action URLs
370      *
371      * @throws ShellyApiException
372      */
373     private void setSensorEventUrls() throws ShellyApiException, ShellyApiException {
374         if (profile.isSensor) {
375             logger.debug("{}: Set Sensor Reporting URL", thingName);
376             setEventUrl(config.eventsSensorReport, SHELLY_EVENT_SENSORREPORT, SHELLY_EVENT_DARK, SHELLY_EVENT_TWILIGHT,
377                     SHELLY_EVENT_FLOOD_DETECTED, SHELLY_EVENT_FLOOD_GONE, SHELLY_EVENT_OPEN, SHELLY_EVENT_CLOSE,
378                     SHELLY_EVENT_VIBRATION, SHELLY_EVENT_ALARM_MILD, SHELLY_EVENT_ALARM_HEAVY, SHELLY_EVENT_ALARM_OFF,
379                     SHELLY_EVENT_TEMP_OVER, SHELLY_EVENT_TEMP_UNDER);
380         }
381     }
382
383     /**
384      * Set/delete Relay/Roller/Dimmer Action URLs
385      *
386      * @param index Device Index (0-based)
387      * @throws ShellyApiException
388      */
389     private void setEventUrls(Integer index) throws ShellyApiException {
390         if (profile.isRoller) {
391             setEventUrl(EVENT_TYPE_ROLLER, 0, config.eventsRoller, SHELLY_EVENT_ROLLER_OPEN, SHELLY_EVENT_ROLLER_CLOSE,
392                     SHELLY_EVENT_ROLLER_STOP);
393         } else if (profile.isDimmer) {
394             // 2 set of URLs
395             setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsButton, SHELLY_EVENT_BTN1_ON, SHELLY_EVENT_BTN1_OFF,
396                     SHELLY_EVENT_BTN2_ON, SHELLY_EVENT_BTN2_OFF);
397             setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH1, SHELLY_EVENT_LONGPUSH1,
398                     SHELLY_EVENT_SHORTPUSH2, SHELLY_EVENT_LONGPUSH2);
399
400             // Relay output
401             setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
402         } else if (profile.hasRelays) {
403             // Standard relays: btn_xxx, out_xxx, short/longpush URLs
404             setEventUrl(EVENT_TYPE_RELAY, index, config.eventsButton, SHELLY_EVENT_BTN_ON, SHELLY_EVENT_BTN_OFF);
405             setEventUrl(EVENT_TYPE_RELAY, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH, SHELLY_EVENT_LONGPUSH);
406             setEventUrl(EVENT_TYPE_RELAY, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
407         } else if (profile.isLight) {
408             // Duo, Bulb
409             setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
410         }
411     }
412
413     private void setEventUrl(boolean enabled, String... eventTypes) throws ShellyApiException {
414         if (config.localIp.isEmpty()) {
415             throw new ShellyApiException(thingName + ": Local IP address was not detected, can't build Callback URL");
416         }
417         for (String eventType : eventTypes) {
418             if (profile.containsEventUrl(eventType)) {
419                 // H&T adds the type=xx to report_url itself, so we need to ommit here
420                 String eclass = profile.isSensor ? EVENT_TYPE_SENSORDATA : eventType;
421                 String urlParm = eventType.contains("temp") || profile.isHT ? "" : "?type=" + eventType;
422                 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
423                         + profile.thingName + "/" + eclass + urlParm;
424                 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
425                 String testUrl = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
426                 if (!enabled && !profile.settingsJson.contains(testUrl)) {
427                     // Don't set URL to null when the current one doesn't point to this OH
428                     // Don't interfere with a 3rd party App
429                     continue;
430                 }
431                 if (!profile.settingsJson.contains(testUrl)) {
432                     // Current Action URL is != new URL
433                     logger.debug("{}: Set new url for event type {}: {}", thingName, eventType, newUrl);
434                     request(SHELLY_URL_SETTINGS + "?" + mkEventUrl(eventType) + "=" + urlEncode(newUrl));
435                 }
436             }
437         }
438     }
439
440     private void setEventUrl(String deviceClass, Integer index, boolean enabled, String... eventTypes)
441             throws ShellyApiException {
442         for (String eventType : eventTypes) {
443             if (profile.containsEventUrl(eventType)) {
444                 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
445                         + profile.thingName + "/" + deviceClass + "/" + index + "?type=" + eventType;
446                 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
447                 String test = "\"" + mkEventUrl(eventType) + "\":\"" + callBackUrl + "\"";
448                 if (!enabled && !profile.settingsJson.contains(test)) {
449                     // Don't set URL to null when the current one doesn't point to this OH
450                     // Don't interfere with a 3rd party App
451                     continue;
452                 }
453                 test = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
454                 if (!profile.settingsJson.contains(test)) {
455                     // Current Action URL is != new URL
456                     logger.debug("{}: Set URL for type {} to {}", thingName, eventType, newUrl);
457                     request(SHELLY_URL_SETTINGS + "/" + deviceClass + "/" + index + "?" + mkEventUrl(eventType) + "="
458                             + urlEncode(newUrl));
459                 }
460             }
461         }
462     }
463
464     private static String mkEventUrl(String eventType) {
465         return eventType + SHELLY_EVENTURL_SUFFIX;
466     }
467
468     /**
469      * Submit GET request and return response, check for invalid responses
470      *
471      * @param uri: URI (e.g. "/settings")
472      */
473     public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
474         try {
475             String json = request(uri);
476             return gson.fromJson(json, classOfT);
477         } catch (JsonSyntaxException e) {
478             throw new ShellyApiException("Unable to convert JSON", e);
479         }
480     }
481
482     private String request(String uri) throws ShellyApiException {
483         ShellyApiResult apiResult = new ShellyApiResult();
484         int retries = 3;
485         boolean timeout = false;
486         while (retries > 0) {
487             try {
488                 apiResult = innerRequest(HttpMethod.GET, uri);
489                 if (timeout) {
490                     logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
491                             apiResult.getUrl());
492                     timeoutsRecovered++;
493                 }
494                 return apiResult.response; // successful
495             } catch (ShellyApiException e) {
496                 if ((!e.isTimeout() && !apiResult.isHttpServerError()) || profile.hasBattery || (retries == 0)) {
497                     // Sensor in sleep mode or API exception for non-battery device or retry counter expired
498                     throw e; // non-timeout exception
499                 }
500
501                 timeout = true;
502                 retries--;
503                 timeoutErrors++; // count the retries
504                 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
505             }
506         }
507         throw new ShellyApiException("Inconsistent API result or Timeout"); // successful
508     }
509
510     private ShellyApiResult innerRequest(HttpMethod method, String uri) throws ShellyApiException {
511         Request request = null;
512         String url = "http://" + config.deviceIp + uri;
513         ShellyApiResult apiResult = new ShellyApiResult(method.toString(), url);
514
515         try {
516             request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
517                     TimeUnit.MILLISECONDS);
518
519             if (!config.userId.isEmpty()) {
520                 String value = config.userId + ":" + config.password;
521                 request.header(HTTP_HEADER_AUTH,
522                         HTTP_AUTH_TYPE_BASIC + " " + Base64.getEncoder().encodeToString(value.getBytes()));
523             }
524             request.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON);
525             logger.trace("{}: HTTP {} for {}", thingName, method, url);
526
527             // Do request and get response
528             ContentResponse contentResponse = request.send();
529             apiResult = new ShellyApiResult(contentResponse);
530             String response = contentResponse.getContentAsString().replace("\t", "").replace("\r\n", "").trim();
531             logger.trace("{}: HTTP Response {}: {}", thingName, contentResponse.getStatus(), response);
532
533             // validate response, API errors are reported as Json
534             if (contentResponse.getStatus() != HttpStatus.OK_200) {
535                 throw new ShellyApiException(apiResult);
536             }
537             if (response == null || response.isEmpty() || !response.startsWith("{") && !response.startsWith("[")) {
538                 throw new ShellyApiException("Unexpected response: " + response);
539             }
540         } catch (ExecutionException | InterruptedException | TimeoutException | IllegalArgumentException e) {
541             ShellyApiException ex = new ShellyApiException(apiResult, e);
542             if (!ex.isTimeout()) { // will be handled by the caller
543                 logger.trace("{}: API call returned exception", thingName, ex);
544             }
545             throw ex;
546         }
547         return apiResult;
548     }
549
550     public String getControlUriPrefix(Integer id) {
551         String uri = "";
552         if (profile.isLight || profile.isDimmer) {
553             if (profile.isDuo || profile.isDimmer) {
554                 // Duo + Dimmer
555                 uri = SHELLY_URL_CONTROL_LIGHT;
556             } else {
557                 // Bulb + RGBW2
558                 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
559             }
560         } else {
561             // Roller, Relay
562             uri = SHELLY_URL_CONTROL_RELEAY;
563         }
564         uri = uri + "/" + id;
565         return uri;
566     }
567
568     public int getTimeoutErrors() {
569         return timeoutErrors;
570     }
571
572     public int getTimeoutsRecovered() {
573         return timeoutsRecovered;
574     }
575 }