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