]> git.basschouten.com Git - openhab-addons.git/blob
7c90b1d2d87e146693d933ba086b7c2fecc90d5e
[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.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         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                         if (s.value == 1) {
131                             thingHandler.triggerChannel(CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ALARM_STATE,
132                                     EVENT_TYPE_VIBRATION);
133                         }
134                         break;
135                     case "luminositylevel": // +
136                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ILLUM, getStringType(s.valueStr));
137                         break;
138                     case "charger": // Sense
139                         updateChannel(updates, CHANNEL_GROUP_DEV_STATUS, CHANNEL_DEVST_CHARGER,
140                                 s.value == 1 ? OnOffType.ON : OnOffType.OFF);
141                         break;
142                     // RGBW2/Bulb
143                     case "red":
144                         col.setRed((int) s.value);
145                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_RED,
146                                 ShellyColorUtils.toPercent((int) s.value));
147                         break;
148                     case "green":
149                         col.setGreen((int) s.value);
150                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_GREEN,
151                                 ShellyColorUtils.toPercent((int) s.value));
152                         break;
153                     case "blue":
154                         col.setBlue((int) s.value);
155                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_BLUE,
156                                 ShellyColorUtils.toPercent((int) s.value));
157                         break;
158                     case "white":
159                         col.setWhite((int) s.value);
160                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_WHITE,
161                                 ShellyColorUtils.toPercent((int) s.value));
162                         break;
163                     case "gain":
164                         col.setGain((int) s.value);
165                         updateChannel(updates, CHANNEL_GROUP_COLOR_CONTROL, CHANNEL_COLOR_GAIN,
166                                 ShellyColorUtils.toPercent((int) s.value, SHELLY_MIN_GAIN, SHELLY_MAX_GAIN));
167                         break;
168                     case "sensorerror":
169                         updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_ERROR, getStringType(s.valueStr));
170                         break;
171                     default:
172                         // Unknown
173                         return false;
174                 }
175                 break;
176
177             default:
178                 // Unknown type
179                 return false;
180         }
181
182         return true;
183     }
184
185     public static boolean updateChannel(Map<String, State> updates, String group, String channel, State value) {
186         updates.put(mkChannelId(group, channel), value);
187         return true;
188     }
189
190     protected void handleInput(CoIotDescrSen sen, CoIotSensor s, String rGroup, Map<String, State> updates) {
191         int idx = getSensorNumber(sen.desc, sen.id) - 1;
192         String iGroup = profile.getInputGroup(idx);
193         String iChannel = CHANNEL_INPUT + profile.getInputSuffix(idx);
194         updateChannel(updates, iGroup, iChannel, s.value == 0 ? OnOffType.OFF : OnOffType.ON);
195     }
196
197     protected void handleInputEvent(CoIotDescrSen sen, String type, int count, int serial, Map<String, State> updates) {
198         int idx = getSensorNumber(sen.desc, sen.id) - 1;
199         String group = profile.getInputGroup(idx);
200         if (count == -1) {
201             // event type
202             updateChannel(updates, group, CHANNEL_STATUS_EVENTTYPE + profile.getInputSuffix(idx), new StringType(type));
203             inputEvent[idx] = type;
204         } else {
205             // event count
206             updateChannel(updates, group, CHANNEL_STATUS_EVENTCOUNT + profile.getInputSuffix(idx), getDecimal(count));
207             logger.trace(
208                     "{}: Check button[{}] for event trigger (isButtonMode={}, isButton={}, hasBattery={}, serial={}, count={}, lastEventCount[{}]={}",
209                     thingName, idx, profile.inButtonMode(idx), profile.isButton, profile.hasBattery, serial, count, idx,
210                     lastEventCount[idx]);
211             if (profile.inButtonMode(idx) && ((profile.hasBattery && (count == 1))
212                     || ((lastEventCount[idx] != -1) && (count != lastEventCount[idx])))) {
213                 if (!profile.isButton || (profile.isButton && (serial != 0x200))) { // skip duplicate on wake-up
214                     logger.debug("{}: Trigger event {}", thingName, inputEvent[idx]);
215                     thingHandler.triggerButton(group, idx, inputEvent[idx]);
216                 }
217             }
218             lastEventCount[idx] = count;
219         }
220     }
221
222     /**
223      *
224      * Handles the combined updated of the brightness channel:
225      * brightness$Switch is the OnOffType (power state)
226      * brightness&Value is the brightness value
227      *
228      * @param profile Device profile, required to select the channel group and name
229      * @param updates List of updates. updatePower will add brightness$Switch and brightness&Value if changed
230      * @param id Sensor id from the update
231      * @param sen Sensor description from the update
232      * @param s New sensor value
233      * @param allUpdatesList of updates. This is required, because we need to update both values at the same time
234      */
235     protected void updatePower(ShellyDeviceProfile profile, Map<String, State> updates, int id, CoIotDescrSen sen,
236             CoIotSensor s, List<CoIotSensor> allUpdates) {
237         String group = "";
238         String channel = CHANNEL_BRIGHTNESS;
239         String checkL = ""; // RGBW-white uses 4 different Power, Brightness, VSwitch values
240         if (profile.isLight || profile.isDimmer) {
241             if (profile.isBulb || profile.inColor) {
242                 group = CHANNEL_GROUP_LIGHT_CONTROL;
243                 channel = CHANNEL_LIGHT_POWER;
244             } else if (profile.isDuo) {
245                 group = CHANNEL_GROUP_WHITE_CONTROL;
246             } else if (profile.isDimmer) {
247                 group = CHANNEL_GROUP_RELAY_CONTROL;
248             } else if (profile.isRGBW2) {
249                 checkL = String.valueOf(id); // String.valueOf(id - 1); // id is 1-based, L is 0-based
250                 group = CHANNEL_GROUP_LIGHT_CHANNEL + id;
251                 logger.trace("{}: updatePower() for L={}", thingName, checkL);
252             }
253
254             // We need to update brightness and on/off state at the same time to avoid "flipping brightness slider" in
255             // the UI
256             double brightness = -1.0;
257             double power = -1.0;
258             for (CoIotSensor update : allUpdates) {
259                 CoIotDescrSen d = fixDescription(sensorMap.get(update.id), blkMap);
260                 if (!checkL.isEmpty() && !d.links.equals(checkL)) {
261                     // continue until we find the correct one
262                     continue;
263                 }
264                 if (d.desc.equalsIgnoreCase("brightness")) {
265                     brightness = update.value;
266                 } else if (d.desc.equalsIgnoreCase("output") || d.desc.equalsIgnoreCase("state")) {
267                     power = update.value;
268                 }
269             }
270             if (power != -1) {
271                 updateChannel(updates, group, channel + "$Switch", power == 1 ? OnOffType.ON : OnOffType.OFF);
272             }
273             if (brightness != -1) {
274                 updateChannel(updates, group, channel + "$Value",
275                         toQuantityType(power == 1 ? brightness : 0, DIGITS_NONE, Units.PERCENT));
276             }
277         } else if (profile.hasRelays) {
278             group = profile.numRelays <= 1 ? CHANNEL_GROUP_RELAY_CONTROL : CHANNEL_GROUP_RELAY_CONTROL + id;
279             updateChannel(updates, group, CHANNEL_OUTPUT, s.value == 1 ? OnOffType.ON : OnOffType.OFF);
280         } else if (profile.isSensor) {
281             // Sensor state
282             if (profile.isDW) { // Door Window has item type Contact
283                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_CONTACT,
284                         s.value != 0 ? OpenClosedType.OPEN : OpenClosedType.CLOSED);
285             } else {
286                 updateChannel(updates, CHANNEL_GROUP_SENSOR, CHANNEL_SENSOR_CONTACT,
287                         s.value == 1 ? OnOffType.ON : OnOffType.OFF);
288             }
289         }
290     }
291
292     /**
293      * Find index of Input id, which is required to map to channel name
294      *
295      * @parm sensorDesc D field from sensor update
296      * @param sensorId The id from the sensor update
297      * @return Index of found entry (+1 will be the suffix for the channel name) or null if sensorId is not found
298      */
299     protected int getSensorNumber(String sensorDesc, String sensorId) {
300         int idx = 0;
301         for (Map.Entry<String, CoIotDescrSen> se : sensorMap.entrySet()) {
302             CoIotDescrSen sen = se.getValue();
303             if (sen.desc.equalsIgnoreCase(sensorDesc)) {
304                 idx++; // iterate from input1..2..n
305             }
306             if (sen.id.equalsIgnoreCase(sensorId) && blkMap.containsKey(sen.links)) {
307                 int id = getIdFromBlk(sen);
308                 if (id != -1) {
309                     return id;
310                 }
311             }
312             if (sen.id.equalsIgnoreCase(sensorId)) {
313                 return idx;
314             }
315         }
316         logger.debug("{}: sensorId {} not found in sensorMap!", thingName, sensorId);
317         return -1;
318     }
319
320     protected int getIdFromBlk(CoIotDescrSen sen) {
321         int idx = -1;
322         CoIotDescrBlk blk = blkMap.get(sen.links);
323         if (blk != null) {
324             String desc = blk.desc.toLowerCase();
325             if (desc.startsWith(SHELLY_CLASS_RELAY) || desc.startsWith(SHELLY_CLASS_ROLLER)
326                     || desc.startsWith(SHELLY_CLASS_LIGHT) || desc.startsWith(SHELLY_CLASS_EMETER)) {
327                 if (desc.contains("_")) { // CoAP v2
328                     idx = Integer.parseInt(substringAfter(desc, "_"));
329                 } else { // CoAP v1
330                     if (desc.substring(0, 5).equalsIgnoreCase(SHELLY_CLASS_RELAY)) {
331                         idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_RELAY));
332                     }
333                     if (desc.substring(0, 6).equalsIgnoreCase(SHELLY_CLASS_ROLLER)) {
334                         idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_ROLLER));
335                     }
336                     if (desc.substring(0, SHELLY_CLASS_EMETER.length()).equalsIgnoreCase(SHELLY_CLASS_EMETER)) {
337                         idx = Integer.parseInt(substringAfter(desc, SHELLY_CLASS_EMETER));
338                     }
339                 }
340                 idx = idx + 1; // make it 1-based (sen.L is 0-based)
341             }
342         }
343         return idx;
344     }
345
346     /**
347      *
348      * Get matching sensorId for updates on "External Temperature" - there might be more than 1 sensor.
349      *
350      * @param sensorId sensorId to map into a channel index
351      * @return Index of the corresponding channel (e.g. 0 build temperature1, 1->temperagture2...)
352      */
353     protected int getExtTempId(String sensorId) {
354         int idx = 0;
355         for (Map.Entry<String, CoIotDescrSen> se : sensorMap.entrySet()) {
356             CoIotDescrSen sen = se.getValue();
357             if (sen.desc.equalsIgnoreCase("external_temperature") || sen.desc.equalsIgnoreCase("external temperature c")
358                     || (sen.desc.equalsIgnoreCase("extTemp") && !sen.unit.equalsIgnoreCase(SHELLY_TEMP_FAHRENHEIT))) {
359                 idx++; // iterate from temperature1..2..n
360             }
361             if (sen.id.equalsIgnoreCase(sensorId)) {
362                 return idx;
363             }
364         }
365         logger.debug("{}: sensorId {} not found in sensorMap!", thingName, sensorId);
366         return -1;
367     }
368
369     protected ShellyDeviceProfile getProfile() {
370         return profile;
371     }
372
373     public CoIotDescrSen fixDescription(@Nullable CoIotDescrSen sen, Map<String, CoIotDescrBlk> blkMap) {
374         return sen != null ? sen : new CoIotDescrSen();
375     }
376
377     public void completeMissingSensorDefinition(Map<String, CoIotDescrSen> sensorMap) {
378     }
379
380     protected void addSensor(Map<String, CoIotDescrSen> sensorMap, String key, String json) {
381         try {
382             if (!sensorMap.containsKey(key)) {
383                 CoIotDescrSen sen = gson.fromJson(json, CoIotDescrSen.class);
384                 if (sen != null) {
385                     sensorMap.put(key, sen);
386                 }
387             }
388         } catch (JsonSyntaxException e) {
389             // should never happen
390             logger.trace("Unable to parse sensor definition: {}", json, e);
391         }
392     }
393
394     public String getLastWakeup() {
395         return lastWakeup;
396     }
397 }