2 * Copyright (c) 2010-2021 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.shelly.internal.api;
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.*;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Base64;
21 import java.util.HashMap;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
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.ShellyOtaCheckResult;
36 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySendKeyList;
37 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySenseKeyCode;
38 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsDevice;
39 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsLight;
40 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsLogin;
41 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsStatus;
42 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsUpdate;
43 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyShortLightStatus;
44 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusLight;
45 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusRelay;
46 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusSensor;
47 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
48 import org.openhab.core.library.unit.ImperialUnits;
49 import org.openhab.core.library.unit.SIUnits;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 import com.google.gson.Gson;
54 import com.google.gson.JsonSyntaxException;
57 * {@link ShellyHttpApi} wraps the Shelly REST API and provides various low level function to access the device api (not
60 * @author Markus Michels - Initial contribution
63 public class ShellyHttpApi {
64 public static final String HTTP_HEADER_AUTH = "Authorization";
65 public static final String HTTP_AUTH_TYPE_BASIC = "Basic";
66 public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
68 private final Logger logger = LoggerFactory.getLogger(ShellyHttpApi.class);
69 private final HttpClient httpClient;
70 private ShellyThingConfiguration config = new ShellyThingConfiguration();
71 private String thingName;
72 private final Gson gson = new Gson();
73 private int timeoutErrors = 0;
74 private int timeoutsRecovered = 0;
76 private ShellyDeviceProfile profile = new ShellyDeviceProfile();
78 public ShellyHttpApi(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
79 this.httpClient = httpClient;
80 this.thingName = thingName;
81 setConfig(thingName, config);
82 profile.initFromThingType(thingName);
85 public void setConfig(String thingName, ShellyThingConfiguration config) {
86 this.thingName = thingName;
90 public ShellySettingsDevice getDevInfo() throws ShellyApiException {
91 return callApi(SHELLY_URL_DEVINFO, ShellySettingsDevice.class);
94 public String setDebug(boolean enabled) throws ShellyApiException {
95 return callApi(SHELLY_URL_SETTINGS + "?debug_enable=" + Boolean.valueOf(enabled), String.class);
98 public String getDebugLog(String id) throws ShellyApiException {
99 return callApi("/debug/" + id, String.class);
103 * Initialize the device profile
105 * @param thingType Type of DEVICE as returned from the thing properties (based on discovery)
106 * @return Initialized ShellyDeviceProfile
107 * @throws ShellyApiException
109 public ShellyDeviceProfile getDeviceProfile(String thingType) throws ShellyApiException {
110 String json = request(SHELLY_URL_SETTINGS);
111 if (json.contains("\"type\":\"SHDM-")) {
112 logger.trace("{}: Detected a Shelly Dimmer: fix Json (replace lights[] tag with dimmers[]", thingName);
113 json = fixDimmerJson(json);
116 // Map settings to device profile for Light and Sense
117 profile.initialize(thingType, json);
119 // 2nd level initialization
120 profile.thingName = profile.hostname;
121 if (profile.isLight && (profile.numMeters == 0)) {
122 logger.debug("{}: Get number of meters from light status", thingName);
123 ShellyStatusLight status = getLightStatus();
124 profile.numMeters = status.meters != null ? status.meters.size() : 0;
126 if (profile.isSense) {
127 profile.irCodes = getIRCodeList();
128 logger.debug("{}: Sense stored key list loaded, {} entries.", thingName, profile.irCodes.size());
134 public boolean isInitialized() {
135 return profile.initialized;
139 * Get generic device settings/status. Json returned from API will be mapped to a Gson object
141 * @return Device settings/status as ShellySettingsStatus object
142 * @throws ShellyApiException
144 public ShellySettingsStatus getStatus() throws ShellyApiException {
147 json = request(SHELLY_URL_STATUS);
148 // Dimmer2 returns invalid json type for loaderror :-(
149 json = getString(json.replace("\"loaderror\":0,", "\"loaderror\":false,"));
150 json = getString(json.replace("\"loaderror\":1,", "\"loaderror\":true,"));
151 ShellySettingsStatus status = fromJson(gson, json, ShellySettingsStatus.class);
154 } catch (JsonSyntaxException e) {
155 throw new ShellyApiException("Unable to parse JSON: " + json, e);
159 public ShellyStatusRelay getRelayStatus(Integer relayIndex) throws ShellyApiException {
160 return callApi(SHELLY_URL_STATUS_RELEAY + "/" + relayIndex.toString(), ShellyStatusRelay.class);
163 public ShellyShortLightStatus setRelayTurn(Integer id, String turnMode) throws ShellyApiException {
164 return callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
165 ShellyShortLightStatus.class);
168 public void setBrightness(Integer id, Integer brightness, boolean autoOn) throws ShellyApiException {
169 String turn = autoOn ? SHELLY_LIGHT_TURN + "=" + SHELLY_API_ON + "&" : "";
170 request(getControlUriPrefix(id) + "?" + turn + "brightness=" + brightness.toString());
173 public ShellyControlRoller getRollerStatus(Integer rollerIndex) throws ShellyApiException {
174 String uri = SHELLY_URL_CONTROL_ROLLER + "/" + rollerIndex.toString() + "/pos";
175 return callApi(uri, ShellyControlRoller.class);
178 public void setRollerTurn(Integer relayIndex, String turnMode) throws ShellyApiException {
179 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=" + turnMode);
182 public void setRollerPos(Integer relayIndex, Integer position) throws ShellyApiException {
183 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=to_pos&roller_pos="
184 + position.toString());
187 public void setRollerTimer(Integer relayIndex, Integer timer) throws ShellyApiException {
188 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?timer=" + timer.toString());
191 public ShellyShortLightStatus getLightStatus(Integer index) throws ShellyApiException {
192 return callApi(getControlUriPrefix(index), ShellyShortLightStatus.class);
195 public ShellyStatusSensor getSensorStatus() throws ShellyApiException {
196 ShellyStatusSensor status = callApi(SHELLY_URL_STATUS, ShellyStatusSensor.class);
197 if (profile.isSense) {
198 // complete reported data, map C to F or vice versa: C=(F - 32) * 0.5556;
199 status.tmp.tC = status.tmp.units.equals(SHELLY_TEMP_CELSIUS) ? status.tmp.value
200 : ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(getDouble(status.tmp.value))
202 double f = SIUnits.CELSIUS.getConverterTo(ImperialUnits.FAHRENHEIT).convert(getDouble(status.tmp.value))
204 status.tmp.tF = status.tmp.units.equals(SHELLY_TEMP_FAHRENHEIT) ? status.tmp.value : f;
206 if ((status.charger == null) && (profile.settings.externalPower != null)) {
207 // SHelly H&T uses external_power, Sense uses charger
208 status.charger = profile.settings.externalPower != 0;
213 public void setTimer(int index, String timerName, int value) throws ShellyApiException {
214 String type = SHELLY_CLASS_RELAY;
215 if (profile.isRoller) {
216 type = SHELLY_CLASS_ROLLER;
217 } else if (profile.isLight) {
218 type = SHELLY_CLASS_LIGHT;
220 String uri = SHELLY_URL_SETTINGS + "/" + type + "/" + index + "?" + timerName + "=" + value;
224 public void setSleepTime(int value) throws ShellyApiException {
225 request(SHELLY_URL_SETTINGS + "?sleep_time=" + value);
228 public void setLedStatus(String ledName, Boolean value) throws ShellyApiException {
229 request(SHELLY_URL_SETTINGS + "?" + ledName + "=" + (value ? SHELLY_API_TRUE : SHELLY_API_FALSE));
232 public ShellySettingsLight getLightSettings() throws ShellyApiException {
233 return callApi(SHELLY_URL_SETTINGS_LIGHT, ShellySettingsLight.class);
236 public ShellyStatusLight getLightStatus() throws ShellyApiException {
237 return callApi(SHELLY_URL_STATUS, ShellyStatusLight.class);
240 public void setLightSetting(String parm, String value) throws ShellyApiException {
241 request(SHELLY_URL_SETTINGS + "?" + parm + "=" + value);
244 public ShellySettingsLogin getLoginSettings() throws ShellyApiException {
245 return callApi(SHELLY_URL_SETTINGS + "/login", ShellySettingsLogin.class);
248 public ShellySettingsLogin setLoginCredentials(String user, String password) throws ShellyApiException {
249 return callApi(SHELLY_URL_SETTINGS + "/login?enabled=yes&username=" + urlEncode(user) + "&password="
250 + urlEncode(password), ShellySettingsLogin.class);
253 public String getCoIoTDescription() throws ShellyApiException {
255 return callApi("/cit/d", String.class);
256 } catch (ShellyApiException e) {
257 if (e.getApiResult().isNotFound()) {
258 return ""; // only supported by FW 1.10+
264 public ShellySettingsLogin setCoIoTPeer(String peer) throws ShellyApiException {
265 return callApi(SHELLY_URL_SETTINGS + "?coiot_enable=true&coiot_peer=" + peer, ShellySettingsLogin.class);
268 public String deviceReboot() throws ShellyApiException {
269 return callApi(SHELLY_URL_RESTART, String.class);
272 public String factoryReset() throws ShellyApiException {
273 return callApi(SHELLY_URL_SETTINGS + "?reset=true", String.class);
276 public ShellyOtaCheckResult checkForUpdate() throws ShellyApiException {
277 return callApi("/ota/check", ShellyOtaCheckResult.class); // nw FW 1.10+: trigger update check
280 public String setWiFiRecovery(boolean enable) throws ShellyApiException {
281 return callApi(SHELLY_URL_SETTINGS + "?wifirecovery_reboot_enabled=" + (enable ? "true" : "false"),
282 String.class); // FW 1.10+: Enable auto-restart on WiFi problems
285 public String setApRoaming(boolean enable) throws ShellyApiException { // FW 1.10+: Enable AP Roadming
286 return callApi(SHELLY_URL_SETTINGS + "?ap_roaming_enabled=" + (enable ? "true" : "false"), String.class);
289 public String resetStaCache() throws ShellyApiException { // FW 1.10+: Reset cached STA/AP list and to a rescan
290 return callApi("/sta_cache_reset", String.class);
293 public ShellySettingsUpdate firmwareUpdate(String uri) throws ShellyApiException {
294 return callApi("/ota?" + uri, ShellySettingsUpdate.class);
297 public String setCloud(boolean enabled) throws ShellyApiException {
298 return callApi("/settings/cloud/?enabled=" + (enabled ? "1" : "0"), String.class);
302 * Change between White and Color Mode
305 * @throws ShellyApiException
307 public void setLightMode(String mode) throws ShellyApiException {
308 if (!mode.isEmpty() && !profile.mode.equals(mode)) {
309 setLightSetting(SHELLY_API_MODE, mode);
311 profile.inColor = profile.isLight && profile.mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
316 * Set a single light parameter
318 * @param lightIndex Index of the light, usually 0 for Bulb and 0..3 for RGBW2.
319 * @param parm Name of the parameter (see API spec)
320 * @param value The value
321 * @throws ShellyApiException
323 public void setLightParm(Integer lightIndex, String parm, String value) throws ShellyApiException {
324 // Bulb, RGW2: /<color mode>/<light id>?parm?value
325 // Dimmer: /light/<light id>?parm=value
326 request(getControlUriPrefix(lightIndex) + "?" + parm + "=" + value);
329 public void setLightParms(Integer lightIndex, Map<String, String> parameters) throws ShellyApiException {
330 String url = getControlUriPrefix(lightIndex) + "?";
332 for (String key : parameters.keySet()) {
336 url = url + key + "=" + parameters.get(key);
343 * Retrieve the IR Code list from the Shelly Sense device. The list could be customized by the user. It defines the
344 * symbolic key code, which gets
345 * map into a PRONTO code
347 * @return Map of key codes
348 * @throws ShellyApiException
350 public Map<String, String> getIRCodeList() throws ShellyApiException {
351 String result = request(SHELLY_URL_LIST_IR);
352 // take pragmatic approach to make the returned JSon into named arrays for Gson parsing
353 String keyList = substringAfter(result, "[");
354 keyList = substringBeforeLast(keyList, "]");
355 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("\",\""), "\", \"name\": \"");
356 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("["), "{ \"id\":");
357 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("]"), "} ");
358 String json = "{\"key_codes\" : [" + keyList + "] }";
359 ShellySendKeyList codes = fromJson(gson, json, ShellySendKeyList.class);
360 Map<String, String> list = new HashMap<>();
361 for (ShellySenseKeyCode key : codes.keyCodes) {
363 list.put(key.id, key.name);
370 * Sends a IR key code to the Shelly Sense.
372 * @param keyCode A keyCoud could be a symbolic name (as defined in the key map on the device) or a PRONTO Code in
373 * plain or hex64 format
375 * @throws ShellyApiException
376 * @throws IllegalArgumentException
378 public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
380 if (profile.irCodes.containsKey(keyCode)) {
381 type = SHELLY_IR_CODET_STORED;
382 } else if ((keyCode.length() > 4) && keyCode.contains(" ")) {
383 type = SHELLY_IR_CODET_PRONTO;
385 type = SHELLY_IR_CODET_PRONTO_HEX;
387 String url = SHELLY_URL_SEND_IR + "?type=" + type;
388 if (type.equals(SHELLY_IR_CODET_STORED)) {
389 url = url + "&" + "id=" + keyCode;
390 } else if (type.equals(SHELLY_IR_CODET_PRONTO)) {
391 String code = Base64.getEncoder().encodeToString(keyCode.getBytes(StandardCharsets.UTF_8));
392 url = url + "&" + SHELLY_IR_CODET_PRONTO + "=" + code;
393 } else if (type.equals(SHELLY_IR_CODET_PRONTO_HEX)) {
394 url = url + "&" + SHELLY_IR_CODET_PRONTO_HEX + "=" + keyCode;
399 public void setSenseSetting(String setting, String value) throws ShellyApiException {
400 request(SHELLY_URL_SETTINGS + "?" + setting + "=" + value);
404 * Set event callback URLs. Depending on the device different event types are supported. In fact all of them will be
405 * redirected to the binding's servlet and act as a trigger to schedule a status update
407 * @param ShellyApiException
408 * @throws ShellyApiException
410 public void setActionURLs() throws ShellyApiException {
413 setSensorEventUrls();
416 private void setRelayEvents() throws ShellyApiException {
417 if (profile.settings.relays != null) {
418 int num = profile.isRoller ? profile.numRollers : profile.numRelays;
419 for (int i = 0; i < num; i++) {
425 private void setDimmerEvents() throws ShellyApiException {
426 if (profile.settings.dimmers != null) {
427 for (int i = 0; i < profile.settings.dimmers.size(); i++) {
430 } else if (profile.isLight) {
436 * Set sensor Action URLs
438 * @throws ShellyApiException
440 private void setSensorEventUrls() throws ShellyApiException, ShellyApiException {
441 if (profile.isSensor) {
442 logger.debug("{}: Set Sensor Reporting URL", thingName);
443 setEventUrl(config.eventsSensorReport, SHELLY_EVENT_SENSORREPORT, SHELLY_EVENT_DARK, SHELLY_EVENT_TWILIGHT,
444 SHELLY_EVENT_FLOOD_DETECTED, SHELLY_EVENT_FLOOD_GONE, SHELLY_EVENT_OPEN, SHELLY_EVENT_CLOSE,
445 SHELLY_EVENT_VIBRATION, SHELLY_EVENT_ALARM_MILD, SHELLY_EVENT_ALARM_HEAVY, SHELLY_EVENT_ALARM_OFF,
446 SHELLY_EVENT_TEMP_OVER, SHELLY_EVENT_TEMP_UNDER);
451 * Set/delete Relay/Roller/Dimmer Action URLs
453 * @param index Device Index (0-based)
454 * @throws ShellyApiException
456 private void setEventUrls(Integer index) throws ShellyApiException {
457 if (profile.isRoller) {
458 setEventUrl(EVENT_TYPE_ROLLER, 0, config.eventsRoller, SHELLY_EVENT_ROLLER_OPEN, SHELLY_EVENT_ROLLER_CLOSE,
459 SHELLY_EVENT_ROLLER_STOP);
460 } else if (profile.isDimmer) {
462 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsButton, SHELLY_EVENT_BTN1_ON, SHELLY_EVENT_BTN1_OFF,
463 SHELLY_EVENT_BTN2_ON, SHELLY_EVENT_BTN2_OFF);
464 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH1, SHELLY_EVENT_LONGPUSH1,
465 SHELLY_EVENT_SHORTPUSH2, SHELLY_EVENT_LONGPUSH2);
468 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
469 } else if (profile.hasRelays) {
470 // Standard relays: btn_xxx, out_xxx, short/longpush URLs
471 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsButton, SHELLY_EVENT_BTN_ON, SHELLY_EVENT_BTN_OFF);
472 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH, SHELLY_EVENT_LONGPUSH);
473 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
474 } else if (profile.isLight) {
476 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
480 private void setEventUrl(boolean enabled, String... eventTypes) throws ShellyApiException {
481 if (config.localIp.isEmpty()) {
482 throw new ShellyApiException(thingName + ": Local IP address was not detected, can't build Callback URL");
484 for (String eventType : eventTypes) {
485 if (profile.containsEventUrl(eventType)) {
486 // H&T adds the type=xx to report_url itself, so we need to ommit here
487 String eclass = profile.isSensor ? EVENT_TYPE_SENSORDATA : eventType;
488 String urlParm = eventType.contains("temp") || profile.isHT ? "" : "?type=" + eventType;
489 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
490 + profile.thingName + "/" + eclass + urlParm;
491 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
492 String testUrl = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
493 if (!enabled && !profile.settingsJson.contains(testUrl)) {
494 // Don't set URL to null when the current one doesn't point to this OH
495 // Don't interfere with a 3rd party App
498 if (!profile.settingsJson.contains(testUrl)) {
499 // Current Action URL is != new URL
500 logger.debug("{}: Set new url for event type {}: {}", thingName, eventType, newUrl);
501 request(SHELLY_URL_SETTINGS + "?" + mkEventUrl(eventType) + "=" + urlEncode(newUrl));
507 private void setEventUrl(String deviceClass, Integer index, boolean enabled, String... eventTypes)
508 throws ShellyApiException {
509 for (String eventType : eventTypes) {
510 if (profile.containsEventUrl(eventType)) {
511 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
512 + profile.thingName + "/" + deviceClass + "/" + index + "?type=" + eventType;
513 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
514 String test = "\"" + mkEventUrl(eventType) + "\":\"" + callBackUrl + "\"";
515 if (!enabled && !profile.settingsJson.contains(test)) {
516 // Don't set URL to null when the current one doesn't point to this OH
517 // Don't interfere with a 3rd party App
520 test = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
521 if (!profile.settingsJson.contains(test)) {
522 // Current Action URL is != new URL
523 logger.debug("{}: Set URL for type {} to {}", thingName, eventType, newUrl);
524 request(SHELLY_URL_SETTINGS + "/" + deviceClass + "/" + index + "?" + mkEventUrl(eventType) + "="
525 + urlEncode(newUrl));
531 private static String mkEventUrl(String eventType) {
532 return eventType + SHELLY_EVENTURL_SUFFIX;
536 * Submit GET request and return response, check for invalid responses
538 * @param uri: URI (e.g. "/settings")
540 public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
541 String json = request(uri);
542 return fromJson(gson, json, classOfT);
545 private String request(String uri) throws ShellyApiException {
546 ShellyApiResult apiResult = new ShellyApiResult();
548 boolean timeout = false;
549 while (retries > 0) {
551 apiResult = innerRequest(HttpMethod.GET, uri);
553 logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
557 return apiResult.response; // successful
558 } catch (ShellyApiException e) {
559 if ((!e.isTimeout() && !apiResult.isHttpServerError()) || profile.hasBattery || (retries == 0)) {
560 // Sensor in sleep mode or API exception for non-battery device or retry counter expired
561 throw e; // non-timeout exception
566 timeoutErrors++; // count the retries
567 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
570 throw new ShellyApiException("API Timeout or inconsistent result"); // successful
573 private ShellyApiResult innerRequest(HttpMethod method, String uri) throws ShellyApiException {
574 Request request = null;
575 String url = "http://" + config.deviceIp + uri;
576 ShellyApiResult apiResult = new ShellyApiResult(method.toString(), url);
579 request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
580 TimeUnit.MILLISECONDS);
582 if (!config.userId.isEmpty()) {
583 String value = config.userId + ":" + config.password;
584 request.header(HTTP_HEADER_AUTH,
585 HTTP_AUTH_TYPE_BASIC + " " + Base64.getEncoder().encodeToString(value.getBytes()));
587 request.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON);
588 logger.trace("{}: HTTP {} for {}", thingName, method, url);
590 // Do request and get response
591 ContentResponse contentResponse = request.send();
592 apiResult = new ShellyApiResult(contentResponse);
593 String response = contentResponse.getContentAsString().replace("\t", "").replace("\r\n", "").trim();
594 logger.trace("{}: HTTP Response {}: {}", thingName, contentResponse.getStatus(), response);
596 // validate response, API errors are reported as Json
597 if (contentResponse.getStatus() != HttpStatus.OK_200) {
598 throw new ShellyApiException(apiResult);
600 if (response.isEmpty() || !response.startsWith("{") && !response.startsWith("[") && !url.contains("/debug/")
601 && !url.contains("/sta_cache_reset")) {
602 throw new ShellyApiException("Unexpected response: " + response);
604 } catch (ExecutionException | InterruptedException | TimeoutException | IllegalArgumentException e) {
605 ShellyApiException ex = new ShellyApiException(apiResult, e);
606 if (!ex.isTimeout()) { // will be handled by the caller
607 logger.trace("{}: API call returned exception", thingName, ex);
614 public String getControlUriPrefix(Integer id) {
616 if (profile.isLight || profile.isDimmer) {
617 if (profile.isDuo || profile.isDimmer) {
619 uri = SHELLY_URL_CONTROL_LIGHT;
622 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
626 uri = SHELLY_URL_CONTROL_RELEAY;
628 uri = uri + "/" + id;
632 public int getTimeoutErrors() {
633 return timeoutErrors;
636 public int getTimeoutsRecovered() {
637 return timeoutsRecovered;