2 * Copyright (c) 2010-2022 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 = (double) SIUnits.CELSIUS.getConverterTo(ImperialUnits.FAHRENHEIT)
203 .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 setTemperature(int valveId, int value) throws ShellyApiException {
229 request("/thermostat/" + valveId + "?target_t_enabled=1&target_t=" + value);
232 public void setValveMode(int valveId, boolean auto) throws ShellyApiException {
233 String uri = "/settings/thermostat/" + valveId + "?target_t_enabled=" + (auto ? "1" : "0");
235 uri = uri + "&target_t=" + getDouble(profile.settings.thermostats.get(0).targetTemp.value);
237 request(uri); // percentage to open the valve
240 public void setProfile(int valveId, int value) throws ShellyApiException {
241 String uri = "/settings/thermostat/" + valveId + "?";
242 request(uri + (value == 0 ? "schedule=0" : "schedule=1&schedule_profile=" + value));
245 public void setValvePosition(int valveId, double value) throws ShellyApiException {
246 request("/thermostat/" + valveId + "?pos=" + value); // percentage to open the valve
249 public void setBoostTime(int valveId, int value) throws ShellyApiException {
250 request("/settings/thermostat/" + valveId + "?boost_minutes=" + value);
253 public void startBoost(int valveId, int value) throws ShellyApiException {
254 int minutes = value != -1 ? value : getInteger(profile.settings.thermostats.get(0).boostMinutes);
255 request("/thermostat/" + valveId + "?boost_minutes=" + minutes);
258 public void setLedStatus(String ledName, Boolean value) throws ShellyApiException {
259 request(SHELLY_URL_SETTINGS + "?" + ledName + "=" + (value ? SHELLY_API_TRUE : SHELLY_API_FALSE));
262 public ShellySettingsLight getLightSettings() throws ShellyApiException {
263 return callApi(SHELLY_URL_SETTINGS_LIGHT, ShellySettingsLight.class);
266 public ShellyStatusLight getLightStatus() throws ShellyApiException {
267 return callApi(SHELLY_URL_STATUS, ShellyStatusLight.class);
270 public void setLightSetting(String parm, String value) throws ShellyApiException {
271 request(SHELLY_URL_SETTINGS + "?" + parm + "=" + value);
274 public ShellySettingsLogin getLoginSettings() throws ShellyApiException {
275 return callApi(SHELLY_URL_SETTINGS + "/login", ShellySettingsLogin.class);
278 public ShellySettingsLogin setLoginCredentials(String user, String password) throws ShellyApiException {
279 return callApi(SHELLY_URL_SETTINGS + "/login?enabled=yes&username=" + urlEncode(user) + "&password="
280 + urlEncode(password), ShellySettingsLogin.class);
283 public String getCoIoTDescription() throws ShellyApiException {
285 return callApi("/cit/d", String.class);
286 } catch (ShellyApiException e) {
287 if (e.getApiResult().isNotFound()) {
288 return ""; // only supported by FW 1.10+
294 public ShellySettingsLogin setCoIoTPeer(String peer) throws ShellyApiException {
295 return callApi(SHELLY_URL_SETTINGS + "?coiot_enable=true&coiot_peer=" + peer, ShellySettingsLogin.class);
298 public String deviceReboot() throws ShellyApiException {
299 return callApi(SHELLY_URL_RESTART, String.class);
302 public String factoryReset() throws ShellyApiException {
303 return callApi(SHELLY_URL_SETTINGS + "?reset=true", String.class);
306 public ShellyOtaCheckResult checkForUpdate() throws ShellyApiException {
307 return callApi("/ota/check", ShellyOtaCheckResult.class); // nw FW 1.10+: trigger update check
310 public String setWiFiRecovery(boolean enable) throws ShellyApiException {
311 return callApi(SHELLY_URL_SETTINGS + "?wifirecovery_reboot_enabled=" + (enable ? "true" : "false"),
312 String.class); // FW 1.10+: Enable auto-restart on WiFi problems
315 public String setApRoaming(boolean enable) throws ShellyApiException { // FW 1.10+: Enable AP Roadming
316 return callApi(SHELLY_URL_SETTINGS + "?ap_roaming_enabled=" + (enable ? "true" : "false"), String.class);
319 public String resetStaCache() throws ShellyApiException { // FW 1.10+: Reset cached STA/AP list and to a rescan
320 return callApi("/sta_cache_reset", String.class);
323 public ShellySettingsUpdate firmwareUpdate(String uri) throws ShellyApiException {
324 return callApi("/ota?" + uri, ShellySettingsUpdate.class);
327 public String setCloud(boolean enabled) throws ShellyApiException {
328 return callApi("/settings/cloud/?enabled=" + (enabled ? "1" : "0"), String.class);
332 * Change between White and Color Mode
335 * @throws ShellyApiException
337 public void setLightMode(String mode) throws ShellyApiException {
338 if (!mode.isEmpty() && !profile.mode.equals(mode)) {
339 setLightSetting(SHELLY_API_MODE, mode);
341 profile.inColor = profile.isLight && profile.mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
346 * Set a single light parameter
348 * @param lightIndex Index of the light, usually 0 for Bulb and 0..3 for RGBW2.
349 * @param parm Name of the parameter (see API spec)
350 * @param value The value
351 * @throws ShellyApiException
353 public void setLightParm(Integer lightIndex, String parm, String value) throws ShellyApiException {
354 // Bulb, RGW2: /<color mode>/<light id>?parm?value
355 // Dimmer: /light/<light id>?parm=value
356 request(getControlUriPrefix(lightIndex) + "?" + parm + "=" + value);
359 public void setLightParms(Integer lightIndex, Map<String, String> parameters) throws ShellyApiException {
360 String url = getControlUriPrefix(lightIndex) + "?";
362 for (String key : parameters.keySet()) {
366 url = url + key + "=" + parameters.get(key);
373 * Retrieve the IR Code list from the Shelly Sense device. The list could be customized by the user. It defines the
374 * symbolic key code, which gets
375 * map into a PRONTO code
377 * @return Map of key codes
378 * @throws ShellyApiException
380 public Map<String, String> getIRCodeList() throws ShellyApiException {
381 String result = request(SHELLY_URL_LIST_IR);
382 // take pragmatic approach to make the returned JSon into named arrays for Gson parsing
383 String keyList = substringAfter(result, "[");
384 keyList = substringBeforeLast(keyList, "]");
385 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("\",\""), "\", \"name\": \"");
386 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("["), "{ \"id\":");
387 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("]"), "} ");
388 String json = "{\"key_codes\" : [" + keyList + "] }";
389 ShellySendKeyList codes = fromJson(gson, json, ShellySendKeyList.class);
390 Map<String, String> list = new HashMap<>();
391 for (ShellySenseKeyCode key : codes.keyCodes) {
393 list.put(key.id, key.name);
400 * Sends a IR key code to the Shelly Sense.
402 * @param keyCode A keyCoud could be a symbolic name (as defined in the key map on the device) or a PRONTO Code in
403 * plain or hex64 format
405 * @throws ShellyApiException
406 * @throws IllegalArgumentException
408 public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
410 if (profile.irCodes.containsKey(keyCode)) {
411 type = SHELLY_IR_CODET_STORED;
412 } else if ((keyCode.length() > 4) && keyCode.contains(" ")) {
413 type = SHELLY_IR_CODET_PRONTO;
415 type = SHELLY_IR_CODET_PRONTO_HEX;
417 String url = SHELLY_URL_SEND_IR + "?type=" + type;
418 if (type.equals(SHELLY_IR_CODET_STORED)) {
419 url = url + "&" + "id=" + keyCode;
420 } else if (type.equals(SHELLY_IR_CODET_PRONTO)) {
421 String code = Base64.getEncoder().encodeToString(keyCode.getBytes(StandardCharsets.UTF_8));
422 url = url + "&" + SHELLY_IR_CODET_PRONTO + "=" + code;
423 } else if (type.equals(SHELLY_IR_CODET_PRONTO_HEX)) {
424 url = url + "&" + SHELLY_IR_CODET_PRONTO_HEX + "=" + keyCode;
429 public void setSenseSetting(String setting, String value) throws ShellyApiException {
430 request(SHELLY_URL_SETTINGS + "?" + setting + "=" + value);
434 * Set event callback URLs. Depending on the device different event types are supported. In fact all of them will be
435 * redirected to the binding's servlet and act as a trigger to schedule a status update
437 * @param ShellyApiException
438 * @throws ShellyApiException
440 public void setActionURLs() throws ShellyApiException {
443 setSensorEventUrls();
446 private void setRelayEvents() throws ShellyApiException {
447 if (profile.settings.relays != null) {
448 int num = profile.isRoller ? profile.numRollers : profile.numRelays;
449 for (int i = 0; i < num; i++) {
455 private void setDimmerEvents() throws ShellyApiException {
456 if (profile.settings.dimmers != null) {
457 for (int i = 0; i < profile.settings.dimmers.size(); i++) {
460 } else if (profile.isLight) {
466 * Set sensor Action URLs
468 * @throws ShellyApiException
470 private void setSensorEventUrls() throws ShellyApiException, ShellyApiException {
471 if (profile.isSensor) {
472 logger.debug("{}: Set Sensor Reporting URL", thingName);
473 setEventUrl(config.eventsSensorReport, SHELLY_EVENT_SENSORREPORT, SHELLY_EVENT_DARK, SHELLY_EVENT_TWILIGHT,
474 SHELLY_EVENT_FLOOD_DETECTED, SHELLY_EVENT_FLOOD_GONE, SHELLY_EVENT_OPEN, SHELLY_EVENT_CLOSE,
475 SHELLY_EVENT_VIBRATION, SHELLY_EVENT_ALARM_MILD, SHELLY_EVENT_ALARM_HEAVY, SHELLY_EVENT_ALARM_OFF,
476 SHELLY_EVENT_TEMP_OVER, SHELLY_EVENT_TEMP_UNDER);
481 * Set/delete Relay/Roller/Dimmer Action URLs
483 * @param index Device Index (0-based)
484 * @throws ShellyApiException
486 private void setEventUrls(Integer index) throws ShellyApiException {
487 if (profile.isRoller) {
488 setEventUrl(EVENT_TYPE_ROLLER, 0, config.eventsRoller, SHELLY_EVENT_ROLLER_OPEN, SHELLY_EVENT_ROLLER_CLOSE,
489 SHELLY_EVENT_ROLLER_STOP);
490 } else if (profile.isDimmer) {
492 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsButton, SHELLY_EVENT_BTN1_ON, SHELLY_EVENT_BTN1_OFF,
493 SHELLY_EVENT_BTN2_ON, SHELLY_EVENT_BTN2_OFF);
494 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH1, SHELLY_EVENT_LONGPUSH1,
495 SHELLY_EVENT_SHORTPUSH2, SHELLY_EVENT_LONGPUSH2);
498 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
499 } else if (profile.hasRelays) {
500 // Standard relays: btn_xxx, out_xxx, short/longpush URLs
501 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsButton, SHELLY_EVENT_BTN_ON, SHELLY_EVENT_BTN_OFF);
502 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH, SHELLY_EVENT_LONGPUSH);
503 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
504 } else if (profile.isLight) {
506 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
510 private void setEventUrl(boolean enabled, String... eventTypes) throws ShellyApiException {
511 if (config.localIp.isEmpty()) {
512 throw new ShellyApiException(thingName + ": Local IP address was not detected, can't build Callback URL");
514 for (String eventType : eventTypes) {
515 if (profile.containsEventUrl(eventType)) {
516 // H&T adds the type=xx to report_url itself, so we need to ommit here
517 String eclass = profile.isSensor ? EVENT_TYPE_SENSORDATA : eventType;
518 String urlParm = eventType.contains("temp") || profile.isHT ? "" : "?type=" + eventType;
519 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
520 + profile.thingName + "/" + eclass + urlParm;
521 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
522 String testUrl = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
523 if (!enabled && !profile.settingsJson.contains(testUrl)) {
524 // Don't set URL to null when the current one doesn't point to this OH
525 // Don't interfere with a 3rd party App
528 if (!profile.settingsJson.contains(testUrl)) {
529 // Current Action URL is != new URL
530 logger.debug("{}: Set new url for event type {}: {}", thingName, eventType, newUrl);
531 request(SHELLY_URL_SETTINGS + "?" + mkEventUrl(eventType) + "=" + urlEncode(newUrl));
537 private void setEventUrl(String deviceClass, Integer index, boolean enabled, String... eventTypes)
538 throws ShellyApiException {
539 for (String eventType : eventTypes) {
540 if (profile.containsEventUrl(eventType)) {
541 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
542 + profile.thingName + "/" + deviceClass + "/" + index + "?type=" + eventType;
543 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
544 String test = "\"" + mkEventUrl(eventType) + "\":\"" + callBackUrl + "\"";
545 if (!enabled && !profile.settingsJson.contains(test)) {
546 // Don't set URL to null when the current one doesn't point to this OH
547 // Don't interfere with a 3rd party App
550 test = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
551 if (!profile.settingsJson.contains(test)) {
552 // Current Action URL is != new URL
553 logger.debug("{}: Set URL for type {} to {}", thingName, eventType, newUrl);
554 request(SHELLY_URL_SETTINGS + "/" + deviceClass + "/" + index + "?" + mkEventUrl(eventType) + "="
555 + urlEncode(newUrl));
561 private static String mkEventUrl(String eventType) {
562 return eventType + SHELLY_EVENTURL_SUFFIX;
566 * Submit GET request and return response, check for invalid responses
568 * @param uri: URI (e.g. "/settings")
570 public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
571 String json = request(uri);
572 return fromJson(gson, json, classOfT);
575 private String request(String uri) throws ShellyApiException {
576 ShellyApiResult apiResult = new ShellyApiResult();
578 boolean timeout = false;
579 while (retries > 0) {
581 apiResult = innerRequest(HttpMethod.GET, uri);
583 logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
587 return apiResult.response; // successful
588 } catch (ShellyApiException e) {
589 if ((!e.isTimeout() && !apiResult.isHttpServerError()) || profile.hasBattery || (retries == 0)) {
590 // Sensor in sleep mode or API exception for non-battery device or retry counter expired
591 throw e; // non-timeout exception
596 timeoutErrors++; // count the retries
597 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
600 throw new ShellyApiException("API Timeout or inconsistent result"); // successful
603 private ShellyApiResult innerRequest(HttpMethod method, String uri) throws ShellyApiException {
604 Request request = null;
605 String url = "http://" + config.deviceIp + uri;
606 ShellyApiResult apiResult = new ShellyApiResult(method.toString(), url);
609 request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
610 TimeUnit.MILLISECONDS);
612 if (!config.userId.isEmpty()) {
613 String value = config.userId + ":" + config.password;
614 request.header(HTTP_HEADER_AUTH,
615 HTTP_AUTH_TYPE_BASIC + " " + Base64.getEncoder().encodeToString(value.getBytes()));
617 request.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON);
618 logger.trace("{}: HTTP {} for {}", thingName, method, url);
620 // Do request and get response
621 ContentResponse contentResponse = request.send();
622 apiResult = new ShellyApiResult(contentResponse);
623 String response = contentResponse.getContentAsString().replace("\t", "").replace("\r\n", "").trim();
624 logger.trace("{}: HTTP Response {}: {}", thingName, contentResponse.getStatus(), response);
626 // validate response, API errors are reported as Json
627 if (contentResponse.getStatus() != HttpStatus.OK_200) {
628 throw new ShellyApiException(apiResult);
630 if (response.isEmpty() || !response.startsWith("{") && !response.startsWith("[") && !url.contains("/debug/")
631 && !url.contains("/sta_cache_reset")) {
632 throw new ShellyApiException("Unexpected response: " + response);
634 } catch (ExecutionException | InterruptedException | TimeoutException | IllegalArgumentException e) {
635 ShellyApiException ex = new ShellyApiException(apiResult, e);
636 if (!ex.isTimeout()) { // will be handled by the caller
637 logger.trace("{}: API call returned exception", thingName, ex);
644 public String getControlUriPrefix(Integer id) {
646 if (profile.isLight || profile.isDimmer) {
647 if (profile.isDuo || profile.isDimmer) {
649 uri = SHELLY_URL_CONTROL_LIGHT;
652 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
656 uri = SHELLY_URL_CONTROL_RELEAY;
658 uri = uri + "/" + id;
662 public int getTimeoutErrors() {
663 return timeoutErrors;
666 public int getTimeoutsRecovered() {
667 return timeoutsRecovered;