]> git.basschouten.com Git - openhab-addons.git/blob
f1b3e3a77ea336067bc366158fa6c7ce7976aff5
[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.api;
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.discovery.ShellyThingCreator.*;
18 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
19
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.regex.Matcher;
23 import java.util.regex.Pattern;
24
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;
37
38 import com.google.gson.Gson;
39
40 /**
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)
44  *
45  * @author Markus Michels - Initial contribution
46  */
47 @NonNullByDefault
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]*)?");
51
52     public boolean initialized = false; // true when initialized
53
54     public String thingName = "";
55     public String deviceType = "";
56     public boolean extFeatures = false;
57
58     public String settingsJson = "";
59     public ShellySettingsGlobal settings = new ShellySettingsGlobal();
60     public ShellySettingsStatus status = new ShellySettingsStatus();
61
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;
70     public boolean isBlu = false;
71     public String gateway = "";
72
73     public String hwRev = "";
74     public String hwBatchId = "";
75     public String mac = "";
76     public String fwVersion = "";
77     public String fwDate = "";
78
79     public boolean hasRelays = false; // true if it has at least 1 power meter
80     public int numRelays = 0; // number of relays/outputs
81     public int numRollers = 0; // number of Rollers, usually 1
82     public boolean isRoller = false; // true for Shelly2 in roller mode
83     public boolean isDimmer = false; // true for a Shelly Dimmer (SHDM-1)
84     public int numInputs = 0; // number of inputs
85
86     public int numMeters = 0;
87     public boolean isEMeter = false; // true for ShellyEM/3EM
88
89     public boolean isLight = false; // true if it is a Shelly Bulb/RGBW2
90     public boolean isBulb = false; // true only if it is a Bulb
91     public boolean isDuo = false; // true only if it is a Duo
92     public boolean isRGBW2 = false; // true only if it a RGBW2
93     public boolean inColor = false; // true if bulb/rgbw2 is in color mode
94
95     public boolean isSensor = false; // true for HT & Smoke
96     public boolean hasBattery = false; // true if battery device
97     public boolean isSense = false; // true if thing is a Shelly Sense
98     public boolean isMotion = false; // true if thing is a Shelly Sense
99     public boolean isHT = false; // true for H&T
100     public boolean isDW = false; // true for Door Window sensor
101     public boolean isButton = false; // true for a Shelly Button 1
102     public boolean isIX = false; // true for a Shelly IX
103     public boolean isTRV = false; // true for a Shelly TRV
104     public boolean isSmoke = false; // true for Shelly Smoke
105     public boolean isWall = false; // true: Shelly Wall Display
106     public boolean is3EM = false; // true for Shelly 3EM and Pro 3EM
107     public boolean isEM50 = false; // true for Shelly Pro EM50
108
109     public int minTemp = 0; // Bulb/Duo: Min Light Temp
110     public int maxTemp = 0; // Bulb/Duo: Max Light Temp
111
112     public int updatePeriod = 2 * UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
113
114     public String coiotEndpoint = "";
115
116     public Map<String, String> irCodes = new HashMap<>(); // Sense: list of stored IR codes
117
118     public ShellyDeviceProfile() {
119     }
120
121     public ShellyDeviceProfile initialize(String thingType, String jsonIn) throws ShellyApiException {
122         Gson gson = new Gson();
123
124         initialized = false;
125
126         initFromThingType(thingType);
127
128         String json = jsonIn;
129         if (json.contains("\"ext_temperature\":{\"0\":[{")) {
130             // Shelly UNI uses ext_temperature array, reformat to avoid GSON exception
131             json = json.replace("ext_temperature", "ext_temperature_array");
132         }
133         if (json.contains("\"ext_humidity\":{\"0\":[{")) {
134             // Shelly UNI uses ext_humidity array, reformat to avoid GSON exception
135             json = json.replace("ext_humidity", "ext_humidity_array");
136         }
137         settingsJson = json;
138         settings = fromJson(gson, json, ShellySettingsGlobal.class);
139
140         // General settings
141         name = getString(settings.name);
142         deviceType = getString(settings.device.type);
143         mac = getString(settings.device.mac);
144         hostname = !getString(settings.device.hostname).isEmpty() ? settings.device.hostname.toLowerCase()
145                 : mac.length() >= 12 ? "shelly-" + mac.toUpperCase().substring(6, 11) : "unknown";
146         mode = getString(settings.mode).toLowerCase();
147         hwRev = settings.hwinfo != null ? getString(settings.hwinfo.hwRevision) : "";
148         hwBatchId = settings.hwinfo != null ? getString(settings.hwinfo.batchId.toString()) : "";
149         fwDate = substringBefore(settings.fw, "/");
150         fwVersion = extractFwVersion(settings.fw);
151         ShellyVersionDTO version = new ShellyVersionDTO();
152         extFeatures = version.compare(fwVersion, SHELLY_API_FW_110) >= 0;
153         discoverable = (settings.discoverable == null) || settings.discoverable;
154
155         isRoller = mode.equalsIgnoreCase(SHELLY_MODE_ROLLER);
156         inColor = isLight && mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
157
158         numRelays = !isLight ? getInteger(settings.device.numOutputs) : 0;
159         if ((numRelays > 0) && (settings.relays == null)) {
160             numRelays = 0;
161         }
162         hasRelays = (numRelays > 0) || isDimmer;
163         numRollers = getInteger(settings.device.numRollers);
164         numInputs = settings.inputs != null ? settings.inputs.size() : hasRelays ? isRoller ? 2 : 1 : 0;
165
166         isEMeter = settings.emeters != null;
167         numMeters = !isEMeter ? getInteger(settings.device.numMeters) : getInteger(settings.device.numEMeters);
168         if ((numMeters == 0) && isLight) {
169             // RGBW2 doesn't report, but has one
170             numMeters = inColor ? 1 : getInteger(settings.device.numOutputs);
171         }
172
173         initialized = true;
174         return this;
175     }
176
177     public boolean containsEventUrl(String eventType) {
178         return containsEventUrl(settingsJson, eventType);
179     }
180
181     public boolean containsEventUrl(String json, String eventType) {
182         String settings = json.toLowerCase();
183         return settings.contains((eventType + SHELLY_EVENTURL_SUFFIX).toLowerCase());
184     }
185
186     public boolean isInitialized() {
187         return initialized;
188     }
189
190     public void initFromThingType(String name) {
191         String thingType = (name.contains("-") ? substringBefore(name, "-") : name).toLowerCase().trim();
192         if (thingType.isEmpty()) {
193             return;
194         }
195
196         isBlu = thingType.startsWith("shellyblu"); // e.g. SBBT for BU Button
197
198         isDimmer = deviceType.equalsIgnoreCase(SHELLYDT_DIMMER) || deviceType.equalsIgnoreCase(SHELLYDT_DIMMER2)
199                 || deviceType.equalsIgnoreCase(SHELLYDT_PLUSDIMMERUS)
200                 || thingType.equalsIgnoreCase(THING_TYPE_SHELLYPLUSDIMMERUS_STR);
201         isBulb = thingType.equals(THING_TYPE_SHELLYBULB_STR);
202         isDuo = thingType.equals(THING_TYPE_SHELLYDUO_STR) || thingType.equals(THING_TYPE_SHELLYVINTAGE_STR)
203                 || thingType.equals(THING_TYPE_SHELLYDUORGBW_STR);
204         isRGBW2 = thingType.startsWith(THING_TYPE_SHELLYRGBW2_PREFIX);
205         isLight = isBulb || isDuo || isRGBW2;
206         if (isLight) {
207             minTemp = isBulb ? MIN_COLOR_TEMP_BULB : MIN_COLOR_TEMP_DUO;
208             maxTemp = isBulb ? MAX_COLOR_TEMP_BULB : MAX_COLOR_TEMP_DUO;
209         }
210
211         boolean isFlood = thingType.equals(THING_TYPE_SHELLYFLOOD_STR);
212         isSmoke = thingType.equals(THING_TYPE_SHELLYSMOKE_STR) || thingType.equals(THING_TYPE_SHELLYPLUSSMOKE_STR);
213         boolean isGas = thingType.equals(THING_TYPE_SHELLYGAS_STR);
214         boolean isUNI = thingType.equals(THING_TYPE_SHELLYUNI_STR);
215         isHT = thingType.equals(THING_TYPE_SHELLYHT_STR) || thingType.equals(THING_TYPE_SHELLYPLUSHT_STR);
216         isDW = thingType.equals(THING_TYPE_SHELLYDOORWIN_STR) || thingType.equals(THING_TYPE_SHELLYDOORWIN2_STR)
217                 || thingType.equals(THING_TYPE_SHELLYBLUDW_STR);
218         isMotion = thingType.startsWith(THING_TYPE_SHELLYMOTION_STR);
219         isSense = thingType.equals(THING_TYPE_SHELLYSENSE_STR);
220         isIX = thingType.equals(THING_TYPE_SHELLYIX3_STR) || thingType.equals(THING_TYPE_SHELLYPLUSI4_STR)
221                 || thingType.equals(THING_TYPE_SHELLYPLUSI4DC_STR);
222         isButton = thingType.equals(THING_TYPE_SHELLYBUTTON1_STR) || thingType.equals(THING_TYPE_SHELLYBUTTON2_STR)
223                 || thingType.equals(THING_TYPE_SHELLYBLUBUTTON_STR);
224         isTRV = thingType.equals(THING_TYPE_SHELLYTRV_STR);
225         isWall = thingType.equals(THING_TYPE_SHELLYPLUSWALLDISPLAY_STR);
226         is3EM = thingType.equals(THING_TYPE_SHELLY3EM_STR) || thingType.startsWith(THING_TYPE_SHELLYPRO3EM_STR);
227         isEM50 = thingType.startsWith(THING_TYPE_SHELLYPROEM50_STR);
228
229         isSensor = isHT || isFlood || isDW || isSmoke || isGas || isButton || isUNI || isMotion || isSense || isTRV
230                 || isWall;
231         hasBattery = isHT || isFlood || isDW || isSmoke || isButton || isMotion || isTRV;
232         alwaysOn = !hasBattery || isMotion || isSense; // true means: device is reachable all the time (no sleep mode)
233     }
234
235     public void updateFromStatus(ShellySettingsStatus status) {
236         if (hasRelays) {
237             // Dimmer-2 doesn't report inputs under /settings, only on /status, we need to update that info after init
238             if (status.inputs != null) {
239                 numInputs = status.inputs.size();
240             }
241         } else if (status.input != null) {
242             // RGBW2
243             numInputs = 1;
244         }
245     }
246
247     public String getControlGroup(int i) {
248         if (i < 0) {
249             logger.debug("{}: Invalid index {} for getControlGroup()", thingName, i);
250             return "";
251         }
252         int idx = i + 1;
253         if (isDimmer) {
254             return CHANNEL_GROUP_DIMMER_CONTROL;
255         } else if (isRoller) {
256             return numRollers <= 1 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
257         } else if (isDimmer) {
258             return CHANNEL_GROUP_RELAY_CONTROL;
259         } else if (hasRelays) {
260             return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
261         } else if (isRGBW2) {
262             return settings.lights == null || settings.lights != null && settings.lights.size() <= 1
263                     ? CHANNEL_GROUP_LIGHT_CONTROL
264                     : CHANNEL_GROUP_LIGHT_CHANNEL + idx;
265         } else if (isLight) {
266             return CHANNEL_GROUP_LIGHT_CONTROL;
267         } else if (isButton) {
268             return CHANNEL_GROUP_STATUS;
269         } else if (isSensor) {
270             return CHANNEL_GROUP_SENSOR;
271         }
272
273         // e.g. ix3
274         return numRelays == 1 ? CHANNEL_GROUP_STATUS : CHANNEL_GROUP_STATUS + idx;
275     }
276
277     public String getMeterGroup(int idx) {
278         return numMeters > 1 ? CHANNEL_GROUP_METER + (idx + 1) : CHANNEL_GROUP_METER;
279     }
280
281     public String getInputGroup(int i) {
282         int idx = i + 1; // group names are 1-based
283         if (isRGBW2) {
284             return CHANNEL_GROUP_LIGHT_CONTROL;
285         } else if (isIX) {
286             return CHANNEL_GROUP_STATUS + idx;
287         } else if (isButton) {
288             return CHANNEL_GROUP_STATUS;
289         } else if (isRoller) {
290             return numRelays <= 2 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
291         } else {
292             // Device has 1 input per relay: 0=off, 1+2 depend on switch mode
293             return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
294         }
295     }
296
297     public String getInputSuffix(int i) {
298         int idx = i + 1; // channel names are 1-based
299         if (isRGBW2 || isIX) {
300             return ""; // RGBW2 has only 1 channel
301         } else if (isRoller || isDimmer) {
302             // Roller has 2 relays, but it will be mapped to 1 roller with 2 inputs
303             return String.valueOf(idx);
304         } else if (hasRelays) {
305             return numRelays == 1 && numInputs >= 2 ? String.valueOf(idx) : "";
306         }
307         return "";
308     }
309
310     @SuppressWarnings("null")
311     public boolean inButtonMode(int idx) {
312         if (idx < 0) {
313             logger.debug("{}: Invalid index {} for inButtonMode()", thingName, idx);
314             return false;
315         }
316         String btnType = "";
317         if (isButton) {
318             return true;
319         } else if (isIX && settings.inputs != null && idx < settings.inputs.size()) {
320             ShellySettingsInput input = settings.inputs.get(idx);
321             btnType = getString(input.btnType);
322         } else if (isDimmer) {
323             if (settings.dimmers != null) {
324                 ShellySettingsDimmer dimmer = settings.dimmers.get(0);
325                 btnType = dimmer.btnType;
326             }
327         } else if (settings.relays != null) {
328             if (numRelays == 1) {
329                 ShellySettingsRelay relay = settings.relays.get(0);
330                 if (relay.btnType != null) {
331                     btnType = getString(relay.btnType);
332                 } else {
333                     // Shelly 1L has 2 inputs
334                     btnType = idx == 0 ? getString(relay.btnType1) : getString(relay.btnType2);
335                 }
336             } else if (idx < settings.relays.size()) {
337                 // only one input channel
338                 ShellySettingsRelay relay = settings.relays.get(idx);
339                 btnType = getString(relay.btnType);
340             }
341         } else if (isRGBW2 && (settings.lights != null) && (idx < settings.lights.size())) {
342             ShellySettingsRgbwLight light = settings.lights.get(idx);
343             btnType = light.btnType;
344         }
345
346         return btnType.equalsIgnoreCase(SHELLY_BTNT_MOMENTARY) || btnType.equalsIgnoreCase(SHELLY_BTNT_MOM_ON_RELEASE)
347                 || btnType.equalsIgnoreCase(SHELLY_BTNT_ONE_BUTTON) || btnType.equalsIgnoreCase(SHELLY_BTNT_TWO_BUTTON)
348                 || btnType.equalsIgnoreCase(SHELLY_BTNT_DETACHED);
349     }
350
351     public int getRollerFav(int id) {
352         if (id >= 0 && getBool(settings.favoritesEnabled) && settings.favorites != null
353                 && id < settings.favorites.size()) {
354             return settings.favorites.get(id).pos;
355         }
356         return -1;
357     }
358
359     public String[] getValveProfileList(int valveId) {
360         if (isTRV && settings.thermostats != null) {
361             int sz = settings.thermostats.size();
362             if (valveId <= sz) {
363                 if (settings.thermostats != null) {
364                     ShellyThermnostat t = settings.thermostats.get(valveId);
365                     return t.profileNames;
366                 }
367             }
368         }
369         return new String[0];
370     }
371
372     public String getValueProfile(int valveId, int profileId) {
373         int id = profileId;
374         if (id <= 0 && settings.thermostats != null) {
375             id = settings.thermostats.get(0).profile;
376         }
377         return "" + id;
378     }
379
380     public static String extractFwVersion(@Nullable String version) {
381         if (version != null) {
382             // fix version e.g.
383             // 20210319-122304/v.1.10-Dimmer1-gfd4cc10 (with v.1. instead of v1.)
384             // 20220809-125346/v1.12-g99f7e0b (.0 in 1.12.0 missing)
385             String vers = version.replace("/v.1.10-", "/v1.10.0-") //
386                     .replace("/v1.12-", "/v1.12.0");
387
388             // Extract version from string, e.g. 20210226-091047/v1.10.0-rc2-89-g623b41ec0-master
389             Matcher matcher = VERSION_PATTERN.matcher(vers);
390             if (matcher.find()) {
391                 return matcher.group(0);
392             }
393         }
394         return "";
395     }
396
397     public boolean coiotEnabled() {
398         if ((settings.coiot != null) && (settings.coiot.enabled != null)) {
399             return settings.coiot.enabled;
400         }
401
402         // If device is not yet intialized or the enabled property is missing we assume that CoIoT is enabled
403         return true;
404     }
405 }