]> git.basschouten.com Git - openhab-addons.git/blob
7e8f335b2f4b066e70ff51b0f11525343a7e8e32
[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         // It is not guaranteed, that the array entries are in order. Check all
130         // possible variants. See openhab#15514.
131         if (json.contains("\"ext_temperature\":{\"0\":[{") || json.contains("\"ext_temperature\":{\"1\":[{")
132                 || json.contains("\"ext_temperature\":{\"2\":[{")) {
133             // Shelly UNI uses ext_temperature array, reformat to avoid GSON exception
134             json = json.replace("ext_temperature", "ext_temperature_array");
135         }
136         if (json.contains("\"ext_humidity\":{\"0\":[{")) {
137             // Shelly UNI uses ext_humidity array, reformat to avoid GSON exception
138             json = json.replace("ext_humidity", "ext_humidity_array");
139         }
140         settingsJson = json;
141         settings = fromJson(gson, json, ShellySettingsGlobal.class);
142
143         // General settings
144         name = getString(settings.name);
145         deviceType = getString(settings.device.type);
146         mac = getString(settings.device.mac);
147         hostname = !getString(settings.device.hostname).isEmpty() ? settings.device.hostname.toLowerCase()
148                 : mac.length() >= 12 ? "shelly-" + mac.toUpperCase().substring(6, 11) : "unknown";
149         mode = getString(settings.mode).toLowerCase();
150         hwRev = settings.hwinfo != null ? getString(settings.hwinfo.hwRevision) : "";
151         hwBatchId = settings.hwinfo != null ? getString(settings.hwinfo.batchId.toString()) : "";
152         fwDate = substringBefore(settings.fw, "/");
153         fwVersion = extractFwVersion(settings.fw);
154         ShellyVersionDTO version = new ShellyVersionDTO();
155         extFeatures = version.compare(fwVersion, SHELLY_API_FW_110) >= 0;
156         discoverable = (settings.discoverable == null) || settings.discoverable;
157
158         isRoller = mode.equalsIgnoreCase(SHELLY_MODE_ROLLER);
159         inColor = isLight && mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
160
161         numRelays = !isLight ? getInteger(settings.device.numOutputs) : 0;
162         if ((numRelays > 0) && (settings.relays == null)) {
163             numRelays = 0;
164         }
165         hasRelays = (numRelays > 0) || isDimmer;
166         numRollers = getInteger(settings.device.numRollers);
167         numInputs = settings.inputs != null ? settings.inputs.size() : hasRelays ? isRoller ? 2 : 1 : 0;
168
169         isEMeter = settings.emeters != null;
170         numMeters = !isEMeter ? getInteger(settings.device.numMeters) : getInteger(settings.device.numEMeters);
171         if ((numMeters == 0) && isLight) {
172             // RGBW2 doesn't report, but has one
173             numMeters = inColor ? 1 : getInteger(settings.device.numOutputs);
174         }
175
176         initialized = true;
177         return this;
178     }
179
180     public boolean containsEventUrl(String eventType) {
181         return containsEventUrl(settingsJson, eventType);
182     }
183
184     public boolean containsEventUrl(String json, String eventType) {
185         String settings = json.toLowerCase();
186         return settings.contains((eventType + SHELLY_EVENTURL_SUFFIX).toLowerCase());
187     }
188
189     public boolean isInitialized() {
190         return initialized;
191     }
192
193     public void initFromThingType(String name) {
194         String thingType = (name.contains("-") ? substringBefore(name, "-") : name).toLowerCase().trim();
195         if (thingType.isEmpty()) {
196             return;
197         }
198
199         isBlu = thingType.startsWith("shellyblu"); // e.g. SBBT for BU Button
200
201         isDimmer = deviceType.equalsIgnoreCase(SHELLYDT_DIMMER) || deviceType.equalsIgnoreCase(SHELLYDT_DIMMER2)
202                 || deviceType.equalsIgnoreCase(SHELLYDT_PLUSDIMMERUS)
203                 || thingType.equalsIgnoreCase(THING_TYPE_SHELLYPLUSDIMMERUS_STR);
204         isBulb = thingType.equals(THING_TYPE_SHELLYBULB_STR);
205         isDuo = thingType.equals(THING_TYPE_SHELLYDUO_STR) || thingType.equals(THING_TYPE_SHELLYVINTAGE_STR)
206                 || thingType.equals(THING_TYPE_SHELLYDUORGBW_STR);
207         isRGBW2 = thingType.startsWith(THING_TYPE_SHELLYRGBW2_PREFIX);
208         isLight = isBulb || isDuo || isRGBW2;
209         if (isLight) {
210             minTemp = isBulb ? MIN_COLOR_TEMP_BULB : MIN_COLOR_TEMP_DUO;
211             maxTemp = isBulb ? MAX_COLOR_TEMP_BULB : MAX_COLOR_TEMP_DUO;
212         }
213
214         boolean isFlood = thingType.equals(THING_TYPE_SHELLYFLOOD_STR);
215         isSmoke = thingType.equals(THING_TYPE_SHELLYSMOKE_STR) || thingType.equals(THING_TYPE_SHELLYPLUSSMOKE_STR);
216         boolean isGas = thingType.equals(THING_TYPE_SHELLYGAS_STR);
217         boolean isUNI = thingType.equals(THING_TYPE_SHELLYUNI_STR);
218         isHT = thingType.equals(THING_TYPE_SHELLYHT_STR) || thingType.equals(THING_TYPE_SHELLYPLUSHT_STR);
219         isDW = thingType.equals(THING_TYPE_SHELLYDOORWIN_STR) || thingType.equals(THING_TYPE_SHELLYDOORWIN2_STR)
220                 || thingType.equals(THING_TYPE_SHELLYBLUDW_STR);
221         isMotion = thingType.startsWith(THING_TYPE_SHELLYMOTION_STR);
222         isSense = thingType.equals(THING_TYPE_SHELLYSENSE_STR);
223         isIX = thingType.equals(THING_TYPE_SHELLYIX3_STR) || thingType.equals(THING_TYPE_SHELLYPLUSI4_STR)
224                 || thingType.equals(THING_TYPE_SHELLYPLUSI4DC_STR);
225         isButton = thingType.equals(THING_TYPE_SHELLYBUTTON1_STR) || thingType.equals(THING_TYPE_SHELLYBUTTON2_STR)
226                 || thingType.equals(THING_TYPE_SHELLYBLUBUTTON_STR);
227         isTRV = thingType.equals(THING_TYPE_SHELLYTRV_STR);
228         isWall = thingType.equals(THING_TYPE_SHELLYPLUSWALLDISPLAY_STR);
229         is3EM = thingType.equals(THING_TYPE_SHELLY3EM_STR) || thingType.startsWith(THING_TYPE_SHELLYPRO3EM_STR);
230         isEM50 = thingType.startsWith(THING_TYPE_SHELLYPROEM50_STR);
231
232         isSensor = isHT || isFlood || isDW || isSmoke || isGas || isButton || isUNI || isMotion || isSense || isTRV
233                 || isWall;
234         hasBattery = isHT || isFlood || isDW || isSmoke || isButton || isMotion || isTRV;
235         alwaysOn = !hasBattery || isMotion || isSense; // true means: device is reachable all the time (no sleep mode)
236     }
237
238     public void updateFromStatus(ShellySettingsStatus status) {
239         if (hasRelays) {
240             // Dimmer-2 doesn't report inputs under /settings, only on /status, we need to update that info after init
241             if (status.inputs != null) {
242                 numInputs = status.inputs.size();
243             }
244         } else if (status.input != null) {
245             // RGBW2
246             numInputs = 1;
247         }
248     }
249
250     public String getControlGroup(int i) {
251         if (i < 0) {
252             logger.debug("{}: Invalid index {} for getControlGroup()", thingName, i);
253             return "";
254         }
255         int idx = i + 1;
256         if (isDimmer) {
257             return CHANNEL_GROUP_DIMMER_CONTROL;
258         } else if (isRoller) {
259             return numRollers <= 1 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
260         } else if (isDimmer) {
261             return CHANNEL_GROUP_RELAY_CONTROL;
262         } else if (hasRelays) {
263             return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
264         } else if (isRGBW2) {
265             return settings.lights == null || settings.lights != null && settings.lights.size() <= 1
266                     ? CHANNEL_GROUP_LIGHT_CONTROL
267                     : CHANNEL_GROUP_LIGHT_CHANNEL + idx;
268         } else if (isLight) {
269             return CHANNEL_GROUP_LIGHT_CONTROL;
270         } else if (isButton) {
271             return CHANNEL_GROUP_STATUS;
272         } else if (isSensor) {
273             return CHANNEL_GROUP_SENSOR;
274         }
275
276         // e.g. ix3
277         return numRelays == 1 ? CHANNEL_GROUP_STATUS : CHANNEL_GROUP_STATUS + idx;
278     }
279
280     public String getMeterGroup(int idx) {
281         return numMeters > 1 ? CHANNEL_GROUP_METER + (idx + 1) : CHANNEL_GROUP_METER;
282     }
283
284     public String getInputGroup(int i) {
285         int idx = i + 1; // group names are 1-based
286         if (isRGBW2) {
287             return CHANNEL_GROUP_LIGHT_CONTROL;
288         } else if (isIX) {
289             return CHANNEL_GROUP_STATUS + idx;
290         } else if (isButton) {
291             return CHANNEL_GROUP_STATUS;
292         } else if (isRoller) {
293             return numRelays <= 2 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
294         } else {
295             // Device has 1 input per relay: 0=off, 1+2 depend on switch mode
296             return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
297         }
298     }
299
300     public String getInputSuffix(int i) {
301         int idx = i + 1; // channel names are 1-based
302         if (isRGBW2 || isIX) {
303             return ""; // RGBW2 has only 1 channel
304         } else if (isRoller || isDimmer) {
305             // Roller has 2 relays, but it will be mapped to 1 roller with 2 inputs
306             return String.valueOf(idx);
307         } else if (hasRelays) {
308             return numRelays == 1 && numInputs >= 2 ? String.valueOf(idx) : "";
309         }
310         return "";
311     }
312
313     @SuppressWarnings("null")
314     public boolean inButtonMode(int idx) {
315         if (idx < 0) {
316             logger.debug("{}: Invalid index {} for inButtonMode()", thingName, idx);
317             return false;
318         }
319         String btnType = "";
320         if (isButton) {
321             return true;
322         } else if (isIX && settings.inputs != null && idx < settings.inputs.size()) {
323             ShellySettingsInput input = settings.inputs.get(idx);
324             btnType = getString(input.btnType);
325         } else if (isDimmer) {
326             if (settings.dimmers != null) {
327                 ShellySettingsDimmer dimmer = settings.dimmers.get(0);
328                 btnType = dimmer.btnType;
329             }
330         } else if (settings.relays != null) {
331             if (numRelays == 1) {
332                 ShellySettingsRelay relay = settings.relays.get(0);
333                 if (relay.btnType != null) {
334                     btnType = getString(relay.btnType);
335                 } else {
336                     // Shelly 1L has 2 inputs
337                     btnType = idx == 0 ? getString(relay.btnType1) : getString(relay.btnType2);
338                 }
339             } else if (idx < settings.relays.size()) {
340                 // only one input channel
341                 ShellySettingsRelay relay = settings.relays.get(idx);
342                 btnType = getString(relay.btnType);
343             }
344         } else if (isRGBW2 && (settings.lights != null) && (idx < settings.lights.size())) {
345             ShellySettingsRgbwLight light = settings.lights.get(idx);
346             btnType = light.btnType;
347         }
348
349         return btnType.equalsIgnoreCase(SHELLY_BTNT_MOMENTARY) || btnType.equalsIgnoreCase(SHELLY_BTNT_MOM_ON_RELEASE)
350                 || btnType.equalsIgnoreCase(SHELLY_BTNT_ONE_BUTTON) || btnType.equalsIgnoreCase(SHELLY_BTNT_TWO_BUTTON)
351                 || btnType.equalsIgnoreCase(SHELLY_BTNT_DETACHED);
352     }
353
354     public int getRollerFav(int id) {
355         if (id >= 0 && getBool(settings.favoritesEnabled) && settings.favorites != null
356                 && id < settings.favorites.size()) {
357             return settings.favorites.get(id).pos;
358         }
359         return -1;
360     }
361
362     public String[] getValveProfileList(int valveId) {
363         if (isTRV && settings.thermostats != null) {
364             int sz = settings.thermostats.size();
365             if (valveId <= sz) {
366                 if (settings.thermostats != null) {
367                     ShellyThermnostat t = settings.thermostats.get(valveId);
368                     return t.profileNames;
369                 }
370             }
371         }
372         return new String[0];
373     }
374
375     public String getValueProfile(int valveId, int profileId) {
376         int id = profileId;
377         if (id <= 0 && settings.thermostats != null) {
378             id = settings.thermostats.get(0).profile;
379         }
380         return "" + id;
381     }
382
383     public static String extractFwVersion(@Nullable String version) {
384         if (version != null) {
385             // fix version e.g.
386             // 20210319-122304/v.1.10-Dimmer1-gfd4cc10 (with v.1. instead of v1.)
387             // 20220809-125346/v1.12-g99f7e0b (.0 in 1.12.0 missing)
388             String vers = version.replace("/v.1.10-", "/v1.10.0-") //
389                     .replace("/v1.12-", "/v1.12.0");
390
391             // Extract version from string, e.g. 20210226-091047/v1.10.0-rc2-89-g623b41ec0-master
392             Matcher matcher = VERSION_PATTERN.matcher(vers);
393             if (matcher.find()) {
394                 return matcher.group(0);
395             }
396         }
397         return "";
398     }
399
400     public boolean coiotEnabled() {
401         if ((settings.coiot != null) && (settings.coiot.enabled != null)) {
402             return settings.coiot.enabled;
403         }
404
405         // If device is not yet intialized or the enabled property is missing we assume that CoIoT is enabled
406         return true;
407     }
408 }