2 * Copyright (c) 2010-2020 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.shelly.internal.api;
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
19 import java.nio.charset.StandardCharsets;
20 import java.util.Base64;
21 import java.util.HashMap;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jetty.client.HttpClient;
29 import org.eclipse.jetty.client.api.ContentResponse;
30 import org.eclipse.jetty.client.api.Request;
31 import org.eclipse.jetty.http.HttpHeader;
32 import org.eclipse.jetty.http.HttpMethod;
33 import org.eclipse.jetty.http.HttpStatus;
34 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyControlRoller;
35 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySendKeyList;
36 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySenseKeyCode;
37 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsDevice;
38 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsLight;
39 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsStatus;
40 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyShortLightStatus;
41 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusLight;
42 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusRelay;
43 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellyStatusSensor;
44 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
45 import org.openhab.core.library.unit.ImperialUnits;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 import com.google.gson.Gson;
50 import com.google.gson.JsonSyntaxException;
52 import tec.uom.se.unit.Units;
55 * {@link ShellyHttpApi} wraps the Shelly REST API and provides various low level function to access the device api (not
58 * @author Markus Michels - Initial contribution
61 public class ShellyHttpApi {
62 public static final String HTTP_HEADER_AUTH = "Authorization";
63 public static final String HTTP_AUTH_TYPE_BASIC = "Basic";
64 public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
66 private final Logger logger = LoggerFactory.getLogger(ShellyHttpApi.class);
67 private final HttpClient httpClient;
68 private ShellyThingConfiguration config = new ShellyThingConfiguration();
69 private String thingName;
70 private final Gson gson = new Gson();
71 private int timeoutErrors = 0;
72 private int timeoutsRecovered = 0;
74 private ShellyDeviceProfile profile = new ShellyDeviceProfile();
76 public ShellyHttpApi(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
77 this.httpClient = httpClient;
78 this.thingName = thingName;
79 setConfig(thingName, config);
80 profile.initFromThingType(thingName);
83 public void setConfig(String thingName, ShellyThingConfiguration config) {
84 this.thingName = thingName;
88 public ShellySettingsDevice getDevInfo() throws ShellyApiException {
89 return callApi(SHELLY_URL_DEVINFO, ShellySettingsDevice.class);
93 * Initialize the device profile
95 * @param thingType Type of DEVICE as returned from the thing properties (based on discovery)
96 * @return Initialized ShellyDeviceProfile
97 * @throws ShellyApiException
99 public ShellyDeviceProfile getDeviceProfile(String thingType) throws ShellyApiException {
100 String json = request(SHELLY_URL_SETTINGS);
101 if (json.contains("\"type\":\"SHDM-")) {
102 logger.trace("{}: Detected a Shelly Dimmer: fix Json (replace lights[] tag with dimmers[]", thingName);
103 json = fixDimmerJson(json);
106 // Map settings to device profile for Light and Sense
107 profile.initialize(thingType, json);
109 // 2nd level initialization
110 profile.thingName = profile.hostname;
111 if (profile.isLight && (profile.numMeters == 0)) {
112 logger.debug("{}: Get number of meters from light status", thingName);
113 ShellyStatusLight status = getLightStatus();
114 profile.numMeters = status.meters != null ? status.meters.size() : 0;
116 if (profile.isSense) {
117 profile.irCodes = getIRCodeList();
118 logger.debug("{}: Sense stored key list loaded, {} entries.", thingName, profile.irCodes.size());
124 public boolean isInitialized() {
125 return profile.initialized;
129 * Get generic device settings/status. Json returned from API will be mapped to a Gson object
131 * @return Device settings/status as ShellySettingsStatus object
132 * @throws ShellyApiException
134 public ShellySettingsStatus getStatus() throws ShellyApiException {
137 json = request(SHELLY_URL_STATUS);
138 // Dimmer2 returns invalid json type for loaderror :-(
139 json = json.replace("\"loaderror\":0,", "\"loaderror\":false,");
140 json = json.replace("\"loaderror\":1,", "\"loaderror\":true,");
141 ShellySettingsStatus status = gson.fromJson(json, ShellySettingsStatus.class);
144 } catch (JsonSyntaxException e) {
145 throw new ShellyApiException("Unable to parse JSON: " + json, e);
149 public ShellyStatusRelay getRelayStatus(Integer relayIndex) throws ShellyApiException {
150 return callApi(SHELLY_URL_STATUS_RELEAY + "/" + relayIndex.toString(), ShellyStatusRelay.class);
153 public ShellyShortLightStatus setRelayTurn(Integer id, String turnMode) throws ShellyApiException {
154 return callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
155 ShellyShortLightStatus.class);
158 public void setBrightness(Integer id, Integer brightness, boolean autoOn) throws ShellyApiException {
159 String turn = autoOn ? SHELLY_LIGHT_TURN + "=" + SHELLY_API_ON + "&" : "";
160 request(getControlUriPrefix(id) + "?" + turn + "brightness=" + brightness.toString());
163 public ShellyControlRoller getRollerStatus(Integer rollerIndex) throws ShellyApiException {
164 String uri = SHELLY_URL_CONTROL_ROLLER + "/" + rollerIndex.toString() + "/pos";
165 return callApi(uri, ShellyControlRoller.class);
168 public void setRollerTurn(Integer relayIndex, String turnMode) throws ShellyApiException {
169 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=" + turnMode);
172 public void setRollerPos(Integer relayIndex, Integer position) throws ShellyApiException {
173 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=to_pos&roller_pos="
174 + position.toString());
177 public void setRollerTimer(Integer relayIndex, Integer timer) throws ShellyApiException {
178 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?timer=" + timer.toString());
181 public ShellyShortLightStatus getLightStatus(Integer index) throws ShellyApiException {
182 return callApi(getControlUriPrefix(index), ShellyShortLightStatus.class);
185 public ShellyStatusSensor getSensorStatus() throws ShellyApiException {
186 ShellyStatusSensor status = callApi(SHELLY_URL_STATUS, ShellyStatusSensor.class);
187 if (profile.isSense) {
188 // complete reported data, map C to F or vice versa: C=(F - 32) * 0.5556;
189 status.tmp.tC = status.tmp.units.equals(SHELLY_TEMP_CELSIUS) ? status.tmp.value
190 : ImperialUnits.FAHRENHEIT.getConverterTo(Units.CELSIUS).convert(getDouble(status.tmp.value))
192 status.tmp.tF = status.tmp.units.equals(SHELLY_TEMP_FAHRENHEIT) ? status.tmp.value
193 : Units.CELSIUS.getConverterTo(ImperialUnits.FAHRENHEIT).convert(getDouble(status.tmp.value))
196 if ((status.charger == null) && (status.externalPower != null)) {
197 // SHelly H&T uses external_power, Sense uses charger
198 status.charger = status.externalPower != 0;
204 public void setTimer(Integer index, String timerName, Double value) throws ShellyApiException {
205 String type = SHELLY_CLASS_RELAY;
206 if (profile.isRoller) {
207 type = SHELLY_CLASS_ROLLER;
208 } else if (profile.isLight) {
209 type = SHELLY_CLASS_LIGHT;
211 String uri = SHELLY_URL_SETTINGS + "/" + type + "/" + index + "?" + timerName + "="
212 + ((Integer) value.intValue()).toString();
216 public void setLedStatus(String ledName, Boolean value) throws ShellyApiException {
217 request(SHELLY_URL_SETTINGS + "?" + ledName + "=" + (value ? SHELLY_API_TRUE : SHELLY_API_FALSE));
220 public ShellySettingsLight getLightSettings() throws ShellyApiException {
221 return callApi(SHELLY_URL_SETTINGS_LIGHT, ShellySettingsLight.class);
224 public ShellyStatusLight getLightStatus() throws ShellyApiException {
225 return callApi(SHELLY_URL_STATUS, ShellyStatusLight.class);
228 public void setLightSetting(String parm, String value) throws ShellyApiException {
229 request(SHELLY_URL_SETTINGS + "?" + parm + "=" + value);
233 * Change between White and Color Mode
236 * @throws ShellyApiException
238 public void setLightMode(String mode) throws ShellyApiException {
239 if (!mode.isEmpty() && !profile.mode.equals(mode)) {
240 setLightSetting(SHELLY_API_MODE, mode);
242 profile.inColor = profile.isLight && profile.mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
247 * Set a single light parameter
249 * @param lightIndex Index of the light, usually 0 for Bulb and 0..3 for RGBW2.
250 * @param parm Name of the parameter (see API spec)
251 * @param value The value
252 * @throws ShellyApiException
254 public void setLightParm(Integer lightIndex, String parm, String value) throws ShellyApiException {
255 // Bulb, RGW2: /<color mode>/<light id>?parm?value
256 // Dimmer: /light/<light id>?parm=value
257 request(getControlUriPrefix(lightIndex) + "?" + parm + "=" + value);
260 public void setLightParms(Integer lightIndex, Map<String, String> parameters) throws ShellyApiException {
261 String url = getControlUriPrefix(lightIndex) + "?";
263 for (String key : parameters.keySet()) {
267 url = url + key + "=" + parameters.get(key);
274 * Retrieve the IR Code list from the Shelly Sense device. The list could be customized by the user. It defines the
275 * symbolic key code, which gets
276 * map into a PRONTO code
278 * @return Map of key codes
279 * @throws ShellyApiException
281 public Map<String, String> getIRCodeList() throws ShellyApiException {
282 String result = request(SHELLY_URL_LIST_IR);
283 // take pragmatic approach to make the returned JSon into named arrays for Gson parsing
284 String keyList = substringAfter(result, "[");
285 keyList = substringBeforeLast(keyList, "]");
286 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("\",\""), "\", \"name\": \"");
287 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("["), "{ \"id\":");
288 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("]"), "} ");
289 String json = "{\"key_codes\" : [" + keyList + "] }";
291 ShellySendKeyList codes = gson.fromJson(json, ShellySendKeyList.class);
292 Map<String, String> list = new HashMap<>();
293 for (ShellySenseKeyCode key : codes.keyCodes) {
294 list.put(key.id, key.name);
300 * Sends a IR key code to the Shelly Sense.
302 * @param keyCode A keyCoud could be a symbolic name (as defined in the key map on the device) or a PRONTO Code in
303 * plain or hex64 format
305 * @throws ShellyApiException
306 * @throws IllegalArgumentException
308 public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
310 if (profile.irCodes.containsKey(keyCode)) {
311 type = SHELLY_IR_CODET_STORED;
312 } else if ((keyCode.length() > 4) && keyCode.contains(" ")) {
313 type = SHELLY_IR_CODET_PRONTO;
315 type = SHELLY_IR_CODET_PRONTO_HEX;
317 String url = SHELLY_URL_SEND_IR + "?type=" + type;
318 if (type.equals(SHELLY_IR_CODET_STORED)) {
319 url = url + "&" + "id=" + keyCode;
320 } else if (type.equals(SHELLY_IR_CODET_PRONTO)) {
321 String code = Base64.getEncoder().encodeToString(keyCode.getBytes(StandardCharsets.UTF_8));
323 throw new IllegalArgumentException("Unable to BASE64 encode the pronto code: " + keyCode);
325 url = url + "&" + SHELLY_IR_CODET_PRONTO + "=" + code;
326 } else if (type.equals(SHELLY_IR_CODET_PRONTO_HEX)) {
327 url = url + "&" + SHELLY_IR_CODET_PRONTO_HEX + "=" + keyCode;
332 public void setSenseSetting(String setting, String value) throws ShellyApiException {
333 request(SHELLY_URL_SETTINGS + "?" + setting + "=" + value);
337 * Set event callback URLs. Depending on the device different event types are supported. In fact all of them will be
338 * redirected to the binding's servlet and act as a trigger to schedule a status update
340 * @param ShellyApiException
341 * @throws ShellyApiException
343 public void setActionURLs() throws ShellyApiException {
346 setSensorEventUrls();
349 private void setRelayEvents() throws ShellyApiException {
350 if (profile.settings.relays != null) {
351 int num = profile.isRoller ? profile.numRollers : profile.numRelays;
352 for (int i = 0; i < num; i++) {
358 private void setDimmerEvents() throws ShellyApiException {
359 if (profile.settings.dimmers != null) {
360 for (int i = 0; i < profile.settings.dimmers.size(); i++) {
363 } else if (profile.isLight) {
369 * Set sensor Action URLs
371 * @throws ShellyApiException
373 private void setSensorEventUrls() throws ShellyApiException, ShellyApiException {
374 if (profile.isSensor) {
375 logger.debug("{}: Set Sensor Reporting URL", thingName);
376 setEventUrl(config.eventsSensorReport, SHELLY_EVENT_SENSORREPORT, SHELLY_EVENT_DARK, SHELLY_EVENT_TWILIGHT,
377 SHELLY_EVENT_FLOOD_DETECTED, SHELLY_EVENT_FLOOD_GONE, SHELLY_EVENT_OPEN, SHELLY_EVENT_CLOSE,
378 SHELLY_EVENT_VIBRATION, SHELLY_EVENT_ALARM_MILD, SHELLY_EVENT_ALARM_HEAVY, SHELLY_EVENT_ALARM_OFF,
379 SHELLY_EVENT_TEMP_OVER, SHELLY_EVENT_TEMP_UNDER);
384 * Set/delete Relay/Roller/Dimmer Action URLs
386 * @param index Device Index (0-based)
387 * @throws ShellyApiException
389 private void setEventUrls(Integer index) throws ShellyApiException {
390 if (profile.isRoller) {
391 setEventUrl(EVENT_TYPE_ROLLER, 0, config.eventsRoller, SHELLY_EVENT_ROLLER_OPEN, SHELLY_EVENT_ROLLER_CLOSE,
392 SHELLY_EVENT_ROLLER_STOP);
393 } else if (profile.isDimmer) {
395 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsButton, SHELLY_EVENT_BTN1_ON, SHELLY_EVENT_BTN1_OFF,
396 SHELLY_EVENT_BTN2_ON, SHELLY_EVENT_BTN2_OFF);
397 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH1, SHELLY_EVENT_LONGPUSH1,
398 SHELLY_EVENT_SHORTPUSH2, SHELLY_EVENT_LONGPUSH2);
401 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
402 } else if (profile.hasRelays) {
403 // Standard relays: btn_xxx, out_xxx, short/longpush URLs
404 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsButton, SHELLY_EVENT_BTN_ON, SHELLY_EVENT_BTN_OFF);
405 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH, SHELLY_EVENT_LONGPUSH);
406 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
407 } else if (profile.isLight) {
409 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
413 private void setEventUrl(boolean enabled, String... eventTypes) throws ShellyApiException {
414 if (config.localIp.isEmpty()) {
415 throw new ShellyApiException(thingName + ": Local IP address was not detected, can't build Callback URL");
417 for (String eventType : eventTypes) {
418 if (profile.containsEventUrl(eventType)) {
419 // H&T adds the type=xx to report_url itself, so we need to ommit here
420 String eclass = profile.isSensor ? EVENT_TYPE_SENSORDATA : eventType;
421 String urlParm = eventType.contains("temp") || profile.isHT ? "" : "?type=" + eventType;
422 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
423 + profile.thingName + "/" + eclass + urlParm;
424 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
425 String testUrl = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
426 if (!enabled && !profile.settingsJson.contains(testUrl)) {
427 // Don't set URL to null when the current one doesn't point to this OH
428 // Don't interfere with a 3rd party App
431 if (!profile.settingsJson.contains(testUrl)) {
432 // Current Action URL is != new URL
433 logger.debug("{}: Set new url for event type {}: {}", thingName, eventType, newUrl);
434 request(SHELLY_URL_SETTINGS + "?" + mkEventUrl(eventType) + "=" + urlEncode(newUrl));
440 private void setEventUrl(String deviceClass, Integer index, boolean enabled, String... eventTypes)
441 throws ShellyApiException {
442 for (String eventType : eventTypes) {
443 if (profile.containsEventUrl(eventType)) {
444 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
445 + profile.thingName + "/" + deviceClass + "/" + index + "?type=" + eventType;
446 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
447 String test = "\"" + mkEventUrl(eventType) + "\":\"" + callBackUrl + "\"";
448 if (!enabled && !profile.settingsJson.contains(test)) {
449 // Don't set URL to null when the current one doesn't point to this OH
450 // Don't interfere with a 3rd party App
453 test = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
454 if (!profile.settingsJson.contains(test)) {
455 // Current Action URL is != new URL
456 logger.debug("{}: Set URL for type {} to {}", thingName, eventType, newUrl);
457 request(SHELLY_URL_SETTINGS + "/" + deviceClass + "/" + index + "?" + mkEventUrl(eventType) + "="
458 + urlEncode(newUrl));
464 private static String mkEventUrl(String eventType) {
465 return eventType + SHELLY_EVENTURL_SUFFIX;
469 * Submit GET request and return response, check for invalid responses
471 * @param uri: URI (e.g. "/settings")
473 public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
475 String json = request(uri);
476 return gson.fromJson(json, classOfT);
477 } catch (JsonSyntaxException e) {
478 throw new ShellyApiException("Unable to convert JSON", e);
482 private String request(String uri) throws ShellyApiException {
483 ShellyApiResult apiResult = new ShellyApiResult();
485 boolean timeout = false;
486 while (retries > 0) {
488 apiResult = innerRequest(HttpMethod.GET, uri);
490 logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
494 return apiResult.response; // successful
495 } catch (ShellyApiException e) {
496 if ((!e.isTimeout() && !apiResult.isHttpServerError()) || profile.hasBattery || (retries == 0)) {
497 // Sensor in sleep mode or API exception for non-battery device or retry counter expired
498 throw e; // non-timeout exception
503 timeoutErrors++; // count the retries
504 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
507 throw new ShellyApiException("Inconsistent API result or Timeout"); // successful
510 private ShellyApiResult innerRequest(HttpMethod method, String uri) throws ShellyApiException {
511 Request request = null;
512 String url = "http://" + config.deviceIp + uri;
513 ShellyApiResult apiResult = new ShellyApiResult(method.toString(), url);
516 request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
517 TimeUnit.MILLISECONDS);
519 if (!config.userId.isEmpty()) {
520 String value = config.userId + ":" + config.password;
521 request.header(HTTP_HEADER_AUTH,
522 HTTP_AUTH_TYPE_BASIC + " " + Base64.getEncoder().encodeToString(value.getBytes()));
524 request.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON);
525 logger.trace("{}: HTTP {} for {}", thingName, method, url);
527 // Do request and get response
528 ContentResponse contentResponse = request.send();
529 apiResult = new ShellyApiResult(contentResponse);
530 String response = contentResponse.getContentAsString().replace("\t", "").replace("\r\n", "").trim();
531 logger.trace("{}: HTTP Response {}: {}", thingName, contentResponse.getStatus(), response);
533 // validate response, API errors are reported as Json
534 if (contentResponse.getStatus() != HttpStatus.OK_200) {
535 throw new ShellyApiException(apiResult);
537 if (response == null || response.isEmpty() || !response.startsWith("{") && !response.startsWith("[")) {
538 throw new ShellyApiException("Unexpected response: " + response);
540 } catch (ExecutionException | InterruptedException | TimeoutException | IllegalArgumentException e) {
541 ShellyApiException ex = new ShellyApiException(apiResult, e);
542 if (!ex.isTimeout()) { // will be handled by the caller
543 logger.trace("{}: API call returned exception", thingName, ex);
550 public String getControlUriPrefix(Integer id) {
552 if (profile.isLight || profile.isDimmer) {
553 if (profile.isDuo || profile.isDimmer) {
555 uri = SHELLY_URL_CONTROL_LIGHT;
558 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
562 uri = SHELLY_URL_CONTROL_RELEAY;
564 uri = uri + "/" + id;
568 public int getTimeoutErrors() {
569 return timeoutErrors;
572 public int getTimeoutsRecovered() {
573 return timeoutsRecovered;