]> git.basschouten.com Git - openhab-addons.git/blob
a8906c84924d4cddfa5741ef71a51ff60bf7c79c
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.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;
52
53 import com.google.gson.Gson;
54 import com.google.gson.JsonSyntaxException;
55
56 /**
57  * {@link ShellyHttpApi} wraps the Shelly REST API and provides various low level function to access the device api (not
58  * cloud api).
59  *
60  * @author Markus Michels - Initial contribution
61  */
62 @NonNullByDefault
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";
67
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;
75
76     private ShellyDeviceProfile profile = new ShellyDeviceProfile();
77
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);
83     }
84
85     public void setConfig(String thingName, ShellyThingConfiguration config) {
86         this.thingName = thingName;
87         this.config = config;
88     }
89
90     public ShellySettingsDevice getDevInfo() throws ShellyApiException {
91         return callApi(SHELLY_URL_DEVINFO, ShellySettingsDevice.class);
92     }
93
94     public String setDebug(boolean enabled) throws ShellyApiException {
95         return callApi(SHELLY_URL_SETTINGS + "?debug_enable=" + Boolean.valueOf(enabled), String.class);
96     }
97
98     public String getDebugLog(String id) throws ShellyApiException {
99         return callApi("/debug/" + id, String.class);
100     }
101
102     /**
103      * Initialize the device profile
104      *
105      * @param thingType Type of DEVICE as returned from the thing properties (based on discovery)
106      * @return Initialized ShellyDeviceProfile
107      * @throws ShellyApiException
108      */
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);
114         }
115
116         // Map settings to device profile for Light and Sense
117         profile.initialize(thingType, json);
118
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;
125         }
126         if (profile.isSense) {
127             profile.irCodes = getIRCodeList();
128             logger.debug("{}: Sense stored key list loaded, {} entries.", thingName, profile.irCodes.size());
129         }
130
131         return profile;
132     }
133
134     public boolean isInitialized() {
135         return profile.initialized;
136     }
137
138     /**
139      * Get generic device settings/status. Json returned from API will be mapped to a Gson object
140      *
141      * @return Device settings/status as ShellySettingsStatus object
142      * @throws ShellyApiException
143      */
144     public ShellySettingsStatus getStatus() throws ShellyApiException {
145         String json = "";
146         try {
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);
152             status.json = json;
153             return status;
154         } catch (JsonSyntaxException e) {
155             throw new ShellyApiException("Unable to parse JSON: " + json, e);
156         }
157     }
158
159     public ShellyStatusRelay getRelayStatus(Integer relayIndex) throws ShellyApiException {
160         return callApi(SHELLY_URL_STATUS_RELEAY + "/" + relayIndex.toString(), ShellyStatusRelay.class);
161     }
162
163     public ShellyShortLightStatus setRelayTurn(Integer id, String turnMode) throws ShellyApiException {
164         return callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
165                 ShellyShortLightStatus.class);
166     }
167
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());
171     }
172
173     public ShellyControlRoller getRollerStatus(Integer rollerIndex) throws ShellyApiException {
174         String uri = SHELLY_URL_CONTROL_ROLLER + "/" + rollerIndex.toString() + "/pos";
175         return callApi(uri, ShellyControlRoller.class);
176     }
177
178     public void setRollerTurn(Integer relayIndex, String turnMode) throws ShellyApiException {
179         request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=" + turnMode);
180     }
181
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());
185     }
186
187     public void setRollerTimer(Integer relayIndex, Integer timer) throws ShellyApiException {
188         request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?timer=" + timer.toString());
189     }
190
191     public ShellyShortLightStatus getLightStatus(Integer index) throws ShellyApiException {
192         return callApi(getControlUriPrefix(index), ShellyShortLightStatus.class);
193     }
194
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))
201                             .doubleValue();
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;
205         }
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;
209         }
210         return status;
211     }
212
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;
219         }
220         String uri = SHELLY_URL_SETTINGS + "/" + type + "/" + index + "?" + timerName + "=" + value;
221         request(uri);
222     }
223
224     public void setSleepTime(int value) throws ShellyApiException {
225         request(SHELLY_URL_SETTINGS + "?sleep_time=" + value);
226     }
227
228     public void setTemperature(int valveId, int value) throws ShellyApiException {
229         request("/thermostat/" + valveId + "?target_t_enabled=1&target_t=" + value);
230     }
231
232     public void setValveMode(int valveId, boolean auto) throws ShellyApiException {
233         String uri = "/settings/thermostat/" + valveId + "?target_t_enabled=" + (auto ? "1" : "0");
234         if (auto) {
235             uri = uri + "&target_t=" + getDouble(profile.settings.thermostats.get(0).targetTemp.value);
236         }
237         request(uri); // percentage to open the valve
238     }
239
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));
243     }
244
245     public void setValvePosition(int valveId, double value) throws ShellyApiException {
246         request("/thermostat/" + valveId + "?pos=" + value); // percentage to open the valve
247     }
248
249     public void setBoostTime(int valveId, int value) throws ShellyApiException {
250         request("/settings/thermostat/" + valveId + "?boost_minutes=" + value);
251     }
252
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);
256     }
257
258     public void setLedStatus(String ledName, Boolean value) throws ShellyApiException {
259         request(SHELLY_URL_SETTINGS + "?" + ledName + "=" + (value ? SHELLY_API_TRUE : SHELLY_API_FALSE));
260     }
261
262     public ShellySettingsLight getLightSettings() throws ShellyApiException {
263         return callApi(SHELLY_URL_SETTINGS_LIGHT, ShellySettingsLight.class);
264     }
265
266     public ShellyStatusLight getLightStatus() throws ShellyApiException {
267         return callApi(SHELLY_URL_STATUS, ShellyStatusLight.class);
268     }
269
270     public void setLightSetting(String parm, String value) throws ShellyApiException {
271         request(SHELLY_URL_SETTINGS + "?" + parm + "=" + value);
272     }
273
274     public ShellySettingsLogin getLoginSettings() throws ShellyApiException {
275         return callApi(SHELLY_URL_SETTINGS + "/login", ShellySettingsLogin.class);
276     }
277
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);
281     }
282
283     public String getCoIoTDescription() throws ShellyApiException {
284         try {
285             return callApi("/cit/d", String.class);
286         } catch (ShellyApiException e) {
287             if (e.getApiResult().isNotFound()) {
288                 return ""; // only supported by FW 1.10+
289             }
290             throw e;
291         }
292     }
293
294     public ShellySettingsLogin setCoIoTPeer(String peer) throws ShellyApiException {
295         return callApi(SHELLY_URL_SETTINGS + "?coiot_enable=true&coiot_peer=" + peer, ShellySettingsLogin.class);
296     }
297
298     public String deviceReboot() throws ShellyApiException {
299         return callApi(SHELLY_URL_RESTART, String.class);
300     }
301
302     public String factoryReset() throws ShellyApiException {
303         return callApi(SHELLY_URL_SETTINGS + "?reset=true", String.class);
304     }
305
306     public ShellyOtaCheckResult checkForUpdate() throws ShellyApiException {
307         return callApi("/ota/check", ShellyOtaCheckResult.class); // nw FW 1.10+: trigger update check
308     }
309
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
313     }
314
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);
317     }
318
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);
321     }
322
323     public ShellySettingsUpdate firmwareUpdate(String uri) throws ShellyApiException {
324         return callApi("/ota?" + uri, ShellySettingsUpdate.class);
325     }
326
327     public String setCloud(boolean enabled) throws ShellyApiException {
328         return callApi("/settings/cloud/?enabled=" + (enabled ? "1" : "0"), String.class);
329     }
330
331     /**
332      * Change between White and Color Mode
333      *
334      * @param mode
335      * @throws ShellyApiException
336      */
337     public void setLightMode(String mode) throws ShellyApiException {
338         if (!mode.isEmpty() && !profile.mode.equals(mode)) {
339             setLightSetting(SHELLY_API_MODE, mode);
340             profile.mode = mode;
341             profile.inColor = profile.isLight && profile.mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
342         }
343     }
344
345     /**
346      * Set a single light parameter
347      *
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
352      */
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);
357     }
358
359     public void setLightParms(Integer lightIndex, Map<String, String> parameters) throws ShellyApiException {
360         String url = getControlUriPrefix(lightIndex) + "?";
361         int i = 0;
362         for (String key : parameters.keySet()) {
363             if (i > 0) {
364                 url = url + "&";
365             }
366             url = url + key + "=" + parameters.get(key);
367             i++;
368         }
369         request(url);
370     }
371
372     /**
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
376      *
377      * @return Map of key codes
378      * @throws ShellyApiException
379      */
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) {
392             if (key != null) {
393                 list.put(key.id, key.name);
394             }
395         }
396         return list;
397     }
398
399     /**
400      * Sends a IR key code to the Shelly Sense.
401      *
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
404      *
405      * @throws ShellyApiException
406      * @throws IllegalArgumentException
407      */
408     public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
409         String type = "";
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;
414         } else {
415             type = SHELLY_IR_CODET_PRONTO_HEX;
416         }
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;
425         }
426         request(url);
427     }
428
429     public void setSenseSetting(String setting, String value) throws ShellyApiException {
430         request(SHELLY_URL_SETTINGS + "?" + setting + "=" + value);
431     }
432
433     /**
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
436      *
437      * @param ShellyApiException
438      * @throws ShellyApiException
439      */
440     public void setActionURLs() throws ShellyApiException {
441         setRelayEvents();
442         setDimmerEvents();
443         setSensorEventUrls();
444     }
445
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++) {
450                 setEventUrls(i);
451             }
452         }
453     }
454
455     private void setDimmerEvents() throws ShellyApiException {
456         if (profile.settings.dimmers != null) {
457             for (int i = 0; i < profile.settings.dimmers.size(); i++) {
458                 setEventUrls(i);
459             }
460         } else if (profile.isLight) {
461             setEventUrls(0);
462         }
463     }
464
465     /**
466      * Set sensor Action URLs
467      *
468      * @throws ShellyApiException
469      */
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);
477         }
478     }
479
480     /**
481      * Set/delete Relay/Roller/Dimmer Action URLs
482      *
483      * @param index Device Index (0-based)
484      * @throws ShellyApiException
485      */
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) {
491             // 2 set of URLs
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);
496
497             // Relay output
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) {
505             // Duo, Bulb
506             setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
507         }
508     }
509
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");
513         }
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
526                     continue;
527                 }
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));
532                 }
533             }
534         }
535     }
536
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
548                     continue;
549                 }
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));
556                 }
557             }
558         }
559     }
560
561     private static String mkEventUrl(String eventType) {
562         return eventType + SHELLY_EVENTURL_SUFFIX;
563     }
564
565     /**
566      * Submit GET request and return response, check for invalid responses
567      *
568      * @param uri: URI (e.g. "/settings")
569      */
570     public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
571         String json = request(uri);
572         return fromJson(gson, json, classOfT);
573     }
574
575     private String request(String uri) throws ShellyApiException {
576         ShellyApiResult apiResult = new ShellyApiResult();
577         int retries = 3;
578         boolean timeout = false;
579         while (retries > 0) {
580             try {
581                 apiResult = innerRequest(HttpMethod.GET, uri);
582                 if (timeout) {
583                     logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
584                             apiResult.getUrl());
585                     timeoutsRecovered++;
586                 }
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
592                 }
593
594                 timeout = true;
595                 retries--;
596                 timeoutErrors++; // count the retries
597                 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
598             }
599         }
600         throw new ShellyApiException("API Timeout or inconsistent result"); // successful
601     }
602
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);
607
608         try {
609             request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
610                     TimeUnit.MILLISECONDS);
611
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()));
616             }
617             request.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON);
618             logger.trace("{}: HTTP {} for {}", thingName, method, url);
619
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);
625
626             // validate response, API errors are reported as Json
627             if (contentResponse.getStatus() != HttpStatus.OK_200) {
628                 throw new ShellyApiException(apiResult);
629             }
630             if (response.isEmpty() || !response.startsWith("{") && !response.startsWith("[") && !url.contains("/debug/")
631                     && !url.contains("/sta_cache_reset")) {
632                 throw new ShellyApiException("Unexpected response: " + response);
633             }
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);
638             }
639             throw ex;
640         }
641         return apiResult;
642     }
643
644     public String getControlUriPrefix(Integer id) {
645         String uri = "";
646         if (profile.isLight || profile.isDimmer) {
647             if (profile.isDuo || profile.isDimmer) {
648                 // Duo + Dimmer
649                 uri = SHELLY_URL_CONTROL_LIGHT;
650             } else {
651                 // Bulb + RGBW2
652                 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
653             }
654         } else {
655             // Roller, Relay
656             uri = SHELLY_URL_CONTROL_RELEAY;
657         }
658         uri = uri + "/" + id;
659         return uri;
660     }
661
662     public int getTimeoutErrors() {
663         return timeoutErrors;
664     }
665
666     public int getTimeoutsRecovered() {
667         return timeoutsRecovered;
668     }
669 }