]> git.basschouten.com Git - openhab-addons.git/blob
f544616756d99e5f85412e4f657172384f6262d1
[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.api1;
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.util.ShellyUtils.*;
18
19 import java.util.List;
20 import java.util.Map;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.openhab.binding.shelly.internal.api.ShellyApiInterface;
25 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
26 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrBlk;
27 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotDescrSen;
28 import org.openhab.binding.shelly.internal.api1.Shelly1CoapJSonDTO.CoIotSensor;
29 import org.openhab.binding.shelly.internal.handler.ShellyColorUtils;
30 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
31 import org.openhab.core.library.types.OnOffType;
32 import org.openhab.core.library.types.OpenClosedType;
33 import org.openhab.core.library.types.StringType;
34 import org.openhab.core.library.unit.Units;
35 import org.openhab.core.types.State;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 import com.google.gson.Gson;
40 import com.google.gson.GsonBuilder;
41 import com.google.gson.JsonSyntaxException;
42
43 /**
44  * The {@link Shelly1CoIoTProtocol} implements common functions for the CoIoT implementations
45  *
46  * @author Markus Michels - Initial contribution
47  */
48 @NonNullByDefault
49 public class Shelly1CoIoTProtocol {
50     private final Logger logger = LoggerFactory.getLogger(Shelly1CoIoTProtocol.class);
51     protected final String thingName;
52     protected final ShellyThingInterface thingHandler;
53     protected final ShellyDeviceProfile profile;
54     protected final ShellyApiInterface api;
55     protected final Map<String, CoIotDescrBlk> blkMap;
56     protected final Map<String, CoIotDescrSen> sensorMap;
57     private final Gson gson = new GsonBuilder().create();
58
59     // Due to the fact that the device reports only the current/last status, but no real events, we need to distinguish
60     // between a real update or just a repeated status on periodic updates
61     protected int lastCfgCount = -1;
62     protected int[] lastEventCount = { -1, -1, -1, -1, -1, -1, -1, -1 }; // 4Pro has 4 relays, so 8 should be fine
63     protected String[] inputEvent = { "", "", "", "", "", "", "", "" };
64     protected String lastWakeup = "";
65
66     public Shelly1CoIoTProtocol(String thingName, ShellyThingInterface thingHandler, Map<String, CoIotDescrBlk> blkMap,
67             Map<String, CoIotDescrSen> sensorMap) {
68         this.thingName = thingName;
69         this.thingHandler = thingHandler;
70         this.blkMap = blkMap;
71         this.sensorMap = sensorMap;
72         this.profile = thingHandler.getProfile();
73         this.api = thingHandler.getApi();
74     }
75
76     protected boolean handleStatusUpdate(List<CoIotSensor> sensorUpdates, CoIotDescrSen sen, CoIotSensor s,
77             Map<String, State> updates, ShellyColorUtils col) {
78         // Process status information and convert into channel updates
79         int rIndex = getIdFromBlk(sen);
80         String rGroup = getProfile().numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL
81                 : CHANNEL_GROUP_RELAY_CONTROL + rIndex;
82
83         switch (sen.type.toLowerCase()) {
84             case "b": // BatteryLevel +
85                 updateChannel(updates, CHANNEL_GROUP_BATTERY, CHANNEL_SENSOR_BAT_LEVEL,
86                         toQuantityType(s.value, 0, Units.PERCENT));
87                 break;
88             case "h" /* Humidity */:
89                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_HUM,
90                         toQuantityType(s.value, DIGITS_PERCENT, Units.PERCENT));
91                 break;
92             case "m" /* Motion */:
93                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_MOTION,
94                         s.value == 1 ? OnOffType.ON : OnOffType.OFF);
95                 break;
96             case "l": // Luminosity +
97                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_LUX,
98                         toQuantityType(s.value, DIGITS_LUX, Units.LUX));
99                 break;
100             case "s": // CatchAll
101                 switch (sen.desc.toLowerCase()) {
102                     case "state": // Relay status +
103                     case "output":
104                         updatePower(profile, updates, rIndex, sen, s, sensorUpdates);
105                         break;
106                     case "input":
107                         handleInput(sen, s, rGroup, updates);
108                         break;
109                     case "brightness":
110                         // already handled by state/output
111                         break;
112                     case "overtemp": // ++
113                         if (s.value == 1) {
114                             thingHandler.postEvent(ALARM_TYPE_OVERTEMP, true);
115                         }
116                         break;
117                     case "position":
118                         // work around: Roller reports 101% instead max 100
119                         double pos = Math.max(SHELLY_MIN_ROLLER_POS, Math.min(s.value, SHELLY_MAX_ROLLER_POS));
120                         updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_CONTROL,
121                                 toQuantityType(SHELLY_MAX_ROLLER_POS - pos, Units.PERCENT));
122                         updateChannel(updates, CHANNEL_GROUP_ROL_CONTROL, CHANNEL_ROL_CONTROL_POS,
123                                 toQuantityType(pos, Units.PERCENT));
124                         break;
125                     case "flood":
126                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_FLOOD,
127                                 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
128                         break;
129                     case "vibration": // DW with FW1.6.5+
130                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_VIBRATION,
131                                 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
132                         if (s.value == 1) {
133                             thingHandler.triggerChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
134                                     EVENT_TYPE_VIBRATION);
135                         }
136                         break;
137                     case "luminositylevel": // +
138                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ILLUM, getStringType(s.valueStr));
139                         break;
140                     case "charger": // Sense
141                         updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CHARGER,
142                                 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
143                         break;
144                     // RGBW2/Bulb
145                     case "red":
146                         col.setRed((int) s.value);
147                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_RED,
148                                 ShellyColorUtils.toPercent((int) s.value));
149                         break;
150                     case "green":
151                         col.setGreen((int) s.value);
152                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_GREEN,
153                                 ShellyColorUtils.toPercent((int) s.value));
154                         break;
155                     case "blue":
156                         col.setBlue((int) s.value);
157                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_BLUE,
158                                 ShellyColorUtils.toPercent((int) s.value));
159                         break;
160                     case "white":
161                         col.setWhite((int) s.value);
162                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_WHITE,
163                                 ShellyColorUtils.toPercent((int) s.value));
164                         break;
165                     case "gain":
166                         col.setGain((int) s.value);
167                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_GAIN,
168                                 ShellyColorUtils.toPercent((int) s.value, SHELLY_MIN_GAIN, SHELLY_MAX_GAIN));
169                         break;
170                     case "sensorerror":
171                         String sensorError = s.valueStr != null ? getString(s.valueStr) : "" + s.value;
172                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR, getStringType(sensorError));
173                         break;
174                     default:
175                         // Unknown
176                         return false;
177                 }
178                 break;
179
180             default:
181                 // Unknown type
182                 return false;
183         }
184
185         return true;
186     }
187
188     public static boolean updateChannel(Map<String, State> updates, String group, String channel, State value) {
189         updates.put(mkChannelId(group, channel), value);
190         return true;
191     }
192
193     protected void handleInput(CoIotDescrSen sen, CoIotSensor s, String rGroup, Map<String, State> updates) {
194         int idx = getSensorNumber(sen.desc, sen.id) - 1;
195         String iGroup = profile.getInputGroup(idx);
196         String iChannel = CHANNEL_INPUT + profile.getInputSuffix(idx);
197         updateChannel(updates, iGroup, iChannel, s.value == 0 ? OnOffType.OFF : OnOffType.ON);
198     }
199
200     protected void handleInputEvent(CoIotDescrSen sen, String type, int count, int serial, Map<String, State> updates) {
201         int idx = getSensorNumber(sen.desc, sen.id) - 1;
202         String group = profile.getInputGroup(idx);
203         if (count == -1) {
204             // event type
205             updateChannel(updates, group, CHANNEL_STATUS_EVENTTYPE + profile.getInputSuffix(idx), new StringType(type));
206             inputEvent[idx] = type;
207         } else {
208             // event count
209             updateChannel(updates, group, CHANNEL_STATUS_EVENTCOUNT + profile.getInputSuffix(idx), getDecimal(count));
210             logger.trace(
211                     "{}: Check button[{}] for event trigger (isButtonMode={}, isButton={}, hasBattery={}, serial={}, count={}, lastEventCount[{}]={}",
212                     thingName, idx, profile.inButtonMode(idx), profile.isButton, profile.hasBattery, serial, count, idx,
213                     lastEventCount[idx]);
214             if (profile.inButtonMode(idx) && ((profile.hasBattery && (count == 1))
215                     || ((lastEventCount[idx] != -1) && (count != lastEventCount[idx])))) {
216                 if (!profile.isButton || (profile.isButton && (serial != 0x200))) { // skip duplicate on wake-up
217                     logger.debug("{}: Trigger event {}", thingName, inputEvent[idx]);
218                     thingHandler.triggerButton(group, idx, inputEvent[idx]);
219                 }
220             }
221             lastEventCount[idx] = count;
222         }
223     }
224
225     /**
226      *
227      * Handles the combined updated of the brightness channel:
228      * brightness$Switch is the OnOffType (power state)
229      * brightness&Value is the brightness value
230      *
231      * @param profile Device profile, required to select the channel group and name
232      * @param updates List of updates. updatePower will add brightness$Switch and brightness&Value if changed
233      * @param id Sensor id from the update
234      * @param sen Sensor description from the update
235      * @param s New sensor value
236      * @param allUpdatesList of updates. This is required, because we need to update both values at the same time
237      */
238     protected void updatePower(ShellyDeviceProfile profile, Map<String, State> updates, int id, CoIotDescrSen sen,
239             CoIotSensor s, List<CoIotSensor> allUpdates) {
240         String group = "";
241         String channel = CHANNEL_BRIGHTNESS;
242         String checkL = ""; // RGBW-white uses 4 different Power, Brightness, VSwitch values
243         if (profile.isLight || profile.isDimmer) {
244             if (profile.isBulb || profile.inColor) {
245                 group = CHANNEL_GROUP_LIGHT_CONTROL;
246                 channel = CHANNEL_LIGHT_POWER;
247             } else if (profile.isDuo) {
248                 group = CHANNEL_GROUP_WHITE_CONTROL;
249             } else if (profile.isDimmer) {
250                 group = CHANNEL_GROUP_RELAY_CONTROL;
251             } else if (profile.isRGBW2) {
252                 checkL = String.valueOf(id); // String.valueOf(id - 1); // id is 1-based, L is 0-based
253                 group = CHANNEL_GROUP_LIGHT_CHANNEL + id;
254                 logger.trace("{}: updatePower() for L={}", thingName, checkL);
255             }
256
257             // We need to update brightness and on/off state at the same time to avoid "flipping brightness slider" in
258             // the UI
259             double brightness = -1.0;
260             double power = -1.0;
261             for (CoIotSensor update : allUpdates) {
262                 CoIotDescrSen d = fixDescription(sensorMap.get(update.id), blkMap);
263                 if (!checkL.isEmpty() && !d.links.equals(checkL)) {
264                     // continue until we find the correct one
265                     continue;
266                 }
267                 if (d.desc.equalsIgnoreCase("brightness")) {
268                     brightness = update.value;
269                 } else if (d.desc.equalsIgnoreCase("output") || d.desc.equalsIgnoreCase("state")) {
270                     power = update.value;
271                 }
272             }
273             if (power != -1) {
274                 updateChannel(updates, group, channel + "$Switch", power == 1 ? OnOffType.ON : OnOffType.OFF);
275             }
276             if (brightness != -1) {
277                 updateChannel(updates, group, channel + "$Value",
278                         toQuantityType(power == 1 ? brightness : 0, DIGITS_NONE, Units.PERCENT));
279             }
280         } else if (profile.hasRelays) {
281             group = profile.numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + id;
282             updateChannel(updates, group, CHANNEL_OUTPUT, s.value == 1 ? OnOffType.ON : OnOffType.OFF);
283         } else if (profile.isSensor) {
284             // Sensor state
285             if (profile.isDW) { // Door Window has item type Contact
286                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
287                         s.value != 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
288             } else {
289                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_STATE,
290                         s.value == 1 ? OnOffType.ON : OnOffType.OFF);
291             }
292         }
293     }
294
295     /**
296      * Find index of Input id, which is required to map to channel name
297      *
298      * @parm sensorDesc D field from sensor update
299      * @param sensorId The id from the sensor update
300      * @return Index of found entry (+1 will be the suffix for the channel name) or null if sensorId is not found
301      */
302     protected int getSensorNumber(String sensorDesc, String sensorId) {
303         int idx = 0;
304         for (Map.Entry<String, CoIotDescrSen> se : sensorMap.entrySet()) {
305             CoIotDescrSen sen = se.getValue();
306             if (sen.desc.equalsIgnoreCase(sensorDesc)) {
307                 idx++; // iterate from input1..2..n
308             }
309             if (sen.id.equalsIgnoreCase(sensorId) && blkMap.containsKey(sen.links)) {
310                 int id = getIdFromBlk(sen);
311                 if (id != -1) {
312                     return id;
313                 }
314             }
315             if (sen.id.equalsIgnoreCase(sensorId)) {
316                 return idx;
317             }
318         }
319         logger.debug("{}: sensorId {} not found in sensorMap!", thingName, sensorId);
320         return -1;
321     }
322
323     protected int getIdFromBlk(CoIotDescrSen sen) {
324         int idx = -1;
325         CoIotDescrBlk blk = blkMap.get(sen.links);
326         if (blk != null) {
327             String desc = blk.desc.toLowerCase();
328             if (desc.startsWith(SHELLY_CLASS_RELAY) || desc.startsWith(SHELLY_CLASS_ROLLER)
329                     || desc.startsWith(SHELLY_CLASS_LIGHT) || desc.startsWith(SHELLY_CLASS_EMETER)) {
330                 if (desc.contains("_")) { // CoAP v2
331                     idx = Integer.parseInt(substringAfter(desc, "_"));
332                 } else { // CoAP v1
333                     if (desc.substring(0, 5).equalsIgnoreCase(SHELLY_CLASS_RELAY)) {
334                         idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_RELAY));
335                     }
336                     if (desc.substring(0, 6).equalsIgnoreCase(SHELLY_CLASS_ROLLER)) {
337                         idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_ROLLER));
338                     }
339                     if (desc.substring(0, SHELLY_CLASS_EMETER.length()).equalsIgnoreCase(SHELLY_CLASS_EMETER)) {
340                         idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_EMETER));
341                     }
342                 }
343                 idx = idx + 1; // make it 1-based (sen.L is 0-based)
344             }
345         }
346         return idx;
347     }
348
349     /**
350      *
351      * Get matching sensorId for updates on "External Temperature" - there might be more than 1 sensor.
352      *
353      * @param sensorId sensorId to map into a channel index
354      * @return Index of the corresponding channel (e.g. 0 build temperature1, 1->temperagture2...)
355      */
356     protected int getExtTempId(String sensorId) {
357         int idx = 0;
358         for (Map.Entry<String, CoIotDescrSen> se : sensorMap.entrySet()) {
359             CoIotDescrSen sen = se.getValue();
360             if (sen.desc.equalsIgnoreCase("external_temperature") || sen.desc.equalsIgnoreCase("external temperature c")
361                     || (sen.desc.equalsIgnoreCase("extTemp") && !sen.unit.equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT))) {
362                 idx++; // iterate from temperature1..2..n
363             }
364             if (sen.id.equalsIgnoreCase(sensorId)) {
365                 return idx;
366             }
367         }
368         logger.debug("{}: sensorId {} not found in sensorMap!", thingName, sensorId);
369         return -1;
370     }
371
372     protected ShellyDeviceProfile getProfile() {
373         return profile;
374     }
375
376     public CoIotDescrSen fixDescription(@Nullable CoIotDescrSen sen, Map<String, CoIotDescrBlk> blkMap) {
377         return sen != null ? sen : new CoIotDescrSen();
378     }
379
380     public void completeMissingSensorDefinition(Map<String, CoIotDescrSen> sensorMap) {
381     }
382
383     protected void addSensor(Map<String, CoIotDescrSen> sensorMap, String key, String json) {
384         try {
385             if (!sensorMap.containsKey(key)) {
386                 CoIotDescrSen sen = gson.fromJson(json, CoIotDescrSen.class);
387                 if (sen != null) {
388                     sensorMap.put(key, sen);
389                 }
390             }
391         } catch (JsonSyntaxException e) {
392             // should never happen
393             logger.trace("Unable to parse sensor definition: {}", json, e);
394         }
395     }
396
397     public String getLastWakeup() {
398         return lastWakeup;
399     }
400 }