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.api1;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
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.ShellyApiException;
35 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
36 import org.openhab.binding.shelly.internal.api.ShellyApiResult;
37 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
38 import org.openhab.binding.shelly.internal.api.ShellyHttpClient;
39 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyOtaCheckResult;
40 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyRollerStatus;
41 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySendKeyList;
42 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySenseKeyCode;
43 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDevice;
44 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsLight;
45 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsLogin;
46 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
47 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsUpdate;
48 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortLightStatus;
49 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusLight;
50 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusRelay;
51 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusSensor;
52 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
53 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
54 import org.openhab.core.library.unit.ImperialUnits;
55 import org.openhab.core.library.unit.SIUnits;
56 import org.slf4j.Logger;
57 import org.slf4j.LoggerFactory;
59 import com.google.gson.JsonSyntaxException;
62 * {@link Shelly1HttpApi} wraps the Shelly REST API and provides various low level function to access the device api
66 * @author Markus Michels - Initial contribution
69 public class Shelly1HttpApi extends ShellyHttpClient implements ShellyApiInterface {
70 private final Logger logger = LoggerFactory.getLogger(Shelly1HttpApi.class);
71 private final ShellyDeviceProfile profile;
73 public Shelly1HttpApi(String thingName, ShellyThingInterface thing) {
74 super(thingName, thing);
75 profile = thing.getProfile();
79 * Simple initialization - called by discovery handler
81 * @param thingName Symbolic thing name
82 * @param config Thing Configuration
83 * @param httpClient HTTP Client to be passed to ShellyHttpClient
85 public Shelly1HttpApi(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
86 super(thingName, config, httpClient);
87 this.profile = new ShellyDeviceProfile();
91 public ShellySettingsDevice getDeviceInfo() throws ShellyApiException {
92 return callApi(SHELLY_URL_DEVINFO, ShellySettingsDevice.class);
96 public String setDebug(boolean enabled) throws ShellyApiException {
97 return callApi(SHELLY_URL_SETTINGS + "?debug_enable=" + Boolean.valueOf(enabled), String.class);
101 public String getDebugLog(String id) throws ShellyApiException {
102 return callApi("/debug/" + id, String.class);
106 * Initialize the device profile
108 * @param thingType Type of DEVICE as returned from the thing properties (based on discovery)
109 * @return Initialized ShellyDeviceProfile
110 * @throws ShellyApiException
113 public ShellyDeviceProfile getDeviceProfile(String thingType) throws ShellyApiException {
114 String json = httpRequest(SHELLY_URL_SETTINGS);
115 if (json.contains("\"type\":\"SHDM-")) {
116 logger.trace("{}: Detected a Shelly Dimmer: fix Json (replace lights[] tag with dimmers[]", thingName);
117 json = fixDimmerJson(json);
120 // Map settings to device profile for Light and Sense
121 profile.initialize(thingType, json);
123 // 2nd level initialization
124 profile.thingName = profile.hostname;
125 if (profile.isLight && (profile.numMeters == 0)) {
126 logger.debug("{}: Get number of meters from light status", thingName);
127 ShellyStatusLight status = getLightStatus();
128 profile.numMeters = status.meters != null ? status.meters.size() : 0;
130 if (profile.isSense) {
131 profile.irCodes = getIRCodeList();
132 logger.debug("{}: Sense stored key list loaded, {} entries.", thingName, profile.irCodes.size());
139 public boolean isInitialized() {
140 return profile.initialized;
144 * Get generic device settings/status. Json returned from API will be mapped to a Gson object
146 * @return Device settings/status as ShellySettingsStatus object
147 * @throws ShellyApiException
150 public ShellySettingsStatus getStatus() throws ShellyApiException {
153 json = httpRequest(SHELLY_URL_STATUS);
155 // Dimmer2 returns invalid json type for loaderror :-(
156 json = json.replace("\"loaderror\":0,", "\"loaderror\":false,")
157 .replace("\"loaderror\":1,", "\"loaderror\":true,")
158 .replace("\"tmp\":{\"value\": \"null\",", "\"tmp\":{\"value\": null,");
159 ShellySettingsStatus status = fromJson(gson, json, ShellySettingsStatus.class);
162 } catch (JsonSyntaxException e) {
163 throw new ShellyApiException("Unable to parse JSON: " + json, e);
168 public ShellyStatusRelay getRelayStatus(int relayIndex) throws ShellyApiException {
169 return callApi(SHELLY_URL_STATUS_RELEAY + "/" + relayIndex, ShellyStatusRelay.class);
173 public void setRelayTurn(int id, String turnMode) throws ShellyApiException {
174 callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
175 ShellyShortLightStatus.class);
179 public ShellyShortLightStatus setLightTurn(int id, String turnMode) throws ShellyApiException {
180 return callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
181 ShellyShortLightStatus.class);
185 public void setBrightness(int id, int brightness, boolean autoOn) throws ShellyApiException {
186 String turn = autoOn ? SHELLY_LIGHT_TURN + "=" + SHELLY_API_ON + "&" : "";
187 httpRequest(getControlUriPrefix(id) + "?" + turn + "brightness=" + brightness);
191 public ShellyRollerStatus getRollerStatus(int rollerIndex) throws ShellyApiException {
192 String uri = SHELLY_URL_CONTROL_ROLLER + "/" + rollerIndex + "/pos";
193 return callApi(uri, ShellyRollerStatus.class);
197 public void setRollerTurn(int relayIndex, String turnMode) throws ShellyApiException {
198 httpRequest(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex + "?go=" + turnMode);
202 public void setRollerPos(int relayIndex, int position) throws ShellyApiException {
203 httpRequest(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex + "?go=to_pos&roller_pos=" + position);
207 public ShellyShortLightStatus getLightStatus(int index) throws ShellyApiException {
208 return callApi(getControlUriPrefix(index), ShellyShortLightStatus.class);
212 public ShellyStatusSensor getSensorStatus() throws ShellyApiException {
213 ShellyStatusSensor status = callApi(SHELLY_URL_STATUS, ShellyStatusSensor.class);
214 if (profile.isSense) {
215 // complete reported data, map C to F or vice versa: C=(F - 32) * 0.5556;
216 status.tmp.tC = status.tmp.units.equals(SHELLY_TEMP_CELSIUS) ? status.tmp.value
217 : ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(getDouble(status.tmp.value))
219 double f = (double) SIUnits.CELSIUS.getConverterTo(ImperialUnits.FAHRENHEIT)
220 .convert(getDouble(status.tmp.value));
221 status.tmp.tF = status.tmp.units.equals(SHELLY_TEMP_FAHRENHEIT) ? status.tmp.value : f;
223 if ((status.charger == null) && (profile.settings.externalPower != null)) {
224 // SHelly H&T uses external_power, Sense uses charger
225 status.charger = profile.settings.externalPower != 0;
227 if (status.tmp != null && status.tmp.tC == null && status.tmp.value != null) { // Motion is is missing tC and tF
228 status.tmp.tC = getString(status.tmp.units).toUpperCase().equals(SHELLY_TEMP_FAHRENHEIT)
229 ? ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(status.tmp.value).doubleValue()
236 public void setAutoTimer(int index, String timerName, double value) throws ShellyApiException {
237 String type = SHELLY_CLASS_RELAY;
238 if (profile.isRoller) {
239 type = SHELLY_CLASS_ROLLER;
240 } else if (profile.isLight) {
241 type = SHELLY_CLASS_LIGHT;
243 String uri = SHELLY_URL_SETTINGS + "/" + type + "/" + index + "?" + timerName + "=" + (int) value;
248 public void setSleepTime(int value) throws ShellyApiException {
249 httpRequest(SHELLY_URL_SETTINGS + "?sleep_time=" + value);
253 public void setValveTemperature(int valveId, int value) throws ShellyApiException {
254 request("/thermostat/" + valveId + "?target_t_enabled=1&target_t=" + value);
258 public void setValveMode(int valveId, boolean auto) throws ShellyApiException {
259 String uri = "/settings/thermostat/" + valveId + "?target_t_enabled=" + (auto ? "1" : "0");
261 uri = uri + "&target_t=" + getDouble(profile.settings.thermostats.get(0).targetTemp.value);
263 httpRequest(uri); // percentage to open the valve
267 public void setValveProfile(int valveId, int value) throws ShellyApiException {
268 String uri = "/settings/thermostat/" + valveId + "?";
269 request(uri + (value == 0 ? "schedule=0" : "schedule=1&schedule_profile=" + value));
273 public void setValvePosition(int valveId, double value) throws ShellyApiException {
274 request("/thermostat/" + valveId + "?pos=" + value); // percentage to open the valve
278 public void setValveBoostTime(int valveId, int value) throws ShellyApiException {
279 request("/settings/thermostat/" + valveId + "?boost_minutes=" + value);
283 public void startValveBoost(int valveId, int value) throws ShellyApiException {
284 int minutes = value != -1 ? value : getInteger(profile.settings.thermostats.get(0).boostMinutes);
285 httpRequest("/thermostat/0?boost_minutes=" + minutes);
289 public void setLedStatus(String ledName, Boolean value) throws ShellyApiException {
290 httpRequest(SHELLY_URL_SETTINGS + "?" + ledName + "=" + (value ? SHELLY_API_TRUE : SHELLY_API_FALSE));
293 public ShellySettingsLight getLightSettings() throws ShellyApiException {
294 return callApi(SHELLY_URL_SETTINGS_LIGHT, ShellySettingsLight.class);
298 public ShellyStatusLight getLightStatus() throws ShellyApiException {
299 return callApi(SHELLY_URL_STATUS, ShellyStatusLight.class);
302 public void setLightSetting(String parm, String value) throws ShellyApiException {
303 httpRequest(SHELLY_URL_SETTINGS + "?" + parm + "=" + value);
307 public ShellySettingsLogin getLoginSettings() throws ShellyApiException {
308 return callApi(SHELLY_URL_SETTINGS + "/login", ShellySettingsLogin.class);
312 public ShellySettingsLogin setLoginCredentials(String user, String password) throws ShellyApiException {
313 return callApi(SHELLY_URL_SETTINGS + "/login?enabled=yes&username=" + urlEncode(user) + "&password="
314 + urlEncode(password), ShellySettingsLogin.class);
318 public String getCoIoTDescription() throws ShellyApiException {
320 return callApi("/cit/d", String.class);
321 } catch (ShellyApiException e) {
322 if (e.getApiResult().isNotFound()) {
323 return ""; // only supported by FW 1.10+
330 public ShellySettingsLogin setCoIoTPeer(String peer) throws ShellyApiException {
331 return callApi(SHELLY_URL_SETTINGS + "?coiot_enable=true&coiot_peer=" + peer, ShellySettingsLogin.class);
335 public String deviceReboot() throws ShellyApiException {
336 return callApi(SHELLY_URL_RESTART, String.class);
340 public String factoryReset() throws ShellyApiException {
341 return callApi(SHELLY_URL_SETTINGS + "?reset=true", String.class);
345 public ShellyOtaCheckResult checkForUpdate() throws ShellyApiException {
346 return callApi("/ota/check", ShellyOtaCheckResult.class); // nw FW 1.10+: trigger update check
350 public String setWiFiRecovery(boolean enable) throws ShellyApiException {
351 return callApi(SHELLY_URL_SETTINGS + "?wifirecovery_reboot_enabled=" + (enable ? "true" : "false"),
352 String.class); // FW 1.10+: Enable auto-restart on WiFi problems
356 public String setApRoaming(boolean enable) throws ShellyApiException { // FW 1.10+: Enable AP Roadming
357 return callApi(SHELLY_URL_SETTINGS + "?ap_roaming_enabled=" + (enable ? "true" : "false"), String.class);
361 public boolean setWiFiRangeExtender(boolean enable) throws ShellyApiException {
366 public boolean setEthernet(boolean enable) throws ShellyApiException {
371 public boolean setBluetooth(boolean enable) throws ShellyApiException {
376 public String resetStaCache() throws ShellyApiException { // FW 1.10+: Reset cached STA/AP list and to a rescan
377 return callApi("/sta_cache_reset", String.class);
381 public ShellySettingsUpdate firmwareUpdate(String uri) throws ShellyApiException {
382 return callApi("/ota?" + uri, ShellySettingsUpdate.class);
386 public String setCloud(boolean enabled) throws ShellyApiException {
387 return callApi("/settings/cloud/?enabled=" + (enabled ? "1" : "0"), String.class);
391 * Change between White and Color Mode
394 * @throws ShellyApiException
397 public void setLightMode(String mode) throws ShellyApiException {
398 if (!mode.isEmpty() && !profile.mode.equals(mode)) {
399 setLightSetting(SHELLY_API_MODE, mode);
401 profile.inColor = profile.isLight && profile.mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
406 * Set a single light parameter
408 * @param lightIndex Index of the light, usually 0 for Bulb and 0..3 for RGBW2.
409 * @param parm Name of the parameter (see API spec)
410 * @param value The value
411 * @throws ShellyApiException
414 public void setLightParm(int lightIndex, String parm, String value) throws ShellyApiException {
415 // Bulb, RGW2: /<color mode>/<light id>?parm?value
416 // Dimmer: /light/<light id>?parm=value
417 httpRequest(getControlUriPrefix(lightIndex) + "?" + parm + "=" + value);
421 public void setLightParms(int lightIndex, Map<String, String> parameters) throws ShellyApiException {
422 String url = getControlUriPrefix(lightIndex) + "?";
424 for (String key : parameters.keySet()) {
428 url = url + key + "=" + parameters.get(key);
435 * Retrieve the IR Code list from the Shelly Sense device. The list could be customized by the user. It defines the
436 * symbolic key code, which gets
437 * map into a PRONTO code
439 * @return Map of key codes
440 * @throws ShellyApiException
442 public Map<String, String> getIRCodeList() throws ShellyApiException {
443 String result = httpRequest(SHELLY_URL_LIST_IR);
444 // take pragmatic approach to make the returned JSon into named arrays for Gson parsing
445 String keyList = substringAfter(result, "[");
446 keyList = substringBeforeLast(keyList, "]");
447 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("\",\""), "\", \"name\": \"");
448 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("["), "{ \"id\":");
449 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("]"), "} ");
450 String json = "{\"key_codes\" : [" + keyList + "] }";
451 ShellySendKeyList codes = fromJson(gson, json, ShellySendKeyList.class);
452 Map<String, String> list = new HashMap<>();
453 for (ShellySenseKeyCode key : codes.keyCodes) {
455 list.put(key.id, key.name);
462 * Sends a IR key code to the Shelly Sense.
464 * @param keyCode A keyCoud could be a symbolic name (as defined in the key map on the device) or a PRONTO Code in
465 * plain or hex64 format
467 * @throws ShellyApiException
468 * @throws IllegalArgumentException
471 public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
473 if (profile.irCodes.containsKey(keyCode)) {
474 type = SHELLY_IR_CODET_STORED;
475 } else if ((keyCode.length() > 4) && keyCode.contains(" ")) {
476 type = SHELLY_IR_CODET_PRONTO;
478 type = SHELLY_IR_CODET_PRONTO_HEX;
480 String url = SHELLY_URL_SEND_IR + "?type=" + type;
481 if (type.equals(SHELLY_IR_CODET_STORED)) {
482 url = url + "&" + "id=" + keyCode;
483 } else if (type.equals(SHELLY_IR_CODET_PRONTO)) {
484 String code = Base64.getEncoder().encodeToString(keyCode.getBytes(StandardCharsets.UTF_8));
485 url = url + "&" + SHELLY_IR_CODET_PRONTO + "=" + code;
486 } else if (type.equals(SHELLY_IR_CODET_PRONTO_HEX)) {
487 url = url + "&" + SHELLY_IR_CODET_PRONTO_HEX + "=" + keyCode;
492 public void setSenseSetting(String setting, String value) throws ShellyApiException {
493 httpRequest(SHELLY_URL_SETTINGS + "?" + setting + "=" + value);
497 * Set event callback URLs. Depending on the device different event types are supported. In fact all of them will be
498 * redirected to the binding's servlet and act as a trigger to schedule a status update
500 * @param ShellyApiException
501 * @throws ShellyApiException
504 public void setActionURLs() throws ShellyApiException {
507 setSensorEventUrls();
510 private void setRelayEvents() throws ShellyApiException {
511 if (profile.settings.relays != null) {
512 int num = profile.isRoller ? profile.numRollers : profile.numRelays;
513 for (int i = 0; i < num; i++) {
519 private void setDimmerEvents() throws ShellyApiException {
520 if (profile.settings.dimmers != null) {
521 int sz = profile.settings.dimmers.size();
522 for (int i = 0; i < sz; i++) {
525 } else if (profile.isLight) {
531 * Set sensor Action URLs
533 * @throws ShellyApiException
535 private void setSensorEventUrls() throws ShellyApiException, ShellyApiException {
536 if (profile.isSensor) {
537 logger.debug("{}: Set Sensor Reporting URL", thingName);
538 setEventUrl(config.eventsSensorReport, SHELLY_EVENT_SENSORREPORT, SHELLY_EVENT_DARK, SHELLY_EVENT_TWILIGHT,
539 SHELLY_EVENT_FLOOD_DETECTED, SHELLY_EVENT_FLOOD_GONE, SHELLY_EVENT_OPEN, SHELLY_EVENT_CLOSE,
540 SHELLY_EVENT_VIBRATION, SHELLY_EVENT_ALARM_MILD, SHELLY_EVENT_ALARM_HEAVY, SHELLY_EVENT_ALARM_OFF,
541 SHELLY_EVENT_TEMP_OVER, SHELLY_EVENT_TEMP_UNDER);
546 * Set/delete Relay/Roller/Dimmer Action URLs
548 * @param index Device Index (0-based)
549 * @throws ShellyApiException
551 private void setEventUrls(Integer index) throws ShellyApiException {
552 if (profile.isRoller) {
553 setEventUrl(EVENT_TYPE_ROLLER, 0, config.eventsRoller, SHELLY_EVENT_ROLLER_OPEN, SHELLY_EVENT_ROLLER_CLOSE,
554 SHELLY_EVENT_ROLLER_STOP);
555 } else if (profile.isDimmer) {
557 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsButton, SHELLY_EVENT_BTN1_ON, SHELLY_EVENT_BTN1_OFF,
558 SHELLY_EVENT_BTN2_ON, SHELLY_EVENT_BTN2_OFF);
559 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH1, SHELLY_EVENT_LONGPUSH1,
560 SHELLY_EVENT_SHORTPUSH2, SHELLY_EVENT_LONGPUSH2);
563 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
564 } else if (profile.hasRelays) {
565 // Standard relays: btn_xxx, out_xxx, short/longpush URLs
566 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsButton, SHELLY_EVENT_BTN_ON, SHELLY_EVENT_BTN_OFF);
567 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH, SHELLY_EVENT_LONGPUSH);
568 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
569 } else if (profile.isLight) {
571 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
575 private void setEventUrl(boolean enabled, String... eventTypes) throws ShellyApiException {
576 if (config.localIp.isEmpty()) {
577 throw new ShellyApiException(thingName + ": Local IP address was not detected, can't build Callback URL");
579 for (String eventType : eventTypes) {
580 if (profile.containsEventUrl(eventType)) {
581 // H&T adds the type=xx to report_url itself, so we need to ommit here
582 String eclass = profile.isSensor ? EVENT_TYPE_SENSORDATA : eventType;
583 String urlParm = eventType.contains("temp") || profile.isHT ? "" : "?type=" + eventType;
584 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY1_CALLBACK_URI + "/"
585 + profile.thingName + "/" + eclass + urlParm;
586 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
587 String testUrl = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
588 if (!enabled && !profile.settingsJson.contains(testUrl)) {
589 // Don't set URL to null when the current one doesn't point to this OH
590 // Don't interfere with a 3rd party App
593 if (!profile.settingsJson.contains(testUrl)) {
594 // Current Action URL is != new URL
595 logger.debug("{}: Set new url for event type {}: {}", thingName, eventType, newUrl);
596 httpRequest(SHELLY_URL_SETTINGS + "?" + mkEventUrl(eventType) + "=" + urlEncode(newUrl));
602 private void setEventUrl(String deviceClass, Integer index, boolean enabled, String... eventTypes)
603 throws ShellyApiException {
604 for (String eventType : eventTypes) {
605 if (profile.containsEventUrl(eventType)) {
606 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY1_CALLBACK_URI + "/"
607 + profile.thingName + "/" + deviceClass + "/" + index + "?type=" + eventType;
608 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
609 String test = "\"" + mkEventUrl(eventType) + "\":\"" + callBackUrl + "\"";
610 if (!enabled && !profile.settingsJson.contains(test)) {
611 // Don't set URL to null when the current one doesn't point to this OH
612 // Don't interfere with a 3rd party App
615 test = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
616 if (!profile.settingsJson.contains(test)) {
617 // Current Action URL is != new URL
618 logger.debug("{}: Set URL for type {} to {}", thingName, eventType, newUrl);
619 httpRequest(SHELLY_URL_SETTINGS + "/" + deviceClass + "/" + index + "?" + mkEventUrl(eventType)
620 + "=" + urlEncode(newUrl));
626 private static String mkEventUrl(String eventType) {
627 return eventType + SHELLY_EVENTURL_SUFFIX;
631 * Submit GET request and return response, check for invalid responses
633 * @param uri: URI (e.g. "/settings")
636 public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
637 String json = request(uri);
638 return fromJson(gson, json, classOfT);
641 private String request(String uri) throws ShellyApiException {
642 ShellyApiResult apiResult = new ShellyApiResult();
644 boolean timeout = false;
645 while (retries > 0) {
647 apiResult = innerRequest(HttpMethod.GET, uri);
649 logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
653 return apiResult.response; // successful
654 } catch (ShellyApiException e) {
655 if ((!e.isTimeout() && !apiResult.isHttpServerError()) || profile.hasBattery || (retries == 0)) {
656 // Sensor in sleep mode or API exception for non-battery device or retry counter expired
657 throw e; // non-timeout exception
662 timeoutErrors++; // count the retries
663 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
666 throw new ShellyApiException("API Timeout or inconsistent result"); // successful
669 private ShellyApiResult innerRequest(HttpMethod method, String uri) throws ShellyApiException {
670 Request request = null;
671 String url = "http://" + config.deviceIp + uri;
672 ShellyApiResult apiResult = new ShellyApiResult(method.toString(), url);
675 request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
676 TimeUnit.MILLISECONDS);
678 if (!config.userId.isEmpty()) {
679 String value = config.userId + ":" + config.password;
680 request.header(HTTP_HEADER_AUTH,
681 HTTP_AUTH_TYPE_BASIC + " " + Base64.getEncoder().encodeToString(value.getBytes()));
683 request.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON);
684 logger.trace("{}: HTTP {} for {}", thingName, method, url);
686 // Do request and get response
687 ContentResponse contentResponse = request.send();
688 apiResult = new ShellyApiResult(contentResponse);
689 String response = contentResponse.getContentAsString().replace("\t", "").replace("\r\n", "").trim();
690 logger.trace("{}: HTTP Response {}: {}", thingName, contentResponse.getStatus(), response);
692 // validate response, API errors are reported as Json
693 if (contentResponse.getStatus() != HttpStatus.OK_200) {
694 throw new ShellyApiException(apiResult);
696 if (response.isEmpty() || !response.startsWith("{") && !response.startsWith("[") && !url.contains("/debug/")
697 && !url.contains("/sta_cache_reset")) {
698 throw new ShellyApiException("Unexpected response: " + response);
700 } catch (ExecutionException | InterruptedException | TimeoutException | IllegalArgumentException e) {
701 ShellyApiException ex = new ShellyApiException(apiResult, e);
702 if (!ex.isTimeout()) { // will be handled by the caller
703 logger.trace("{}: API call returned exception", thingName, ex);
711 public String getControlUriPrefix(Integer id) {
713 if (profile.isLight || profile.isDimmer) {
714 if (profile.isDuo || profile.isDimmer) {
716 uri = SHELLY_URL_CONTROL_LIGHT;
719 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
723 uri = SHELLY_URL_CONTROL_RELEAY;
725 uri = uri + "/" + id;
730 public int getTimeoutErrors() {
731 return timeoutErrors;
735 public int getTimeoutsRecovered() {
736 return timeoutsRecovered;
740 public void close() {