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