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