]> git.basschouten.com Git - openhab-addons.git/blob
2d576a27ecd178b1db8c3685080ba54b44da99b2
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.util.ShellyVersionDTO;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 import com.google.gson.Gson;
38
39 /**
40  * The {@link ShellyDeviceProfile} creates a device profile based on the settings returned from the API's /settings
41  * call. This is used to be more dynamic in controlling the device, but also to overcome some issues in the API (e.g.
42  * RGBW2 returns "no meter" even it has one)
43  *
44  * @author Markus Michels - Initial contribution
45  */
46 @NonNullByDefault
47 public class ShellyDeviceProfile {
48     private final Logger logger = LoggerFactory.getLogger(ShellyDeviceProfile.class);
49     private static final Pattern VERSION_PATTERN = Pattern.compile("v\\d+\\.\\d+\\.\\d+(-[a-z0-9]*)?");
50
51     public boolean initialized = false; // true when initialized
52
53     public String thingName = "";
54     public String deviceType = "";
55     public boolean extFeatures = false;
56
57     public String settingsJson = "";
58     public ShellySettingsGlobal settings = new ShellySettingsGlobal();
59     public ShellySettingsStatus status = new ShellySettingsStatus();
60
61     public String hostname = "";
62     public String name = "";
63     public String mode = "";
64     public boolean discoverable = true;
65     public boolean auth = false;
66     public boolean alwaysOn = true;
67     public boolean isGen2 = false;
68
69     public String hwRev = "";
70     public String hwBatchId = "";
71     public String mac = "";
72     public String fwVersion = "";
73     public String fwDate = "";
74
75     public boolean hasRelays = false; // true if it has at least 1 power meter
76     public int numRelays = 0; // number of relays/outputs
77     public int numRollers = 0; // number of Rollers, usually 1
78     public boolean isRoller = false; // true for Shelly2 in roller mode
79     public boolean isDimmer = false; // true for a Shelly Dimmer (SHDM-1)
80     public int numInputs = 0; // number of inputs
81
82     public int numMeters = 0;
83     public boolean isEMeter = false; // true for ShellyEM/3EM
84
85     public boolean isLight = false; // true if it is a Shelly Bulb/RGBW2
86     public boolean isBulb = false; // true only if it is a Bulb
87     public boolean isDuo = false; // true only if it is a Duo
88     public boolean isRGBW2 = false; // true only if it a a RGBW2
89     public boolean inColor = false; // true if bulb/rgbw2 is in color mode
90
91     public boolean isSensor = false; // true for HT & Smoke
92     public boolean hasBattery = false; // true if battery device
93     public boolean isSense = false; // true if thing is a Shelly Sense
94     public boolean isMotion = false; // true if thing is a Shelly Sense
95     public boolean isHT = false; // true for H&T
96     public boolean isDW = false; // true for Door Window sensor
97     public boolean isButton = false; // true for a Shelly Button 1
98     public boolean isIX = false; // true for a Shelly IX
99     public boolean isTRV = false; // true for a Shelly TRV
100
101     public int minTemp = 0; // Bulb/Duo: Min Light Temp
102     public int maxTemp = 0; // Bulb/Duo: Max Light Temp
103
104     public int updatePeriod = 2 * UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
105
106     public String coiotEndpoint = "";
107
108     public Map<String, String> irCodes = new HashMap<>(); // Sense: list of stored IR codes
109
110     public ShellyDeviceProfile() {
111     }
112
113     public ShellyDeviceProfile initialize(String thingType, String json) throws ShellyApiException {
114         Gson gson = new Gson();
115
116         initialized = false;
117
118         initFromThingType(thingType);
119         settingsJson = json;
120         ShellySettingsGlobal gs = fromJson(gson, json, ShellySettingsGlobal.class);
121         settings = gs; // only update when no exception
122
123         // General settings
124         name = getString(settings.name);
125         deviceType = getString(settings.device.type);
126         mac = getString(settings.device.mac);
127         hostname = settings.device.hostname != null && !settings.device.hostname.isEmpty()
128                 ? settings.device.hostname.toLowerCase()
129                 : "shelly-" + mac.toUpperCase().substring(6, 11);
130         mode = getString(settings.mode).toLowerCase();
131         hwRev = settings.hwinfo != null ? getString(settings.hwinfo.hwRevision) : "";
132         hwBatchId = settings.hwinfo != null ? getString(settings.hwinfo.batchId.toString()) : "";
133         fwDate = substringBefore(settings.fw, "/");
134         fwVersion = extractFwVersion(settings.fw);
135         ShellyVersionDTO version = new ShellyVersionDTO();
136         extFeatures = version.compare(fwVersion, SHELLY_API_FW_110) >= 0;
137         discoverable = (settings.discoverable == null) || settings.discoverable;
138
139         isRoller = mode.equalsIgnoreCase(SHELLY_MODE_ROLLER);
140         inColor = isLight && mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
141
142         numRelays = !isLight ? getInteger(settings.device.numOutputs) : 0;
143         if ((numRelays > 0) && (settings.relays == null)) {
144             numRelays = 0;
145         }
146         hasRelays = (numRelays > 0) || isDimmer;
147         numRollers = getInteger(settings.device.numRollers);
148         numInputs = settings.inputs != null ? settings.inputs.size() : hasRelays ? isRoller ? 2 : 1 : 0;
149
150         isEMeter = settings.emeters != null;
151         numMeters = !isEMeter ? getInteger(settings.device.numMeters) : getInteger(settings.device.numEMeters);
152         if ((numMeters == 0) && isLight) {
153             // RGBW2 doesn't report, but has one
154             numMeters = inColor ? 1 : getInteger(settings.device.numOutputs);
155         }
156
157         if (settings.sleepMode != null) {
158             // Sensor, usually 12h, H&T in USB mode 10min
159             updatePeriod = getString(settings.sleepMode.unit).equalsIgnoreCase("m") ? settings.sleepMode.period * 60 // minutes
160                     : settings.sleepMode.period * 3600; // hours
161             updatePeriod += 60; // give 1min extra
162         } else if ((settings.coiot != null) && settings.coiot.updatePeriod != null && !isTRV) {
163             // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
164             updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS, 2 * getInteger(settings.coiot.updatePeriod)) + 10;
165         } else {
166             updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
167         }
168
169         initialized = true;
170         return this;
171     }
172
173     public boolean containsEventUrl(String eventType) {
174         return containsEventUrl(settingsJson, eventType);
175     }
176
177     public boolean containsEventUrl(String json, String eventType) {
178         String settings = json.toLowerCase();
179         return settings.contains((eventType + SHELLY_EVENTURL_SUFFIX).toLowerCase());
180     }
181
182     public boolean isInitialized() {
183         return initialized;
184     }
185
186     public void initFromThingType(String name) {
187         String thingType = (name.contains("-") ? substringBefore(name, "-") : name).toLowerCase().trim();
188         if (thingType.isEmpty()) {
189             return;
190         }
191
192         isDimmer = deviceType.equalsIgnoreCase(SHELLYDT_DIMMER) || deviceType.equalsIgnoreCase(SHELLYDT_DIMMER2);
193         isBulb = thingType.equals(THING_TYPE_SHELLYBULB_STR);
194         isDuo = thingType.equals(THING_TYPE_SHELLYDUO_STR) || thingType.equals(THING_TYPE_SHELLYVINTAGE_STR)
195                 || thingType.equals(THING_TYPE_SHELLYDUORGBW_STR);
196         isRGBW2 = thingType.startsWith(THING_TYPE_SHELLYRGBW2_PREFIX);
197         isLight = isBulb || isDuo || isRGBW2;
198         if (isLight) {
199             minTemp = isBulb ? MIN_COLOR_TEMP_BULB : MIN_COLOR_TEMP_DUO;
200             maxTemp = isBulb ? MAX_COLOR_TEMP_BULB : MAX_COLOR_TEMP_DUO;
201         }
202
203         boolean isFlood = thingType.equals(THING_TYPE_SHELLYFLOOD_STR);
204         boolean isSmoke = thingType.equals(THING_TYPE_SHELLYSMOKE_STR);
205         boolean isGas = thingType.equals(THING_TYPE_SHELLYGAS_STR);
206         boolean isUNI = thingType.equals(THING_TYPE_SHELLYUNI_STR);
207         isHT = thingType.equals(THING_TYPE_SHELLYHT_STR) || thingType.equals(THING_TYPE_SHELLYPLUSHT_STR);
208         isDW = thingType.equals(THING_TYPE_SHELLYDOORWIN_STR) || thingType.equals(THING_TYPE_SHELLYDOORWIN2_STR);
209         isMotion = thingType.startsWith(THING_TYPE_SHELLYMOTION_STR);
210         isSense = thingType.equals(THING_TYPE_SHELLYSENSE_STR);
211         isIX = thingType.equals(THING_TYPE_SHELLYIX3_STR) || thingType.equals(THING_TYPE_SHELLYPLUSI4_STR)
212                 || thingType.equals(THING_TYPE_SHELLYPLUSI4DC_STR);
213         isButton = thingType.equals(THING_TYPE_SHELLYBUTTON1_STR) || thingType.equals(THING_TYPE_SHELLYBUTTON2_STR);
214         isSensor = isHT || isFlood || isDW || isSmoke || isGas || isButton || isUNI || isMotion || isSense || isTRV;
215         hasBattery = isHT || isFlood || isDW || isSmoke || isButton || isMotion || isTRV;
216         isTRV = thingType.equals(THING_TYPE_SHELLYTRV_STR);
217
218         alwaysOn = !hasBattery || isMotion || isSense; // true means: device is reachable all the time (no sleep mode)
219     }
220
221     public void updateFromStatus(ShellySettingsStatus status) {
222         if (hasRelays) {
223             // Dimmer-2 doesn't report inputs under /settings, only on /status, we need to update that info after init
224             if (status.inputs != null) {
225                 numInputs = status.inputs.size();
226             }
227         } else if (status.input != null) {
228             // RGBW2
229             numInputs = 1;
230         }
231     }
232
233     public String getControlGroup(int i) {
234         if (i < 0) {
235             logger.debug("{}: Invalid index {} for getControlGroup()", thingName, i);
236             return "";
237         }
238         int idx = i + 1;
239         if (isDimmer) {
240             return CHANNEL_GROUP_DIMMER_CONTROL;
241         } else if (isRoller) {
242             return numRollers <= 1 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
243         } else if (isDimmer) {
244             return CHANNEL_GROUP_RELAY_CONTROL;
245         } else if (hasRelays) {
246             return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
247         } else if (isLight) {
248             return numRelays <= 1 ? CHANNEL_GROUP_LIGHT_CONTROL : CHANNEL_GROUP_LIGHT_CONTROL + idx;
249         } else if (isButton) {
250             return CHANNEL_GROUP_STATUS;
251         } else if (isSensor) {
252             return CHANNEL_GROUP_SENSOR;
253         }
254
255         // e.g. ix3
256         return numRelays == 1 ? CHANNEL_GROUP_STATUS : CHANNEL_GROUP_STATUS + idx;
257     }
258
259     public String getMeterGroup(int idx) {
260         return numMeters > 1 ? CHANNEL_GROUP_METER + (idx + 1) : CHANNEL_GROUP_METER;
261     }
262
263     public String getInputGroup(int i) {
264         int idx = i + 1; // group names are 1-based
265         if (isRGBW2) {
266             return CHANNEL_GROUP_LIGHT_CONTROL;
267         } else if (isIX) {
268             return CHANNEL_GROUP_STATUS + idx;
269         } else if (isButton) {
270             return CHANNEL_GROUP_STATUS;
271         } else if (isRoller) {
272             return numRelays <= 2 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
273         } else {
274             // Device has 1 input per relay: 0=off, 1+2 depend on switch mode
275             return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
276         }
277     }
278
279     public String getInputSuffix(int i) {
280         int idx = i + 1; // channel names are 1-based
281         if (isRGBW2 || isIX) {
282             return ""; // RGBW2 has only 1 channel
283         } else if (isRoller || isDimmer) {
284             // Roller has 2 relays, but it will be mapped to 1 roller with 2 inputs
285             return String.valueOf(idx);
286         } else if (hasRelays) {
287             return numRelays == 1 && numInputs >= 2 ? String.valueOf(idx) : "";
288         }
289         return "";
290     }
291
292     public boolean inButtonMode(int idx) {
293         if (idx < 0) {
294             logger.debug("{}: Invalid index {} for inButtonMode()", thingName, idx);
295             return false;
296         }
297         String btnType = "";
298         if (isButton) {
299             return true;
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;
307             }
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);
313                 } else {
314                     // Shelly 1L has 2 inputs
315                     btnType = idx == 0 ? getString(relay.btnType1) : getString(relay.btnType2);
316                 }
317             } else if (idx < settings.relays.size()) {
318                 // only one input channel
319                 ShellySettingsRelay relay = settings.relays.get(idx);
320                 btnType = getString(relay.btnType);
321             }
322         } else if (isRGBW2 && (settings.lights != null) && (idx < settings.lights.size())) {
323             ShellySettingsRgbwLight light = settings.lights.get(idx);
324             btnType = light.btnType;
325         }
326
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);
330     }
331
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;
336         }
337         return -1;
338     }
339
340     public static String extractFwVersion(@Nullable String version) {
341         if (version != null) {
342             // fix version e.g. 20210319-122304/v.1.10-Dimmer1-gfd4cc10 (with v.1. instead of v1.)
343             String vers = version.replace("/v.1.10-", "/v1.10.0-");
344
345             // Extract version from string, e.g. 20210226-091047/v1.10.0-rc2-89-g623b41ec0-master
346             Matcher matcher = VERSION_PATTERN.matcher(vers);
347             if (matcher.find()) {
348                 return matcher.group(0);
349             }
350         }
351         return "";
352     }
353
354     public boolean coiotEnabled() {
355         if ((settings.coiot != null) && (settings.coiot.enabled != null)) {
356             return settings.coiot.enabled;
357         }
358
359         // If device is not yet intialized or the enabled property is missing we assume that CoIoT is enabled
360         return true;
361     }
362 }