]> git.basschouten.com Git - openhab-addons.git/blob
978d7e8a9af33a6359a1279b17944b87f7884b16
[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.api.ShellyApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
18
19 import java.util.HashMap;
20 import java.util.Map;
21 import java.util.regex.Matcher;
22 import java.util.regex.Pattern;
23
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsDimmer;
27 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsGlobal;
28 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsInput;
29 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsRelay;
30 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsRgbwLight;
31 import org.openhab.binding.shelly.internal.api.ShellyApiJsonDTO.ShellySettingsStatus;
32 import org.openhab.binding.shelly.internal.util.ShellyVersionDTO;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
35
36 import com.google.gson.Gson;
37
38 /**
39  * The {@link ShellyDeviceProfile} creates a device profile based on the settings returned from the API's /settings
40  * call. This is used to be more dynamic in controlling the device, but also to overcome some issues in the API (e.g.
41  * RGBW2 returns "no meter" even it has one)
42  *
43  * @author Markus Michels - Initial contribution
44  */
45 @NonNullByDefault
46 public class ShellyDeviceProfile {
47     private final Logger logger = LoggerFactory.getLogger(ShellyDeviceProfile.class);
48     private static final Pattern VERSION_PATTERN = Pattern.compile("v\\d+\\.\\d+\\.\\d+(-[a-z0-9]*)?");
49
50     public boolean initialized = false; // true when initialized
51
52     public String thingName = "";
53     public String deviceType = "";
54     public boolean extFeatures = false;
55
56     public String settingsJson = "";
57     public ShellySettingsGlobal settings = new ShellySettingsGlobal();
58     public ShellySettingsStatus status = new ShellySettingsStatus();
59
60     public String hostname = "";
61     public String mode = "";
62     public boolean discoverable = true;
63     public boolean auth = false;
64     public boolean alwaysOn = true;
65
66     public String hwRev = "";
67     public String hwBatchId = "";
68     public String mac = "";
69     public String fwVersion = "";
70     public String fwDate = "";
71
72     public boolean hasRelays = false; // true if it has at least 1 power meter
73     public int numRelays = 0; // number of relays/outputs
74     public int numRollers = 0; // number of Rollers, usually 1
75     public boolean isRoller = false; // true for Shelly2 in roller mode
76     public boolean isDimmer = false; // true for a Shelly Dimmer (SHDM-1)
77     public int numInputs = 0; // number of inputs
78
79     public int numMeters = 0;
80     public boolean isEMeter = false; // true for ShellyEM/3EM
81
82     public boolean isLight = false; // true if it is a Shelly Bulb/RGBW2
83     public boolean isBulb = false; // true only if it is a Bulb
84     public boolean isDuo = false; // true only if it is a Duo
85     public boolean isRGBW2 = false; // true only if it a a RGBW2
86     public boolean inColor = false; // true if bulb/rgbw2 is in color mode
87
88     public boolean isSensor = false; // true for HT & Smoke
89     public boolean hasBattery = false; // true if battery device
90     public boolean isSense = false; // true if thing is a Shelly Sense
91     public boolean isMotion = false; // true if thing is a Shelly Sense
92     public boolean isHT = false; // true for H&T
93     public boolean isDW = false; // true for Door Window sensor
94     public boolean isButton = false; // true for a Shelly Button 1
95     public boolean isIX3 = false; // true for a Shelly IX
96
97     public int minTemp = 0; // Bulb/Duo: Min Light Temp
98     public int maxTemp = 0; // Bulb/Duo: Max Light Temp
99
100     public int updatePeriod = 2 * UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
101
102     public String coiotEndpoint = "";
103
104     public Map<String, String> irCodes = new HashMap<>(); // Sense: list of stored IR codes
105
106     public ShellyDeviceProfile() {
107     }
108
109     public ShellyDeviceProfile initialize(String thingType, String json) throws ShellyApiException {
110         Gson gson = new Gson();
111
112         initialized = false;
113
114         initFromThingType(thingType);
115         settingsJson = json;
116         ShellySettingsGlobal gs = fromJson(gson, json, ShellySettingsGlobal.class);
117         settings = gs; // only update when no exception
118
119         // General settings
120         deviceType = getString(settings.device.type);
121         mac = getString(settings.device.mac);
122         hostname = settings.device.hostname != null && !settings.device.hostname.isEmpty()
123                 ? settings.device.hostname.toLowerCase()
124                 : "shelly-" + mac.toUpperCase().substring(6, 11);
125         mode = getString(settings.mode).toLowerCase();
126         hwRev = settings.hwinfo != null ? getString(settings.hwinfo.hwRevision) : "";
127         hwBatchId = settings.hwinfo != null ? getString(settings.hwinfo.batchId.toString()) : "";
128         fwDate = substringBefore(settings.fw, "/");
129         fwVersion = extractFwVersion(settings.fw);
130         ShellyVersionDTO version = new ShellyVersionDTO();
131         extFeatures = version.compare(fwVersion, SHELLY_API_FW_110) >= 0;
132         discoverable = (settings.discoverable == null) || settings.discoverable;
133
134         isRoller = mode.equalsIgnoreCase(SHELLY_MODE_ROLLER);
135         inColor = isLight && mode.equalsIgnoreCase(SHELLY_MODE_COLOR);
136
137         numRelays = !isLight ? getInteger(settings.device.numOutputs) : 0;
138         if ((numRelays > 0) && (settings.relays == null)) {
139             numRelays = 0;
140         }
141         hasRelays = (numRelays > 0) || isDimmer;
142         numRollers = getInteger(settings.device.numRollers);
143         numInputs = settings.inputs != null ? settings.inputs.size() : hasRelays ? isRoller ? 2 : 1 : 0;
144
145         isEMeter = settings.emeters != null;
146         numMeters = !isEMeter ? getInteger(settings.device.numMeters) : getInteger(settings.device.numEMeters);
147         if ((numMeters == 0) && isLight) {
148             // RGBW2 doesn't report, but has one
149             numMeters = inColor ? 1 : getInteger(settings.device.numOutputs);
150         }
151
152         if (settings.sleepMode != null) {
153             // Sensor, usually 12h, H&T in USB mode 10min
154             updatePeriod = getString(settings.sleepMode.unit).equalsIgnoreCase("m") ? settings.sleepMode.period * 60 // minutes
155                     : settings.sleepMode.period * 3600; // hours
156             updatePeriod += 60; // give 1min extra
157         } else if ((settings.coiot != null) && (settings.coiot.updatePeriod != null)) {
158             // Derive from CoAP update interval, usually 2*15+10s=40sec -> 70sec
159             updatePeriod = Math.max(UPDATE_SETTINGS_INTERVAL_SECONDS, 2 * getInteger(settings.coiot.updatePeriod)) + 10;
160         } else {
161             updatePeriod = UPDATE_SETTINGS_INTERVAL_SECONDS + 10;
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);
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         isIX3 = thingType.equals(THING_TYPE_SHELLYIX3_STR);
207         isButton = thingType.equals(THING_TYPE_SHELLYBUTTON1_STR);
208         isSensor = isHT || isFlood || isDW || isSmoke || isGas || isButton || isUNI || isMotion || isSense;
209         hasBattery = isHT || isFlood || isDW || isSmoke || isButton || isMotion;
210
211         alwaysOn = !hasBattery || isMotion || isSense; // true means: device is reachable all the time (no sleep mode)
212     }
213
214     public void updateFromStatus(ShellySettingsStatus status) {
215         if (hasRelays) {
216             // Dimmer-2 doesn't report inputs under /settings, only on /status, we need to update that info after init
217             if (status.inputs != null) {
218                 numInputs = status.inputs.size();
219             }
220         } else if (status.input != null) {
221             // RGBW2
222             numInputs = 1;
223         }
224     }
225
226     public String getControlGroup(int i) {
227         if (i < 0) {
228             logger.debug("{}: Invalid index {} for getControlGroup()", thingName, i);
229             return "";
230         }
231         int idx = i + 1;
232         if (isDimmer) {
233             return CHANNEL_GROUP_DIMMER_CONTROL;
234         } else if (isRoller) {
235             return numRollers <= 1 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
236         } else if (isDimmer) {
237             return CHANNEL_GROUP_RELAY_CONTROL;
238         } else if (hasRelays) {
239             return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
240         } else if (isLight) {
241             return numRelays <= 1 ? CHANNEL_GROUP_LIGHT_CONTROL : CHANNEL_GROUP_LIGHT_CONTROL + idx;
242         } else if (isButton) {
243             return CHANNEL_GROUP_STATUS;
244         } else if (isSensor) {
245             return CHANNEL_GROUP_SENSOR;
246         }
247
248         // e.g. ix3
249         return numRelays == 1 ? CHANNEL_GROUP_STATUS : CHANNEL_GROUP_STATUS + idx;
250     }
251
252     public String getInputGroup(int i) {
253         int idx = i + 1; // group names are 1-based
254         if (isRGBW2) {
255             return CHANNEL_GROUP_LIGHT_CONTROL;
256         } else if (isIX3) {
257             return CHANNEL_GROUP_STATUS + idx;
258         } else if (isButton) {
259             return CHANNEL_GROUP_STATUS;
260         } else if (isRoller) {
261             return numRelays <= 2 ? CHANNEL_GROUP_ROL_CONTROL : CHANNEL_GROUP_ROL_CONTROL + idx;
262         } else {
263             // Device has 1 input per relay: 0=off, 1+2 depend on switch mode
264             return numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + idx;
265         }
266     }
267
268     public String getInputSuffix(int i) {
269         int idx = i + 1; // channel names are 1-based
270         if (isRGBW2 || isIX3) {
271             return ""; // RGBW2 has only 1 channel
272         } else if (isRoller || isDimmer) {
273             // Roller has 2 relays, but it will be mapped to 1 roller with 2 inputs
274             return String.valueOf(idx);
275         } else if (hasRelays) {
276             return (numRelays) == 1 && (numInputs >= 2) ? String.valueOf(idx) : "";
277         }
278         return "";
279     }
280
281     public boolean inButtonMode(int idx) {
282         if (idx < 0) {
283             logger.debug("{}: Invalid index {} for inButtonMode()", thingName, idx);
284             return false;
285         }
286         String btnType = "";
287         if (isButton) {
288             return true;
289         } else if (isIX3 && (settings.inputs != null) && (idx < settings.inputs.size())) {
290             ShellySettingsInput input = settings.inputs.get(idx);
291             btnType = getString(input.btnType);
292         } else if (isDimmer) {
293             if (settings.dimmers != null) {
294                 ShellySettingsDimmer dimmer = settings.dimmers.get(0);
295                 btnType = dimmer.btnType;
296             }
297         } else if (settings.relays != null) {
298             if (numRelays == 1) {
299                 ShellySettingsRelay relay = settings.relays.get(0);
300                 if (relay.btnType != null) {
301                     btnType = getString(relay.btnType);
302                 } else {
303                     // Shelly 1L has 2 inputs
304                     btnType = idx == 0 ? getString(relay.btnType1) : getString(relay.btnType2);
305                 }
306             } else if (idx < settings.relays.size()) {
307                 // only one input channel
308                 ShellySettingsRelay relay = settings.relays.get(idx);
309                 btnType = getString(relay.btnType);
310             }
311         } else if (isRGBW2 && (settings.lights != null) && (idx < settings.lights.size())) {
312             ShellySettingsRgbwLight light = settings.lights.get(idx);
313             btnType = light.btnType;
314         }
315
316         logger.trace("{}: Checking for trigger, button-type[{}] is {}", thingName, idx, btnType);
317         return btnType.equalsIgnoreCase(SHELLY_BTNT_MOMENTARY) || btnType.equalsIgnoreCase(SHELLY_BTNT_MOM_ON_RELEASE)
318                 || btnType.equalsIgnoreCase(SHELLY_BTNT_ONE_BUTTON) || btnType.equalsIgnoreCase(SHELLY_BTNT_TWO_BUTTON)
319                 || btnType.equalsIgnoreCase(SHELLY_BTNT_DETACHED);
320     }
321
322     public int getRollerFav(int id) {
323         if ((id >= 0) && getBool(settings.favoritesEnabled) && (settings.favorites != null)
324                 && (id < settings.favorites.size())) {
325             return settings.favorites.get(id).pos;
326         }
327         return -1;
328     }
329
330     public static String extractFwVersion(@Nullable String version) {
331         if (version != null) {
332             // fix version e.g. 20210319-122304/v.1.10-Dimmer1-gfd4cc10 (with v.1. instead of v1.)
333             String vers = version.replace("/v.1.10-", "/v1.10.0-");
334
335             // Extract version from string, e.g. 20210226-091047/v1.10.0-rc2-89-g623b41ec0-master
336             Matcher matcher = VERSION_PATTERN.matcher(vers);
337             if (matcher.find()) {
338                 return matcher.group(0);
339             }
340         }
341         return "";
342     }
343
344     public boolean coiotEnabled() {
345         if ((settings.coiot != null) && (settings.coiot.enabled != null)) {
346             return settings.coiot.enabled;
347         }
348
349         // If device is not yet intialized or the enabled property is missing we assume that CoIoT is enabled
350         return true;
351     }
352 }