]> git.basschouten.com Git - openhab-addons.git/blob
027d75d89bc38fad5a7496e1dcf3faacc38babdd
[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.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.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;
58
59 import com.google.gson.JsonSyntaxException;
60
61 /**
62  * {@link Shelly1HttpApi} wraps the Shelly REST API and provides various low level function to access the device api
63  * (not
64  * cloud api).
65  *
66  * @author Markus Michels - Initial contribution
67  */
68 @NonNullByDefault
69 public class Shelly1HttpApi extends ShellyHttpClient implements ShellyApiInterface {
70     private final Logger logger = LoggerFactory.getLogger(Shelly1HttpApi.class);
71     private final ShellyDeviceProfile profile;
72
73     public Shelly1HttpApi(String thingName, ShellyThingInterface thing) {
74         super(thingName, thing);
75         profile = thing.getProfile();
76     }
77
78     /**
79      * Simple initialization - called by discovery handler
80      *
81      * @param thingName Symbolic thing name
82      * @param config Thing Configuration
83      * @param httpClient HTTP Client to be passed to ShellyHttpClient
84      */
85     public Shelly1HttpApi(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
86         super(thingName, config, httpClient);
87         this.profile = new ShellyDeviceProfile();
88     }
89
90     @Override
91     public ShellySettingsDevice getDeviceInfo() throws ShellyApiException {
92         return callApi(SHELLY_URL_DEVINFO, ShellySettingsDevice.class);
93     }
94
95     @Override
96     public String setDebug(boolean enabled) throws ShellyApiException {
97         return callApi(SHELLY_URL_SETTINGS + "?debug_enable=" + Boolean.valueOf(enabled), String.class);
98     }
99
100     @Override
101     public String getDebugLog(String id) throws ShellyApiException {
102         return callApi("/debug/" + id, String.class);
103     }
104
105     /**
106      * Initialize the device profile
107      *
108      * @param thingType Type of DEVICE as returned from the thing properties (based on discovery)
109      * @return Initialized ShellyDeviceProfile
110      * @throws ShellyApiException
111      */
112     @Override
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);
118         }
119
120         // Map settings to device profile for Light and Sense
121         profile.initialize(thingType, json);
122
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;
129         }
130         if (profile.isSense) {
131             profile.irCodes = getIRCodeList();
132             logger.debug("{}: Sense stored key list loaded, {} entries.", thingName, profile.irCodes.size());
133         }
134
135         return profile;
136     }
137
138     @Override
139     public boolean isInitialized() {
140         return profile.initialized;
141     }
142
143     /**
144      * Get generic device settings/status. Json returned from API will be mapped to a Gson object
145      *
146      * @return Device settings/status as ShellySettingsStatus object
147      * @throws ShellyApiException
148      */
149     @Override
150     public ShellySettingsStatus getStatus() throws ShellyApiException {
151         String json = "";
152         try {
153             json = httpRequest(SHELLY_URL_STATUS);
154
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);
160             status.json = json;
161             return status;
162         } catch (JsonSyntaxException e) {
163             throw new ShellyApiException("Unable to parse JSON: " + json, e);
164         }
165     }
166
167     @Override
168     public ShellyStatusRelay getRelayStatus(int relayIndex) throws ShellyApiException {
169         return callApi(SHELLY_URL_STATUS_RELEAY + "/" + relayIndex, ShellyStatusRelay.class);
170     }
171
172     @Override
173     public void setRelayTurn(int id, String turnMode) throws ShellyApiException {
174         callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
175                 ShellyShortLightStatus.class);
176     }
177
178     @Override
179     public ShellyShortLightStatus setLightTurn(int id, String turnMode) throws ShellyApiException {
180         return callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
181                 ShellyShortLightStatus.class);
182     }
183
184     @Override
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);
188     }
189
190     @Override
191     public ShellyRollerStatus getRollerStatus(int rollerIndex) throws ShellyApiException {
192         String uri = SHELLY_URL_CONTROL_ROLLER + "/" + rollerIndex + "/pos";
193         return callApi(uri, ShellyRollerStatus.class);
194     }
195
196     @Override
197     public void setRollerTurn(int relayIndex, String turnMode) throws ShellyApiException {
198         httpRequest(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex + "?go=" + turnMode);
199     }
200
201     @Override
202     public void setRollerPos(int relayIndex, int position) throws ShellyApiException {
203         httpRequest(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex + "?go=to_pos&roller_pos=" + position);
204     }
205
206     @Override
207     public ShellyShortLightStatus getLightStatus(int index) throws ShellyApiException {
208         return callApi(getControlUriPrefix(index), ShellyShortLightStatus.class);
209     }
210
211     @Override
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))
218                             .doubleValue();
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;
222         }
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;
226         }
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()
230                     : status.tmp.value;
231         }
232         return status;
233     }
234
235     @Override
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;
242         }
243         String uri = SHELLY_URL_SETTINGS + "/" + type + "/" + index + "?" + timerName + "=" + (int) value;
244         httpRequest(uri);
245     }
246
247     @Override
248     public void setSleepTime(int value) throws ShellyApiException {
249         httpRequest(SHELLY_URL_SETTINGS + "?sleep_time=" + value);
250     }
251
252     @Override
253     public void setValveTemperature(int valveId, int value) throws ShellyApiException {
254         request("/thermostat/" + valveId + "?target_t_enabled=1&target_t=" + value);
255     }
256
257     @Override
258     public void setValveMode(int valveId, boolean auto) throws ShellyApiException {
259         String uri = "/settings/thermostat/" + valveId + "?target_t_enabled=" + (auto ? "1" : "0");
260         if (auto) {
261             uri = uri + "&target_t=" + getDouble(profile.settings.thermostats.get(0).targetTemp.value);
262         }
263         httpRequest(uri); // percentage to open the valve
264     }
265
266     @Override
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));
270     }
271
272     @Override
273     public void setValvePosition(int valveId, double value) throws ShellyApiException {
274         request("/thermostat/" + valveId + "?pos=" + value); // percentage to open the valve
275     }
276
277     @Override
278     public void setValveBoostTime(int valveId, int value) throws ShellyApiException {
279         request("/settings/thermostat/" + valveId + "?boost_minutes=" + value);
280     }
281
282     @Override
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);
286     }
287
288     @Override
289     public void setLedStatus(String ledName, Boolean value) throws ShellyApiException {
290         httpRequest(SHELLY_URL_SETTINGS + "?" + ledName + "=" + (value ? SHELLY_API_TRUE : SHELLY_API_FALSE));
291     }
292
293     public ShellySettingsLight getLightSettings() throws ShellyApiException {
294         return callApi(SHELLY_URL_SETTINGS_LIGHT, ShellySettingsLight.class);
295     }
296
297     @Override
298     public ShellyStatusLight getLightStatus() throws ShellyApiException {
299         return callApi(SHELLY_URL_STATUS, ShellyStatusLight.class);
300     }
301
302     public void setLightSetting(String parm, String value) throws ShellyApiException {
303         httpRequest(SHELLY_URL_SETTINGS + "?" + parm + "=" + value);
304     }
305
306     @Override
307     public ShellySettingsLogin getLoginSettings() throws ShellyApiException {
308         return callApi(SHELLY_URL_SETTINGS + "/login", ShellySettingsLogin.class);
309     }
310
311     @Override
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);
315     }
316
317     @Override
318     public String getCoIoTDescription() throws ShellyApiException {
319         try {
320             return callApi("/cit/d", String.class);
321         } catch (ShellyApiException e) {
322             if (e.getApiResult().isNotFound()) {
323                 return ""; // only supported by FW 1.10+
324             }
325             throw e;
326         }
327     }
328
329     @Override
330     public ShellySettingsLogin setCoIoTPeer(String peer) throws ShellyApiException {
331         return callApi(SHELLY_URL_SETTINGS + "?coiot_enable=true&coiot_peer=" + peer, ShellySettingsLogin.class);
332     }
333
334     @Override
335     public String deviceReboot() throws ShellyApiException {
336         return callApi(SHELLY_URL_RESTART, String.class);
337     }
338
339     @Override
340     public String factoryReset() throws ShellyApiException {
341         return callApi(SHELLY_URL_SETTINGS + "?reset=true", String.class);
342     }
343
344     @Override
345     public ShellyOtaCheckResult checkForUpdate() throws ShellyApiException {
346         return callApi("/ota/check", ShellyOtaCheckResult.class); // nw FW 1.10+: trigger update check
347     }
348
349     @Override
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
353     }
354
355     @Override
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);
358     }
359
360     @Override
361     public boolean setWiFiRangeExtender(boolean enable) throws ShellyApiException {
362         return false;
363     }
364
365     @Override
366     public boolean setEthernet(boolean enable) throws ShellyApiException {
367         return false;
368     }
369
370     @Override
371     public boolean setBluetooth(boolean enable) throws ShellyApiException {
372         return false;
373     }
374
375     @Override
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);
378     }
379
380     @Override
381     public ShellySettingsUpdate firmwareUpdate(String uri) throws ShellyApiException {
382         return callApi("/ota?" + uri, ShellySettingsUpdate.class);
383     }
384
385     @Override
386     public String setCloud(boolean enabled) throws ShellyApiException {
387         return callApi("/settings/cloud/?enabled=" + (enabled ? "1" : "0"), String.class);
388     }
389
390     /**
391      * Change between White and Color Mode
392      *
393      * @param mode
394      * @throws ShellyApiException
395      */
396     @Override
397     public void setLightMode(String mode) throws ShellyApiException {
398         if (!mode.isEmpty() && !profile.mode.equals(mode)) {
399             setLightSetting(SHELLY_API_MODE, mode);
400             profile.mode = mode;
401             profile.inColor = profile.isLight && profile.mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
402         }
403     }
404
405     /**
406      * Set a single light parameter
407      *
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
412      */
413     @Override
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);
418     }
419
420     @Override
421     public void setLightParms(int lightIndex, Map<String, String> parameters) throws ShellyApiException {
422         String url = getControlUriPrefix(lightIndex) + "?";
423         int i = 0;
424         for (String key : parameters.keySet()) {
425             if (i > 0) {
426                 url = url + "&";
427             }
428             url = url + key + "=" + parameters.get(key);
429             i++;
430         }
431         httpRequest(url);
432     }
433
434     /**
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
438      *
439      * @return Map of key codes
440      * @throws ShellyApiException
441      */
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) {
454             if (key != null) {
455                 list.put(key.id, key.name);
456             }
457         }
458         return list;
459     }
460
461     /**
462      * Sends a IR key code to the Shelly Sense.
463      *
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
466      *
467      * @throws ShellyApiException
468      * @throws IllegalArgumentException
469      */
470     @Override
471     public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
472         String type = "";
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;
477         } else {
478             type = SHELLY_IR_CODET_PRONTO_HEX;
479         }
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;
488         }
489         httpRequest(url);
490     }
491
492     public void setSenseSetting(String setting, String value) throws ShellyApiException {
493         httpRequest(SHELLY_URL_SETTINGS + "?" + setting + "=" + value);
494     }
495
496     /**
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
499      *
500      * @param ShellyApiException
501      * @throws ShellyApiException
502      */
503     @Override
504     public void setActionURLs() throws ShellyApiException {
505         setRelayEvents();
506         setDimmerEvents();
507         setSensorEventUrls();
508     }
509
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++) {
514                 setEventUrls(i);
515             }
516         }
517     }
518
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++) {
523                 setEventUrls(i);
524             }
525         } else if (profile.isLight) {
526             setEventUrls(0);
527         }
528     }
529
530     /**
531      * Set sensor Action URLs
532      *
533      * @throws ShellyApiException
534      */
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);
542         }
543     }
544
545     /**
546      * Set/delete Relay/Roller/Dimmer Action URLs
547      *
548      * @param index Device Index (0-based)
549      * @throws ShellyApiException
550      */
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) {
556             // 2 set of URLs
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);
561
562             // Relay output
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) {
570             // Duo, Bulb
571             setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
572         }
573     }
574
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");
578         }
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
591                     continue;
592                 }
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));
597                 }
598             }
599         }
600     }
601
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
613                     continue;
614                 }
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));
621                 }
622             }
623         }
624     }
625
626     private static String mkEventUrl(String eventType) {
627         return eventType + SHELLY_EVENTURL_SUFFIX;
628     }
629
630     /**
631      * Submit GET request and return response, check for invalid responses
632      *
633      * @param uri: URI (e.g. "/settings")
634      */
635     @Override
636     public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
637         String json = request(uri);
638         return fromJson(gson, json, classOfT);
639     }
640
641     private String request(String uri) throws ShellyApiException {
642         ShellyApiResult apiResult = new ShellyApiResult();
643         int retries = 3;
644         boolean timeout = false;
645         while (retries > 0) {
646             try {
647                 apiResult = innerRequest(HttpMethod.GET, uri);
648                 if (timeout) {
649                     logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
650                             apiResult.getUrl());
651                     timeoutsRecovered++;
652                 }
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
658                 }
659
660                 timeout = true;
661                 retries--;
662                 timeoutErrors++; // count the retries
663                 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
664             }
665         }
666         throw new ShellyApiException("API Timeout or inconsistent result"); // successful
667     }
668
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);
673
674         try {
675             request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
676                     TimeUnit.MILLISECONDS);
677
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()));
682             }
683             request.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON);
684             logger.trace("{}: HTTP {} for {}", thingName, method, url);
685
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);
691
692             // validate response, API errors are reported as Json
693             if (contentResponse.getStatus() != HttpStatus.OK_200) {
694                 throw new ShellyApiException(apiResult);
695             }
696             if (response.isEmpty() || !response.startsWith("{") && !response.startsWith("[") && !url.contains("/debug/")
697                     && !url.contains("/sta_cache_reset")) {
698                 throw new ShellyApiException("Unexpected response: " + response);
699             }
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);
704             }
705             throw ex;
706         }
707         return apiResult;
708     }
709
710     @Override
711     public String getControlUriPrefix(Integer id) {
712         String uri = "";
713         if (profile.isLight || profile.isDimmer) {
714             if (profile.isDuo || profile.isDimmer) {
715                 // Duo + Dimmer
716                 uri = SHELLY_URL_CONTROL_LIGHT;
717             } else {
718                 // Bulb + RGBW2
719                 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
720             }
721         } else {
722             // Roller, Relay
723             uri = SHELLY_URL_CONTROL_RELEAY;
724         }
725         uri = uri + "/" + id;
726         return uri;
727     }
728
729     @Override
730     public int getTimeoutErrors() {
731         return timeoutErrors;
732     }
733
734     @Override
735     public int getTimeoutsRecovered() {
736         return timeoutsRecovered;
737     }
738
739     @Override
740     public void close() {
741     }
742 }