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