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