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.openhab.core.library.unit.SIUnits;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
50 import com.google.gson.Gson;
51 import com.google.gson.JsonSyntaxException;
54 * {@link ShellyHttpApi} wraps the Shelly REST API and provides various low level function to access the device api (not
57 * @author Markus Michels - Initial contribution
60 public class ShellyHttpApi {
61 public static final String HTTP_HEADER_AUTH = "Authorization";
62 public static final String HTTP_AUTH_TYPE_BASIC = "Basic";
63 public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
65 private final Logger logger = LoggerFactory.getLogger(ShellyHttpApi.class);
66 private final HttpClient httpClient;
67 private ShellyThingConfiguration config = new ShellyThingConfiguration();
68 private String thingName;
69 private final Gson gson = new Gson();
70 private int timeoutErrors = 0;
71 private int timeoutsRecovered = 0;
73 private ShellyDeviceProfile profile = new ShellyDeviceProfile();
75 public ShellyHttpApi(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
76 this.httpClient = httpClient;
77 this.thingName = thingName;
78 setConfig(thingName, config);
79 profile.initFromThingType(thingName);
82 public void setConfig(String thingName, ShellyThingConfiguration config) {
83 this.thingName = thingName;
87 public ShellySettingsDevice getDevInfo() throws ShellyApiException {
88 return callApi(SHELLY_URL_DEVINFO, ShellySettingsDevice.class);
92 * Initialize the device profile
94 * @param thingType Type of DEVICE as returned from the thing properties (based on discovery)
95 * @return Initialized ShellyDeviceProfile
96 * @throws ShellyApiException
98 public ShellyDeviceProfile getDeviceProfile(String thingType) throws ShellyApiException {
99 String json = request(SHELLY_URL_SETTINGS);
100 if (json.contains("\"type\":\"SHDM-")) {
101 logger.trace("{}: Detected a Shelly Dimmer: fix Json (replace lights[] tag with dimmers[]", thingName);
102 json = fixDimmerJson(json);
105 // Map settings to device profile for Light and Sense
106 profile.initialize(thingType, json);
108 // 2nd level initialization
109 profile.thingName = profile.hostname;
110 if (profile.isLight && (profile.numMeters == 0)) {
111 logger.debug("{}: Get number of meters from light status", thingName);
112 ShellyStatusLight status = getLightStatus();
113 profile.numMeters = status.meters != null ? status.meters.size() : 0;
115 if (profile.isSense) {
116 profile.irCodes = getIRCodeList();
117 logger.debug("{}: Sense stored key list loaded, {} entries.", thingName, profile.irCodes.size());
123 public boolean isInitialized() {
124 return profile.initialized;
128 * Get generic device settings/status. Json returned from API will be mapped to a Gson object
130 * @return Device settings/status as ShellySettingsStatus object
131 * @throws ShellyApiException
133 public ShellySettingsStatus getStatus() throws ShellyApiException {
136 json = request(SHELLY_URL_STATUS);
137 // Dimmer2 returns invalid json type for loaderror :-(
138 json = json.replace("\"loaderror\":0,", "\"loaderror\":false,");
139 json = json.replace("\"loaderror\":1,", "\"loaderror\":true,");
140 ShellySettingsStatus status = gson.fromJson(json, ShellySettingsStatus.class);
143 } catch (JsonSyntaxException e) {
144 throw new ShellyApiException("Unable to parse JSON: " + json, e);
148 public ShellyStatusRelay getRelayStatus(Integer relayIndex) throws ShellyApiException {
149 return callApi(SHELLY_URL_STATUS_RELEAY + "/" + relayIndex.toString(), ShellyStatusRelay.class);
152 public ShellyShortLightStatus setRelayTurn(Integer id, String turnMode) throws ShellyApiException {
153 return callApi(getControlUriPrefix(id) + "?" + SHELLY_LIGHT_TURN + "=" + turnMode.toLowerCase(),
154 ShellyShortLightStatus.class);
157 public void setBrightness(Integer id, Integer brightness, boolean autoOn) throws ShellyApiException {
158 String turn = autoOn ? SHELLY_LIGHT_TURN + "=" + SHELLY_API_ON + "&" : "";
159 request(getControlUriPrefix(id) + "?" + turn + "brightness=" + brightness.toString());
162 public ShellyControlRoller getRollerStatus(Integer rollerIndex) throws ShellyApiException {
163 String uri = SHELLY_URL_CONTROL_ROLLER + "/" + rollerIndex.toString() + "/pos";
164 return callApi(uri, ShellyControlRoller.class);
167 public void setRollerTurn(Integer relayIndex, String turnMode) throws ShellyApiException {
168 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=" + turnMode);
171 public void setRollerPos(Integer relayIndex, Integer position) throws ShellyApiException {
172 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?go=to_pos&roller_pos="
173 + position.toString());
176 public void setRollerTimer(Integer relayIndex, Integer timer) throws ShellyApiException {
177 request(SHELLY_URL_CONTROL_ROLLER + "/" + relayIndex.toString() + "?timer=" + timer.toString());
180 public ShellyShortLightStatus getLightStatus(Integer index) throws ShellyApiException {
181 return callApi(getControlUriPrefix(index), ShellyShortLightStatus.class);
184 public ShellyStatusSensor getSensorStatus() throws ShellyApiException {
185 ShellyStatusSensor status = callApi(SHELLY_URL_STATUS, ShellyStatusSensor.class);
186 if (profile.isSense) {
187 // complete reported data, map C to F or vice versa: C=(F - 32) * 0.5556;
188 status.tmp.tC = status.tmp.units.equals(SHELLY_TEMP_CELSIUS) ? status.tmp.value
189 : ImperialUnits.FAHRENHEIT.getConverterTo(SIUnits.CELSIUS).convert(getDouble(status.tmp.value))
191 status.tmp.tF = status.tmp.units.equals(SHELLY_TEMP_FAHRENHEIT) ? status.tmp.value
192 : SIUnits.CELSIUS.getConverterTo(ImperialUnits.FAHRENHEIT).convert(getDouble(status.tmp.value))
195 if ((status.charger == null) && (status.externalPower != null)) {
196 // SHelly H&T uses external_power, Sense uses charger
197 status.charger = status.externalPower != 0;
203 public void setTimer(Integer index, String timerName, Double value) throws ShellyApiException {
204 String type = SHELLY_CLASS_RELAY;
205 if (profile.isRoller) {
206 type = SHELLY_CLASS_ROLLER;
207 } else if (profile.isLight) {
208 type = SHELLY_CLASS_LIGHT;
210 String uri = SHELLY_URL_SETTINGS + "/" + type + "/" + index + "?" + timerName + "="
211 + ((Integer) value.intValue()).toString();
215 public void setLedStatus(String ledName, Boolean value) throws ShellyApiException {
216 request(SHELLY_URL_SETTINGS + "?" + ledName + "=" + (value ? SHELLY_API_TRUE : SHELLY_API_FALSE));
219 public ShellySettingsLight getLightSettings() throws ShellyApiException {
220 return callApi(SHELLY_URL_SETTINGS_LIGHT, ShellySettingsLight.class);
223 public ShellyStatusLight getLightStatus() throws ShellyApiException {
224 return callApi(SHELLY_URL_STATUS, ShellyStatusLight.class);
227 public void setLightSetting(String parm, String value) throws ShellyApiException {
228 request(SHELLY_URL_SETTINGS + "?" + parm + "=" + value);
232 * Change between White and Color Mode
235 * @throws ShellyApiException
237 public void setLightMode(String mode) throws ShellyApiException {
238 if (!mode.isEmpty() && !profile.mode.equals(mode)) {
239 setLightSetting(SHELLY_API_MODE, mode);
241 profile.inColor = profile.isLight && profile.mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
246 * Set a single light parameter
248 * @param lightIndex Index of the light, usually 0 for Bulb and 0..3 for RGBW2.
249 * @param parm Name of the parameter (see API spec)
250 * @param value The value
251 * @throws ShellyApiException
253 public void setLightParm(Integer lightIndex, String parm, String value) throws ShellyApiException {
254 // Bulb, RGW2: /<color mode>/<light id>?parm?value
255 // Dimmer: /light/<light id>?parm=value
256 request(getControlUriPrefix(lightIndex) + "?" + parm + "=" + value);
259 public void setLightParms(Integer lightIndex, Map<String, String> parameters) throws ShellyApiException {
260 String url = getControlUriPrefix(lightIndex) + "?";
262 for (String key : parameters.keySet()) {
266 url = url + key + "=" + parameters.get(key);
273 * Retrieve the IR Code list from the Shelly Sense device. The list could be customized by the user. It defines the
274 * symbolic key code, which gets
275 * map into a PRONTO code
277 * @return Map of key codes
278 * @throws ShellyApiException
280 public Map<String, String> getIRCodeList() throws ShellyApiException {
281 String result = request(SHELLY_URL_LIST_IR);
282 // take pragmatic approach to make the returned JSon into named arrays for Gson parsing
283 String keyList = substringAfter(result, "[");
284 keyList = substringBeforeLast(keyList, "]");
285 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("\",\""), "\", \"name\": \"");
286 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("["), "{ \"id\":");
287 keyList = keyList.replaceAll(java.util.regex.Pattern.quote("]"), "} ");
288 String json = "{\"key_codes\" : [" + keyList + "] }";
290 ShellySendKeyList codes = gson.fromJson(json, ShellySendKeyList.class);
291 Map<String, String> list = new HashMap<>();
292 for (ShellySenseKeyCode key : codes.keyCodes) {
293 list.put(key.id, key.name);
299 * Sends a IR key code to the Shelly Sense.
301 * @param keyCode A keyCoud could be a symbolic name (as defined in the key map on the device) or a PRONTO Code in
302 * plain or hex64 format
304 * @throws ShellyApiException
305 * @throws IllegalArgumentException
307 public void sendIRKey(String keyCode) throws ShellyApiException, IllegalArgumentException {
309 if (profile.irCodes.containsKey(keyCode)) {
310 type = SHELLY_IR_CODET_STORED;
311 } else if ((keyCode.length() > 4) && keyCode.contains(" ")) {
312 type = SHELLY_IR_CODET_PRONTO;
314 type = SHELLY_IR_CODET_PRONTO_HEX;
316 String url = SHELLY_URL_SEND_IR + "?type=" + type;
317 if (type.equals(SHELLY_IR_CODET_STORED)) {
318 url = url + "&" + "id=" + keyCode;
319 } else if (type.equals(SHELLY_IR_CODET_PRONTO)) {
320 String code = Base64.getEncoder().encodeToString(keyCode.getBytes(StandardCharsets.UTF_8));
322 throw new IllegalArgumentException("Unable to BASE64 encode the pronto code: " + keyCode);
324 url = url + "&" + SHELLY_IR_CODET_PRONTO + "=" + code;
325 } else if (type.equals(SHELLY_IR_CODET_PRONTO_HEX)) {
326 url = url + "&" + SHELLY_IR_CODET_PRONTO_HEX + "=" + keyCode;
331 public void setSenseSetting(String setting, String value) throws ShellyApiException {
332 request(SHELLY_URL_SETTINGS + "?" + setting + "=" + value);
336 * Set event callback URLs. Depending on the device different event types are supported. In fact all of them will be
337 * redirected to the binding's servlet and act as a trigger to schedule a status update
339 * @param ShellyApiException
340 * @throws ShellyApiException
342 public void setActionURLs() throws ShellyApiException {
345 setSensorEventUrls();
348 private void setRelayEvents() throws ShellyApiException {
349 if (profile.settings.relays != null) {
350 int num = profile.isRoller ? profile.numRollers : profile.numRelays;
351 for (int i = 0; i < num; i++) {
357 private void setDimmerEvents() throws ShellyApiException {
358 if (profile.settings.dimmers != null) {
359 for (int i = 0; i < profile.settings.dimmers.size(); i++) {
362 } else if (profile.isLight) {
368 * Set sensor Action URLs
370 * @throws ShellyApiException
372 private void setSensorEventUrls() throws ShellyApiException, ShellyApiException {
373 if (profile.isSensor) {
374 logger.debug("{}: Set Sensor Reporting URL", thingName);
375 setEventUrl(config.eventsSensorReport, SHELLY_EVENT_SENSORREPORT, SHELLY_EVENT_DARK, SHELLY_EVENT_TWILIGHT,
376 SHELLY_EVENT_FLOOD_DETECTED, SHELLY_EVENT_FLOOD_GONE, SHELLY_EVENT_OPEN, SHELLY_EVENT_CLOSE,
377 SHELLY_EVENT_VIBRATION, SHELLY_EVENT_ALARM_MILD, SHELLY_EVENT_ALARM_HEAVY, SHELLY_EVENT_ALARM_OFF,
378 SHELLY_EVENT_TEMP_OVER, SHELLY_EVENT_TEMP_UNDER);
383 * Set/delete Relay/Roller/Dimmer Action URLs
385 * @param index Device Index (0-based)
386 * @throws ShellyApiException
388 private void setEventUrls(Integer index) throws ShellyApiException {
389 if (profile.isRoller) {
390 setEventUrl(EVENT_TYPE_ROLLER, 0, config.eventsRoller, SHELLY_EVENT_ROLLER_OPEN, SHELLY_EVENT_ROLLER_CLOSE,
391 SHELLY_EVENT_ROLLER_STOP);
392 } else if (profile.isDimmer) {
394 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsButton, SHELLY_EVENT_BTN1_ON, SHELLY_EVENT_BTN1_OFF,
395 SHELLY_EVENT_BTN2_ON, SHELLY_EVENT_BTN2_OFF);
396 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH1, SHELLY_EVENT_LONGPUSH1,
397 SHELLY_EVENT_SHORTPUSH2, SHELLY_EVENT_LONGPUSH2);
400 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
401 } else if (profile.hasRelays) {
402 // Standard relays: btn_xxx, out_xxx, short/longpush URLs
403 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsButton, SHELLY_EVENT_BTN_ON, SHELLY_EVENT_BTN_OFF);
404 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsPush, SHELLY_EVENT_SHORTPUSH, SHELLY_EVENT_LONGPUSH);
405 setEventUrl(EVENT_TYPE_RELAY, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
406 } else if (profile.isLight) {
408 setEventUrl(EVENT_TYPE_LIGHT, index, config.eventsSwitch, SHELLY_EVENT_OUT_ON, SHELLY_EVENT_OUT_OFF);
412 private void setEventUrl(boolean enabled, String... eventTypes) throws ShellyApiException {
413 if (config.localIp.isEmpty()) {
414 throw new ShellyApiException(thingName + ": Local IP address was not detected, can't build Callback URL");
416 for (String eventType : eventTypes) {
417 if (profile.containsEventUrl(eventType)) {
418 // H&T adds the type=xx to report_url itself, so we need to ommit here
419 String eclass = profile.isSensor ? EVENT_TYPE_SENSORDATA : eventType;
420 String urlParm = eventType.contains("temp") || profile.isHT ? "" : "?type=" + eventType;
421 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
422 + profile.thingName + "/" + eclass + urlParm;
423 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
424 String testUrl = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
425 if (!enabled && !profile.settingsJson.contains(testUrl)) {
426 // Don't set URL to null when the current one doesn't point to this OH
427 // Don't interfere with a 3rd party App
430 if (!profile.settingsJson.contains(testUrl)) {
431 // Current Action URL is != new URL
432 logger.debug("{}: Set new url for event type {}: {}", thingName, eventType, newUrl);
433 request(SHELLY_URL_SETTINGS + "?" + mkEventUrl(eventType) + "=" + urlEncode(newUrl));
439 private void setEventUrl(String deviceClass, Integer index, boolean enabled, String... eventTypes)
440 throws ShellyApiException {
441 for (String eventType : eventTypes) {
442 if (profile.containsEventUrl(eventType)) {
443 String callBackUrl = "http://" + config.localIp + ":" + config.localPort + SHELLY_CALLBACK_URI + "/"
444 + profile.thingName + "/" + deviceClass + "/" + index + "?type=" + eventType;
445 String newUrl = enabled ? callBackUrl : SHELLY_NULL_URL;
446 String test = "\"" + mkEventUrl(eventType) + "\":\"" + callBackUrl + "\"";
447 if (!enabled && !profile.settingsJson.contains(test)) {
448 // Don't set URL to null when the current one doesn't point to this OH
449 // Don't interfere with a 3rd party App
452 test = "\"" + mkEventUrl(eventType) + "\":\"" + newUrl + "\"";
453 if (!profile.settingsJson.contains(test)) {
454 // Current Action URL is != new URL
455 logger.debug("{}: Set URL for type {} to {}", thingName, eventType, newUrl);
456 request(SHELLY_URL_SETTINGS + "/" + deviceClass + "/" + index + "?" + mkEventUrl(eventType) + "="
457 + urlEncode(newUrl));
463 private static String mkEventUrl(String eventType) {
464 return eventType + SHELLY_EVENTURL_SUFFIX;
468 * Submit GET request and return response, check for invalid responses
470 * @param uri: URI (e.g. "/settings")
472 public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
474 String json = request(uri);
475 return gson.fromJson(json, classOfT);
476 } catch (JsonSyntaxException e) {
477 throw new ShellyApiException("Unable to convert JSON", e);
481 private String request(String uri) throws ShellyApiException {
482 ShellyApiResult apiResult = new ShellyApiResult();
484 boolean timeout = false;
485 while (retries > 0) {
487 apiResult = innerRequest(HttpMethod.GET, uri);
489 logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
493 return apiResult.response; // successful
494 } catch (ShellyApiException e) {
495 if ((!e.isTimeout() && !apiResult.isHttpServerError()) || profile.hasBattery || (retries == 0)) {
496 // Sensor in sleep mode or API exception for non-battery device or retry counter expired
497 throw e; // non-timeout exception
502 timeoutErrors++; // count the retries
503 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
506 throw new ShellyApiException("Inconsistent API result or Timeout"); // successful
509 private ShellyApiResult innerRequest(HttpMethod method, String uri) throws ShellyApiException {
510 Request request = null;
511 String url = "http://" + config.deviceIp + uri;
512 ShellyApiResult apiResult = new ShellyApiResult(method.toString(), url);
515 request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
516 TimeUnit.MILLISECONDS);
518 if (!config.userId.isEmpty()) {
519 String value = config.userId + ":" + config.password;
520 request.header(HTTP_HEADER_AUTH,
521 HTTP_AUTH_TYPE_BASIC + " " + Base64.getEncoder().encodeToString(value.getBytes()));
523 request.header(HttpHeader.ACCEPT, CONTENT_TYPE_JSON);
524 logger.trace("{}: HTTP {} for {}", thingName, method, url);
526 // Do request and get response
527 ContentResponse contentResponse = request.send();
528 apiResult = new ShellyApiResult(contentResponse);
529 String response = contentResponse.getContentAsString().replace("\t", "").replace("\r\n", "").trim();
530 logger.trace("{}: HTTP Response {}: {}", thingName, contentResponse.getStatus(), response);
532 // validate response, API errors are reported as Json
533 if (contentResponse.getStatus() != HttpStatus.OK_200) {
534 throw new ShellyApiException(apiResult);
536 if (response == null || response.isEmpty() || !response.startsWith("{") && !response.startsWith("[")) {
537 throw new ShellyApiException("Unexpected response: " + response);
539 } catch (ExecutionException | InterruptedException | TimeoutException | IllegalArgumentException e) {
540 ShellyApiException ex = new ShellyApiException(apiResult, e);
541 if (!ex.isTimeout()) { // will be handled by the caller
542 logger.trace("{}: API call returned exception", thingName, ex);
549 public String getControlUriPrefix(Integer id) {
551 if (profile.isLight || profile.isDimmer) {
552 if (profile.isDuo || profile.isDimmer) {
554 uri = SHELLY_URL_CONTROL_LIGHT;
557 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
561 uri = SHELLY_URL_CONTROL_RELEAY;
563 uri = uri + "/" + id;
567 public int getTimeoutErrors() {
568 return timeoutErrors;
571 public int getTimeoutsRecovered() {
572 return timeoutsRecovered;