2 * Copyright (c) 2010-2023 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.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.discovery.ShellyThingCreator.*;
18 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
20 import java.util.HashMap;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsDimmer;
28 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsGlobal;
29 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsInput;
30 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRelay;
31 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRgbwLight;
32 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
33 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyThermnostat;
34 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
38 import com.google.gson.Gson;
41 * The {@link ShellyDeviceProfile} creates a device profile based on the settings returned from the API's /settings
42 * call. This is used to be more dynamic in controlling the device, but also to overcome some issues in the API (e.g.
43 * RGBW2 returns "no meter" even it has one)
45 * @author Markus Michels - Initial contribution
48 public class ShellyDeviceProfile {
49 private final Logger logger = LoggerFactory.getLogger(ShellyDeviceProfile.class);
50 private static final Pattern VERSION_PATTERN = Pattern.compile("v\\d+\\.\\d+\\.\\d+(-[a-z0-9]*)?");
52 public boolean initialized = false; // true when initialized
54 public String thingName = "";
55 public String deviceType = "";
56 public boolean extFeatures = false;
58 public String settingsJson = "";
59 public ShellySettingsGlobal settings = new ShellySettingsGlobal();
60 public ShellySettingsStatus status = new ShellySettingsStatus();
62 public String hostname = "";
63 public String name = "";
64 public String model = "";
65 public String mode = "";
66 public boolean discoverable = true;
67 public boolean auth = false;
68 public boolean alwaysOn = true;
69 public boolean isGen2 = false;
71 public String hwRev = "";
72 public String hwBatchId = "";
73 public String mac = "";
74 public String fwVersion = "";
75 public String fwDate = "";
77 public boolean hasRelays = false; // true if it has at least 1 power meter
78 public int numRelays = 0; // number of relays/outputs
79 public int numRollers = 0; // number of Rollers, usually 1
80 public boolean isRoller = false; // true for Shelly2 in roller mode
81 public boolean isDimmer = false; // true for a Shelly Dimmer (SHDM-1)
82 public int numInputs = 0; // number of inputs
84 public int numMeters = 0;
85 public boolean isEMeter = false; // true for ShellyEM/3EM
87 public boolean isLight = false; // true if it is a Shelly Bulb/RGBW2
88 public boolean isBulb = false; // true only if it is a Bulb
89 public boolean isDuo = false; // true only if it is a Duo
90 public boolean isRGBW2 = false; // true only if it a RGBW2
91 public boolean inColor = false; // true if bulb/rgbw2 is in color mode
93 public boolean isSensor = false; // true for HT & Smoke
94 public boolean hasBattery = false; // true if battery device
95 public boolean isSense = false; // true if thing is a Shelly Sense
96 public boolean isMotion = false; // true if thing is a Shelly Sense
97 public boolean isHT = false; // true for H&T
98 public boolean isDW = false; // true for Door Window sensor
99 public boolean isButton = false; // true for a Shelly Button 1
100 public boolean isIX = false; // true for a Shelly IX
101 public boolean isTRV = false; // true for a Shelly TRV
102 public boolean isSmoke = false; // true for Shelly Smoke
104 public int minTemp = 0; // Bulb/Duo: Min Light Temp
105 public int maxTemp = 0; // Bulb/Duo: Max Light Temp
107 public int updatePeriod = 2 * UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
109 public String coiotEndpoint = "";
111 public Map<String, String> irCodes = new HashMap<>(); // Sense: list of stored IR codes
113 public ShellyDeviceProfile() {
116 public ShellyDeviceProfile initialize(String thingType, String jsonIn) throws ShellyApiException {
117 Gson gson = new Gson();
121 initFromThingType(thingType);
123 String json = jsonIn;
124 if (json.contains("\"ext_temperature\":{\"0\":[{")) {
125 // Shelly UNI uses ext_temperature array, reformat to avoid GSON exception
126 json = json.replace("ext_temperature", "ext_temperature_array");
129 settings = fromJson(gson, json, ShellySettingsGlobal.class);
132 name = getString(settings.name);
133 deviceType = getString(settings.device.type);
134 mac = getString(settings.device.mac);
135 hostname = settings.device.hostname != null && !settings.device.hostname.isEmpty()
136 ? settings.device.hostname.toLowerCase()
137 : "shelly-" + mac.toUpperCase().substring(6, 11);
138 mode = getString(settings.mode).toLowerCase();
139 hwRev = settings.hwinfo != null ? getString(settings.hwinfo.hwRevision) : "";
140 hwBatchId = settings.hwinfo != null ? getString(settings.hwinfo.batchId.toString()) : "";
141 fwDate = substringBefore(settings.fw, "/");
142 fwVersion = extractFwVersion(settings.fw);
143 ShellyVersionDTO version = new ShellyVersionDTO();
144 extFeatures = version.compare(fwVersion, SHELLY_API_FW_110) >= 0;
145 discoverable = (settings.discoverable == null) || settings.discoverable;
147 isRoller = mode.equalsIgnoreCase(SHELLY_MODE_ROLLER);
148 inColor = isLight && mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
150 numRelays = !isLight ? getInteger(settings.device.numOutputs) : 0;
151 if ((numRelays > 0) && (settings.relays == null)) {
154 hasRelays = (numRelays > 0) || isDimmer;
155 numRollers = getInteger(settings.device.numRollers);
156 numInputs = settings.inputs != null ? settings.inputs.size() : hasRelays ? isRoller ? 2 : 1 : 0;
158 isEMeter = settings.emeters != null;
159 numMeters = !isEMeter ? getInteger(settings.device.numMeters) : getInteger(settings.device.numEMeters);
160 if ((numMeters == 0) && isLight) {
161 // RGBW2 doesn't report, but has one
162 numMeters = inColor ? 1 : getInteger(settings.device.numOutputs);
169 public boolean containsEventUrl(String eventType) {
170 return containsEventUrl(settingsJson, eventType);
173 public boolean containsEventUrl(String json, String eventType) {
174 String settings = json.toLowerCase();
175 return settings.contains((eventType + SHELLY_EVENTURL_SUFFIX).toLowerCase());
178 public boolean isInitialized() {
182 public void initFromThingType(String name) {
183 String thingType = (name.contains("-") ? substringBefore(name, "-") : name).toLowerCase().trim();
184 if (thingType.isEmpty()) {
188 isDimmer = deviceType.equalsIgnoreCase(SHELLYDT_DIMMER) || deviceType.equalsIgnoreCase(SHELLYDT_DIMMER2);
189 isBulb = thingType.equals(THING_TYPE_SHELLYBULB_STR);
190 isDuo = thingType.equals(THING_TYPE_SHELLYDUO_STR) || thingType.equals(THING_TYPE_SHELLYVINTAGE_STR)
191 || thingType.equals(THING_TYPE_SHELLYDUORGBW_STR);
192 isRGBW2 = thingType.startsWith(THING_TYPE_SHELLYRGBW2_PREFIX);
193 isLight = isBulb || isDuo || isRGBW2;
195 minTemp = isBulb ? MIN_COLOR_TEMP_BULB : MIN_COLOR_TEMP_DUO;
196 maxTemp = isBulb ? MAX_COLOR_TEMP_BULB : MAX_COLOR_TEMP_DUO;
199 boolean isFlood = thingType.equals(THING_TYPE_SHELLYFLOOD_STR);
200 isSmoke = thingType.equals(THING_TYPE_SHELLYSMOKE_STR) || thingType.equals(THING_TYPE_SHELLYPLUSSMOKE_STR);
201 boolean isGas = thingType.equals(THING_TYPE_SHELLYGAS_STR);
202 boolean isUNI = thingType.equals(THING_TYPE_SHELLYUNI_STR);
203 isHT = thingType.equals(THING_TYPE_SHELLYHT_STR) || thingType.equals(THING_TYPE_SHELLYPLUSHT_STR);
204 isDW = thingType.equals(THING_TYPE_SHELLYDOORWIN_STR) || thingType.equals(THING_TYPE_SHELLYDOORWIN2_STR);
205 isMotion = thingType.startsWith(THING_TYPE_SHELLYMOTION_STR);
206 isSense = thingType.equals(THING_TYPE_SHELLYSENSE_STR);
207 isIX = thingType.equals(THING_TYPE_SHELLYIX3_STR) || thingType.equals(THING_TYPE_SHELLYPLUSI4_STR)
208 || thingType.equals(THING_TYPE_SHELLYPLUSI4DC_STR);
209 isButton = thingType.equals(THING_TYPE_SHELLYBUTTON1_STR) || thingType.equals(THING_TYPE_SHELLYBUTTON2_STR);
210 isSensor = isHT || isFlood || isDW || isSmoke || isGas || isButton || isUNI || isMotion || isSense || isTRV;
211 hasBattery = isHT || isFlood || isDW || isSmoke || isButton || isMotion || isTRV;
212 isTRV = thingType.equals(THING_TYPE_SHELLYTRV_STR);
214 alwaysOn = !hasBattery || isMotion || isSense; // true means: device is reachable all the time (no sleep mode)
217 public void updateFromStatus(ShellySettingsStatus status) {
219 // Dimmer-2 doesn't report inputs under /settings, only on /status, we need to update that info after init
220 if (status.inputs != null) {
221 numInputs = status.inputs.size();
223 } else if (status.input != null) {
229 public String getControlGroup(int i) {
231 logger.debug("{}: Invalid index {} for getControlGroup()", thingName, i);
236 return CHANNEL_GROUP_DIMMER_CONTROL;
237 } else if (isRoller) {
238 return numRollers <= 1 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
239 } else if (isDimmer) {
240 return CHANNEL_GROUP_RELAY_CONTROL;
241 } else if (hasRelays) {
242 return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
243 } else if (isRGBW2) {
244 return settings.lights == null || settings.lights.size() <= 1 ? CHANNEL_GROUP_LIGHT_CONTROL
245 : CHANNEL_GROUP_LIGHT_CHANNEL + idx;
246 } else if (isLight) {
247 return CHANNEL_GROUP_LIGHT_CONTROL;
248 } else if (isButton) {
249 return CHANNEL_GROUP_STATUS;
250 } else if (isSensor) {
251 return CHANNEL_GROUP_SENSOR;
255 return numRelays == 1 ? CHANNEL_GROUP_STATUS : CHANNEL_GROUP_STATUS + idx;
258 public String getMeterGroup(int idx) {
259 return numMeters > 1 ? CHANNEL_GROUP_METER + (idx + 1) : CHANNEL_GROUP_METER;
262 public String getInputGroup(int i) {
263 int idx = i + 1; // group names are 1-based
265 return CHANNEL_GROUP_LIGHT_CONTROL;
267 return CHANNEL_GROUP_STATUS + idx;
268 } else if (isButton) {
269 return CHANNEL_GROUP_STATUS;
270 } else if (isRoller) {
271 return numRelays <= 2 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
273 // Device has 1 input per relay: 0=off, 1+2 depend on switch mode
274 return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
278 public String getInputSuffix(int i) {
279 int idx = i + 1; // channel names are 1-based
280 if (isRGBW2 || isIX) {
281 return ""; // RGBW2 has only 1 channel
282 } else if (isRoller || isDimmer) {
283 // Roller has 2 relays, but it will be mapped to 1 roller with 2 inputs
284 return String.valueOf(idx);
285 } else if (hasRelays) {
286 return numRelays == 1 && numInputs >= 2 ? String.valueOf(idx) : "";
291 @SuppressWarnings("null")
292 public boolean inButtonMode(int idx) {
294 logger.debug("{}: Invalid index {} for inButtonMode()", thingName, idx);
300 } else if (isIX && settings.inputs != null && idx < settings.inputs.size()) {
301 ShellySettingsInput input = settings.inputs.get(idx);
302 btnType = getString(input.btnType);
303 } else if (isDimmer) {
304 if (settings.dimmers != null) {
305 ShellySettingsDimmer dimmer = settings.dimmers.get(0);
306 btnType = dimmer.btnType;
308 } else if (settings.relays != null) {
309 if (numRelays == 1) {
310 ShellySettingsRelay relay = settings.relays.get(0);
311 if (relay.btnType != null) {
312 btnType = getString(relay.btnType);
314 // Shelly 1L has 2 inputs
315 btnType = idx == 0 ? getString(relay.btnType1) : getString(relay.btnType2);
317 } else if (idx < settings.relays.size()) {
318 // only one input channel
319 ShellySettingsRelay relay = settings.relays.get(idx);
320 btnType = getString(relay.btnType);
322 } else if (isRGBW2 && (settings.lights != null) && (idx < settings.lights.size())) {
323 ShellySettingsRgbwLight light = settings.lights.get(idx);
324 btnType = light.btnType;
327 return btnType.equalsIgnoreCase(SHELLY_BTNT_MOMENTARY) || btnType.equalsIgnoreCase(SHELLY_BTNT_MOM_ON_RELEASE)
328 || btnType.equalsIgnoreCase(SHELLY_BTNT_ONE_BUTTON) || btnType.equalsIgnoreCase(SHELLY_BTNT_TWO_BUTTON)
329 || btnType.equalsIgnoreCase(SHELLY_BTNT_DETACHED);
332 public int getRollerFav(int id) {
333 if (id >= 0 && getBool(settings.favoritesEnabled) && settings.favorites != null
334 && id < settings.favorites.size()) {
335 return settings.favorites.get(id).pos;
340 public String[] getValveProfileList(int valveId) {
341 if (isTRV && settings.thermostats != null) {
342 int sz = settings.thermostats.size();
344 if (settings.thermostats != null) {
345 ShellyThermnostat t = settings.thermostats.get(valveId);
346 return t.profileNames;
350 return new String[0];
353 public String getValueProfile(int valveId, int profileId) {
355 if (id <= 0 && settings.thermostats != null) {
356 id = settings.thermostats.get(0).profile;
361 public static String extractFwVersion(@Nullable String version) {
362 if (version != null) {
364 // 20210319-122304/v.1.10-Dimmer1-gfd4cc10 (with v.1. instead of v1.)
365 // 20220809-125346/v1.12-g99f7e0b (.0 in 1.12.0 missing)
366 String vers = version.replace("/v.1.10-", "/v1.10.0-") //
367 .replace("/v1.12-", "/v1.12.0");
369 // Extract version from string, e.g. 20210226-091047/v1.10.0-rc2-89-g623b41ec0-master
370 Matcher matcher = VERSION_PATTERN.matcher(vers);
371 if (matcher.find()) {
372 return matcher.group(0);
378 public boolean coiotEnabled() {
379 if ((settings.coiot != null) && (settings.coiot.enabled != null)) {
380 return settings.coiot.enabled;
383 // If device is not yet intialized or the enabled property is missing we assume that CoIoT is enabled